code stringlengths 1 2.08M | language stringclasses 1 value |
|---|---|
/**
* editor_plugin_src.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
(function() {
tinymce.create('tinymce.plugins.Print', {
init : function(ed, url) {
ed.addCommand('mcePrint', function() {
ed.getWin().print();
});
ed.addButton('print', {title : 'print.print_desc', cmd : 'mcePrint'});
},
getInfo : function() {
return {
longname : 'Print',
author : 'Moxiecode Systems AB',
authorurl : 'http://tinymce.moxiecode.com',
infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/print',
version : tinymce.majorVersion + "." + tinymce.minorVersion
};
}
});
// Register plugin
tinymce.PluginManager.add('print', tinymce.plugins.Print);
})();
| JavaScript |
/**
* editor_plugin_src.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
(function() {
var Event = tinymce.dom.Event;
tinymce.create('tinymce.plugins.NonEditablePlugin', {
init : function(ed, url) {
var t = this, editClass, nonEditClass;
t.editor = ed;
editClass = ed.getParam("noneditable_editable_class", "mceEditable");
nonEditClass = ed.getParam("noneditable_noneditable_class", "mceNonEditable");
ed.onNodeChange.addToTop(function(ed, cm, n) {
var sc, ec;
// Block if start or end is inside a non editable element
sc = ed.dom.getParent(ed.selection.getStart(), function(n) {
return ed.dom.hasClass(n, nonEditClass);
});
ec = ed.dom.getParent(ed.selection.getEnd(), function(n) {
return ed.dom.hasClass(n, nonEditClass);
});
// Block or unblock
if (sc || ec) {
t._setDisabled(1);
return false;
} else
t._setDisabled(0);
});
},
getInfo : function() {
return {
longname : 'Non editable elements',
author : 'Moxiecode Systems AB',
authorurl : 'http://tinymce.moxiecode.com',
infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/noneditable',
version : tinymce.majorVersion + "." + tinymce.minorVersion
};
},
_block : function(ed, e) {
var k = e.keyCode;
// Don't block arrow keys, pg up/down, and F1-F12
if ((k > 32 && k < 41) || (k > 111 && k < 124))
return;
return Event.cancel(e);
},
_setDisabled : function(s) {
var t = this, ed = t.editor;
tinymce.each(ed.controlManager.controls, function(c) {
c.setDisabled(s);
});
if (s !== t.disabled) {
if (s) {
ed.onKeyDown.addToTop(t._block);
ed.onKeyPress.addToTop(t._block);
ed.onKeyUp.addToTop(t._block);
ed.onPaste.addToTop(t._block);
} else {
ed.onKeyDown.remove(t._block);
ed.onKeyPress.remove(t._block);
ed.onKeyUp.remove(t._block);
ed.onPaste.remove(t._block);
}
t.disabled = s;
}
}
});
// Register plugin
tinymce.PluginManager.add('noneditable', tinymce.plugins.NonEditablePlugin);
})(); | JavaScript |
/**
* editor_plugin_src.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
(function() {
tinymce.create('tinymce.plugins.Preview', {
init : function(ed, url) {
var t = this, css = tinymce.explode(ed.settings.content_css);
t.editor = ed;
// Force absolute CSS urls
tinymce.each(css, function(u, k) {
css[k] = ed.documentBaseURI.toAbsolute(u);
});
ed.addCommand('mcePreview', function() {
ed.windowManager.open({
file : ed.getParam("plugin_preview_pageurl", url + "/preview.html"),
width : parseInt(ed.getParam("plugin_preview_width", "550")),
height : parseInt(ed.getParam("plugin_preview_height", "600")),
resizable : "yes",
scrollbars : "yes",
popup_css : css ? css.join(',') : ed.baseURI.toAbsolute("themes/" + ed.settings.theme + "/skins/" + ed.settings.skin + "/content.css"),
inline : ed.getParam("plugin_preview_inline", 1)
}, {
base : ed.documentBaseURI.getURI()
});
});
ed.addButton('preview', {title : 'preview.preview_desc', cmd : 'mcePreview'});
},
getInfo : function() {
return {
longname : 'Preview',
author : 'Moxiecode Systems AB',
authorurl : 'http://tinymce.moxiecode.com',
infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/preview',
version : tinymce.majorVersion + "." + tinymce.minorVersion
};
}
});
// Register plugin
tinymce.PluginManager.add('preview', tinymce.plugins.Preview);
})(); | JavaScript |
/**
* This script contains embed functions for common plugins. This scripts are complety free to use for any purpose.
*/
function writeFlash(p) {
writeEmbed(
'D27CDB6E-AE6D-11cf-96B8-444553540000',
'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0',
'application/x-shockwave-flash',
p
);
}
function writeShockWave(p) {
writeEmbed(
'166B1BCA-3F9C-11CF-8075-444553540000',
'http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=8,5,1,0',
'application/x-director',
p
);
}
function writeQuickTime(p) {
writeEmbed(
'02BF25D5-8C17-4B23-BC80-D3488ABDDC6B',
'http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0',
'video/quicktime',
p
);
}
function writeRealMedia(p) {
writeEmbed(
'CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA',
'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0',
'audio/x-pn-realaudio-plugin',
p
);
}
function writeWindowsMedia(p) {
p.url = p.src;
writeEmbed(
'6BF52A52-394A-11D3-B153-00C04F79FAA6',
'http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701',
'application/x-mplayer2',
p
);
}
function writeEmbed(cls, cb, mt, p) {
var h = '', n;
h += '<object classid="clsid:' + cls + '" codebase="' + cb + '"';
h += typeof(p.id) != "undefined" ? 'id="' + p.id + '"' : '';
h += typeof(p.name) != "undefined" ? 'name="' + p.name + '"' : '';
h += typeof(p.width) != "undefined" ? 'width="' + p.width + '"' : '';
h += typeof(p.height) != "undefined" ? 'height="' + p.height + '"' : '';
h += typeof(p.align) != "undefined" ? 'align="' + p.align + '"' : '';
h += '>';
for (n in p)
h += '<param name="' + n + '" value="' + p[n] + '">';
h += '<embed type="' + mt + '"';
for (n in p)
h += n + '="' + p[n] + '" ';
h += '></embed></object>';
document.write(h);
}
| JavaScript |
tinyMCEPopup.requireLangPack();
var TemplateDialog = {
preInit : function() {
var url = tinyMCEPopup.getParam("template_external_list_url");
if (url != null)
document.write('<sc'+'ript language="javascript" type="text/javascript" src="' + tinyMCEPopup.editor.documentBaseURI.toAbsolute(url) + '"></sc'+'ript>');
},
init : function() {
var ed = tinyMCEPopup.editor, tsrc, sel, x, u;
tsrc = ed.getParam("template_templates", false);
sel = document.getElementById('tpath');
// Setup external template list
if (!tsrc && typeof(tinyMCETemplateList) != 'undefined') {
for (x=0, tsrc = []; x<tinyMCETemplateList.length; x++)
tsrc.push({title : tinyMCETemplateList[x][0], src : tinyMCETemplateList[x][1], description : tinyMCETemplateList[x][2]});
}
for (x=0; x<tsrc.length; x++)
sel.options[sel.options.length] = new Option(tsrc[x].title, tinyMCEPopup.editor.documentBaseURI.toAbsolute(tsrc[x].src));
this.resize();
this.tsrc = tsrc;
},
resize : function() {
var w, h, e;
if (!self.innerWidth) {
w = document.body.clientWidth - 50;
h = document.body.clientHeight - 160;
} else {
w = self.innerWidth - 50;
h = self.innerHeight - 170;
}
e = document.getElementById('templatesrc');
if (e) {
e.style.height = Math.abs(h) + 'px';
e.style.width = Math.abs(w - 5) + 'px';
}
},
loadCSSFiles : function(d) {
var ed = tinyMCEPopup.editor;
tinymce.each(ed.getParam("content_css", '').split(','), function(u) {
d.write('<link href="' + ed.documentBaseURI.toAbsolute(u) + '" rel="stylesheet" type="text/css" />');
});
},
selectTemplate : function(u, ti) {
var d = window.frames['templatesrc'].document, x, tsrc = this.tsrc;
if (!u)
return;
d.body.innerHTML = this.templateHTML = this.getFileContents(u);
for (x=0; x<tsrc.length; x++) {
if (tsrc[x].title == ti)
document.getElementById('tmpldesc').innerHTML = tsrc[x].description || '';
}
},
insert : function() {
tinyMCEPopup.execCommand('mceInsertTemplate', false, {
content : this.templateHTML,
selection : tinyMCEPopup.editor.selection.getContent()
});
tinyMCEPopup.close();
},
getFileContents : function(u) {
var x, d, t = 'text/plain';
function g(s) {
x = 0;
try {
x = new ActiveXObject(s);
} catch (s) {
}
return x;
};
x = window.ActiveXObject ? g('Msxml2.XMLHTTP') || g('Microsoft.XMLHTTP') : new XMLHttpRequest();
// Synchronous AJAX load file
x.overrideMimeType && x.overrideMimeType(t);
x.open("GET", u, false);
x.send(null);
return x.responseText;
}
};
TemplateDialog.preInit();
tinyMCEPopup.onInit.add(TemplateDialog.init, TemplateDialog);
| JavaScript |
/**
* editor_plugin_src.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
(function() {
var each = tinymce.each;
tinymce.create('tinymce.plugins.TemplatePlugin', {
init : function(ed, url) {
var t = this;
t.editor = ed;
// Register commands
ed.addCommand('mceTemplate', function(ui) {
ed.windowManager.open({
file : url + '/template.htm',
width : ed.getParam('template_popup_width', 750),
height : ed.getParam('template_popup_height', 600),
inline : 1
}, {
plugin_url : url
});
});
ed.addCommand('mceInsertTemplate', t._insertTemplate, t);
// Register buttons
ed.addButton('template', {title : 'template.desc', cmd : 'mceTemplate'});
ed.onPreProcess.add(function(ed, o) {
var dom = ed.dom;
each(dom.select('div', o.node), function(e) {
if (dom.hasClass(e, 'mceTmpl')) {
each(dom.select('*', e), function(e) {
if (dom.hasClass(e, ed.getParam('template_mdate_classes', 'mdate').replace(/\s+/g, '|')))
e.innerHTML = t._getDateTime(new Date(), ed.getParam("template_mdate_format", ed.getLang("template.mdate_format")));
});
t._replaceVals(e);
}
});
});
},
getInfo : function() {
return {
longname : 'Template plugin',
author : 'Moxiecode Systems AB',
authorurl : 'http://www.moxiecode.com',
infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/template',
version : tinymce.majorVersion + "." + tinymce.minorVersion
};
},
_insertTemplate : function(ui, v) {
var t = this, ed = t.editor, h, el, dom = ed.dom, sel = ed.selection.getContent();
h = v.content;
each(t.editor.getParam('template_replace_values'), function(v, k) {
if (typeof(v) != 'function')
h = h.replace(new RegExp('\\{\\$' + k + '\\}', 'g'), v);
});
el = dom.create('div', null, h);
// Find template element within div
n = dom.select('.mceTmpl', el);
if (n && n.length > 0) {
el = dom.create('div', null);
el.appendChild(n[0].cloneNode(true));
}
function hasClass(n, c) {
return new RegExp('\\b' + c + '\\b', 'g').test(n.className);
};
each(dom.select('*', el), function(n) {
// Replace cdate
if (hasClass(n, ed.getParam('template_cdate_classes', 'cdate').replace(/\s+/g, '|')))
n.innerHTML = t._getDateTime(new Date(), ed.getParam("template_cdate_format", ed.getLang("template.cdate_format")));
// Replace mdate
if (hasClass(n, ed.getParam('template_mdate_classes', 'mdate').replace(/\s+/g, '|')))
n.innerHTML = t._getDateTime(new Date(), ed.getParam("template_mdate_format", ed.getLang("template.mdate_format")));
// Replace selection
if (hasClass(n, ed.getParam('template_selected_content_classes', 'selcontent').replace(/\s+/g, '|')))
n.innerHTML = sel;
});
t._replaceVals(el);
ed.execCommand('mceInsertContent', false, el.innerHTML);
ed.addVisual();
},
_replaceVals : function(e) {
var dom = this.editor.dom, vl = this.editor.getParam('template_replace_values');
each(dom.select('*', e), function(e) {
each(vl, function(v, k) {
if (dom.hasClass(e, k)) {
if (typeof(vl[k]) == 'function')
vl[k](e);
}
});
});
},
_getDateTime : function(d, fmt) {
if (!fmt)
return "";
function addZeros(value, len) {
var i;
value = "" + value;
if (value.length < len) {
for (i=0; i<(len-value.length); i++)
value = "0" + value;
}
return value;
}
fmt = fmt.replace("%D", "%m/%d/%y");
fmt = fmt.replace("%r", "%I:%M:%S %p");
fmt = fmt.replace("%Y", "" + d.getFullYear());
fmt = fmt.replace("%y", "" + d.getYear());
fmt = fmt.replace("%m", addZeros(d.getMonth()+1, 2));
fmt = fmt.replace("%d", addZeros(d.getDate(), 2));
fmt = fmt.replace("%H", "" + addZeros(d.getHours(), 2));
fmt = fmt.replace("%M", "" + addZeros(d.getMinutes(), 2));
fmt = fmt.replace("%S", "" + addZeros(d.getSeconds(), 2));
fmt = fmt.replace("%I", "" + ((d.getHours() + 11) % 12 + 1));
fmt = fmt.replace("%p", "" + (d.getHours() < 12 ? "AM" : "PM"));
fmt = fmt.replace("%B", "" + this.editor.getLang("template_months_long").split(',')[d.getMonth()]);
fmt = fmt.replace("%b", "" + this.editor.getLang("template_months_short").split(',')[d.getMonth()]);
fmt = fmt.replace("%A", "" + this.editor.getLang("template_day_long").split(',')[d.getDay()]);
fmt = fmt.replace("%a", "" + this.editor.getLang("template_day_short").split(',')[d.getDay()]);
fmt = fmt.replace("%%", "%");
return fmt;
}
});
// Register plugin
tinymce.PluginManager.add('template', tinymce.plugins.TemplatePlugin);
})(); | JavaScript |
tinyMCE.addI18n('en.template_dlg',{
title:"Templates",
label:"Template",
desc_label:"Description",
desc:"Insert predefined template content",
select:"Select a template",
preview:"Preview",
warning:"Warning: Updating a template with a different one may cause data loss.",
mdate_format:"%Y-%m-%d %H:%M:%S",
cdate_format:"%Y-%m-%d %H:%M:%S",
months_long:"January,February,March,April,May,June,July,August,September,October,November,December",
months_short:"Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec",
day_long:"Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday",
day_short:"Sun,Mon,Tue,Wed,Thu,Fri,Sat,Sun"
}); | JavaScript |
/**
* editor_plugin_src.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
(function() {
/**
* Auto Resize
*
* This plugin automatically resizes the content area to fit its content height.
* It will retain a minimum height, which is the height of the content area when
* it's initialized.
*/
tinymce.create('tinymce.plugins.AutoResizePlugin', {
/**
* Initializes the plugin, this will be executed after the plugin has been created.
* This call is done before the editor instance has finished it's initialization so use the onInit event
* of the editor instance to intercept that event.
*
* @param {tinymce.Editor} ed Editor instance that the plugin is initialized in.
* @param {string} url Absolute URL to where the plugin is located.
*/
init : function(ed, url) {
var t = this;
if (ed.getParam('fullscreen_is_enabled'))
return;
/**
* This method gets executed each time the editor needs to resize.
*/
function resize() {
var d = ed.getDoc(), b = d.body, de = d.documentElement, DOM = tinymce.DOM, resizeHeight = t.autoresize_min_height, myHeight;
// Get height differently depending on the browser used
myHeight = tinymce.isIE ? b.scrollHeight : de.offsetHeight;
// Don't make it smaller than the minimum height
if (myHeight > t.autoresize_min_height)
resizeHeight = myHeight;
// Resize content element
DOM.setStyle(DOM.get(ed.id + '_ifr'), 'height', resizeHeight + 'px');
// if we're throbbing, we'll re-throb to match the new size
if (t.throbbing) {
ed.setProgressState(false);
ed.setProgressState(true);
}
};
t.editor = ed;
// Define minimum height
t.autoresize_min_height = ed.getElement().offsetHeight;
// Add appropriate listeners for resizing content area
ed.onChange.add(resize);
ed.onSetContent.add(resize);
ed.onPaste.add(resize);
ed.onKeyUp.add(resize);
ed.onPostRender.add(resize);
if (ed.getParam('autoresize_on_init', true)) {
// Things to do when the editor is ready
ed.onInit.add(function(ed, l) {
// Show throbber until content area is resized properly
ed.setProgressState(true);
t.throbbing = true;
// Hide scrollbars
ed.getBody().style.overflowY = "hidden";
});
ed.onLoadContent.add(function(ed, l) {
resize();
// Because the content area resizes when its content CSS loads,
// and we can't easily add a listener to its onload event,
// we'll just trigger a resize after a short loading period
setTimeout(function() {
resize();
// Disable throbber
ed.setProgressState(false);
t.throbbing = false;
}, 1250);
});
}
// Register the command so that it can be invoked by using tinyMCE.activeEditor.execCommand('mceExample');
ed.addCommand('mceAutoResize', resize);
},
/**
* Returns information about the plugin as a name/value array.
* The current keys are longname, author, authorurl, infourl and version.
*
* @return {Object} Name/value array containing information about the plugin.
*/
getInfo : function() {
return {
longname : 'Auto Resize',
author : 'Moxiecode Systems AB',
authorurl : 'http://tinymce.moxiecode.com',
infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/autoresize',
version : tinymce.majorVersion + "." + tinymce.minorVersion
};
}
});
// Register plugin
tinymce.PluginManager.add('autoresize', tinymce.plugins.AutoResizePlugin);
})(); | JavaScript |
/**
* element_common.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
tinyMCEPopup.requireLangPack();
function initCommonAttributes(elm) {
var formObj = document.forms[0], dom = tinyMCEPopup.editor.dom;
// Setup form data for common element attributes
setFormValue('title', dom.getAttrib(elm, 'title'));
setFormValue('id', dom.getAttrib(elm, 'id'));
selectByValue(formObj, 'class', dom.getAttrib(elm, 'class'), true);
setFormValue('style', dom.getAttrib(elm, 'style'));
selectByValue(formObj, 'dir', dom.getAttrib(elm, 'dir'));
setFormValue('lang', dom.getAttrib(elm, 'lang'));
setFormValue('onfocus', dom.getAttrib(elm, 'onfocus'));
setFormValue('onblur', dom.getAttrib(elm, 'onblur'));
setFormValue('onclick', dom.getAttrib(elm, 'onclick'));
setFormValue('ondblclick', dom.getAttrib(elm, 'ondblclick'));
setFormValue('onmousedown', dom.getAttrib(elm, 'onmousedown'));
setFormValue('onmouseup', dom.getAttrib(elm, 'onmouseup'));
setFormValue('onmouseover', dom.getAttrib(elm, 'onmouseover'));
setFormValue('onmousemove', dom.getAttrib(elm, 'onmousemove'));
setFormValue('onmouseout', dom.getAttrib(elm, 'onmouseout'));
setFormValue('onkeypress', dom.getAttrib(elm, 'onkeypress'));
setFormValue('onkeydown', dom.getAttrib(elm, 'onkeydown'));
setFormValue('onkeyup', dom.getAttrib(elm, 'onkeyup'));
}
function setFormValue(name, value) {
if(document.forms[0].elements[name]) document.forms[0].elements[name].value = value;
}
function insertDateTime(id) {
document.getElementById(id).value = getDateTime(new Date(), "%Y-%m-%dT%H:%M:%S");
}
function getDateTime(d, fmt) {
fmt = fmt.replace("%D", "%m/%d/%y");
fmt = fmt.replace("%r", "%I:%M:%S %p");
fmt = fmt.replace("%Y", "" + d.getFullYear());
fmt = fmt.replace("%y", "" + d.getYear());
fmt = fmt.replace("%m", addZeros(d.getMonth()+1, 2));
fmt = fmt.replace("%d", addZeros(d.getDate(), 2));
fmt = fmt.replace("%H", "" + addZeros(d.getHours(), 2));
fmt = fmt.replace("%M", "" + addZeros(d.getMinutes(), 2));
fmt = fmt.replace("%S", "" + addZeros(d.getSeconds(), 2));
fmt = fmt.replace("%I", "" + ((d.getHours() + 11) % 12 + 1));
fmt = fmt.replace("%p", "" + (d.getHours() < 12 ? "AM" : "PM"));
fmt = fmt.replace("%%", "%");
return fmt;
}
function addZeros(value, len) {
var i;
value = "" + value;
if (value.length < len) {
for (i=0; i<(len-value.length); i++)
value = "0" + value;
}
return value;
}
function selectByValue(form_obj, field_name, value, add_custom, ignore_case) {
if (!form_obj || !form_obj.elements[field_name])
return;
var sel = form_obj.elements[field_name];
var found = false;
for (var i=0; i<sel.options.length; i++) {
var option = sel.options[i];
if (option.value == value || (ignore_case && option.value.toLowerCase() == value.toLowerCase())) {
option.selected = true;
found = true;
} else
option.selected = false;
}
if (!found && add_custom && value != '') {
var option = new Option('Value: ' + value, value);
option.selected = true;
sel.options[sel.options.length] = option;
}
return found;
}
function setAttrib(elm, attrib, value) {
var formObj = document.forms[0];
var valueElm = formObj.elements[attrib.toLowerCase()];
tinyMCEPopup.editor.dom.setAttrib(elm, attrib, value || valueElm.value);
}
function setAllCommonAttribs(elm) {
setAttrib(elm, 'title');
setAttrib(elm, 'id');
setAttrib(elm, 'class');
setAttrib(elm, 'style');
setAttrib(elm, 'dir');
setAttrib(elm, 'lang');
/*setAttrib(elm, 'onfocus');
setAttrib(elm, 'onblur');
setAttrib(elm, 'onclick');
setAttrib(elm, 'ondblclick');
setAttrib(elm, 'onmousedown');
setAttrib(elm, 'onmouseup');
setAttrib(elm, 'onmouseover');
setAttrib(elm, 'onmousemove');
setAttrib(elm, 'onmouseout');
setAttrib(elm, 'onkeypress');
setAttrib(elm, 'onkeydown');
setAttrib(elm, 'onkeyup');*/
}
SXE = {
currentAction : "insert",
inst : tinyMCEPopup.editor,
updateElement : null
}
SXE.focusElement = SXE.inst.selection.getNode();
SXE.initElementDialog = function(element_name) {
addClassesToList('class', 'xhtmlxtras_styles');
TinyMCE_EditableSelects.init();
element_name = element_name.toLowerCase();
var elm = SXE.inst.dom.getParent(SXE.focusElement, element_name.toUpperCase());
if (elm != null && elm.nodeName.toUpperCase() == element_name.toUpperCase()) {
SXE.currentAction = "update";
}
if (SXE.currentAction == "update") {
initCommonAttributes(elm);
SXE.updateElement = elm;
}
document.forms[0].insert.value = tinyMCEPopup.getLang(SXE.currentAction, 'Insert', true);
}
SXE.insertElement = function(element_name) {
var elm = SXE.inst.dom.getParent(SXE.focusElement, element_name.toUpperCase()), h, tagName;
tinyMCEPopup.execCommand('mceBeginUndoLevel');
if (elm == null) {
var s = SXE.inst.selection.getContent();
if(s.length > 0) {
tagName = element_name;
insertInlineElement(element_name);
var elementArray = tinymce.grep(SXE.inst.dom.select(element_name));
for (var i=0; i<elementArray.length; i++) {
var elm = elementArray[i];
if (SXE.inst.dom.getAttrib(elm, '_mce_new')) {
elm.id = '';
elm.setAttribute('id', '');
elm.removeAttribute('id');
elm.removeAttribute('_mce_new');
setAllCommonAttribs(elm);
}
}
}
} else {
setAllCommonAttribs(elm);
}
SXE.inst.nodeChanged();
tinyMCEPopup.execCommand('mceEndUndoLevel');
}
SXE.removeElement = function(element_name){
element_name = element_name.toLowerCase();
elm = SXE.inst.dom.getParent(SXE.focusElement, element_name.toUpperCase());
if(elm && elm.nodeName.toUpperCase() == element_name.toUpperCase()){
tinyMCEPopup.execCommand('mceBeginUndoLevel');
tinyMCE.execCommand('mceRemoveNode', false, elm);
SXE.inst.nodeChanged();
tinyMCEPopup.execCommand('mceEndUndoLevel');
}
}
SXE.showRemoveButton = function() {
document.getElementById("remove").style.display = '';
}
SXE.containsClass = function(elm,cl) {
return (elm.className.indexOf(cl) > -1) ? true : false;
}
SXE.removeClass = function(elm,cl) {
if(elm.className == null || elm.className == "" || !SXE.containsClass(elm,cl)) {
return true;
}
var classNames = elm.className.split(" ");
var newClassNames = "";
for (var x = 0, cnl = classNames.length; x < cnl; x++) {
if (classNames[x] != cl) {
newClassNames += (classNames[x] + " ");
}
}
elm.className = newClassNames.substring(0,newClassNames.length-1); //removes extra space at the end
}
SXE.addClass = function(elm,cl) {
if(!SXE.containsClass(elm,cl)) elm.className ? elm.className += " " + cl : elm.className = cl;
return true;
}
function insertInlineElement(en) {
var ed = tinyMCEPopup.editor, dom = ed.dom;
ed.getDoc().execCommand('FontName', false, 'mceinline');
tinymce.each(dom.select('span,font'), function(n) {
if (n.style.fontFamily == 'mceinline' || n.face == 'mceinline')
dom.replace(dom.create(en, {_mce_new : 1}), n, 1);
});
}
| JavaScript |
/**
* abbr.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
function init() {
SXE.initElementDialog('abbr');
if (SXE.currentAction == "update") {
SXE.showRemoveButton();
}
}
function insertAbbr() {
SXE.insertElement('abbr');
tinyMCEPopup.close();
}
function removeAbbr() {
SXE.removeElement('abbr');
tinyMCEPopup.close();
}
tinyMCEPopup.onInit.add(init);
| JavaScript |
/**
* cite.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
function init() {
SXE.initElementDialog('cite');
if (SXE.currentAction == "update") {
SXE.showRemoveButton();
}
}
function insertCite() {
SXE.insertElement('cite');
tinyMCEPopup.close();
}
function removeCite() {
SXE.removeElement('cite');
tinyMCEPopup.close();
}
tinyMCEPopup.onInit.add(init);
| JavaScript |
/**
* del.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
function init() {
SXE.initElementDialog('del');
if (SXE.currentAction == "update") {
setFormValue('datetime', tinyMCEPopup.editor.dom.getAttrib(SXE.updateElement, 'datetime'));
setFormValue('cite', tinyMCEPopup.editor.dom.getAttrib(SXE.updateElement, 'cite'));
SXE.showRemoveButton();
}
}
function setElementAttribs(elm) {
setAllCommonAttribs(elm);
setAttrib(elm, 'datetime');
setAttrib(elm, 'cite');
}
function insertDel() {
var elm = tinyMCEPopup.editor.dom.getParent(SXE.focusElement, 'DEL');
tinyMCEPopup.execCommand('mceBeginUndoLevel');
if (elm == null) {
var s = SXE.inst.selection.getContent();
if(s.length > 0) {
insertInlineElement('del');
var elementArray = tinymce.grep(SXE.inst.dom.select('del'), function(n) {return n.id == '#sxe_temp_del#';});
for (var i=0; i<elementArray.length; i++) {
var elm = elementArray[i];
setElementAttribs(elm);
}
}
} else {
setElementAttribs(elm);
}
tinyMCEPopup.editor.nodeChanged();
tinyMCEPopup.execCommand('mceEndUndoLevel');
tinyMCEPopup.close();
}
function insertInlineElement(en) {
var ed = tinyMCEPopup.editor, dom = ed.dom;
ed.getDoc().execCommand('FontName', false, 'mceinline');
tinymce.each(dom.select(tinymce.isWebKit ? 'span' : 'font'), function(n) {
if (n.style.fontFamily == 'mceinline' || n.face == 'mceinline')
dom.replace(dom.create(en), n, 1);
});
}
function removeDel() {
SXE.removeElement('del');
tinyMCEPopup.close();
}
tinyMCEPopup.onInit.add(init);
| JavaScript |
/**
* ins.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
function init() {
SXE.initElementDialog('ins');
if (SXE.currentAction == "update") {
setFormValue('datetime', tinyMCEPopup.editor.dom.getAttrib(SXE.updateElement, 'datetime'));
setFormValue('cite', tinyMCEPopup.editor.dom.getAttrib(SXE.updateElement, 'cite'));
SXE.showRemoveButton();
}
}
function setElementAttribs(elm) {
setAllCommonAttribs(elm);
setAttrib(elm, 'datetime');
setAttrib(elm, 'cite');
}
function insertIns() {
var elm = tinyMCEPopup.editor.dom.getParent(SXE.focusElement, 'INS');
tinyMCEPopup.execCommand('mceBeginUndoLevel');
if (elm == null) {
var s = SXE.inst.selection.getContent();
if(s.length > 0) {
insertInlineElement('INS');
var elementArray = tinymce.grep(SXE.inst.dom.select('ins'), function(n) {return n.id == '#sxe_temp_ins#';});
for (var i=0; i<elementArray.length; i++) {
var elm = elementArray[i];
setElementAttribs(elm);
}
}
} else {
setElementAttribs(elm);
}
tinyMCEPopup.editor.nodeChanged();
tinyMCEPopup.execCommand('mceEndUndoLevel');
tinyMCEPopup.close();
}
function removeIns() {
SXE.removeElement('ins');
tinyMCEPopup.close();
}
function insertInlineElement(en) {
var ed = tinyMCEPopup.editor, dom = ed.dom;
ed.getDoc().execCommand('FontName', false, 'mceinline');
tinymce.each(dom.select(tinymce.isWebKit ? 'span' : 'font'), function(n) {
if (n.style.fontFamily == 'mceinline' || n.face == 'mceinline')
dom.replace(dom.create(en), n, 1);
});
}
tinyMCEPopup.onInit.add(init);
| JavaScript |
/**
* acronym.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
function init() {
SXE.initElementDialog('acronym');
if (SXE.currentAction == "update") {
SXE.showRemoveButton();
}
}
function insertAcronym() {
SXE.insertElement('acronym');
tinyMCEPopup.close();
}
function removeAcronym() {
SXE.removeElement('acronym');
tinyMCEPopup.close();
}
tinyMCEPopup.onInit.add(init);
| JavaScript |
/**
* attributes.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
function init() {
tinyMCEPopup.resizeToInnerSize();
var inst = tinyMCEPopup.editor;
var dom = inst.dom;
var elm = inst.selection.getNode();
var f = document.forms[0];
var onclick = dom.getAttrib(elm, 'onclick');
setFormValue('title', dom.getAttrib(elm, 'title'));
setFormValue('id', dom.getAttrib(elm, 'id'));
setFormValue('style', dom.getAttrib(elm, "style"));
setFormValue('dir', dom.getAttrib(elm, 'dir'));
setFormValue('lang', dom.getAttrib(elm, 'lang'));
setFormValue('tabindex', dom.getAttrib(elm, 'tabindex', typeof(elm.tabindex) != "undefined" ? elm.tabindex : ""));
setFormValue('accesskey', dom.getAttrib(elm, 'accesskey', typeof(elm.accesskey) != "undefined" ? elm.accesskey : ""));
setFormValue('onfocus', dom.getAttrib(elm, 'onfocus'));
setFormValue('onblur', dom.getAttrib(elm, 'onblur'));
setFormValue('onclick', onclick);
setFormValue('ondblclick', dom.getAttrib(elm, 'ondblclick'));
setFormValue('onmousedown', dom.getAttrib(elm, 'onmousedown'));
setFormValue('onmouseup', dom.getAttrib(elm, 'onmouseup'));
setFormValue('onmouseover', dom.getAttrib(elm, 'onmouseover'));
setFormValue('onmousemove', dom.getAttrib(elm, 'onmousemove'));
setFormValue('onmouseout', dom.getAttrib(elm, 'onmouseout'));
setFormValue('onkeypress', dom.getAttrib(elm, 'onkeypress'));
setFormValue('onkeydown', dom.getAttrib(elm, 'onkeydown'));
setFormValue('onkeyup', dom.getAttrib(elm, 'onkeyup'));
className = dom.getAttrib(elm, 'class');
addClassesToList('classlist', 'advlink_styles');
selectByValue(f, 'classlist', className, true);
TinyMCE_EditableSelects.init();
}
function setFormValue(name, value) {
if(value && document.forms[0].elements[name]){
document.forms[0].elements[name].value = value;
}
}
function insertAction() {
var inst = tinyMCEPopup.editor;
var elm = inst.selection.getNode();
tinyMCEPopup.execCommand("mceBeginUndoLevel");
setAllAttribs(elm);
tinyMCEPopup.execCommand("mceEndUndoLevel");
tinyMCEPopup.close();
}
function setAttrib(elm, attrib, value) {
var formObj = document.forms[0];
var valueElm = formObj.elements[attrib.toLowerCase()];
var inst = tinyMCEPopup.editor;
var dom = inst.dom;
if (typeof(value) == "undefined" || value == null) {
value = "";
if (valueElm)
value = valueElm.value;
}
if (value != "") {
dom.setAttrib(elm, attrib.toLowerCase(), value);
if (attrib == "style")
attrib = "style.cssText";
if (attrib.substring(0, 2) == 'on')
value = 'return true;' + value;
if (attrib == "class")
attrib = "className";
elm[attrib]=value;
} else
elm.removeAttribute(attrib);
}
function setAllAttribs(elm) {
var f = document.forms[0];
setAttrib(elm, 'title');
setAttrib(elm, 'id');
setAttrib(elm, 'style');
setAttrib(elm, 'class', getSelectValue(f, 'classlist'));
setAttrib(elm, 'dir');
setAttrib(elm, 'lang');
setAttrib(elm, 'tabindex');
setAttrib(elm, 'accesskey');
setAttrib(elm, 'onfocus');
setAttrib(elm, 'onblur');
setAttrib(elm, 'onclick');
setAttrib(elm, 'ondblclick');
setAttrib(elm, 'onmousedown');
setAttrib(elm, 'onmouseup');
setAttrib(elm, 'onmouseover');
setAttrib(elm, 'onmousemove');
setAttrib(elm, 'onmouseout');
setAttrib(elm, 'onkeypress');
setAttrib(elm, 'onkeydown');
setAttrib(elm, 'onkeyup');
// Refresh in old MSIE
// if (tinyMCE.isMSIE5)
// elm.outerHTML = elm.outerHTML;
}
function insertAttribute() {
tinyMCEPopup.close();
}
tinyMCEPopup.onInit.add(init);
tinyMCEPopup.requireLangPack();
| JavaScript |
/**
* editor_plugin_src.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
(function() {
tinymce.create('tinymce.plugins.XHTMLXtrasPlugin', {
init : function(ed, url) {
// Register commands
ed.addCommand('mceCite', function() {
ed.windowManager.open({
file : url + '/cite.htm',
width : 350 + parseInt(ed.getLang('xhtmlxtras.cite_delta_width', 0)),
height : 250 + parseInt(ed.getLang('xhtmlxtras.cite_delta_height', 0)),
inline : 1
}, {
plugin_url : url
});
});
ed.addCommand('mceAcronym', function() {
ed.windowManager.open({
file : url + '/acronym.htm',
width : 350 + parseInt(ed.getLang('xhtmlxtras.acronym_delta_width', 0)),
height : 250 + parseInt(ed.getLang('xhtmlxtras.acronym_delta_width', 0)),
inline : 1
}, {
plugin_url : url
});
});
ed.addCommand('mceAbbr', function() {
ed.windowManager.open({
file : url + '/abbr.htm',
width : 350 + parseInt(ed.getLang('xhtmlxtras.abbr_delta_width', 0)),
height : 250 + parseInt(ed.getLang('xhtmlxtras.abbr_delta_width', 0)),
inline : 1
}, {
plugin_url : url
});
});
ed.addCommand('mceDel', function() {
ed.windowManager.open({
file : url + '/del.htm',
width : 340 + parseInt(ed.getLang('xhtmlxtras.del_delta_width', 0)),
height : 310 + parseInt(ed.getLang('xhtmlxtras.del_delta_width', 0)),
inline : 1
}, {
plugin_url : url
});
});
ed.addCommand('mceIns', function() {
ed.windowManager.open({
file : url + '/ins.htm',
width : 340 + parseInt(ed.getLang('xhtmlxtras.ins_delta_width', 0)),
height : 310 + parseInt(ed.getLang('xhtmlxtras.ins_delta_width', 0)),
inline : 1
}, {
plugin_url : url
});
});
ed.addCommand('mceAttributes', function() {
ed.windowManager.open({
file : url + '/attributes.htm',
width : 380,
height : 370,
inline : 1
}, {
plugin_url : url
});
});
// Register buttons
ed.addButton('cite', {title : 'xhtmlxtras.cite_desc', cmd : 'mceCite'});
ed.addButton('acronym', {title : 'xhtmlxtras.acronym_desc', cmd : 'mceAcronym'});
ed.addButton('abbr', {title : 'xhtmlxtras.abbr_desc', cmd : 'mceAbbr'});
ed.addButton('del', {title : 'xhtmlxtras.del_desc', cmd : 'mceDel'});
ed.addButton('ins', {title : 'xhtmlxtras.ins_desc', cmd : 'mceIns'});
ed.addButton('attribs', {title : 'xhtmlxtras.attribs_desc', cmd : 'mceAttributes'});
ed.onNodeChange.add(function(ed, cm, n, co) {
n = ed.dom.getParent(n, 'CITE,ACRONYM,ABBR,DEL,INS');
cm.setDisabled('cite', co);
cm.setDisabled('acronym', co);
cm.setDisabled('abbr', co);
cm.setDisabled('del', co);
cm.setDisabled('ins', co);
cm.setDisabled('attribs', n && n.nodeName == 'BODY');
cm.setActive('cite', 0);
cm.setActive('acronym', 0);
cm.setActive('abbr', 0);
cm.setActive('del', 0);
cm.setActive('ins', 0);
// Activate all
if (n) {
do {
cm.setDisabled(n.nodeName.toLowerCase(), 0);
cm.setActive(n.nodeName.toLowerCase(), 1);
} while (n = n.parentNode);
}
});
ed.onPreInit.add(function() {
// Fixed IE issue where it can't handle these elements correctly
ed.dom.create('abbr');
});
},
getInfo : function() {
return {
longname : 'XHTML Xtras Plugin',
author : 'Moxiecode Systems AB',
authorurl : 'http://tinymce.moxiecode.com',
infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/xhtmlxtras',
version : tinymce.majorVersion + "." + tinymce.minorVersion
};
}
});
// Register plugin
tinymce.PluginManager.add('xhtmlxtras', tinymce.plugins.XHTMLXtrasPlugin);
})(); | JavaScript |
tinyMCE.addI18n('en.xhtmlxtras_dlg',{
attribute_label_title:"Title",
attribute_label_id:"ID",
attribute_label_class:"Class",
attribute_label_style:"Style",
attribute_label_cite:"Cite",
attribute_label_datetime:"Date/Time",
attribute_label_langdir:"Text Direction",
attribute_option_ltr:"Left to right",
attribute_option_rtl:"Right to left",
attribute_label_langcode:"Language",
attribute_label_tabindex:"TabIndex",
attribute_label_accesskey:"AccessKey",
attribute_events_tab:"Events",
attribute_attrib_tab:"Attributes",
general_tab:"General",
attrib_tab:"Attributes",
events_tab:"Events",
fieldset_general_tab:"General Settings",
fieldset_attrib_tab:"Element Attributes",
fieldset_events_tab:"Element Events",
title_ins_element:"Insertion Element",
title_del_element:"Deletion Element",
title_acronym_element:"Acronym Element",
title_abbr_element:"Abbreviation Element",
title_cite_element:"Citation Element",
remove:"Remove",
insert_date:"Insert current date/time",
option_ltr:"Left to right",
option_rtl:"Right to left",
attribs_title:"Insert/Edit Attributes"
}); | JavaScript |
/**
* editor_plugin_src.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
(function() {
tinymce.create('tinymce.plugins.IESpell', {
init : function(ed, url) {
var t = this, sp;
if (!tinymce.isIE)
return;
t.editor = ed;
// Register commands
ed.addCommand('mceIESpell', function() {
try {
sp = new ActiveXObject("ieSpell.ieSpellExtension");
sp.CheckDocumentNode(ed.getDoc().documentElement);
} catch (e) {
if (e.number == -2146827859) {
ed.windowManager.confirm(ed.getLang("iespell.download"), function(s) {
if (s)
window.open('http://www.iespell.com/download.php', 'ieSpellDownload', '');
});
} else
ed.windowManager.alert("Error Loading ieSpell: Exception " + e.number);
}
});
// Register buttons
ed.addButton('iespell', {title : 'iespell.iespell_desc', cmd : 'mceIESpell'});
},
getInfo : function() {
return {
longname : 'IESpell (IE Only)',
author : 'Moxiecode Systems AB',
authorurl : 'http://tinymce.moxiecode.com',
infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/iespell',
version : tinymce.majorVersion + "." + tinymce.minorVersion
};
}
});
// Register plugin
tinymce.PluginManager.add('iespell', tinymce.plugins.IESpell);
})(); | JavaScript |
/**
* editor_plugin_src.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
(function() {
tinymce.create('tinymce.plugins.Nonbreaking', {
init : function(ed, url) {
var t = this;
t.editor = ed;
// Register commands
ed.addCommand('mceNonBreaking', function() {
ed.execCommand('mceInsertContent', false, (ed.plugins.visualchars && ed.plugins.visualchars.state) ? '<span _mce_bogus="1" class="mceItemHidden mceItemNbsp"> </span>' : ' ');
});
// Register buttons
ed.addButton('nonbreaking', {title : 'nonbreaking.nonbreaking_desc', cmd : 'mceNonBreaking'});
if (ed.getParam('nonbreaking_force_tab')) {
ed.onKeyDown.add(function(ed, e) {
if (tinymce.isIE && e.keyCode == 9) {
ed.execCommand('mceNonBreaking');
ed.execCommand('mceNonBreaking');
ed.execCommand('mceNonBreaking');
tinymce.dom.Event.cancel(e);
}
});
}
},
getInfo : function() {
return {
longname : 'Nonbreaking space',
author : 'Moxiecode Systems AB',
authorurl : 'http://tinymce.moxiecode.com',
infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/nonbreaking',
version : tinymce.majorVersion + "." + tinymce.minorVersion
};
}
// Private methods
});
// Register plugin
tinymce.PluginManager.add('nonbreaking', tinymce.plugins.Nonbreaking);
})(); | JavaScript |
/**
* editor_plugin_src.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*
* This plugin will force TinyMCE to produce deprecated legacy output such as font elements, u elements, align
* attributes and so forth. There are a few cases where these old items might be needed for example in email applications or with Flash
*
* However you should NOT use this plugin if you are building some system that produces web contents such as a CMS. All these elements are
* not apart of the newer specifications for HTML and XHTML.
*/
(function(tinymce) {
// Override inline_styles setting to force TinyMCE to produce deprecated contents
tinymce.onAddEditor.addToTop(function(tinymce, editor) {
editor.settings.inline_styles = false;
});
// Create the legacy ouput plugin
tinymce.create('tinymce.plugins.LegacyOutput', {
init : function(editor) {
editor.onInit.add(function() {
var alignElements = 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img',
fontSizes = tinymce.explode(editor.settings.font_size_style_values),
serializer = editor.serializer;
// Override some internal formats to produce legacy elements and attributes
editor.formatter.register({
// Change alignment formats to use the deprecated align attribute
alignleft : {selector : alignElements, attributes : {align : 'left'}},
aligncenter : {selector : alignElements, attributes : {align : 'center'}},
alignright : {selector : alignElements, attributes : {align : 'right'}},
alignfull : {selector : alignElements, attributes : {align : 'full'}},
// Change the basic formatting elements to use deprecated element types
bold : {inline : 'b'},
italic : {inline : 'i'},
underline : {inline : 'u'},
strikethrough : {inline : 'strike'},
// Change font size and font family to use the deprecated font element
fontname : {inline : 'font', attributes : {face : '%value'}},
fontsize : {
inline : 'font',
attributes : {
size : function(vars) {
return tinymce.inArray(fontSizes, vars.value) + 1;
}
}
},
// Setup font elements for colors as well
forecolor : {inline : 'font', styles : {color : '%value'}},
hilitecolor : {inline : 'font', styles : {backgroundColor : '%value'}}
});
// Force parsing of the serializer rules
serializer._setup();
// Check that deprecated elements are allowed if not add them
tinymce.each('b,i,u,strike'.split(','), function(name) {
var rule = serializer.rules[name];
if (!rule)
serializer.addRules(name);
});
// Add font element if it's missing
if (!serializer.rules["font"])
serializer.addRules("font[face|size|color|style]");
// Add the missing and depreacted align attribute for the serialization engine
tinymce.each(alignElements.split(','), function(name) {
var rule = serializer.rules[name], found;
if (rule) {
tinymce.each(rule.attribs, function(name, attr) {
if (attr.name == 'align') {
found = true;
return false;
}
});
if (!found)
rule.attribs.push({name : 'align'});
}
});
// Listen for the onNodeChange event so that we can do special logic for the font size and font name drop boxes
editor.onNodeChange.add(function(editor, control_manager) {
var control, fontElm, fontName, fontSize;
// Find font element get it's name and size
fontElm = editor.dom.getParent(editor.selection.getNode(), 'font');
if (fontElm) {
fontName = fontElm.face;
fontSize = fontElm.size;
}
// Select/unselect the font name in droplist
if (control = control_manager.get('fontselect')) {
control.select(function(value) {
return value == fontName;
});
}
// Select/unselect the font size in droplist
if (control = control_manager.get('fontsizeselect')) {
control.select(function(value) {
var index = tinymce.inArray(fontSizes, value.fontSize);
return index + 1 == fontSize;
});
}
});
});
},
getInfo : function() {
return {
longname : 'LegacyOutput',
author : 'Moxiecode Systems AB',
authorurl : 'http://tinymce.moxiecode.com',
infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/legacyoutput',
version : tinymce.majorVersion + "." + tinymce.minorVersion
};
}
});
// Register plugin
tinymce.PluginManager.add('legacyoutput', tinymce.plugins.LegacyOutput);
})(tinymce); | JavaScript |
/**
* editor_plugin_src.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
(function() {
tinymce.create('tinymce.plugins.Save', {
init : function(ed, url) {
var t = this;
t.editor = ed;
// Register commands
ed.addCommand('mceSave', t._save, t);
ed.addCommand('mceCancel', t._cancel, t);
// Register buttons
ed.addButton('save', {title : 'save.save_desc', cmd : 'mceSave'});
ed.addButton('cancel', {title : 'save.cancel_desc', cmd : 'mceCancel'});
ed.onNodeChange.add(t._nodeChange, t);
ed.addShortcut('ctrl+s', ed.getLang('save.save_desc'), 'mceSave');
},
getInfo : function() {
return {
longname : 'Save',
author : 'Moxiecode Systems AB',
authorurl : 'http://tinymce.moxiecode.com',
infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/save',
version : tinymce.majorVersion + "." + tinymce.minorVersion
};
},
// Private methods
_nodeChange : function(ed, cm, n) {
var ed = this.editor;
if (ed.getParam('save_enablewhendirty')) {
cm.setDisabled('save', !ed.isDirty());
cm.setDisabled('cancel', !ed.isDirty());
}
},
// Private methods
_save : function() {
var ed = this.editor, formObj, os, i, elementId;
formObj = tinymce.DOM.get(ed.id).form || tinymce.DOM.getParent(ed.id, 'form');
if (ed.getParam("save_enablewhendirty") && !ed.isDirty())
return;
tinyMCE.triggerSave();
// Use callback instead
if (os = ed.getParam("save_onsavecallback")) {
if (ed.execCallback('save_onsavecallback', ed)) {
ed.startContent = tinymce.trim(ed.getContent({format : 'raw'}));
ed.nodeChanged();
}
return;
}
if (formObj) {
ed.isNotDirty = true;
if (formObj.onsubmit == null || formObj.onsubmit() != false)
formObj.submit();
ed.nodeChanged();
} else
ed.windowManager.alert("Error: No form element found.");
},
_cancel : function() {
var ed = this.editor, os, h = tinymce.trim(ed.startContent);
// Use callback instead
if (os = ed.getParam("save_oncancelcallback")) {
ed.execCallback('save_oncancelcallback', ed);
return;
}
ed.setContent(h);
ed.undoManager.clear();
ed.nodeChanged();
}
});
// Register plugin
tinymce.PluginManager.add('save', tinymce.plugins.Save);
})(); | JavaScript |
tinyMCEPopup.requireLangPack();
var ExampleDialog = {
init : function() {
var f = document.forms[0];
// Get the selected contents as text and place it in the input
f.someval.value = tinyMCEPopup.editor.selection.getContent({format : 'text'});
f.somearg.value = tinyMCEPopup.getWindowArg('some_custom_arg');
},
insert : function() {
// Insert the contents from the input into the document
tinyMCEPopup.editor.execCommand('mceInsertContent', false, document.forms[0].someval.value);
tinyMCEPopup.close();
}
};
tinyMCEPopup.onInit.add(ExampleDialog.init, ExampleDialog);
| JavaScript |
/**
* editor_plugin_src.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
(function() {
// Load plugin specific language pack
tinymce.PluginManager.requireLangPack('example');
tinymce.create('tinymce.plugins.ExamplePlugin', {
/**
* Initializes the plugin, this will be executed after the plugin has been created.
* This call is done before the editor instance has finished it's initialization so use the onInit event
* of the editor instance to intercept that event.
*
* @param {tinymce.Editor} ed Editor instance that the plugin is initialized in.
* @param {string} url Absolute URL to where the plugin is located.
*/
init : function(ed, url) {
// Register the command so that it can be invoked by using tinyMCE.activeEditor.execCommand('mceExample');
ed.addCommand('mceExample', function() {
ed.windowManager.open({
file : url + '/dialog.htm',
width : 320 + parseInt(ed.getLang('example.delta_width', 0)),
height : 120 + parseInt(ed.getLang('example.delta_height', 0)),
inline : 1
}, {
plugin_url : url, // Plugin absolute URL
some_custom_arg : 'custom arg' // Custom argument
});
});
// Register example button
ed.addButton('example', {
title : 'example.desc',
cmd : 'mceExample',
image : url + '/img/example.gif'
});
// Add a node change handler, selects the button in the UI when a image is selected
ed.onNodeChange.add(function(ed, cm, n) {
cm.setActive('example', n.nodeName == 'IMG');
});
},
/**
* Creates control instances based in the incomming name. This method is normally not
* needed since the addButton method of the tinymce.Editor class is a more easy way of adding buttons
* but you sometimes need to create more complex controls like listboxes, split buttons etc then this
* method can be used to create those.
*
* @param {String} n Name of the control to create.
* @param {tinymce.ControlManager} cm Control manager to use inorder to create new control.
* @return {tinymce.ui.Control} New control instance or null if no control was created.
*/
createControl : function(n, cm) {
return null;
},
/**
* Returns information about the plugin as a name/value array.
* The current keys are longname, author, authorurl, infourl and version.
*
* @return {Object} Name/value array containing information about the plugin.
*/
getInfo : function() {
return {
longname : 'Example plugin',
author : 'Some author',
authorurl : 'http://tinymce.moxiecode.com',
infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/example',
version : "1.0"
};
}
});
// Register plugin
tinymce.PluginManager.add('example', tinymce.plugins.ExamplePlugin);
})(); | JavaScript |
tinyMCE.addI18n('en.example_dlg',{
title : 'This is just a example title'
});
| JavaScript |
tinyMCE.addI18n('en.example',{
desc : 'This is just a template button'
});
| JavaScript |
/**
* editor_plugin_src.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
(function() {
tinymce.create('tinymce.plugins.BBCodePlugin', {
init : function(ed, url) {
var t = this, dialect = ed.getParam('bbcode_dialect', 'punbb').toLowerCase();
ed.onBeforeSetContent.add(function(ed, o) {
o.content = t['_' + dialect + '_bbcode2html'](o.content);
});
ed.onPostProcess.add(function(ed, o) {
if (o.set)
o.content = t['_' + dialect + '_bbcode2html'](o.content);
if (o.get)
o.content = t['_' + dialect + '_html2bbcode'](o.content);
});
},
getInfo : function() {
return {
longname : 'BBCode Plugin',
author : 'Moxiecode Systems AB',
authorurl : 'http://tinymce.moxiecode.com',
infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/bbcode',
version : tinymce.majorVersion + "." + tinymce.minorVersion
};
},
// Private methods
// HTML -> BBCode in PunBB dialect
_punbb_html2bbcode : function(s) {
s = tinymce.trim(s);
function rep(re, str) {
s = s.replace(re, str);
};
// example: <strong> to [b]
rep(/<a.*?href=\"(.*?)\".*?>(.*?)<\/a>/gi,"[url=$1]$2[/url]");
rep(/<font.*?color=\"(.*?)\".*?class=\"codeStyle\".*?>(.*?)<\/font>/gi,"[code][color=$1]$2[/color][/code]");
rep(/<font.*?color=\"(.*?)\".*?class=\"quoteStyle\".*?>(.*?)<\/font>/gi,"[quote][color=$1]$2[/color][/quote]");
rep(/<font.*?class=\"codeStyle\".*?color=\"(.*?)\".*?>(.*?)<\/font>/gi,"[code][color=$1]$2[/color][/code]");
rep(/<font.*?class=\"quoteStyle\".*?color=\"(.*?)\".*?>(.*?)<\/font>/gi,"[quote][color=$1]$2[/color][/quote]");
rep(/<span style=\"color: ?(.*?);\">(.*?)<\/span>/gi,"[color=$1]$2[/color]");
rep(/<font.*?color=\"(.*?)\".*?>(.*?)<\/font>/gi,"[color=$1]$2[/color]");
rep(/<span style=\"font-size:(.*?);\">(.*?)<\/span>/gi,"[size=$1]$2[/size]");
rep(/<font>(.*?)<\/font>/gi,"$1");
rep(/<img.*?src=\"(.*?)\".*?\/>/gi,"[img]$1[/img]");
rep(/<span class=\"codeStyle\">(.*?)<\/span>/gi,"[code]$1[/code]");
rep(/<span class=\"quoteStyle\">(.*?)<\/span>/gi,"[quote]$1[/quote]");
rep(/<strong class=\"codeStyle\">(.*?)<\/strong>/gi,"[code][b]$1[/b][/code]");
rep(/<strong class=\"quoteStyle\">(.*?)<\/strong>/gi,"[quote][b]$1[/b][/quote]");
rep(/<em class=\"codeStyle\">(.*?)<\/em>/gi,"[code][i]$1[/i][/code]");
rep(/<em class=\"quoteStyle\">(.*?)<\/em>/gi,"[quote][i]$1[/i][/quote]");
rep(/<u class=\"codeStyle\">(.*?)<\/u>/gi,"[code][u]$1[/u][/code]");
rep(/<u class=\"quoteStyle\">(.*?)<\/u>/gi,"[quote][u]$1[/u][/quote]");
rep(/<\/(strong|b)>/gi,"[/b]");
rep(/<(strong|b)>/gi,"[b]");
rep(/<\/(em|i)>/gi,"[/i]");
rep(/<(em|i)>/gi,"[i]");
rep(/<\/u>/gi,"[/u]");
rep(/<span style=\"text-decoration: ?underline;\">(.*?)<\/span>/gi,"[u]$1[/u]");
rep(/<u>/gi,"[u]");
rep(/<blockquote[^>]*>/gi,"[quote]");
rep(/<\/blockquote>/gi,"[/quote]");
rep(/<br \/>/gi,"\n");
rep(/<br\/>/gi,"\n");
rep(/<br>/gi,"\n");
rep(/<p>/gi,"");
rep(/<\/p>/gi,"\n");
rep(/ /gi," ");
rep(/"/gi,"\"");
rep(/</gi,"<");
rep(/>/gi,">");
rep(/&/gi,"&");
return s;
},
// BBCode -> HTML from PunBB dialect
_punbb_bbcode2html : function(s) {
s = tinymce.trim(s);
function rep(re, str) {
s = s.replace(re, str);
};
// example: [b] to <strong>
rep(/\n/gi,"<br />");
rep(/\[b\]/gi,"<strong>");
rep(/\[\/b\]/gi,"</strong>");
rep(/\[i\]/gi,"<em>");
rep(/\[\/i\]/gi,"</em>");
rep(/\[u\]/gi,"<u>");
rep(/\[\/u\]/gi,"</u>");
rep(/\[url=([^\]]+)\](.*?)\[\/url\]/gi,"<a href=\"$1\">$2</a>");
rep(/\[url\](.*?)\[\/url\]/gi,"<a href=\"$1\">$1</a>");
rep(/\[img\](.*?)\[\/img\]/gi,"<img src=\"$1\" />");
rep(/\[color=(.*?)\](.*?)\[\/color\]/gi,"<font color=\"$1\">$2</font>");
rep(/\[code\](.*?)\[\/code\]/gi,"<span class=\"codeStyle\">$1</span> ");
rep(/\[quote.*?\](.*?)\[\/quote\]/gi,"<span class=\"quoteStyle\">$1</span> ");
return s;
}
});
// Register plugin
tinymce.PluginManager.add('bbcode', tinymce.plugins.BBCodePlugin);
})(); | JavaScript |
tinyMCEPopup.requireLangPack();
function init() {
tinyMCEPopup.resizeToInnerSize();
document.getElementById('backgroundimagebrowsercontainer').innerHTML = getBrowserHTML('backgroundimagebrowser','backgroundimage','image','table');
document.getElementById('bgcolor_pickcontainer').innerHTML = getColorPickerHTML('bgcolor_pick','bgcolor');
var inst = tinyMCEPopup.editor;
var dom = inst.dom;
var trElm = dom.getParent(inst.selection.getStart(), "tr");
var formObj = document.forms[0];
var st = dom.parseStyle(dom.getAttrib(trElm, "style"));
// Get table row data
var rowtype = trElm.parentNode.nodeName.toLowerCase();
var align = dom.getAttrib(trElm, 'align');
var valign = dom.getAttrib(trElm, 'valign');
var height = trimSize(getStyle(trElm, 'height', 'height'));
var className = dom.getAttrib(trElm, 'class');
var bgcolor = convertRGBToHex(getStyle(trElm, 'bgcolor', 'backgroundColor'));
var backgroundimage = getStyle(trElm, 'background', 'backgroundImage').replace(new RegExp("url\\(['\"]?([^'\"]*)['\"]?\\)", 'gi'), "$1");
var id = dom.getAttrib(trElm, 'id');
var lang = dom.getAttrib(trElm, 'lang');
var dir = dom.getAttrib(trElm, 'dir');
selectByValue(formObj, 'rowtype', rowtype);
// Any cells selected
if (dom.select('td.mceSelected,th.mceSelected', trElm).length == 0) {
// Setup form
addClassesToList('class', 'table_row_styles');
TinyMCE_EditableSelects.init();
formObj.bgcolor.value = bgcolor;
formObj.backgroundimage.value = backgroundimage;
formObj.height.value = height;
formObj.id.value = id;
formObj.lang.value = lang;
formObj.style.value = dom.serializeStyle(st);
selectByValue(formObj, 'align', align);
selectByValue(formObj, 'valign', valign);
selectByValue(formObj, 'class', className, true, true);
selectByValue(formObj, 'dir', dir);
// Resize some elements
if (isVisible('backgroundimagebrowser'))
document.getElementById('backgroundimage').style.width = '180px';
updateColor('bgcolor_pick', 'bgcolor');
} else
tinyMCEPopup.dom.hide('action');
}
function updateAction() {
var inst = tinyMCEPopup.editor, dom = inst.dom, trElm, tableElm, formObj = document.forms[0];
var action = getSelectValue(formObj, 'action');
tinyMCEPopup.restoreSelection();
trElm = dom.getParent(inst.selection.getStart(), "tr");
tableElm = dom.getParent(inst.selection.getStart(), "table");
// Update all selected rows
if (dom.select('td.mceSelected,th.mceSelected', trElm).length > 0) {
tinymce.each(tableElm.rows, function(tr) {
var i;
for (i = 0; i < tr.cells.length; i++) {
if (dom.hasClass(tr.cells[i], 'mceSelected')) {
updateRow(tr, true);
return;
}
}
});
inst.addVisual();
inst.nodeChanged();
inst.execCommand('mceEndUndoLevel');
tinyMCEPopup.close();
return;
}
inst.execCommand('mceBeginUndoLevel');
switch (action) {
case "row":
updateRow(trElm);
break;
case "all":
var rows = tableElm.getElementsByTagName("tr");
for (var i=0; i<rows.length; i++)
updateRow(rows[i], true);
break;
case "odd":
case "even":
var rows = tableElm.getElementsByTagName("tr");
for (var i=0; i<rows.length; i++) {
if ((i % 2 == 0 && action == "odd") || (i % 2 != 0 && action == "even"))
updateRow(rows[i], true, true);
}
break;
}
inst.addVisual();
inst.nodeChanged();
inst.execCommand('mceEndUndoLevel');
tinyMCEPopup.close();
}
function updateRow(tr_elm, skip_id, skip_parent) {
var inst = tinyMCEPopup.editor;
var formObj = document.forms[0];
var dom = inst.dom;
var curRowType = tr_elm.parentNode.nodeName.toLowerCase();
var rowtype = getSelectValue(formObj, 'rowtype');
var doc = inst.getDoc();
// Update row element
if (!skip_id)
tr_elm.setAttribute('id', formObj.id.value);
tr_elm.setAttribute('align', getSelectValue(formObj, 'align'));
tr_elm.setAttribute('vAlign', getSelectValue(formObj, 'valign'));
tr_elm.setAttribute('lang', formObj.lang.value);
tr_elm.setAttribute('dir', getSelectValue(formObj, 'dir'));
tr_elm.setAttribute('style', dom.serializeStyle(dom.parseStyle(formObj.style.value)));
dom.setAttrib(tr_elm, 'class', getSelectValue(formObj, 'class'));
// Clear deprecated attributes
tr_elm.setAttribute('background', '');
tr_elm.setAttribute('bgColor', '');
tr_elm.setAttribute('height', '');
// Set styles
tr_elm.style.height = getCSSSize(formObj.height.value);
tr_elm.style.backgroundColor = formObj.bgcolor.value;
if (formObj.backgroundimage.value != "")
tr_elm.style.backgroundImage = "url('" + formObj.backgroundimage.value + "')";
else
tr_elm.style.backgroundImage = '';
// Setup new rowtype
if (curRowType != rowtype && !skip_parent) {
// first, clone the node we are working on
var newRow = tr_elm.cloneNode(1);
// next, find the parent of its new destination (creating it if necessary)
var theTable = dom.getParent(tr_elm, "table");
var dest = rowtype;
var newParent = null;
for (var i = 0; i < theTable.childNodes.length; i++) {
if (theTable.childNodes[i].nodeName.toLowerCase() == dest)
newParent = theTable.childNodes[i];
}
if (newParent == null) {
newParent = doc.createElement(dest);
if (dest == "thead") {
if (theTable.firstChild.nodeName == 'CAPTION')
inst.dom.insertAfter(newParent, theTable.firstChild);
else
theTable.insertBefore(newParent, theTable.firstChild);
} else
theTable.appendChild(newParent);
}
// append the row to the new parent
newParent.appendChild(newRow);
// remove the original
tr_elm.parentNode.removeChild(tr_elm);
// set tr_elm to the new node
tr_elm = newRow;
}
dom.setAttrib(tr_elm, 'style', dom.serializeStyle(dom.parseStyle(tr_elm.style.cssText)));
}
function changedBackgroundImage() {
var formObj = document.forms[0], dom = tinyMCEPopup.editor.dom;
var st = dom.parseStyle(formObj.style.value);
st['background-image'] = "url('" + formObj.backgroundimage.value + "')";
formObj.style.value = dom.serializeStyle(st);
}
function changedStyle() {
var formObj = document.forms[0], dom = tinyMCEPopup.editor.dom;
var st = dom.parseStyle(formObj.style.value);
if (st['background-image'])
formObj.backgroundimage.value = st['background-image'].replace(new RegExp("url\\('?([^']*)'?\\)", 'gi'), "$1");
else
formObj.backgroundimage.value = '';
if (st['height'])
formObj.height.value = trimSize(st['height']);
if (st['background-color']) {
formObj.bgcolor.value = st['background-color'];
updateColor('bgcolor_pick','bgcolor');
}
}
function changedSize() {
var formObj = document.forms[0], dom = tinyMCEPopup.editor.dom;
var st = dom.parseStyle(formObj.style.value);
var height = formObj.height.value;
if (height != "")
st['height'] = getCSSSize(height);
else
st['height'] = "";
formObj.style.value = dom.serializeStyle(st);
}
function changedColor() {
var formObj = document.forms[0], dom = tinyMCEPopup.editor.dom;
var st = dom.parseStyle(formObj.style.value);
st['background-color'] = formObj.bgcolor.value;
formObj.style.value = dom.serializeStyle(st);
}
tinyMCEPopup.onInit.add(init);
| JavaScript |
tinyMCEPopup.requireLangPack();
var action, orgTableWidth, orgTableHeight, dom = tinyMCEPopup.editor.dom;
function insertTable() {
var formObj = document.forms[0];
var inst = tinyMCEPopup.editor, dom = inst.dom;
var cols = 2, rows = 2, border = 0, cellpadding = -1, cellspacing = -1, align, width, height, className, caption, frame, rules;
var html = '', capEl, elm;
var cellLimit, rowLimit, colLimit;
tinyMCEPopup.restoreSelection();
if (!AutoValidator.validate(formObj)) {
tinyMCEPopup.alert(inst.getLang('invalid_data'));
return false;
}
elm = dom.getParent(inst.selection.getNode(), 'table');
// Get form data
cols = formObj.elements['cols'].value;
rows = formObj.elements['rows'].value;
border = formObj.elements['border'].value != "" ? formObj.elements['border'].value : 0;
cellpadding = formObj.elements['cellpadding'].value != "" ? formObj.elements['cellpadding'].value : "";
cellspacing = formObj.elements['cellspacing'].value != "" ? formObj.elements['cellspacing'].value : "";
align = getSelectValue(formObj, "align");
frame = getSelectValue(formObj, "tframe");
rules = getSelectValue(formObj, "rules");
width = formObj.elements['width'].value;
height = formObj.elements['height'].value;
bordercolor = formObj.elements['bordercolor'].value;
bgcolor = formObj.elements['bgcolor'].value;
className = getSelectValue(formObj, "class");
id = formObj.elements['id'].value;
summary = formObj.elements['summary'].value;
style = formObj.elements['style'].value;
dir = formObj.elements['dir'].value;
lang = formObj.elements['lang'].value;
background = formObj.elements['backgroundimage'].value;
caption = formObj.elements['caption'].checked;
cellLimit = tinyMCEPopup.getParam('table_cell_limit', false);
rowLimit = tinyMCEPopup.getParam('table_row_limit', false);
colLimit = tinyMCEPopup.getParam('table_col_limit', false);
// Validate table size
if (colLimit && cols > colLimit) {
tinyMCEPopup.alert(inst.getLang('table_dlg.col_limit').replace(/\{\$cols\}/g, colLimit));
return false;
} else if (rowLimit && rows > rowLimit) {
tinyMCEPopup.alert(inst.getLang('table_dlg.row_limit').replace(/\{\$rows\}/g, rowLimit));
return false;
} else if (cellLimit && cols * rows > cellLimit) {
tinyMCEPopup.alert(inst.getLang('table_dlg.cell_limit').replace(/\{\$cells\}/g, cellLimit));
return false;
}
// Update table
if (action == "update") {
inst.execCommand('mceBeginUndoLevel');
dom.setAttrib(elm, 'cellPadding', cellpadding, true);
dom.setAttrib(elm, 'cellSpacing', cellspacing, true);
dom.setAttrib(elm, 'border', border);
dom.setAttrib(elm, 'align', align);
dom.setAttrib(elm, 'frame', frame);
dom.setAttrib(elm, 'rules', rules);
dom.setAttrib(elm, 'class', className);
dom.setAttrib(elm, 'style', style);
dom.setAttrib(elm, 'id', id);
dom.setAttrib(elm, 'summary', summary);
dom.setAttrib(elm, 'dir', dir);
dom.setAttrib(elm, 'lang', lang);
capEl = inst.dom.select('caption', elm)[0];
if (capEl && !caption)
capEl.parentNode.removeChild(capEl);
if (!capEl && caption) {
capEl = elm.ownerDocument.createElement('caption');
if (!tinymce.isIE)
capEl.innerHTML = '<br _mce_bogus="1"/>';
elm.insertBefore(capEl, elm.firstChild);
}
if (width && inst.settings.inline_styles) {
dom.setStyle(elm, 'width', width);
dom.setAttrib(elm, 'width', '');
} else {
dom.setAttrib(elm, 'width', width, true);
dom.setStyle(elm, 'width', '');
}
// Remove these since they are not valid XHTML
dom.setAttrib(elm, 'borderColor', '');
dom.setAttrib(elm, 'bgColor', '');
dom.setAttrib(elm, 'background', '');
if (height && inst.settings.inline_styles) {
dom.setStyle(elm, 'height', height);
dom.setAttrib(elm, 'height', '');
} else {
dom.setAttrib(elm, 'height', height, true);
dom.setStyle(elm, 'height', '');
}
if (background != '')
elm.style.backgroundImage = "url('" + background + "')";
else
elm.style.backgroundImage = '';
/* if (tinyMCEPopup.getParam("inline_styles")) {
if (width != '')
elm.style.width = getCSSSize(width);
}*/
if (bordercolor != "") {
elm.style.borderColor = bordercolor;
elm.style.borderStyle = elm.style.borderStyle == "" ? "solid" : elm.style.borderStyle;
elm.style.borderWidth = border == "" ? "1px" : border;
} else
elm.style.borderColor = '';
elm.style.backgroundColor = bgcolor;
elm.style.height = getCSSSize(height);
inst.addVisual();
// Fix for stange MSIE align bug
//elm.outerHTML = elm.outerHTML;
inst.nodeChanged();
inst.execCommand('mceEndUndoLevel');
// Repaint if dimensions changed
if (formObj.width.value != orgTableWidth || formObj.height.value != orgTableHeight)
inst.execCommand('mceRepaint');
tinyMCEPopup.close();
return true;
}
// Create new table
html += '<table';
html += makeAttrib('id', id);
html += makeAttrib('border', border);
html += makeAttrib('cellpadding', cellpadding);
html += makeAttrib('cellspacing', cellspacing);
html += makeAttrib('_mce_new', '1');
if (width && inst.settings.inline_styles) {
if (style)
style += '; ';
// Force px
if (/^[0-9\.]+$/.test(width))
width += 'px';
style += 'width: ' + width;
} else
html += makeAttrib('width', width);
/* if (height) {
if (style)
style += '; ';
style += 'height: ' + height;
}*/
//html += makeAttrib('height', height);
//html += makeAttrib('bordercolor', bordercolor);
//html += makeAttrib('bgcolor', bgcolor);
html += makeAttrib('align', align);
html += makeAttrib('frame', frame);
html += makeAttrib('rules', rules);
html += makeAttrib('class', className);
html += makeAttrib('style', style);
html += makeAttrib('summary', summary);
html += makeAttrib('dir', dir);
html += makeAttrib('lang', lang);
html += '>';
if (caption) {
if (!tinymce.isIE)
html += '<caption><br _mce_bogus="1"/></caption>';
else
html += '<caption></caption>';
}
for (var y=0; y<rows; y++) {
html += "<tr>";
for (var x=0; x<cols; x++) {
if (!tinymce.isIE)
html += '<td><br _mce_bogus="1"/></td>';
else
html += '<td></td>';
}
html += "</tr>";
}
html += "</table>";
inst.execCommand('mceBeginUndoLevel');
// Move table
if (inst.settings.fix_table_elements) {
var patt = '';
inst.focus();
inst.selection.setContent('<br class="_mce_marker" />');
tinymce.each('h1,h2,h3,h4,h5,h6,p'.split(','), function(n) {
if (patt)
patt += ',';
patt += n + ' ._mce_marker';
});
tinymce.each(inst.dom.select(patt), function(n) {
inst.dom.split(inst.dom.getParent(n, 'h1,h2,h3,h4,h5,h6,p'), n);
});
dom.setOuterHTML(dom.select('br._mce_marker')[0], html);
} else
inst.execCommand('mceInsertContent', false, html);
tinymce.each(dom.select('table[_mce_new]'), function(node) {
var td = dom.select('td', node);
inst.selection.select(td[0], true);
inst.selection.collapse();
dom.setAttrib(node, '_mce_new', '');
});
inst.addVisual();
inst.execCommand('mceEndUndoLevel');
tinyMCEPopup.close();
}
function makeAttrib(attrib, value) {
var formObj = document.forms[0];
var valueElm = formObj.elements[attrib];
if (typeof(value) == "undefined" || value == null) {
value = "";
if (valueElm)
value = valueElm.value;
}
if (value == "")
return "";
// XML encode it
value = value.replace(/&/g, '&');
value = value.replace(/\"/g, '"');
value = value.replace(/</g, '<');
value = value.replace(/>/g, '>');
return ' ' + attrib + '="' + value + '"';
}
function init() {
tinyMCEPopup.resizeToInnerSize();
document.getElementById('backgroundimagebrowsercontainer').innerHTML = getBrowserHTML('backgroundimagebrowser','backgroundimage','image','table');
document.getElementById('backgroundimagebrowsercontainer').innerHTML = getBrowserHTML('backgroundimagebrowser','backgroundimage','image','table');
document.getElementById('bordercolor_pickcontainer').innerHTML = getColorPickerHTML('bordercolor_pick','bordercolor');
document.getElementById('bgcolor_pickcontainer').innerHTML = getColorPickerHTML('bgcolor_pick','bgcolor');
var cols = 2, rows = 2, border = tinyMCEPopup.getParam('table_default_border', '0'), cellpadding = tinyMCEPopup.getParam('table_default_cellpadding', ''), cellspacing = tinyMCEPopup.getParam('table_default_cellspacing', '');
var align = "", width = "", height = "", bordercolor = "", bgcolor = "", className = "";
var id = "", summary = "", style = "", dir = "", lang = "", background = "", bgcolor = "", bordercolor = "", rules = "", frame = "";
var inst = tinyMCEPopup.editor, dom = inst.dom;
var formObj = document.forms[0];
var elm = dom.getParent(inst.selection.getNode(), "table");
action = tinyMCEPopup.getWindowArg('action');
if (!action)
action = elm ? "update" : "insert";
if (elm && action != "insert") {
var rowsAr = elm.rows;
var cols = 0;
for (var i=0; i<rowsAr.length; i++)
if (rowsAr[i].cells.length > cols)
cols = rowsAr[i].cells.length;
cols = cols;
rows = rowsAr.length;
st = dom.parseStyle(dom.getAttrib(elm, "style"));
border = trimSize(getStyle(elm, 'border', 'borderWidth'));
cellpadding = dom.getAttrib(elm, 'cellpadding', "");
cellspacing = dom.getAttrib(elm, 'cellspacing', "");
width = trimSize(getStyle(elm, 'width', 'width'));
height = trimSize(getStyle(elm, 'height', 'height'));
bordercolor = convertRGBToHex(getStyle(elm, 'bordercolor', 'borderLeftColor'));
bgcolor = convertRGBToHex(getStyle(elm, 'bgcolor', 'backgroundColor'));
align = dom.getAttrib(elm, 'align', align);
frame = dom.getAttrib(elm, 'frame');
rules = dom.getAttrib(elm, 'rules');
className = tinymce.trim(dom.getAttrib(elm, 'class').replace(/mceItem.+/g, ''));
id = dom.getAttrib(elm, 'id');
summary = dom.getAttrib(elm, 'summary');
style = dom.serializeStyle(st);
dir = dom.getAttrib(elm, 'dir');
lang = dom.getAttrib(elm, 'lang');
background = getStyle(elm, 'background', 'backgroundImage').replace(new RegExp("url\\(['\"]?([^'\"]*)['\"]?\\)", 'gi'), "$1");
formObj.caption.checked = elm.getElementsByTagName('caption').length > 0;
orgTableWidth = width;
orgTableHeight = height;
action = "update";
formObj.insert.value = inst.getLang('update');
}
addClassesToList('class', "table_styles");
TinyMCE_EditableSelects.init();
// Update form
selectByValue(formObj, 'align', align);
selectByValue(formObj, 'tframe', frame);
selectByValue(formObj, 'rules', rules);
selectByValue(formObj, 'class', className, true, true);
formObj.cols.value = cols;
formObj.rows.value = rows;
formObj.border.value = border;
formObj.cellpadding.value = cellpadding;
formObj.cellspacing.value = cellspacing;
formObj.width.value = width;
formObj.height.value = height;
formObj.bordercolor.value = bordercolor;
formObj.bgcolor.value = bgcolor;
formObj.id.value = id;
formObj.summary.value = summary;
formObj.style.value = style;
formObj.dir.value = dir;
formObj.lang.value = lang;
formObj.backgroundimage.value = background;
updateColor('bordercolor_pick', 'bordercolor');
updateColor('bgcolor_pick', 'bgcolor');
// Resize some elements
if (isVisible('backgroundimagebrowser'))
document.getElementById('backgroundimage').style.width = '180px';
// Disable some fields in update mode
if (action == "update") {
formObj.cols.disabled = true;
formObj.rows.disabled = true;
}
}
function changedSize() {
var formObj = document.forms[0];
var st = dom.parseStyle(formObj.style.value);
/* var width = formObj.width.value;
if (width != "")
st['width'] = tinyMCEPopup.getParam("inline_styles") ? getCSSSize(width) : "";
else
st['width'] = "";*/
var height = formObj.height.value;
if (height != "")
st['height'] = getCSSSize(height);
else
st['height'] = "";
formObj.style.value = dom.serializeStyle(st);
}
function changedBackgroundImage() {
var formObj = document.forms[0];
var st = dom.parseStyle(formObj.style.value);
st['background-image'] = "url('" + formObj.backgroundimage.value + "')";
formObj.style.value = dom.serializeStyle(st);
}
function changedBorder() {
var formObj = document.forms[0];
var st = dom.parseStyle(formObj.style.value);
// Update border width if the element has a color
if (formObj.border.value != "" && formObj.bordercolor.value != "")
st['border-width'] = formObj.border.value + "px";
formObj.style.value = dom.serializeStyle(st);
}
function changedColor() {
var formObj = document.forms[0];
var st = dom.parseStyle(formObj.style.value);
st['background-color'] = formObj.bgcolor.value;
if (formObj.bordercolor.value != "") {
st['border-color'] = formObj.bordercolor.value;
// Add border-width if it's missing
if (!st['border-width'])
st['border-width'] = formObj.border.value == "" ? "1px" : formObj.border.value + "px";
}
formObj.style.value = dom.serializeStyle(st);
}
function changedStyle() {
var formObj = document.forms[0];
var st = dom.parseStyle(formObj.style.value);
if (st['background-image'])
formObj.backgroundimage.value = st['background-image'].replace(new RegExp("url\\(['\"]?([^'\"]*)['\"]?\\)", 'gi'), "$1");
else
formObj.backgroundimage.value = '';
if (st['width'])
formObj.width.value = trimSize(st['width']);
if (st['height'])
formObj.height.value = trimSize(st['height']);
if (st['background-color']) {
formObj.bgcolor.value = st['background-color'];
updateColor('bgcolor_pick','bgcolor');
}
if (st['border-color']) {
formObj.bordercolor.value = st['border-color'];
updateColor('bordercolor_pick','bordercolor');
}
}
tinyMCEPopup.onInit.add(init);
| JavaScript |
tinyMCEPopup.requireLangPack();
var ed;
function init() {
ed = tinyMCEPopup.editor;
tinyMCEPopup.resizeToInnerSize();
document.getElementById('backgroundimagebrowsercontainer').innerHTML = getBrowserHTML('backgroundimagebrowser','backgroundimage','image','table');
document.getElementById('bordercolor_pickcontainer').innerHTML = getColorPickerHTML('bordercolor_pick','bordercolor');
document.getElementById('bgcolor_pickcontainer').innerHTML = getColorPickerHTML('bgcolor_pick','bgcolor')
var inst = ed;
var tdElm = ed.dom.getParent(ed.selection.getStart(), "td,th");
var formObj = document.forms[0];
var st = ed.dom.parseStyle(ed.dom.getAttrib(tdElm, "style"));
// Get table cell data
var celltype = tdElm.nodeName.toLowerCase();
var align = ed.dom.getAttrib(tdElm, 'align');
var valign = ed.dom.getAttrib(tdElm, 'valign');
var width = trimSize(getStyle(tdElm, 'width', 'width'));
var height = trimSize(getStyle(tdElm, 'height', 'height'));
var bordercolor = convertRGBToHex(getStyle(tdElm, 'bordercolor', 'borderLeftColor'));
var bgcolor = convertRGBToHex(getStyle(tdElm, 'bgcolor', 'backgroundColor'));
var className = ed.dom.getAttrib(tdElm, 'class');
var backgroundimage = getStyle(tdElm, 'background', 'backgroundImage').replace(new RegExp("url\\(['\"]?([^'\"]*)['\"]?\\)", 'gi'), "$1");
var id = ed.dom.getAttrib(tdElm, 'id');
var lang = ed.dom.getAttrib(tdElm, 'lang');
var dir = ed.dom.getAttrib(tdElm, 'dir');
var scope = ed.dom.getAttrib(tdElm, 'scope');
// Setup form
addClassesToList('class', 'table_cell_styles');
TinyMCE_EditableSelects.init();
if (!ed.dom.hasClass(tdElm, 'mceSelected')) {
formObj.bordercolor.value = bordercolor;
formObj.bgcolor.value = bgcolor;
formObj.backgroundimage.value = backgroundimage;
formObj.width.value = width;
formObj.height.value = height;
formObj.id.value = id;
formObj.lang.value = lang;
formObj.style.value = ed.dom.serializeStyle(st);
selectByValue(formObj, 'align', align);
selectByValue(formObj, 'valign', valign);
selectByValue(formObj, 'class', className, true, true);
selectByValue(formObj, 'celltype', celltype);
selectByValue(formObj, 'dir', dir);
selectByValue(formObj, 'scope', scope);
// Resize some elements
if (isVisible('backgroundimagebrowser'))
document.getElementById('backgroundimage').style.width = '180px';
updateColor('bordercolor_pick', 'bordercolor');
updateColor('bgcolor_pick', 'bgcolor');
} else
tinyMCEPopup.dom.hide('action');
}
function updateAction() {
var el, inst = ed, tdElm, trElm, tableElm, formObj = document.forms[0];
tinyMCEPopup.restoreSelection();
el = ed.selection.getStart();
tdElm = ed.dom.getParent(el, "td,th");
trElm = ed.dom.getParent(el, "tr");
tableElm = ed.dom.getParent(el, "table");
// Cell is selected
if (ed.dom.hasClass(tdElm, 'mceSelected')) {
// Update all selected sells
tinymce.each(ed.dom.select('td.mceSelected,th.mceSelected'), function(td) {
updateCell(td);
});
ed.addVisual();
ed.nodeChanged();
inst.execCommand('mceEndUndoLevel');
tinyMCEPopup.close();
return;
}
ed.execCommand('mceBeginUndoLevel');
switch (getSelectValue(formObj, 'action')) {
case "cell":
var celltype = getSelectValue(formObj, 'celltype');
var scope = getSelectValue(formObj, 'scope');
function doUpdate(s) {
if (s) {
updateCell(tdElm);
ed.addVisual();
ed.nodeChanged();
inst.execCommand('mceEndUndoLevel');
tinyMCEPopup.close();
}
};
if (ed.getParam("accessibility_warnings", 1)) {
if (celltype == "th" && scope == "")
tinyMCEPopup.confirm(ed.getLang('table_dlg.missing_scope', '', true), doUpdate);
else
doUpdate(1);
return;
}
updateCell(tdElm);
break;
case "row":
var cell = trElm.firstChild;
if (cell.nodeName != "TD" && cell.nodeName != "TH")
cell = nextCell(cell);
do {
cell = updateCell(cell, true);
} while ((cell = nextCell(cell)) != null);
break;
case "all":
var rows = tableElm.getElementsByTagName("tr");
for (var i=0; i<rows.length; i++) {
var cell = rows[i].firstChild;
if (cell.nodeName != "TD" && cell.nodeName != "TH")
cell = nextCell(cell);
do {
cell = updateCell(cell, true);
} while ((cell = nextCell(cell)) != null);
}
break;
}
ed.addVisual();
ed.nodeChanged();
inst.execCommand('mceEndUndoLevel');
tinyMCEPopup.close();
}
function nextCell(elm) {
while ((elm = elm.nextSibling) != null) {
if (elm.nodeName == "TD" || elm.nodeName == "TH")
return elm;
}
return null;
}
function updateCell(td, skip_id) {
var inst = ed;
var formObj = document.forms[0];
var curCellType = td.nodeName.toLowerCase();
var celltype = getSelectValue(formObj, 'celltype');
var doc = inst.getDoc();
var dom = ed.dom;
if (!skip_id)
td.setAttribute('id', formObj.id.value);
td.setAttribute('align', formObj.align.value);
td.setAttribute('vAlign', formObj.valign.value);
td.setAttribute('lang', formObj.lang.value);
td.setAttribute('dir', getSelectValue(formObj, 'dir'));
td.setAttribute('style', ed.dom.serializeStyle(ed.dom.parseStyle(formObj.style.value)));
td.setAttribute('scope', formObj.scope.value);
ed.dom.setAttrib(td, 'class', getSelectValue(formObj, 'class'));
// Clear deprecated attributes
ed.dom.setAttrib(td, 'width', '');
ed.dom.setAttrib(td, 'height', '');
ed.dom.setAttrib(td, 'bgColor', '');
ed.dom.setAttrib(td, 'borderColor', '');
ed.dom.setAttrib(td, 'background', '');
// Set styles
td.style.width = getCSSSize(formObj.width.value);
td.style.height = getCSSSize(formObj.height.value);
if (formObj.bordercolor.value != "") {
td.style.borderColor = formObj.bordercolor.value;
td.style.borderStyle = td.style.borderStyle == "" ? "solid" : td.style.borderStyle;
td.style.borderWidth = td.style.borderWidth == "" ? "1px" : td.style.borderWidth;
} else
td.style.borderColor = '';
td.style.backgroundColor = formObj.bgcolor.value;
if (formObj.backgroundimage.value != "")
td.style.backgroundImage = "url('" + formObj.backgroundimage.value + "')";
else
td.style.backgroundImage = '';
if (curCellType != celltype) {
// changing to a different node type
var newCell = doc.createElement(celltype);
for (var c=0; c<td.childNodes.length; c++)
newCell.appendChild(td.childNodes[c].cloneNode(1));
for (var a=0; a<td.attributes.length; a++)
ed.dom.setAttrib(newCell, td.attributes[a].name, ed.dom.getAttrib(td, td.attributes[a].name));
td.parentNode.replaceChild(newCell, td);
td = newCell;
}
dom.setAttrib(td, 'style', dom.serializeStyle(dom.parseStyle(td.style.cssText)));
return td;
}
function changedBackgroundImage() {
var formObj = document.forms[0];
var st = ed.dom.parseStyle(formObj.style.value);
st['background-image'] = "url('" + formObj.backgroundimage.value + "')";
formObj.style.value = ed.dom.serializeStyle(st);
}
function changedSize() {
var formObj = document.forms[0];
var st = ed.dom.parseStyle(formObj.style.value);
var width = formObj.width.value;
if (width != "")
st['width'] = getCSSSize(width);
else
st['width'] = "";
var height = formObj.height.value;
if (height != "")
st['height'] = getCSSSize(height);
else
st['height'] = "";
formObj.style.value = ed.dom.serializeStyle(st);
}
function changedColor() {
var formObj = document.forms[0];
var st = ed.dom.parseStyle(formObj.style.value);
st['background-color'] = formObj.bgcolor.value;
st['border-color'] = formObj.bordercolor.value;
formObj.style.value = ed.dom.serializeStyle(st);
}
function changedStyle() {
var formObj = document.forms[0];
var st = ed.dom.parseStyle(formObj.style.value);
if (st['background-image'])
formObj.backgroundimage.value = st['background-image'].replace(new RegExp("url\\('?([^']*)'?\\)", 'gi'), "$1");
else
formObj.backgroundimage.value = '';
if (st['width'])
formObj.width.value = trimSize(st['width']);
if (st['height'])
formObj.height.value = trimSize(st['height']);
if (st['background-color']) {
formObj.bgcolor.value = st['background-color'];
updateColor('bgcolor_pick','bgcolor');
}
if (st['border-color']) {
formObj.bordercolor.value = st['border-color'];
updateColor('bordercolor_pick','bordercolor');
}
}
tinyMCEPopup.onInit.add(init);
| JavaScript |
tinyMCEPopup.requireLangPack();
var MergeCellsDialog = {
init : function() {
var f = document.forms[0];
f.numcols.value = tinyMCEPopup.getWindowArg('cols', 1);
f.numrows.value = tinyMCEPopup.getWindowArg('rows', 1);
},
merge : function() {
var func, f = document.forms[0];
tinyMCEPopup.restoreSelection();
func = tinyMCEPopup.getWindowArg('onaction');
func({
cols : f.numcols.value,
rows : f.numrows.value
});
tinyMCEPopup.close();
}
};
tinyMCEPopup.onInit.add(MergeCellsDialog.init, MergeCellsDialog);
| JavaScript |
/**
* editor_plugin_src.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
(function(tinymce) {
var each = tinymce.each;
// Checks if the selection/caret is at the start of the specified block element
function isAtStart(rng, par) {
var doc = par.ownerDocument, rng2 = doc.createRange(), elm;
rng2.setStartBefore(par);
rng2.setEnd(rng.endContainer, rng.endOffset);
elm = doc.createElement('body');
elm.appendChild(rng2.cloneContents());
// Check for text characters of other elements that should be treated as content
return elm.innerHTML.replace(/<(br|img|object|embed|input|textarea)[^>]*>/gi, '-').replace(/<[^>]+>/g, '').length == 0;
};
/**
* Table Grid class.
*/
function TableGrid(table, dom, selection) {
var grid, startPos, endPos, selectedCell;
buildGrid();
selectedCell = dom.getParent(selection.getStart(), 'th,td');
if (selectedCell) {
startPos = getPos(selectedCell);
endPos = findEndPos();
selectedCell = getCell(startPos.x, startPos.y);
}
function cloneNode(node, children) {
node = node.cloneNode(children);
node.removeAttribute('id');
return node;
}
function buildGrid() {
var startY = 0;
grid = [];
each(['thead', 'tbody', 'tfoot'], function(part) {
var rows = dom.select('> ' + part + ' tr', table);
each(rows, function(tr, y) {
y += startY;
each(dom.select('> td, > th', tr), function(td, x) {
var x2, y2, rowspan, colspan;
// Skip over existing cells produced by rowspan
if (grid[y]) {
while (grid[y][x])
x++;
}
// Get col/rowspan from cell
rowspan = getSpanVal(td, 'rowspan');
colspan = getSpanVal(td, 'colspan');
// Fill out rowspan/colspan right and down
for (y2 = y; y2 < y + rowspan; y2++) {
if (!grid[y2])
grid[y2] = [];
for (x2 = x; x2 < x + colspan; x2++) {
grid[y2][x2] = {
part : part,
real : y2 == y && x2 == x,
elm : td,
rowspan : rowspan,
colspan : colspan
};
}
}
});
});
startY += rows.length;
});
};
function getCell(x, y) {
var row;
row = grid[y];
if (row)
return row[x];
};
function getSpanVal(td, name) {
return parseInt(td.getAttribute(name) || 1);
};
function isCellSelected(cell) {
return dom.hasClass(cell.elm, 'mceSelected') || cell == selectedCell;
};
function getSelectedRows() {
var rows = [];
each(table.rows, function(row) {
each(row.cells, function(cell) {
if (dom.hasClass(cell, 'mceSelected') || cell == selectedCell.elm) {
rows.push(row);
return false;
}
});
});
return rows;
};
function deleteTable() {
var rng = dom.createRng();
rng.setStartAfter(table);
rng.setEndAfter(table);
selection.setRng(rng);
dom.remove(table);
};
function cloneCell(cell) {
var formatNode;
// Clone formats
tinymce.walk(cell, function(node) {
var curNode;
if (node.nodeType == 3) {
each(dom.getParents(node.parentNode, null, cell).reverse(), function(node) {
node = cloneNode(node, false);
if (!formatNode)
formatNode = curNode = node;
else if (curNode)
curNode.appendChild(node);
curNode = node;
});
// Add something to the inner node
if (curNode)
curNode.innerHTML = tinymce.isIE ? ' ' : '<br _mce_bogus="1" />';
return false;
}
}, 'childNodes');
cell = cloneNode(cell, false);
cell.rowSpan = cell.colSpan = 1;
if (formatNode) {
cell.appendChild(formatNode);
} else {
if (!tinymce.isIE)
cell.innerHTML = '<br _mce_bogus="1" />';
}
return cell;
};
function cleanup() {
var rng = dom.createRng();
// Empty rows
each(dom.select('tr', table), function(tr) {
if (tr.cells.length == 0)
dom.remove(tr);
});
// Empty table
if (dom.select('tr', table).length == 0) {
rng.setStartAfter(table);
rng.setEndAfter(table);
selection.setRng(rng);
dom.remove(table);
return;
}
// Empty header/body/footer
each(dom.select('thead,tbody,tfoot', table), function(part) {
if (part.rows.length == 0)
dom.remove(part);
});
// Restore selection to start position if it still exists
buildGrid();
// Restore the selection to the closest table position
row = grid[Math.min(grid.length - 1, startPos.y)];
if (row) {
selection.select(row[Math.min(row.length - 1, startPos.x)].elm, true);
selection.collapse(true);
}
};
function fillLeftDown(x, y, rows, cols) {
var tr, x2, r, c, cell;
tr = grid[y][x].elm.parentNode;
for (r = 1; r <= rows; r++) {
tr = dom.getNext(tr, 'tr');
if (tr) {
// Loop left to find real cell
for (x2 = x; x2 >= 0; x2--) {
cell = grid[y + r][x2].elm;
if (cell.parentNode == tr) {
// Append clones after
for (c = 1; c <= cols; c++)
dom.insertAfter(cloneCell(cell), cell);
break;
}
}
if (x2 == -1) {
// Insert nodes before first cell
for (c = 1; c <= cols; c++)
tr.insertBefore(cloneCell(tr.cells[0]), tr.cells[0]);
}
}
}
};
function split() {
each(grid, function(row, y) {
each(row, function(cell, x) {
var colSpan, rowSpan, newCell, i;
if (isCellSelected(cell)) {
cell = cell.elm;
colSpan = getSpanVal(cell, 'colspan');
rowSpan = getSpanVal(cell, 'rowspan');
if (colSpan > 1 || rowSpan > 1) {
cell.colSpan = cell.rowSpan = 1;
// Insert cells right
for (i = 0; i < colSpan - 1; i++)
dom.insertAfter(cloneCell(cell), cell);
fillLeftDown(x, y, rowSpan - 1, colSpan);
}
}
});
});
};
function merge(cell, cols, rows) {
var startX, startY, endX, endY, x, y, startCell, endCell, cell, children;
// Use specified cell and cols/rows
if (cell) {
pos = getPos(cell);
startX = pos.x;
startY = pos.y;
endX = startX + (cols - 1);
endY = startY + (rows - 1);
} else {
// Use selection
startX = startPos.x;
startY = startPos.y;
endX = endPos.x;
endY = endPos.y;
}
// Find start/end cells
startCell = getCell(startX, startY);
endCell = getCell(endX, endY);
// Check if the cells exists and if they are of the same part for example tbody = tbody
if (startCell && endCell && startCell.part == endCell.part) {
// Split and rebuild grid
split();
buildGrid();
// Set row/col span to start cell
startCell = getCell(startX, startY).elm;
startCell.colSpan = (endX - startX) + 1;
startCell.rowSpan = (endY - startY) + 1;
// Remove other cells and add it's contents to the start cell
for (y = startY; y <= endY; y++) {
for (x = startX; x <= endX; x++) {
cell = grid[y][x].elm;
if (cell != startCell) {
// Move children to startCell
children = tinymce.grep(cell.childNodes);
each(children, function(node, i) {
// Jump over last BR element
if (node.nodeName != 'BR' || i != children.length - 1)
startCell.appendChild(node);
});
// Remove cell
dom.remove(cell);
}
}
}
// Remove empty rows etc and restore caret location
cleanup();
}
};
function insertRow(before) {
var posY, cell, lastCell, x, rowElm, newRow, newCell, otherCell;
// Find first/last row
each(grid, function(row, y) {
each(row, function(cell, x) {
if (isCellSelected(cell)) {
cell = cell.elm;
rowElm = cell.parentNode;
newRow = cloneNode(rowElm, false);
posY = y;
if (before)
return false;
}
});
if (before)
return !posY;
});
for (x = 0; x < grid[0].length; x++) {
cell = grid[posY][x].elm;
if (cell != lastCell) {
if (!before) {
rowSpan = getSpanVal(cell, 'rowspan');
if (rowSpan > 1) {
cell.rowSpan = rowSpan + 1;
continue;
}
} else {
// Check if cell above can be expanded
if (posY > 0 && grid[posY - 1][x]) {
otherCell = grid[posY - 1][x].elm;
rowSpan = getSpanVal(otherCell, 'rowspan');
if (rowSpan > 1) {
otherCell.rowSpan = rowSpan + 1;
continue;
}
}
}
// Insert new cell into new row
newCell = cloneCell(cell)
newCell.colSpan = cell.colSpan;
newRow.appendChild(newCell);
lastCell = cell;
}
}
if (newRow.hasChildNodes()) {
if (!before)
dom.insertAfter(newRow, rowElm);
else
rowElm.parentNode.insertBefore(newRow, rowElm);
}
};
function insertCol(before) {
var posX, lastCell;
// Find first/last column
each(grid, function(row, y) {
each(row, function(cell, x) {
if (isCellSelected(cell)) {
posX = x;
if (before)
return false;
}
});
if (before)
return !posX;
});
each(grid, function(row, y) {
var cell = row[posX].elm, rowSpan, colSpan;
if (cell != lastCell) {
colSpan = getSpanVal(cell, 'colspan');
rowSpan = getSpanVal(cell, 'rowspan');
if (colSpan == 1) {
if (!before) {
dom.insertAfter(cloneCell(cell), cell);
fillLeftDown(posX, y, rowSpan - 1, colSpan);
} else {
cell.parentNode.insertBefore(cloneCell(cell), cell);
fillLeftDown(posX, y, rowSpan - 1, colSpan);
}
} else
cell.colSpan++;
lastCell = cell;
}
});
};
function deleteCols() {
var cols = [];
// Get selected column indexes
each(grid, function(row, y) {
each(row, function(cell, x) {
if (isCellSelected(cell) && tinymce.inArray(cols, x) === -1) {
each(grid, function(row) {
var cell = row[x].elm, colSpan;
colSpan = getSpanVal(cell, 'colspan');
if (colSpan > 1)
cell.colSpan = colSpan - 1;
else
dom.remove(cell);
});
cols.push(x);
}
});
});
cleanup();
};
function deleteRows() {
var rows;
function deleteRow(tr) {
var nextTr, pos, lastCell;
nextTr = dom.getNext(tr, 'tr');
// Move down row spanned cells
each(tr.cells, function(cell) {
var rowSpan = getSpanVal(cell, 'rowspan');
if (rowSpan > 1) {
cell.rowSpan = rowSpan - 1;
pos = getPos(cell);
fillLeftDown(pos.x, pos.y, 1, 1);
}
});
// Delete cells
pos = getPos(tr.cells[0]);
each(grid[pos.y], function(cell) {
var rowSpan;
cell = cell.elm;
if (cell != lastCell) {
rowSpan = getSpanVal(cell, 'rowspan');
if (rowSpan <= 1)
dom.remove(cell);
else
cell.rowSpan = rowSpan - 1;
lastCell = cell;
}
});
};
// Get selected rows and move selection out of scope
rows = getSelectedRows();
// Delete all selected rows
each(rows.reverse(), function(tr) {
deleteRow(tr);
});
cleanup();
};
function cutRows() {
var rows = getSelectedRows();
dom.remove(rows);
cleanup();
return rows;
};
function copyRows() {
var rows = getSelectedRows();
each(rows, function(row, i) {
rows[i] = cloneNode(row, true);
});
return rows;
};
function pasteRows(rows, before) {
var selectedRows = getSelectedRows(),
targetRow = selectedRows[before ? 0 : selectedRows.length - 1],
targetCellCount = targetRow.cells.length;
// Calc target cell count
each(grid, function(row) {
var match;
targetCellCount = 0;
each(row, function(cell, x) {
if (cell.real)
targetCellCount += cell.colspan;
if (cell.elm.parentNode == targetRow)
match = 1;
});
if (match)
return false;
});
if (!before)
rows.reverse();
each(rows, function(row) {
var cellCount = row.cells.length, cell;
// Remove col/rowspans
for (i = 0; i < cellCount; i++) {
cell = row.cells[i];
cell.colSpan = cell.rowSpan = 1;
}
// Needs more cells
for (i = cellCount; i < targetCellCount; i++)
row.appendChild(cloneCell(row.cells[cellCount - 1]));
// Needs less cells
for (i = targetCellCount; i < cellCount; i++)
dom.remove(row.cells[i]);
// Add before/after
if (before)
targetRow.parentNode.insertBefore(row, targetRow);
else
dom.insertAfter(row, targetRow);
});
};
function getPos(target) {
var pos;
each(grid, function(row, y) {
each(row, function(cell, x) {
if (cell.elm == target) {
pos = {x : x, y : y};
return false;
}
});
return !pos;
});
return pos;
};
function setStartCell(cell) {
startPos = getPos(cell);
};
function findEndPos() {
var pos, maxX, maxY;
maxX = maxY = 0;
each(grid, function(row, y) {
each(row, function(cell, x) {
var colSpan, rowSpan;
if (isCellSelected(cell)) {
cell = grid[y][x];
if (x > maxX)
maxX = x;
if (y > maxY)
maxY = y;
if (cell.real) {
colSpan = cell.colspan - 1;
rowSpan = cell.rowspan - 1;
if (colSpan) {
if (x + colSpan > maxX)
maxX = x + colSpan;
}
if (rowSpan) {
if (y + rowSpan > maxY)
maxY = y + rowSpan;
}
}
}
});
});
return {x : maxX, y : maxY};
};
function setEndCell(cell) {
var startX, startY, endX, endY, maxX, maxY, colSpan, rowSpan;
endPos = getPos(cell);
if (startPos && endPos) {
// Get start/end positions
startX = Math.min(startPos.x, endPos.x);
startY = Math.min(startPos.y, endPos.y);
endX = Math.max(startPos.x, endPos.x);
endY = Math.max(startPos.y, endPos.y);
// Expand end positon to include spans
maxX = endX;
maxY = endY;
// Expand startX
for (y = startY; y <= maxY; y++) {
cell = grid[y][startX];
if (!cell.real) {
if (startX - (cell.colspan - 1) < startX)
startX -= cell.colspan - 1;
}
}
// Expand startY
for (x = startX; x <= maxX; x++) {
cell = grid[startY][x];
if (!cell.real) {
if (startY - (cell.rowspan - 1) < startY)
startY -= cell.rowspan - 1;
}
}
// Find max X, Y
for (y = startY; y <= endY; y++) {
for (x = startX; x <= endX; x++) {
cell = grid[y][x];
if (cell.real) {
colSpan = cell.colspan - 1;
rowSpan = cell.rowspan - 1;
if (colSpan) {
if (x + colSpan > maxX)
maxX = x + colSpan;
}
if (rowSpan) {
if (y + rowSpan > maxY)
maxY = y + rowSpan;
}
}
}
}
// Remove current selection
dom.removeClass(dom.select('td.mceSelected,th.mceSelected'), 'mceSelected');
// Add new selection
for (y = startY; y <= maxY; y++) {
for (x = startX; x <= maxX; x++)
dom.addClass(grid[y][x].elm, 'mceSelected');
}
}
};
// Expose to public
tinymce.extend(this, {
deleteTable : deleteTable,
split : split,
merge : merge,
insertRow : insertRow,
insertCol : insertCol,
deleteCols : deleteCols,
deleteRows : deleteRows,
cutRows : cutRows,
copyRows : copyRows,
pasteRows : pasteRows,
getPos : getPos,
setStartCell : setStartCell,
setEndCell : setEndCell
});
};
tinymce.create('tinymce.plugins.TablePlugin', {
init : function(ed, url) {
var winMan, clipboardRows;
function createTableGrid(node) {
var selection = ed.selection, tblElm = ed.dom.getParent(node || selection.getNode(), 'table');
if (tblElm)
return new TableGrid(tblElm, ed.dom, selection);
};
function cleanup() {
// Restore selection possibilities
ed.getBody().style.webkitUserSelect = '';
ed.dom.removeClass(ed.dom.select('td.mceSelected,th.mceSelected'), 'mceSelected');
};
// Register buttons
each([
['table', 'table.desc', 'mceInsertTable', true],
['delete_table', 'table.del', 'mceTableDelete'],
['delete_col', 'table.delete_col_desc', 'mceTableDeleteCol'],
['delete_row', 'table.delete_row_desc', 'mceTableDeleteRow'],
['col_after', 'table.col_after_desc', 'mceTableInsertColAfter'],
['col_before', 'table.col_before_desc', 'mceTableInsertColBefore'],
['row_after', 'table.row_after_desc', 'mceTableInsertRowAfter'],
['row_before', 'table.row_before_desc', 'mceTableInsertRowBefore'],
['row_props', 'table.row_desc', 'mceTableRowProps', true],
['cell_props', 'table.cell_desc', 'mceTableCellProps', true],
['split_cells', 'table.split_cells_desc', 'mceTableSplitCells', true],
['merge_cells', 'table.merge_cells_desc', 'mceTableMergeCells', true]
], function(c) {
ed.addButton(c[0], {title : c[1], cmd : c[2], ui : c[3]});
});
// Select whole table is a table border is clicked
if (!tinymce.isIE) {
ed.onClick.add(function(ed, e) {
e = e.target;
if (e.nodeName === 'TABLE')
ed.selection.select(e);
});
}
// Handle node change updates
ed.onNodeChange.add(function(ed, cm, n) {
var p;
n = ed.selection.getStart();
p = ed.dom.getParent(n, 'td,th,caption');
cm.setActive('table', n.nodeName === 'TABLE' || !!p);
// Disable table tools if we are in caption
if (p && p.nodeName === 'CAPTION')
p = 0;
cm.setDisabled('delete_table', !p);
cm.setDisabled('delete_col', !p);
cm.setDisabled('delete_table', !p);
cm.setDisabled('delete_row', !p);
cm.setDisabled('col_after', !p);
cm.setDisabled('col_before', !p);
cm.setDisabled('row_after', !p);
cm.setDisabled('row_before', !p);
cm.setDisabled('row_props', !p);
cm.setDisabled('cell_props', !p);
cm.setDisabled('split_cells', !p);
cm.setDisabled('merge_cells', !p);
});
ed.onInit.add(function(ed) {
var startTable, startCell, dom = ed.dom, tableGrid;
winMan = ed.windowManager;
// Add cell selection logic
ed.onMouseDown.add(function(ed, e) {
if (e.button != 2) {
cleanup();
startCell = dom.getParent(e.target, 'td,th');
startTable = dom.getParent(startCell, 'table');
}
});
dom.bind(ed.getDoc(), 'mouseover', function(e) {
var sel, table, target = e.target;
if (startCell && (tableGrid || target != startCell) && (target.nodeName == 'TD' || target.nodeName == 'TH')) {
table = dom.getParent(target, 'table');
if (table == startTable) {
if (!tableGrid) {
tableGrid = createTableGrid(table);
tableGrid.setStartCell(startCell);
ed.getBody().style.webkitUserSelect = 'none';
}
tableGrid.setEndCell(target);
}
// Remove current selection
sel = ed.selection.getSel();
if (sel.removeAllRanges)
sel.removeAllRanges();
else
sel.empty();
e.preventDefault();
}
});
ed.onMouseUp.add(function(ed, e) {
var rng, sel = ed.selection, selectedCells, nativeSel = sel.getSel(), walker, node, lastNode, endNode;
// Move selection to startCell
if (startCell) {
if (tableGrid)
ed.getBody().style.webkitUserSelect = '';
function setPoint(node, start) {
var walker = new tinymce.dom.TreeWalker(node, node);
do {
// Text node
if (node.nodeType == 3 && tinymce.trim(node.nodeValue).length != 0) {
if (start)
rng.setStart(node, 0);
else
rng.setEnd(node, node.nodeValue.length);
return;
}
// BR element
if (node.nodeName == 'BR') {
if (start)
rng.setStartBefore(node);
else
rng.setEndBefore(node);
return;
}
} while (node = (start ? walker.next() : walker.prev()));
};
// Try to expand text selection as much as we can only Gecko supports cell selection
selectedCells = dom.select('td.mceSelected,th.mceSelected');
if (selectedCells.length > 0) {
rng = dom.createRng();
node = selectedCells[0];
endNode = selectedCells[selectedCells.length - 1];
setPoint(node, 1);
walker = new tinymce.dom.TreeWalker(node, dom.getParent(selectedCells[0], 'table'));
do {
if (node.nodeName == 'TD' || node.nodeName == 'TH') {
if (!dom.hasClass(node, 'mceSelected'))
break;
lastNode = node;
}
} while (node = walker.next());
setPoint(lastNode);
sel.setRng(rng);
}
ed.nodeChanged();
startCell = tableGrid = startTable = null;
}
});
ed.onKeyUp.add(function(ed, e) {
cleanup();
});
// Add context menu
if (ed && ed.plugins.contextmenu) {
ed.plugins.contextmenu.onContextMenu.add(function(th, m, e) {
var sm, se = ed.selection, el = se.getNode() || ed.getBody();
if (ed.dom.getParent(e, 'td') || ed.dom.getParent(e, 'th') || ed.dom.select('td.mceSelected,th.mceSelected').length) {
m.removeAll();
if (el.nodeName == 'A' && !ed.dom.getAttrib(el, 'name')) {
m.add({title : 'advanced.link_desc', icon : 'link', cmd : ed.plugins.advlink ? 'mceAdvLink' : 'mceLink', ui : true});
m.add({title : 'advanced.unlink_desc', icon : 'unlink', cmd : 'UnLink'});
m.addSeparator();
}
if (el.nodeName == 'IMG' && el.className.indexOf('mceItem') == -1) {
m.add({title : 'advanced.image_desc', icon : 'image', cmd : ed.plugins.advimage ? 'mceAdvImage' : 'mceImage', ui : true});
m.addSeparator();
}
m.add({title : 'table.desc', icon : 'table', cmd : 'mceInsertTable', value : {action : 'insert'}});
m.add({title : 'table.props_desc', icon : 'table_props', cmd : 'mceInsertTable'});
m.add({title : 'table.del', icon : 'delete_table', cmd : 'mceTableDelete'});
m.addSeparator();
// Cell menu
sm = m.addMenu({title : 'table.cell'});
sm.add({title : 'table.cell_desc', icon : 'cell_props', cmd : 'mceTableCellProps'});
sm.add({title : 'table.split_cells_desc', icon : 'split_cells', cmd : 'mceTableSplitCells'});
sm.add({title : 'table.merge_cells_desc', icon : 'merge_cells', cmd : 'mceTableMergeCells'});
// Row menu
sm = m.addMenu({title : 'table.row'});
sm.add({title : 'table.row_desc', icon : 'row_props', cmd : 'mceTableRowProps'});
sm.add({title : 'table.row_before_desc', icon : 'row_before', cmd : 'mceTableInsertRowBefore'});
sm.add({title : 'table.row_after_desc', icon : 'row_after', cmd : 'mceTableInsertRowAfter'});
sm.add({title : 'table.delete_row_desc', icon : 'delete_row', cmd : 'mceTableDeleteRow'});
sm.addSeparator();
sm.add({title : 'table.cut_row_desc', icon : 'cut', cmd : 'mceTableCutRow'});
sm.add({title : 'table.copy_row_desc', icon : 'copy', cmd : 'mceTableCopyRow'});
sm.add({title : 'table.paste_row_before_desc', icon : 'paste', cmd : 'mceTablePasteRowBefore'}).setDisabled(!clipboardRows);
sm.add({title : 'table.paste_row_after_desc', icon : 'paste', cmd : 'mceTablePasteRowAfter'}).setDisabled(!clipboardRows);
// Column menu
sm = m.addMenu({title : 'table.col'});
sm.add({title : 'table.col_before_desc', icon : 'col_before', cmd : 'mceTableInsertColBefore'});
sm.add({title : 'table.col_after_desc', icon : 'col_after', cmd : 'mceTableInsertColAfter'});
sm.add({title : 'table.delete_col_desc', icon : 'delete_col', cmd : 'mceTableDeleteCol'});
} else
m.add({title : 'table.desc', icon : 'table', cmd : 'mceInsertTable'});
});
}
// Fixes an issue on Gecko where it's impossible to place the caret behind a table
// This fix will force a paragraph element after the table but only when the forced_root_block setting is enabled
if (!tinymce.isIE) {
function fixTableCaretPos() {
var last;
// Skip empty text nodes form the end
for (last = ed.getBody().lastChild; last && last.nodeType == 3 && !last.nodeValue.length; last = last.previousSibling) ;
if (last && last.nodeName == 'TABLE')
ed.dom.add(ed.getBody(), 'p', null, '<br mce_bogus="1" />');
};
// Fixes an bug where it's impossible to place the caret before a table in Gecko
// this fix solves it by detecting when the caret is at the beginning of such a table
// and then manually moves the caret infront of the table
if (tinymce.isGecko) {
ed.onKeyDown.add(function(ed, e) {
var rng, table, dom = ed.dom;
// On gecko it's not possible to place the caret before a table
if (e.keyCode == 37 || e.keyCode == 38) {
rng = ed.selection.getRng();
table = dom.getParent(rng.startContainer, 'table');
if (table && ed.getBody().firstChild == table) {
if (isAtStart(rng, table)) {
rng = dom.createRng();
rng.setStartBefore(table);
rng.setEndBefore(table);
ed.selection.setRng(rng);
e.preventDefault();
}
}
}
});
}
ed.onKeyUp.add(fixTableCaretPos);
ed.onSetContent.add(fixTableCaretPos);
ed.onVisualAid.add(fixTableCaretPos);
ed.onPreProcess.add(function(ed, o) {
var last = o.node.lastChild;
if (last && last.childNodes.length == 1 && last.firstChild.nodeName == 'BR')
ed.dom.remove(last);
});
fixTableCaretPos();
}
});
// Register action commands
each({
mceTableSplitCells : function(grid) {
grid.split();
},
mceTableMergeCells : function(grid) {
var rowSpan, colSpan, cell;
cell = ed.dom.getParent(ed.selection.getNode(), 'th,td');
if (cell) {
rowSpan = cell.rowSpan;
colSpan = cell.colSpan;
}
if (!ed.dom.select('td.mceSelected,th.mceSelected').length) {
winMan.open({
url : url + '/merge_cells.htm',
width : 240 + parseInt(ed.getLang('table.merge_cells_delta_width', 0)),
height : 110 + parseInt(ed.getLang('table.merge_cells_delta_height', 0)),
inline : 1
}, {
rows : rowSpan,
cols : colSpan,
onaction : function(data) {
grid.merge(cell, data.cols, data.rows);
},
plugin_url : url
});
} else
grid.merge();
},
mceTableInsertRowBefore : function(grid) {
grid.insertRow(true);
},
mceTableInsertRowAfter : function(grid) {
grid.insertRow();
},
mceTableInsertColBefore : function(grid) {
grid.insertCol(true);
},
mceTableInsertColAfter : function(grid) {
grid.insertCol();
},
mceTableDeleteCol : function(grid) {
grid.deleteCols();
},
mceTableDeleteRow : function(grid) {
grid.deleteRows();
},
mceTableCutRow : function(grid) {
clipboardRows = grid.cutRows();
},
mceTableCopyRow : function(grid) {
clipboardRows = grid.copyRows();
},
mceTablePasteRowBefore : function(grid) {
grid.pasteRows(clipboardRows, true);
},
mceTablePasteRowAfter : function(grid) {
grid.pasteRows(clipboardRows);
},
mceTableDelete : function(grid) {
grid.deleteTable();
}
}, function(func, name) {
ed.addCommand(name, function() {
var grid = createTableGrid();
if (grid) {
func(grid);
ed.execCommand('mceRepaint');
cleanup();
}
});
});
// Register dialog commands
each({
mceInsertTable : function(val) {
winMan.open({
url : url + '/table.htm',
width : 400 + parseInt(ed.getLang('table.table_delta_width', 0)),
height : 320 + parseInt(ed.getLang('table.table_delta_height', 0)),
inline : 1
}, {
plugin_url : url,
action : val ? val.action : 0
});
},
mceTableRowProps : function() {
winMan.open({
url : url + '/row.htm',
width : 400 + parseInt(ed.getLang('table.rowprops_delta_width', 0)),
height : 295 + parseInt(ed.getLang('table.rowprops_delta_height', 0)),
inline : 1
}, {
plugin_url : url
});
},
mceTableCellProps : function() {
winMan.open({
url : url + '/cell.htm',
width : 400 + parseInt(ed.getLang('table.cellprops_delta_width', 0)),
height : 295 + parseInt(ed.getLang('table.cellprops_delta_height', 0)),
inline : 1
}, {
plugin_url : url
});
}
}, function(func, name) {
ed.addCommand(name, function(ui, val) {
func(val);
});
});
}
});
// Register plugin
tinymce.PluginManager.add('table', tinymce.plugins.TablePlugin);
})(tinymce); | JavaScript |
tinyMCE.addI18n('en.table_dlg',{
general_tab:"General",
advanced_tab:"Advanced",
general_props:"General properties",
advanced_props:"Advanced properties",
rowtype:"Row in table part",
title:"Insert/Modify table",
width:"Width",
height:"Height",
cols:"Cols",
rows:"Rows",
cellspacing:"Cellspacing",
cellpadding:"Cellpadding",
border:"Border",
align:"Alignment",
align_default:"Default",
align_left:"Left",
align_right:"Right",
align_middle:"Center",
row_title:"Table row properties",
cell_title:"Table cell properties",
cell_type:"Cell type",
valign:"Vertical alignment",
align_top:"Top",
align_bottom:"Bottom",
bordercolor:"Border color",
bgcolor:"Background color",
merge_cells_title:"Merge table cells",
id:"Id",
style:"Style",
langdir:"Language direction",
langcode:"Language code",
mime:"Target MIME type",
ltr:"Left to right",
rtl:"Right to left",
bgimage:"Background image",
summary:"Summary",
td:"Data",
th:"Header",
cell_cell:"Update current cell",
cell_row:"Update all cells in row",
cell_all:"Update all cells in table",
row_row:"Update current row",
row_odd:"Update odd rows in table",
row_even:"Update even rows in table",
row_all:"Update all rows in table",
thead:"Table Head",
tbody:"Table Body",
tfoot:"Table Foot",
scope:"Scope",
rowgroup:"Row Group",
colgroup:"Col Group",
col_limit:"You've exceeded the maximum number of columns of {$cols}.",
row_limit:"You've exceeded the maximum number of rows of {$rows}.",
cell_limit:"You've exceeded the maximum number of cells of {$cells}.",
missing_scope:"Are you sure you want to continue without specifying a scope for this table header cell. Without it, it may be difficult for some users with disabilities to understand the content or data displayed of the table.",
caption:"Table caption",
frame:"Frame",
frame_none:"none",
frame_groups:"groups",
frame_rows:"rows",
frame_cols:"cols",
frame_all:"all",
rules:"Rules",
rules_void:"void",
rules_above:"above",
rules_below:"below",
rules_hsides:"hsides",
rules_lhs:"lhs",
rules_rhs:"rhs",
rules_vsides:"vsides",
rules_box:"box",
rules_border:"border"
}); | JavaScript |
tinyMCEPopup.requireLangPack();
var SearchReplaceDialog = {
init : function(ed) {
var f = document.forms[0], m = tinyMCEPopup.getWindowArg("mode");
this.switchMode(m);
f[m + '_panel_searchstring'].value = tinyMCEPopup.getWindowArg("search_string");
// Focus input field
f[m + '_panel_searchstring'].focus();
},
switchMode : function(m) {
var f, lm = this.lastMode;
if (lm != m) {
f = document.forms[0];
if (lm) {
f[m + '_panel_searchstring'].value = f[lm + '_panel_searchstring'].value;
f[m + '_panel_backwardsu'].checked = f[lm + '_panel_backwardsu'].checked;
f[m + '_panel_backwardsd'].checked = f[lm + '_panel_backwardsd'].checked;
f[m + '_panel_casesensitivebox'].checked = f[lm + '_panel_casesensitivebox'].checked;
}
mcTabs.displayTab(m + '_tab', m + '_panel');
document.getElementById("replaceBtn").style.display = (m == "replace") ? "inline" : "none";
document.getElementById("replaceAllBtn").style.display = (m == "replace") ? "inline" : "none";
this.lastMode = m;
}
},
searchNext : function(a) {
var ed = tinyMCEPopup.editor, se = ed.selection, r = se.getRng(), f, m = this.lastMode, s, b, fl = 0, w = ed.getWin(), wm = ed.windowManager, fo = 0;
// Get input
f = document.forms[0];
s = f[m + '_panel_searchstring'].value;
b = f[m + '_panel_backwardsu'].checked;
ca = f[m + '_panel_casesensitivebox'].checked;
rs = f['replace_panel_replacestring'].value;
if (s == '')
return;
function fix() {
// Correct Firefox graphics glitches
r = se.getRng().cloneRange();
ed.getDoc().execCommand('SelectAll', false, null);
se.setRng(r);
};
function replace() {
if (tinymce.isIE)
ed.selection.getRng().duplicate().pasteHTML(rs); // Needs to be duplicated due to selection bug in IE
else
ed.getDoc().execCommand('InsertHTML', false, rs);
};
// IE flags
if (ca)
fl = fl | 4;
switch (a) {
case 'all':
// Move caret to beginning of text
ed.execCommand('SelectAll');
ed.selection.collapse(true);
if (tinymce.isIE) {
while (r.findText(s, b ? -1 : 1, fl)) {
r.scrollIntoView();
r.select();
replace();
fo = 1;
if (b) {
r.moveEnd("character", -(rs.length)); // Otherwise will loop forever
}
}
tinyMCEPopup.storeSelection();
} else {
while (w.find(s, ca, b, false, false, false, false)) {
replace();
fo = 1;
}
}
if (fo)
tinyMCEPopup.alert(ed.getLang('searchreplace_dlg.allreplaced'));
else
tinyMCEPopup.alert(ed.getLang('searchreplace_dlg.notfound'));
return;
case 'current':
if (!ed.selection.isCollapsed())
replace();
break;
}
se.collapse(b);
r = se.getRng();
// Whats the point
if (!s)
return;
if (tinymce.isIE) {
if (r.findText(s, b ? -1 : 1, fl)) {
r.scrollIntoView();
r.select();
} else
tinyMCEPopup.alert(ed.getLang('searchreplace_dlg.notfound'));
tinyMCEPopup.storeSelection();
} else {
if (!w.find(s, ca, b, false, false, false, false))
tinyMCEPopup.alert(ed.getLang('searchreplace_dlg.notfound'));
else
fix();
}
}
};
tinyMCEPopup.onInit.add(SearchReplaceDialog.init, SearchReplaceDialog);
| JavaScript |
/**
* editor_plugin_src.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
(function() {
tinymce.create('tinymce.plugins.SearchReplacePlugin', {
init : function(ed, url) {
function open(m) {
ed.windowManager.open({
file : url + '/searchreplace.htm',
width : 420 + parseInt(ed.getLang('searchreplace.delta_width', 0)),
height : 170 + parseInt(ed.getLang('searchreplace.delta_height', 0)),
inline : 1,
auto_focus : 0
}, {
mode : m,
search_string : ed.selection.getContent({format : 'text'}),
plugin_url : url
});
};
// Register commands
ed.addCommand('mceSearch', function() {
open('search');
});
ed.addCommand('mceReplace', function() {
open('replace');
});
// Register buttons
ed.addButton('search', {title : 'searchreplace.search_desc', cmd : 'mceSearch'});
ed.addButton('replace', {title : 'searchreplace.replace_desc', cmd : 'mceReplace'});
ed.addShortcut('ctrl+f', 'searchreplace.search_desc', 'mceSearch');
},
getInfo : function() {
return {
longname : 'Search/Replace',
author : 'Moxiecode Systems AB',
authorurl : 'http://tinymce.moxiecode.com',
infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/searchreplace',
version : tinymce.majorVersion + "." + tinymce.minorVersion
};
}
});
// Register plugin
tinymce.PluginManager.add('searchreplace', tinymce.plugins.SearchReplacePlugin);
})(); | JavaScript |
tinyMCE.addI18n('en.searchreplace_dlg',{
searchnext_desc:"Find again",
notfound:"The search has been completed. The search string could not be found.",
search_title:"Find",
replace_title:"Find/Replace",
allreplaced:"All occurrences of the search string were replaced.",
findwhat:"Find what",
replacewith:"Replace with",
direction:"Direction",
up:"Up",
down:"Down",
mcase:"Match case",
findnext:"Find next",
replace:"Replace",
replaceall:"Replace all"
}); | JavaScript |
/**
* editor_plugin_src.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*
* Adds auto-save capability to the TinyMCE text editor to rescue content
* inadvertently lost. This plugin was originally developed by Speednet
* and that project can be found here: http://code.google.com/p/tinyautosave/
*
* TECHNOLOGY DISCUSSION:
*
* The plugin attempts to use the most advanced features available in the current browser to save
* as much content as possible. There are a total of four different methods used to autosave the
* content. In order of preference, they are:
*
* 1. localStorage - A new feature of HTML 5, localStorage can store megabytes of data per domain
* on the client computer. Data stored in the localStorage area has no expiration date, so we must
* manage expiring the data ourselves. localStorage is fully supported by IE8, and it is supposed
* to be working in Firefox 3 and Safari 3.2, but in reality is is flaky in those browsers. As
* HTML 5 gets wider support, the AutoSave plugin will use it automatically. In Windows Vista/7,
* localStorage is stored in the following folder:
* C:\Users\[username]\AppData\Local\Microsoft\Internet Explorer\DOMStore\[tempFolder]
*
* 2. sessionStorage - A new feature of HTML 5, sessionStorage works similarly to localStorage,
* except it is designed to expire after a certain amount of time. Because the specification
* around expiration date/time is very loosely-described, it is preferrable to use locaStorage and
* manage the expiration ourselves. sessionStorage has similar storage characteristics to
* localStorage, although it seems to have better support by Firefox 3 at the moment. (That will
* certainly change as Firefox continues getting better at HTML 5 adoption.)
*
* 3. UserData - A very under-exploited feature of Microsoft Internet Explorer, UserData is a
* way to store up to 128K of data per "document", or up to 1MB of data per domain, on the client
* computer. The feature is available for IE 5+, which makes it available for every version of IE
* supported by TinyMCE. The content is persistent across browser restarts and expires on the
* date/time specified, just like a cookie. However, the data is not cleared when the user clears
* cookies on the browser, which makes it well-suited for rescuing autosaved content. UserData,
* like other Microsoft IE browser technologies, is implemented as a behavior attached to a
* specific DOM object, so in this case we attach the behavior to the same DOM element that the
* TinyMCE editor instance is attached to.
*/
(function(tinymce) {
// Setup constants to help the compressor to reduce script size
var PLUGIN_NAME = 'autosave',
RESTORE_DRAFT = 'restoredraft',
TRUE = true,
undefined,
unloadHandlerAdded,
Dispatcher = tinymce.util.Dispatcher;
/**
* This plugin adds auto-save capability to the TinyMCE text editor to rescue content
* inadvertently lost. By using localStorage.
*
* @class tinymce.plugins.AutoSave
*/
tinymce.create('tinymce.plugins.AutoSave', {
/**
* Initializes the plugin, this will be executed after the plugin has been created.
* This call is done before the editor instance has finished it's initialization so use the onInit event
* of the editor instance to intercept that event.
*
* @method init
* @param {tinymce.Editor} ed Editor instance that the plugin is initialized in.
* @param {string} url Absolute URL to where the plugin is located.
*/
init : function(ed, url) {
var self = this, settings = ed.settings;
self.editor = ed;
// Parses the specified time string into a milisecond number 10m, 10s etc.
function parseTime(time) {
var multipels = {
s : 1000,
m : 60000
};
time = /^(\d+)([ms]?)$/.exec('' + time);
return (time[2] ? multipels[time[2]] : 1) * parseInt(time);
};
// Default config
tinymce.each({
ask_before_unload : TRUE,
interval : '30s',
retention : '20m',
minlength : 50
}, function(value, key) {
key = PLUGIN_NAME + '_' + key;
if (settings[key] === undefined)
settings[key] = value;
});
// Parse times
settings.autosave_interval = parseTime(settings.autosave_interval);
settings.autosave_retention = parseTime(settings.autosave_retention);
// Register restore button
ed.addButton(RESTORE_DRAFT, {
title : PLUGIN_NAME + ".restore_content",
onclick : function() {
if (ed.getContent({draft: true}).replace(/\s| |<\/?p[^>]*>|<br[^>]*>/gi, "").length > 0) {
// Show confirm dialog if the editor isn't empty
ed.windowManager.confirm(
PLUGIN_NAME + ".warning_message",
function(ok) {
if (ok)
self.restoreDraft();
}
);
} else
self.restoreDraft();
}
});
// Enable/disable restoredraft button depending on if there is a draft stored or not
ed.onNodeChange.add(function() {
var controlManager = ed.controlManager;
if (controlManager.get(RESTORE_DRAFT))
controlManager.setDisabled(RESTORE_DRAFT, !self.hasDraft());
});
ed.onInit.add(function() {
// Check if the user added the restore button, then setup auto storage logic
if (ed.controlManager.get(RESTORE_DRAFT)) {
// Setup storage engine
self.setupStorage(ed);
// Auto save contents each interval time
setInterval(function() {
self.storeDraft();
ed.nodeChanged();
}, settings.autosave_interval);
}
});
/**
* This event gets fired when a draft is stored to local storage.
*
* @event onStoreDraft
* @param {tinymce.plugins.AutoSave} sender Plugin instance sending the event.
* @param {Object} draft Draft object containing the HTML contents of the editor.
*/
self.onStoreDraft = new Dispatcher(self);
/**
* This event gets fired when a draft is restored from local storage.
*
* @event onStoreDraft
* @param {tinymce.plugins.AutoSave} sender Plugin instance sending the event.
* @param {Object} draft Draft object containing the HTML contents of the editor.
*/
self.onRestoreDraft = new Dispatcher(self);
/**
* This event gets fired when a draft removed/expired.
*
* @event onRemoveDraft
* @param {tinymce.plugins.AutoSave} sender Plugin instance sending the event.
* @param {Object} draft Draft object containing the HTML contents of the editor.
*/
self.onRemoveDraft = new Dispatcher(self);
// Add ask before unload dialog only add one unload handler
if (!unloadHandlerAdded) {
window.onbeforeunload = tinymce.plugins.AutoSave._beforeUnloadHandler;
unloadHandlerAdded = TRUE;
}
},
/**
* Returns information about the plugin as a name/value array.
* The current keys are longname, author, authorurl, infourl and version.
*
* @method getInfo
* @return {Object} Name/value array containing information about the plugin.
*/
getInfo : function() {
return {
longname : 'Auto save',
author : 'Moxiecode Systems AB',
authorurl : 'http://tinymce.moxiecode.com',
infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/autosave',
version : tinymce.majorVersion + "." + tinymce.minorVersion
};
},
/**
* Returns an expiration date UTC string.
*
* @method getExpDate
* @return {String} Expiration date UTC string.
*/
getExpDate : function() {
return new Date(
new Date().getTime() + this.editor.settings.autosave_retention
).toUTCString();
},
/**
* This method will setup the storage engine. If the browser has support for it.
*
* @method setupStorage
*/
setupStorage : function(ed) {
var self = this, testKey = PLUGIN_NAME + '_test', testVal = "OK";
self.key = PLUGIN_NAME + ed.id;
// Loop though each storage engine type until we find one that works
tinymce.each([
function() {
// Try HTML5 Local Storage
if (localStorage) {
localStorage.setItem(testKey, testVal);
if (localStorage.getItem(testKey) === testVal) {
localStorage.removeItem(testKey);
return localStorage;
}
}
},
function() {
// Try HTML5 Session Storage
if (sessionStorage) {
sessionStorage.setItem(testKey, testVal);
if (sessionStorage.getItem(testKey) === testVal) {
sessionStorage.removeItem(testKey);
return sessionStorage;
}
}
},
function() {
// Try IE userData
if (tinymce.isIE) {
ed.getElement().style.behavior = "url('#default#userData')";
// Fake localStorage on old IE
return {
autoExpires : TRUE,
setItem : function(key, value) {
var userDataElement = ed.getElement();
userDataElement.setAttribute(key, value);
userDataElement.expires = self.getExpDate();
userDataElement.save("TinyMCE");
},
getItem : function(key) {
var userDataElement = ed.getElement();
userDataElement.load("TinyMCE");
return userDataElement.getAttribute(key);
},
removeItem : function(key) {
ed.getElement().removeAttribute(key);
}
};
}
},
], function(setup) {
// Try executing each function to find a suitable storage engine
try {
self.storage = setup();
if (self.storage)
return false;
} catch (e) {
// Ignore
}
});
},
/**
* This method will store the current contents in the the storage engine.
*
* @method storeDraft
*/
storeDraft : function() {
var self = this, storage = self.storage, editor = self.editor, expires, content;
// Is the contents dirty
if (storage) {
// If there is no existing key and the contents hasn't been changed since
// it's original value then there is no point in saving a draft
if (!storage.getItem(self.key) && !editor.isDirty())
return;
// Store contents if the contents if longer than the minlength of characters
content = editor.getContent({draft: true});
if (content.length > editor.settings.autosave_minlength) {
expires = self.getExpDate();
// Store expiration date if needed IE userData has auto expire built in
if (!self.storage.autoExpires)
self.storage.setItem(self.key + "_expires", expires);
self.storage.setItem(self.key, content);
self.onStoreDraft.dispatch(self, {
expires : expires,
content : content
});
}
}
},
/**
* This method will restore the contents from the storage engine back to the editor.
*
* @method restoreDraft
*/
restoreDraft : function() {
var self = this, storage = self.storage;
if (storage) {
content = storage.getItem(self.key);
if (content) {
self.editor.setContent(content);
self.onRestoreDraft.dispatch(self, {
content : content
});
}
}
},
/**
* This method will return true/false if there is a local storage draft available.
*
* @method hasDraft
* @return {boolean} true/false state if there is a local draft.
*/
hasDraft : function() {
var self = this, storage = self.storage, expDate, exists;
if (storage) {
// Does the item exist at all
exists = !!storage.getItem(self.key);
if (exists) {
// Storage needs autoexpire
if (!self.storage.autoExpires) {
expDate = new Date(storage.getItem(self.key + "_expires"));
// Contents hasn't expired
if (new Date().getTime() < expDate.getTime())
return TRUE;
// Remove it if it has
self.removeDraft();
} else
return TRUE;
}
}
return false;
},
/**
* Removes the currently stored draft.
*
* @method removeDraft
*/
removeDraft : function() {
var self = this, storage = self.storage, key = self.key, content;
if (storage) {
// Get current contents and remove the existing draft
content = storage.getItem(key);
storage.removeItem(key);
storage.removeItem(key + "_expires");
// Dispatch remove event if we had any contents
if (content) {
self.onRemoveDraft.dispatch(self, {
content : content
});
}
}
},
"static" : {
// Internal unload handler will be called before the page is unloaded
_beforeUnloadHandler : function(e) {
var msg;
tinymce.each(tinyMCE.editors, function(ed) {
// Store a draft for each editor instance
if (ed.plugins.autosave)
ed.plugins.autosave.storeDraft();
// Never ask in fullscreen mode
if (ed.getParam("fullscreen_is_enabled"))
return;
// Setup a return message if the editor is dirty
if (!msg && ed.isDirty() && ed.getParam("autosave_ask_before_unload"))
msg = ed.getLang("autosave.unload_msg");
});
return msg;
}
}
});
tinymce.PluginManager.add('autosave', tinymce.plugins.AutoSave);
})(tinymce);
| JavaScript |
tinyMCE.addI18n('en.autosave',{
restore_content: "Restore auto-saved content",
warning_message: "If you restore the saved content, you will lose all the content that is currently in the editor.\n\nAre you sure you want to restore the saved content?"
}); | JavaScript |
tinyMCE.addI18n({en:{
common:{
edit_confirm:"Do you want to use the WYSIWYG mode for this textarea?",
apply:"Apply",
insert:"Insert",
update:"Update",
cancel:"Cancel",
close:"Close",
browse:"Browse",
class_name:"Class",
not_set:"-- Not set --",
clipboard_msg:"Copy/Cut/Paste is not available in Mozilla and Firefox.\nDo you want more information about this issue?",
clipboard_no_support:"Currently not supported by your browser, use keyboard shortcuts instead.",
popup_blocked:"Sorry, but we have noticed that your popup-blocker has disabled a window that provides application functionality. You will need to disable popup blocking on this site in order to fully utilize this tool.",
invalid_data:"Error: Invalid values entered, these are marked in red.",
more_colors:"More colors"
},
contextmenu:{
align:"Alignment",
left:"Left",
center:"Center",
right:"Right",
full:"Full"
},
insertdatetime:{
date_fmt:"%Y-%m-%d",
time_fmt:"%H:%M:%S",
insertdate_desc:"Insert date",
inserttime_desc:"Insert time",
months_long:"January,February,March,April,May,June,July,August,September,October,November,December",
months_short:"Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec",
day_long:"Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday",
day_short:"Sun,Mon,Tue,Wed,Thu,Fri,Sat,Sun"
},
print:{
print_desc:"Print"
},
preview:{
preview_desc:"Preview"
},
directionality:{
ltr_desc:"Direction left to right",
rtl_desc:"Direction right to left"
},
layer:{
insertlayer_desc:"Insert new layer",
forward_desc:"Move forward",
backward_desc:"Move backward",
absolute_desc:"Toggle absolute positioning",
content:"New layer..."
},
save:{
save_desc:"Save",
cancel_desc:"Cancel all changes"
},
nonbreaking:{
nonbreaking_desc:"Insert non-breaking space character"
},
iespell:{
iespell_desc:"Run spell checking",
download:"ieSpell not detected. Do you want to install it now?"
},
advhr:{
advhr_desc:"Horizontal rule"
},
emotions:{
emotions_desc:"Emotions"
},
searchreplace:{
search_desc:"Find",
replace_desc:"Find/Replace"
},
advimage:{
image_desc:"Insert/edit image"
},
advlink:{
link_desc:"Insert/edit link"
},
xhtmlxtras:{
cite_desc:"Citation",
abbr_desc:"Abbreviation",
acronym_desc:"Acronym",
del_desc:"Deletion",
ins_desc:"Insertion",
attribs_desc:"Insert/Edit Attributes"
},
style:{
desc:"Edit CSS Style"
},
paste:{
paste_text_desc:"Paste as Plain Text",
paste_word_desc:"Paste from Word",
selectall_desc:"Select All",
plaintext_mode_sticky:"Paste is now in plain text mode. Click again to toggle back to regular paste mode. After you paste something you will be returned to regular paste mode.",
plaintext_mode:"Paste is now in plain text mode. Click again to toggle back to regular paste mode."
},
paste_dlg:{
text_title:"Use CTRL+V on your keyboard to paste the text into the window.",
text_linebreaks:"Keep linebreaks",
word_title:"Use CTRL+V on your keyboard to paste the text into the window."
},
table:{
desc:"Inserts a new table",
row_before_desc:"Insert row before",
row_after_desc:"Insert row after",
delete_row_desc:"Delete row",
col_before_desc:"Insert column before",
col_after_desc:"Insert column after",
delete_col_desc:"Remove column",
split_cells_desc:"Split merged table cells",
merge_cells_desc:"Merge table cells",
row_desc:"Table row properties",
cell_desc:"Table cell properties",
props_desc:"Table properties",
paste_row_before_desc:"Paste table row before",
paste_row_after_desc:"Paste table row after",
cut_row_desc:"Cut table row",
copy_row_desc:"Copy table row",
del:"Delete table",
row:"Row",
col:"Column",
cell:"Cell"
},
autosave:{
unload_msg:"The changes you made will be lost if you navigate away from this page.",
restore_content:"Restore auto-saved content.",
warning_message:"If you restore the saved content, you will lose all the content that is currently in the editor.\n\nAre you sure you want to restore the saved content?."
},
fullscreen:{
desc:"Toggle fullscreen mode"
},
media:{
desc:"Insert / edit embedded media",
edit:"Edit embedded media"
},
fullpage:{
desc:"Document properties"
},
template:{
desc:"Insert predefined template content"
},
visualchars:{
desc:"Visual control characters on/off."
},
spellchecker:{
desc:"Toggle spellchecker",
menu:"Spellchecker settings",
ignore_word:"Ignore word",
ignore_words:"Ignore all",
langs:"Languages",
wait:"Please wait...",
sug:"Suggestions",
no_sug:"No suggestions",
no_mpell:"No misspellings found."
},
pagebreak:{
desc:"Insert page break."
},
advlist:{
types:"Types",
def:"Default",
lower_alpha:"Lower alpha",
lower_greek:"Lower greek",
lower_roman:"Lower roman",
upper_alpha:"Upper alpha",
upper_roman:"Upper roman",
circle:"Circle",
disc:"Disc",
square:"Square"
}}}); | JavaScript |
tinyMCEPopup.requireLangPack();
tinyMCEPopup.onInit.add(onLoadInit);
function saveContent() {
tinyMCEPopup.editor.setContent(document.getElementById('htmlSource').value, {source_view : true});
tinyMCEPopup.close();
}
function onLoadInit() {
tinyMCEPopup.resizeToInnerSize();
// Remove Gecko spellchecking
if (tinymce.isGecko)
document.body.spellcheck = tinyMCEPopup.editor.getParam("gecko_spellcheck");
document.getElementById('htmlSource').value = tinyMCEPopup.editor.getContent({source_view : true});
if (tinyMCEPopup.editor.getParam("theme_advanced_source_editor_wrap", true)) {
setWrap('soft');
document.getElementById('wraped').checked = true;
}
resizeInputs();
}
function setWrap(val) {
var v, n, s = document.getElementById('htmlSource');
s.wrap = val;
if (!tinymce.isIE) {
v = s.value;
n = s.cloneNode(false);
n.setAttribute("wrap", val);
s.parentNode.replaceChild(n, s);
n.value = v;
}
}
function toggleWordWrap(elm) {
if (elm.checked)
setWrap('soft');
else
setWrap('off');
}
var wHeight=0, wWidth=0, owHeight=0, owWidth=0;
function resizeInputs() {
var el = document.getElementById('htmlSource');
if (!tinymce.isIE) {
wHeight = self.innerHeight - 65;
wWidth = self.innerWidth - 16;
} else {
wHeight = document.body.clientHeight - 70;
wWidth = document.body.clientWidth - 16;
}
el.style.height = Math.abs(wHeight) + 'px';
el.style.width = Math.abs(wWidth) + 'px';
}
| JavaScript |
/**
* charmap.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
tinyMCEPopup.requireLangPack();
var charmap = [
[' ', ' ', true, 'no-break space'],
['&', '&', true, 'ampersand'],
['"', '"', true, 'quotation mark'],
// finance
['¢', '¢', true, 'cent sign'],
['€', '€', true, 'euro sign'],
['£', '£', true, 'pound sign'],
['¥', '¥', true, 'yen sign'],
// signs
['©', '©', true, 'copyright sign'],
['®', '®', true, 'registered sign'],
['™', '™', true, 'trade mark sign'],
['‰', '‰', true, 'per mille sign'],
['µ', 'µ', true, 'micro sign'],
['·', '·', true, 'middle dot'],
['•', '•', true, 'bullet'],
['…', '…', true, 'three dot leader'],
['′', '′', true, 'minutes / feet'],
['″', '″', true, 'seconds / inches'],
['§', '§', true, 'section sign'],
['¶', '¶', true, 'paragraph sign'],
['ß', 'ß', true, 'sharp s / ess-zed'],
// quotations
['‹', '‹', true, 'single left-pointing angle quotation mark'],
['›', '›', true, 'single right-pointing angle quotation mark'],
['«', '«', true, 'left pointing guillemet'],
['»', '»', true, 'right pointing guillemet'],
['‘', '‘', true, 'left single quotation mark'],
['’', '’', true, 'right single quotation mark'],
['“', '“', true, 'left double quotation mark'],
['”', '”', true, 'right double quotation mark'],
['‚', '‚', true, 'single low-9 quotation mark'],
['„', '„', true, 'double low-9 quotation mark'],
['<', '<', true, 'less-than sign'],
['>', '>', true, 'greater-than sign'],
['≤', '≤', true, 'less-than or equal to'],
['≥', '≥', true, 'greater-than or equal to'],
['–', '–', true, 'en dash'],
['—', '—', true, 'em dash'],
['¯', '¯', true, 'macron'],
['‾', '‾', true, 'overline'],
['¤', '¤', true, 'currency sign'],
['¦', '¦', true, 'broken bar'],
['¨', '¨', true, 'diaeresis'],
['¡', '¡', true, 'inverted exclamation mark'],
['¿', '¿', true, 'turned question mark'],
['ˆ', 'ˆ', true, 'circumflex accent'],
['˜', '˜', true, 'small tilde'],
['°', '°', true, 'degree sign'],
['−', '−', true, 'minus sign'],
['±', '±', true, 'plus-minus sign'],
['÷', '÷', true, 'division sign'],
['⁄', '⁄', true, 'fraction slash'],
['×', '×', true, 'multiplication sign'],
['¹', '¹', true, 'superscript one'],
['²', '²', true, 'superscript two'],
['³', '³', true, 'superscript three'],
['¼', '¼', true, 'fraction one quarter'],
['½', '½', true, 'fraction one half'],
['¾', '¾', true, 'fraction three quarters'],
// math / logical
['ƒ', 'ƒ', true, 'function / florin'],
['∫', '∫', true, 'integral'],
['∑', '∑', true, 'n-ary sumation'],
['∞', '∞', true, 'infinity'],
['√', '√', true, 'square root'],
['∼', '∼', false,'similar to'],
['≅', '≅', false,'approximately equal to'],
['≈', '≈', true, 'almost equal to'],
['≠', '≠', true, 'not equal to'],
['≡', '≡', true, 'identical to'],
['∈', '∈', false,'element of'],
['∉', '∉', false,'not an element of'],
['∋', '∋', false,'contains as member'],
['∏', '∏', true, 'n-ary product'],
['∧', '∧', false,'logical and'],
['∨', '∨', false,'logical or'],
['¬', '¬', true, 'not sign'],
['∩', '∩', true, 'intersection'],
['∪', '∪', false,'union'],
['∂', '∂', true, 'partial differential'],
['∀', '∀', false,'for all'],
['∃', '∃', false,'there exists'],
['∅', '∅', false,'diameter'],
['∇', '∇', false,'backward difference'],
['∗', '∗', false,'asterisk operator'],
['∝', '∝', false,'proportional to'],
['∠', '∠', false,'angle'],
// undefined
['´', '´', true, 'acute accent'],
['¸', '¸', true, 'cedilla'],
['ª', 'ª', true, 'feminine ordinal indicator'],
['º', 'º', true, 'masculine ordinal indicator'],
['†', '†', true, 'dagger'],
['‡', '‡', true, 'double dagger'],
// alphabetical special chars
['À', 'À', true, 'A - grave'],
['Á', 'Á', true, 'A - acute'],
['Â', 'Â', true, 'A - circumflex'],
['Ã', 'Ã', true, 'A - tilde'],
['Ä', 'Ä', true, 'A - diaeresis'],
['Å', 'Å', true, 'A - ring above'],
['Æ', 'Æ', true, 'ligature AE'],
['Ç', 'Ç', true, 'C - cedilla'],
['È', 'È', true, 'E - grave'],
['É', 'É', true, 'E - acute'],
['Ê', 'Ê', true, 'E - circumflex'],
['Ë', 'Ë', true, 'E - diaeresis'],
['Ì', 'Ì', true, 'I - grave'],
['Í', 'Í', true, 'I - acute'],
['Î', 'Î', true, 'I - circumflex'],
['Ï', 'Ï', true, 'I - diaeresis'],
['Ð', 'Ð', true, 'ETH'],
['Ñ', 'Ñ', true, 'N - tilde'],
['Ò', 'Ò', true, 'O - grave'],
['Ó', 'Ó', true, 'O - acute'],
['Ô', 'Ô', true, 'O - circumflex'],
['Õ', 'Õ', true, 'O - tilde'],
['Ö', 'Ö', true, 'O - diaeresis'],
['Ø', 'Ø', true, 'O - slash'],
['Œ', 'Œ', true, 'ligature OE'],
['Š', 'Š', true, 'S - caron'],
['Ù', 'Ù', true, 'U - grave'],
['Ú', 'Ú', true, 'U - acute'],
['Û', 'Û', true, 'U - circumflex'],
['Ü', 'Ü', true, 'U - diaeresis'],
['Ý', 'Ý', true, 'Y - acute'],
['Ÿ', 'Ÿ', true, 'Y - diaeresis'],
['Þ', 'Þ', true, 'THORN'],
['à', 'à', true, 'a - grave'],
['á', 'á', true, 'a - acute'],
['â', 'â', true, 'a - circumflex'],
['ã', 'ã', true, 'a - tilde'],
['ä', 'ä', true, 'a - diaeresis'],
['å', 'å', true, 'a - ring above'],
['æ', 'æ', true, 'ligature ae'],
['ç', 'ç', true, 'c - cedilla'],
['è', 'è', true, 'e - grave'],
['é', 'é', true, 'e - acute'],
['ê', 'ê', true, 'e - circumflex'],
['ë', 'ë', true, 'e - diaeresis'],
['ì', 'ì', true, 'i - grave'],
['í', 'í', true, 'i - acute'],
['î', 'î', true, 'i - circumflex'],
['ï', 'ï', true, 'i - diaeresis'],
['ð', 'ð', true, 'eth'],
['ñ', 'ñ', true, 'n - tilde'],
['ò', 'ò', true, 'o - grave'],
['ó', 'ó', true, 'o - acute'],
['ô', 'ô', true, 'o - circumflex'],
['õ', 'õ', true, 'o - tilde'],
['ö', 'ö', true, 'o - diaeresis'],
['ø', 'ø', true, 'o slash'],
['œ', 'œ', true, 'ligature oe'],
['š', 'š', true, 's - caron'],
['ù', 'ù', true, 'u - grave'],
['ú', 'ú', true, 'u - acute'],
['û', 'û', true, 'u - circumflex'],
['ü', 'ü', true, 'u - diaeresis'],
['ý', 'ý', true, 'y - acute'],
['þ', 'þ', true, 'thorn'],
['ÿ', 'ÿ', true, 'y - diaeresis'],
['Α', 'Α', true, 'Alpha'],
['Β', 'Β', true, 'Beta'],
['Γ', 'Γ', true, 'Gamma'],
['Δ', 'Δ', true, 'Delta'],
['Ε', 'Ε', true, 'Epsilon'],
['Ζ', 'Ζ', true, 'Zeta'],
['Η', 'Η', true, 'Eta'],
['Θ', 'Θ', true, 'Theta'],
['Ι', 'Ι', true, 'Iota'],
['Κ', 'Κ', true, 'Kappa'],
['Λ', 'Λ', true, 'Lambda'],
['Μ', 'Μ', true, 'Mu'],
['Ν', 'Ν', true, 'Nu'],
['Ξ', 'Ξ', true, 'Xi'],
['Ο', 'Ο', true, 'Omicron'],
['Π', 'Π', true, 'Pi'],
['Ρ', 'Ρ', true, 'Rho'],
['Σ', 'Σ', true, 'Sigma'],
['Τ', 'Τ', true, 'Tau'],
['Υ', 'Υ', true, 'Upsilon'],
['Φ', 'Φ', true, 'Phi'],
['Χ', 'Χ', true, 'Chi'],
['Ψ', 'Ψ', true, 'Psi'],
['Ω', 'Ω', true, 'Omega'],
['α', 'α', true, 'alpha'],
['β', 'β', true, 'beta'],
['γ', 'γ', true, 'gamma'],
['δ', 'δ', true, 'delta'],
['ε', 'ε', true, 'epsilon'],
['ζ', 'ζ', true, 'zeta'],
['η', 'η', true, 'eta'],
['θ', 'θ', true, 'theta'],
['ι', 'ι', true, 'iota'],
['κ', 'κ', true, 'kappa'],
['λ', 'λ', true, 'lambda'],
['μ', 'μ', true, 'mu'],
['ν', 'ν', true, 'nu'],
['ξ', 'ξ', true, 'xi'],
['ο', 'ο', true, 'omicron'],
['π', 'π', true, 'pi'],
['ρ', 'ρ', true, 'rho'],
['ς', 'ς', true, 'final sigma'],
['σ', 'σ', true, 'sigma'],
['τ', 'τ', true, 'tau'],
['υ', 'υ', true, 'upsilon'],
['φ', 'φ', true, 'phi'],
['χ', 'χ', true, 'chi'],
['ψ', 'ψ', true, 'psi'],
['ω', 'ω', true, 'omega'],
// symbols
['ℵ', 'ℵ', false,'alef symbol'],
['ϖ', 'ϖ', false,'pi symbol'],
['ℜ', 'ℜ', false,'real part symbol'],
['ϑ','ϑ', false,'theta symbol'],
['ϒ', 'ϒ', false,'upsilon - hook symbol'],
['℘', '℘', false,'Weierstrass p'],
['ℑ', 'ℑ', false,'imaginary part'],
// arrows
['←', '←', true, 'leftwards arrow'],
['↑', '↑', true, 'upwards arrow'],
['→', '→', true, 'rightwards arrow'],
['↓', '↓', true, 'downwards arrow'],
['↔', '↔', true, 'left right arrow'],
['↵', '↵', false,'carriage return'],
['⇐', '⇐', false,'leftwards double arrow'],
['⇑', '⇑', false,'upwards double arrow'],
['⇒', '⇒', false,'rightwards double arrow'],
['⇓', '⇓', false,'downwards double arrow'],
['⇔', '⇔', false,'left right double arrow'],
['∴', '∴', false,'therefore'],
['⊂', '⊂', false,'subset of'],
['⊃', '⊃', false,'superset of'],
['⊄', '⊄', false,'not a subset of'],
['⊆', '⊆', false,'subset of or equal to'],
['⊇', '⊇', false,'superset of or equal to'],
['⊕', '⊕', false,'circled plus'],
['⊗', '⊗', false,'circled times'],
['⊥', '⊥', false,'perpendicular'],
['⋅', '⋅', false,'dot operator'],
['⌈', '⌈', false,'left ceiling'],
['⌉', '⌉', false,'right ceiling'],
['⌊', '⌊', false,'left floor'],
['⌋', '⌋', false,'right floor'],
['⟨', '〈', false,'left-pointing angle bracket'],
['⟩', '〉', false,'right-pointing angle bracket'],
['◊', '◊', true,'lozenge'],
['♠', '♠', false,'black spade suit'],
['♣', '♣', true, 'black club suit'],
['♥', '♥', true, 'black heart suit'],
['♦', '♦', true, 'black diamond suit'],
[' ', ' ', false,'en space'],
[' ', ' ', false,'em space'],
[' ', ' ', false,'thin space'],
['‌', '‌', false,'zero width non-joiner'],
['‍', '‍', false,'zero width joiner'],
['‎', '‎', false,'left-to-right mark'],
['‏', '‏', false,'right-to-left mark'],
['­', '­', false,'soft hyphen']
];
tinyMCEPopup.onInit.add(function() {
tinyMCEPopup.dom.setHTML('charmapView', renderCharMapHTML());
});
function renderCharMapHTML() {
var charsPerRow = 20, tdWidth=20, tdHeight=20, i;
var html = '<table border="0" cellspacing="1" cellpadding="0" width="' + (tdWidth*charsPerRow) + '"><tr height="' + tdHeight + '">';
var cols=-1;
for (i=0; i<charmap.length; i++) {
if (charmap[i][2]==true) {
cols++;
html += ''
+ '<td class="charmap">'
+ '<a onmouseover="previewChar(\'' + charmap[i][1].substring(1,charmap[i][1].length) + '\',\'' + charmap[i][0].substring(1,charmap[i][0].length) + '\',\'' + charmap[i][3] + '\');" onfocus="previewChar(\'' + charmap[i][1].substring(1,charmap[i][1].length) + '\',\'' + charmap[i][0].substring(1,charmap[i][0].length) + '\',\'' + charmap[i][3] + '\');" href="javascript:void(0)" onclick="insertChar(\'' + charmap[i][1].substring(2,charmap[i][1].length-1) + '\');" onclick="return false;" onmousedown="return false;" title="' + charmap[i][3] + '">'
+ charmap[i][1]
+ '</a></td>';
if ((cols+1) % charsPerRow == 0)
html += '</tr><tr height="' + tdHeight + '">';
}
}
if (cols % charsPerRow > 0) {
var padd = charsPerRow - (cols % charsPerRow);
for (var i=0; i<padd-1; i++)
html += '<td width="' + tdWidth + '" height="' + tdHeight + '" class="charmap"> </td>';
}
html += '</tr></table>';
return html;
}
function insertChar(chr) {
tinyMCEPopup.execCommand('mceInsertContent', false, '&#' + chr + ';');
// Refocus in window
if (tinyMCEPopup.isWindow)
window.focus();
tinyMCEPopup.editor.focus();
tinyMCEPopup.close();
}
function previewChar(codeA, codeB, codeN) {
var elmA = document.getElementById('codeA');
var elmB = document.getElementById('codeB');
var elmV = document.getElementById('codeV');
var elmN = document.getElementById('codeN');
if (codeA=='#160;') {
elmV.innerHTML = '__';
} else {
elmV.innerHTML = '&' + codeA;
}
elmB.innerHTML = '&' + codeA;
elmA.innerHTML = '&' + codeB;
elmN.innerHTML = codeN;
}
| JavaScript |
tinyMCEPopup.requireLangPack();
var AnchorDialog = {
init : function(ed) {
var action, elm, f = document.forms[0];
this.editor = ed;
elm = ed.dom.getParent(ed.selection.getNode(), 'A');
v = ed.dom.getAttrib(elm, 'name');
if (v) {
this.action = 'update';
f.anchorName.value = v;
}
f.insert.value = ed.getLang(elm ? 'update' : 'insert');
},
update : function() {
var ed = this.editor, elm, name = document.forms[0].anchorName.value;
tinyMCEPopup.restoreSelection();
if (this.action != 'update')
ed.selection.collapse(1);
elm = ed.dom.getParent(ed.selection.getNode(), 'A');
if (elm)
elm.name = name;
else
ed.execCommand('mceInsertContent', 0, ed.dom.createHTML('a', {name : name, 'class' : 'mceItemAnchor'}, ''));
tinyMCEPopup.close();
}
};
tinyMCEPopup.onInit.add(AnchorDialog.init, AnchorDialog);
| JavaScript |
var ImageDialog = {
preInit : function() {
var url;
tinyMCEPopup.requireLangPack();
if (url = tinyMCEPopup.getParam("external_image_list_url"))
document.write('<script language="javascript" type="text/javascript" src="' + tinyMCEPopup.editor.documentBaseURI.toAbsolute(url) + '"></script>');
},
init : function() {
var f = document.forms[0], ed = tinyMCEPopup.editor;
// Setup browse button
document.getElementById('srcbrowsercontainer').innerHTML = getBrowserHTML('srcbrowser','src','image','theme_advanced_image');
if (isVisible('srcbrowser'))
document.getElementById('src').style.width = '180px';
e = ed.selection.getNode();
this.fillFileList('image_list', 'tinyMCEImageList');
if (e.nodeName == 'IMG') {
f.src.value = ed.dom.getAttrib(e, 'src');
f.alt.value = ed.dom.getAttrib(e, 'alt');
f.border.value = this.getAttrib(e, 'border');
f.vspace.value = this.getAttrib(e, 'vspace');
f.hspace.value = this.getAttrib(e, 'hspace');
f.width.value = ed.dom.getAttrib(e, 'width');
f.height.value = ed.dom.getAttrib(e, 'height');
f.insert.value = ed.getLang('update');
this.styleVal = ed.dom.getAttrib(e, 'style');
selectByValue(f, 'image_list', f.src.value);
selectByValue(f, 'align', this.getAttrib(e, 'align'));
this.updateStyle();
}
},
fillFileList : function(id, l) {
var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl;
l = window[l];
if (l && l.length > 0) {
lst.options[lst.options.length] = new Option('', '');
tinymce.each(l, function(o) {
lst.options[lst.options.length] = new Option(o[0], o[1]);
});
} else
dom.remove(dom.getParent(id, 'tr'));
},
update : function() {
var f = document.forms[0], nl = f.elements, ed = tinyMCEPopup.editor, args = {}, el;
tinyMCEPopup.restoreSelection();
if (f.src.value === '') {
if (ed.selection.getNode().nodeName == 'IMG') {
ed.dom.remove(ed.selection.getNode());
ed.execCommand('mceRepaint');
}
tinyMCEPopup.close();
return;
}
if (!ed.settings.inline_styles) {
args = tinymce.extend(args, {
vspace : nl.vspace.value,
hspace : nl.hspace.value,
border : nl.border.value,
align : getSelectValue(f, 'align')
});
} else
args.style = this.styleVal;
tinymce.extend(args, {
src : f.src.value,
alt : f.alt.value,
width : f.width.value,
height : f.height.value
});
el = ed.selection.getNode();
if (el && el.nodeName == 'IMG') {
ed.dom.setAttribs(el, args);
} else {
ed.execCommand('mceInsertContent', false, '<img id="__mce_tmp" />', {skip_undo : 1});
ed.dom.setAttribs('__mce_tmp', args);
ed.dom.setAttrib('__mce_tmp', 'id', '');
ed.undoManager.add();
}
tinyMCEPopup.close();
},
updateStyle : function() {
var dom = tinyMCEPopup.dom, st, v, f = document.forms[0];
if (tinyMCEPopup.editor.settings.inline_styles) {
st = tinyMCEPopup.dom.parseStyle(this.styleVal);
// Handle align
v = getSelectValue(f, 'align');
if (v) {
if (v == 'left' || v == 'right') {
st['float'] = v;
delete st['vertical-align'];
} else {
st['vertical-align'] = v;
delete st['float'];
}
} else {
delete st['float'];
delete st['vertical-align'];
}
// Handle border
v = f.border.value;
if (v || v == '0') {
if (v == '0')
st['border'] = '0';
else
st['border'] = v + 'px solid black';
} else
delete st['border'];
// Handle hspace
v = f.hspace.value;
if (v) {
delete st['margin'];
st['margin-left'] = v + 'px';
st['margin-right'] = v + 'px';
} else {
delete st['margin-left'];
delete st['margin-right'];
}
// Handle vspace
v = f.vspace.value;
if (v) {
delete st['margin'];
st['margin-top'] = v + 'px';
st['margin-bottom'] = v + 'px';
} else {
delete st['margin-top'];
delete st['margin-bottom'];
}
// Merge
st = tinyMCEPopup.dom.parseStyle(dom.serializeStyle(st), 'img');
this.styleVal = dom.serializeStyle(st, 'img');
}
},
getAttrib : function(e, at) {
var ed = tinyMCEPopup.editor, dom = ed.dom, v, v2;
if (ed.settings.inline_styles) {
switch (at) {
case 'align':
if (v = dom.getStyle(e, 'float'))
return v;
if (v = dom.getStyle(e, 'vertical-align'))
return v;
break;
case 'hspace':
v = dom.getStyle(e, 'margin-left')
v2 = dom.getStyle(e, 'margin-right');
if (v && v == v2)
return parseInt(v.replace(/[^0-9]/g, ''));
break;
case 'vspace':
v = dom.getStyle(e, 'margin-top')
v2 = dom.getStyle(e, 'margin-bottom');
if (v && v == v2)
return parseInt(v.replace(/[^0-9]/g, ''));
break;
case 'border':
v = 0;
tinymce.each(['top', 'right', 'bottom', 'left'], function(sv) {
sv = dom.getStyle(e, 'border-' + sv + '-width');
// False or not the same as prev
if (!sv || (sv != v && v !== 0)) {
v = 0;
return false;
}
if (sv)
v = sv;
});
if (v)
return parseInt(v.replace(/[^0-9]/g, ''));
break;
}
}
if (v = dom.getAttrib(e, at))
return v;
return '';
},
resetImageData : function() {
var f = document.forms[0];
f.width.value = f.height.value = "";
},
updateImageData : function() {
var f = document.forms[0], t = ImageDialog;
if (f.width.value == "")
f.width.value = t.preloadImg.width;
if (f.height.value == "")
f.height.value = t.preloadImg.height;
},
getImageData : function() {
var f = document.forms[0];
this.preloadImg = new Image();
this.preloadImg.onload = this.updateImageData;
this.preloadImg.onerror = this.resetImageData;
this.preloadImg.src = tinyMCEPopup.editor.documentBaseURI.toAbsolute(f.src.value);
}
};
ImageDialog.preInit();
tinyMCEPopup.onInit.add(ImageDialog.init, ImageDialog);
| JavaScript |
tinyMCEPopup.requireLangPack();
var LinkDialog = {
preInit : function() {
var url;
if (url = tinyMCEPopup.getParam("external_link_list_url"))
document.write('<script language="javascript" type="text/javascript" src="' + tinyMCEPopup.editor.documentBaseURI.toAbsolute(url) + '"></script>');
},
init : function() {
var f = document.forms[0], ed = tinyMCEPopup.editor;
// Setup browse button
document.getElementById('hrefbrowsercontainer').innerHTML = getBrowserHTML('hrefbrowser', 'href', 'file', 'theme_advanced_link');
if (isVisible('hrefbrowser'))
document.getElementById('href').style.width = '180px';
this.fillClassList('class_list');
this.fillFileList('link_list', 'tinyMCELinkList');
this.fillTargetList('target_list');
if (e = ed.dom.getParent(ed.selection.getNode(), 'A')) {
f.href.value = ed.dom.getAttrib(e, 'href');
f.linktitle.value = ed.dom.getAttrib(e, 'title');
f.insert.value = ed.getLang('update');
selectByValue(f, 'link_list', f.href.value);
selectByValue(f, 'target_list', ed.dom.getAttrib(e, 'target'));
selectByValue(f, 'class_list', ed.dom.getAttrib(e, 'class'));
}
},
update : function() {
var f = document.forms[0], ed = tinyMCEPopup.editor, e, b;
tinyMCEPopup.restoreSelection();
e = ed.dom.getParent(ed.selection.getNode(), 'A');
// Remove element if there is no href
if (!f.href.value) {
if (e) {
tinyMCEPopup.execCommand("mceBeginUndoLevel");
b = ed.selection.getBookmark();
ed.dom.remove(e, 1);
ed.selection.moveToBookmark(b);
tinyMCEPopup.execCommand("mceEndUndoLevel");
tinyMCEPopup.close();
return;
}
}
tinyMCEPopup.execCommand("mceBeginUndoLevel");
// Create new anchor elements
if (e == null) {
ed.getDoc().execCommand("unlink", false, null);
tinyMCEPopup.execCommand("CreateLink", false, "#mce_temp_url#", {skip_undo : 1});
tinymce.each(ed.dom.select("a"), function(n) {
if (ed.dom.getAttrib(n, 'href') == '#mce_temp_url#') {
e = n;
ed.dom.setAttribs(e, {
href : f.href.value,
title : f.linktitle.value,
target : f.target_list ? getSelectValue(f, "target_list") : null,
'class' : f.class_list ? getSelectValue(f, "class_list") : null
});
}
});
} else {
ed.dom.setAttribs(e, {
href : f.href.value,
title : f.linktitle.value,
target : f.target_list ? getSelectValue(f, "target_list") : null,
'class' : f.class_list ? getSelectValue(f, "class_list") : null
});
}
// Don't move caret if selection was image
if (e.childNodes.length != 1 || e.firstChild.nodeName != 'IMG') {
ed.focus();
ed.selection.select(e);
ed.selection.collapse(0);
tinyMCEPopup.storeSelection();
}
tinyMCEPopup.execCommand("mceEndUndoLevel");
tinyMCEPopup.close();
},
checkPrefix : function(n) {
if (n.value && Validator.isEmail(n) && !/^\s*mailto:/i.test(n.value) && confirm(tinyMCEPopup.getLang('advanced_dlg.link_is_email')))
n.value = 'mailto:' + n.value;
if (/^\s*www\./i.test(n.value) && confirm(tinyMCEPopup.getLang('advanced_dlg.link_is_external')))
n.value = 'http://' + n.value;
},
fillFileList : function(id, l) {
var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl;
l = window[l];
if (l && l.length > 0) {
lst.options[lst.options.length] = new Option('', '');
tinymce.each(l, function(o) {
lst.options[lst.options.length] = new Option(o[0], o[1]);
});
} else
dom.remove(dom.getParent(id, 'tr'));
},
fillClassList : function(id) {
var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl;
if (v = tinyMCEPopup.getParam('theme_advanced_styles')) {
cl = [];
tinymce.each(v.split(';'), function(v) {
var p = v.split('=');
cl.push({'title' : p[0], 'class' : p[1]});
});
} else
cl = tinyMCEPopup.editor.dom.getClasses();
if (cl.length > 0) {
lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('not_set'), '');
tinymce.each(cl, function(o) {
lst.options[lst.options.length] = new Option(o.title || o['class'], o['class']);
});
} else
dom.remove(dom.getParent(id, 'tr'));
},
fillTargetList : function(id) {
var dom = tinyMCEPopup.dom, lst = dom.get(id), v;
lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('not_set'), '');
lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('advanced_dlg.link_target_same'), '_self');
lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('advanced_dlg.link_target_blank'), '_blank');
if (v = tinyMCEPopup.getParam('theme_advanced_link_targets')) {
tinymce.each(v.split(','), function(v) {
v = v.split('=');
lst.options[lst.options.length] = new Option(v[0], v[1]);
});
}
}
};
LinkDialog.preInit();
tinyMCEPopup.onInit.add(LinkDialog.init, LinkDialog);
| JavaScript |
tinyMCEPopup.requireLangPack();
function init() {
var ed, tcont;
tinyMCEPopup.resizeToInnerSize();
ed = tinyMCEPopup.editor;
// Give FF some time
window.setTimeout(insertHelpIFrame, 10);
tcont = document.getElementById('plugintablecontainer');
document.getElementById('plugins_tab').style.display = 'none';
var html = "";
html += '<table id="plugintable">';
html += '<thead>';
html += '<tr>';
html += '<td>' + ed.getLang('advanced_dlg.about_plugin') + '</td>';
html += '<td>' + ed.getLang('advanced_dlg.about_author') + '</td>';
html += '<td>' + ed.getLang('advanced_dlg.about_version') + '</td>';
html += '</tr>';
html += '</thead>';
html += '<tbody>';
tinymce.each(ed.plugins, function(p, n) {
var info;
if (!p.getInfo)
return;
html += '<tr>';
info = p.getInfo();
if (info.infourl != null && info.infourl != '')
html += '<td width="50%" title="' + n + '"><a href="' + info.infourl + '" target="_blank">' + info.longname + '</a></td>';
else
html += '<td width="50%" title="' + n + '">' + info.longname + '</td>';
if (info.authorurl != null && info.authorurl != '')
html += '<td width="35%"><a href="' + info.authorurl + '" target="_blank">' + info.author + '</a></td>';
else
html += '<td width="35%">' + info.author + '</td>';
html += '<td width="15%">' + info.version + '</td>';
html += '</tr>';
document.getElementById('plugins_tab').style.display = '';
});
html += '</tbody>';
html += '</table>';
tcont.innerHTML = html;
tinyMCEPopup.dom.get('version').innerHTML = tinymce.majorVersion + "." + tinymce.minorVersion;
tinyMCEPopup.dom.get('date').innerHTML = tinymce.releaseDate;
}
function insertHelpIFrame() {
var html;
if (tinyMCEPopup.getParam('docs_url')) {
html = '<iframe width="100%" height="300" src="' + tinyMCEPopup.editor.baseURI.toAbsolute(tinyMCEPopup.getParam('docs_url')) + '"></iframe>';
document.getElementById('iframecontainer').innerHTML = html;
document.getElementById('help_tab').style.display = 'block';
}
}
tinyMCEPopup.onInit.add(init);
| JavaScript |
tinyMCEPopup.requireLangPack();
var detail = 50, strhex = "0123456789abcdef", i, isMouseDown = false, isMouseOver = false;
var colors = [
"#000000","#000033","#000066","#000099","#0000cc","#0000ff","#330000","#330033",
"#330066","#330099","#3300cc","#3300ff","#660000","#660033","#660066","#660099",
"#6600cc","#6600ff","#990000","#990033","#990066","#990099","#9900cc","#9900ff",
"#cc0000","#cc0033","#cc0066","#cc0099","#cc00cc","#cc00ff","#ff0000","#ff0033",
"#ff0066","#ff0099","#ff00cc","#ff00ff","#003300","#003333","#003366","#003399",
"#0033cc","#0033ff","#333300","#333333","#333366","#333399","#3333cc","#3333ff",
"#663300","#663333","#663366","#663399","#6633cc","#6633ff","#993300","#993333",
"#993366","#993399","#9933cc","#9933ff","#cc3300","#cc3333","#cc3366","#cc3399",
"#cc33cc","#cc33ff","#ff3300","#ff3333","#ff3366","#ff3399","#ff33cc","#ff33ff",
"#006600","#006633","#006666","#006699","#0066cc","#0066ff","#336600","#336633",
"#336666","#336699","#3366cc","#3366ff","#666600","#666633","#666666","#666699",
"#6666cc","#6666ff","#996600","#996633","#996666","#996699","#9966cc","#9966ff",
"#cc6600","#cc6633","#cc6666","#cc6699","#cc66cc","#cc66ff","#ff6600","#ff6633",
"#ff6666","#ff6699","#ff66cc","#ff66ff","#009900","#009933","#009966","#009999",
"#0099cc","#0099ff","#339900","#339933","#339966","#339999","#3399cc","#3399ff",
"#669900","#669933","#669966","#669999","#6699cc","#6699ff","#999900","#999933",
"#999966","#999999","#9999cc","#9999ff","#cc9900","#cc9933","#cc9966","#cc9999",
"#cc99cc","#cc99ff","#ff9900","#ff9933","#ff9966","#ff9999","#ff99cc","#ff99ff",
"#00cc00","#00cc33","#00cc66","#00cc99","#00cccc","#00ccff","#33cc00","#33cc33",
"#33cc66","#33cc99","#33cccc","#33ccff","#66cc00","#66cc33","#66cc66","#66cc99",
"#66cccc","#66ccff","#99cc00","#99cc33","#99cc66","#99cc99","#99cccc","#99ccff",
"#cccc00","#cccc33","#cccc66","#cccc99","#cccccc","#ccccff","#ffcc00","#ffcc33",
"#ffcc66","#ffcc99","#ffcccc","#ffccff","#00ff00","#00ff33","#00ff66","#00ff99",
"#00ffcc","#00ffff","#33ff00","#33ff33","#33ff66","#33ff99","#33ffcc","#33ffff",
"#66ff00","#66ff33","#66ff66","#66ff99","#66ffcc","#66ffff","#99ff00","#99ff33",
"#99ff66","#99ff99","#99ffcc","#99ffff","#ccff00","#ccff33","#ccff66","#ccff99",
"#ccffcc","#ccffff","#ffff00","#ffff33","#ffff66","#ffff99","#ffffcc","#ffffff"
];
var named = {
'#F0F8FF':'AliceBlue','#FAEBD7':'AntiqueWhite','#00FFFF':'Aqua','#7FFFD4':'Aquamarine','#F0FFFF':'Azure','#F5F5DC':'Beige',
'#FFE4C4':'Bisque','#000000':'Black','#FFEBCD':'BlanchedAlmond','#0000FF':'Blue','#8A2BE2':'BlueViolet','#A52A2A':'Brown',
'#DEB887':'BurlyWood','#5F9EA0':'CadetBlue','#7FFF00':'Chartreuse','#D2691E':'Chocolate','#FF7F50':'Coral','#6495ED':'CornflowerBlue',
'#FFF8DC':'Cornsilk','#DC143C':'Crimson','#00FFFF':'Cyan','#00008B':'DarkBlue','#008B8B':'DarkCyan','#B8860B':'DarkGoldenRod',
'#A9A9A9':'DarkGray','#A9A9A9':'DarkGrey','#006400':'DarkGreen','#BDB76B':'DarkKhaki','#8B008B':'DarkMagenta','#556B2F':'DarkOliveGreen',
'#FF8C00':'Darkorange','#9932CC':'DarkOrchid','#8B0000':'DarkRed','#E9967A':'DarkSalmon','#8FBC8F':'DarkSeaGreen','#483D8B':'DarkSlateBlue',
'#2F4F4F':'DarkSlateGray','#2F4F4F':'DarkSlateGrey','#00CED1':'DarkTurquoise','#9400D3':'DarkViolet','#FF1493':'DeepPink','#00BFFF':'DeepSkyBlue',
'#696969':'DimGray','#696969':'DimGrey','#1E90FF':'DodgerBlue','#B22222':'FireBrick','#FFFAF0':'FloralWhite','#228B22':'ForestGreen',
'#FF00FF':'Fuchsia','#DCDCDC':'Gainsboro','#F8F8FF':'GhostWhite','#FFD700':'Gold','#DAA520':'GoldenRod','#808080':'Gray','#808080':'Grey',
'#008000':'Green','#ADFF2F':'GreenYellow','#F0FFF0':'HoneyDew','#FF69B4':'HotPink','#CD5C5C':'IndianRed','#4B0082':'Indigo','#FFFFF0':'Ivory',
'#F0E68C':'Khaki','#E6E6FA':'Lavender','#FFF0F5':'LavenderBlush','#7CFC00':'LawnGreen','#FFFACD':'LemonChiffon','#ADD8E6':'LightBlue',
'#F08080':'LightCoral','#E0FFFF':'LightCyan','#FAFAD2':'LightGoldenRodYellow','#D3D3D3':'LightGray','#D3D3D3':'LightGrey','#90EE90':'LightGreen',
'#FFB6C1':'LightPink','#FFA07A':'LightSalmon','#20B2AA':'LightSeaGreen','#87CEFA':'LightSkyBlue','#778899':'LightSlateGray','#778899':'LightSlateGrey',
'#B0C4DE':'LightSteelBlue','#FFFFE0':'LightYellow','#00FF00':'Lime','#32CD32':'LimeGreen','#FAF0E6':'Linen','#FF00FF':'Magenta','#800000':'Maroon',
'#66CDAA':'MediumAquaMarine','#0000CD':'MediumBlue','#BA55D3':'MediumOrchid','#9370D8':'MediumPurple','#3CB371':'MediumSeaGreen','#7B68EE':'MediumSlateBlue',
'#00FA9A':'MediumSpringGreen','#48D1CC':'MediumTurquoise','#C71585':'MediumVioletRed','#191970':'MidnightBlue','#F5FFFA':'MintCream','#FFE4E1':'MistyRose','#FFE4B5':'Moccasin',
'#FFDEAD':'NavajoWhite','#000080':'Navy','#FDF5E6':'OldLace','#808000':'Olive','#6B8E23':'OliveDrab','#FFA500':'Orange','#FF4500':'OrangeRed','#DA70D6':'Orchid',
'#EEE8AA':'PaleGoldenRod','#98FB98':'PaleGreen','#AFEEEE':'PaleTurquoise','#D87093':'PaleVioletRed','#FFEFD5':'PapayaWhip','#FFDAB9':'PeachPuff',
'#CD853F':'Peru','#FFC0CB':'Pink','#DDA0DD':'Plum','#B0E0E6':'PowderBlue','#800080':'Purple','#FF0000':'Red','#BC8F8F':'RosyBrown','#4169E1':'RoyalBlue',
'#8B4513':'SaddleBrown','#FA8072':'Salmon','#F4A460':'SandyBrown','#2E8B57':'SeaGreen','#FFF5EE':'SeaShell','#A0522D':'Sienna','#C0C0C0':'Silver',
'#87CEEB':'SkyBlue','#6A5ACD':'SlateBlue','#708090':'SlateGray','#708090':'SlateGrey','#FFFAFA':'Snow','#00FF7F':'SpringGreen',
'#4682B4':'SteelBlue','#D2B48C':'Tan','#008080':'Teal','#D8BFD8':'Thistle','#FF6347':'Tomato','#40E0D0':'Turquoise','#EE82EE':'Violet',
'#F5DEB3':'Wheat','#FFFFFF':'White','#F5F5F5':'WhiteSmoke','#FFFF00':'Yellow','#9ACD32':'YellowGreen'
};
function init() {
var inputColor = convertRGBToHex(tinyMCEPopup.getWindowArg('input_color'));
tinyMCEPopup.resizeToInnerSize();
generatePicker();
if (inputColor) {
changeFinalColor(inputColor);
col = convertHexToRGB(inputColor);
if (col)
updateLight(col.r, col.g, col.b);
}
}
function insertAction() {
var color = document.getElementById("color").value, f = tinyMCEPopup.getWindowArg('func');
tinyMCEPopup.restoreSelection();
if (f)
f(color);
tinyMCEPopup.close();
}
function showColor(color, name) {
if (name)
document.getElementById("colorname").innerHTML = name;
document.getElementById("preview").style.backgroundColor = color;
document.getElementById("color").value = color.toLowerCase();
}
function convertRGBToHex(col) {
var re = new RegExp("rgb\\s*\\(\\s*([0-9]+).*,\\s*([0-9]+).*,\\s*([0-9]+).*\\)", "gi");
if (!col)
return col;
var rgb = col.replace(re, "$1,$2,$3").split(',');
if (rgb.length == 3) {
r = parseInt(rgb[0]).toString(16);
g = parseInt(rgb[1]).toString(16);
b = parseInt(rgb[2]).toString(16);
r = r.length == 1 ? '0' + r : r;
g = g.length == 1 ? '0' + g : g;
b = b.length == 1 ? '0' + b : b;
return "#" + r + g + b;
}
return col;
}
function convertHexToRGB(col) {
if (col.indexOf('#') != -1) {
col = col.replace(new RegExp('[^0-9A-F]', 'gi'), '');
r = parseInt(col.substring(0, 2), 16);
g = parseInt(col.substring(2, 4), 16);
b = parseInt(col.substring(4, 6), 16);
return {r : r, g : g, b : b};
}
return null;
}
function generatePicker() {
var el = document.getElementById('light'), h = '', i;
for (i = 0; i < detail; i++){
h += '<div id="gs'+i+'" style="background-color:#000000; width:15px; height:3px; border-style:none; border-width:0px;"'
+ ' onclick="changeFinalColor(this.style.backgroundColor)"'
+ ' onmousedown="isMouseDown = true; return false;"'
+ ' onmouseup="isMouseDown = false;"'
+ ' onmousemove="if (isMouseDown && isMouseOver) changeFinalColor(this.style.backgroundColor); return false;"'
+ ' onmouseover="isMouseOver = true;"'
+ ' onmouseout="isMouseOver = false;"'
+ '></div>';
}
el.innerHTML = h;
}
function generateWebColors() {
var el = document.getElementById('webcolors'), h = '', i;
if (el.className == 'generated')
return;
h += '<table border="0" cellspacing="1" cellpadding="0">'
+ '<tr>';
for (i=0; i<colors.length; i++) {
h += '<td bgcolor="' + colors[i] + '" width="10" height="10">'
+ '<a href="javascript:insertAction();" onfocus="showColor(\'' + colors[i] + '\');" onmouseover="showColor(\'' + colors[i] + '\');" style="display:block;width:10px;height:10px;overflow:hidden;">'
+ '</a></td>';
if ((i+1) % 18 == 0)
h += '</tr><tr>';
}
h += '</table>';
el.innerHTML = h;
el.className = 'generated';
}
function generateNamedColors() {
var el = document.getElementById('namedcolors'), h = '', n, v, i = 0;
if (el.className == 'generated')
return;
for (n in named) {
v = named[n];
h += '<a href="javascript:insertAction();" onmouseover="showColor(\'' + n + '\',\'' + v + '\');" style="background-color: ' + n + '"><!-- IE --></a>'
}
el.innerHTML = h;
el.className = 'generated';
}
function dechex(n) {
return strhex.charAt(Math.floor(n / 16)) + strhex.charAt(n % 16);
}
function computeColor(e) {
var x, y, partWidth, partDetail, imHeight, r, g, b, coef, i, finalCoef, finalR, finalG, finalB;
x = e.offsetX ? e.offsetX : (e.target ? e.clientX - e.target.x : 0);
y = e.offsetY ? e.offsetY : (e.target ? e.clientY - e.target.y : 0);
partWidth = document.getElementById('colors').width / 6;
partDetail = detail / 2;
imHeight = document.getElementById('colors').height;
r = (x >= 0)*(x < partWidth)*255 + (x >= partWidth)*(x < 2*partWidth)*(2*255 - x * 255 / partWidth) + (x >= 4*partWidth)*(x < 5*partWidth)*(-4*255 + x * 255 / partWidth) + (x >= 5*partWidth)*(x < 6*partWidth)*255;
g = (x >= 0)*(x < partWidth)*(x * 255 / partWidth) + (x >= partWidth)*(x < 3*partWidth)*255 + (x >= 3*partWidth)*(x < 4*partWidth)*(4*255 - x * 255 / partWidth);
b = (x >= 2*partWidth)*(x < 3*partWidth)*(-2*255 + x * 255 / partWidth) + (x >= 3*partWidth)*(x < 5*partWidth)*255 + (x >= 5*partWidth)*(x < 6*partWidth)*(6*255 - x * 255 / partWidth);
coef = (imHeight - y) / imHeight;
r = 128 + (r - 128) * coef;
g = 128 + (g - 128) * coef;
b = 128 + (b - 128) * coef;
changeFinalColor('#' + dechex(r) + dechex(g) + dechex(b));
updateLight(r, g, b);
}
function updateLight(r, g, b) {
var i, partDetail = detail / 2, finalCoef, finalR, finalG, finalB, color;
for (i=0; i<detail; i++) {
if ((i>=0) && (i<partDetail)) {
finalCoef = i / partDetail;
finalR = dechex(255 - (255 - r) * finalCoef);
finalG = dechex(255 - (255 - g) * finalCoef);
finalB = dechex(255 - (255 - b) * finalCoef);
} else {
finalCoef = 2 - i / partDetail;
finalR = dechex(r * finalCoef);
finalG = dechex(g * finalCoef);
finalB = dechex(b * finalCoef);
}
color = finalR + finalG + finalB;
setCol('gs' + i, '#'+color);
}
}
function changeFinalColor(color) {
if (color.indexOf('#') == -1)
color = convertRGBToHex(color);
setCol('preview', color);
document.getElementById('color').value = color;
}
function setCol(e, c) {
try {
document.getElementById(e).style.backgroundColor = c;
} catch (ex) {
// Ignore IE warning
}
}
tinyMCEPopup.onInit.add(init);
| JavaScript |
/**
* editor_template_src.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
(function(tinymce) {
var DOM = tinymce.DOM, Event = tinymce.dom.Event, extend = tinymce.extend, each = tinymce.each, Cookie = tinymce.util.Cookie, lastExtID, explode = tinymce.explode;
// Tell it to load theme specific language pack(s)
tinymce.ThemeManager.requireLangPack('advanced');
tinymce.create('tinymce.themes.AdvancedTheme', {
sizes : [8, 10, 12, 14, 18, 24, 36],
// Control name lookup, format: title, command
controls : {
bold : ['bold_desc', 'Bold'],
italic : ['italic_desc', 'Italic'],
underline : ['underline_desc', 'Underline'],
strikethrough : ['striketrough_desc', 'Strikethrough'],
justifyleft : ['justifyleft_desc', 'JustifyLeft'],
justifycenter : ['justifycenter_desc', 'JustifyCenter'],
justifyright : ['justifyright_desc', 'JustifyRight'],
justifyfull : ['justifyfull_desc', 'JustifyFull'],
bullist : ['bullist_desc', 'InsertUnorderedList'],
numlist : ['numlist_desc', 'InsertOrderedList'],
outdent : ['outdent_desc', 'Outdent'],
indent : ['indent_desc', 'Indent'],
cut : ['cut_desc', 'Cut'],
copy : ['copy_desc', 'Copy'],
paste : ['paste_desc', 'Paste'],
undo : ['undo_desc', 'Undo'],
redo : ['redo_desc', 'Redo'],
link : ['link_desc', 'mceLink'],
unlink : ['unlink_desc', 'unlink'],
image : ['image_desc', 'mceImage'],
cleanup : ['cleanup_desc', 'mceCleanup'],
help : ['help_desc', 'mceHelp'],
code : ['code_desc', 'mceCodeEditor'],
hr : ['hr_desc', 'InsertHorizontalRule'],
removeformat : ['removeformat_desc', 'RemoveFormat'],
sub : ['sub_desc', 'subscript'],
sup : ['sup_desc', 'superscript'],
forecolor : ['forecolor_desc', 'ForeColor'],
forecolorpicker : ['forecolor_desc', 'mceForeColor'],
backcolor : ['backcolor_desc', 'HiliteColor'],
backcolorpicker : ['backcolor_desc', 'mceBackColor'],
charmap : ['charmap_desc', 'mceCharMap'],
visualaid : ['visualaid_desc', 'mceToggleVisualAid'],
anchor : ['anchor_desc', 'mceInsertAnchor'],
newdocument : ['newdocument_desc', 'mceNewDocument'],
blockquote : ['blockquote_desc', 'mceBlockQuote']
},
stateControls : ['bold', 'italic', 'underline', 'strikethrough', 'bullist', 'numlist', 'justifyleft', 'justifycenter', 'justifyright', 'justifyfull', 'sub', 'sup', 'blockquote'],
init : function(ed, url) {
var t = this, s, v, o;
t.editor = ed;
t.url = url;
t.onResolveName = new tinymce.util.Dispatcher(this);
// Default settings
t.settings = s = extend({
theme_advanced_path : true,
theme_advanced_toolbar_location : 'bottom',
theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect",
theme_advanced_buttons2 : "bullist,numlist,|,outdent,indent,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code",
theme_advanced_buttons3 : "hr,removeformat,visualaid,|,sub,sup,|,charmap",
theme_advanced_blockformats : "p,address,pre,h1,h2,h3,h4,h5,h6",
theme_advanced_toolbar_align : "center",
theme_advanced_fonts : "Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings,zapf dingbats",
theme_advanced_more_colors : 1,
theme_advanced_row_height : 23,
theme_advanced_resize_horizontal : 1,
theme_advanced_resizing_use_cookie : 1,
theme_advanced_font_sizes : "1,2,3,4,5,6,7",
readonly : ed.settings.readonly
}, ed.settings);
// Setup default font_size_style_values
if (!s.font_size_style_values)
s.font_size_style_values = "8pt,10pt,12pt,14pt,18pt,24pt,36pt";
if (tinymce.is(s.theme_advanced_font_sizes, 'string')) {
s.font_size_style_values = tinymce.explode(s.font_size_style_values);
s.font_size_classes = tinymce.explode(s.font_size_classes || '');
// Parse string value
o = {};
ed.settings.theme_advanced_font_sizes = s.theme_advanced_font_sizes;
each(ed.getParam('theme_advanced_font_sizes', '', 'hash'), function(v, k) {
var cl;
if (k == v && v >= 1 && v <= 7) {
k = v + ' (' + t.sizes[v - 1] + 'pt)';
cl = s.font_size_classes[v - 1];
v = s.font_size_style_values[v - 1] || (t.sizes[v - 1] + 'pt');
}
if (/^\s*\./.test(v))
cl = v.replace(/\./g, '');
o[k] = cl ? {'class' : cl} : {fontSize : v};
});
s.theme_advanced_font_sizes = o;
}
if ((v = s.theme_advanced_path_location) && v != 'none')
s.theme_advanced_statusbar_location = s.theme_advanced_path_location;
if (s.theme_advanced_statusbar_location == 'none')
s.theme_advanced_statusbar_location = 0;
// Init editor
ed.onInit.add(function() {
if (!ed.settings.readonly)
ed.onNodeChange.add(t._nodeChanged, t);
if (ed.settings.content_css !== false)
ed.dom.loadCSS(ed.baseURI.toAbsolute(url + "/skins/" + ed.settings.skin + "/content.css"));
});
ed.onSetProgressState.add(function(ed, b, ti) {
var co, id = ed.id, tb;
if (b) {
t.progressTimer = setTimeout(function() {
co = ed.getContainer();
co = co.insertBefore(DOM.create('DIV', {style : 'position:relative'}), co.firstChild);
tb = DOM.get(ed.id + '_tbl');
DOM.add(co, 'div', {id : id + '_blocker', 'class' : 'mceBlocker', style : {width : tb.clientWidth + 2, height : tb.clientHeight + 2}});
DOM.add(co, 'div', {id : id + '_progress', 'class' : 'mceProgress', style : {left : tb.clientWidth / 2, top : tb.clientHeight / 2}});
}, ti || 0);
} else {
DOM.remove(id + '_blocker');
DOM.remove(id + '_progress');
clearTimeout(t.progressTimer);
}
});
DOM.loadCSS(s.editor_css ? ed.documentBaseURI.toAbsolute(s.editor_css) : url + "/skins/" + ed.settings.skin + "/ui.css");
if (s.skin_variant)
DOM.loadCSS(url + "/skins/" + ed.settings.skin + "/ui_" + s.skin_variant + ".css");
},
createControl : function(n, cf) {
var cd, c;
if (c = cf.createControl(n))
return c;
switch (n) {
case "styleselect":
return this._createStyleSelect();
case "formatselect":
return this._createBlockFormats();
case "fontselect":
return this._createFontSelect();
case "fontsizeselect":
return this._createFontSizeSelect();
case "forecolor":
return this._createForeColorMenu();
case "backcolor":
return this._createBackColorMenu();
}
if ((cd = this.controls[n]))
return cf.createButton(n, {title : "advanced." + cd[0], cmd : cd[1], ui : cd[2], value : cd[3]});
},
execCommand : function(cmd, ui, val) {
var f = this['_' + cmd];
if (f) {
f.call(this, ui, val);
return true;
}
return false;
},
_importClasses : function(e) {
var ed = this.editor, ctrl = ed.controlManager.get('styleselect');
if (ctrl.getLength() == 0) {
each(ed.dom.getClasses(), function(o, idx) {
var name = 'style_' + idx;
ed.formatter.register(name, {
inline : 'span',
attributes : {'class' : o['class']},
selector : '*'
});
ctrl.add(o['class'], name);
});
}
},
_createStyleSelect : function(n) {
var t = this, ed = t.editor, ctrlMan = ed.controlManager, ctrl;
// Setup style select box
ctrl = ctrlMan.createListBox('styleselect', {
title : 'advanced.style_select',
onselect : function(name) {
var matches, formatNames = [];
each(ctrl.items, function(item) {
formatNames.push(item.value);
});
ed.focus();
ed.undoManager.add();
// Toggle off the current format
matches = ed.formatter.matchAll(formatNames);
if (!name || matches[0] == name)
ed.formatter.remove(matches[0]);
else
ed.formatter.apply(name);
ed.undoManager.add();
ed.nodeChanged();
return false; // No auto select
}
});
// Handle specified format
ed.onInit.add(function() {
var counter = 0, formats = ed.getParam('style_formats');
if (formats) {
each(formats, function(fmt) {
var name, keys = 0;
each(fmt, function() {keys++;});
if (keys > 1) {
name = fmt.name = fmt.name || 'style_' + (counter++);
ed.formatter.register(name, fmt);
ctrl.add(fmt.title, name);
} else
ctrl.add(fmt.title);
});
} else {
each(ed.getParam('theme_advanced_styles', '', 'hash'), function(val, key) {
var name;
if (val) {
name = 'style_' + (counter++);
ed.formatter.register(name, {
inline : 'span',
classes : val,
selector : '*'
});
ctrl.add(t.editor.translate(key), name);
}
});
}
});
// Auto import classes if the ctrl box is empty
if (ctrl.getLength() == 0) {
ctrl.onPostRender.add(function(ed, n) {
if (!ctrl.NativeListBox) {
Event.add(n.id + '_text', 'focus', t._importClasses, t);
Event.add(n.id + '_text', 'mousedown', t._importClasses, t);
Event.add(n.id + '_open', 'focus', t._importClasses, t);
Event.add(n.id + '_open', 'mousedown', t._importClasses, t);
} else
Event.add(n.id, 'focus', t._importClasses, t);
});
}
return ctrl;
},
_createFontSelect : function() {
var c, t = this, ed = t.editor;
c = ed.controlManager.createListBox('fontselect', {
title : 'advanced.fontdefault',
onselect : function(v) {
var cur = c.items[c.selectedIndex];
if (!v && cur) {
ed.execCommand('FontName', false, cur.value);
return;
}
ed.execCommand('FontName', false, v);
// Fake selection, execCommand will fire a nodeChange and update the selection
c.select(function(sv) {
return v == sv;
});
return false; // No auto select
}
});
if (c) {
each(ed.getParam('theme_advanced_fonts', t.settings.theme_advanced_fonts, 'hash'), function(v, k) {
c.add(ed.translate(k), v, {style : v.indexOf('dings') == -1 ? 'font-family:' + v : ''});
});
}
return c;
},
_createFontSizeSelect : function() {
var t = this, ed = t.editor, c, i = 0, cl = [];
c = ed.controlManager.createListBox('fontsizeselect', {title : 'advanced.font_size', onselect : function(v) {
var cur = c.items[c.selectedIndex];
if (!v && cur) {
cur = cur.value;
if (cur['class']) {
ed.formatter.toggle('fontsize_class', {value : cur['class']});
ed.undoManager.add();
ed.nodeChanged();
} else {
ed.execCommand('FontSize', false, cur.fontSize);
}
return;
}
if (v['class']) {
ed.focus();
ed.undoManager.add();
ed.formatter.toggle('fontsize_class', {value : v['class']});
ed.undoManager.add();
ed.nodeChanged();
} else
ed.execCommand('FontSize', false, v.fontSize);
// Fake selection, execCommand will fire a nodeChange and update the selection
c.select(function(sv) {
return v == sv;
});
return false; // No auto select
}});
if (c) {
each(t.settings.theme_advanced_font_sizes, function(v, k) {
var fz = v.fontSize;
if (fz >= 1 && fz <= 7)
fz = t.sizes[parseInt(fz) - 1] + 'pt';
c.add(k, v, {'style' : 'font-size:' + fz, 'class' : 'mceFontSize' + (i++) + (' ' + (v['class'] || ''))});
});
}
return c;
},
_createBlockFormats : function() {
var c, fmts = {
p : 'advanced.paragraph',
address : 'advanced.address',
pre : 'advanced.pre',
h1 : 'advanced.h1',
h2 : 'advanced.h2',
h3 : 'advanced.h3',
h4 : 'advanced.h4',
h5 : 'advanced.h5',
h6 : 'advanced.h6',
div : 'advanced.div',
blockquote : 'advanced.blockquote',
code : 'advanced.code',
dt : 'advanced.dt',
dd : 'advanced.dd',
samp : 'advanced.samp'
}, t = this;
c = t.editor.controlManager.createListBox('formatselect', {title : 'advanced.block', cmd : 'FormatBlock'});
if (c) {
each(t.editor.getParam('theme_advanced_blockformats', t.settings.theme_advanced_blockformats, 'hash'), function(v, k) {
c.add(t.editor.translate(k != v ? k : fmts[v]), v, {'class' : 'mce_formatPreview mce_' + v});
});
}
return c;
},
_createForeColorMenu : function() {
var c, t = this, s = t.settings, o = {}, v;
if (s.theme_advanced_more_colors) {
o.more_colors_func = function() {
t._mceColorPicker(0, {
color : c.value,
func : function(co) {
c.setColor(co);
}
});
};
}
if (v = s.theme_advanced_text_colors)
o.colors = v;
if (s.theme_advanced_default_foreground_color)
o.default_color = s.theme_advanced_default_foreground_color;
o.title = 'advanced.forecolor_desc';
o.cmd = 'ForeColor';
o.scope = this;
c = t.editor.controlManager.createColorSplitButton('forecolor', o);
return c;
},
_createBackColorMenu : function() {
var c, t = this, s = t.settings, o = {}, v;
if (s.theme_advanced_more_colors) {
o.more_colors_func = function() {
t._mceColorPicker(0, {
color : c.value,
func : function(co) {
c.setColor(co);
}
});
};
}
if (v = s.theme_advanced_background_colors)
o.colors = v;
if (s.theme_advanced_default_background_color)
o.default_color = s.theme_advanced_default_background_color;
o.title = 'advanced.backcolor_desc';
o.cmd = 'HiliteColor';
o.scope = this;
c = t.editor.controlManager.createColorSplitButton('backcolor', o);
return c;
},
renderUI : function(o) {
var n, ic, tb, t = this, ed = t.editor, s = t.settings, sc, p, nl;
n = p = DOM.create('span', {id : ed.id + '_parent', 'class' : 'mceEditor ' + ed.settings.skin + 'Skin' + (s.skin_variant ? ' ' + ed.settings.skin + 'Skin' + t._ufirst(s.skin_variant) : '')});
if (!DOM.boxModel)
n = DOM.add(n, 'div', {'class' : 'mceOldBoxModel'});
n = sc = DOM.add(n, 'table', {id : ed.id + '_tbl', 'class' : 'mceLayout', cellSpacing : 0, cellPadding : 0});
n = tb = DOM.add(n, 'tbody');
switch ((s.theme_advanced_layout_manager || '').toLowerCase()) {
case "rowlayout":
ic = t._rowLayout(s, tb, o);
break;
case "customlayout":
ic = ed.execCallback("theme_advanced_custom_layout", s, tb, o, p);
break;
default:
ic = t._simpleLayout(s, tb, o, p);
}
n = o.targetNode;
// Add classes to first and last TRs
nl = DOM.stdMode ? sc.getElementsByTagName('tr') : sc.rows; // Quick fix for IE 8
DOM.addClass(nl[0], 'mceFirst');
DOM.addClass(nl[nl.length - 1], 'mceLast');
// Add classes to first and last TDs
each(DOM.select('tr', tb), function(n) {
DOM.addClass(n.firstChild, 'mceFirst');
DOM.addClass(n.childNodes[n.childNodes.length - 1], 'mceLast');
});
if (DOM.get(s.theme_advanced_toolbar_container))
DOM.get(s.theme_advanced_toolbar_container).appendChild(p);
else
DOM.insertAfter(p, n);
Event.add(ed.id + '_path_row', 'click', function(e) {
e = e.target;
if (e.nodeName == 'A') {
t._sel(e.className.replace(/^.*mcePath_([0-9]+).*$/, '$1'));
return Event.cancel(e);
}
});
/*
if (DOM.get(ed.id + '_path_row')) {
Event.add(ed.id + '_tbl', 'mouseover', function(e) {
var re;
e = e.target;
if (e.nodeName == 'SPAN' && DOM.hasClass(e.parentNode, 'mceButton')) {
re = DOM.get(ed.id + '_path_row');
t.lastPath = re.innerHTML;
DOM.setHTML(re, e.parentNode.title);
}
});
Event.add(ed.id + '_tbl', 'mouseout', function(e) {
if (t.lastPath) {
DOM.setHTML(ed.id + '_path_row', t.lastPath);
t.lastPath = 0;
}
});
}
*/
if (!ed.getParam('accessibility_focus'))
Event.add(DOM.add(p, 'a', {href : '#'}, '<!-- IE -->'), 'focus', function() {tinyMCE.get(ed.id).focus();});
if (s.theme_advanced_toolbar_location == 'external')
o.deltaHeight = 0;
t.deltaHeight = o.deltaHeight;
o.targetNode = null;
return {
iframeContainer : ic,
editorContainer : ed.id + '_parent',
sizeContainer : sc,
deltaHeight : o.deltaHeight
};
},
getInfo : function() {
return {
longname : 'Advanced theme',
author : 'Moxiecode Systems AB',
authorurl : 'http://tinymce.moxiecode.com',
version : tinymce.majorVersion + "." + tinymce.minorVersion
}
},
resizeBy : function(dw, dh) {
var e = DOM.get(this.editor.id + '_tbl');
this.resizeTo(e.clientWidth + dw, e.clientHeight + dh);
},
resizeTo : function(w, h) {
var ed = this.editor, s = this.settings, e = DOM.get(ed.id + '_tbl'), ifr = DOM.get(ed.id + '_ifr');
// Boundery fix box
w = Math.max(s.theme_advanced_resizing_min_width || 100, w);
h = Math.max(s.theme_advanced_resizing_min_height || 100, h);
w = Math.min(s.theme_advanced_resizing_max_width || 0xFFFF, w);
h = Math.min(s.theme_advanced_resizing_max_height || 0xFFFF, h);
// Resize iframe and container
DOM.setStyle(e, 'height', '');
DOM.setStyle(ifr, 'height', h);
if (s.theme_advanced_resize_horizontal) {
DOM.setStyle(e, 'width', '');
DOM.setStyle(ifr, 'width', w);
// Make sure that the size is never smaller than the over all ui
if (w < e.clientWidth)
DOM.setStyle(ifr, 'width', e.clientWidth);
}
},
destroy : function() {
var id = this.editor.id;
Event.clear(id + '_resize');
Event.clear(id + '_path_row');
Event.clear(id + '_external_close');
},
// Internal functions
_simpleLayout : function(s, tb, o, p) {
var t = this, ed = t.editor, lo = s.theme_advanced_toolbar_location, sl = s.theme_advanced_statusbar_location, n, ic, etb, c;
if (s.readonly) {
n = DOM.add(tb, 'tr');
n = ic = DOM.add(n, 'td', {'class' : 'mceIframeContainer'});
return ic;
}
// Create toolbar container at top
if (lo == 'top')
t._addToolbars(tb, o);
// Create external toolbar
if (lo == 'external') {
n = c = DOM.create('div', {style : 'position:relative'});
n = DOM.add(n, 'div', {id : ed.id + '_external', 'class' : 'mceExternalToolbar'});
DOM.add(n, 'a', {id : ed.id + '_external_close', href : 'javascript:;', 'class' : 'mceExternalClose'});
n = DOM.add(n, 'table', {id : ed.id + '_tblext', cellSpacing : 0, cellPadding : 0});
etb = DOM.add(n, 'tbody');
if (p.firstChild.className == 'mceOldBoxModel')
p.firstChild.appendChild(c);
else
p.insertBefore(c, p.firstChild);
t._addToolbars(etb, o);
ed.onMouseUp.add(function() {
var e = DOM.get(ed.id + '_external');
DOM.show(e);
DOM.hide(lastExtID);
var f = Event.add(ed.id + '_external_close', 'click', function() {
DOM.hide(ed.id + '_external');
Event.remove(ed.id + '_external_close', 'click', f);
});
DOM.show(e);
DOM.setStyle(e, 'top', 0 - DOM.getRect(ed.id + '_tblext').h - 1);
// Fixes IE rendering bug
DOM.hide(e);
DOM.show(e);
e.style.filter = '';
lastExtID = ed.id + '_external';
e = null;
});
}
if (sl == 'top')
t._addStatusBar(tb, o);
// Create iframe container
if (!s.theme_advanced_toolbar_container) {
n = DOM.add(tb, 'tr');
n = ic = DOM.add(n, 'td', {'class' : 'mceIframeContainer'});
}
// Create toolbar container at bottom
if (lo == 'bottom')
t._addToolbars(tb, o);
if (sl == 'bottom')
t._addStatusBar(tb, o);
return ic;
},
_rowLayout : function(s, tb, o) {
var t = this, ed = t.editor, dc, da, cf = ed.controlManager, n, ic, to, a;
dc = s.theme_advanced_containers_default_class || '';
da = s.theme_advanced_containers_default_align || 'center';
each(explode(s.theme_advanced_containers || ''), function(c, i) {
var v = s['theme_advanced_container_' + c] || '';
switch (v.toLowerCase()) {
case 'mceeditor':
n = DOM.add(tb, 'tr');
n = ic = DOM.add(n, 'td', {'class' : 'mceIframeContainer'});
break;
case 'mceelementpath':
t._addStatusBar(tb, o);
break;
default:
a = (s['theme_advanced_container_' + c + '_align'] || da).toLowerCase();
a = 'mce' + t._ufirst(a);
n = DOM.add(DOM.add(tb, 'tr'), 'td', {
'class' : 'mceToolbar ' + (s['theme_advanced_container_' + c + '_class'] || dc) + ' ' + a || da
});
to = cf.createToolbar("toolbar" + i);
t._addControls(v, to);
DOM.setHTML(n, to.renderHTML());
o.deltaHeight -= s.theme_advanced_row_height;
}
});
return ic;
},
_addControls : function(v, tb) {
var t = this, s = t.settings, di, cf = t.editor.controlManager;
if (s.theme_advanced_disable && !t._disabled) {
di = {};
each(explode(s.theme_advanced_disable), function(v) {
di[v] = 1;
});
t._disabled = di;
} else
di = t._disabled;
each(explode(v), function(n) {
var c;
if (di && di[n])
return;
// Compatiblity with 2.x
if (n == 'tablecontrols') {
each(["table","|","row_props","cell_props","|","row_before","row_after","delete_row","|","col_before","col_after","delete_col","|","split_cells","merge_cells"], function(n) {
n = t.createControl(n, cf);
if (n)
tb.add(n);
});
return;
}
c = t.createControl(n, cf);
if (c)
tb.add(c);
});
},
_addToolbars : function(c, o) {
var t = this, i, tb, ed = t.editor, s = t.settings, v, cf = ed.controlManager, di, n, h = [], a;
a = s.theme_advanced_toolbar_align.toLowerCase();
a = 'mce' + t._ufirst(a);
n = DOM.add(DOM.add(c, 'tr'), 'td', {'class' : 'mceToolbar ' + a});
if (!ed.getParam('accessibility_focus'))
h.push(DOM.createHTML('a', {href : '#', onfocus : 'tinyMCE.get(\'' + ed.id + '\').focus();'}, '<!-- IE -->'));
h.push(DOM.createHTML('a', {href : '#', accesskey : 'q', title : ed.getLang("advanced.toolbar_focus")}, '<!-- IE -->'));
// Create toolbar and add the controls
for (i=1; (v = s['theme_advanced_buttons' + i]); i++) {
tb = cf.createToolbar("toolbar" + i, {'class' : 'mceToolbarRow' + i});
if (s['theme_advanced_buttons' + i + '_add'])
v += ',' + s['theme_advanced_buttons' + i + '_add'];
if (s['theme_advanced_buttons' + i + '_add_before'])
v = s['theme_advanced_buttons' + i + '_add_before'] + ',' + v;
t._addControls(v, tb);
//n.appendChild(n = tb.render());
h.push(tb.renderHTML());
o.deltaHeight -= s.theme_advanced_row_height;
}
h.push(DOM.createHTML('a', {href : '#', accesskey : 'z', title : ed.getLang("advanced.toolbar_focus"), onfocus : 'tinyMCE.getInstanceById(\'' + ed.id + '\').focus();'}, '<!-- IE -->'));
DOM.setHTML(n, h.join(''));
},
_addStatusBar : function(tb, o) {
var n, t = this, ed = t.editor, s = t.settings, r, mf, me, td;
n = DOM.add(tb, 'tr');
n = td = DOM.add(n, 'td', {'class' : 'mceStatusbar'});
n = DOM.add(n, 'div', {id : ed.id + '_path_row'}, s.theme_advanced_path ? ed.translate('advanced.path') + ': ' : ' ');
DOM.add(n, 'a', {href : '#', accesskey : 'x'});
if (s.theme_advanced_resizing) {
DOM.add(td, 'a', {id : ed.id + '_resize', href : 'javascript:;', onclick : "return false;", 'class' : 'mceResize'});
if (s.theme_advanced_resizing_use_cookie) {
ed.onPostRender.add(function() {
var o = Cookie.getHash("TinyMCE_" + ed.id + "_size"), c = DOM.get(ed.id + '_tbl');
if (!o)
return;
t.resizeTo(o.cw, o.ch);
});
}
ed.onPostRender.add(function() {
Event.add(ed.id + '_resize', 'mousedown', function(e) {
var mouseMoveHandler1, mouseMoveHandler2,
mouseUpHandler1, mouseUpHandler2,
startX, startY, startWidth, startHeight, width, height, ifrElm;
function resizeOnMove(e) {
width = startWidth + (e.screenX - startX);
height = startHeight + (e.screenY - startY);
t.resizeTo(width, height);
};
function endResize(e) {
// Stop listening
Event.remove(DOM.doc, 'mousemove', mouseMoveHandler1);
Event.remove(ed.getDoc(), 'mousemove', mouseMoveHandler2);
Event.remove(DOM.doc, 'mouseup', mouseUpHandler1);
Event.remove(ed.getDoc(), 'mouseup', mouseUpHandler2);
// Store away the size
if (s.theme_advanced_resizing_use_cookie) {
Cookie.setHash("TinyMCE_" + ed.id + "_size", {
cw : width,
ch : height
});
}
};
e.preventDefault();
// Get the current rect size
startX = e.screenX;
startY = e.screenY;
ifrElm = DOM.get(t.editor.id + '_ifr');
startWidth = width = ifrElm.clientWidth;
startHeight = height = ifrElm.clientHeight;
// Register envent handlers
mouseMoveHandler1 = Event.add(DOM.doc, 'mousemove', resizeOnMove);
mouseMoveHandler2 = Event.add(ed.getDoc(), 'mousemove', resizeOnMove);
mouseUpHandler1 = Event.add(DOM.doc, 'mouseup', endResize);
mouseUpHandler2 = Event.add(ed.getDoc(), 'mouseup', endResize);
});
});
}
o.deltaHeight -= 21;
n = tb = null;
},
_nodeChanged : function(ed, cm, n, co, ob) {
var t = this, p, de = 0, v, c, s = t.settings, cl, fz, fn, formatNames, matches;
tinymce.each(t.stateControls, function(c) {
cm.setActive(c, ed.queryCommandState(t.controls[c][1]));
});
function getParent(name) {
var i, parents = ob.parents, func = name;
if (typeof(name) == 'string') {
func = function(node) {
return node.nodeName == name;
};
}
for (i = 0; i < parents.length; i++) {
if (func(parents[i]))
return parents[i];
}
};
cm.setActive('visualaid', ed.hasVisual);
cm.setDisabled('undo', !ed.undoManager.hasUndo() && !ed.typing);
cm.setDisabled('redo', !ed.undoManager.hasRedo());
cm.setDisabled('outdent', !ed.queryCommandState('Outdent'));
p = getParent('A');
if (c = cm.get('link')) {
if (!p || !p.name) {
c.setDisabled(!p && co);
c.setActive(!!p);
}
}
if (c = cm.get('unlink')) {
c.setDisabled(!p && co);
c.setActive(!!p && !p.name);
}
if (c = cm.get('anchor')) {
c.setActive(!!p && p.name);
}
p = getParent('IMG');
if (c = cm.get('image'))
c.setActive(!!p && n.className.indexOf('mceItem') == -1);
if (c = cm.get('styleselect')) {
t._importClasses();
formatNames = [];
each(c.items, function(item) {
formatNames.push(item.value);
});
matches = ed.formatter.matchAll(formatNames);
c.select(matches[0]);
}
if (c = cm.get('formatselect')) {
p = getParent(DOM.isBlock);
if (p)
c.select(p.nodeName.toLowerCase());
}
// Find out current fontSize, fontFamily and fontClass
getParent(function(n) {
if (n.nodeName === 'SPAN') {
if (!cl && n.className)
cl = n.className;
if (!fz && n.style.fontSize)
fz = n.style.fontSize;
if (!fn && n.style.fontFamily)
fn = n.style.fontFamily.replace(/[\"\']+/g, '').replace(/^([^,]+).*/, '$1').toLowerCase();
}
return false;
});
if (c = cm.get('fontselect')) {
c.select(function(v) {
return v.replace(/^([^,]+).*/, '$1').toLowerCase() == fn;
});
}
// Select font size
if (c = cm.get('fontsizeselect')) {
// Use computed style
if (s.theme_advanced_runtime_fontsize && !fz && !cl)
fz = ed.dom.getStyle(n, 'fontSize', true);
c.select(function(v) {
if (v.fontSize && v.fontSize === fz)
return true;
if (v['class'] && v['class'] === cl)
return true;
});
}
if (s.theme_advanced_path && s.theme_advanced_statusbar_location) {
p = DOM.get(ed.id + '_path') || DOM.add(ed.id + '_path_row', 'span', {id : ed.id + '_path'});
DOM.setHTML(p, '');
getParent(function(n) {
var na = n.nodeName.toLowerCase(), u, pi, ti = '';
/*if (n.getAttribute('_mce_bogus'))
return;
*/
// Ignore non element and hidden elements
if (n.nodeType != 1 || n.nodeName === 'BR' || (DOM.hasClass(n, 'mceItemHidden') || DOM.hasClass(n, 'mceItemRemoved')))
return;
// Fake name
if (v = DOM.getAttrib(n, 'mce_name'))
na = v;
// Handle prefix
if (tinymce.isIE && n.scopeName !== 'HTML')
na = n.scopeName + ':' + na;
// Remove internal prefix
na = na.replace(/mce\:/g, '');
// Handle node name
switch (na) {
case 'b':
na = 'strong';
break;
case 'i':
na = 'em';
break;
case 'img':
if (v = DOM.getAttrib(n, 'src'))
ti += 'src: ' + v + ' ';
break;
case 'a':
if (v = DOM.getAttrib(n, 'name')) {
ti += 'name: ' + v + ' ';
na += '#' + v;
}
if (v = DOM.getAttrib(n, 'href'))
ti += 'href: ' + v + ' ';
break;
case 'font':
if (v = DOM.getAttrib(n, 'face'))
ti += 'font: ' + v + ' ';
if (v = DOM.getAttrib(n, 'size'))
ti += 'size: ' + v + ' ';
if (v = DOM.getAttrib(n, 'color'))
ti += 'color: ' + v + ' ';
break;
case 'span':
if (v = DOM.getAttrib(n, 'style'))
ti += 'style: ' + v + ' ';
break;
}
if (v = DOM.getAttrib(n, 'id'))
ti += 'id: ' + v + ' ';
if (v = n.className) {
v = v.replace(/\b\s*(webkit|mce|Apple-)\w+\s*\b/g, '')
if (v) {
ti += 'class: ' + v + ' ';
if (DOM.isBlock(n) || na == 'img' || na == 'span')
na += '.' + v;
}
}
na = na.replace(/(html:)/g, '');
na = {name : na, node : n, title : ti};
t.onResolveName.dispatch(t, na);
ti = na.title;
na = na.name;
//u = "javascript:tinymce.EditorManager.get('" + ed.id + "').theme._sel('" + (de++) + "');";
pi = DOM.create('a', {'href' : "javascript:;", onmousedown : "return false;", title : ti, 'class' : 'mcePath_' + (de++)}, na);
if (p.hasChildNodes()) {
p.insertBefore(DOM.doc.createTextNode(' \u00bb '), p.firstChild);
p.insertBefore(pi, p.firstChild);
} else
p.appendChild(pi);
}, ed.getBody());
}
},
// Commands gets called by execCommand
_sel : function(v) {
this.editor.execCommand('mceSelectNodeDepth', false, v);
},
_mceInsertAnchor : function(ui, v) {
var ed = this.editor;
ed.windowManager.open({
url : this.url + '/anchor.htm',
width : 320 + parseInt(ed.getLang('advanced.anchor_delta_width', 0)),
height : 90 + parseInt(ed.getLang('advanced.anchor_delta_height', 0)),
inline : true
}, {
theme_url : this.url
});
},
_mceCharMap : function() {
var ed = this.editor;
ed.windowManager.open({
url : this.url + '/charmap.htm',
width : 550 + parseInt(ed.getLang('advanced.charmap_delta_width', 0)),
height : 250 + parseInt(ed.getLang('advanced.charmap_delta_height', 0)),
inline : true
}, {
theme_url : this.url
});
},
_mceHelp : function() {
var ed = this.editor;
ed.windowManager.open({
url : this.url + '/about.htm',
width : 480,
height : 380,
inline : true
}, {
theme_url : this.url
});
},
_mceColorPicker : function(u, v) {
var ed = this.editor;
v = v || {};
ed.windowManager.open({
url : this.url + '/color_picker.htm',
width : 375 + parseInt(ed.getLang('advanced.colorpicker_delta_width', 0)),
height : 250 + parseInt(ed.getLang('advanced.colorpicker_delta_height', 0)),
close_previous : false,
inline : true
}, {
input_color : v.color,
func : v.func,
theme_url : this.url
});
},
_mceCodeEditor : function(ui, val) {
var ed = this.editor;
ed.windowManager.open({
url : this.url + '/source_editor.htm',
width : parseInt(ed.getParam("theme_advanced_source_editor_width", 720)),
height : parseInt(ed.getParam("theme_advanced_source_editor_height", 580)),
inline : true,
resizable : true,
maximizable : true
}, {
theme_url : this.url
});
},
_mceImage : function(ui, val) {
var ed = this.editor;
// Internal image object like a flash placeholder
if (ed.dom.getAttrib(ed.selection.getNode(), 'class').indexOf('mceItem') != -1)
return;
ed.windowManager.open({
url : this.url + '/image.htm',
width : 355 + parseInt(ed.getLang('advanced.image_delta_width', 0)),
height : 275 + parseInt(ed.getLang('advanced.image_delta_height', 0)),
inline : true
}, {
theme_url : this.url
});
},
_mceLink : function(ui, val) {
var ed = this.editor;
ed.windowManager.open({
url : this.url + '/link.htm',
width : 310 + parseInt(ed.getLang('advanced.link_delta_width', 0)),
height : 200 + parseInt(ed.getLang('advanced.link_delta_height', 0)),
inline : true
}, {
theme_url : this.url
});
},
_mceNewDocument : function() {
var ed = this.editor;
ed.windowManager.confirm('advanced.newdocument', function(s) {
if (s)
ed.execCommand('mceSetContent', false, '');
});
},
_mceForeColor : function() {
var t = this;
this._mceColorPicker(0, {
color: t.fgColor,
func : function(co) {
t.fgColor = co;
t.editor.execCommand('ForeColor', false, co);
}
});
},
_mceBackColor : function() {
var t = this;
this._mceColorPicker(0, {
color: t.bgColor,
func : function(co) {
t.bgColor = co;
t.editor.execCommand('HiliteColor', false, co);
}
});
},
_ufirst : function(s) {
return s.substring(0, 1).toUpperCase() + s.substring(1);
}
});
tinymce.ThemeManager.add('advanced', tinymce.themes.AdvancedTheme);
}(tinymce)); | JavaScript |
tinyMCE.addI18n('en.advanced_dlg',{
about_title:"About TinyMCE",
about_general:"About",
about_help:"Help",
about_license:"License",
about_plugins:"Plugins",
about_plugin:"Plugin",
about_author:"Author",
about_version:"Version",
about_loaded:"Loaded plugins",
anchor_title:"Insert/edit anchor",
anchor_name:"Anchor name",
code_title:"HTML Source Editor",
code_wordwrap:"Word wrap",
colorpicker_title:"Select a color",
colorpicker_picker_tab:"Picker",
colorpicker_picker_title:"Color picker",
colorpicker_palette_tab:"Palette",
colorpicker_palette_title:"Palette colors",
colorpicker_named_tab:"Named",
colorpicker_named_title:"Named colors",
colorpicker_color:"Color:",
colorpicker_name:"Name:",
charmap_title:"Select custom character",
image_title:"Insert/edit image",
image_src:"Image URL",
image_alt:"Image description",
image_list:"Image list",
image_border:"Border",
image_dimensions:"Dimensions",
image_vspace:"Vertical space",
image_hspace:"Horizontal space",
image_align:"Alignment",
image_align_baseline:"Baseline",
image_align_top:"Top",
image_align_middle:"Middle",
image_align_bottom:"Bottom",
image_align_texttop:"Text top",
image_align_textbottom:"Text bottom",
image_align_left:"Left",
image_align_right:"Right",
link_title:"Insert/edit link",
link_url:"Link URL",
link_target:"Target",
link_target_same:"Open link in the same window",
link_target_blank:"Open link in a new window",
link_titlefield:"Title",
link_is_email:"The URL you entered seems to be an email address, do you want to add the required mailto: prefix?",
link_is_external:"The URL you entered seems to external link, do you want to add the required http:// prefix?",
link_list:"Link list"
}); | JavaScript |
tinyMCE.addI18n('en.advanced',{
style_select:"Styles",
font_size:"Font size",
fontdefault:"Font family",
block:"Format",
paragraph:"Paragraph",
div:"Div",
address:"Address",
pre:"Preformatted",
h1:"Heading 1",
h2:"Heading 2",
h3:"Heading 3",
h4:"Heading 4",
h5:"Heading 5",
h6:"Heading 6",
blockquote:"Blockquote",
code:"Code",
samp:"Code sample",
dt:"Definition term ",
dd:"Definition description",
bold_desc:"Bold (Ctrl+B)",
italic_desc:"Italic (Ctrl+I)",
underline_desc:"Underline (Ctrl+U)",
striketrough_desc:"Strikethrough",
justifyleft_desc:"Align left",
justifycenter_desc:"Align center",
justifyright_desc:"Align right",
justifyfull_desc:"Align full",
bullist_desc:"Unordered list",
numlist_desc:"Ordered list",
outdent_desc:"Outdent",
indent_desc:"Indent",
undo_desc:"Undo (Ctrl+Z)",
redo_desc:"Redo (Ctrl+Y)",
link_desc:"Insert/edit link",
unlink_desc:"Unlink",
image_desc:"Insert/edit image",
cleanup_desc:"Cleanup messy code",
code_desc:"Edit HTML Source",
sub_desc:"Subscript",
sup_desc:"Superscript",
hr_desc:"Insert horizontal ruler",
removeformat_desc:"Remove formatting",
custom1_desc:"Your custom description here",
forecolor_desc:"Select text color",
backcolor_desc:"Select background color",
charmap_desc:"Insert custom character",
visualaid_desc:"Toggle guidelines/invisible elements",
anchor_desc:"Insert/edit anchor",
cut_desc:"Cut",
copy_desc:"Copy",
paste_desc:"Paste",
image_props_desc:"Image properties",
newdocument_desc:"New document",
help_desc:"Help",
blockquote_desc:"Blockquote",
clipboard_msg:"Copy/Cut/Paste is not available in Mozilla and Firefox.\r\nDo you want more information about this issue?",
path:"Path",
newdocument:"Are you sure you want clear all contents?",
toolbar_focus:"Jump to tool buttons - Alt+Q, Jump to editor - Alt-Z, Jump to element path - Alt-X",
more_colors:"More colors"
}); | JavaScript |
/**
* editor_template_src.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
(function() {
var DOM = tinymce.DOM;
// Tell it to load theme specific language pack(s)
tinymce.ThemeManager.requireLangPack('simple');
tinymce.create('tinymce.themes.SimpleTheme', {
init : function(ed, url) {
var t = this, states = ['Bold', 'Italic', 'Underline', 'Strikethrough', 'InsertUnorderedList', 'InsertOrderedList'], s = ed.settings;
t.editor = ed;
ed.onInit.add(function() {
ed.onNodeChange.add(function(ed, cm) {
tinymce.each(states, function(c) {
cm.get(c.toLowerCase()).setActive(ed.queryCommandState(c));
});
});
ed.dom.loadCSS(url + "/skins/" + s.skin + "/content.css");
});
DOM.loadCSS((s.editor_css ? ed.documentBaseURI.toAbsolute(s.editor_css) : '') || url + "/skins/" + s.skin + "/ui.css");
},
renderUI : function(o) {
var t = this, n = o.targetNode, ic, tb, ed = t.editor, cf = ed.controlManager, sc;
n = DOM.insertAfter(DOM.create('span', {id : ed.id + '_container', 'class' : 'mceEditor ' + ed.settings.skin + 'SimpleSkin'}), n);
n = sc = DOM.add(n, 'table', {cellPadding : 0, cellSpacing : 0, 'class' : 'mceLayout'});
n = tb = DOM.add(n, 'tbody');
// Create iframe container
n = DOM.add(tb, 'tr');
n = ic = DOM.add(DOM.add(n, 'td'), 'div', {'class' : 'mceIframeContainer'});
// Create toolbar container
n = DOM.add(DOM.add(tb, 'tr', {'class' : 'last'}), 'td', {'class' : 'mceToolbar mceLast', align : 'center'});
// Create toolbar
tb = t.toolbar = cf.createToolbar("tools1");
tb.add(cf.createButton('bold', {title : 'simple.bold_desc', cmd : 'Bold'}));
tb.add(cf.createButton('italic', {title : 'simple.italic_desc', cmd : 'Italic'}));
tb.add(cf.createButton('underline', {title : 'simple.underline_desc', cmd : 'Underline'}));
tb.add(cf.createButton('strikethrough', {title : 'simple.striketrough_desc', cmd : 'Strikethrough'}));
tb.add(cf.createSeparator());
tb.add(cf.createButton('undo', {title : 'simple.undo_desc', cmd : 'Undo'}));
tb.add(cf.createButton('redo', {title : 'simple.redo_desc', cmd : 'Redo'}));
tb.add(cf.createSeparator());
tb.add(cf.createButton('cleanup', {title : 'simple.cleanup_desc', cmd : 'mceCleanup'}));
tb.add(cf.createSeparator());
tb.add(cf.createButton('insertunorderedlist', {title : 'simple.bullist_desc', cmd : 'InsertUnorderedList'}));
tb.add(cf.createButton('insertorderedlist', {title : 'simple.numlist_desc', cmd : 'InsertOrderedList'}));
tb.renderTo(n);
return {
iframeContainer : ic,
editorContainer : ed.id + '_container',
sizeContainer : sc,
deltaHeight : -20
};
},
getInfo : function() {
return {
longname : 'Simple theme',
author : 'Moxiecode Systems AB',
authorurl : 'http://tinymce.moxiecode.com',
version : tinymce.majorVersion + "." + tinymce.minorVersion
}
}
});
tinymce.ThemeManager.add('simple', tinymce.themes.SimpleTheme);
})(); | JavaScript |
tinyMCE.addI18n('en.simple',{
bold_desc:"Bold (Ctrl+B)",
italic_desc:"Italic (Ctrl+I)",
underline_desc:"Underline (Ctrl+U)",
striketrough_desc:"Strikethrough",
bullist_desc:"Unordered list",
numlist_desc:"Ordered list",
undo_desc:"Undo (Ctrl+Z)",
redo_desc:"Redo (Ctrl+Y)",
cleanup_desc:"Cleanup messy code"
}); | JavaScript |
/**
* validate.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
/**
// String validation:
if (!Validator.isEmail('myemail'))
alert('Invalid email.');
// Form validation:
var f = document.forms['myform'];
if (!Validator.isEmail(f.myemail))
alert('Invalid email.');
*/
var Validator = {
isEmail : function(s) {
return this.test(s, '^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+@[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$');
},
isAbsUrl : function(s) {
return this.test(s, '^(news|telnet|nttp|file|http|ftp|https)://[-A-Za-z0-9\\.]+\\/?.*$');
},
isSize : function(s) {
return this.test(s, '^[0-9]+(%|in|cm|mm|em|ex|pt|pc|px)?$');
},
isId : function(s) {
return this.test(s, '^[A-Za-z_]([A-Za-z0-9_])*$');
},
isEmpty : function(s) {
var nl, i;
if (s.nodeName == 'SELECT' && s.selectedIndex < 1)
return true;
if (s.type == 'checkbox' && !s.checked)
return true;
if (s.type == 'radio') {
for (i=0, nl = s.form.elements; i<nl.length; i++) {
if (nl[i].type == "radio" && nl[i].name == s.name && nl[i].checked)
return false;
}
return true;
}
return new RegExp('^\\s*$').test(s.nodeType == 1 ? s.value : s);
},
isNumber : function(s, d) {
return !isNaN(s.nodeType == 1 ? s.value : s) && (!d || !this.test(s, '^-?[0-9]*\\.[0-9]*$'));
},
test : function(s, p) {
s = s.nodeType == 1 ? s.value : s;
return s == '' || new RegExp(p).test(s);
}
};
var AutoValidator = {
settings : {
id_cls : 'id',
int_cls : 'int',
url_cls : 'url',
number_cls : 'number',
email_cls : 'email',
size_cls : 'size',
required_cls : 'required',
invalid_cls : 'invalid',
min_cls : 'min',
max_cls : 'max'
},
init : function(s) {
var n;
for (n in s)
this.settings[n] = s[n];
},
validate : function(f) {
var i, nl, s = this.settings, c = 0;
nl = this.tags(f, 'label');
for (i=0; i<nl.length; i++)
this.removeClass(nl[i], s.invalid_cls);
c += this.validateElms(f, 'input');
c += this.validateElms(f, 'select');
c += this.validateElms(f, 'textarea');
return c == 3;
},
invalidate : function(n) {
this.mark(n.form, n);
},
reset : function(e) {
var t = ['label', 'input', 'select', 'textarea'];
var i, j, nl, s = this.settings;
if (e == null)
return;
for (i=0; i<t.length; i++) {
nl = this.tags(e.form ? e.form : e, t[i]);
for (j=0; j<nl.length; j++)
this.removeClass(nl[j], s.invalid_cls);
}
},
validateElms : function(f, e) {
var nl, i, n, s = this.settings, st = true, va = Validator, v;
nl = this.tags(f, e);
for (i=0; i<nl.length; i++) {
n = nl[i];
this.removeClass(n, s.invalid_cls);
if (this.hasClass(n, s.required_cls) && va.isEmpty(n))
st = this.mark(f, n);
if (this.hasClass(n, s.number_cls) && !va.isNumber(n))
st = this.mark(f, n);
if (this.hasClass(n, s.int_cls) && !va.isNumber(n, true))
st = this.mark(f, n);
if (this.hasClass(n, s.url_cls) && !va.isAbsUrl(n))
st = this.mark(f, n);
if (this.hasClass(n, s.email_cls) && !va.isEmail(n))
st = this.mark(f, n);
if (this.hasClass(n, s.size_cls) && !va.isSize(n))
st = this.mark(f, n);
if (this.hasClass(n, s.id_cls) && !va.isId(n))
st = this.mark(f, n);
if (this.hasClass(n, s.min_cls, true)) {
v = this.getNum(n, s.min_cls);
if (isNaN(v) || parseInt(n.value) < parseInt(v))
st = this.mark(f, n);
}
if (this.hasClass(n, s.max_cls, true)) {
v = this.getNum(n, s.max_cls);
if (isNaN(v) || parseInt(n.value) > parseInt(v))
st = this.mark(f, n);
}
}
return st;
},
hasClass : function(n, c, d) {
return new RegExp('\\b' + c + (d ? '[0-9]+' : '') + '\\b', 'g').test(n.className);
},
getNum : function(n, c) {
c = n.className.match(new RegExp('\\b' + c + '([0-9]+)\\b', 'g'))[0];
c = c.replace(/[^0-9]/g, '');
return c;
},
addClass : function(n, c, b) {
var o = this.removeClass(n, c);
n.className = b ? c + (o != '' ? (' ' + o) : '') : (o != '' ? (o + ' ') : '') + c;
},
removeClass : function(n, c) {
c = n.className.replace(new RegExp("(^|\\s+)" + c + "(\\s+|$)"), ' ');
return n.className = c != ' ' ? c : '';
},
tags : function(f, s) {
return f.getElementsByTagName(s);
},
mark : function(f, n) {
var s = this.settings;
this.addClass(n, s.invalid_cls);
this.markLabels(f, n, s.invalid_cls);
return false;
},
markLabels : function(f, n, ic) {
var nl, i;
nl = this.tags(f, "label");
for (i=0; i<nl.length; i++) {
if (nl[i].getAttribute("for") == n.id || nl[i].htmlFor == n.id)
this.addClass(nl[i], ic);
}
return null;
}
};
| JavaScript |
/**
* mctabs.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
function MCTabs() {
this.settings = [];
};
MCTabs.prototype.init = function(settings) {
this.settings = settings;
};
MCTabs.prototype.getParam = function(name, default_value) {
var value = null;
value = (typeof(this.settings[name]) == "undefined") ? default_value : this.settings[name];
// Fix bool values
if (value == "true" || value == "false")
return (value == "true");
return value;
};
MCTabs.prototype.displayTab = function(tab_id, panel_id) {
var panelElm, panelContainerElm, tabElm, tabContainerElm, selectionClass, nodes, i;
panelElm= document.getElementById(panel_id);
panelContainerElm = panelElm ? panelElm.parentNode : null;
tabElm = document.getElementById(tab_id);
tabContainerElm = tabElm ? tabElm.parentNode : null;
selectionClass = this.getParam('selection_class', 'current');
if (tabElm && tabContainerElm) {
nodes = tabContainerElm.childNodes;
// Hide all other tabs
for (i = 0; i < nodes.length; i++) {
if (nodes[i].nodeName == "LI")
nodes[i].className = '';
}
// Show selected tab
tabElm.className = 'current';
}
if (panelElm && panelContainerElm) {
nodes = panelContainerElm.childNodes;
// Hide all other panels
for (i = 0; i < nodes.length; i++) {
if (nodes[i].nodeName == "DIV")
nodes[i].className = 'panel';
}
// Show selected panel
panelElm.className = 'current';
}
};
MCTabs.prototype.getAnchor = function() {
var pos, url = document.location.href;
if ((pos = url.lastIndexOf('#')) != -1)
return url.substring(pos + 1);
return "";
};
// Global instance
var mcTabs = new MCTabs();
| JavaScript |
/**
* editable_selects.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
var TinyMCE_EditableSelects = {
editSelectElm : null,
init : function() {
var nl = document.getElementsByTagName("select"), i, d = document, o;
for (i=0; i<nl.length; i++) {
if (nl[i].className.indexOf('mceEditableSelect') != -1) {
o = new Option('(value)', '__mce_add_custom__');
o.className = 'mceAddSelectValue';
nl[i].options[nl[i].options.length] = o;
nl[i].onchange = TinyMCE_EditableSelects.onChangeEditableSelect;
}
}
},
onChangeEditableSelect : function(e) {
var d = document, ne, se = window.event ? window.event.srcElement : e.target;
if (se.options[se.selectedIndex].value == '__mce_add_custom__') {
ne = d.createElement("input");
ne.id = se.id + "_custom";
ne.name = se.name + "_custom";
ne.type = "text";
ne.style.width = se.offsetWidth + 'px';
se.parentNode.insertBefore(ne, se);
se.style.display = 'none';
ne.focus();
ne.onblur = TinyMCE_EditableSelects.onBlurEditableSelectInput;
ne.onkeydown = TinyMCE_EditableSelects.onKeyDown;
TinyMCE_EditableSelects.editSelectElm = se;
}
},
onBlurEditableSelectInput : function() {
var se = TinyMCE_EditableSelects.editSelectElm;
if (se) {
if (se.previousSibling.value != '') {
addSelectValue(document.forms[0], se.id, se.previousSibling.value, se.previousSibling.value);
selectByValue(document.forms[0], se.id, se.previousSibling.value);
} else
selectByValue(document.forms[0], se.id, '');
se.style.display = 'inline';
se.parentNode.removeChild(se.previousSibling);
TinyMCE_EditableSelects.editSelectElm = null;
}
},
onKeyDown : function(e) {
e = e || window.event;
if (e.keyCode == 13)
TinyMCE_EditableSelects.onBlurEditableSelectInput();
}
};
| JavaScript |
/**
* form_utils.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
var themeBaseURL = tinyMCEPopup.editor.baseURI.toAbsolute('themes/' + tinyMCEPopup.getParam("theme"));
function getColorPickerHTML(id, target_form_element) {
var h = "";
h += '<a id="' + id + '_link" href="javascript:;" onclick="tinyMCEPopup.pickColor(event,\'' + target_form_element +'\');" onmousedown="return false;" class="pickcolor">';
h += '<span id="' + id + '" title="' + tinyMCEPopup.getLang('browse') + '"> </span></a>';
return h;
}
function updateColor(img_id, form_element_id) {
document.getElementById(img_id).style.backgroundColor = document.forms[0].elements[form_element_id].value;
}
function setBrowserDisabled(id, state) {
var img = document.getElementById(id);
var lnk = document.getElementById(id + "_link");
if (lnk) {
if (state) {
lnk.setAttribute("realhref", lnk.getAttribute("href"));
lnk.removeAttribute("href");
tinyMCEPopup.dom.addClass(img, 'disabled');
} else {
if (lnk.getAttribute("realhref"))
lnk.setAttribute("href", lnk.getAttribute("realhref"));
tinyMCEPopup.dom.removeClass(img, 'disabled');
}
}
}
function getBrowserHTML(id, target_form_element, type, prefix) {
var option = prefix + "_" + type + "_browser_callback", cb, html;
cb = tinyMCEPopup.getParam(option, tinyMCEPopup.getParam("file_browser_callback"));
if (!cb)
return "";
html = "";
html += '<a id="' + id + '_link" href="javascript:openBrowser(\'' + id + '\',\'' + target_form_element + '\', \'' + type + '\',\'' + option + '\');" onmousedown="return false;" class="browse">';
html += '<span id="' + id + '" title="' + tinyMCEPopup.getLang('browse') + '"> </span></a>';
return html;
}
function openBrowser(img_id, target_form_element, type, option) {
var img = document.getElementById(img_id);
if (img.className != "mceButtonDisabled")
tinyMCEPopup.openBrowser(target_form_element, type, option);
}
function selectByValue(form_obj, field_name, value, add_custom, ignore_case) {
if (!form_obj || !form_obj.elements[field_name])
return;
var sel = form_obj.elements[field_name];
var found = false;
for (var i=0; i<sel.options.length; i++) {
var option = sel.options[i];
if (option.value == value || (ignore_case && option.value.toLowerCase() == value.toLowerCase())) {
option.selected = true;
found = true;
} else
option.selected = false;
}
if (!found && add_custom && value != '') {
var option = new Option(value, value);
option.selected = true;
sel.options[sel.options.length] = option;
sel.selectedIndex = sel.options.length - 1;
}
return found;
}
function getSelectValue(form_obj, field_name) {
var elm = form_obj.elements[field_name];
if (elm == null || elm.options == null || elm.selectedIndex === -1)
return "";
return elm.options[elm.selectedIndex].value;
}
function addSelectValue(form_obj, field_name, name, value) {
var s = form_obj.elements[field_name];
var o = new Option(name, value);
s.options[s.options.length] = o;
}
function addClassesToList(list_id, specific_option) {
// Setup class droplist
var styleSelectElm = document.getElementById(list_id);
var styles = tinyMCEPopup.getParam('theme_advanced_styles', false);
styles = tinyMCEPopup.getParam(specific_option, styles);
if (styles) {
var stylesAr = styles.split(';');
for (var i=0; i<stylesAr.length; i++) {
if (stylesAr != "") {
var key, value;
key = stylesAr[i].split('=')[0];
value = stylesAr[i].split('=')[1];
styleSelectElm.options[styleSelectElm.length] = new Option(key, value);
}
}
} else {
tinymce.each(tinyMCEPopup.editor.dom.getClasses(), function(o) {
styleSelectElm.options[styleSelectElm.length] = new Option(o.title || o['class'], o['class']);
});
}
}
function isVisible(element_id) {
var elm = document.getElementById(element_id);
return elm && elm.style.display != "none";
}
function convertRGBToHex(col) {
var re = new RegExp("rgb\\s*\\(\\s*([0-9]+).*,\\s*([0-9]+).*,\\s*([0-9]+).*\\)", "gi");
var rgb = col.replace(re, "$1,$2,$3").split(',');
if (rgb.length == 3) {
r = parseInt(rgb[0]).toString(16);
g = parseInt(rgb[1]).toString(16);
b = parseInt(rgb[2]).toString(16);
r = r.length == 1 ? '0' + r : r;
g = g.length == 1 ? '0' + g : g;
b = b.length == 1 ? '0' + b : b;
return "#" + r + g + b;
}
return col;
}
function convertHexToRGB(col) {
if (col.indexOf('#') != -1) {
col = col.replace(new RegExp('[^0-9A-F]', 'gi'), '');
r = parseInt(col.substring(0, 2), 16);
g = parseInt(col.substring(2, 4), 16);
b = parseInt(col.substring(4, 6), 16);
return "rgb(" + r + "," + g + "," + b + ")";
}
return col;
}
function trimSize(size) {
return size.replace(/([0-9\.]+)px|(%|in|cm|mm|em|ex|pt|pc)/, '$1$2');
}
function getCSSSize(size) {
size = trimSize(size);
if (size == "")
return "";
// Add px
if (/^[0-9]+$/.test(size))
size += 'px';
return size;
}
function getStyle(elm, attrib, style) {
var val = tinyMCEPopup.dom.getAttrib(elm, attrib);
if (val != '')
return '' + val;
if (typeof(style) == 'undefined')
style = attrib;
return tinyMCEPopup.dom.getStyle(elm, style);
}
| JavaScript |
/**
* jqPlot
* Pure JavaScript plotting plugin using jQuery
*
* Version: 1.0.8
* Revision: 1250
*
* Copyright (c) 2009-2013 Chris Leonello
* jqPlot is currently available for use in all personal or commercial projects
* under both the MIT (http://www.opensource.org/licenses/mit-license.php) and GPL
* version 2.0 (http://www.gnu.org/licenses/gpl-2.0.html) licenses. This means that you can
* choose the license that best suits your project and use it accordingly.
*
* Although not required, the author would appreciate an email letting him
* know of any substantial use of jqPlot. You can reach the author at:
* chris at jqplot dot com or see http://www.jqplot.com/info.php .
*
* If you are feeling kind and generous, consider supporting the project by
* making a donation at: http://www.jqplot.com/donate.php .
*
* sprintf functions contained in jqplot.sprintf.js by Ash Searle:
*
* version 2007.04.27
* author Ash Searle
* http://hexmen.com/blog/2007/03/printf-sprintf/
* http://hexmen.com/js/sprintf.js
* The author (Ash Searle) has placed this code in the public domain:
* "This code is unrestricted: you are free to use it however you like."
*
*/
(function($) {
// class $.jqplot.EnhancedLegendRenderer
// Legend renderer which can specify the number of rows and/or columns in the legend.
$.jqplot.EnhancedLegendRenderer = function(){
$.jqplot.TableLegendRenderer.call(this);
};
$.jqplot.EnhancedLegendRenderer.prototype = new $.jqplot.TableLegendRenderer();
$.jqplot.EnhancedLegendRenderer.prototype.constructor = $.jqplot.EnhancedLegendRenderer;
// called with scope of legend.
$.jqplot.EnhancedLegendRenderer.prototype.init = function(options) {
// prop: numberRows
// Maximum number of rows in the legend. 0 or null for unlimited.
this.numberRows = null;
// prop: numberColumns
// Maximum number of columns in the legend. 0 or null for unlimited.
this.numberColumns = null;
// prop: seriesToggle
// false to not enable series on/off toggling on the legend.
// true or a fadein/fadeout speed (number of milliseconds or 'fast', 'normal', 'slow')
// to enable show/hide of series on click of legend item.
this.seriesToggle = 'normal';
// prop: seriesToggleReplot
// True to replot the chart after toggling series on/off.
// This will set the series show property to false.
// This allows for rescaling or other maniplation of chart.
// Set to an options object (e.g. {resetAxes: true}) for replot options.
this.seriesToggleReplot = false;
// prop: disableIEFading
// true to toggle series with a show/hide method only and not allow fading in/out.
// This is to overcome poor performance of fade in some versions of IE.
this.disableIEFading = true;
$.extend(true, this, options);
if (this.seriesToggle) {
$.jqplot.postDrawHooks.push(postDraw);
}
};
// called with scope of legend
$.jqplot.EnhancedLegendRenderer.prototype.draw = function(offsets, plot) {
var legend = this;
if (this.show) {
var series = this._series;
var s;
var ss = 'position:absolute;';
ss += (this.background) ? 'background:'+this.background+';' : '';
ss += (this.border) ? 'border:'+this.border+';' : '';
ss += (this.fontSize) ? 'font-size:'+this.fontSize+';' : '';
ss += (this.fontFamily) ? 'font-family:'+this.fontFamily+';' : '';
ss += (this.textColor) ? 'color:'+this.textColor+';' : '';
ss += (this.marginTop != null) ? 'margin-top:'+this.marginTop+';' : '';
ss += (this.marginBottom != null) ? 'margin-bottom:'+this.marginBottom+';' : '';
ss += (this.marginLeft != null) ? 'margin-left:'+this.marginLeft+';' : '';
ss += (this.marginRight != null) ? 'margin-right:'+this.marginRight+';' : '';
this._elem = $('<table class="jqplot-table-legend" style="'+ss+'"></table>');
if (this.seriesToggle) {
this._elem.css('z-index', '3');
}
var pad = false,
reverse = false,
nr, nc;
if (this.numberRows) {
nr = this.numberRows;
if (!this.numberColumns){
nc = Math.ceil(series.length/nr);
}
else{
nc = this.numberColumns;
}
}
else if (this.numberColumns) {
nc = this.numberColumns;
nr = Math.ceil(series.length/this.numberColumns);
}
else {
nr = series.length;
nc = 1;
}
var i, j, tr, td1, td2, lt, rs, div, div0, div1;
var idx = 0;
// check to see if we need to reverse
for (i=series.length-1; i>=0; i--) {
if (nc == 1 && series[i]._stack || series[i].renderer.constructor == $.jqplot.BezierCurveRenderer){
reverse = true;
}
}
for (i=0; i<nr; i++) {
tr = $(document.createElement('tr'));
tr.addClass('jqplot-table-legend');
if (reverse){
tr.prependTo(this._elem);
}
else{
tr.appendTo(this._elem);
}
for (j=0; j<nc; j++) {
if (idx < series.length && (series[idx].show || series[idx].showLabel)){
s = series[idx];
lt = this.labels[idx] || s.label.toString();
if (lt) {
var color = s.color;
if (!reverse){
if (i>0){
pad = true;
}
else{
pad = false;
}
}
else{
if (i == nr -1){
pad = false;
}
else{
pad = true;
}
}
rs = (pad) ? this.rowSpacing : '0';
td1 = $(document.createElement('td'));
td1.addClass('jqplot-table-legend jqplot-table-legend-swatch');
td1.css({textAlign: 'center', paddingTop: rs});
div0 = $(document.createElement('div'));
div0.addClass('jqplot-table-legend-swatch-outline');
div1 = $(document.createElement('div'));
div1.addClass('jqplot-table-legend-swatch');
div1.css({backgroundColor: color, borderColor: color});
td1.append(div0.append(div1));
td2 = $(document.createElement('td'));
td2.addClass('jqplot-table-legend jqplot-table-legend-label');
td2.css('paddingTop', rs);
// td1 = $('<td class="jqplot-table-legend" style="text-align:center;padding-top:'+rs+';">'+
// '<div><div class="jqplot-table-legend-swatch" style="background-color:'+color+';border-color:'+color+';"></div>'+
// '</div></td>');
// td2 = $('<td class="jqplot-table-legend" style="padding-top:'+rs+';"></td>');
if (this.escapeHtml){
td2.text(lt);
}
else {
td2.html(lt);
}
if (reverse) {
if (this.showLabels) {td2.prependTo(tr);}
if (this.showSwatches) {td1.prependTo(tr);}
}
else {
if (this.showSwatches) {td1.appendTo(tr);}
if (this.showLabels) {td2.appendTo(tr);}
}
if (this.seriesToggle) {
// add an overlay for clicking series on/off
// div0 = $(document.createElement('div'));
// div0.addClass('jqplot-table-legend-overlay');
// div0.css({position:'relative', left:0, top:0, height:'100%', width:'100%'});
// tr.append(div0);
var speed;
if (typeof(this.seriesToggle) === 'string' || typeof(this.seriesToggle) === 'number') {
if (!$.jqplot.use_excanvas || !this.disableIEFading) {
speed = this.seriesToggle;
}
}
if (this.showSwatches) {
td1.bind('click', {series:s, speed:speed, plot: plot, replot:this.seriesToggleReplot}, handleToggle);
td1.addClass('jqplot-seriesToggle');
}
if (this.showLabels) {
td2.bind('click', {series:s, speed:speed, plot: plot, replot:this.seriesToggleReplot}, handleToggle);
td2.addClass('jqplot-seriesToggle');
}
// for series that are already hidden, add the hidden class
if (!s.show && s.showLabel) {
td1.addClass('jqplot-series-hidden');
td2.addClass('jqplot-series-hidden');
}
}
pad = true;
}
}
idx++;
}
td1 = td2 = div0 = div1 = null;
}
}
return this._elem;
};
var handleToggle = function (ev) {
var d = ev.data,
s = d.series,
replot = d.replot,
plot = d.plot,
speed = d.speed,
sidx = s.index,
showing = false;
if (s.canvas._elem.is(':hidden') || !s.show) {
showing = true;
}
var doLegendToggle = function() {
if (replot) {
var opts = {};
if ($.isPlainObject(replot)) {
$.extend(true, opts, replot);
}
plot.replot(opts);
// if showing, there was no canvas element to fade in, so hide here
// and then do a fade in.
if (showing && speed) {
var s = plot.series[sidx];
if (s.shadowCanvas._elem) {
s.shadowCanvas._elem.hide().fadeIn(speed);
}
s.canvas._elem.hide().fadeIn(speed);
s.canvas._elem.nextAll('.jqplot-point-label.jqplot-series-'+s.index).hide().fadeIn(speed);
}
}
else {
var s = plot.series[sidx];
if (s.canvas._elem.is(':hidden') || !s.show) {
// Not sure if there is a better way to check for showSwatches and showLabels === true.
// Test for "undefined" since default values for both showSwatches and showLables is true.
if (typeof plot.options.legend.showSwatches === 'undefined' || plot.options.legend.showSwatches === true) {
plot.legend._elem.find('td').eq(sidx * 2).addClass('jqplot-series-hidden');
}
if (typeof plot.options.legend.showLabels === 'undefined' || plot.options.legend.showLabels === true) {
plot.legend._elem.find('td').eq((sidx * 2) + 1).addClass('jqplot-series-hidden');
}
}
else {
if (typeof plot.options.legend.showSwatches === 'undefined' || plot.options.legend.showSwatches === true) {
plot.legend._elem.find('td').eq(sidx * 2).removeClass('jqplot-series-hidden');
}
if (typeof plot.options.legend.showLabels === 'undefined' || plot.options.legend.showLabels === true) {
plot.legend._elem.find('td').eq((sidx * 2) + 1).removeClass('jqplot-series-hidden');
}
}
}
};
s.toggleDisplay(ev, doLegendToggle);
};
// called with scope of plot.
var postDraw = function () {
if (this.legend.renderer.constructor == $.jqplot.EnhancedLegendRenderer && this.legend.seriesToggle){
var e = this.legend._elem.detach();
this.eventCanvas._elem.after(e);
}
};
})(jQuery);
| JavaScript |
/**
* jqPlot
* Pure JavaScript plotting plugin using jQuery
*
* Version: 1.0.8
* Revision: 1250
*
* Copyright (c) 2009-2013 Chris Leonello
* jqPlot is currently available for use in all personal or commercial projects
* under both the MIT (http://www.opensource.org/licenses/mit-license.php) and GPL
* version 2.0 (http://www.gnu.org/licenses/gpl-2.0.html) licenses. This means that you can
* choose the license that best suits your project and use it accordingly.
*
* Although not required, the author would appreciate an email letting him
* know of any substantial use of jqPlot. You can reach the author at:
* chris at jqplot dot com or see http://www.jqplot.com/info.php .
*
* If you are feeling kind and generous, consider supporting the project by
* making a donation at: http://www.jqplot.com/donate.php .
*
* sprintf functions contained in jqplot.sprintf.js by Ash Searle:
*
* version 2007.04.27
* author Ash Searle
* http://hexmen.com/blog/2007/03/printf-sprintf/
* http://hexmen.com/js/sprintf.js
* The author (Ash Searle) has placed this code in the public domain:
* "This code is unrestricted: you are free to use it however you like."
*
*/
(function($) {
/**
* Class: $.jqplot.CanvasAxisTickRenderer
* Renderer to draw axis ticks with a canvas element to support advanced
* featrues such as rotated text. This renderer uses a separate rendering engine
* to draw the text on the canvas. Two modes of rendering the text are available.
* If the browser has native font support for canvas fonts (currently Mozila 3.5
* and Safari 4), you can enable text rendering with the canvas fillText method.
* You do so by setting the "enableFontSupport" option to true.
*
* Browsers lacking native font support will have the text drawn on the canvas
* using the Hershey font metrics. Even if the "enableFontSupport" option is true
* non-supporting browsers will still render with the Hershey font.
*/
$.jqplot.CanvasAxisTickRenderer = function(options) {
// Group: Properties
// prop: mark
// tick mark on the axis. One of 'inside', 'outside', 'cross', '' or null.
this.mark = 'outside';
// prop: showMark
// whether or not to show the mark on the axis.
this.showMark = true;
// prop: showGridline
// whether or not to draw the gridline on the grid at this tick.
this.showGridline = true;
// prop: isMinorTick
// if this is a minor tick.
this.isMinorTick = false;
// prop: angle
// angle of text, measured clockwise from x axis.
this.angle = 0;
// prop: markSize
// Length of the tick marks in pixels. For 'cross' style, length
// will be stoked above and below axis, so total length will be twice this.
this.markSize = 4;
// prop: show
// whether or not to show the tick (mark and label).
this.show = true;
// prop: showLabel
// whether or not to show the label.
this.showLabel = true;
// prop: labelPosition
// 'auto', 'start', 'middle' or 'end'.
// Whether tick label should be positioned so the start, middle, or end
// of the tick mark.
this.labelPosition = 'auto';
this.label = '';
this.value = null;
this._styles = {};
// prop: formatter
// A class of a formatter for the tick text.
// The default $.jqplot.DefaultTickFormatter uses sprintf.
this.formatter = $.jqplot.DefaultTickFormatter;
// prop: formatString
// string passed to the formatter.
this.formatString = '';
// prop: prefix
// String to prepend to the tick label.
// Prefix is prepended to the formatted tick label.
this.prefix = '';
// prop: fontFamily
// css spec for the font-family css attribute.
this.fontFamily = '"Trebuchet MS", Arial, Helvetica, sans-serif';
// prop: fontSize
// CSS spec for font size.
this.fontSize = '10pt';
// prop: fontWeight
// CSS spec for fontWeight
this.fontWeight = 'normal';
// prop: fontStretch
// Multiplier to condense or expand font width.
// Applies only to browsers which don't support canvas native font rendering.
this.fontStretch = 1.0;
// prop: textColor
// css spec for the color attribute.
this.textColor = '#666666';
// prop: enableFontSupport
// true to turn on native canvas font support in Mozilla 3.5+ and Safari 4+.
// If true, tick label will be drawn with canvas tag native support for fonts.
// If false, tick label will be drawn with Hershey font metrics.
this.enableFontSupport = true;
// prop: pt2px
// Point to pixel scaling factor, used for computing height of bounding box
// around a label. The labels text renderer has a default setting of 1.4, which
// should be suitable for most fonts. Leave as null to use default. If tops of
// letters appear clipped, increase this. If bounding box seems too big, decrease.
// This is an issue only with the native font renderering capabilities of Mozilla
// 3.5 and Safari 4 since they do not provide a method to determine the font height.
this.pt2px = null;
this._elem;
this._ctx;
this._plotWidth;
this._plotHeight;
this._plotDimensions = {height:null, width:null};
$.extend(true, this, options);
var ropts = {fontSize:this.fontSize, fontWeight:this.fontWeight, fontStretch:this.fontStretch, fillStyle:this.textColor, angle:this.getAngleRad(), fontFamily:this.fontFamily};
if (this.pt2px) {
ropts.pt2px = this.pt2px;
}
if (this.enableFontSupport) {
if ($.jqplot.support_canvas_text()) {
this._textRenderer = new $.jqplot.CanvasFontRenderer(ropts);
}
else {
this._textRenderer = new $.jqplot.CanvasTextRenderer(ropts);
}
}
else {
this._textRenderer = new $.jqplot.CanvasTextRenderer(ropts);
}
};
$.jqplot.CanvasAxisTickRenderer.prototype.init = function(options) {
$.extend(true, this, options);
this._textRenderer.init({fontSize:this.fontSize, fontWeight:this.fontWeight, fontStretch:this.fontStretch, fillStyle:this.textColor, angle:this.getAngleRad(), fontFamily:this.fontFamily});
};
// return width along the x axis
// will check first to see if an element exists.
// if not, will return the computed text box width.
$.jqplot.CanvasAxisTickRenderer.prototype.getWidth = function(ctx) {
if (this._elem) {
return this._elem.outerWidth(true);
}
else {
var tr = this._textRenderer;
var l = tr.getWidth(ctx);
var h = tr.getHeight(ctx);
var w = Math.abs(Math.sin(tr.angle)*h) + Math.abs(Math.cos(tr.angle)*l);
return w;
}
};
// return height along the y axis.
$.jqplot.CanvasAxisTickRenderer.prototype.getHeight = function(ctx) {
if (this._elem) {
return this._elem.outerHeight(true);
}
else {
var tr = this._textRenderer;
var l = tr.getWidth(ctx);
var h = tr.getHeight(ctx);
var w = Math.abs(Math.cos(tr.angle)*h) + Math.abs(Math.sin(tr.angle)*l);
return w;
}
};
// return top.
$.jqplot.CanvasAxisTickRenderer.prototype.getTop = function(ctx) {
if (this._elem) {
return this._elem.position().top;
}
else {
return null;
}
};
$.jqplot.CanvasAxisTickRenderer.prototype.getAngleRad = function() {
var a = this.angle * Math.PI/180;
return a;
};
$.jqplot.CanvasAxisTickRenderer.prototype.setTick = function(value, axisName, isMinor) {
this.value = value;
if (isMinor) {
this.isMinorTick = true;
}
return this;
};
$.jqplot.CanvasAxisTickRenderer.prototype.draw = function(ctx, plot) {
if (!this.label) {
this.label = this.prefix + this.formatter(this.formatString, this.value);
}
// Memory Leaks patch
if (this._elem) {
if ($.jqplot.use_excanvas && window.G_vmlCanvasManager.uninitElement !== undefined) {
window.G_vmlCanvasManager.uninitElement(this._elem.get(0));
}
this._elem.emptyForce();
this._elem = null;
}
// create a canvas here, but can't draw on it untill it is appended
// to dom for IE compatability.
var elem = plot.canvasManager.getCanvas();
this._textRenderer.setText(this.label, ctx);
var w = this.getWidth(ctx);
var h = this.getHeight(ctx);
// canvases seem to need to have width and heigh attributes directly set.
elem.width = w;
elem.height = h;
elem.style.width = w;
elem.style.height = h;
elem.style.textAlign = 'left';
elem.style.position = 'absolute';
elem = plot.canvasManager.initCanvas(elem);
this._elem = $(elem);
this._elem.css(this._styles);
this._elem.addClass('jqplot-'+this.axis+'-tick');
elem = null;
return this._elem;
};
$.jqplot.CanvasAxisTickRenderer.prototype.pack = function() {
this._textRenderer.draw(this._elem.get(0).getContext("2d"), this.label);
};
})(jQuery); | JavaScript |
/**
* jqPlot
* Pure JavaScript plotting plugin using jQuery
*
* Version: 1.0.8
* Revision: 1250
*
* Copyright (c) 2009-2013 Chris Leonello
* jqPlot is currently available for use in all personal or commercial projects
* under both the MIT (http://www.opensource.org/licenses/mit-license.php) and GPL
* version 2.0 (http://www.gnu.org/licenses/gpl-2.0.html) licenses. This means that you can
* choose the license that best suits your project and use it accordingly.
*
* Although not required, the author would appreciate an email letting him
* know of any substantial use of jqPlot. You can reach the author at:
* chris at jqplot dot com or see http://www.jqplot.com/info.php .
*
* If you are feeling kind and generous, consider supporting the project by
* making a donation at: http://www.jqplot.com/donate.php .
*
* sprintf functions contained in jqplot.sprintf.js by Ash Searle:
*
* version 2007.04.27
* author Ash Searle
* http://hexmen.com/blog/2007/03/printf-sprintf/
* http://hexmen.com/js/sprintf.js
* The author (Ash Searle) has placed this code in the public domain:
* "This code is unrestricted: you are free to use it however you like."
*
* included jsDate library by Chris Leonello:
*
* Copyright (c) 2010-2013 Chris Leonello
*
* jsDate is currently available for use in all personal or commercial projects
* under both the MIT and GPL version 2.0 licenses. This means that you can
* choose the license that best suits your project and use it accordingly.
*
* jsDate borrows many concepts and ideas from the Date Instance
* Methods by Ken Snyder along with some parts of Ken's actual code.
*
* Ken's original Date Instance Methods and copyright notice:
*
* Ken Snyder (ken d snyder at gmail dot com)
* 2008-09-10
* version 2.0.2 (http://kendsnyder.com/sandbox/date/)
* Creative Commons Attribution License 3.0 (http://creativecommons.org/licenses/by/3.0/)
*
* jqplotToImage function based on Larry Siden's export-jqplot-to-png.js.
* Larry has generously given permission to adapt his code for inclusion
* into jqPlot.
*
* Larry's original code can be found here:
*
* https://github.com/lsiden/export-jqplot-to-png
*
*
*/
(function($) {
// This code is a modified version of the canvastext.js code, copyright below:
//
// This code is released to the public domain by Jim Studt, 2007.
// He may keep some sort of up to date copy at http://www.federated.com/~jim/canvastext/
//
$.jqplot.CanvasTextRenderer = function(options){
this.fontStyle = 'normal'; // normal, italic, oblique [not implemented]
this.fontVariant = 'normal'; // normal, small caps [not implemented]
this.fontWeight = 'normal'; // normal, bold, bolder, lighter, 100 - 900
this.fontSize = '10px';
this.fontFamily = 'sans-serif';
this.fontStretch = 1.0;
this.fillStyle = '#666666';
this.angle = 0;
this.textAlign = 'start';
this.textBaseline = 'alphabetic';
this.text;
this.width;
this.height;
this.pt2px = 1.28;
$.extend(true, this, options);
this.normalizedFontSize = this.normalizeFontSize(this.fontSize);
this.setHeight();
};
$.jqplot.CanvasTextRenderer.prototype.init = function(options) {
$.extend(true, this, options);
this.normalizedFontSize = this.normalizeFontSize(this.fontSize);
this.setHeight();
};
// convert css spec into point size
// returns float
$.jqplot.CanvasTextRenderer.prototype.normalizeFontSize = function(sz) {
sz = String(sz);
var n = parseFloat(sz);
if (sz.indexOf('px') > -1) {
return n/this.pt2px;
}
else if (sz.indexOf('pt') > -1) {
return n;
}
else if (sz.indexOf('em') > -1) {
return n*12;
}
else if (sz.indexOf('%') > -1) {
return n*12/100;
}
// default to pixels;
else {
return n/this.pt2px;
}
};
$.jqplot.CanvasTextRenderer.prototype.fontWeight2Float = function(w) {
// w = normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900
// return values adjusted for Hershey font.
if (Number(w)) {
return w/400;
}
else {
switch (w) {
case 'normal':
return 1;
break;
case 'bold':
return 1.75;
break;
case 'bolder':
return 2.25;
break;
case 'lighter':
return 0.75;
break;
default:
return 1;
break;
}
}
};
$.jqplot.CanvasTextRenderer.prototype.getText = function() {
return this.text;
};
$.jqplot.CanvasTextRenderer.prototype.setText = function(t, ctx) {
this.text = t;
this.setWidth(ctx);
return this;
};
$.jqplot.CanvasTextRenderer.prototype.getWidth = function(ctx) {
return this.width;
};
$.jqplot.CanvasTextRenderer.prototype.setWidth = function(ctx, w) {
if (!w) {
this.width = this.measure(ctx, this.text);
}
else {
this.width = w;
}
return this;
};
// return height in pixels.
$.jqplot.CanvasTextRenderer.prototype.getHeight = function(ctx) {
return this.height;
};
// w - height in pt
// set heigh in px
$.jqplot.CanvasTextRenderer.prototype.setHeight = function(w) {
if (!w) {
//height = this.fontSize /0.75;
this.height = this.normalizedFontSize * this.pt2px;
}
else {
this.height = w;
}
return this;
};
$.jqplot.CanvasTextRenderer.prototype.letter = function (ch)
{
return this.letters[ch];
};
$.jqplot.CanvasTextRenderer.prototype.ascent = function()
{
return this.normalizedFontSize;
};
$.jqplot.CanvasTextRenderer.prototype.descent = function()
{
return 7.0*this.normalizedFontSize/25.0;
};
$.jqplot.CanvasTextRenderer.prototype.measure = function(ctx, str)
{
var total = 0;
var len = str.length;
for (var i = 0; i < len; i++) {
var c = this.letter(str.charAt(i));
if (c) {
total += c.width * this.normalizedFontSize / 25.0 * this.fontStretch;
}
}
return total;
};
$.jqplot.CanvasTextRenderer.prototype.draw = function(ctx,str)
{
var x = 0;
// leave room at bottom for descenders.
var y = this.height*0.72;
var total = 0;
var len = str.length;
var mag = this.normalizedFontSize / 25.0;
ctx.save();
var tx, ty;
// 1st quadrant
if ((-Math.PI/2 <= this.angle && this.angle <= 0) || (Math.PI*3/2 <= this.angle && this.angle <= Math.PI*2)) {
tx = 0;
ty = -Math.sin(this.angle) * this.width;
}
// 4th quadrant
else if ((0 < this.angle && this.angle <= Math.PI/2) || (-Math.PI*2 <= this.angle && this.angle <= -Math.PI*3/2)) {
tx = Math.sin(this.angle) * this.height;
ty = 0;
}
// 2nd quadrant
else if ((-Math.PI < this.angle && this.angle < -Math.PI/2) || (Math.PI <= this.angle && this.angle <= Math.PI*3/2)) {
tx = -Math.cos(this.angle) * this.width;
ty = -Math.sin(this.angle) * this.width - Math.cos(this.angle) * this.height;
}
// 3rd quadrant
else if ((-Math.PI*3/2 < this.angle && this.angle < Math.PI) || (Math.PI/2 < this.angle && this.angle < Math.PI)) {
tx = Math.sin(this.angle) * this.height - Math.cos(this.angle)*this.width;
ty = -Math.cos(this.angle) * this.height;
}
ctx.strokeStyle = this.fillStyle;
ctx.fillStyle = this.fillStyle;
ctx.translate(tx, ty);
ctx.rotate(this.angle);
ctx.lineCap = "round";
// multiplier was 2.0
var fact = (this.normalizedFontSize > 30) ? 2.0 : 2 + (30 - this.normalizedFontSize)/20;
ctx.lineWidth = fact * mag * this.fontWeight2Float(this.fontWeight);
for ( var i = 0; i < len; i++) {
var c = this.letter( str.charAt(i));
if ( !c) {
continue;
}
ctx.beginPath();
var penUp = 1;
var needStroke = 0;
for ( var j = 0; j < c.points.length; j++) {
var a = c.points[j];
if ( a[0] == -1 && a[1] == -1) {
penUp = 1;
continue;
}
if ( penUp) {
ctx.moveTo( x + a[0]*mag*this.fontStretch, y - a[1]*mag);
penUp = false;
} else {
ctx.lineTo( x + a[0]*mag*this.fontStretch, y - a[1]*mag);
}
}
ctx.stroke();
x += c.width*mag*this.fontStretch;
}
ctx.restore();
return total;
};
$.jqplot.CanvasTextRenderer.prototype.letters = {
' ': { width: 16, points: [] },
'!': { width: 10, points: [[5,21],[5,7],[-1,-1],[5,2],[4,1],[5,0],[6,1],[5,2]] },
'"': { width: 16, points: [[4,21],[4,14],[-1,-1],[12,21],[12,14]] },
'#': { width: 21, points: [[11,25],[4,-7],[-1,-1],[17,25],[10,-7],[-1,-1],[4,12],[18,12],[-1,-1],[3,6],[17,6]] },
'$': { width: 20, points: [[8,25],[8,-4],[-1,-1],[12,25],[12,-4],[-1,-1],[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]] },
'%': { width: 24, points: [[21,21],[3,0],[-1,-1],[8,21],[10,19],[10,17],[9,15],[7,14],[5,14],[3,16],[3,18],[4,20],[6,21],[8,21],[10,20],[13,19],[16,19],[19,20],[21,21],[-1,-1],[17,7],[15,6],[14,4],[14,2],[16,0],[18,0],[20,1],[21,3],[21,5],[19,7],[17,7]] },
'&': { width: 26, points: [[23,12],[23,13],[22,14],[21,14],[20,13],[19,11],[17,6],[15,3],[13,1],[11,0],[7,0],[5,1],[4,2],[3,4],[3,6],[4,8],[5,9],[12,13],[13,14],[14,16],[14,18],[13,20],[11,21],[9,20],[8,18],[8,16],[9,13],[11,10],[16,3],[18,1],[20,0],[22,0],[23,1],[23,2]] },
'\'': { width: 10, points: [[5,19],[4,20],[5,21],[6,20],[6,18],[5,16],[4,15]] },
'(': { width: 14, points: [[11,25],[9,23],[7,20],[5,16],[4,11],[4,7],[5,2],[7,-2],[9,-5],[11,-7]] },
')': { width: 14, points: [[3,25],[5,23],[7,20],[9,16],[10,11],[10,7],[9,2],[7,-2],[5,-5],[3,-7]] },
'*': { width: 16, points: [[8,21],[8,9],[-1,-1],[3,18],[13,12],[-1,-1],[13,18],[3,12]] },
'+': { width: 26, points: [[13,18],[13,0],[-1,-1],[4,9],[22,9]] },
',': { width: 10, points: [[6,1],[5,0],[4,1],[5,2],[6,1],[6,-1],[5,-3],[4,-4]] },
'-': { width: 18, points: [[6,9],[12,9]] },
'.': { width: 10, points: [[5,2],[4,1],[5,0],[6,1],[5,2]] },
'/': { width: 22, points: [[20,25],[2,-7]] },
'0': { width: 20, points: [[9,21],[6,20],[4,17],[3,12],[3,9],[4,4],[6,1],[9,0],[11,0],[14,1],[16,4],[17,9],[17,12],[16,17],[14,20],[11,21],[9,21]] },
'1': { width: 20, points: [[6,17],[8,18],[11,21],[11,0]] },
'2': { width: 20, points: [[4,16],[4,17],[5,19],[6,20],[8,21],[12,21],[14,20],[15,19],[16,17],[16,15],[15,13],[13,10],[3,0],[17,0]] },
'3': { width: 20, points: [[5,21],[16,21],[10,13],[13,13],[15,12],[16,11],[17,8],[17,6],[16,3],[14,1],[11,0],[8,0],[5,1],[4,2],[3,4]] },
'4': { width: 20, points: [[13,21],[3,7],[18,7],[-1,-1],[13,21],[13,0]] },
'5': { width: 20, points: [[15,21],[5,21],[4,12],[5,13],[8,14],[11,14],[14,13],[16,11],[17,8],[17,6],[16,3],[14,1],[11,0],[8,0],[5,1],[4,2],[3,4]] },
'6': { width: 20, points: [[16,18],[15,20],[12,21],[10,21],[7,20],[5,17],[4,12],[4,7],[5,3],[7,1],[10,0],[11,0],[14,1],[16,3],[17,6],[17,7],[16,10],[14,12],[11,13],[10,13],[7,12],[5,10],[4,7]] },
'7': { width: 20, points: [[17,21],[7,0],[-1,-1],[3,21],[17,21]] },
'8': { width: 20, points: [[8,21],[5,20],[4,18],[4,16],[5,14],[7,13],[11,12],[14,11],[16,9],[17,7],[17,4],[16,2],[15,1],[12,0],[8,0],[5,1],[4,2],[3,4],[3,7],[4,9],[6,11],[9,12],[13,13],[15,14],[16,16],[16,18],[15,20],[12,21],[8,21]] },
'9': { width: 20, points: [[16,14],[15,11],[13,9],[10,8],[9,8],[6,9],[4,11],[3,14],[3,15],[4,18],[6,20],[9,21],[10,21],[13,20],[15,18],[16,14],[16,9],[15,4],[13,1],[10,0],[8,0],[5,1],[4,3]] },
':': { width: 10, points: [[5,14],[4,13],[5,12],[6,13],[5,14],[-1,-1],[5,2],[4,1],[5,0],[6,1],[5,2]] },
';': { width: 10, points: [[5,14],[4,13],[5,12],[6,13],[5,14],[-1,-1],[6,1],[5,0],[4,1],[5,2],[6,1],[6,-1],[5,-3],[4,-4]] },
'<': { width: 24, points: [[20,18],[4,9],[20,0]] },
'=': { width: 26, points: [[4,12],[22,12],[-1,-1],[4,6],[22,6]] },
'>': { width: 24, points: [[4,18],[20,9],[4,0]] },
'?': { width: 18, points: [[3,16],[3,17],[4,19],[5,20],[7,21],[11,21],[13,20],[14,19],[15,17],[15,15],[14,13],[13,12],[9,10],[9,7],[-1,-1],[9,2],[8,1],[9,0],[10,1],[9,2]] },
'@': { width: 27, points: [[18,13],[17,15],[15,16],[12,16],[10,15],[9,14],[8,11],[8,8],[9,6],[11,5],[14,5],[16,6],[17,8],[-1,-1],[12,16],[10,14],[9,11],[9,8],[10,6],[11,5],[-1,-1],[18,16],[17,8],[17,6],[19,5],[21,5],[23,7],[24,10],[24,12],[23,15],[22,17],[20,19],[18,20],[15,21],[12,21],[9,20],[7,19],[5,17],[4,15],[3,12],[3,9],[4,6],[5,4],[7,2],[9,1],[12,0],[15,0],[18,1],[20,2],[21,3],[-1,-1],[19,16],[18,8],[18,6],[19,5]] },
'A': { width: 18, points: [[9,21],[1,0],[-1,-1],[9,21],[17,0],[-1,-1],[4,7],[14,7]] },
'B': { width: 21, points: [[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[-1,-1],[4,11],[13,11],[16,10],[17,9],[18,7],[18,4],[17,2],[16,1],[13,0],[4,0]] },
'C': { width: 21, points: [[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5]] },
'D': { width: 21, points: [[4,21],[4,0],[-1,-1],[4,21],[11,21],[14,20],[16,18],[17,16],[18,13],[18,8],[17,5],[16,3],[14,1],[11,0],[4,0]] },
'E': { width: 19, points: [[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11],[-1,-1],[4,0],[17,0]] },
'F': { width: 18, points: [[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11]] },
'G': { width: 21, points: [[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[18,8],[-1,-1],[13,8],[18,8]] },
'H': { width: 22, points: [[4,21],[4,0],[-1,-1],[18,21],[18,0],[-1,-1],[4,11],[18,11]] },
'I': { width: 8, points: [[4,21],[4,0]] },
'J': { width: 16, points: [[12,21],[12,5],[11,2],[10,1],[8,0],[6,0],[4,1],[3,2],[2,5],[2,7]] },
'K': { width: 21, points: [[4,21],[4,0],[-1,-1],[18,21],[4,7],[-1,-1],[9,12],[18,0]] },
'L': { width: 17, points: [[4,21],[4,0],[-1,-1],[4,0],[16,0]] },
'M': { width: 24, points: [[4,21],[4,0],[-1,-1],[4,21],[12,0],[-1,-1],[20,21],[12,0],[-1,-1],[20,21],[20,0]] },
'N': { width: 22, points: [[4,21],[4,0],[-1,-1],[4,21],[18,0],[-1,-1],[18,21],[18,0]] },
'O': { width: 22, points: [[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21]] },
'P': { width: 21, points: [[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,14],[17,12],[16,11],[13,10],[4,10]] },
'Q': { width: 22, points: [[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21],[-1,-1],[12,4],[18,-2]] },
'R': { width: 21, points: [[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[4,11],[-1,-1],[11,11],[18,0]] },
'S': { width: 20, points: [[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]] },
'T': { width: 16, points: [[8,21],[8,0],[-1,-1],[1,21],[15,21]] },
'U': { width: 22, points: [[4,21],[4,6],[5,3],[7,1],[10,0],[12,0],[15,1],[17,3],[18,6],[18,21]] },
'V': { width: 18, points: [[1,21],[9,0],[-1,-1],[17,21],[9,0]] },
'W': { width: 24, points: [[2,21],[7,0],[-1,-1],[12,21],[7,0],[-1,-1],[12,21],[17,0],[-1,-1],[22,21],[17,0]] },
'X': { width: 20, points: [[3,21],[17,0],[-1,-1],[17,21],[3,0]] },
'Y': { width: 18, points: [[1,21],[9,11],[9,0],[-1,-1],[17,21],[9,11]] },
'Z': { width: 20, points: [[17,21],[3,0],[-1,-1],[3,21],[17,21],[-1,-1],[3,0],[17,0]] },
'[': { width: 14, points: [[4,25],[4,-7],[-1,-1],[5,25],[5,-7],[-1,-1],[4,25],[11,25],[-1,-1],[4,-7],[11,-7]] },
'\\': { width: 14, points: [[0,21],[14,-3]] },
']': { width: 14, points: [[9,25],[9,-7],[-1,-1],[10,25],[10,-7],[-1,-1],[3,25],[10,25],[-1,-1],[3,-7],[10,-7]] },
'^': { width: 16, points: [[6,15],[8,18],[10,15],[-1,-1],[3,12],[8,17],[13,12],[-1,-1],[8,17],[8,0]] },
'_': { width: 16, points: [[0,-2],[16,-2]] },
'`': { width: 10, points: [[6,21],[5,20],[4,18],[4,16],[5,15],[6,16],[5,17]] },
'a': { width: 19, points: [[15,14],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]] },
'b': { width: 19, points: [[4,21],[4,0],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]] },
'c': { width: 18, points: [[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]] },
'd': { width: 19, points: [[15,21],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]] },
'e': { width: 18, points: [[3,8],[15,8],[15,10],[14,12],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]] },
'f': { width: 12, points: [[10,21],[8,21],[6,20],[5,17],[5,0],[-1,-1],[2,14],[9,14]] },
'g': { width: 19, points: [[15,14],[15,-2],[14,-5],[13,-6],[11,-7],[8,-7],[6,-6],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]] },
'h': { width: 19, points: [[4,21],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]] },
'i': { width: 8, points: [[3,21],[4,20],[5,21],[4,22],[3,21],[-1,-1],[4,14],[4,0]] },
'j': { width: 10, points: [[5,21],[6,20],[7,21],[6,22],[5,21],[-1,-1],[6,14],[6,-3],[5,-6],[3,-7],[1,-7]] },
'k': { width: 17, points: [[4,21],[4,0],[-1,-1],[14,14],[4,4],[-1,-1],[8,8],[15,0]] },
'l': { width: 8, points: [[4,21],[4,0]] },
'm': { width: 30, points: [[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0],[-1,-1],[15,10],[18,13],[20,14],[23,14],[25,13],[26,10],[26,0]] },
'n': { width: 19, points: [[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]] },
'o': { width: 19, points: [[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3],[16,6],[16,8],[15,11],[13,13],[11,14],[8,14]] },
'p': { width: 19, points: [[4,14],[4,-7],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]] },
'q': { width: 19, points: [[15,14],[15,-7],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]] },
'r': { width: 13, points: [[4,14],[4,0],[-1,-1],[4,8],[5,11],[7,13],[9,14],[12,14]] },
's': { width: 17, points: [[14,11],[13,13],[10,14],[7,14],[4,13],[3,11],[4,9],[6,8],[11,7],[13,6],[14,4],[14,3],[13,1],[10,0],[7,0],[4,1],[3,3]] },
't': { width: 12, points: [[5,21],[5,4],[6,1],[8,0],[10,0],[-1,-1],[2,14],[9,14]] },
'u': { width: 19, points: [[4,14],[4,4],[5,1],[7,0],[10,0],[12,1],[15,4],[-1,-1],[15,14],[15,0]] },
'v': { width: 16, points: [[2,14],[8,0],[-1,-1],[14,14],[8,0]] },
'w': { width: 22, points: [[3,14],[7,0],[-1,-1],[11,14],[7,0],[-1,-1],[11,14],[15,0],[-1,-1],[19,14],[15,0]] },
'x': { width: 17, points: [[3,14],[14,0],[-1,-1],[14,14],[3,0]] },
'y': { width: 16, points: [[2,14],[8,0],[-1,-1],[14,14],[8,0],[6,-4],[4,-6],[2,-7],[1,-7]] },
'z': { width: 17, points: [[14,14],[3,0],[-1,-1],[3,14],[14,14],[-1,-1],[3,0],[14,0]] },
'{': { width: 14, points: [[9,25],[7,24],[6,23],[5,21],[5,19],[6,17],[7,16],[8,14],[8,12],[6,10],[-1,-1],[7,24],[6,22],[6,20],[7,18],[8,17],[9,15],[9,13],[8,11],[4,9],[8,7],[9,5],[9,3],[8,1],[7,0],[6,-2],[6,-4],[7,-6],[-1,-1],[6,8],[8,6],[8,4],[7,2],[6,1],[5,-1],[5,-3],[6,-5],[7,-6],[9,-7]] },
'|': { width: 8, points: [[4,25],[4,-7]] },
'}': { width: 14, points: [[5,25],[7,24],[8,23],[9,21],[9,19],[8,17],[7,16],[6,14],[6,12],[8,10],[-1,-1],[7,24],[8,22],[8,20],[7,18],[6,17],[5,15],[5,13],[6,11],[10,9],[6,7],[5,5],[5,3],[6,1],[7,0],[8,-2],[8,-4],[7,-6],[-1,-1],[8,8],[6,6],[6,4],[7,2],[8,1],[9,-1],[9,-3],[8,-5],[7,-6],[5,-7]] },
'~': { width: 24, points: [[3,6],[3,8],[4,11],[6,12],[8,12],[10,11],[14,8],[16,7],[18,7],[20,8],[21,10],[-1,-1],[3,8],[4,10],[6,11],[8,11],[10,10],[14,7],[16,6],[18,6],[20,7],[21,10],[21,12]] }
};
$.jqplot.CanvasFontRenderer = function(options) {
options = options || {};
if (!options.pt2px) {
options.pt2px = 1.5;
}
$.jqplot.CanvasTextRenderer.call(this, options);
};
$.jqplot.CanvasFontRenderer.prototype = new $.jqplot.CanvasTextRenderer({});
$.jqplot.CanvasFontRenderer.prototype.constructor = $.jqplot.CanvasFontRenderer;
$.jqplot.CanvasFontRenderer.prototype.measure = function(ctx, str)
{
// var fstyle = this.fontStyle+' '+this.fontVariant+' '+this.fontWeight+' '+this.fontSize+' '+this.fontFamily;
var fstyle = this.fontSize+' '+this.fontFamily;
ctx.save();
ctx.font = fstyle;
var w = ctx.measureText(str).width;
ctx.restore();
return w;
};
$.jqplot.CanvasFontRenderer.prototype.draw = function(ctx, str)
{
var x = 0;
// leave room at bottom for descenders.
var y = this.height*0.72;
//var y = 12;
ctx.save();
var tx, ty;
// 1st quadrant
if ((-Math.PI/2 <= this.angle && this.angle <= 0) || (Math.PI*3/2 <= this.angle && this.angle <= Math.PI*2)) {
tx = 0;
ty = -Math.sin(this.angle) * this.width;
}
// 4th quadrant
else if ((0 < this.angle && this.angle <= Math.PI/2) || (-Math.PI*2 <= this.angle && this.angle <= -Math.PI*3/2)) {
tx = Math.sin(this.angle) * this.height;
ty = 0;
}
// 2nd quadrant
else if ((-Math.PI < this.angle && this.angle < -Math.PI/2) || (Math.PI <= this.angle && this.angle <= Math.PI*3/2)) {
tx = -Math.cos(this.angle) * this.width;
ty = -Math.sin(this.angle) * this.width - Math.cos(this.angle) * this.height;
}
// 3rd quadrant
else if ((-Math.PI*3/2 < this.angle && this.angle < Math.PI) || (Math.PI/2 < this.angle && this.angle < Math.PI)) {
tx = Math.sin(this.angle) * this.height - Math.cos(this.angle)*this.width;
ty = -Math.cos(this.angle) * this.height;
}
ctx.strokeStyle = this.fillStyle;
ctx.fillStyle = this.fillStyle;
// var fstyle = this.fontStyle+' '+this.fontVariant+' '+this.fontWeight+' '+this.fontSize+' '+this.fontFamily;
var fstyle = this.fontSize+' '+this.fontFamily;
ctx.font = fstyle;
ctx.translate(tx, ty);
ctx.rotate(this.angle);
ctx.fillText(str, x, y);
// ctx.strokeText(str, x, y);
ctx.restore();
};
})(jQuery); | JavaScript |
/*
jQuery.msgBox plugin
Copyright 2011, Halil İbrahim Kalyoncu
License: BSD
modified by Oliver Kopp, 2012.
* added support for configurable image paths
* a new msgBox can be shown within an existing msgBox
*/
/*
contact :
halil@ibrahimkalyoncu.com
koppdev@googlemail.com
*/
// users may change this variable to fit their needs
var msgBoxImagePath = host + "assets/js/jqmsgbox/Images/";
jQuery.msgBox = msg;
function msg (options) {
var isShown = false;
var typeOfValue = typeof options;
var defaults = {
content: (typeOfValue == "string" ? options : "Message"),
title: "Warning",
type: "alert",
autoClose: false,
timeOut: 0,
showButtons: true,
buttons: [{ value: "Ok"}],
inputs: [{ type: "text", name:"userName", header: "User Name" }, { type: "password",name:"password", header: "Password"}],
success: function (result) { },
beforeShow: function () { },
afterShow: function () { },
beforeClose: function () { },
afterClose: function () { },
opacity: 0.7
};
options = typeOfValue == "string" ? defaults : options;
if (options.type != null) {
switch (options.type) {
case "alert":
options.title = options.title == null ? "Warning" : options.title;
break;
case "info":
options.title = options.title == null ? "Information" : options.title;
break;
case "error":
options.title = options.title == null ? "Error" : options.title;
break;
case "confirm":
options.title = options.title == null ? "Confirmation" : options.title;
options.buttons = options.buttons == null ? [{ value: "Yes" }, { value: "No" }, { value: "Cancel"}] : options.buttons;
break;
case "prompt":
options.title = options.title == null ? "Log In" : options.title;
options.buttons = options.buttons == null ? [{ value: "Login" }, { value: "Cancel"}] : options.buttons;
break;
default:
image = "alert.png";
}
}
options.timeOut = options.timeOut == null ? (options.content == null ? 500 : options.content.length * 70) : options.timeOut;
options = $.extend(defaults, options);
if (options.autoClose) {
setTimeout(hide, options.timeOut);
}
var image = "";
switch (options.type) {
case "alert":
image = "alert.png";
break;
case "info":
image = "info.png";
break;
case "error":
image = "error.png";
break;
case "confirm":
image = "confirm.png";
break;
default:
image = "alert.png";
}
var divId = "msgBox" + new Date().getTime();
var divMsgBoxId = divId;
var divMsgBoxContentId = divId+"Content";
var divMsgBoxImageId = divId+"Image";
var divMsgBoxButtonsId = divId+"Buttons";
var divMsgBoxBackGroundId = divId+"BackGround";
var buttons = "";
$(options.buttons).each(function (index, button) {
buttons += "<input class=\"msgButton\" type=\"button\" name=\"" + button.value + "\" value=\"" + button.value + "\" />";
});
var inputs = "";
$(options.inputs).each(function (index, input) {
var type = input.type;
if (type=="checkbox" || type =="radiobutton") {
inputs += "<div class=\"msgInput\">" +
"<input type=\"" + input.type + "\" name=\"" + input.name + "\" "+(input.checked == null ? "" : "checked ='"+input.checked+"'")+" value=\"" + (typeof input.value == "undefined" ? "" : input.value) + "\" />" +
"<text>"+input.header +"</text>"+
"</div>";
}
else {
inputs += "<div class=\"msgInput\">" +
"<span class=\"msgInputHeader\">" + input.header + "<span>" +
"<input type=\"" + input.type + "\" name=\"" + input.name + "\" value=\"" + (typeof input.value == "undefined" ? "" : input.value) + "\" />" +
"</div>";
}
});
var divBackGround = "<div id=" + divMsgBoxBackGroundId + " class=\"msgBoxBackGround\"></div>";
var divTitle = "<div class=\"msgBoxTitle\">" + options.title + "</div>";
var divContainer = "<div class=\"msgBoxContainer\"><div id=" + divMsgBoxImageId + " class=\"msgBoxImage\"><img src=\"" + msgBoxImagePath + image + "\"/></div><div id=" + divMsgBoxContentId + " class=\"msgBoxContent\"><p><span>" + options.content + "</span></p></div></div>";
var divButtons = "<div id=" + divMsgBoxButtonsId + " class=\"msgBoxButtons\">" + buttons + "</div>";
var divInputs = "<div class=\"msgBoxInputs\">" + inputs + "</div>";
var divMsgBox;
var divMsgBoxContent;
var divMsgBoxImage;
var divMsgBoxButtons;
var divMsgBoxBackGround;
if (options.type == "prompt") {
$("html").append(divBackGround + "<div id=" + divMsgBoxId + " class=\"msgBox\">" + divTitle + "<div>" + divContainer + (options.showButtons ? divButtons + "</div>" : "</div>") + "</div>");
divMsgBox = $("#"+divMsgBoxId);
divMsgBoxContent = $("#"+divMsgBoxContentId);
divMsgBoxImage = $("#"+divMsgBoxImageId);
divMsgBoxButtons = $("#"+divMsgBoxButtonsId);
divMsgBoxBackGround = $("#"+divMsgBoxBackGroundId);
divMsgBoxImage.remove();
divMsgBoxButtons.css({"text-align":"center","margin-top":"5px"});
divMsgBoxContent.css({"width":"100%","height":"100%"});
divMsgBoxContent.html(divInputs);
}
else {
$("html").append(divBackGround + "<div id=" + divMsgBoxId + " class=\"msgBox\">" + divTitle + "<div>" + divContainer + (options.showButtons ? divButtons + "</div>" : "</div>") + "</div>");
divMsgBox= $("#"+divMsgBoxId);
divMsgBoxContent = $("#"+divMsgBoxContentId);
divMsgBoxImage = $("#"+divMsgBoxImageId);
divMsgBoxButtons = $("#"+divMsgBoxButtonsId);
divMsgBoxBackGround = $("#"+divMsgBoxBackGroundId);
}
var width = divMsgBox.width();
var height = divMsgBox.height();
var windowHeight = $(window).height();
var windowWidth = $(window).width();
var top = windowHeight / 2 - height / 2;
var left = windowWidth / 2 - width / 2;
show();
function show() {
if (isShown) {
return;
}
divMsgBox.css({ opacity: 0, top: top - 50, left: left });
divMsgBox.css("background-image", "url('"+msgBoxImagePath+"msgBoxBackGround.png')");
divMsgBoxBackGround.css({ opacity: options.opacity });
options.beforeShow();
divMsgBoxBackGround.css({ "width": $(document).width(), "height": getDocHeight() });
$(divMsgBoxId+","+divMsgBoxBackGroundId).fadeIn(0);
divMsgBox.animate({ opacity: 1, "top": top, "left": left }, 200);
setTimeout(options.afterShow, 200);
isShown = true;
$(window).bind("resize", function (e) {
var width = divMsgBox.width();
var height = divMsgBox.height();
var windowHeight = $(window).height();
var windowWidth = $(window).width();
var top = windowHeight / 2 - height / 2;
var left = windowWidth / 2 - width / 2;
divMsgBox.css({ "top": top, "left": left });
});
}
function hide() {
if (!isShown) {
return;
}
options.beforeClose();
divMsgBox.animate({ opacity: 0, "top": top - 50, "left": left }, 200);
divMsgBoxBackGround.fadeOut(300);
setTimeout(function () { divMsgBox.remove(); divMsgBoxBackGround.remove(); }, 300);
setTimeout(options.afterClose, 300);
isShown = false;
}
function getDocHeight() {
var D = document;
return Math.max(
Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
Math.max(D.body.clientHeight, D.documentElement.clientHeight));
}
function getFocus() {
divMsgBox.fadeOut(200).fadeIn(200);
}
$("input.msgButton").click(function (e) {
e.preventDefault();
var value = $(this).val();
if (options.type != "prompt") {
options.success(value);
}
else {
var inputValues = [];
$("div.msgInput input").each(function (index, domEle) {
var name = $(this).attr("name");
var value = $(this).val();
var type = $(this).attr("type");
if (type == "checkbox" || type == "radiobutton") {
inputValues.push({ name: name, value: value,checked: $(this).attr("checked")});
}
else {
inputValues.push({ name: name, value: value });
}
});
options.success(value,inputValues);
}
hide();
});
divMsgBoxBackGround.click(function (e) {
if (!options.showButtons || options.autoClose) {
hide();
}
else {
getFocus();
}
});
};
| JavaScript |
/*
Uniform v1.7.5
Copyright © 2009 Josh Pyles / Pixelmatrix Design LLC
http://pixelmatrixdesign.com
Requires jQuery 1.4 or newer
Much thanks to Thomas Reynolds and Buck Wilson for their help and advice on this
Disabling text selection is made possible by Mathias Bynens <http://mathiasbynens.be/>
and his noSelect plugin. <http://github.com/mathiasbynens/noSelect-jQuery-Plugin>
Also, thanks to David Kaneda and Eugene Bond for their contributions to the plugin
License:
MIT License - http://www.opensource.org/licenses/mit-license.php
Enjoy!
*/
(function($) {
$.uniform = {
options: {
selectClass: 'selector',
radioClass: 'radio',
checkboxClass: 'checker',
fileClass: 'uploader',
filenameClass: 'filename',
fileBtnClass: 'action',
fileDefaultText: 'No file selected',
fileBtnText: 'Choose File',
checkedClass: 'checked',
focusClass: 'focus',
disabledClass: 'disabled',
buttonClass: 'button',
activeClass: 'active',
hoverClass: 'hover',
useID: true,
idPrefix: 'uniform',
resetSelector: false,
autoHide: true
},
elements: []
};
if($.browser.msie && $.browser.version < 7){
$.support.selectOpacity = false;
}else{
$.support.selectOpacity = true;
}
$.fn.uniform = function(options) {
options = $.extend($.uniform.options, options);
var el = this;
//code for specifying a reset button
if(options.resetSelector != false){
$(options.resetSelector).mouseup(function(){
function resetThis(){
$.uniform.update(el);
}
setTimeout(resetThis, 10);
});
}
function doInput(elem){
$el = $(elem);
$el.addClass($el.attr("type"));
storeElement(elem);
}
function doTextarea(elem){
$(elem).addClass("uniform");
storeElement(elem);
}
function doButton(elem){
var $el = $(elem);
var divTag = $("<div>"),
spanTag = $("<span>");
divTag.addClass(options.buttonClass);
if(options.useID && $el.attr("id") != "") divTag.attr("id", options.idPrefix+"-"+$el.attr("id"));
var btnText;
if($el.is("a") || $el.is("button")){
btnText = $el.text();
}else if($el.is(":submit") || $el.is(":reset") || $el.is("input[type=button]")){
btnText = $el.attr("value");
}
btnText = btnText == "" ? $el.is(":reset") ? "Reset" : "Submit" : btnText;
spanTag.html(btnText);
$el.css("opacity", 0);
$el.wrap(divTag);
$el.wrap(spanTag);
//redefine variables
divTag = $el.closest("div");
spanTag = $el.closest("span");
if($el.is(":disabled")) divTag.addClass(options.disabledClass);
divTag.bind({
"mouseenter.uniform": function(){
divTag.addClass(options.hoverClass);
},
"mouseleave.uniform": function(){
divTag.removeClass(options.hoverClass);
divTag.removeClass(options.activeClass);
},
"mousedown.uniform touchbegin.uniform": function(){
divTag.addClass(options.activeClass);
},
"mouseup.uniform touchend.uniform": function(){
divTag.removeClass(options.activeClass);
},
"click.uniform touchend.uniform": function(e){
if($(e.target).is("span") || $(e.target).is("div")){
if(elem[0].dispatchEvent){
var ev = document.createEvent('MouseEvents');
ev.initEvent( 'click', true, true );
elem[0].dispatchEvent(ev);
}else{
elem[0].click();
}
}
}
});
elem.bind({
"focus.uniform": function(){
divTag.addClass(options.focusClass);
},
"blur.uniform": function(){
divTag.removeClass(options.focusClass);
}
});
$.uniform.noSelect(divTag);
storeElement(elem);
}
function doSelect(elem){
var $el = $(elem);
var divTag = $('<div />'),
spanTag = $('<span />');
if(!$el.css("display") == "none" && options.autoHide){
divTag.hide();
}
divTag.addClass(options.selectClass);
if(options.useID && elem.attr("id") != ""){
divTag.attr("id", options.idPrefix+"-"+elem.attr("id"));
}
var selected = elem.find(":selected:first");
if(selected.length == 0){
selected = elem.find("option:first");
}
spanTag.html(selected.html());
elem.css('opacity', 0);
elem.wrap(divTag);
elem.before(spanTag);
//redefine variables
divTag = elem.parent("div");
spanTag = elem.siblings("span");
elem.bind({
"change.uniform": function() {
spanTag.text(elem.find(":selected").html());
divTag.removeClass(options.activeClass);
},
"focus.uniform": function() {
divTag.addClass(options.focusClass);
},
"blur.uniform": function() {
divTag.removeClass(options.focusClass);
divTag.removeClass(options.activeClass);
},
"mousedown.uniform touchbegin.uniform": function() {
divTag.addClass(options.activeClass);
},
"mouseup.uniform touchend.uniform": function() {
divTag.removeClass(options.activeClass);
},
"click.uniform touchend.uniform": function(){
divTag.removeClass(options.activeClass);
},
"mouseenter.uniform": function() {
divTag.addClass(options.hoverClass);
},
"mouseleave.uniform": function() {
divTag.removeClass(options.hoverClass);
divTag.removeClass(options.activeClass);
},
"keyup.uniform": function(){
spanTag.text(elem.find(":selected").html());
}
});
//handle disabled state
if($(elem).attr("disabled")){
//box is checked by default, check our box
divTag.addClass(options.disabledClass);
}
$.uniform.noSelect(spanTag);
storeElement(elem);
}
function doCheckbox(elem){
var $el = $(elem);
var divTag = $('<div />'),
spanTag = $('<span />');
if(!$el.css("display") == "none" && options.autoHide){
divTag.hide();
}
divTag.addClass(options.checkboxClass);
//assign the id of the element
if(options.useID && elem.attr("id") != ""){
divTag.attr("id", options.idPrefix+"-"+elem.attr("id"));
}
//wrap with the proper elements
$(elem).wrap(divTag);
$(elem).wrap(spanTag);
//redefine variables
spanTag = elem.parent();
divTag = spanTag.parent();
//hide normal input and add focus classes
$(elem)
.css("opacity", 0)
.bind({
"focus.uniform": function(){
divTag.addClass(options.focusClass);
},
"blur.uniform": function(){
divTag.removeClass(options.focusClass);
},
"click.uniform touchend.uniform": function(){
if(!$(elem).attr("checked")){
//box was just unchecked, uncheck span
spanTag.removeClass(options.checkedClass);
}else{
//box was just checked, check span.
spanTag.addClass(options.checkedClass);
}
},
"mousedown.uniform touchbegin.uniform": function() {
divTag.addClass(options.activeClass);
},
"mouseup.uniform touchend.uniform": function() {
divTag.removeClass(options.activeClass);
},
"mouseenter.uniform": function() {
divTag.addClass(options.hoverClass);
},
"mouseleave.uniform": function() {
divTag.removeClass(options.hoverClass);
divTag.removeClass(options.activeClass);
}
});
//handle defaults
if($(elem).attr("checked")){
//box is checked by default, check our box
spanTag.addClass(options.checkedClass);
}
//handle disabled state
if($(elem).attr("disabled")){
//box is checked by default, check our box
divTag.addClass(options.disabledClass);
}
storeElement(elem);
}
function doRadio(elem){
var $el = $(elem);
var divTag = $('<div />'),
spanTag = $('<span />');
if(!$el.css("display") == "none" && options.autoHide){
divTag.hide();
}
divTag.addClass(options.radioClass);
if(options.useID && elem.attr("id") != ""){
divTag.attr("id", options.idPrefix+"-"+elem.attr("id"));
}
//wrap with the proper elements
$(elem).wrap(divTag);
$(elem).wrap(spanTag);
//redefine variables
spanTag = elem.parent();
divTag = spanTag.parent();
//hide normal input and add focus classes
$(elem)
.css("opacity", 0)
.bind({
"focus.uniform": function(){
divTag.addClass(options.focusClass);
},
"blur.uniform": function(){
divTag.removeClass(options.focusClass);
},
"click.uniform touchend.uniform": function(){
if(!$(elem).attr("checked")){
//box was just unchecked, uncheck span
spanTag.removeClass(options.checkedClass);
}else{
//box was just checked, check span
var classes = options.radioClass.split(" ")[0];
$("." + classes + " span." + options.checkedClass + ":has([name='" + $(elem).attr('name') + "'])").removeClass(options.checkedClass);
spanTag.addClass(options.checkedClass);
}
},
"mousedown.uniform touchend.uniform": function() {
if(!$(elem).is(":disabled")){
divTag.addClass(options.activeClass);
}
},
"mouseup.uniform touchbegin.uniform": function() {
divTag.removeClass(options.activeClass);
},
"mouseenter.uniform touchend.uniform": function() {
divTag.addClass(options.hoverClass);
},
"mouseleave.uniform": function() {
divTag.removeClass(options.hoverClass);
divTag.removeClass(options.activeClass);
}
});
//handle defaults
if($(elem).attr("checked")){
//box is checked by default, check span
spanTag.addClass(options.checkedClass);
}
//handle disabled state
if($(elem).attr("disabled")){
//box is checked by default, check our box
divTag.addClass(options.disabledClass);
}
storeElement(elem);
}
function doFile(elem){
//sanitize input
var $el = $(elem);
var divTag = $('<div />'),
filenameTag = $('<span>'+options.fileDefaultText+'</span>'),
btnTag = $('<span>'+options.fileBtnText+'</span>');
if(!$el.css("display") == "none" && options.autoHide){
divTag.hide();
}
divTag.addClass(options.fileClass);
filenameTag.addClass(options.filenameClass);
btnTag.addClass(options.fileBtnClass);
if(options.useID && $el.attr("id") != ""){
divTag.attr("id", options.idPrefix+"-"+$el.attr("id"));
}
//wrap with the proper elements
$el.wrap(divTag);
$el.after(btnTag);
$el.after(filenameTag);
//redefine variables
divTag = $el.closest("div");
filenameTag = $el.siblings("."+options.filenameClass);
btnTag = $el.siblings("."+options.fileBtnClass);
//set the size
if(!$el.attr("size")){
var divWidth = divTag.width();
//$el.css("width", divWidth);
$el.attr("size", divWidth/10);
}
//actions
var setFilename = function()
{
var filename = $el.val();
if (filename === '')
{
filename = options.fileDefaultText;
}
else
{
filename = filename.split(/[\/\\]+/);
filename = filename[(filename.length-1)];
}
filenameTag.text(filename);
};
// Account for input saved across refreshes
setFilename();
$el
.css("opacity", 0)
.bind({
"focus.uniform": function(){
divTag.addClass(options.focusClass);
},
"blur.uniform": function(){
divTag.removeClass(options.focusClass);
},
"mousedown.uniform": function() {
if(!$(elem).is(":disabled")){
divTag.addClass(options.activeClass);
}
},
"mouseup.uniform": function() {
divTag.removeClass(options.activeClass);
},
"mouseenter.uniform": function() {
divTag.addClass(options.hoverClass);
},
"mouseleave.uniform": function() {
divTag.removeClass(options.hoverClass);
divTag.removeClass(options.activeClass);
}
});
// IE7 doesn't fire onChange until blur or second fire.
if ($.browser.msie){
// IE considers browser chrome blocking I/O, so it
// suspends tiemouts until after the file has been selected.
$el.bind('click.uniform.ie7', function() {
setTimeout(setFilename, 0);
});
}else{
// All other browsers behave properly
$el.bind('change.uniform', setFilename);
}
//handle defaults
if($el.attr("disabled")){
//box is checked by default, check our box
divTag.addClass(options.disabledClass);
}
$.uniform.noSelect(filenameTag);
$.uniform.noSelect(btnTag);
storeElement(elem);
}
$.uniform.restore = function(elem){
if(elem == undefined){
elem = $($.uniform.elements);
}
$(elem).each(function(){
if($(this).is(":checkbox")){
//unwrap from span and div
$(this).unwrap().unwrap();
}else if($(this).is("select")){
//remove sibling span
$(this).siblings("span").remove();
//unwrap parent div
$(this).unwrap();
}else if($(this).is(":radio")){
//unwrap from span and div
$(this).unwrap().unwrap();
}else if($(this).is(":file")){
//remove sibling spans
$(this).siblings("span").remove();
//unwrap parent div
$(this).unwrap();
}else if($(this).is("button, :submit, :reset, a, input[type='button']")){
//unwrap from span and div
$(this).unwrap().unwrap();
}
//unbind events
$(this).unbind(".uniform");
//reset inline style
$(this).css("opacity", "1");
//remove item from list of uniformed elements
var index = $.inArray($(elem), $.uniform.elements);
$.uniform.elements.splice(index, 1);
});
};
function storeElement(elem){
//store this element in our global array
elem = $(elem).get();
if(elem.length > 1){
$.each(elem, function(i, val){
$.uniform.elements.push(val);
});
}else{
$.uniform.elements.push(elem);
}
}
//noSelect v1.0
$.uniform.noSelect = function(elem) {
function f() {
return false;
};
$(elem).each(function() {
this.onselectstart = this.ondragstart = f; // Webkit & IE
$(this)
.mousedown(f) // Webkit & Opera
.css({ MozUserSelect: 'none' }); // Firefox
});
};
$.uniform.update = function(elem){
if(elem == undefined){
elem = $($.uniform.elements);
}
//sanitize input
elem = $(elem);
elem.each(function(){
//do to each item in the selector
//function to reset all classes
var $e = $(this);
if($e.is("select")){
//element is a select
var spanTag = $e.siblings("span");
var divTag = $e.parent("div");
divTag.removeClass(options.hoverClass+" "+options.focusClass+" "+options.activeClass);
//reset current selected text
spanTag.html($e.find(":selected").html());
if($e.is(":disabled")){
divTag.addClass(options.disabledClass);
}else{
divTag.removeClass(options.disabledClass);
}
}else if($e.is(":checkbox")){
//element is a checkbox
var spanTag = $e.closest("span");
var divTag = $e.closest("div");
divTag.removeClass(options.hoverClass+" "+options.focusClass+" "+options.activeClass);
spanTag.removeClass(options.checkedClass);
if($e.is(":checked")){
spanTag.addClass(options.checkedClass);
}
if($e.is(":disabled")){
divTag.addClass(options.disabledClass);
}else{
divTag.removeClass(options.disabledClass);
}
}else if($e.is(":radio")){
//element is a radio
var spanTag = $e.closest("span");
var divTag = $e.closest("div");
divTag.removeClass(options.hoverClass+" "+options.focusClass+" "+options.activeClass);
spanTag.removeClass(options.checkedClass);
if($e.is(":checked")){
spanTag.addClass(options.checkedClass);
}
if($e.is(":disabled")){
divTag.addClass(options.disabledClass);
}else{
divTag.removeClass(options.disabledClass);
}
}else if($e.is(":file")){
var divTag = $e.parent("div");
var filenameTag = $e.siblings(options.filenameClass);
btnTag = $e.siblings(options.fileBtnClass);
divTag.removeClass(options.hoverClass+" "+options.focusClass+" "+options.activeClass);
filenameTag.text($e.val());
if($e.is(":disabled")){
divTag.addClass(options.disabledClass);
}else{
divTag.removeClass(options.disabledClass);
}
}else if($e.is(":submit") || $e.is(":reset") || $e.is("button") || $e.is("a") || elem.is("input[type=button]")){
var divTag = $e.closest("div");
divTag.removeClass(options.hoverClass+" "+options.focusClass+" "+options.activeClass);
if($e.is(":disabled")){
divTag.addClass(options.disabledClass);
}else{
divTag.removeClass(options.disabledClass);
}
}
});
};
return this.each(function() {
if($.support.selectOpacity){
var elem = $(this);
if(elem.is("select")){
//element is a select
if(elem.attr("multiple") != true){
//element is not a multi-select
if(elem.attr("size") == undefined || elem.attr("size") <= 1){
doSelect(elem);
}
}
}else if(elem.is(":checkbox")){
//element is a checkbox
doCheckbox(elem);
}else if(elem.is(":radio")){
//element is a radio
doRadio(elem);
}else if(elem.is(":file")){
//element is a file upload
doFile(elem);
}else if(elem.is(":text, :password, input[type='email']")){
doInput(elem);
}else if(elem.is("textarea")){
doTextarea(elem);
}else if(elem.is("a") || elem.is(":submit") || elem.is(":reset") || elem.is("button") || elem.is("input[type=button]")){
doButton(elem);
}
}
});
};
})(jQuery); | JavaScript |
/*
Flot plugin for stacking data sets, i.e. putting them on top of each
other, for accumulative graphs.
The plugin assumes the data is sorted on x (or y if stacking
horizontally). For line charts, it is assumed that if a line has an
undefined gap (from a null point), then the line above it should have
the same gap - insert zeros instead of "null" if you want another
behaviour. This also holds for the start and end of the chart. Note
that stacking a mix of positive and negative values in most instances
doesn't make sense (so it looks weird).
Two or more series are stacked when their "stack" attribute is set to
the same key (which can be any number or string or just "true"). To
specify the default stack, you can set
series: {
stack: null or true or key (number/string)
}
or specify it for a specific series
$.plot($("#placeholder"), [{ data: [ ... ], stack: true }])
The stacking order is determined by the order of the data series in
the array (later series end up on top of the previous).
Internally, the plugin modifies the datapoints in each series, adding
an offset to the y value. For line series, extra data points are
inserted through interpolation. If there's a second y value, it's also
adjusted (e.g for bar charts or filled areas).
*/
(function ($) {
var options = {
series: { stack: null } // or number/string
};
function init(plot) {
function findMatchingSeries(s, allseries) {
var res = null
for (var i = 0; i < allseries.length; ++i) {
if (s == allseries[i])
break;
if (allseries[i].stack == s.stack)
res = allseries[i];
}
return res;
}
function stackData(plot, s, datapoints) {
if (s.stack == null)
return;
var other = findMatchingSeries(s, plot.getData());
if (!other)
return;
var ps = datapoints.pointsize,
points = datapoints.points,
otherps = other.datapoints.pointsize,
otherpoints = other.datapoints.points,
newpoints = [],
px, py, intery, qx, qy, bottom,
withlines = s.lines.show,
horizontal = s.bars.horizontal,
withbottom = ps > 2 && (horizontal ? datapoints.format[2].x : datapoints.format[2].y),
withsteps = withlines && s.lines.steps,
fromgap = true,
keyOffset = horizontal ? 1 : 0,
accumulateOffset = horizontal ? 0 : 1,
i = 0, j = 0, l;
while (true) {
if (i >= points.length)
break;
l = newpoints.length;
if (points[i] == null) {
// copy gaps
for (m = 0; m < ps; ++m)
newpoints.push(points[i + m]);
i += ps;
}
else if (j >= otherpoints.length) {
// for lines, we can't use the rest of the points
if (!withlines) {
for (m = 0; m < ps; ++m)
newpoints.push(points[i + m]);
}
i += ps;
}
else if (otherpoints[j] == null) {
// oops, got a gap
for (m = 0; m < ps; ++m)
newpoints.push(null);
fromgap = true;
j += otherps;
}
else {
// cases where we actually got two points
px = points[i + keyOffset];
py = points[i + accumulateOffset];
qx = otherpoints[j + keyOffset];
qy = otherpoints[j + accumulateOffset];
bottom = 0;
if (px == qx) {
for (m = 0; m < ps; ++m)
newpoints.push(points[i + m]);
newpoints[l + accumulateOffset] += qy;
bottom = qy;
i += ps;
j += otherps;
}
else if (px > qx) {
// we got past point below, might need to
// insert interpolated extra point
if (withlines && i > 0 && points[i - ps] != null) {
intery = py + (points[i - ps + accumulateOffset] - py) * (qx - px) / (points[i - ps + keyOffset] - px);
newpoints.push(qx);
newpoints.push(intery + qy);
for (m = 2; m < ps; ++m)
newpoints.push(points[i + m]);
bottom = qy;
}
j += otherps;
}
else { // px < qx
if (fromgap && withlines) {
// if we come from a gap, we just skip this point
i += ps;
continue;
}
for (m = 0; m < ps; ++m)
newpoints.push(points[i + m]);
// we might be able to interpolate a point below,
// this can give us a better y
if (withlines && j > 0 && otherpoints[j - otherps] != null)
bottom = qy + (otherpoints[j - otherps + accumulateOffset] - qy) * (px - qx) / (otherpoints[j - otherps + keyOffset] - qx);
newpoints[l + accumulateOffset] += bottom;
i += ps;
}
fromgap = false;
if (l != newpoints.length && withbottom)
newpoints[l + 2] += bottom;
}
// maintain the line steps invariant
if (withsteps && l != newpoints.length && l > 0
&& newpoints[l] != null
&& newpoints[l] != newpoints[l - ps]
&& newpoints[l + 1] != newpoints[l - ps + 1]) {
for (m = 0; m < ps; ++m)
newpoints[l + ps + m] = newpoints[l + m];
newpoints[l + 1] = newpoints[l - ps + 1];
}
}
datapoints.points = newpoints;
}
plot.hooks.processDatapoints.push(stackData);
}
$.plot.plugins.push({
init: init,
options: options,
name: 'stack',
version: '1.2'
});
})(jQuery);
| JavaScript |
/*! Javascript plotting library for jQuery, v. 0.7.
*
* Released under the MIT license by IOLA, December 2007.
*
*/
// first an inline dependency, jquery.colorhelpers.js, we inline it here
// for convenience
/* Plugin for jQuery for working with colors.
*
* Version 1.1.
*
* Inspiration from jQuery color animation plugin by John Resig.
*
* Released under the MIT license by Ole Laursen, October 2009.
*
* Examples:
*
* $.color.parse("#fff").scale('rgb', 0.25).add('a', -0.5).toString()
* var c = $.color.extract($("#mydiv"), 'background-color');
* console.log(c.r, c.g, c.b, c.a);
* $.color.make(100, 50, 25, 0.4).toString() // returns "rgba(100,50,25,0.4)"
*
* Note that .scale() and .add() return the same modified object
* instead of making a new one.
*
* V. 1.1: Fix error handling so e.g. parsing an empty string does
* produce a color rather than just crashing.
*/
(function(B){B.color={};B.color.make=function(F,E,C,D){var G={};G.r=F||0;G.g=E||0;G.b=C||0;G.a=D!=null?D:1;G.add=function(J,I){for(var H=0;H<J.length;++H){G[J.charAt(H)]+=I}return G.normalize()};G.scale=function(J,I){for(var H=0;H<J.length;++H){G[J.charAt(H)]*=I}return G.normalize()};G.toString=function(){if(G.a>=1){return"rgb("+[G.r,G.g,G.b].join(",")+")"}else{return"rgba("+[G.r,G.g,G.b,G.a].join(",")+")"}};G.normalize=function(){function H(J,K,I){return K<J?J:(K>I?I:K)}G.r=H(0,parseInt(G.r),255);G.g=H(0,parseInt(G.g),255);G.b=H(0,parseInt(G.b),255);G.a=H(0,G.a,1);return G};G.clone=function(){return B.color.make(G.r,G.b,G.g,G.a)};return G.normalize()};B.color.extract=function(D,C){var E;do{E=D.css(C).toLowerCase();if(E!=""&&E!="transparent"){break}D=D.parent()}while(!B.nodeName(D.get(0),"body"));if(E=="rgba(0, 0, 0, 0)"){E="transparent"}return B.color.parse(E)};B.color.parse=function(F){var E,C=B.color.make;if(E=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(F)){return C(parseInt(E[1],10),parseInt(E[2],10),parseInt(E[3],10))}if(E=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(F)){return C(parseInt(E[1],10),parseInt(E[2],10),parseInt(E[3],10),parseFloat(E[4]))}if(E=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(F)){return C(parseFloat(E[1])*2.55,parseFloat(E[2])*2.55,parseFloat(E[3])*2.55)}if(E=/rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(F)){return C(parseFloat(E[1])*2.55,parseFloat(E[2])*2.55,parseFloat(E[3])*2.55,parseFloat(E[4]))}if(E=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(F)){return C(parseInt(E[1],16),parseInt(E[2],16),parseInt(E[3],16))}if(E=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(F)){return C(parseInt(E[1]+E[1],16),parseInt(E[2]+E[2],16),parseInt(E[3]+E[3],16))}var D=B.trim(F).toLowerCase();if(D=="transparent"){return C(255,255,255,0)}else{E=A[D]||[0,0,0];return C(E[0],E[1],E[2])}};var A={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]}})(jQuery);
// the actual Flot code
(function($) {
function Plot(placeholder, data_, options_, plugins) {
// data is on the form:
// [ series1, series2 ... ]
// where series is either just the data as [ [x1, y1], [x2, y2], ... ]
// or { data: [ [x1, y1], [x2, y2], ... ], label: "some label", ... }
var series = [],
options = {
// the color theme used for graphs
colors: ["#edc240", "#afd8f8", "#cb4b4b", "#4da74d", "#9440ed"],
legend: {
show: true,
noColumns: 1, // number of colums in legend table
labelFormatter: null, // fn: string -> string
labelBoxBorderColor: "#ccc", // border color for the little label boxes
container: null, // container (as jQuery object) to put legend in, null means default on top of graph
position: "ne", // position of default legend container within plot
margin: 5, // distance from grid edge to default legend container within plot
backgroundColor: null, // null means auto-detect
backgroundOpacity: 0.85 // set to 0 to avoid background
},
xaxis: {
show: null, // null = auto-detect, true = always, false = never
position: "bottom", // or "top"
mode: null, // null or "time"
color: null, // base color, labels, ticks
tickColor: null, // possibly different color of ticks, e.g. "rgba(0,0,0,0.15)"
transform: null, // null or f: number -> number to transform axis
inverseTransform: null, // if transform is set, this should be the inverse function
min: null, // min. value to show, null means set automatically
max: null, // max. value to show, null means set automatically
autoscaleMargin: null, // margin in % to add if auto-setting min/max
ticks: null, // either [1, 3] or [[1, "a"], 3] or (fn: axis info -> ticks) or app. number of ticks for auto-ticks
tickFormatter: null, // fn: number -> string
labelWidth: null, // size of tick labels in pixels
labelHeight: null,
reserveSpace: null, // whether to reserve space even if axis isn't shown
tickLength: null, // size in pixels of ticks, or "full" for whole line
alignTicksWithAxis: null, // axis number or null for no sync
// mode specific options
tickDecimals: null, // no. of decimals, null means auto
tickSize: null, // number or [number, "unit"]
minTickSize: null, // number or [number, "unit"]
monthNames: null, // list of names of months
timeformat: null, // format string to use
twelveHourClock: false // 12 or 24 time in time mode
},
yaxis: {
autoscaleMargin: 0.02,
position: "left" // or "right"
},
xaxes: [],
yaxes: [],
series: {
points: {
show: false,
radius: 3,
lineWidth: 2, // in pixels
fill: true,
fillColor: "#ffffff",
symbol: "circle" // or callback
},
lines: {
// we don't put in show: false so we can see
// whether lines were actively disabled
lineWidth: 2, // in pixels
fill: false,
fillColor: null,
steps: false
},
bars: {
show: false,
lineWidth: 2, // in pixels
barWidth: 1, // in units of the x axis
fill: true,
fillColor: null,
align: "left", // or "center"
horizontal: false
},
shadowSize: 3
},
grid: {
show: true,
aboveData: false,
color: "#545454", // primary color used for outline and labels
backgroundColor: null, // null for transparent, else color
borderColor: null, // set if different from the grid color
tickColor: null, // color for the ticks, e.g. "rgba(0,0,0,0.15)"
labelMargin: 5, // in pixels
axisMargin: 8, // in pixels
borderWidth: 2, // in pixels
minBorderMargin: null, // in pixels, null means taken from points radius
markings: null, // array of ranges or fn: axes -> array of ranges
markingsColor: "#f4f4f4",
markingsLineWidth: 2,
// interactive stuff
clickable: false,
hoverable: false,
autoHighlight: true, // highlight in case mouse is near
mouseActiveRadius: 10 // how far the mouse can be away to activate an item
},
hooks: {}
},
canvas = null, // the canvas for the plot itself
overlay = null, // canvas for interactive stuff on top of plot
eventHolder = null, // jQuery object that events should be bound to
ctx = null, octx = null,
xaxes = [], yaxes = [],
plotOffset = { left: 0, right: 0, top: 0, bottom: 0},
canvasWidth = 0, canvasHeight = 0,
plotWidth = 0, plotHeight = 0,
hooks = {
processOptions: [],
processRawData: [],
processDatapoints: [],
drawSeries: [],
draw: [],
bindEvents: [],
drawOverlay: [],
shutdown: []
},
plot = this;
// public functions
plot.setData = setData;
plot.setupGrid = setupGrid;
plot.draw = draw;
plot.getPlaceholder = function() { return placeholder; };
plot.getCanvas = function() { return canvas; };
plot.getPlotOffset = function() { return plotOffset; };
plot.width = function () { return plotWidth; };
plot.height = function () { return plotHeight; };
plot.offset = function () {
var o = eventHolder.offset();
o.left += plotOffset.left;
o.top += plotOffset.top;
return o;
};
plot.getData = function () { return series; };
plot.getAxes = function () {
var res = {}, i;
$.each(xaxes.concat(yaxes), function (_, axis) {
if (axis)
res[axis.direction + (axis.n != 1 ? axis.n : "") + "axis"] = axis;
});
return res;
};
plot.getXAxes = function () { return xaxes; };
plot.getYAxes = function () { return yaxes; };
plot.c2p = canvasToAxisCoords;
plot.p2c = axisToCanvasCoords;
plot.getOptions = function () { return options; };
plot.highlight = highlight;
plot.unhighlight = unhighlight;
plot.triggerRedrawOverlay = triggerRedrawOverlay;
plot.pointOffset = function(point) {
return {
left: parseInt(xaxes[axisNumber(point, "x") - 1].p2c(+point.x) + plotOffset.left),
top: parseInt(yaxes[axisNumber(point, "y") - 1].p2c(+point.y) + plotOffset.top)
};
};
plot.shutdown = shutdown;
plot.resize = function () {
getCanvasDimensions();
resizeCanvas(canvas);
resizeCanvas(overlay);
};
// public attributes
plot.hooks = hooks;
// initialize
initPlugins(plot);
parseOptions(options_);
setupCanvases();
setData(data_);
setupGrid();
draw();
bindEvents();
function executeHooks(hook, args) {
args = [plot].concat(args);
for (var i = 0; i < hook.length; ++i)
hook[i].apply(this, args);
}
function initPlugins() {
for (var i = 0; i < plugins.length; ++i) {
var p = plugins[i];
p.init(plot);
if (p.options)
$.extend(true, options, p.options);
}
}
function parseOptions(opts) {
var i;
$.extend(true, options, opts);
if (options.xaxis.color == null)
options.xaxis.color = options.grid.color;
if (options.yaxis.color == null)
options.yaxis.color = options.grid.color;
if (options.xaxis.tickColor == null) // backwards-compatibility
options.xaxis.tickColor = options.grid.tickColor;
if (options.yaxis.tickColor == null) // backwards-compatibility
options.yaxis.tickColor = options.grid.tickColor;
if (options.grid.borderColor == null)
options.grid.borderColor = options.grid.color;
if (options.grid.tickColor == null)
options.grid.tickColor = $.color.parse(options.grid.color).scale('a', 0.22).toString();
// fill in defaults in axes, copy at least always the
// first as the rest of the code assumes it'll be there
for (i = 0; i < Math.max(1, options.xaxes.length); ++i)
options.xaxes[i] = $.extend(true, {}, options.xaxis, options.xaxes[i]);
for (i = 0; i < Math.max(1, options.yaxes.length); ++i)
options.yaxes[i] = $.extend(true, {}, options.yaxis, options.yaxes[i]);
// backwards compatibility, to be removed in future
if (options.xaxis.noTicks && options.xaxis.ticks == null)
options.xaxis.ticks = options.xaxis.noTicks;
if (options.yaxis.noTicks && options.yaxis.ticks == null)
options.yaxis.ticks = options.yaxis.noTicks;
if (options.x2axis) {
options.xaxes[1] = $.extend(true, {}, options.xaxis, options.x2axis);
options.xaxes[1].position = "top";
}
if (options.y2axis) {
options.yaxes[1] = $.extend(true, {}, options.yaxis, options.y2axis);
options.yaxes[1].position = "right";
}
if (options.grid.coloredAreas)
options.grid.markings = options.grid.coloredAreas;
if (options.grid.coloredAreasColor)
options.grid.markingsColor = options.grid.coloredAreasColor;
if (options.lines)
$.extend(true, options.series.lines, options.lines);
if (options.points)
$.extend(true, options.series.points, options.points);
if (options.bars)
$.extend(true, options.series.bars, options.bars);
if (options.shadowSize != null)
options.series.shadowSize = options.shadowSize;
// save options on axes for future reference
for (i = 0; i < options.xaxes.length; ++i)
getOrCreateAxis(xaxes, i + 1).options = options.xaxes[i];
for (i = 0; i < options.yaxes.length; ++i)
getOrCreateAxis(yaxes, i + 1).options = options.yaxes[i];
// add hooks from options
for (var n in hooks)
if (options.hooks[n] && options.hooks[n].length)
hooks[n] = hooks[n].concat(options.hooks[n]);
executeHooks(hooks.processOptions, [options]);
}
function setData(d) {
series = parseData(d);
fillInSeriesOptions();
processData();
}
function parseData(d) {
var res = [];
for (var i = 0; i < d.length; ++i) {
var s = $.extend(true, {}, options.series);
if (d[i].data != null) {
s.data = d[i].data; // move the data instead of deep-copy
delete d[i].data;
$.extend(true, s, d[i]);
d[i].data = s.data;
}
else
s.data = d[i];
res.push(s);
}
return res;
}
function axisNumber(obj, coord) {
var a = obj[coord + "axis"];
if (typeof a == "object") // if we got a real axis, extract number
a = a.n;
if (typeof a != "number")
a = 1; // default to first axis
return a;
}
function allAxes() {
// return flat array without annoying null entries
return $.grep(xaxes.concat(yaxes), function (a) { return a; });
}
function canvasToAxisCoords(pos) {
// return an object with x/y corresponding to all used axes
var res = {}, i, axis;
for (i = 0; i < xaxes.length; ++i) {
axis = xaxes[i];
if (axis && axis.used)
res["x" + axis.n] = axis.c2p(pos.left);
}
for (i = 0; i < yaxes.length; ++i) {
axis = yaxes[i];
if (axis && axis.used)
res["y" + axis.n] = axis.c2p(pos.top);
}
if (res.x1 !== undefined)
res.x = res.x1;
if (res.y1 !== undefined)
res.y = res.y1;
return res;
}
function axisToCanvasCoords(pos) {
// get canvas coords from the first pair of x/y found in pos
var res = {}, i, axis, key;
for (i = 0; i < xaxes.length; ++i) {
axis = xaxes[i];
if (axis && axis.used) {
key = "x" + axis.n;
if (pos[key] == null && axis.n == 1)
key = "x";
if (pos[key] != null) {
res.left = axis.p2c(pos[key]);
break;
}
}
}
for (i = 0; i < yaxes.length; ++i) {
axis = yaxes[i];
if (axis && axis.used) {
key = "y" + axis.n;
if (pos[key] == null && axis.n == 1)
key = "y";
if (pos[key] != null) {
res.top = axis.p2c(pos[key]);
break;
}
}
}
return res;
}
function getOrCreateAxis(axes, number) {
if (!axes[number - 1])
axes[number - 1] = {
n: number, // save the number for future reference
direction: axes == xaxes ? "x" : "y",
options: $.extend(true, {}, axes == xaxes ? options.xaxis : options.yaxis)
};
return axes[number - 1];
}
function fillInSeriesOptions() {
var i;
// collect what we already got of colors
var neededColors = series.length,
usedColors = [],
assignedColors = [];
for (i = 0; i < series.length; ++i) {
var sc = series[i].color;
if (sc != null) {
--neededColors;
if (typeof sc == "number")
assignedColors.push(sc);
else
usedColors.push($.color.parse(series[i].color));
}
}
// we might need to generate more colors if higher indices
// are assigned
for (i = 0; i < assignedColors.length; ++i) {
neededColors = Math.max(neededColors, assignedColors[i] + 1);
}
// produce colors as needed
var colors = [], variation = 0;
i = 0;
while (colors.length < neededColors) {
var c;
if (options.colors.length == i) // check degenerate case
c = $.color.make(100, 100, 100);
else
c = $.color.parse(options.colors[i]);
// vary color if needed
var sign = variation % 2 == 1 ? -1 : 1;
c.scale('rgb', 1 + sign * Math.ceil(variation / 2) * 0.2)
// FIXME: if we're getting to close to something else,
// we should probably skip this one
colors.push(c);
++i;
if (i >= options.colors.length) {
i = 0;
++variation;
}
}
// fill in the options
var colori = 0, s;
for (i = 0; i < series.length; ++i) {
s = series[i];
// assign colors
if (s.color == null) {
s.color = colors[colori].toString();
++colori;
}
else if (typeof s.color == "number")
s.color = colors[s.color].toString();
// turn on lines automatically in case nothing is set
if (s.lines.show == null) {
var v, show = true;
for (v in s)
if (s[v] && s[v].show) {
show = false;
break;
}
if (show)
s.lines.show = true;
}
// setup axes
s.xaxis = getOrCreateAxis(xaxes, axisNumber(s, "x"));
s.yaxis = getOrCreateAxis(yaxes, axisNumber(s, "y"));
}
}
function processData() {
var topSentry = Number.POSITIVE_INFINITY,
bottomSentry = Number.NEGATIVE_INFINITY,
fakeInfinity = Number.MAX_VALUE,
i, j, k, m, length,
s, points, ps, x, y, axis, val, f, p;
function updateAxis(axis, min, max) {
if (min < axis.datamin && min != -fakeInfinity)
axis.datamin = min;
if (max > axis.datamax && max != fakeInfinity)
axis.datamax = max;
}
$.each(allAxes(), function (_, axis) {
// init axis
axis.datamin = topSentry;
axis.datamax = bottomSentry;
axis.used = false;
});
for (i = 0; i < series.length; ++i) {
s = series[i];
s.datapoints = { points: [] };
executeHooks(hooks.processRawData, [ s, s.data, s.datapoints ]);
}
// first pass: clean and copy data
for (i = 0; i < series.length; ++i) {
s = series[i];
var data = s.data, format = s.datapoints.format;
if (!format) {
format = [];
// find out how to copy
format.push({ x: true, number: true, required: true });
format.push({ y: true, number: true, required: true });
if (s.bars.show || (s.lines.show && s.lines.fill)) {
format.push({ y: true, number: true, required: false, defaultValue: 0 });
if (s.bars.horizontal) {
delete format[format.length - 1].y;
format[format.length - 1].x = true;
}
}
s.datapoints.format = format;
}
if (s.datapoints.pointsize != null)
continue; // already filled in
s.datapoints.pointsize = format.length;
ps = s.datapoints.pointsize;
points = s.datapoints.points;
insertSteps = s.lines.show && s.lines.steps;
s.xaxis.used = s.yaxis.used = true;
for (j = k = 0; j < data.length; ++j, k += ps) {
p = data[j];
var nullify = p == null;
if (!nullify) {
for (m = 0; m < ps; ++m) {
val = p[m];
f = format[m];
if (f) {
if (f.number && val != null) {
val = +val; // convert to number
if (isNaN(val))
val = null;
else if (val == Infinity)
val = fakeInfinity;
else if (val == -Infinity)
val = -fakeInfinity;
}
if (val == null) {
if (f.required)
nullify = true;
if (f.defaultValue != null)
val = f.defaultValue;
}
}
points[k + m] = val;
}
}
if (nullify) {
for (m = 0; m < ps; ++m) {
val = points[k + m];
if (val != null) {
f = format[m];
// extract min/max info
if (f.x)
updateAxis(s.xaxis, val, val);
if (f.y)
updateAxis(s.yaxis, val, val);
}
points[k + m] = null;
}
}
else {
// a little bit of line specific stuff that
// perhaps shouldn't be here, but lacking
// better means...
if (insertSteps && k > 0
&& points[k - ps] != null
&& points[k - ps] != points[k]
&& points[k - ps + 1] != points[k + 1]) {
// copy the point to make room for a middle point
for (m = 0; m < ps; ++m)
points[k + ps + m] = points[k + m];
// middle point has same y
points[k + 1] = points[k - ps + 1];
// we've added a point, better reflect that
k += ps;
}
}
}
}
// give the hooks a chance to run
for (i = 0; i < series.length; ++i) {
s = series[i];
executeHooks(hooks.processDatapoints, [ s, s.datapoints]);
}
// second pass: find datamax/datamin for auto-scaling
for (i = 0; i < series.length; ++i) {
s = series[i];
points = s.datapoints.points,
ps = s.datapoints.pointsize;
var xmin = topSentry, ymin = topSentry,
xmax = bottomSentry, ymax = bottomSentry;
for (j = 0; j < points.length; j += ps) {
if (points[j] == null)
continue;
for (m = 0; m < ps; ++m) {
val = points[j + m];
f = format[m];
if (!f || val == fakeInfinity || val == -fakeInfinity)
continue;
if (f.x) {
if (val < xmin)
xmin = val;
if (val > xmax)
xmax = val;
}
if (f.y) {
if (val < ymin)
ymin = val;
if (val > ymax)
ymax = val;
}
}
}
if (s.bars.show) {
// make sure we got room for the bar on the dancing floor
var delta = s.bars.align == "left" ? 0 : -s.bars.barWidth/2;
if (s.bars.horizontal) {
ymin += delta;
ymax += delta + s.bars.barWidth;
}
else {
xmin += delta;
xmax += delta + s.bars.barWidth;
}
}
updateAxis(s.xaxis, xmin, xmax);
updateAxis(s.yaxis, ymin, ymax);
}
$.each(allAxes(), function (_, axis) {
if (axis.datamin == topSentry)
axis.datamin = null;
if (axis.datamax == bottomSentry)
axis.datamax = null;
});
}
function makeCanvas(skipPositioning, cls) {
var c = document.createElement('canvas');
c.className = cls;
c.width = canvasWidth;
c.height = canvasHeight;
if (!skipPositioning)
$(c).css({ position: 'absolute', left: 0, top: 0 });
$(c).appendTo(placeholder);
if (!c.getContext) // excanvas hack
c = window.G_vmlCanvasManager.initElement(c);
// used for resetting in case we get replotted
c.getContext("2d").save();
return c;
}
function getCanvasDimensions() {
canvasWidth = placeholder.width();
canvasHeight = placeholder.height();
if (canvasWidth <= 0 || canvasHeight <= 0)
throw "Invalid dimensions for plot, width = " + canvasWidth + ", height = " + canvasHeight;
}
function resizeCanvas(c) {
// resizing should reset the state (excanvas seems to be
// buggy though)
if (c.width != canvasWidth)
c.width = canvasWidth;
if (c.height != canvasHeight)
c.height = canvasHeight;
// so try to get back to the initial state (even if it's
// gone now, this should be safe according to the spec)
var cctx = c.getContext("2d");
cctx.restore();
// and save again
cctx.save();
}
function setupCanvases() {
var reused,
existingCanvas = placeholder.children("canvas.base"),
existingOverlay = placeholder.children("canvas.overlay");
if (existingCanvas.length == 0 || existingOverlay == 0) {
// init everything
placeholder.html(""); // make sure placeholder is clear
placeholder.css({ padding: 0 }); // padding messes up the positioning
if (placeholder.css("position") == 'static')
placeholder.css("position", "relative"); // for positioning labels and overlay
getCanvasDimensions();
canvas = makeCanvas(true, "base");
overlay = makeCanvas(false, "overlay"); // overlay canvas for interactive features
reused = false;
}
else {
// reuse existing elements
canvas = existingCanvas.get(0);
overlay = existingOverlay.get(0);
reused = true;
}
ctx = canvas.getContext("2d");
octx = overlay.getContext("2d");
// we include the canvas in the event holder too, because IE 7
// sometimes has trouble with the stacking order
eventHolder = $([overlay, canvas]);
if (reused) {
// run shutdown in the old plot object
placeholder.data("plot").shutdown();
// reset reused canvases
plot.resize();
// make sure overlay pixels are cleared (canvas is cleared when we redraw)
octx.clearRect(0, 0, canvasWidth, canvasHeight);
// then whack any remaining obvious garbage left
eventHolder.unbind();
placeholder.children().not([canvas, overlay]).remove();
}
// save in case we get replotted
placeholder.data("plot", plot);
}
function bindEvents() {
// bind events
if (options.grid.hoverable) {
eventHolder.mousemove(onMouseMove);
eventHolder.mouseleave(onMouseLeave);
}
if (options.grid.clickable)
eventHolder.click(onClick);
executeHooks(hooks.bindEvents, [eventHolder]);
}
function shutdown() {
if (redrawTimeout)
clearTimeout(redrawTimeout);
eventHolder.unbind("mousemove", onMouseMove);
eventHolder.unbind("mouseleave", onMouseLeave);
eventHolder.unbind("click", onClick);
executeHooks(hooks.shutdown, [eventHolder]);
}
function setTransformationHelpers(axis) {
// set helper functions on the axis, assumes plot area
// has been computed already
function identity(x) { return x; }
var s, m, t = axis.options.transform || identity,
it = axis.options.inverseTransform;
// precompute how much the axis is scaling a point
// in canvas space
if (axis.direction == "x") {
s = axis.scale = plotWidth / Math.abs(t(axis.max) - t(axis.min));
m = Math.min(t(axis.max), t(axis.min));
}
else {
s = axis.scale = plotHeight / Math.abs(t(axis.max) - t(axis.min));
s = -s;
m = Math.max(t(axis.max), t(axis.min));
}
// data point to canvas coordinate
if (t == identity) // slight optimization
axis.p2c = function (p) { return (p - m) * s; };
else
axis.p2c = function (p) { return (t(p) - m) * s; };
// canvas coordinate to data point
if (!it)
axis.c2p = function (c) { return m + c / s; };
else
axis.c2p = function (c) { return it(m + c / s); };
}
function measureTickLabels(axis) {
var opts = axis.options, i, ticks = axis.ticks || [], labels = [],
l, w = opts.labelWidth, h = opts.labelHeight, dummyDiv;
function makeDummyDiv(labels, width) {
return $('<div style="position:absolute;top:-10000px;' + width + 'font-size:smaller">' +
'<div class="' + axis.direction + 'Axis ' + axis.direction + axis.n + 'Axis">'
+ labels.join("") + '</div></div>')
.appendTo(placeholder);
}
if (axis.direction == "x") {
// to avoid measuring the widths of the labels (it's slow), we
// construct fixed-size boxes and put the labels inside
// them, we don't need the exact figures and the
// fixed-size box content is easy to center
if (w == null)
w = Math.floor(canvasWidth / (ticks.length > 0 ? ticks.length : 1));
// measure x label heights
if (h == null) {
labels = [];
for (i = 0; i < ticks.length; ++i) {
l = ticks[i].label;
if (l)
labels.push('<div class="tickLabel" style="float:left;width:' + w + 'px">' + l + '</div>');
}
if (labels.length > 0) {
// stick them all in the same div and measure
// collective height
labels.push('<div style="clear:left"></div>');
dummyDiv = makeDummyDiv(labels, "width:10000px;");
h = dummyDiv.height();
dummyDiv.remove();
}
}
}
else if (w == null || h == null) {
// calculate y label dimensions
for (i = 0; i < ticks.length; ++i) {
l = ticks[i].label;
if (l)
labels.push('<div class="tickLabel">' + l + '</div>');
}
if (labels.length > 0) {
dummyDiv = makeDummyDiv(labels, "");
if (w == null)
w = dummyDiv.children().width();
if (h == null)
h = dummyDiv.find("div.tickLabel").height();
dummyDiv.remove();
}
}
if (w == null)
w = 0;
if (h == null)
h = 0;
axis.labelWidth = w;
axis.labelHeight = h;
}
function allocateAxisBoxFirstPhase(axis) {
// find the bounding box of the axis by looking at label
// widths/heights and ticks, make room by diminishing the
// plotOffset
var lw = axis.labelWidth,
lh = axis.labelHeight,
pos = axis.options.position,
tickLength = axis.options.tickLength,
axismargin = options.grid.axisMargin,
padding = options.grid.labelMargin,
all = axis.direction == "x" ? xaxes : yaxes,
index;
// determine axis margin
var samePosition = $.grep(all, function (a) {
return a && a.options.position == pos && a.reserveSpace;
});
if ($.inArray(axis, samePosition) == samePosition.length - 1)
axismargin = 0; // outermost
// determine tick length - if we're innermost, we can use "full"
if (tickLength == null)
tickLength = "full";
var sameDirection = $.grep(all, function (a) {
return a && a.reserveSpace;
});
var innermost = $.inArray(axis, sameDirection) == 0;
if (!innermost && tickLength == "full")
tickLength = 5;
if (!isNaN(+tickLength))
padding += +tickLength;
// compute box
if (axis.direction == "x") {
lh += padding;
if (pos == "bottom") {
plotOffset.bottom += lh + axismargin;
axis.box = { top: canvasHeight - plotOffset.bottom, height: lh };
}
else {
axis.box = { top: plotOffset.top + axismargin, height: lh };
plotOffset.top += lh + axismargin;
}
}
else {
lw += padding;
if (pos == "left") {
axis.box = { left: plotOffset.left + axismargin, width: lw };
plotOffset.left += lw + axismargin;
}
else {
plotOffset.right += lw + axismargin;
axis.box = { left: canvasWidth - plotOffset.right, width: lw };
}
}
// save for future reference
axis.position = pos;
axis.tickLength = tickLength;
axis.box.padding = padding;
axis.innermost = innermost;
}
function allocateAxisBoxSecondPhase(axis) {
// set remaining bounding box coordinates
if (axis.direction == "x") {
axis.box.left = plotOffset.left;
axis.box.width = plotWidth;
}
else {
axis.box.top = plotOffset.top;
axis.box.height = plotHeight;
}
}
function setupGrid() {
var i, axes = allAxes();
// first calculate the plot and axis box dimensions
$.each(axes, function (_, axis) {
axis.show = axis.options.show;
if (axis.show == null)
axis.show = axis.used; // by default an axis is visible if it's got data
axis.reserveSpace = axis.show || axis.options.reserveSpace;
setRange(axis);
});
allocatedAxes = $.grep(axes, function (axis) { return axis.reserveSpace; });
plotOffset.left = plotOffset.right = plotOffset.top = plotOffset.bottom = 0;
if (options.grid.show) {
$.each(allocatedAxes, function (_, axis) {
// make the ticks
setupTickGeneration(axis);
setTicks(axis);
snapRangeToTicks(axis, axis.ticks);
// find labelWidth/Height for axis
measureTickLabels(axis);
});
// with all dimensions in house, we can compute the
// axis boxes, start from the outside (reverse order)
for (i = allocatedAxes.length - 1; i >= 0; --i)
allocateAxisBoxFirstPhase(allocatedAxes[i]);
// make sure we've got enough space for things that
// might stick out
var minMargin = options.grid.minBorderMargin;
if (minMargin == null) {
minMargin = 0;
for (i = 0; i < series.length; ++i)
minMargin = Math.max(minMargin, series[i].points.radius + series[i].points.lineWidth/2);
}
for (var a in plotOffset) {
plotOffset[a] += options.grid.borderWidth;
plotOffset[a] = Math.max(minMargin, plotOffset[a]);
}
}
plotWidth = canvasWidth - plotOffset.left - plotOffset.right;
plotHeight = canvasHeight - plotOffset.bottom - plotOffset.top;
// now we got the proper plotWidth/Height, we can compute the scaling
$.each(axes, function (_, axis) {
setTransformationHelpers(axis);
});
if (options.grid.show) {
$.each(allocatedAxes, function (_, axis) {
allocateAxisBoxSecondPhase(axis);
});
insertAxisLabels();
}
insertLegend();
}
function setRange(axis) {
var opts = axis.options,
min = +(opts.min != null ? opts.min : axis.datamin),
max = +(opts.max != null ? opts.max : axis.datamax),
delta = max - min;
if (delta == 0.0) {
// degenerate case
var widen = max == 0 ? 1 : 0.01;
if (opts.min == null)
min -= widen;
// always widen max if we couldn't widen min to ensure we
// don't fall into min == max which doesn't work
if (opts.max == null || opts.min != null)
max += widen;
}
else {
// consider autoscaling
var margin = opts.autoscaleMargin;
if (margin != null) {
if (opts.min == null) {
min -= delta * margin;
// make sure we don't go below zero if all values
// are positive
if (min < 0 && axis.datamin != null && axis.datamin >= 0)
min = 0;
}
if (opts.max == null) {
max += delta * margin;
if (max > 0 && axis.datamax != null && axis.datamax <= 0)
max = 0;
}
}
}
axis.min = min;
axis.max = max;
}
function setupTickGeneration(axis) {
var opts = axis.options;
// estimate number of ticks
var noTicks;
if (typeof opts.ticks == "number" && opts.ticks > 0)
noTicks = opts.ticks;
else
// heuristic based on the model a*sqrt(x) fitted to
// some data points that seemed reasonable
noTicks = 0.3 * Math.sqrt(axis.direction == "x" ? canvasWidth : canvasHeight);
var delta = (axis.max - axis.min) / noTicks,
size, generator, unit, formatter, i, magn, norm;
if (opts.mode == "time") {
// pretty handling of time
// map of app. size of time units in milliseconds
var timeUnitSize = {
"second": 1000,
"minute": 60 * 1000,
"hour": 60 * 60 * 1000,
"day": 24 * 60 * 60 * 1000,
"month": 30 * 24 * 60 * 60 * 1000,
"year": 365.2425 * 24 * 60 * 60 * 1000
};
// the allowed tick sizes, after 1 year we use
// an integer algorithm
var spec = [
[1, "second"], [2, "second"], [5, "second"], [10, "second"],
[30, "second"],
[1, "minute"], [2, "minute"], [5, "minute"], [10, "minute"],
[30, "minute"],
[1, "hour"], [2, "hour"], [4, "hour"],
[8, "hour"], [12, "hour"],
[1, "day"], [2, "day"], [3, "day"],
[0.25, "month"], [0.5, "month"], [1, "month"],
[2, "month"], [3, "month"], [6, "month"],
[1, "year"]
];
var minSize = 0;
if (opts.minTickSize != null) {
if (typeof opts.tickSize == "number")
minSize = opts.tickSize;
else
minSize = opts.minTickSize[0] * timeUnitSize[opts.minTickSize[1]];
}
for (var i = 0; i < spec.length - 1; ++i)
if (delta < (spec[i][0] * timeUnitSize[spec[i][1]]
+ spec[i + 1][0] * timeUnitSize[spec[i + 1][1]]) / 2
&& spec[i][0] * timeUnitSize[spec[i][1]] >= minSize)
break;
size = spec[i][0];
unit = spec[i][1];
// special-case the possibility of several years
if (unit == "year") {
magn = Math.pow(10, Math.floor(Math.log(delta / timeUnitSize.year) / Math.LN10));
norm = (delta / timeUnitSize.year) / magn;
if (norm < 1.5)
size = 1;
else if (norm < 3)
size = 2;
else if (norm < 7.5)
size = 5;
else
size = 10;
size *= magn;
}
axis.tickSize = opts.tickSize || [size, unit];
generator = function(axis) {
var ticks = [],
tickSize = axis.tickSize[0], unit = axis.tickSize[1],
d = new Date(axis.min);
var step = tickSize * timeUnitSize[unit];
if (unit == "second")
d.setUTCSeconds(floorInBase(d.getUTCSeconds(), tickSize));
if (unit == "minute")
d.setUTCMinutes(floorInBase(d.getUTCMinutes(), tickSize));
if (unit == "hour")
d.setUTCHours(floorInBase(d.getUTCHours(), tickSize));
if (unit == "month")
d.setUTCMonth(floorInBase(d.getUTCMonth(), tickSize));
if (unit == "year")
d.setUTCFullYear(floorInBase(d.getUTCFullYear(), tickSize));
// reset smaller components
d.setUTCMilliseconds(0);
if (step >= timeUnitSize.minute)
d.setUTCSeconds(0);
if (step >= timeUnitSize.hour)
d.setUTCMinutes(0);
if (step >= timeUnitSize.day)
d.setUTCHours(0);
if (step >= timeUnitSize.day * 4)
d.setUTCDate(1);
if (step >= timeUnitSize.year)
d.setUTCMonth(0);
var carry = 0, v = Number.NaN, prev;
do {
prev = v;
v = d.getTime();
ticks.push(v);
if (unit == "month") {
if (tickSize < 1) {
// a bit complicated - we'll divide the month
// up but we need to take care of fractions
// so we don't end up in the middle of a day
d.setUTCDate(1);
var start = d.getTime();
d.setUTCMonth(d.getUTCMonth() + 1);
var end = d.getTime();
d.setTime(v + carry * timeUnitSize.hour + (end - start) * tickSize);
carry = d.getUTCHours();
d.setUTCHours(0);
}
else
d.setUTCMonth(d.getUTCMonth() + tickSize);
}
else if (unit == "year") {
d.setUTCFullYear(d.getUTCFullYear() + tickSize);
}
else
d.setTime(v + step);
} while (v < axis.max && v != prev);
return ticks;
};
formatter = function (v, axis) {
var d = new Date(v);
// first check global format
if (opts.timeformat != null)
return $.plot.formatDate(d, opts.timeformat, opts.monthNames);
var t = axis.tickSize[0] * timeUnitSize[axis.tickSize[1]];
var span = axis.max - axis.min;
var suffix = (opts.twelveHourClock) ? " %p" : "";
if (t < timeUnitSize.minute)
fmt = "%h:%M:%S" + suffix;
else if (t < timeUnitSize.day) {
if (span < 2 * timeUnitSize.day)
fmt = "%h:%M" + suffix;
else
fmt = "%b %d %h:%M" + suffix;
}
else if (t < timeUnitSize.month)
fmt = "%b %d";
else if (t < timeUnitSize.year) {
if (span < timeUnitSize.year)
fmt = "%b";
else
fmt = "%b %y";
}
else
fmt = "%y";
return $.plot.formatDate(d, fmt, opts.monthNames);
};
}
else {
// pretty rounding of base-10 numbers
var maxDec = opts.tickDecimals;
var dec = -Math.floor(Math.log(delta) / Math.LN10);
if (maxDec != null && dec > maxDec)
dec = maxDec;
magn = Math.pow(10, -dec);
norm = delta / magn; // norm is between 1.0 and 10.0
if (norm < 1.5)
size = 1;
else if (norm < 3) {
size = 2;
// special case for 2.5, requires an extra decimal
if (norm > 2.25 && (maxDec == null || dec + 1 <= maxDec)) {
size = 2.5;
++dec;
}
}
else if (norm < 7.5)
size = 5;
else
size = 10;
size *= magn;
if (opts.minTickSize != null && size < opts.minTickSize)
size = opts.minTickSize;
axis.tickDecimals = Math.max(0, maxDec != null ? maxDec : dec);
axis.tickSize = opts.tickSize || size;
generator = function (axis) {
var ticks = [];
// spew out all possible ticks
var start = floorInBase(axis.min, axis.tickSize),
i = 0, v = Number.NaN, prev;
do {
prev = v;
v = start + i * axis.tickSize;
ticks.push(v);
++i;
} while (v < axis.max && v != prev);
return ticks;
};
formatter = function (v, axis) {
return v.toFixed(axis.tickDecimals);
};
}
if (opts.alignTicksWithAxis != null) {
var otherAxis = (axis.direction == "x" ? xaxes : yaxes)[opts.alignTicksWithAxis - 1];
if (otherAxis && otherAxis.used && otherAxis != axis) {
// consider snapping min/max to outermost nice ticks
var niceTicks = generator(axis);
if (niceTicks.length > 0) {
if (opts.min == null)
axis.min = Math.min(axis.min, niceTicks[0]);
if (opts.max == null && niceTicks.length > 1)
axis.max = Math.max(axis.max, niceTicks[niceTicks.length - 1]);
}
generator = function (axis) {
// copy ticks, scaled to this axis
var ticks = [], v, i;
for (i = 0; i < otherAxis.ticks.length; ++i) {
v = (otherAxis.ticks[i].v - otherAxis.min) / (otherAxis.max - otherAxis.min);
v = axis.min + v * (axis.max - axis.min);
ticks.push(v);
}
return ticks;
};
// we might need an extra decimal since forced
// ticks don't necessarily fit naturally
if (axis.mode != "time" && opts.tickDecimals == null) {
var extraDec = Math.max(0, -Math.floor(Math.log(delta) / Math.LN10) + 1),
ts = generator(axis);
// only proceed if the tick interval rounded
// with an extra decimal doesn't give us a
// zero at end
if (!(ts.length > 1 && /\..*0$/.test((ts[1] - ts[0]).toFixed(extraDec))))
axis.tickDecimals = extraDec;
}
}
}
axis.tickGenerator = generator;
if ($.isFunction(opts.tickFormatter))
axis.tickFormatter = function (v, axis) { return "" + opts.tickFormatter(v, axis); };
else
axis.tickFormatter = formatter;
}
function setTicks(axis) {
var oticks = axis.options.ticks, ticks = [];
if (oticks == null || (typeof oticks == "number" && oticks > 0))
ticks = axis.tickGenerator(axis);
else if (oticks) {
if ($.isFunction(oticks))
// generate the ticks
ticks = oticks({ min: axis.min, max: axis.max });
else
ticks = oticks;
}
// clean up/labelify the supplied ticks, copy them over
var i, v;
axis.ticks = [];
for (i = 0; i < ticks.length; ++i) {
var label = null;
var t = ticks[i];
if (typeof t == "object") {
v = +t[0];
if (t.length > 1)
label = t[1];
}
else
v = +t;
if (label == null)
label = axis.tickFormatter(v, axis);
if (!isNaN(v))
axis.ticks.push({ v: v, label: label });
}
}
function snapRangeToTicks(axis, ticks) {
if (axis.options.autoscaleMargin && ticks.length > 0) {
// snap to ticks
if (axis.options.min == null)
axis.min = Math.min(axis.min, ticks[0].v);
if (axis.options.max == null && ticks.length > 1)
axis.max = Math.max(axis.max, ticks[ticks.length - 1].v);
}
}
function draw() {
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
var grid = options.grid;
// draw background, if any
if (grid.show && grid.backgroundColor)
drawBackground();
if (grid.show && !grid.aboveData)
drawGrid();
for (var i = 0; i < series.length; ++i) {
executeHooks(hooks.drawSeries, [ctx, series[i]]);
drawSeries(series[i]);
}
executeHooks(hooks.draw, [ctx]);
if (grid.show && grid.aboveData)
drawGrid();
}
function extractRange(ranges, coord) {
var axis, from, to, key, axes = allAxes();
for (i = 0; i < axes.length; ++i) {
axis = axes[i];
if (axis.direction == coord) {
key = coord + axis.n + "axis";
if (!ranges[key] && axis.n == 1)
key = coord + "axis"; // support x1axis as xaxis
if (ranges[key]) {
from = ranges[key].from;
to = ranges[key].to;
break;
}
}
}
// backwards-compat stuff - to be removed in future
if (!ranges[key]) {
axis = coord == "x" ? xaxes[0] : yaxes[0];
from = ranges[coord + "1"];
to = ranges[coord + "2"];
}
// auto-reverse as an added bonus
if (from != null && to != null && from > to) {
var tmp = from;
from = to;
to = tmp;
}
return { from: from, to: to, axis: axis };
}
function drawBackground() {
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
ctx.fillStyle = getColorOrGradient(options.grid.backgroundColor, plotHeight, 0, "rgba(255, 255, 255, 0)");
ctx.fillRect(0, 0, plotWidth, plotHeight);
ctx.restore();
}
function drawGrid() {
var i;
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
// draw markings
var markings = options.grid.markings;
if (markings) {
if ($.isFunction(markings)) {
var axes = plot.getAxes();
// xmin etc. is backwards compatibility, to be
// removed in the future
axes.xmin = axes.xaxis.min;
axes.xmax = axes.xaxis.max;
axes.ymin = axes.yaxis.min;
axes.ymax = axes.yaxis.max;
markings = markings(axes);
}
for (i = 0; i < markings.length; ++i) {
var m = markings[i],
xrange = extractRange(m, "x"),
yrange = extractRange(m, "y");
// fill in missing
if (xrange.from == null)
xrange.from = xrange.axis.min;
if (xrange.to == null)
xrange.to = xrange.axis.max;
if (yrange.from == null)
yrange.from = yrange.axis.min;
if (yrange.to == null)
yrange.to = yrange.axis.max;
// clip
if (xrange.to < xrange.axis.min || xrange.from > xrange.axis.max ||
yrange.to < yrange.axis.min || yrange.from > yrange.axis.max)
continue;
xrange.from = Math.max(xrange.from, xrange.axis.min);
xrange.to = Math.min(xrange.to, xrange.axis.max);
yrange.from = Math.max(yrange.from, yrange.axis.min);
yrange.to = Math.min(yrange.to, yrange.axis.max);
if (xrange.from == xrange.to && yrange.from == yrange.to)
continue;
// then draw
xrange.from = xrange.axis.p2c(xrange.from);
xrange.to = xrange.axis.p2c(xrange.to);
yrange.from = yrange.axis.p2c(yrange.from);
yrange.to = yrange.axis.p2c(yrange.to);
if (xrange.from == xrange.to || yrange.from == yrange.to) {
// draw line
ctx.beginPath();
ctx.strokeStyle = m.color || options.grid.markingsColor;
ctx.lineWidth = m.lineWidth || options.grid.markingsLineWidth;
ctx.moveTo(xrange.from, yrange.from);
ctx.lineTo(xrange.to, yrange.to);
ctx.stroke();
}
else {
// fill area
ctx.fillStyle = m.color || options.grid.markingsColor;
ctx.fillRect(xrange.from, yrange.to,
xrange.to - xrange.from,
yrange.from - yrange.to);
}
}
}
// draw the ticks
var axes = allAxes(), bw = options.grid.borderWidth;
for (var j = 0; j < axes.length; ++j) {
var axis = axes[j], box = axis.box,
t = axis.tickLength, x, y, xoff, yoff;
if (!axis.show || axis.ticks.length == 0)
continue
ctx.strokeStyle = axis.options.tickColor || $.color.parse(axis.options.color).scale('a', 0.22).toString();
ctx.lineWidth = 1;
// find the edges
if (axis.direction == "x") {
x = 0;
if (t == "full")
y = (axis.position == "top" ? 0 : plotHeight);
else
y = box.top - plotOffset.top + (axis.position == "top" ? box.height : 0);
}
else {
y = 0;
if (t == "full")
x = (axis.position == "left" ? 0 : plotWidth);
else
x = box.left - plotOffset.left + (axis.position == "left" ? box.width : 0);
}
// draw tick bar
if (!axis.innermost) {
ctx.beginPath();
xoff = yoff = 0;
if (axis.direction == "x")
xoff = plotWidth;
else
yoff = plotHeight;
if (ctx.lineWidth == 1) {
x = Math.floor(x) + 0.5;
y = Math.floor(y) + 0.5;
}
ctx.moveTo(x, y);
ctx.lineTo(x + xoff, y + yoff);
ctx.stroke();
}
// draw ticks
ctx.beginPath();
for (i = 0; i < axis.ticks.length; ++i) {
var v = axis.ticks[i].v;
xoff = yoff = 0;
if (v < axis.min || v > axis.max
// skip those lying on the axes if we got a border
|| (t == "full" && bw > 0
&& (v == axis.min || v == axis.max)))
continue;
if (axis.direction == "x") {
x = axis.p2c(v);
yoff = t == "full" ? -plotHeight : t;
if (axis.position == "top")
yoff = -yoff;
}
else {
y = axis.p2c(v);
xoff = t == "full" ? -plotWidth : t;
if (axis.position == "left")
xoff = -xoff;
}
if (ctx.lineWidth == 1) {
if (axis.direction == "x")
x = Math.floor(x) + 0.5;
else
y = Math.floor(y) + 0.5;
}
ctx.moveTo(x, y);
ctx.lineTo(x + xoff, y + yoff);
}
ctx.stroke();
}
// draw border
if (bw) {
ctx.lineWidth = bw;
ctx.strokeStyle = options.grid.borderColor;
ctx.strokeRect(-bw/2, -bw/2, plotWidth + bw, plotHeight + bw);
}
ctx.restore();
}
function insertAxisLabels() {
placeholder.find(".tickLabels").remove();
var html = ['<div class="tickLabels" style="font-size:smaller">'];
var axes = allAxes();
for (var j = 0; j < axes.length; ++j) {
var axis = axes[j], box = axis.box;
if (!axis.show)
continue;
//debug: html.push('<div style="position:absolute;opacity:0.10;background-color:red;left:' + box.left + 'px;top:' + box.top + 'px;width:' + box.width + 'px;height:' + box.height + 'px"></div>')
html.push('<div class="' + axis.direction + 'Axis ' + axis.direction + axis.n + 'Axis" style="color:' + axis.options.color + '">');
for (var i = 0; i < axis.ticks.length; ++i) {
var tick = axis.ticks[i];
if (!tick.label || tick.v < axis.min || tick.v > axis.max)
continue;
var pos = {}, align;
if (axis.direction == "x") {
align = "center";
pos.left = Math.round(plotOffset.left + axis.p2c(tick.v) - axis.labelWidth/2);
if (axis.position == "bottom")
pos.top = box.top + box.padding;
else
pos.bottom = canvasHeight - (box.top + box.height - box.padding);
}
else {
pos.top = Math.round(plotOffset.top + axis.p2c(tick.v) - axis.labelHeight/2);
if (axis.position == "left") {
pos.right = canvasWidth - (box.left + box.width - box.padding)
align = "right";
}
else {
pos.left = box.left + box.padding;
align = "left";
}
}
pos.width = axis.labelWidth;
var style = ["position:absolute", "text-align:" + align ];
for (var a in pos)
style.push(a + ":" + pos[a] + "px")
html.push('<div class="tickLabel" style="' + style.join(';') + '">' + tick.label + '</div>');
}
html.push('</div>');
}
html.push('</div>');
placeholder.append(html.join(""));
}
function drawSeries(series) {
if (series.lines.show)
drawSeriesLines(series);
if (series.bars.show)
drawSeriesBars(series);
if (series.points.show)
drawSeriesPoints(series);
}
function drawSeriesLines(series) {
function plotLine(datapoints, xoffset, yoffset, axisx, axisy) {
var points = datapoints.points,
ps = datapoints.pointsize,
prevx = null, prevy = null;
ctx.beginPath();
for (var i = ps; i < points.length; i += ps) {
var x1 = points[i - ps], y1 = points[i - ps + 1],
x2 = points[i], y2 = points[i + 1];
if (x1 == null || x2 == null)
continue;
// clip with ymin
if (y1 <= y2 && y1 < axisy.min) {
if (y2 < axisy.min)
continue; // line segment is outside
// compute new intersection point
x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
y1 = axisy.min;
}
else if (y2 <= y1 && y2 < axisy.min) {
if (y1 < axisy.min)
continue;
x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
y2 = axisy.min;
}
// clip with ymax
if (y1 >= y2 && y1 > axisy.max) {
if (y2 > axisy.max)
continue;
x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
y1 = axisy.max;
}
else if (y2 >= y1 && y2 > axisy.max) {
if (y1 > axisy.max)
continue;
x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
y2 = axisy.max;
}
// clip with xmin
if (x1 <= x2 && x1 < axisx.min) {
if (x2 < axisx.min)
continue;
y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
x1 = axisx.min;
}
else if (x2 <= x1 && x2 < axisx.min) {
if (x1 < axisx.min)
continue;
y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
x2 = axisx.min;
}
// clip with xmax
if (x1 >= x2 && x1 > axisx.max) {
if (x2 > axisx.max)
continue;
y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
x1 = axisx.max;
}
else if (x2 >= x1 && x2 > axisx.max) {
if (x1 > axisx.max)
continue;
y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
x2 = axisx.max;
}
if (x1 != prevx || y1 != prevy)
ctx.moveTo(axisx.p2c(x1) + xoffset, axisy.p2c(y1) + yoffset);
prevx = x2;
prevy = y2;
ctx.lineTo(axisx.p2c(x2) + xoffset, axisy.p2c(y2) + yoffset);
}
ctx.stroke();
}
function plotLineArea(datapoints, axisx, axisy) {
var points = datapoints.points,
ps = datapoints.pointsize,
bottom = Math.min(Math.max(0, axisy.min), axisy.max),
i = 0, top, areaOpen = false,
ypos = 1, segmentStart = 0, segmentEnd = 0;
// we process each segment in two turns, first forward
// direction to sketch out top, then once we hit the
// end we go backwards to sketch the bottom
while (true) {
if (ps > 0 && i > points.length + ps)
break;
i += ps; // ps is negative if going backwards
var x1 = points[i - ps],
y1 = points[i - ps + ypos],
x2 = points[i], y2 = points[i + ypos];
if (areaOpen) {
if (ps > 0 && x1 != null && x2 == null) {
// at turning point
segmentEnd = i;
ps = -ps;
ypos = 2;
continue;
}
if (ps < 0 && i == segmentStart + ps) {
// done with the reverse sweep
ctx.fill();
areaOpen = false;
ps = -ps;
ypos = 1;
i = segmentStart = segmentEnd + ps;
continue;
}
}
if (x1 == null || x2 == null)
continue;
// clip x values
// clip with xmin
if (x1 <= x2 && x1 < axisx.min) {
if (x2 < axisx.min)
continue;
y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
x1 = axisx.min;
}
else if (x2 <= x1 && x2 < axisx.min) {
if (x1 < axisx.min)
continue;
y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
x2 = axisx.min;
}
// clip with xmax
if (x1 >= x2 && x1 > axisx.max) {
if (x2 > axisx.max)
continue;
y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
x1 = axisx.max;
}
else if (x2 >= x1 && x2 > axisx.max) {
if (x1 > axisx.max)
continue;
y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
x2 = axisx.max;
}
if (!areaOpen) {
// open area
ctx.beginPath();
ctx.moveTo(axisx.p2c(x1), axisy.p2c(bottom));
areaOpen = true;
}
// now first check the case where both is outside
if (y1 >= axisy.max && y2 >= axisy.max) {
ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.max));
ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.max));
continue;
}
else if (y1 <= axisy.min && y2 <= axisy.min) {
ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.min));
ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.min));
continue;
}
// else it's a bit more complicated, there might
// be a flat maxed out rectangle first, then a
// triangular cutout or reverse; to find these
// keep track of the current x values
var x1old = x1, x2old = x2;
// clip the y values, without shortcutting, we
// go through all cases in turn
// clip with ymin
if (y1 <= y2 && y1 < axisy.min && y2 >= axisy.min) {
x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
y1 = axisy.min;
}
else if (y2 <= y1 && y2 < axisy.min && y1 >= axisy.min) {
x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
y2 = axisy.min;
}
// clip with ymax
if (y1 >= y2 && y1 > axisy.max && y2 <= axisy.max) {
x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
y1 = axisy.max;
}
else if (y2 >= y1 && y2 > axisy.max && y1 <= axisy.max) {
x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
y2 = axisy.max;
}
// if the x value was changed we got a rectangle
// to fill
if (x1 != x1old) {
ctx.lineTo(axisx.p2c(x1old), axisy.p2c(y1));
// it goes to (x1, y1), but we fill that below
}
// fill triangular section, this sometimes result
// in redundant points if (x1, y1) hasn't changed
// from previous line to, but we just ignore that
ctx.lineTo(axisx.p2c(x1), axisy.p2c(y1));
ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2));
// fill the other rectangle if it's there
if (x2 != x2old) {
ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2));
ctx.lineTo(axisx.p2c(x2old), axisy.p2c(y2));
}
}
}
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
ctx.lineJoin = "round";
var lw = series.lines.lineWidth,
sw = series.shadowSize;
// FIXME: consider another form of shadow when filling is turned on
if (lw > 0 && sw > 0) {
// draw shadow as a thick and thin line with transparency
ctx.lineWidth = sw;
ctx.strokeStyle = "rgba(0,0,0,0.1)";
// position shadow at angle from the mid of line
var angle = Math.PI/18;
plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/2), Math.cos(angle) * (lw/2 + sw/2), series.xaxis, series.yaxis);
ctx.lineWidth = sw/2;
plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/4), Math.cos(angle) * (lw/2 + sw/4), series.xaxis, series.yaxis);
}
ctx.lineWidth = lw;
ctx.strokeStyle = series.color;
var fillStyle = getFillStyle(series.lines, series.color, 0, plotHeight);
if (fillStyle) {
ctx.fillStyle = fillStyle;
plotLineArea(series.datapoints, series.xaxis, series.yaxis);
}
if (lw > 0)
plotLine(series.datapoints, 0, 0, series.xaxis, series.yaxis);
ctx.restore();
}
function drawSeriesPoints(series) {
function plotPoints(datapoints, radius, fillStyle, offset, shadow, axisx, axisy, symbol) {
var points = datapoints.points, ps = datapoints.pointsize;
for (var i = 0; i < points.length; i += ps) {
var x = points[i], y = points[i + 1];
if (x == null || x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max)
continue;
ctx.beginPath();
x = axisx.p2c(x);
y = axisy.p2c(y) + offset;
if (symbol == "circle")
ctx.arc(x, y, radius, 0, shadow ? Math.PI : Math.PI * 2, false);
else
symbol(ctx, x, y, radius, shadow);
ctx.closePath();
if (fillStyle) {
ctx.fillStyle = fillStyle;
ctx.fill();
}
ctx.stroke();
}
}
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
var lw = series.points.lineWidth,
sw = series.shadowSize,
radius = series.points.radius,
symbol = series.points.symbol;
if (lw > 0 && sw > 0) {
// draw shadow in two steps
var w = sw / 2;
ctx.lineWidth = w;
ctx.strokeStyle = "rgba(0,0,0,0.1)";
plotPoints(series.datapoints, radius, null, w + w/2, true,
series.xaxis, series.yaxis, symbol);
ctx.strokeStyle = "rgba(0,0,0,0.2)";
plotPoints(series.datapoints, radius, null, w/2, true,
series.xaxis, series.yaxis, symbol);
}
ctx.lineWidth = lw;
ctx.strokeStyle = series.color;
plotPoints(series.datapoints, radius,
getFillStyle(series.points, series.color), 0, false,
series.xaxis, series.yaxis, symbol);
ctx.restore();
}
function drawBar(x, y, b, barLeft, barRight, offset, fillStyleCallback, axisx, axisy, c, horizontal, lineWidth) {
var left, right, bottom, top,
drawLeft, drawRight, drawTop, drawBottom,
tmp;
// in horizontal mode, we start the bar from the left
// instead of from the bottom so it appears to be
// horizontal rather than vertical
if (horizontal) {
drawBottom = drawRight = drawTop = true;
drawLeft = false;
left = b;
right = x;
top = y + barLeft;
bottom = y + barRight;
// account for negative bars
if (right < left) {
tmp = right;
right = left;
left = tmp;
drawLeft = true;
drawRight = false;
}
}
else {
drawLeft = drawRight = drawTop = true;
drawBottom = false;
left = x + barLeft;
right = x + barRight;
bottom = b;
top = y;
// account for negative bars
if (top < bottom) {
tmp = top;
top = bottom;
bottom = tmp;
drawBottom = true;
drawTop = false;
}
}
// clip
if (right < axisx.min || left > axisx.max ||
top < axisy.min || bottom > axisy.max)
return;
if (left < axisx.min) {
left = axisx.min;
drawLeft = false;
}
if (right > axisx.max) {
right = axisx.max;
drawRight = false;
}
if (bottom < axisy.min) {
bottom = axisy.min;
drawBottom = false;
}
if (top > axisy.max) {
top = axisy.max;
drawTop = false;
}
left = axisx.p2c(left);
bottom = axisy.p2c(bottom);
right = axisx.p2c(right);
top = axisy.p2c(top);
// fill the bar
if (fillStyleCallback) {
c.beginPath();
c.moveTo(left, bottom);
c.lineTo(left, top);
c.lineTo(right, top);
c.lineTo(right, bottom);
c.fillStyle = fillStyleCallback(bottom, top);
c.fill();
}
// draw outline
if (lineWidth > 0 && (drawLeft || drawRight || drawTop || drawBottom)) {
c.beginPath();
// FIXME: inline moveTo is buggy with excanvas
c.moveTo(left, bottom + offset);
if (drawLeft)
c.lineTo(left, top + offset);
else
c.moveTo(left, top + offset);
if (drawTop)
c.lineTo(right, top + offset);
else
c.moveTo(right, top + offset);
if (drawRight)
c.lineTo(right, bottom + offset);
else
c.moveTo(right, bottom + offset);
if (drawBottom)
c.lineTo(left, bottom + offset);
else
c.moveTo(left, bottom + offset);
c.stroke();
}
}
function drawSeriesBars(series) {
function plotBars(datapoints, barLeft, barRight, offset, fillStyleCallback, axisx, axisy) {
var points = datapoints.points, ps = datapoints.pointsize;
for (var i = 0; i < points.length; i += ps) {
if (points[i] == null)
continue;
drawBar(points[i], points[i + 1], points[i + 2], barLeft, barRight, offset, fillStyleCallback, axisx, axisy, ctx, series.bars.horizontal, series.bars.lineWidth);
}
}
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
// FIXME: figure out a way to add shadows (for instance along the right edge)
ctx.lineWidth = series.bars.lineWidth;
ctx.strokeStyle = series.color;
var barLeft = series.bars.align == "left" ? 0 : -series.bars.barWidth/2;
var fillStyleCallback = series.bars.fill ? function (bottom, top) { return getFillStyle(series.bars, series.color, bottom, top); } : null;
plotBars(series.datapoints, barLeft, barLeft + series.bars.barWidth, 0, fillStyleCallback, series.xaxis, series.yaxis);
ctx.restore();
}
function getFillStyle(filloptions, seriesColor, bottom, top) {
var fill = filloptions.fill;
if (!fill)
return null;
if (filloptions.fillColor)
return getColorOrGradient(filloptions.fillColor, bottom, top, seriesColor);
var c = $.color.parse(seriesColor);
c.a = typeof fill == "number" ? fill : 0.4;
c.normalize();
return c.toString();
}
function insertLegend() {
placeholder.find(".legend").remove();
if (!options.legend.show)
return;
var fragments = [], rowStarted = false,
lf = options.legend.labelFormatter, s, label;
for (var i = 0; i < series.length; ++i) {
s = series[i];
label = s.label;
if (!label)
continue;
if (i % options.legend.noColumns == 0) {
if (rowStarted)
fragments.push('</tr>');
fragments.push('<tr>');
rowStarted = true;
}
if (lf)
label = lf(label, s);
fragments.push(
'<td class="legendColorBox"><div style="border:1px solid ' + options.legend.labelBoxBorderColor + ';padding:1px"><div style="width:4px;height:0;border:5px solid ' + s.color + ';overflow:hidden"></div></div></td>' +
'<td class="legendLabel">' + label + '</td>');
}
if (rowStarted)
fragments.push('</tr>');
if (fragments.length == 0)
return;
var table = '<table style="font-size:smaller;color:' + options.grid.color + '">' + fragments.join("") + '</table>';
if (options.legend.container != null)
$(options.legend.container).html(table);
else {
var pos = "",
p = options.legend.position,
m = options.legend.margin;
if (m[0] == null)
m = [m, m];
if (p.charAt(0) == "n")
pos += 'top:' + (m[1] + plotOffset.top) + 'px;';
else if (p.charAt(0) == "s")
pos += 'bottom:' + (m[1] + plotOffset.bottom) + 'px;';
if (p.charAt(1) == "e")
pos += 'right:' + (m[0] + plotOffset.right) + 'px;';
else if (p.charAt(1) == "w")
pos += 'left:' + (m[0] + plotOffset.left) + 'px;';
var legend = $('<div class="legend">' + table.replace('style="', 'style="position:absolute;' + pos +';') + '</div>').appendTo(placeholder);
if (options.legend.backgroundOpacity != 0.0) {
// put in the transparent background
// separately to avoid blended labels and
// label boxes
var c = options.legend.backgroundColor;
if (c == null) {
c = options.grid.backgroundColor;
if (c && typeof c == "string")
c = $.color.parse(c);
else
c = $.color.extract(legend, 'background-color');
c.a = 1;
c = c.toString();
}
var div = legend.children();
$('<div style="position:absolute;width:' + div.width() + 'px;height:' + div.height() + 'px;' + pos +'background-color:' + c + ';"> </div>').prependTo(legend).css('opacity', options.legend.backgroundOpacity);
}
}
}
// interactive features
var highlights = [],
redrawTimeout = null;
// returns the data item the mouse is over, or null if none is found
function findNearbyItem(mouseX, mouseY, seriesFilter) {
var maxDistance = options.grid.mouseActiveRadius,
smallestDistance = maxDistance * maxDistance + 1,
item = null, foundPoint = false, i, j;
for (i = series.length - 1; i >= 0; --i) {
if (!seriesFilter(series[i]))
continue;
var s = series[i],
axisx = s.xaxis,
axisy = s.yaxis,
points = s.datapoints.points,
ps = s.datapoints.pointsize,
mx = axisx.c2p(mouseX), // precompute some stuff to make the loop faster
my = axisy.c2p(mouseY),
maxx = maxDistance / axisx.scale,
maxy = maxDistance / axisy.scale;
// with inverse transforms, we can't use the maxx/maxy
// optimization, sadly
if (axisx.options.inverseTransform)
maxx = Number.MAX_VALUE;
if (axisy.options.inverseTransform)
maxy = Number.MAX_VALUE;
if (s.lines.show || s.points.show) {
for (j = 0; j < points.length; j += ps) {
var x = points[j], y = points[j + 1];
if (x == null)
continue;
// For points and lines, the cursor must be within a
// certain distance to the data point
if (x - mx > maxx || x - mx < -maxx ||
y - my > maxy || y - my < -maxy)
continue;
// We have to calculate distances in pixels, not in
// data units, because the scales of the axes may be different
var dx = Math.abs(axisx.p2c(x) - mouseX),
dy = Math.abs(axisy.p2c(y) - mouseY),
dist = dx * dx + dy * dy; // we save the sqrt
// use <= to ensure last point takes precedence
// (last generally means on top of)
if (dist < smallestDistance) {
smallestDistance = dist;
item = [i, j / ps];
}
}
}
if (s.bars.show && !item) { // no other point can be nearby
var barLeft = s.bars.align == "left" ? 0 : -s.bars.barWidth/2,
barRight = barLeft + s.bars.barWidth;
for (j = 0; j < points.length; j += ps) {
var x = points[j], y = points[j + 1], b = points[j + 2];
if (x == null)
continue;
// for a bar graph, the cursor must be inside the bar
if (series[i].bars.horizontal ?
(mx <= Math.max(b, x) && mx >= Math.min(b, x) &&
my >= y + barLeft && my <= y + barRight) :
(mx >= x + barLeft && mx <= x + barRight &&
my >= Math.min(b, y) && my <= Math.max(b, y)))
item = [i, j / ps];
}
}
}
if (item) {
i = item[0];
j = item[1];
ps = series[i].datapoints.pointsize;
return { datapoint: series[i].datapoints.points.slice(j * ps, (j + 1) * ps),
dataIndex: j,
series: series[i],
seriesIndex: i };
}
return null;
}
function onMouseMove(e) {
if (options.grid.hoverable)
triggerClickHoverEvent("plothover", e,
function (s) { return s["hoverable"] != false; });
}
function onMouseLeave(e) {
if (options.grid.hoverable)
triggerClickHoverEvent("plothover", e,
function (s) { return false; });
}
function onClick(e) {
triggerClickHoverEvent("plotclick", e,
function (s) { return s["clickable"] != false; });
}
// trigger click or hover event (they send the same parameters
// so we share their code)
function triggerClickHoverEvent(eventname, event, seriesFilter) {
var offset = eventHolder.offset(),
canvasX = event.pageX - offset.left - plotOffset.left,
canvasY = event.pageY - offset.top - plotOffset.top,
pos = canvasToAxisCoords({ left: canvasX, top: canvasY });
pos.pageX = event.pageX;
pos.pageY = event.pageY;
var item = findNearbyItem(canvasX, canvasY, seriesFilter);
if (item) {
// fill in mouse pos for any listeners out there
item.pageX = parseInt(item.series.xaxis.p2c(item.datapoint[0]) + offset.left + plotOffset.left);
item.pageY = parseInt(item.series.yaxis.p2c(item.datapoint[1]) + offset.top + plotOffset.top);
}
if (options.grid.autoHighlight) {
// clear auto-highlights
for (var i = 0; i < highlights.length; ++i) {
var h = highlights[i];
if (h.auto == eventname &&
!(item && h.series == item.series &&
h.point[0] == item.datapoint[0] &&
h.point[1] == item.datapoint[1]))
unhighlight(h.series, h.point);
}
if (item)
highlight(item.series, item.datapoint, eventname);
}
placeholder.trigger(eventname, [ pos, item ]);
}
function triggerRedrawOverlay() {
if (!redrawTimeout)
redrawTimeout = setTimeout(drawOverlay, 30);
}
function drawOverlay() {
redrawTimeout = null;
// draw highlights
octx.save();
octx.clearRect(0, 0, canvasWidth, canvasHeight);
octx.translate(plotOffset.left, plotOffset.top);
var i, hi;
for (i = 0; i < highlights.length; ++i) {
hi = highlights[i];
if (hi.series.bars.show)
drawBarHighlight(hi.series, hi.point);
else
drawPointHighlight(hi.series, hi.point);
}
octx.restore();
executeHooks(hooks.drawOverlay, [octx]);
}
function highlight(s, point, auto) {
if (typeof s == "number")
s = series[s];
if (typeof point == "number") {
var ps = s.datapoints.pointsize;
point = s.datapoints.points.slice(ps * point, ps * (point + 1));
}
var i = indexOfHighlight(s, point);
if (i == -1) {
highlights.push({ series: s, point: point, auto: auto });
triggerRedrawOverlay();
}
else if (!auto)
highlights[i].auto = false;
}
function unhighlight(s, point) {
if (s == null && point == null) {
highlights = [];
triggerRedrawOverlay();
}
if (typeof s == "number")
s = series[s];
if (typeof point == "number")
point = s.data[point];
var i = indexOfHighlight(s, point);
if (i != -1) {
highlights.splice(i, 1);
triggerRedrawOverlay();
}
}
function indexOfHighlight(s, p) {
for (var i = 0; i < highlights.length; ++i) {
var h = highlights[i];
if (h.series == s && h.point[0] == p[0]
&& h.point[1] == p[1])
return i;
}
return -1;
}
function drawPointHighlight(series, point) {
var x = point[0], y = point[1],
axisx = series.xaxis, axisy = series.yaxis;
if (x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max)
return;
var pointRadius = series.points.radius + series.points.lineWidth / 2;
octx.lineWidth = pointRadius;
octx.strokeStyle = $.color.parse(series.color).scale('a', 0.5).toString();
var radius = 1.5 * pointRadius,
x = axisx.p2c(x),
y = axisy.p2c(y);
octx.beginPath();
if (series.points.symbol == "circle")
octx.arc(x, y, radius, 0, 2 * Math.PI, false);
else
series.points.symbol(octx, x, y, radius, false);
octx.closePath();
octx.stroke();
}
function drawBarHighlight(series, point) {
octx.lineWidth = series.bars.lineWidth;
octx.strokeStyle = $.color.parse(series.color).scale('a', 0.5).toString();
var fillStyle = $.color.parse(series.color).scale('a', 0.5).toString();
var barLeft = series.bars.align == "left" ? 0 : -series.bars.barWidth/2;
drawBar(point[0], point[1], point[2] || 0, barLeft, barLeft + series.bars.barWidth,
0, function () { return fillStyle; }, series.xaxis, series.yaxis, octx, series.bars.horizontal, series.bars.lineWidth);
}
function getColorOrGradient(spec, bottom, top, defaultColor) {
if (typeof spec == "string")
return spec;
else {
// assume this is a gradient spec; IE currently only
// supports a simple vertical gradient properly, so that's
// what we support too
var gradient = ctx.createLinearGradient(0, top, 0, bottom);
for (var i = 0, l = spec.colors.length; i < l; ++i) {
var c = spec.colors[i];
if (typeof c != "string") {
var co = $.color.parse(defaultColor);
if (c.brightness != null)
co = co.scale('rgb', c.brightness)
if (c.opacity != null)
co.a *= c.opacity;
c = co.toString();
}
gradient.addColorStop(i / (l - 1), c);
}
return gradient;
}
}
}
$.plot = function(placeholder, data, options) {
//var t0 = new Date();
var plot = new Plot($(placeholder), data, options, $.plot.plugins);
//(window.console ? console.log : alert)("time used (msecs): " + ((new Date()).getTime() - t0.getTime()));
return plot;
};
$.plot.version = "0.7";
$.plot.plugins = [];
// returns a string with the date d formatted according to fmt
$.plot.formatDate = function(d, fmt, monthNames) {
var leftPad = function(n) {
n = "" + n;
return n.length == 1 ? "0" + n : n;
};
var r = [];
var escape = false, padNext = false;
var hours = d.getUTCHours();
var isAM = hours < 12;
if (monthNames == null)
monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
if (fmt.search(/%p|%P/) != -1) {
if (hours > 12) {
hours = hours - 12;
} else if (hours == 0) {
hours = 12;
}
}
for (var i = 0; i < fmt.length; ++i) {
var c = fmt.charAt(i);
if (escape) {
switch (c) {
case 'h': c = "" + hours; break;
case 'H': c = leftPad(hours); break;
case 'M': c = leftPad(d.getUTCMinutes()); break;
case 'S': c = leftPad(d.getUTCSeconds()); break;
case 'd': c = "" + d.getUTCDate(); break;
case 'm': c = "" + (d.getUTCMonth() + 1); break;
case 'y': c = "" + d.getUTCFullYear(); break;
case 'b': c = "" + monthNames[d.getUTCMonth()]; break;
case 'p': c = (isAM) ? ("" + "am") : ("" + "pm"); break;
case 'P': c = (isAM) ? ("" + "AM") : ("" + "PM"); break;
case '0': c = ""; padNext = true; break;
}
if (c && padNext) {
c = leftPad(c);
padNext = false;
}
r.push(c);
if (!padNext)
escape = false;
}
else {
if (c == "%")
escape = true;
else
r.push(c);
}
}
return r.join("");
};
// round to nearby lower multiple of base
function floorInBase(n, base) {
return base * Math.floor(n / base);
}
})(jQuery);
| JavaScript |
/*
Flot plugin for showing crosshairs, thin lines, when the mouse hovers
over the plot.
crosshair: {
mode: null or "x" or "y" or "xy"
color: color
lineWidth: number
}
Set the mode to one of "x", "y" or "xy". The "x" mode enables a
vertical crosshair that lets you trace the values on the x axis, "y"
enables a horizontal crosshair and "xy" enables them both. "color" is
the color of the crosshair (default is "rgba(170, 0, 0, 0.80)"),
"lineWidth" is the width of the drawn lines (default is 1).
The plugin also adds four public methods:
- setCrosshair(pos)
Set the position of the crosshair. Note that this is cleared if
the user moves the mouse. "pos" is in coordinates of the plot and
should be on the form { x: xpos, y: ypos } (you can use x2/x3/...
if you're using multiple axes), which is coincidentally the same
format as what you get from a "plothover" event. If "pos" is null,
the crosshair is cleared.
- clearCrosshair()
Clear the crosshair.
- lockCrosshair(pos)
Cause the crosshair to lock to the current location, no longer
updating if the user moves the mouse. Optionally supply a position
(passed on to setCrosshair()) to move it to.
Example usage:
var myFlot = $.plot( $("#graph"), ..., { crosshair: { mode: "x" } } };
$("#graph").bind("plothover", function (evt, position, item) {
if (item) {
// Lock the crosshair to the data point being hovered
myFlot.lockCrosshair({ x: item.datapoint[0], y: item.datapoint[1] });
}
else {
// Return normal crosshair operation
myFlot.unlockCrosshair();
}
});
- unlockCrosshair()
Free the crosshair to move again after locking it.
*/
(function ($) {
var options = {
crosshair: {
mode: null, // one of null, "x", "y" or "xy",
color: "rgba(170, 0, 0, 0.80)",
lineWidth: 1
}
};
function init(plot) {
// position of crosshair in pixels
var crosshair = { x: -1, y: -1, locked: false };
plot.setCrosshair = function setCrosshair(pos) {
if (!pos)
crosshair.x = -1;
else {
var o = plot.p2c(pos);
crosshair.x = Math.max(0, Math.min(o.left, plot.width()));
crosshair.y = Math.max(0, Math.min(o.top, plot.height()));
}
plot.triggerRedrawOverlay();
};
plot.clearCrosshair = plot.setCrosshair; // passes null for pos
plot.lockCrosshair = function lockCrosshair(pos) {
if (pos)
plot.setCrosshair(pos);
crosshair.locked = true;
}
plot.unlockCrosshair = function unlockCrosshair() {
crosshair.locked = false;
}
function onMouseOut(e) {
if (crosshair.locked)
return;
if (crosshair.x != -1) {
crosshair.x = -1;
plot.triggerRedrawOverlay();
}
}
function onMouseMove(e) {
if (crosshair.locked)
return;
if (plot.getSelection && plot.getSelection()) {
crosshair.x = -1; // hide the crosshair while selecting
return;
}
var offset = plot.offset();
crosshair.x = Math.max(0, Math.min(e.pageX - offset.left, plot.width()));
crosshair.y = Math.max(0, Math.min(e.pageY - offset.top, plot.height()));
plot.triggerRedrawOverlay();
}
plot.hooks.bindEvents.push(function (plot, eventHolder) {
if (!plot.getOptions().crosshair.mode)
return;
eventHolder.mouseout(onMouseOut);
eventHolder.mousemove(onMouseMove);
});
plot.hooks.drawOverlay.push(function (plot, ctx) {
var c = plot.getOptions().crosshair;
if (!c.mode)
return;
var plotOffset = plot.getPlotOffset();
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
if (crosshair.x != -1) {
ctx.strokeStyle = c.color;
ctx.lineWidth = c.lineWidth;
ctx.lineJoin = "round";
ctx.beginPath();
if (c.mode.indexOf("x") != -1) {
ctx.moveTo(crosshair.x, 0);
ctx.lineTo(crosshair.x, plot.height());
}
if (c.mode.indexOf("y") != -1) {
ctx.moveTo(0, crosshair.y);
ctx.lineTo(plot.width(), crosshair.y);
}
ctx.stroke();
}
ctx.restore();
});
plot.hooks.shutdown.push(function (plot, eventHolder) {
eventHolder.unbind("mouseout", onMouseOut);
eventHolder.unbind("mousemove", onMouseMove);
});
}
$.plot.plugins.push({
init: init,
options: options,
name: 'crosshair',
version: '1.0'
});
})(jQuery);
| JavaScript |
/*
Flot plugin for adding panning and zooming capabilities to a plot.
The default behaviour is double click and scrollwheel up/down to zoom
in, drag to pan. The plugin defines plot.zoom({ center }),
plot.zoomOut() and plot.pan(offset) so you easily can add custom
controls. It also fires a "plotpan" and "plotzoom" event when
something happens, useful for synchronizing plots.
Options:
zoom: {
interactive: false
trigger: "dblclick" // or "click" for single click
amount: 1.5 // 2 = 200% (zoom in), 0.5 = 50% (zoom out)
}
pan: {
interactive: false
cursor: "move" // CSS mouse cursor value used when dragging, e.g. "pointer"
frameRate: 20
}
xaxis, yaxis, x2axis, y2axis: {
zoomRange: null // or [number, number] (min range, max range) or false
panRange: null // or [number, number] (min, max) or false
}
"interactive" enables the built-in drag/click behaviour. If you enable
interactive for pan, then you'll have a basic plot that supports
moving around; the same for zoom.
"amount" specifies the default amount to zoom in (so 1.5 = 150%)
relative to the current viewport.
"cursor" is a standard CSS mouse cursor string used for visual
feedback to the user when dragging.
"frameRate" specifies the maximum number of times per second the plot
will update itself while the user is panning around on it (set to null
to disable intermediate pans, the plot will then not update until the
mouse button is released).
"zoomRange" is the interval in which zooming can happen, e.g. with
zoomRange: [1, 100] the zoom will never scale the axis so that the
difference between min and max is smaller than 1 or larger than 100.
You can set either end to null to ignore, e.g. [1, null]. If you set
zoomRange to false, zooming on that axis will be disabled.
"panRange" confines the panning to stay within a range, e.g. with
panRange: [-10, 20] panning stops at -10 in one end and at 20 in the
other. Either can be null, e.g. [-10, null]. If you set
panRange to false, panning on that axis will be disabled.
Example API usage:
plot = $.plot(...);
// zoom default amount in on the pixel (10, 20)
plot.zoom({ center: { left: 10, top: 20 } });
// zoom out again
plot.zoomOut({ center: { left: 10, top: 20 } });
// zoom 200% in on the pixel (10, 20)
plot.zoom({ amount: 2, center: { left: 10, top: 20 } });
// pan 100 pixels to the left and 20 down
plot.pan({ left: -100, top: 20 })
Here, "center" specifies where the center of the zooming should
happen. Note that this is defined in pixel space, not the space of the
data points (you can use the p2c helpers on the axes in Flot to help
you convert between these).
"amount" is the amount to zoom the viewport relative to the current
range, so 1 is 100% (i.e. no change), 1.5 is 150% (zoom in), 0.7 is
70% (zoom out). You can set the default in the options.
*/
// First two dependencies, jquery.event.drag.js and
// jquery.mousewheel.js, we put them inline here to save people the
// effort of downloading them.
/*
jquery.event.drag.js ~ v1.5 ~ Copyright (c) 2008, Three Dub Media (http://threedubmedia.com)
Licensed under the MIT License ~ http://threedubmedia.googlecode.com/files/MIT-LICENSE.txt
*/
(function(E){E.fn.drag=function(L,K,J){if(K){this.bind("dragstart",L)}if(J){this.bind("dragend",J)}return !L?this.trigger("drag"):this.bind("drag",K?K:L)};var A=E.event,B=A.special,F=B.drag={not:":input",distance:0,which:1,dragging:false,setup:function(J){J=E.extend({distance:F.distance,which:F.which,not:F.not},J||{});J.distance=I(J.distance);A.add(this,"mousedown",H,J);if(this.attachEvent){this.attachEvent("ondragstart",D)}},teardown:function(){A.remove(this,"mousedown",H);if(this===F.dragging){F.dragging=F.proxy=false}G(this,true);if(this.detachEvent){this.detachEvent("ondragstart",D)}}};B.dragstart=B.dragend={setup:function(){},teardown:function(){}};function H(L){var K=this,J,M=L.data||{};if(M.elem){K=L.dragTarget=M.elem;L.dragProxy=F.proxy||K;L.cursorOffsetX=M.pageX-M.left;L.cursorOffsetY=M.pageY-M.top;L.offsetX=L.pageX-L.cursorOffsetX;L.offsetY=L.pageY-L.cursorOffsetY}else{if(F.dragging||(M.which>0&&L.which!=M.which)||E(L.target).is(M.not)){return }}switch(L.type){case"mousedown":E.extend(M,E(K).offset(),{elem:K,target:L.target,pageX:L.pageX,pageY:L.pageY});A.add(document,"mousemove mouseup",H,M);G(K,false);F.dragging=null;return false;case !F.dragging&&"mousemove":if(I(L.pageX-M.pageX)+I(L.pageY-M.pageY)<M.distance){break}L.target=M.target;J=C(L,"dragstart",K);if(J!==false){F.dragging=K;F.proxy=L.dragProxy=E(J||K)[0]}case"mousemove":if(F.dragging){J=C(L,"drag",K);if(B.drop){B.drop.allowed=(J!==false);B.drop.handler(L)}if(J!==false){break}L.type="mouseup"}case"mouseup":A.remove(document,"mousemove mouseup",H);if(F.dragging){if(B.drop){B.drop.handler(L)}C(L,"dragend",K)}G(K,true);F.dragging=F.proxy=M.elem=false;break}return true}function C(M,K,L){M.type=K;var J=E.event.handle.call(L,M);return J===false?false:J||M.result}function I(J){return Math.pow(J,2)}function D(){return(F.dragging===false)}function G(K,J){if(!K){return }K.unselectable=J?"off":"on";K.onselectstart=function(){return J};if(K.style){K.style.MozUserSelect=J?"":"none"}}})(jQuery);
/* jquery.mousewheel.min.js
* Copyright (c) 2009 Brandon Aaron (http://brandonaaron.net)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
* Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
* Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
*
* Version: 3.0.2
*
* Requires: 1.2.2+
*/
(function(c){var a=["DOMMouseScroll","mousewheel"];c.event.special.mousewheel={setup:function(){if(this.addEventListener){for(var d=a.length;d;){this.addEventListener(a[--d],b,false)}}else{this.onmousewheel=b}},teardown:function(){if(this.removeEventListener){for(var d=a.length;d;){this.removeEventListener(a[--d],b,false)}}else{this.onmousewheel=null}}};c.fn.extend({mousewheel:function(d){return d?this.bind("mousewheel",d):this.trigger("mousewheel")},unmousewheel:function(d){return this.unbind("mousewheel",d)}});function b(f){var d=[].slice.call(arguments,1),g=0,e=true;f=c.event.fix(f||window.event);f.type="mousewheel";if(f.wheelDelta){g=f.wheelDelta/120}if(f.detail){g=-f.detail/3}d.unshift(f,g);return c.event.handle.apply(this,d)}})(jQuery);
(function ($) {
var options = {
xaxis: {
zoomRange: null, // or [number, number] (min range, max range)
panRange: null // or [number, number] (min, max)
},
zoom: {
interactive: false,
trigger: "dblclick", // or "click" for single click
amount: 1.5 // how much to zoom relative to current position, 2 = 200% (zoom in), 0.5 = 50% (zoom out)
},
pan: {
interactive: false,
cursor: "move",
frameRate: 20
}
};
function init(plot) {
function onZoomClick(e, zoomOut) {
var c = plot.offset();
c.left = e.pageX - c.left;
c.top = e.pageY - c.top;
if (zoomOut)
plot.zoomOut({ center: c });
else
plot.zoom({ center: c });
}
function onMouseWheel(e, delta) {
onZoomClick(e, delta < 0);
return false;
}
var prevCursor = 'default', prevPageX = 0, prevPageY = 0,
panTimeout = null;
function onDragStart(e) {
if (e.which != 1) // only accept left-click
return false;
var c = plot.getPlaceholder().css('cursor');
if (c)
prevCursor = c;
plot.getPlaceholder().css('cursor', plot.getOptions().pan.cursor);
prevPageX = e.pageX;
prevPageY = e.pageY;
}
function onDrag(e) {
var frameRate = plot.getOptions().pan.frameRate;
if (panTimeout || !frameRate)
return;
panTimeout = setTimeout(function () {
plot.pan({ left: prevPageX - e.pageX,
top: prevPageY - e.pageY });
prevPageX = e.pageX;
prevPageY = e.pageY;
panTimeout = null;
}, 1 / frameRate * 1000);
}
function onDragEnd(e) {
if (panTimeout) {
clearTimeout(panTimeout);
panTimeout = null;
}
plot.getPlaceholder().css('cursor', prevCursor);
plot.pan({ left: prevPageX - e.pageX,
top: prevPageY - e.pageY });
}
function bindEvents(plot, eventHolder) {
var o = plot.getOptions();
if (o.zoom.interactive) {
eventHolder[o.zoom.trigger](onZoomClick);
eventHolder.mousewheel(onMouseWheel);
}
if (o.pan.interactive) {
eventHolder.bind("dragstart", { distance: 10 }, onDragStart);
eventHolder.bind("drag", onDrag);
eventHolder.bind("dragend", onDragEnd);
}
}
plot.zoomOut = function (args) {
if (!args)
args = {};
if (!args.amount)
args.amount = plot.getOptions().zoom.amount
args.amount = 1 / args.amount;
plot.zoom(args);
}
plot.zoom = function (args) {
if (!args)
args = {};
var c = args.center,
amount = args.amount || plot.getOptions().zoom.amount,
w = plot.width(), h = plot.height();
if (!c)
c = { left: w / 2, top: h / 2 };
var xf = c.left / w,
yf = c.top / h,
minmax = {
x: {
min: c.left - xf * w / amount,
max: c.left + (1 - xf) * w / amount
},
y: {
min: c.top - yf * h / amount,
max: c.top + (1 - yf) * h / amount
}
};
$.each(plot.getAxes(), function(_, axis) {
var opts = axis.options,
min = minmax[axis.direction].min,
max = minmax[axis.direction].max,
zr = opts.zoomRange;
if (zr === false) // no zooming on this axis
return;
min = axis.c2p(min);
max = axis.c2p(max);
if (min > max) {
// make sure min < max
var tmp = min;
min = max;
max = tmp;
}
var range = max - min;
if (zr &&
((zr[0] != null && range < zr[0]) ||
(zr[1] != null && range > zr[1])))
return;
opts.min = min;
opts.max = max;
});
plot.setupGrid();
plot.draw();
if (!args.preventEvent)
plot.getPlaceholder().trigger("plotzoom", [ plot ]);
}
plot.pan = function (args) {
var delta = {
x: +args.left,
y: +args.top
};
if (isNaN(delta.x))
delta.x = 0;
if (isNaN(delta.y))
delta.y = 0;
$.each(plot.getAxes(), function (_, axis) {
var opts = axis.options,
min, max, d = delta[axis.direction];
min = axis.c2p(axis.p2c(axis.min) + d),
max = axis.c2p(axis.p2c(axis.max) + d);
var pr = opts.panRange;
if (pr === false) // no panning on this axis
return;
if (pr) {
// check whether we hit the wall
if (pr[0] != null && pr[0] > min) {
d = pr[0] - min;
min += d;
max += d;
}
if (pr[1] != null && pr[1] < max) {
d = pr[1] - max;
min += d;
max += d;
}
}
opts.min = min;
opts.max = max;
});
plot.setupGrid();
plot.draw();
if (!args.preventEvent)
plot.getPlaceholder().trigger("plotpan", [ plot ]);
}
function shutdown(plot, eventHolder) {
eventHolder.unbind(plot.getOptions().zoom.trigger, onZoomClick);
eventHolder.unbind("mousewheel", onMouseWheel);
eventHolder.unbind("dragstart", onDragStart);
eventHolder.unbind("drag", onDrag);
eventHolder.unbind("dragend", onDragEnd);
if (panTimeout)
clearTimeout(panTimeout);
}
plot.hooks.bindEvents.push(bindEvents);
plot.hooks.shutdown.push(shutdown);
}
$.plot.plugins.push({
init: init,
options: options,
name: 'navigate',
version: '1.3'
});
})(jQuery);
| JavaScript |
/*
Flot plugin that adds some extra symbols for plotting points.
The symbols are accessed as strings through the standard symbol
choice:
series: {
points: {
symbol: "square" // or "diamond", "triangle", "cross"
}
}
*/
(function ($) {
function processRawData(plot, series, datapoints) {
// we normalize the area of each symbol so it is approximately the
// same as a circle of the given radius
var handlers = {
square: function (ctx, x, y, radius, shadow) {
// pi * r^2 = (2s)^2 => s = r * sqrt(pi)/2
var size = radius * Math.sqrt(Math.PI) / 2;
ctx.rect(x - size, y - size, size + size, size + size);
},
diamond: function (ctx, x, y, radius, shadow) {
// pi * r^2 = 2s^2 => s = r * sqrt(pi/2)
var size = radius * Math.sqrt(Math.PI / 2);
ctx.moveTo(x - size, y);
ctx.lineTo(x, y - size);
ctx.lineTo(x + size, y);
ctx.lineTo(x, y + size);
ctx.lineTo(x - size, y);
},
triangle: function (ctx, x, y, radius, shadow) {
// pi * r^2 = 1/2 * s^2 * sin (pi / 3) => s = r * sqrt(2 * pi / sin(pi / 3))
var size = radius * Math.sqrt(2 * Math.PI / Math.sin(Math.PI / 3));
var height = size * Math.sin(Math.PI / 3);
ctx.moveTo(x - size/2, y + height/2);
ctx.lineTo(x + size/2, y + height/2);
if (!shadow) {
ctx.lineTo(x, y - height/2);
ctx.lineTo(x - size/2, y + height/2);
}
},
cross: function (ctx, x, y, radius, shadow) {
// pi * r^2 = (2s)^2 => s = r * sqrt(pi)/2
var size = radius * Math.sqrt(Math.PI) / 2;
ctx.moveTo(x - size, y - size);
ctx.lineTo(x + size, y + size);
ctx.moveTo(x - size, y + size);
ctx.lineTo(x + size, y - size);
}
}
var s = series.points.symbol;
if (handlers[s])
series.points.symbol = handlers[s];
}
function init(plot) {
plot.hooks.processDatapoints.push(processRawData);
}
$.plot.plugins.push({
init: init,
name: 'symbols',
version: '1.0'
});
})(jQuery);
| JavaScript |
/*
Flot plugin for automatically redrawing plots when the placeholder
size changes, e.g. on window resizes.
It works by listening for changes on the placeholder div (through the
jQuery resize event plugin) - if the size changes, it will redraw the
plot.
There are no options. If you need to disable the plugin for some
plots, you can just fix the size of their placeholders.
*/
/* Inline dependency:
* jQuery resize event - v1.1 - 3/14/2010
* http://benalman.com/projects/jquery-resize-plugin/
*
* Copyright (c) 2010 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
(function($,h,c){var a=$([]),e=$.resize=$.extend($.resize,{}),i,k="setTimeout",j="resize",d=j+"-special-event",b="delay",f="throttleWindow";e[b]=250;e[f]=true;$.event.special[j]={setup:function(){if(!e[f]&&this[k]){return false}var l=$(this);a=a.add(l);$.data(this,d,{w:l.width(),h:l.height()});if(a.length===1){g()}},teardown:function(){if(!e[f]&&this[k]){return false}var l=$(this);a=a.not(l);l.removeData(d);if(!a.length){clearTimeout(i)}},add:function(l){if(!e[f]&&this[k]){return false}var n;function m(s,o,p){var q=$(this),r=$.data(this,d);r.w=o!==c?o:q.width();r.h=p!==c?p:q.height();n.apply(this,arguments)}if($.isFunction(l)){n=l;return m}else{n=l.handler;l.handler=m}}};function g(){i=h[k](function(){a.each(function(){var n=$(this),m=n.width(),l=n.height(),o=$.data(this,d);if(m!==o.w||l!==o.h){n.trigger(j,[o.w=m,o.h=l])}});g()},e[b])}})(jQuery,this);
(function ($) {
var options = { }; // no options
function init(plot) {
function onResize() {
var placeholder = plot.getPlaceholder();
// somebody might have hidden us and we can't plot
// when we don't have the dimensions
if (placeholder.width() == 0 || placeholder.height() == 0)
return;
plot.resize();
plot.setupGrid();
plot.draw();
}
function bindEvents(plot, eventHolder) {
plot.getPlaceholder().resize(onResize);
}
function shutdown(plot, eventHolder) {
plot.getPlaceholder().unbind("resize", onResize);
}
plot.hooks.bindEvents.push(bindEvents);
plot.hooks.shutdown.push(shutdown);
}
$.plot.plugins.push({
init: init,
options: options,
name: 'resize',
version: '1.0'
});
})(jQuery);
| JavaScript |
/*
Flot plugin for thresholding data. Controlled through the option
"threshold" in either the global series options
series: {
threshold: {
below: number
color: colorspec
}
}
or in a specific series
$.plot($("#placeholder"), [{ data: [ ... ], threshold: { ... }}])
The data points below "below" are drawn with the specified color. This
makes it easy to mark points below 0, e.g. for budget data.
Internally, the plugin works by splitting the data into two series,
above and below the threshold. The extra series below the threshold
will have its label cleared and the special "originSeries" attribute
set to the original series. You may need to check for this in hover
events.
*/
(function ($) {
var options = {
series: { threshold: null } // or { below: number, color: color spec}
};
function init(plot) {
function thresholdData(plot, s, datapoints) {
if (!s.threshold)
return;
var ps = datapoints.pointsize, i, x, y, p, prevp,
thresholded = $.extend({}, s); // note: shallow copy
thresholded.datapoints = { points: [], pointsize: ps };
thresholded.label = null;
thresholded.color = s.threshold.color;
thresholded.threshold = null;
thresholded.originSeries = s;
thresholded.data = [];
var below = s.threshold.below,
origpoints = datapoints.points,
addCrossingPoints = s.lines.show;
threspoints = [];
newpoints = [];
for (i = 0; i < origpoints.length; i += ps) {
x = origpoints[i]
y = origpoints[i + 1];
prevp = p;
if (y < below)
p = threspoints;
else
p = newpoints;
if (addCrossingPoints && prevp != p && x != null
&& i > 0 && origpoints[i - ps] != null) {
var interx = (x - origpoints[i - ps]) / (y - origpoints[i - ps + 1]) * (below - y) + x;
prevp.push(interx);
prevp.push(below);
for (m = 2; m < ps; ++m)
prevp.push(origpoints[i + m]);
p.push(null); // start new segment
p.push(null);
for (m = 2; m < ps; ++m)
p.push(origpoints[i + m]);
p.push(interx);
p.push(below);
for (m = 2; m < ps; ++m)
p.push(origpoints[i + m]);
}
p.push(x);
p.push(y);
}
datapoints.points = newpoints;
thresholded.datapoints.points = threspoints;
if (thresholded.datapoints.points.length > 0)
plot.getData().push(thresholded);
// FIXME: there are probably some edge cases left in bars
}
plot.hooks.processDatapoints.push(thresholdData);
}
$.plot.plugins.push({
init: init,
options: options,
name: 'threshold',
version: '1.0'
});
})(jQuery);
| JavaScript |
/*
Flot plugin for selecting regions.
The plugin defines the following options:
selection: {
mode: null or "x" or "y" or "xy",
color: color
}
Selection support is enabled by setting the mode to one of "x", "y" or
"xy". In "x" mode, the user will only be able to specify the x range,
similarly for "y" mode. For "xy", the selection becomes a rectangle
where both ranges can be specified. "color" is color of the selection
(if you need to change the color later on, you can get to it with
plot.getOptions().selection.color).
When selection support is enabled, a "plotselected" event will be
emitted on the DOM element you passed into the plot function. The
event handler gets a parameter with the ranges selected on the axes,
like this:
placeholder.bind("plotselected", function(event, ranges) {
alert("You selected " + ranges.xaxis.from + " to " + ranges.xaxis.to)
// similar for yaxis - with multiple axes, the extra ones are in
// x2axis, x3axis, ...
});
The "plotselected" event is only fired when the user has finished
making the selection. A "plotselecting" event is fired during the
process with the same parameters as the "plotselected" event, in case
you want to know what's happening while it's happening,
A "plotunselected" event with no arguments is emitted when the user
clicks the mouse to remove the selection.
The plugin allso adds the following methods to the plot object:
- setSelection(ranges, preventEvent)
Set the selection rectangle. The passed in ranges is on the same
form as returned in the "plotselected" event. If the selection mode
is "x", you should put in either an xaxis range, if the mode is "y"
you need to put in an yaxis range and both xaxis and yaxis if the
selection mode is "xy", like this:
setSelection({ xaxis: { from: 0, to: 10 }, yaxis: { from: 40, to: 60 } });
setSelection will trigger the "plotselected" event when called. If
you don't want that to happen, e.g. if you're inside a
"plotselected" handler, pass true as the second parameter. If you
are using multiple axes, you can specify the ranges on any of those,
e.g. as x2axis/x3axis/... instead of xaxis, the plugin picks the
first one it sees.
- clearSelection(preventEvent)
Clear the selection rectangle. Pass in true to avoid getting a
"plotunselected" event.
- getSelection()
Returns the current selection in the same format as the
"plotselected" event. If there's currently no selection, the
function returns null.
*/
(function ($) {
function init(plot) {
var selection = {
first: { x: -1, y: -1}, second: { x: -1, y: -1},
show: false,
active: false
};
// FIXME: The drag handling implemented here should be
// abstracted out, there's some similar code from a library in
// the navigation plugin, this should be massaged a bit to fit
// the Flot cases here better and reused. Doing this would
// make this plugin much slimmer.
var savedhandlers = {};
var mouseUpHandler = null;
function onMouseMove(e) {
if (selection.active) {
updateSelection(e);
plot.getPlaceholder().trigger("plotselecting", [ getSelection() ]);
}
}
function onMouseDown(e) {
if (e.which != 1) // only accept left-click
return;
// cancel out any text selections
document.body.focus();
// prevent text selection and drag in old-school browsers
if (document.onselectstart !== undefined && savedhandlers.onselectstart == null) {
savedhandlers.onselectstart = document.onselectstart;
document.onselectstart = function () { return false; };
}
if (document.ondrag !== undefined && savedhandlers.ondrag == null) {
savedhandlers.ondrag = document.ondrag;
document.ondrag = function () { return false; };
}
setSelectionPos(selection.first, e);
selection.active = true;
// this is a bit silly, but we have to use a closure to be
// able to whack the same handler again
mouseUpHandler = function (e) { onMouseUp(e); };
$(document).one("mouseup", mouseUpHandler);
}
function onMouseUp(e) {
mouseUpHandler = null;
// revert drag stuff for old-school browsers
if (document.onselectstart !== undefined)
document.onselectstart = savedhandlers.onselectstart;
if (document.ondrag !== undefined)
document.ondrag = savedhandlers.ondrag;
// no more dragging
selection.active = false;
updateSelection(e);
if (selectionIsSane())
triggerSelectedEvent();
else {
// this counts as a clear
plot.getPlaceholder().trigger("plotunselected", [ ]);
plot.getPlaceholder().trigger("plotselecting", [ null ]);
}
return false;
}
function getSelection() {
if (!selectionIsSane())
return null;
var r = {}, c1 = selection.first, c2 = selection.second;
$.each(plot.getAxes(), function (name, axis) {
if (axis.used) {
var p1 = axis.c2p(c1[axis.direction]), p2 = axis.c2p(c2[axis.direction]);
r[name] = { from: Math.min(p1, p2), to: Math.max(p1, p2) };
}
});
return r;
}
function triggerSelectedEvent() {
var r = getSelection();
plot.getPlaceholder().trigger("plotselected", [ r ]);
// backwards-compat stuff, to be removed in future
if (r.xaxis && r.yaxis)
plot.getPlaceholder().trigger("selected", [ { x1: r.xaxis.from, y1: r.yaxis.from, x2: r.xaxis.to, y2: r.yaxis.to } ]);
}
function clamp(min, value, max) {
return value < min ? min: (value > max ? max: value);
}
function setSelectionPos(pos, e) {
var o = plot.getOptions();
var offset = plot.getPlaceholder().offset();
var plotOffset = plot.getPlotOffset();
pos.x = clamp(0, e.pageX - offset.left - plotOffset.left, plot.width());
pos.y = clamp(0, e.pageY - offset.top - plotOffset.top, plot.height());
if (o.selection.mode == "y")
pos.x = pos == selection.first ? 0 : plot.width();
if (o.selection.mode == "x")
pos.y = pos == selection.first ? 0 : plot.height();
}
function updateSelection(pos) {
if (pos.pageX == null)
return;
setSelectionPos(selection.second, pos);
if (selectionIsSane()) {
selection.show = true;
plot.triggerRedrawOverlay();
}
else
clearSelection(true);
}
function clearSelection(preventEvent) {
if (selection.show) {
selection.show = false;
plot.triggerRedrawOverlay();
if (!preventEvent)
plot.getPlaceholder().trigger("plotunselected", [ ]);
}
}
// function taken from markings support in Flot
function extractRange(ranges, coord) {
var axis, from, to, key, axes = plot.getAxes();
for (var k in axes) {
axis = axes[k];
if (axis.direction == coord) {
key = coord + axis.n + "axis";
if (!ranges[key] && axis.n == 1)
key = coord + "axis"; // support x1axis as xaxis
if (ranges[key]) {
from = ranges[key].from;
to = ranges[key].to;
break;
}
}
}
// backwards-compat stuff - to be removed in future
if (!ranges[key]) {
axis = coord == "x" ? plot.getXAxes()[0] : plot.getYAxes()[0];
from = ranges[coord + "1"];
to = ranges[coord + "2"];
}
// auto-reverse as an added bonus
if (from != null && to != null && from > to) {
var tmp = from;
from = to;
to = tmp;
}
return { from: from, to: to, axis: axis };
}
function setSelection(ranges, preventEvent) {
var axis, range, o = plot.getOptions();
if (o.selection.mode == "y") {
selection.first.x = 0;
selection.second.x = plot.width();
}
else {
range = extractRange(ranges, "x");
selection.first.x = range.axis.p2c(range.from);
selection.second.x = range.axis.p2c(range.to);
}
if (o.selection.mode == "x") {
selection.first.y = 0;
selection.second.y = plot.height();
}
else {
range = extractRange(ranges, "y");
selection.first.y = range.axis.p2c(range.from);
selection.second.y = range.axis.p2c(range.to);
}
selection.show = true;
plot.triggerRedrawOverlay();
if (!preventEvent && selectionIsSane())
triggerSelectedEvent();
}
function selectionIsSane() {
var minSize = 5;
return Math.abs(selection.second.x - selection.first.x) >= minSize &&
Math.abs(selection.second.y - selection.first.y) >= minSize;
}
plot.clearSelection = clearSelection;
plot.setSelection = setSelection;
plot.getSelection = getSelection;
plot.hooks.bindEvents.push(function(plot, eventHolder) {
var o = plot.getOptions();
if (o.selection.mode != null) {
eventHolder.mousemove(onMouseMove);
eventHolder.mousedown(onMouseDown);
}
});
plot.hooks.drawOverlay.push(function (plot, ctx) {
// draw selection
if (selection.show && selectionIsSane()) {
var plotOffset = plot.getPlotOffset();
var o = plot.getOptions();
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
var c = $.color.parse(o.selection.color);
ctx.strokeStyle = c.scale('a', 0.8).toString();
ctx.lineWidth = 1;
ctx.lineJoin = "round";
ctx.fillStyle = c.scale('a', 0.4).toString();
var x = Math.min(selection.first.x, selection.second.x),
y = Math.min(selection.first.y, selection.second.y),
w = Math.abs(selection.second.x - selection.first.x),
h = Math.abs(selection.second.y - selection.first.y);
ctx.fillRect(x, y, w, h);
ctx.strokeRect(x, y, w, h);
ctx.restore();
}
});
plot.hooks.shutdown.push(function (plot, eventHolder) {
eventHolder.unbind("mousemove", onMouseMove);
eventHolder.unbind("mousedown", onMouseDown);
if (mouseUpHandler)
$(document).unbind("mouseup", mouseUpHandler);
});
}
$.plot.plugins.push({
init: init,
options: {
selection: {
mode: null, // one of null, "x", "y" or "xy"
color: "#e8cfac"
}
},
name: 'selection',
version: '1.1'
});
})(jQuery);
| JavaScript |
/* Plugin for jQuery for working with colors.
*
* Version 1.1.
*
* Inspiration from jQuery color animation plugin by John Resig.
*
* Released under the MIT license by Ole Laursen, October 2009.
*
* Examples:
*
* $.color.parse("#fff").scale('rgb', 0.25).add('a', -0.5).toString()
* var c = $.color.extract($("#mydiv"), 'background-color');
* console.log(c.r, c.g, c.b, c.a);
* $.color.make(100, 50, 25, 0.4).toString() // returns "rgba(100,50,25,0.4)"
*
* Note that .scale() and .add() return the same modified object
* instead of making a new one.
*
* V. 1.1: Fix error handling so e.g. parsing an empty string does
* produce a color rather than just crashing.
*/
(function($) {
$.color = {};
// construct color object with some convenient chainable helpers
$.color.make = function (r, g, b, a) {
var o = {};
o.r = r || 0;
o.g = g || 0;
o.b = b || 0;
o.a = a != null ? a : 1;
o.add = function (c, d) {
for (var i = 0; i < c.length; ++i)
o[c.charAt(i)] += d;
return o.normalize();
};
o.scale = function (c, f) {
for (var i = 0; i < c.length; ++i)
o[c.charAt(i)] *= f;
return o.normalize();
};
o.toString = function () {
if (o.a >= 1.0) {
return "rgb("+[o.r, o.g, o.b].join(",")+")";
} else {
return "rgba("+[o.r, o.g, o.b, o.a].join(",")+")";
}
};
o.normalize = function () {
function clamp(min, value, max) {
return value < min ? min: (value > max ? max: value);
}
o.r = clamp(0, parseInt(o.r), 255);
o.g = clamp(0, parseInt(o.g), 255);
o.b = clamp(0, parseInt(o.b), 255);
o.a = clamp(0, o.a, 1);
return o;
};
o.clone = function () {
return $.color.make(o.r, o.b, o.g, o.a);
};
return o.normalize();
}
// extract CSS color property from element, going up in the DOM
// if it's "transparent"
$.color.extract = function (elem, css) {
var c;
do {
c = elem.css(css).toLowerCase();
// keep going until we find an element that has color, or
// we hit the body
if (c != '' && c != 'transparent')
break;
elem = elem.parent();
} while (!$.nodeName(elem.get(0), "body"));
// catch Safari's way of signalling transparent
if (c == "rgba(0, 0, 0, 0)")
c = "transparent";
return $.color.parse(c);
}
// parse CSS color string (like "rgb(10, 32, 43)" or "#fff"),
// returns color object, if parsing failed, you get black (0, 0,
// 0) out
$.color.parse = function (str) {
var res, m = $.color.make;
// Look for rgb(num,num,num)
if (res = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(str))
return m(parseInt(res[1], 10), parseInt(res[2], 10), parseInt(res[3], 10));
// Look for rgba(num,num,num,num)
if (res = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str))
return m(parseInt(res[1], 10), parseInt(res[2], 10), parseInt(res[3], 10), parseFloat(res[4]));
// Look for rgb(num%,num%,num%)
if (res = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(str))
return m(parseFloat(res[1])*2.55, parseFloat(res[2])*2.55, parseFloat(res[3])*2.55);
// Look for rgba(num%,num%,num%,num)
if (res = /rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str))
return m(parseFloat(res[1])*2.55, parseFloat(res[2])*2.55, parseFloat(res[3])*2.55, parseFloat(res[4]));
// Look for #a0b1c2
if (res = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(str))
return m(parseInt(res[1], 16), parseInt(res[2], 16), parseInt(res[3], 16));
// Look for #fff
if (res = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(str))
return m(parseInt(res[1]+res[1], 16), parseInt(res[2]+res[2], 16), parseInt(res[3]+res[3], 16));
// Otherwise, we're most likely dealing with a named color
var name = $.trim(str).toLowerCase();
if (name == "transparent")
return m(255, 255, 255, 0);
else {
// default to black
res = lookupColors[name] || [0, 0, 0];
return m(res[0], res[1], res[2]);
}
}
var lookupColors = {
aqua:[0,255,255],
azure:[240,255,255],
beige:[245,245,220],
black:[0,0,0],
blue:[0,0,255],
brown:[165,42,42],
cyan:[0,255,255],
darkblue:[0,0,139],
darkcyan:[0,139,139],
darkgrey:[169,169,169],
darkgreen:[0,100,0],
darkkhaki:[189,183,107],
darkmagenta:[139,0,139],
darkolivegreen:[85,107,47],
darkorange:[255,140,0],
darkorchid:[153,50,204],
darkred:[139,0,0],
darksalmon:[233,150,122],
darkviolet:[148,0,211],
fuchsia:[255,0,255],
gold:[255,215,0],
green:[0,128,0],
indigo:[75,0,130],
khaki:[240,230,140],
lightblue:[173,216,230],
lightcyan:[224,255,255],
lightgreen:[144,238,144],
lightgrey:[211,211,211],
lightpink:[255,182,193],
lightyellow:[255,255,224],
lime:[0,255,0],
magenta:[255,0,255],
maroon:[128,0,0],
navy:[0,0,128],
olive:[128,128,0],
orange:[255,165,0],
pink:[255,192,203],
purple:[128,0,128],
violet:[128,0,128],
red:[255,0,0],
silver:[192,192,192],
white:[255,255,255],
yellow:[255,255,0]
};
})(jQuery);
| JavaScript |
// Copyright 2006 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Known Issues:
//
// * Patterns only support repeat.
// * Radial gradient are not implemented. The VML version of these look very
// different from the canvas one.
// * Clipping paths are not implemented.
// * Coordsize. The width and height attribute have higher priority than the
// width and height style values which isn't correct.
// * Painting mode isn't implemented.
// * Canvas width/height should is using content-box by default. IE in
// Quirks mode will draw the canvas using border-box. Either change your
// doctype to HTML5
// (http://www.whatwg.org/specs/web-apps/current-work/#the-doctype)
// or use Box Sizing Behavior from WebFX
// (http://webfx.eae.net/dhtml/boxsizing/boxsizing.html)
// * Non uniform scaling does not correctly scale strokes.
// * Filling very large shapes (above 5000 points) is buggy.
// * Optimize. There is always room for speed improvements.
// Only add this code if we do not already have a canvas implementation
if (!document.createElement('canvas').getContext) {
(function() {
// alias some functions to make (compiled) code shorter
var m = Math;
var mr = m.round;
var ms = m.sin;
var mc = m.cos;
var abs = m.abs;
var sqrt = m.sqrt;
// this is used for sub pixel precision
var Z = 10;
var Z2 = Z / 2;
/**
* This funtion is assigned to the <canvas> elements as element.getContext().
* @this {HTMLElement}
* @return {CanvasRenderingContext2D_}
*/
function getContext() {
return this.context_ ||
(this.context_ = new CanvasRenderingContext2D_(this));
}
var slice = Array.prototype.slice;
/**
* Binds a function to an object. The returned function will always use the
* passed in {@code obj} as {@code this}.
*
* Example:
*
* g = bind(f, obj, a, b)
* g(c, d) // will do f.call(obj, a, b, c, d)
*
* @param {Function} f The function to bind the object to
* @param {Object} obj The object that should act as this when the function
* is called
* @param {*} var_args Rest arguments that will be used as the initial
* arguments when the function is called
* @return {Function} A new function that has bound this
*/
function bind(f, obj, var_args) {
var a = slice.call(arguments, 2);
return function() {
return f.apply(obj, a.concat(slice.call(arguments)));
};
}
function encodeHtmlAttribute(s) {
return String(s).replace(/&/g, '&').replace(/"/g, '"');
}
function addNamespacesAndStylesheet(doc) {
// create xmlns
if (!doc.namespaces['g_vml_']) {
doc.namespaces.add('g_vml_', 'urn:schemas-microsoft-com:vml',
'#default#VML');
}
if (!doc.namespaces['g_o_']) {
doc.namespaces.add('g_o_', 'urn:schemas-microsoft-com:office:office',
'#default#VML');
}
// Setup default CSS. Only add one style sheet per document
if (!doc.styleSheets['ex_canvas_']) {
var ss = doc.createStyleSheet();
ss.owningElement.id = 'ex_canvas_';
ss.cssText = 'canvas{display:inline-block;overflow:hidden;' +
// default size is 300x150 in Gecko and Opera
'text-align:left;width:300px;height:150px}';
}
}
// Add namespaces and stylesheet at startup.
addNamespacesAndStylesheet(document);
var G_vmlCanvasManager_ = {
init: function(opt_doc) {
if (/MSIE/.test(navigator.userAgent) && !window.opera) {
var doc = opt_doc || document;
// Create a dummy element so that IE will allow canvas elements to be
// recognized.
doc.createElement('canvas');
doc.attachEvent('onreadystatechange', bind(this.init_, this, doc));
}
},
init_: function(doc) {
// find all canvas elements
var els = doc.getElementsByTagName('canvas');
for (var i = 0; i < els.length; i++) {
this.initElement(els[i]);
}
},
/**
* Public initializes a canvas element so that it can be used as canvas
* element from now on. This is called automatically before the page is
* loaded but if you are creating elements using createElement you need to
* make sure this is called on the element.
* @param {HTMLElement} el The canvas element to initialize.
* @return {HTMLElement} the element that was created.
*/
initElement: function(el) {
if (!el.getContext) {
el.getContext = getContext;
// Add namespaces and stylesheet to document of the element.
addNamespacesAndStylesheet(el.ownerDocument);
// Remove fallback content. There is no way to hide text nodes so we
// just remove all childNodes. We could hide all elements and remove
// text nodes but who really cares about the fallback content.
el.innerHTML = '';
// do not use inline function because that will leak memory
el.attachEvent('onpropertychange', onPropertyChange);
el.attachEvent('onresize', onResize);
var attrs = el.attributes;
if (attrs.width && attrs.width.specified) {
// TODO: use runtimeStyle and coordsize
// el.getContext().setWidth_(attrs.width.nodeValue);
el.style.width = attrs.width.nodeValue + 'px';
} else {
el.width = el.clientWidth;
}
if (attrs.height && attrs.height.specified) {
// TODO: use runtimeStyle and coordsize
// el.getContext().setHeight_(attrs.height.nodeValue);
el.style.height = attrs.height.nodeValue + 'px';
} else {
el.height = el.clientHeight;
}
//el.getContext().setCoordsize_()
}
return el;
}
};
function onPropertyChange(e) {
var el = e.srcElement;
switch (e.propertyName) {
case 'width':
el.getContext().clearRect();
el.style.width = el.attributes.width.nodeValue + 'px';
// In IE8 this does not trigger onresize.
el.firstChild.style.width = el.clientWidth + 'px';
break;
case 'height':
el.getContext().clearRect();
el.style.height = el.attributes.height.nodeValue + 'px';
el.firstChild.style.height = el.clientHeight + 'px';
break;
}
}
function onResize(e) {
var el = e.srcElement;
if (el.firstChild) {
el.firstChild.style.width = el.clientWidth + 'px';
el.firstChild.style.height = el.clientHeight + 'px';
}
}
G_vmlCanvasManager_.init();
// precompute "00" to "FF"
var decToHex = [];
for (var i = 0; i < 16; i++) {
for (var j = 0; j < 16; j++) {
decToHex[i * 16 + j] = i.toString(16) + j.toString(16);
}
}
function createMatrixIdentity() {
return [
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]
];
}
function matrixMultiply(m1, m2) {
var result = createMatrixIdentity();
for (var x = 0; x < 3; x++) {
for (var y = 0; y < 3; y++) {
var sum = 0;
for (var z = 0; z < 3; z++) {
sum += m1[x][z] * m2[z][y];
}
result[x][y] = sum;
}
}
return result;
}
function copyState(o1, o2) {
o2.fillStyle = o1.fillStyle;
o2.lineCap = o1.lineCap;
o2.lineJoin = o1.lineJoin;
o2.lineWidth = o1.lineWidth;
o2.miterLimit = o1.miterLimit;
o2.shadowBlur = o1.shadowBlur;
o2.shadowColor = o1.shadowColor;
o2.shadowOffsetX = o1.shadowOffsetX;
o2.shadowOffsetY = o1.shadowOffsetY;
o2.strokeStyle = o1.strokeStyle;
o2.globalAlpha = o1.globalAlpha;
o2.font = o1.font;
o2.textAlign = o1.textAlign;
o2.textBaseline = o1.textBaseline;
o2.arcScaleX_ = o1.arcScaleX_;
o2.arcScaleY_ = o1.arcScaleY_;
o2.lineScale_ = o1.lineScale_;
}
var colorData = {
aliceblue: '#F0F8FF',
antiquewhite: '#FAEBD7',
aquamarine: '#7FFFD4',
azure: '#F0FFFF',
beige: '#F5F5DC',
bisque: '#FFE4C4',
black: '#000000',
blanchedalmond: '#FFEBCD',
blueviolet: '#8A2BE2',
brown: '#A52A2A',
burlywood: '#DEB887',
cadetblue: '#5F9EA0',
chartreuse: '#7FFF00',
chocolate: '#D2691E',
coral: '#FF7F50',
cornflowerblue: '#6495ED',
cornsilk: '#FFF8DC',
crimson: '#DC143C',
cyan: '#00FFFF',
darkblue: '#00008B',
darkcyan: '#008B8B',
darkgoldenrod: '#B8860B',
darkgray: '#A9A9A9',
darkgreen: '#006400',
darkgrey: '#A9A9A9',
darkkhaki: '#BDB76B',
darkmagenta: '#8B008B',
darkolivegreen: '#556B2F',
darkorange: '#FF8C00',
darkorchid: '#9932CC',
darkred: '#8B0000',
darksalmon: '#E9967A',
darkseagreen: '#8FBC8F',
darkslateblue: '#483D8B',
darkslategray: '#2F4F4F',
darkslategrey: '#2F4F4F',
darkturquoise: '#00CED1',
darkviolet: '#9400D3',
deeppink: '#FF1493',
deepskyblue: '#00BFFF',
dimgray: '#696969',
dimgrey: '#696969',
dodgerblue: '#1E90FF',
firebrick: '#B22222',
floralwhite: '#FFFAF0',
forestgreen: '#228B22',
gainsboro: '#DCDCDC',
ghostwhite: '#F8F8FF',
gold: '#FFD700',
goldenrod: '#DAA520',
grey: '#808080',
greenyellow: '#ADFF2F',
honeydew: '#F0FFF0',
hotpink: '#FF69B4',
indianred: '#CD5C5C',
indigo: '#4B0082',
ivory: '#FFFFF0',
khaki: '#F0E68C',
lavender: '#E6E6FA',
lavenderblush: '#FFF0F5',
lawngreen: '#7CFC00',
lemonchiffon: '#FFFACD',
lightblue: '#ADD8E6',
lightcoral: '#F08080',
lightcyan: '#E0FFFF',
lightgoldenrodyellow: '#FAFAD2',
lightgreen: '#90EE90',
lightgrey: '#D3D3D3',
lightpink: '#FFB6C1',
lightsalmon: '#FFA07A',
lightseagreen: '#20B2AA',
lightskyblue: '#87CEFA',
lightslategray: '#778899',
lightslategrey: '#778899',
lightsteelblue: '#B0C4DE',
lightyellow: '#FFFFE0',
limegreen: '#32CD32',
linen: '#FAF0E6',
magenta: '#FF00FF',
mediumaquamarine: '#66CDAA',
mediumblue: '#0000CD',
mediumorchid: '#BA55D3',
mediumpurple: '#9370DB',
mediumseagreen: '#3CB371',
mediumslateblue: '#7B68EE',
mediumspringgreen: '#00FA9A',
mediumturquoise: '#48D1CC',
mediumvioletred: '#C71585',
midnightblue: '#191970',
mintcream: '#F5FFFA',
mistyrose: '#FFE4E1',
moccasin: '#FFE4B5',
navajowhite: '#FFDEAD',
oldlace: '#FDF5E6',
olivedrab: '#6B8E23',
orange: '#FFA500',
orangered: '#FF4500',
orchid: '#DA70D6',
palegoldenrod: '#EEE8AA',
palegreen: '#98FB98',
paleturquoise: '#AFEEEE',
palevioletred: '#DB7093',
papayawhip: '#FFEFD5',
peachpuff: '#FFDAB9',
peru: '#CD853F',
pink: '#FFC0CB',
plum: '#DDA0DD',
powderblue: '#B0E0E6',
rosybrown: '#BC8F8F',
royalblue: '#4169E1',
saddlebrown: '#8B4513',
salmon: '#FA8072',
sandybrown: '#F4A460',
seagreen: '#2E8B57',
seashell: '#FFF5EE',
sienna: '#A0522D',
skyblue: '#87CEEB',
slateblue: '#6A5ACD',
slategray: '#708090',
slategrey: '#708090',
snow: '#FFFAFA',
springgreen: '#00FF7F',
steelblue: '#4682B4',
tan: '#D2B48C',
thistle: '#D8BFD8',
tomato: '#FF6347',
turquoise: '#40E0D0',
violet: '#EE82EE',
wheat: '#F5DEB3',
whitesmoke: '#F5F5F5',
yellowgreen: '#9ACD32'
};
function getRgbHslContent(styleString) {
var start = styleString.indexOf('(', 3);
var end = styleString.indexOf(')', start + 1);
var parts = styleString.substring(start + 1, end).split(',');
// add alpha if needed
if (parts.length == 4 && styleString.substr(3, 1) == 'a') {
alpha = Number(parts[3]);
} else {
parts[3] = 1;
}
return parts;
}
function percent(s) {
return parseFloat(s) / 100;
}
function clamp(v, min, max) {
return Math.min(max, Math.max(min, v));
}
function hslToRgb(parts){
var r, g, b;
h = parseFloat(parts[0]) / 360 % 360;
if (h < 0)
h++;
s = clamp(percent(parts[1]), 0, 1);
l = clamp(percent(parts[2]), 0, 1);
if (s == 0) {
r = g = b = l; // achromatic
} else {
var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
var p = 2 * l - q;
r = hueToRgb(p, q, h + 1 / 3);
g = hueToRgb(p, q, h);
b = hueToRgb(p, q, h - 1 / 3);
}
return '#' + decToHex[Math.floor(r * 255)] +
decToHex[Math.floor(g * 255)] +
decToHex[Math.floor(b * 255)];
}
function hueToRgb(m1, m2, h) {
if (h < 0)
h++;
if (h > 1)
h--;
if (6 * h < 1)
return m1 + (m2 - m1) * 6 * h;
else if (2 * h < 1)
return m2;
else if (3 * h < 2)
return m1 + (m2 - m1) * (2 / 3 - h) * 6;
else
return m1;
}
function processStyle(styleString) {
var str, alpha = 1;
styleString = String(styleString);
if (styleString.charAt(0) == '#') {
str = styleString;
} else if (/^rgb/.test(styleString)) {
var parts = getRgbHslContent(styleString);
var str = '#', n;
for (var i = 0; i < 3; i++) {
if (parts[i].indexOf('%') != -1) {
n = Math.floor(percent(parts[i]) * 255);
} else {
n = Number(parts[i]);
}
str += decToHex[clamp(n, 0, 255)];
}
alpha = parts[3];
} else if (/^hsl/.test(styleString)) {
var parts = getRgbHslContent(styleString);
str = hslToRgb(parts);
alpha = parts[3];
} else {
str = colorData[styleString] || styleString;
}
return {color: str, alpha: alpha};
}
var DEFAULT_STYLE = {
style: 'normal',
variant: 'normal',
weight: 'normal',
size: 10,
family: 'sans-serif'
};
// Internal text style cache
var fontStyleCache = {};
function processFontStyle(styleString) {
if (fontStyleCache[styleString]) {
return fontStyleCache[styleString];
}
var el = document.createElement('div');
var style = el.style;
try {
style.font = styleString;
} catch (ex) {
// Ignore failures to set to invalid font.
}
return fontStyleCache[styleString] = {
style: style.fontStyle || DEFAULT_STYLE.style,
variant: style.fontVariant || DEFAULT_STYLE.variant,
weight: style.fontWeight || DEFAULT_STYLE.weight,
size: style.fontSize || DEFAULT_STYLE.size,
family: style.fontFamily || DEFAULT_STYLE.family
};
}
function getComputedStyle(style, element) {
var computedStyle = {};
for (var p in style) {
computedStyle[p] = style[p];
}
// Compute the size
var canvasFontSize = parseFloat(element.currentStyle.fontSize),
fontSize = parseFloat(style.size);
if (typeof style.size == 'number') {
computedStyle.size = style.size;
} else if (style.size.indexOf('px') != -1) {
computedStyle.size = fontSize;
} else if (style.size.indexOf('em') != -1) {
computedStyle.size = canvasFontSize * fontSize;
} else if(style.size.indexOf('%') != -1) {
computedStyle.size = (canvasFontSize / 100) * fontSize;
} else if (style.size.indexOf('pt') != -1) {
computedStyle.size = fontSize / .75;
} else {
computedStyle.size = canvasFontSize;
}
// Different scaling between normal text and VML text. This was found using
// trial and error to get the same size as non VML text.
computedStyle.size *= 0.981;
return computedStyle;
}
function buildStyle(style) {
return style.style + ' ' + style.variant + ' ' + style.weight + ' ' +
style.size + 'px ' + style.family;
}
function processLineCap(lineCap) {
switch (lineCap) {
case 'butt':
return 'flat';
case 'round':
return 'round';
case 'square':
default:
return 'square';
}
}
/**
* This class implements CanvasRenderingContext2D interface as described by
* the WHATWG.
* @param {HTMLElement} surfaceElement The element that the 2D context should
* be associated with
*/
function CanvasRenderingContext2D_(surfaceElement) {
this.m_ = createMatrixIdentity();
this.mStack_ = [];
this.aStack_ = [];
this.currentPath_ = [];
// Canvas context properties
this.strokeStyle = '#000';
this.fillStyle = '#000';
this.lineWidth = 1;
this.lineJoin = 'miter';
this.lineCap = 'butt';
this.miterLimit = Z * 1;
this.globalAlpha = 1;
this.font = '10px sans-serif';
this.textAlign = 'left';
this.textBaseline = 'alphabetic';
this.canvas = surfaceElement;
var el = surfaceElement.ownerDocument.createElement('div');
el.style.width = surfaceElement.clientWidth + 'px';
el.style.height = surfaceElement.clientHeight + 'px';
el.style.overflow = 'hidden';
el.style.position = 'absolute';
surfaceElement.appendChild(el);
this.element_ = el;
this.arcScaleX_ = 1;
this.arcScaleY_ = 1;
this.lineScale_ = 1;
}
var contextPrototype = CanvasRenderingContext2D_.prototype;
contextPrototype.clearRect = function() {
if (this.textMeasureEl_) {
this.textMeasureEl_.removeNode(true);
this.textMeasureEl_ = null;
}
this.element_.innerHTML = '';
};
contextPrototype.beginPath = function() {
// TODO: Branch current matrix so that save/restore has no effect
// as per safari docs.
this.currentPath_ = [];
};
contextPrototype.moveTo = function(aX, aY) {
var p = this.getCoords_(aX, aY);
this.currentPath_.push({type: 'moveTo', x: p.x, y: p.y});
this.currentX_ = p.x;
this.currentY_ = p.y;
};
contextPrototype.lineTo = function(aX, aY) {
var p = this.getCoords_(aX, aY);
this.currentPath_.push({type: 'lineTo', x: p.x, y: p.y});
this.currentX_ = p.x;
this.currentY_ = p.y;
};
contextPrototype.bezierCurveTo = function(aCP1x, aCP1y,
aCP2x, aCP2y,
aX, aY) {
var p = this.getCoords_(aX, aY);
var cp1 = this.getCoords_(aCP1x, aCP1y);
var cp2 = this.getCoords_(aCP2x, aCP2y);
bezierCurveTo(this, cp1, cp2, p);
};
// Helper function that takes the already fixed cordinates.
function bezierCurveTo(self, cp1, cp2, p) {
self.currentPath_.push({
type: 'bezierCurveTo',
cp1x: cp1.x,
cp1y: cp1.y,
cp2x: cp2.x,
cp2y: cp2.y,
x: p.x,
y: p.y
});
self.currentX_ = p.x;
self.currentY_ = p.y;
}
contextPrototype.quadraticCurveTo = function(aCPx, aCPy, aX, aY) {
// the following is lifted almost directly from
// http://developer.mozilla.org/en/docs/Canvas_tutorial:Drawing_shapes
var cp = this.getCoords_(aCPx, aCPy);
var p = this.getCoords_(aX, aY);
var cp1 = {
x: this.currentX_ + 2.0 / 3.0 * (cp.x - this.currentX_),
y: this.currentY_ + 2.0 / 3.0 * (cp.y - this.currentY_)
};
var cp2 = {
x: cp1.x + (p.x - this.currentX_) / 3.0,
y: cp1.y + (p.y - this.currentY_) / 3.0
};
bezierCurveTo(this, cp1, cp2, p);
};
contextPrototype.arc = function(aX, aY, aRadius,
aStartAngle, aEndAngle, aClockwise) {
aRadius *= Z;
var arcType = aClockwise ? 'at' : 'wa';
var xStart = aX + mc(aStartAngle) * aRadius - Z2;
var yStart = aY + ms(aStartAngle) * aRadius - Z2;
var xEnd = aX + mc(aEndAngle) * aRadius - Z2;
var yEnd = aY + ms(aEndAngle) * aRadius - Z2;
// IE won't render arches drawn counter clockwise if xStart == xEnd.
if (xStart == xEnd && !aClockwise) {
xStart += 0.125; // Offset xStart by 1/80 of a pixel. Use something
// that can be represented in binary
}
var p = this.getCoords_(aX, aY);
var pStart = this.getCoords_(xStart, yStart);
var pEnd = this.getCoords_(xEnd, yEnd);
this.currentPath_.push({type: arcType,
x: p.x,
y: p.y,
radius: aRadius,
xStart: pStart.x,
yStart: pStart.y,
xEnd: pEnd.x,
yEnd: pEnd.y});
};
contextPrototype.rect = function(aX, aY, aWidth, aHeight) {
this.moveTo(aX, aY);
this.lineTo(aX + aWidth, aY);
this.lineTo(aX + aWidth, aY + aHeight);
this.lineTo(aX, aY + aHeight);
this.closePath();
};
contextPrototype.strokeRect = function(aX, aY, aWidth, aHeight) {
var oldPath = this.currentPath_;
this.beginPath();
this.moveTo(aX, aY);
this.lineTo(aX + aWidth, aY);
this.lineTo(aX + aWidth, aY + aHeight);
this.lineTo(aX, aY + aHeight);
this.closePath();
this.stroke();
this.currentPath_ = oldPath;
};
contextPrototype.fillRect = function(aX, aY, aWidth, aHeight) {
var oldPath = this.currentPath_;
this.beginPath();
this.moveTo(aX, aY);
this.lineTo(aX + aWidth, aY);
this.lineTo(aX + aWidth, aY + aHeight);
this.lineTo(aX, aY + aHeight);
this.closePath();
this.fill();
this.currentPath_ = oldPath;
};
contextPrototype.createLinearGradient = function(aX0, aY0, aX1, aY1) {
var gradient = new CanvasGradient_('gradient');
gradient.x0_ = aX0;
gradient.y0_ = aY0;
gradient.x1_ = aX1;
gradient.y1_ = aY1;
return gradient;
};
contextPrototype.createRadialGradient = function(aX0, aY0, aR0,
aX1, aY1, aR1) {
var gradient = new CanvasGradient_('gradientradial');
gradient.x0_ = aX0;
gradient.y0_ = aY0;
gradient.r0_ = aR0;
gradient.x1_ = aX1;
gradient.y1_ = aY1;
gradient.r1_ = aR1;
return gradient;
};
contextPrototype.drawImage = function(image, var_args) {
var dx, dy, dw, dh, sx, sy, sw, sh;
// to find the original width we overide the width and height
var oldRuntimeWidth = image.runtimeStyle.width;
var oldRuntimeHeight = image.runtimeStyle.height;
image.runtimeStyle.width = 'auto';
image.runtimeStyle.height = 'auto';
// get the original size
var w = image.width;
var h = image.height;
// and remove overides
image.runtimeStyle.width = oldRuntimeWidth;
image.runtimeStyle.height = oldRuntimeHeight;
if (arguments.length == 3) {
dx = arguments[1];
dy = arguments[2];
sx = sy = 0;
sw = dw = w;
sh = dh = h;
} else if (arguments.length == 5) {
dx = arguments[1];
dy = arguments[2];
dw = arguments[3];
dh = arguments[4];
sx = sy = 0;
sw = w;
sh = h;
} else if (arguments.length == 9) {
sx = arguments[1];
sy = arguments[2];
sw = arguments[3];
sh = arguments[4];
dx = arguments[5];
dy = arguments[6];
dw = arguments[7];
dh = arguments[8];
} else {
throw Error('Invalid number of arguments');
}
var d = this.getCoords_(dx, dy);
var w2 = sw / 2;
var h2 = sh / 2;
var vmlStr = [];
var W = 10;
var H = 10;
// For some reason that I've now forgotten, using divs didn't work
vmlStr.push(' <g_vml_:group',
' coordsize="', Z * W, ',', Z * H, '"',
' coordorigin="0,0"' ,
' style="width:', W, 'px;height:', H, 'px;position:absolute;');
// If filters are necessary (rotation exists), create them
// filters are bog-slow, so only create them if abbsolutely necessary
// The following check doesn't account for skews (which don't exist
// in the canvas spec (yet) anyway.
if (this.m_[0][0] != 1 || this.m_[0][1] ||
this.m_[1][1] != 1 || this.m_[1][0]) {
var filter = [];
// Note the 12/21 reversal
filter.push('M11=', this.m_[0][0], ',',
'M12=', this.m_[1][0], ',',
'M21=', this.m_[0][1], ',',
'M22=', this.m_[1][1], ',',
'Dx=', mr(d.x / Z), ',',
'Dy=', mr(d.y / Z), '');
// Bounding box calculation (need to minimize displayed area so that
// filters don't waste time on unused pixels.
var max = d;
var c2 = this.getCoords_(dx + dw, dy);
var c3 = this.getCoords_(dx, dy + dh);
var c4 = this.getCoords_(dx + dw, dy + dh);
max.x = m.max(max.x, c2.x, c3.x, c4.x);
max.y = m.max(max.y, c2.y, c3.y, c4.y);
vmlStr.push('padding:0 ', mr(max.x / Z), 'px ', mr(max.y / Z),
'px 0;filter:progid:DXImageTransform.Microsoft.Matrix(',
filter.join(''), ", sizingmethod='clip');");
} else {
vmlStr.push('top:', mr(d.y / Z), 'px;left:', mr(d.x / Z), 'px;');
}
vmlStr.push(' ">' ,
'<g_vml_:image src="', image.src, '"',
' style="width:', Z * dw, 'px;',
' height:', Z * dh, 'px"',
' cropleft="', sx / w, '"',
' croptop="', sy / h, '"',
' cropright="', (w - sx - sw) / w, '"',
' cropbottom="', (h - sy - sh) / h, '"',
' />',
'</g_vml_:group>');
this.element_.insertAdjacentHTML('BeforeEnd', vmlStr.join(''));
};
contextPrototype.stroke = function(aFill) {
var W = 10;
var H = 10;
// Divide the shape into chunks if it's too long because IE has a limit
// somewhere for how long a VML shape can be. This simple division does
// not work with fills, only strokes, unfortunately.
var chunkSize = 5000;
var min = {x: null, y: null};
var max = {x: null, y: null};
for (var j = 0; j < this.currentPath_.length; j += chunkSize) {
var lineStr = [];
var lineOpen = false;
lineStr.push('<g_vml_:shape',
' filled="', !!aFill, '"',
' style="position:absolute;width:', W, 'px;height:', H, 'px;"',
' coordorigin="0,0"',
' coordsize="', Z * W, ',', Z * H, '"',
' stroked="', !aFill, '"',
' path="');
var newSeq = false;
for (var i = j; i < Math.min(j + chunkSize, this.currentPath_.length); i++) {
if (i % chunkSize == 0 && i > 0) { // move into position for next chunk
lineStr.push(' m ', mr(this.currentPath_[i-1].x), ',', mr(this.currentPath_[i-1].y));
}
var p = this.currentPath_[i];
var c;
switch (p.type) {
case 'moveTo':
c = p;
lineStr.push(' m ', mr(p.x), ',', mr(p.y));
break;
case 'lineTo':
lineStr.push(' l ', mr(p.x), ',', mr(p.y));
break;
case 'close':
lineStr.push(' x ');
p = null;
break;
case 'bezierCurveTo':
lineStr.push(' c ',
mr(p.cp1x), ',', mr(p.cp1y), ',',
mr(p.cp2x), ',', mr(p.cp2y), ',',
mr(p.x), ',', mr(p.y));
break;
case 'at':
case 'wa':
lineStr.push(' ', p.type, ' ',
mr(p.x - this.arcScaleX_ * p.radius), ',',
mr(p.y - this.arcScaleY_ * p.radius), ' ',
mr(p.x + this.arcScaleX_ * p.radius), ',',
mr(p.y + this.arcScaleY_ * p.radius), ' ',
mr(p.xStart), ',', mr(p.yStart), ' ',
mr(p.xEnd), ',', mr(p.yEnd));
break;
}
// TODO: Following is broken for curves due to
// move to proper paths.
// Figure out dimensions so we can do gradient fills
// properly
if (p) {
if (min.x == null || p.x < min.x) {
min.x = p.x;
}
if (max.x == null || p.x > max.x) {
max.x = p.x;
}
if (min.y == null || p.y < min.y) {
min.y = p.y;
}
if (max.y == null || p.y > max.y) {
max.y = p.y;
}
}
}
lineStr.push(' ">');
if (!aFill) {
appendStroke(this, lineStr);
} else {
appendFill(this, lineStr, min, max);
}
lineStr.push('</g_vml_:shape>');
this.element_.insertAdjacentHTML('beforeEnd', lineStr.join(''));
}
};
function appendStroke(ctx, lineStr) {
var a = processStyle(ctx.strokeStyle);
var color = a.color;
var opacity = a.alpha * ctx.globalAlpha;
var lineWidth = ctx.lineScale_ * ctx.lineWidth;
// VML cannot correctly render a line if the width is less than 1px.
// In that case, we dilute the color to make the line look thinner.
if (lineWidth < 1) {
opacity *= lineWidth;
}
lineStr.push(
'<g_vml_:stroke',
' opacity="', opacity, '"',
' joinstyle="', ctx.lineJoin, '"',
' miterlimit="', ctx.miterLimit, '"',
' endcap="', processLineCap(ctx.lineCap), '"',
' weight="', lineWidth, 'px"',
' color="', color, '" />'
);
}
function appendFill(ctx, lineStr, min, max) {
var fillStyle = ctx.fillStyle;
var arcScaleX = ctx.arcScaleX_;
var arcScaleY = ctx.arcScaleY_;
var width = max.x - min.x;
var height = max.y - min.y;
if (fillStyle instanceof CanvasGradient_) {
// TODO: Gradients transformed with the transformation matrix.
var angle = 0;
var focus = {x: 0, y: 0};
// additional offset
var shift = 0;
// scale factor for offset
var expansion = 1;
if (fillStyle.type_ == 'gradient') {
var x0 = fillStyle.x0_ / arcScaleX;
var y0 = fillStyle.y0_ / arcScaleY;
var x1 = fillStyle.x1_ / arcScaleX;
var y1 = fillStyle.y1_ / arcScaleY;
var p0 = ctx.getCoords_(x0, y0);
var p1 = ctx.getCoords_(x1, y1);
var dx = p1.x - p0.x;
var dy = p1.y - p0.y;
angle = Math.atan2(dx, dy) * 180 / Math.PI;
// The angle should be a non-negative number.
if (angle < 0) {
angle += 360;
}
// Very small angles produce an unexpected result because they are
// converted to a scientific notation string.
if (angle < 1e-6) {
angle = 0;
}
} else {
var p0 = ctx.getCoords_(fillStyle.x0_, fillStyle.y0_);
focus = {
x: (p0.x - min.x) / width,
y: (p0.y - min.y) / height
};
width /= arcScaleX * Z;
height /= arcScaleY * Z;
var dimension = m.max(width, height);
shift = 2 * fillStyle.r0_ / dimension;
expansion = 2 * fillStyle.r1_ / dimension - shift;
}
// We need to sort the color stops in ascending order by offset,
// otherwise IE won't interpret it correctly.
var stops = fillStyle.colors_;
stops.sort(function(cs1, cs2) {
return cs1.offset - cs2.offset;
});
var length = stops.length;
var color1 = stops[0].color;
var color2 = stops[length - 1].color;
var opacity1 = stops[0].alpha * ctx.globalAlpha;
var opacity2 = stops[length - 1].alpha * ctx.globalAlpha;
var colors = [];
for (var i = 0; i < length; i++) {
var stop = stops[i];
colors.push(stop.offset * expansion + shift + ' ' + stop.color);
}
// When colors attribute is used, the meanings of opacity and o:opacity2
// are reversed.
lineStr.push('<g_vml_:fill type="', fillStyle.type_, '"',
' method="none" focus="100%"',
' color="', color1, '"',
' color2="', color2, '"',
' colors="', colors.join(','), '"',
' opacity="', opacity2, '"',
' g_o_:opacity2="', opacity1, '"',
' angle="', angle, '"',
' focusposition="', focus.x, ',', focus.y, '" />');
} else if (fillStyle instanceof CanvasPattern_) {
if (width && height) {
var deltaLeft = -min.x;
var deltaTop = -min.y;
lineStr.push('<g_vml_:fill',
' position="',
deltaLeft / width * arcScaleX * arcScaleX, ',',
deltaTop / height * arcScaleY * arcScaleY, '"',
' type="tile"',
// TODO: Figure out the correct size to fit the scale.
//' size="', w, 'px ', h, 'px"',
' src="', fillStyle.src_, '" />');
}
} else {
var a = processStyle(ctx.fillStyle);
var color = a.color;
var opacity = a.alpha * ctx.globalAlpha;
lineStr.push('<g_vml_:fill color="', color, '" opacity="', opacity,
'" />');
}
}
contextPrototype.fill = function() {
this.stroke(true);
};
contextPrototype.closePath = function() {
this.currentPath_.push({type: 'close'});
};
/**
* @private
*/
contextPrototype.getCoords_ = function(aX, aY) {
var m = this.m_;
return {
x: Z * (aX * m[0][0] + aY * m[1][0] + m[2][0]) - Z2,
y: Z * (aX * m[0][1] + aY * m[1][1] + m[2][1]) - Z2
};
};
contextPrototype.save = function() {
var o = {};
copyState(this, o);
this.aStack_.push(o);
this.mStack_.push(this.m_);
this.m_ = matrixMultiply(createMatrixIdentity(), this.m_);
};
contextPrototype.restore = function() {
if (this.aStack_.length) {
copyState(this.aStack_.pop(), this);
this.m_ = this.mStack_.pop();
}
};
function matrixIsFinite(m) {
return isFinite(m[0][0]) && isFinite(m[0][1]) &&
isFinite(m[1][0]) && isFinite(m[1][1]) &&
isFinite(m[2][0]) && isFinite(m[2][1]);
}
function setM(ctx, m, updateLineScale) {
if (!matrixIsFinite(m)) {
return;
}
ctx.m_ = m;
if (updateLineScale) {
// Get the line scale.
// Determinant of this.m_ means how much the area is enlarged by the
// transformation. So its square root can be used as a scale factor
// for width.
var det = m[0][0] * m[1][1] - m[0][1] * m[1][0];
ctx.lineScale_ = sqrt(abs(det));
}
}
contextPrototype.translate = function(aX, aY) {
var m1 = [
[1, 0, 0],
[0, 1, 0],
[aX, aY, 1]
];
setM(this, matrixMultiply(m1, this.m_), false);
};
contextPrototype.rotate = function(aRot) {
var c = mc(aRot);
var s = ms(aRot);
var m1 = [
[c, s, 0],
[-s, c, 0],
[0, 0, 1]
];
setM(this, matrixMultiply(m1, this.m_), false);
};
contextPrototype.scale = function(aX, aY) {
this.arcScaleX_ *= aX;
this.arcScaleY_ *= aY;
var m1 = [
[aX, 0, 0],
[0, aY, 0],
[0, 0, 1]
];
setM(this, matrixMultiply(m1, this.m_), true);
};
contextPrototype.transform = function(m11, m12, m21, m22, dx, dy) {
var m1 = [
[m11, m12, 0],
[m21, m22, 0],
[dx, dy, 1]
];
setM(this, matrixMultiply(m1, this.m_), true);
};
contextPrototype.setTransform = function(m11, m12, m21, m22, dx, dy) {
var m = [
[m11, m12, 0],
[m21, m22, 0],
[dx, dy, 1]
];
setM(this, m, true);
};
/**
* The text drawing function.
* The maxWidth argument isn't taken in account, since no browser supports
* it yet.
*/
contextPrototype.drawText_ = function(text, x, y, maxWidth, stroke) {
var m = this.m_,
delta = 1000,
left = 0,
right = delta,
offset = {x: 0, y: 0},
lineStr = [];
var fontStyle = getComputedStyle(processFontStyle(this.font),
this.element_);
var fontStyleString = buildStyle(fontStyle);
var elementStyle = this.element_.currentStyle;
var textAlign = this.textAlign.toLowerCase();
switch (textAlign) {
case 'left':
case 'center':
case 'right':
break;
case 'end':
textAlign = elementStyle.direction == 'ltr' ? 'right' : 'left';
break;
case 'start':
textAlign = elementStyle.direction == 'rtl' ? 'right' : 'left';
break;
default:
textAlign = 'left';
}
// 1.75 is an arbitrary number, as there is no info about the text baseline
switch (this.textBaseline) {
case 'hanging':
case 'top':
offset.y = fontStyle.size / 1.75;
break;
case 'middle':
break;
default:
case null:
case 'alphabetic':
case 'ideographic':
case 'bottom':
offset.y = -fontStyle.size / 2.25;
break;
}
switch(textAlign) {
case 'right':
left = delta;
right = 0.05;
break;
case 'center':
left = right = delta / 2;
break;
}
var d = this.getCoords_(x + offset.x, y + offset.y);
lineStr.push('<g_vml_:line from="', -left ,' 0" to="', right ,' 0.05" ',
' coordsize="100 100" coordorigin="0 0"',
' filled="', !stroke, '" stroked="', !!stroke,
'" style="position:absolute;width:1px;height:1px;">');
if (stroke) {
appendStroke(this, lineStr);
} else {
// TODO: Fix the min and max params.
appendFill(this, lineStr, {x: -left, y: 0},
{x: right, y: fontStyle.size});
}
var skewM = m[0][0].toFixed(3) + ',' + m[1][0].toFixed(3) + ',' +
m[0][1].toFixed(3) + ',' + m[1][1].toFixed(3) + ',0,0';
var skewOffset = mr(d.x / Z) + ',' + mr(d.y / Z);
lineStr.push('<g_vml_:skew on="t" matrix="', skewM ,'" ',
' offset="', skewOffset, '" origin="', left ,' 0" />',
'<g_vml_:path textpathok="true" />',
'<g_vml_:textpath on="true" string="',
encodeHtmlAttribute(text),
'" style="v-text-align:', textAlign,
';font:', encodeHtmlAttribute(fontStyleString),
'" /></g_vml_:line>');
this.element_.insertAdjacentHTML('beforeEnd', lineStr.join(''));
};
contextPrototype.fillText = function(text, x, y, maxWidth) {
this.drawText_(text, x, y, maxWidth, false);
};
contextPrototype.strokeText = function(text, x, y, maxWidth) {
this.drawText_(text, x, y, maxWidth, true);
};
contextPrototype.measureText = function(text) {
if (!this.textMeasureEl_) {
var s = '<span style="position:absolute;' +
'top:-20000px;left:0;padding:0;margin:0;border:none;' +
'white-space:pre;"></span>';
this.element_.insertAdjacentHTML('beforeEnd', s);
this.textMeasureEl_ = this.element_.lastChild;
}
var doc = this.element_.ownerDocument;
this.textMeasureEl_.innerHTML = '';
this.textMeasureEl_.style.font = this.font;
// Don't use innerHTML or innerText because they allow markup/whitespace.
this.textMeasureEl_.appendChild(doc.createTextNode(text));
return {width: this.textMeasureEl_.offsetWidth};
};
/******** STUBS ********/
contextPrototype.clip = function() {
// TODO: Implement
};
contextPrototype.arcTo = function() {
// TODO: Implement
};
contextPrototype.createPattern = function(image, repetition) {
return new CanvasPattern_(image, repetition);
};
// Gradient / Pattern Stubs
function CanvasGradient_(aType) {
this.type_ = aType;
this.x0_ = 0;
this.y0_ = 0;
this.r0_ = 0;
this.x1_ = 0;
this.y1_ = 0;
this.r1_ = 0;
this.colors_ = [];
}
CanvasGradient_.prototype.addColorStop = function(aOffset, aColor) {
aColor = processStyle(aColor);
this.colors_.push({offset: aOffset,
color: aColor.color,
alpha: aColor.alpha});
};
function CanvasPattern_(image, repetition) {
assertImageIsValid(image);
switch (repetition) {
case 'repeat':
case null:
case '':
this.repetition_ = 'repeat';
break
case 'repeat-x':
case 'repeat-y':
case 'no-repeat':
this.repetition_ = repetition;
break;
default:
throwException('SYNTAX_ERR');
}
this.src_ = image.src;
this.width_ = image.width;
this.height_ = image.height;
}
function throwException(s) {
throw new DOMException_(s);
}
function assertImageIsValid(img) {
if (!img || img.nodeType != 1 || img.tagName != 'IMG') {
throwException('TYPE_MISMATCH_ERR');
}
if (img.readyState != 'complete') {
throwException('INVALID_STATE_ERR');
}
}
function DOMException_(s) {
this.code = this[s];
this.message = s +': DOM Exception ' + this.code;
}
var p = DOMException_.prototype = new Error;
p.INDEX_SIZE_ERR = 1;
p.DOMSTRING_SIZE_ERR = 2;
p.HIERARCHY_REQUEST_ERR = 3;
p.WRONG_DOCUMENT_ERR = 4;
p.INVALID_CHARACTER_ERR = 5;
p.NO_DATA_ALLOWED_ERR = 6;
p.NO_MODIFICATION_ALLOWED_ERR = 7;
p.NOT_FOUND_ERR = 8;
p.NOT_SUPPORTED_ERR = 9;
p.INUSE_ATTRIBUTE_ERR = 10;
p.INVALID_STATE_ERR = 11;
p.SYNTAX_ERR = 12;
p.INVALID_MODIFICATION_ERR = 13;
p.NAMESPACE_ERR = 14;
p.INVALID_ACCESS_ERR = 15;
p.VALIDATION_ERR = 16;
p.TYPE_MISMATCH_ERR = 17;
// set up externs
G_vmlCanvasManager = G_vmlCanvasManager_;
CanvasRenderingContext2D = CanvasRenderingContext2D_;
CanvasGradient = CanvasGradient_;
CanvasPattern = CanvasPattern_;
DOMException = DOMException_;
})();
} // if
| JavaScript |
/*
Flot plugin for computing bottoms for filled line and bar charts.
The case: you've got two series that you want to fill the area
between. In Flot terms, you need to use one as the fill bottom of the
other. You can specify the bottom of each data point as the third
coordinate manually, or you can use this plugin to compute it for you.
In order to name the other series, you need to give it an id, like this
var dataset = [
{ data: [ ... ], id: "foo" } , // use default bottom
{ data: [ ... ], fillBetween: "foo" }, // use first dataset as bottom
];
$.plot($("#placeholder"), dataset, { line: { show: true, fill: true }});
As a convenience, if the id given is a number that doesn't appear as
an id in the series, it is interpreted as the index in the array
instead (so fillBetween: 0 can also mean the first series).
Internally, the plugin modifies the datapoints in each series. For
line series, extra data points might be inserted through
interpolation. Note that at points where the bottom line is not
defined (due to a null point or start/end of line), the current line
will show a gap too. The algorithm comes from the jquery.flot.stack.js
plugin, possibly some code could be shared.
*/
(function ($) {
var options = {
series: { fillBetween: null } // or number
};
function init(plot) {
function findBottomSeries(s, allseries) {
var i;
for (i = 0; i < allseries.length; ++i) {
if (allseries[i].id == s.fillBetween)
return allseries[i];
}
if (typeof s.fillBetween == "number") {
i = s.fillBetween;
if (i < 0 || i >= allseries.length)
return null;
return allseries[i];
}
return null;
}
function computeFillBottoms(plot, s, datapoints) {
if (s.fillBetween == null)
return;
var other = findBottomSeries(s, plot.getData());
if (!other)
return;
var ps = datapoints.pointsize,
points = datapoints.points,
otherps = other.datapoints.pointsize,
otherpoints = other.datapoints.points,
newpoints = [],
px, py, intery, qx, qy, bottom,
withlines = s.lines.show,
withbottom = ps > 2 && datapoints.format[2].y,
withsteps = withlines && s.lines.steps,
fromgap = true,
i = 0, j = 0, l;
while (true) {
if (i >= points.length)
break;
l = newpoints.length;
if (points[i] == null) {
// copy gaps
for (m = 0; m < ps; ++m)
newpoints.push(points[i + m]);
i += ps;
}
else if (j >= otherpoints.length) {
// for lines, we can't use the rest of the points
if (!withlines) {
for (m = 0; m < ps; ++m)
newpoints.push(points[i + m]);
}
i += ps;
}
else if (otherpoints[j] == null) {
// oops, got a gap
for (m = 0; m < ps; ++m)
newpoints.push(null);
fromgap = true;
j += otherps;
}
else {
// cases where we actually got two points
px = points[i];
py = points[i + 1];
qx = otherpoints[j];
qy = otherpoints[j + 1];
bottom = 0;
if (px == qx) {
for (m = 0; m < ps; ++m)
newpoints.push(points[i + m]);
//newpoints[l + 1] += qy;
bottom = qy;
i += ps;
j += otherps;
}
else if (px > qx) {
// we got past point below, might need to
// insert interpolated extra point
if (withlines && i > 0 && points[i - ps] != null) {
intery = py + (points[i - ps + 1] - py) * (qx - px) / (points[i - ps] - px);
newpoints.push(qx);
newpoints.push(intery)
for (m = 2; m < ps; ++m)
newpoints.push(points[i + m]);
bottom = qy;
}
j += otherps;
}
else { // px < qx
if (fromgap && withlines) {
// if we come from a gap, we just skip this point
i += ps;
continue;
}
for (m = 0; m < ps; ++m)
newpoints.push(points[i + m]);
// we might be able to interpolate a point below,
// this can give us a better y
if (withlines && j > 0 && otherpoints[j - otherps] != null)
bottom = qy + (otherpoints[j - otherps + 1] - qy) * (px - qx) / (otherpoints[j - otherps] - qx);
//newpoints[l + 1] += bottom;
i += ps;
}
fromgap = false;
if (l != newpoints.length && withbottom)
newpoints[l + 2] = bottom;
}
// maintain the line steps invariant
if (withsteps && l != newpoints.length && l > 0
&& newpoints[l] != null
&& newpoints[l] != newpoints[l - ps]
&& newpoints[l + 1] != newpoints[l - ps + 1]) {
for (m = 0; m < ps; ++m)
newpoints[l + ps + m] = newpoints[l + m];
newpoints[l + 1] = newpoints[l - ps + 1];
}
}
datapoints.points = newpoints;
}
plot.hooks.processDatapoints.push(computeFillBottoms);
}
$.plot.plugins.push({
init: init,
options: options,
name: 'fillbetween',
version: '1.0'
});
})(jQuery);
| JavaScript |
/*
Flot plugin for rendering pie charts. The plugin assumes the data is
coming is as a single data value for each series, and each of those
values is a positive value or zero (negative numbers don't make
any sense and will cause strange effects). The data values do
NOT need to be passed in as percentage values because it
internally calculates the total and percentages.
* Created by Brian Medendorp, June 2009
* Updated November 2009 with contributions from: btburnett3, Anthony Aragues and Xavi Ivars
* Changes:
2009-10-22: lineJoin set to round
2009-10-23: IE full circle fix, donut
2009-11-11: Added basic hover from btburnett3 - does not work in IE, and center is off in Chrome and Opera
2009-11-17: Added IE hover capability submitted by Anthony Aragues
2009-11-18: Added bug fix submitted by Xavi Ivars (issues with arrays when other JS libraries are included as well)
Available options are:
series: {
pie: {
show: true/false
radius: 0-1 for percentage of fullsize, or a specified pixel length, or 'auto'
innerRadius: 0-1 for percentage of fullsize or a specified pixel length, for creating a donut effect
startAngle: 0-2 factor of PI used for starting angle (in radians) i.e 3/2 starts at the top, 0 and 2 have the same result
tilt: 0-1 for percentage to tilt the pie, where 1 is no tilt, and 0 is completely flat (nothing will show)
offset: {
top: integer value to move the pie up or down
left: integer value to move the pie left or right, or 'auto'
},
stroke: {
color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#FFF')
width: integer pixel width of the stroke
},
label: {
show: true/false, or 'auto'
formatter: a user-defined function that modifies the text/style of the label text
radius: 0-1 for percentage of fullsize, or a specified pixel length
background: {
color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#000')
opacity: 0-1
},
threshold: 0-1 for the percentage value at which to hide labels (if they're too small)
},
combine: {
threshold: 0-1 for the percentage value at which to combine slices (if they're too small)
color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#CCC'), if null, the plugin will automatically use the color of the first slice to be combined
label: any text value of what the combined slice should be labeled
}
highlight: {
opacity: 0-1
}
}
}
More detail and specific examples can be found in the included HTML file.
*/
(function ($)
{
function init(plot) // this is the "body" of the plugin
{
var canvas = null;
var target = null;
var maxRadius = null;
var centerLeft = null;
var centerTop = null;
var total = 0;
var redraw = true;
var redrawAttempts = 10;
var shrink = 0.95;
var legendWidth = 0;
var processed = false;
var raw = false;
// interactive variables
var highlights = [];
// add hook to determine if pie plugin in enabled, and then perform necessary operations
plot.hooks.processOptions.push(checkPieEnabled);
plot.hooks.bindEvents.push(bindEvents);
// check to see if the pie plugin is enabled
function checkPieEnabled(plot, options)
{
if (options.series.pie.show)
{
//disable grid
options.grid.show = false;
// set labels.show
if (options.series.pie.label.show=='auto')
if (options.legend.show)
options.series.pie.label.show = false;
else
options.series.pie.label.show = true;
// set radius
if (options.series.pie.radius=='auto')
if (options.series.pie.label.show)
options.series.pie.radius = 3/4;
else
options.series.pie.radius = 1;
// ensure sane tilt
if (options.series.pie.tilt>1)
options.series.pie.tilt=1;
if (options.series.pie.tilt<0)
options.series.pie.tilt=0;
// add processData hook to do transformations on the data
plot.hooks.processDatapoints.push(processDatapoints);
plot.hooks.drawOverlay.push(drawOverlay);
// add draw hook
plot.hooks.draw.push(draw);
}
}
// bind hoverable events
function bindEvents(plot, eventHolder)
{
var options = plot.getOptions();
if (options.series.pie.show && options.grid.hoverable)
eventHolder.unbind('mousemove').mousemove(onMouseMove);
if (options.series.pie.show && options.grid.clickable)
eventHolder.unbind('click').click(onClick);
}
// debugging function that prints out an object
function alertObject(obj)
{
var msg = '';
function traverse(obj, depth)
{
if (!depth)
depth = 0;
for (var i = 0; i < obj.length; ++i)
{
for (var j=0; j<depth; j++)
msg += '\t';
if( typeof obj[i] == "object")
{ // its an object
msg += ''+i+':\n';
traverse(obj[i], depth+1);
}
else
{ // its a value
msg += ''+i+': '+obj[i]+'\n';
}
}
}
traverse(obj);
alert(msg);
}
function calcTotal(data)
{
for (var i = 0; i < data.length; ++i)
{
var item = parseFloat(data[i].data[0][1]);
if (item)
total += item;
}
}
function processDatapoints(plot, series, data, datapoints)
{
if (!processed)
{
processed = true;
canvas = plot.getCanvas();
target = $(canvas).parent();
options = plot.getOptions();
plot.setData(combine(plot.getData()));
}
}
function setupPie()
{
legendWidth = target.children().filter('.legend').children().width();
// calculate maximum radius and center point
maxRadius = Math.min(canvas.width,(canvas.height/options.series.pie.tilt))/2;
centerTop = (canvas.height/2)+options.series.pie.offset.top;
centerLeft = (canvas.width/2);
if (options.series.pie.offset.left=='auto')
if (options.legend.position.match('w'))
centerLeft += legendWidth/2;
else
centerLeft -= legendWidth/2;
else
centerLeft += options.series.pie.offset.left;
if (centerLeft<maxRadius)
centerLeft = maxRadius;
else if (centerLeft>canvas.width-maxRadius)
centerLeft = canvas.width-maxRadius;
}
function fixData(data)
{
for (var i = 0; i < data.length; ++i)
{
if (typeof(data[i].data)=='number')
data[i].data = [[1,data[i].data]];
else if (typeof(data[i].data)=='undefined' || typeof(data[i].data[0])=='undefined')
{
if (typeof(data[i].data)!='undefined' && typeof(data[i].data.label)!='undefined')
data[i].label = data[i].data.label; // fix weirdness coming from flot
data[i].data = [[1,0]];
}
}
return data;
}
function combine(data)
{
data = fixData(data);
calcTotal(data);
var combined = 0;
var numCombined = 0;
var color = options.series.pie.combine.color;
var newdata = [];
for (var i = 0; i < data.length; ++i)
{
// make sure its a number
data[i].data[0][1] = parseFloat(data[i].data[0][1]);
if (!data[i].data[0][1])
data[i].data[0][1] = 0;
if (data[i].data[0][1]/total<=options.series.pie.combine.threshold)
{
combined += data[i].data[0][1];
numCombined++;
if (!color)
color = data[i].color;
}
else
{
newdata.push({
data: [[1,data[i].data[0][1]]],
color: data[i].color,
label: data[i].label,
angle: (data[i].data[0][1]*(Math.PI*2))/total,
percent: (data[i].data[0][1]/total*100)
});
}
}
if (numCombined>0)
newdata.push({
data: [[1,combined]],
color: color,
label: options.series.pie.combine.label,
angle: (combined*(Math.PI*2))/total,
percent: (combined/total*100)
});
return newdata;
}
function draw(plot, newCtx)
{
if (!target) return; // if no series were passed
ctx = newCtx;
setupPie();
var slices = plot.getData();
var attempts = 0;
while (redraw && attempts<redrawAttempts)
{
redraw = false;
if (attempts>0)
maxRadius *= shrink;
attempts += 1;
clear();
if (options.series.pie.tilt<=0.8)
drawShadow();
drawPie();
}
if (attempts >= redrawAttempts) {
clear();
target.prepend('<div class="error">Could not draw pie with labels contained inside canvas</div>');
}
if ( plot.setSeries && plot.insertLegend )
{
plot.setSeries(slices);
plot.insertLegend();
}
// we're actually done at this point, just defining internal functions at this point
function clear()
{
ctx.clearRect(0,0,canvas.width,canvas.height);
target.children().filter('.pieLabel, .pieLabelBackground').remove();
}
function drawShadow()
{
var shadowLeft = 5;
var shadowTop = 15;
var edge = 10;
var alpha = 0.02;
// set radius
if (options.series.pie.radius>1)
var radius = options.series.pie.radius;
else
var radius = maxRadius * options.series.pie.radius;
if (radius>=(canvas.width/2)-shadowLeft || radius*options.series.pie.tilt>=(canvas.height/2)-shadowTop || radius<=edge)
return; // shadow would be outside canvas, so don't draw it
ctx.save();
ctx.translate(shadowLeft,shadowTop);
ctx.globalAlpha = alpha;
ctx.fillStyle = '#000';
// center and rotate to starting position
ctx.translate(centerLeft,centerTop);
ctx.scale(1, options.series.pie.tilt);
//radius -= edge;
for (var i=1; i<=edge; i++)
{
ctx.beginPath();
ctx.arc(0,0,radius,0,Math.PI*2,false);
ctx.fill();
radius -= i;
}
ctx.restore();
}
function drawPie()
{
startAngle = Math.PI*options.series.pie.startAngle;
// set radius
if (options.series.pie.radius>1)
var radius = options.series.pie.radius;
else
var radius = maxRadius * options.series.pie.radius;
// center and rotate to starting position
ctx.save();
ctx.translate(centerLeft,centerTop);
ctx.scale(1, options.series.pie.tilt);
//ctx.rotate(startAngle); // start at top; -- This doesn't work properly in Opera
// draw slices
ctx.save();
var currentAngle = startAngle;
for (var i = 0; i < slices.length; ++i)
{
slices[i].startAngle = currentAngle;
drawSlice(slices[i].angle, slices[i].color, true);
}
ctx.restore();
// draw slice outlines
ctx.save();
ctx.lineWidth = options.series.pie.stroke.width;
currentAngle = startAngle;
for (var i = 0; i < slices.length; ++i)
drawSlice(slices[i].angle, options.series.pie.stroke.color, false);
ctx.restore();
// draw donut hole
drawDonutHole(ctx);
// draw labels
if (options.series.pie.label.show)
drawLabels();
// restore to original state
ctx.restore();
function drawSlice(angle, color, fill)
{
if (angle<=0)
return;
if (fill)
ctx.fillStyle = color;
else
{
ctx.strokeStyle = color;
ctx.lineJoin = 'round';
}
ctx.beginPath();
if (Math.abs(angle - Math.PI*2) > 0.000000001)
ctx.moveTo(0,0); // Center of the pie
else if ($.browser.msie)
angle -= 0.0001;
//ctx.arc(0,0,radius,0,angle,false); // This doesn't work properly in Opera
ctx.arc(0,0,radius,currentAngle,currentAngle+angle,false);
ctx.closePath();
//ctx.rotate(angle); // This doesn't work properly in Opera
currentAngle += angle;
if (fill)
ctx.fill();
else
ctx.stroke();
}
function drawLabels()
{
var currentAngle = startAngle;
// set radius
if (options.series.pie.label.radius>1)
var radius = options.series.pie.label.radius;
else
var radius = maxRadius * options.series.pie.label.radius;
for (var i = 0; i < slices.length; ++i)
{
if (slices[i].percent >= options.series.pie.label.threshold*100)
drawLabel(slices[i], currentAngle, i);
currentAngle += slices[i].angle;
}
function drawLabel(slice, startAngle, index)
{
if (slice.data[0][1]==0)
return;
// format label text
var lf = options.legend.labelFormatter, text, plf = options.series.pie.label.formatter;
if (lf)
text = lf(slice.label, slice);
else
text = slice.label;
if (plf)
text = plf(text, slice);
var halfAngle = ((startAngle+slice.angle) + startAngle)/2;
var x = centerLeft + Math.round(Math.cos(halfAngle) * radius);
var y = centerTop + Math.round(Math.sin(halfAngle) * radius) * options.series.pie.tilt;
var html = '<span class="pieLabel" id="pieLabel'+index+'" style="position:absolute;top:' + y + 'px;left:' + x + 'px;">' + text + "</span>";
target.append(html);
var label = target.children('#pieLabel'+index);
var labelTop = (y - label.height()/2);
var labelLeft = (x - label.width()/2);
label.css('top', labelTop);
label.css('left', labelLeft);
// check to make sure that the label is not outside the canvas
if (0-labelTop>0 || 0-labelLeft>0 || canvas.height-(labelTop+label.height())<0 || canvas.width-(labelLeft+label.width())<0)
redraw = true;
if (options.series.pie.label.background.opacity != 0) {
// put in the transparent background separately to avoid blended labels and label boxes
var c = options.series.pie.label.background.color;
if (c == null) {
c = slice.color;
}
var pos = 'top:'+labelTop+'px;left:'+labelLeft+'px;';
$('<div class="pieLabelBackground" style="position:absolute;width:' + label.width() + 'px;height:' + label.height() + 'px;' + pos +'background-color:' + c + ';"> </div>').insertBefore(label).css('opacity', options.series.pie.label.background.opacity);
}
} // end individual label function
} // end drawLabels function
} // end drawPie function
} // end draw function
// Placed here because it needs to be accessed from multiple locations
function drawDonutHole(layer)
{
// draw donut hole
if(options.series.pie.innerRadius > 0)
{
// subtract the center
layer.save();
innerRadius = options.series.pie.innerRadius > 1 ? options.series.pie.innerRadius : maxRadius * options.series.pie.innerRadius;
layer.globalCompositeOperation = 'destination-out'; // this does not work with excanvas, but it will fall back to using the stroke color
layer.beginPath();
layer.fillStyle = options.series.pie.stroke.color;
layer.arc(0,0,innerRadius,0,Math.PI*2,false);
layer.fill();
layer.closePath();
layer.restore();
// add inner stroke
layer.save();
layer.beginPath();
layer.strokeStyle = options.series.pie.stroke.color;
layer.arc(0,0,innerRadius,0,Math.PI*2,false);
layer.stroke();
layer.closePath();
layer.restore();
// TODO: add extra shadow inside hole (with a mask) if the pie is tilted.
}
}
//-- Additional Interactive related functions --
function isPointInPoly(poly, pt)
{
for(var c = false, i = -1, l = poly.length, j = l - 1; ++i < l; j = i)
((poly[i][1] <= pt[1] && pt[1] < poly[j][1]) || (poly[j][1] <= pt[1] && pt[1]< poly[i][1]))
&& (pt[0] < (poly[j][0] - poly[i][0]) * (pt[1] - poly[i][1]) / (poly[j][1] - poly[i][1]) + poly[i][0])
&& (c = !c);
return c;
}
function findNearbySlice(mouseX, mouseY)
{
var slices = plot.getData(),
options = plot.getOptions(),
radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius;
for (var i = 0; i < slices.length; ++i)
{
var s = slices[i];
if(s.pie.show)
{
ctx.save();
ctx.beginPath();
ctx.moveTo(0,0); // Center of the pie
//ctx.scale(1, options.series.pie.tilt); // this actually seems to break everything when here.
ctx.arc(0,0,radius,s.startAngle,s.startAngle+s.angle,false);
ctx.closePath();
x = mouseX-centerLeft;
y = mouseY-centerTop;
if(ctx.isPointInPath)
{
if (ctx.isPointInPath(mouseX-centerLeft, mouseY-centerTop))
{
//alert('found slice!');
ctx.restore();
return {datapoint: [s.percent, s.data], dataIndex: 0, series: s, seriesIndex: i};
}
}
else
{
// excanvas for IE doesn;t support isPointInPath, this is a workaround.
p1X = (radius * Math.cos(s.startAngle));
p1Y = (radius * Math.sin(s.startAngle));
p2X = (radius * Math.cos(s.startAngle+(s.angle/4)));
p2Y = (radius * Math.sin(s.startAngle+(s.angle/4)));
p3X = (radius * Math.cos(s.startAngle+(s.angle/2)));
p3Y = (radius * Math.sin(s.startAngle+(s.angle/2)));
p4X = (radius * Math.cos(s.startAngle+(s.angle/1.5)));
p4Y = (radius * Math.sin(s.startAngle+(s.angle/1.5)));
p5X = (radius * Math.cos(s.startAngle+s.angle));
p5Y = (radius * Math.sin(s.startAngle+s.angle));
arrPoly = [[0,0],[p1X,p1Y],[p2X,p2Y],[p3X,p3Y],[p4X,p4Y],[p5X,p5Y]];
arrPoint = [x,y];
// TODO: perhaps do some mathmatical trickery here with the Y-coordinate to compensate for pie tilt?
if(isPointInPoly(arrPoly, arrPoint))
{
ctx.restore();
return {datapoint: [s.percent, s.data], dataIndex: 0, series: s, seriesIndex: i};
}
}
ctx.restore();
}
}
return null;
}
function onMouseMove(e)
{
triggerClickHoverEvent('plothover', e);
}
function onClick(e)
{
triggerClickHoverEvent('plotclick', e);
}
// trigger click or hover event (they send the same parameters so we share their code)
function triggerClickHoverEvent(eventname, e)
{
var offset = plot.offset(),
canvasX = parseInt(e.pageX - offset.left),
canvasY = parseInt(e.pageY - offset.top),
item = findNearbySlice(canvasX, canvasY);
if (options.grid.autoHighlight)
{
// clear auto-highlights
for (var i = 0; i < highlights.length; ++i)
{
var h = highlights[i];
if (h.auto == eventname && !(item && h.series == item.series))
unhighlight(h.series);
}
}
// highlight the slice
if (item)
highlight(item.series, eventname);
// trigger any hover bind events
var pos = { pageX: e.pageX, pageY: e.pageY };
target.trigger(eventname, [ pos, item ]);
}
function highlight(s, auto)
{
if (typeof s == "number")
s = series[s];
var i = indexOfHighlight(s);
if (i == -1)
{
highlights.push({ series: s, auto: auto });
plot.triggerRedrawOverlay();
}
else if (!auto)
highlights[i].auto = false;
}
function unhighlight(s)
{
if (s == null)
{
highlights = [];
plot.triggerRedrawOverlay();
}
if (typeof s == "number")
s = series[s];
var i = indexOfHighlight(s);
if (i != -1)
{
highlights.splice(i, 1);
plot.triggerRedrawOverlay();
}
}
function indexOfHighlight(s)
{
for (var i = 0; i < highlights.length; ++i)
{
var h = highlights[i];
if (h.series == s)
return i;
}
return -1;
}
function drawOverlay(plot, octx)
{
//alert(options.series.pie.radius);
var options = plot.getOptions();
//alert(options.series.pie.radius);
var radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius;
octx.save();
octx.translate(centerLeft, centerTop);
octx.scale(1, options.series.pie.tilt);
for (i = 0; i < highlights.length; ++i)
drawHighlight(highlights[i].series);
drawDonutHole(octx);
octx.restore();
function drawHighlight(series)
{
if (series.angle < 0) return;
//octx.fillStyle = parseColor(options.series.pie.highlight.color).scale(null, null, null, options.series.pie.highlight.opacity).toString();
octx.fillStyle = "rgba(255, 255, 255, "+options.series.pie.highlight.opacity+")"; // this is temporary until we have access to parseColor
octx.beginPath();
if (Math.abs(series.angle - Math.PI*2) > 0.000000001)
octx.moveTo(0,0); // Center of the pie
octx.arc(0,0,radius,series.startAngle,series.startAngle+series.angle,false);
octx.closePath();
octx.fill();
}
}
} // end init (plugin body)
// define pie specific options and their default values
var options = {
series: {
pie: {
show: false,
radius: 'auto', // actual radius of the visible pie (based on full calculated radius if <=1, or hard pixel value)
innerRadius:0, /* for donut */
startAngle: 3/2,
tilt: 1,
offset: {
top: 0,
left: 'auto'
},
stroke: {
color: '#FFF',
width: 1
},
label: {
show: 'auto',
formatter: function(label, slice){
return '<div style="font-size:x-small;text-align:center;padding:2px;color:'+slice.color+';">'+label+'<br/>'+Math.round(slice.percent)+'%</div>';
}, // formatter function
radius: 1, // radius at which to place the labels (based on full calculated radius if <=1, or hard pixel value)
background: {
color: null,
opacity: 0
},
threshold: 0 // percentage at which to hide the label (i.e. the slice is too narrow)
},
combine: {
threshold: -1, // percentage at which to combine little slices into one larger slice
color: null, // color to give the new slice (auto-generated if null)
label: 'Other' // label to give the new slice
},
highlight: {
//color: '#FFF', // will add this functionality once parseColor is available
opacity: 0.5
}
}
}
};
$.plot.plugins.push({
init: init,
options: options,
name: "pie",
version: "1.0"
});
})(jQuery);
| JavaScript |
/*
Flot plugin for plotting images, e.g. useful for putting ticks on a
prerendered complex visualization.
The data syntax is [[image, x1, y1, x2, y2], ...] where (x1, y1) and
(x2, y2) are where you intend the two opposite corners of the image to
end up in the plot. Image must be a fully loaded Javascript image (you
can make one with new Image()). If the image is not complete, it's
skipped when plotting.
There are two helpers included for retrieving images. The easiest work
the way that you put in URLs instead of images in the data (like
["myimage.png", 0, 0, 10, 10]), then call $.plot.image.loadData(data,
options, callback) where data and options are the same as you pass in
to $.plot. This loads the images, replaces the URLs in the data with
the corresponding images and calls "callback" when all images are
loaded (or failed loading). In the callback, you can then call $.plot
with the data set. See the included example.
A more low-level helper, $.plot.image.load(urls, callback) is also
included. Given a list of URLs, it calls callback with an object
mapping from URL to Image object when all images are loaded or have
failed loading.
Options for the plugin are
series: {
images: {
show: boolean
anchor: "corner" or "center"
alpha: [0,1]
}
}
which can be specified for a specific series
$.plot($("#placeholder"), [{ data: [ ... ], images: { ... } ])
Note that because the data format is different from usual data points,
you can't use images with anything else in a specific data series.
Setting "anchor" to "center" causes the pixels in the image to be
anchored at the corner pixel centers inside of at the pixel corners,
effectively letting half a pixel stick out to each side in the plot.
A possible future direction could be support for tiling for large
images (like Google Maps).
*/
(function ($) {
var options = {
series: {
images: {
show: false,
alpha: 1,
anchor: "corner" // or "center"
}
}
};
$.plot.image = {};
$.plot.image.loadDataImages = function (series, options, callback) {
var urls = [], points = [];
var defaultShow = options.series.images.show;
$.each(series, function (i, s) {
if (!(defaultShow || s.images.show))
return;
if (s.data)
s = s.data;
$.each(s, function (i, p) {
if (typeof p[0] == "string") {
urls.push(p[0]);
points.push(p);
}
});
});
$.plot.image.load(urls, function (loadedImages) {
$.each(points, function (i, p) {
var url = p[0];
if (loadedImages[url])
p[0] = loadedImages[url];
});
callback();
});
}
$.plot.image.load = function (urls, callback) {
var missing = urls.length, loaded = {};
if (missing == 0)
callback({});
$.each(urls, function (i, url) {
var handler = function () {
--missing;
loaded[url] = this;
if (missing == 0)
callback(loaded);
};
$('<img />').load(handler).error(handler).attr('src', url);
});
}
function drawSeries(plot, ctx, series) {
var plotOffset = plot.getPlotOffset();
if (!series.images || !series.images.show)
return;
var points = series.datapoints.points,
ps = series.datapoints.pointsize;
for (var i = 0; i < points.length; i += ps) {
var img = points[i],
x1 = points[i + 1], y1 = points[i + 2],
x2 = points[i + 3], y2 = points[i + 4],
xaxis = series.xaxis, yaxis = series.yaxis,
tmp;
// actually we should check img.complete, but it
// appears to be a somewhat unreliable indicator in
// IE6 (false even after load event)
if (!img || img.width <= 0 || img.height <= 0)
continue;
if (x1 > x2) {
tmp = x2;
x2 = x1;
x1 = tmp;
}
if (y1 > y2) {
tmp = y2;
y2 = y1;
y1 = tmp;
}
// if the anchor is at the center of the pixel, expand the
// image by 1/2 pixel in each direction
if (series.images.anchor == "center") {
tmp = 0.5 * (x2-x1) / (img.width - 1);
x1 -= tmp;
x2 += tmp;
tmp = 0.5 * (y2-y1) / (img.height - 1);
y1 -= tmp;
y2 += tmp;
}
// clip
if (x1 == x2 || y1 == y2 ||
x1 >= xaxis.max || x2 <= xaxis.min ||
y1 >= yaxis.max || y2 <= yaxis.min)
continue;
var sx1 = 0, sy1 = 0, sx2 = img.width, sy2 = img.height;
if (x1 < xaxis.min) {
sx1 += (sx2 - sx1) * (xaxis.min - x1) / (x2 - x1);
x1 = xaxis.min;
}
if (x2 > xaxis.max) {
sx2 += (sx2 - sx1) * (xaxis.max - x2) / (x2 - x1);
x2 = xaxis.max;
}
if (y1 < yaxis.min) {
sy2 += (sy1 - sy2) * (yaxis.min - y1) / (y2 - y1);
y1 = yaxis.min;
}
if (y2 > yaxis.max) {
sy1 += (sy1 - sy2) * (yaxis.max - y2) / (y2 - y1);
y2 = yaxis.max;
}
x1 = xaxis.p2c(x1);
x2 = xaxis.p2c(x2);
y1 = yaxis.p2c(y1);
y2 = yaxis.p2c(y2);
// the transformation may have swapped us
if (x1 > x2) {
tmp = x2;
x2 = x1;
x1 = tmp;
}
if (y1 > y2) {
tmp = y2;
y2 = y1;
y1 = tmp;
}
tmp = ctx.globalAlpha;
ctx.globalAlpha *= series.images.alpha;
ctx.drawImage(img,
sx1, sy1, sx2 - sx1, sy2 - sy1,
x1 + plotOffset.left, y1 + plotOffset.top,
x2 - x1, y2 - y1);
ctx.globalAlpha = tmp;
}
}
function processRawData(plot, series, data, datapoints) {
if (!series.images.show)
return;
// format is Image, x1, y1, x2, y2 (opposite corners)
datapoints.format = [
{ required: true },
{ x: true, number: true, required: true },
{ y: true, number: true, required: true },
{ x: true, number: true, required: true },
{ y: true, number: true, required: true }
];
}
function init(plot) {
plot.hooks.processRawData.push(processRawData);
plot.hooks.drawSeries.push(drawSeries);
}
$.plot.plugins.push({
init: init,
options: options,
name: 'image',
version: '1.1'
});
})(jQuery);
| JavaScript |
// Copyright 2010 htmldrive.net Inc.
/**
* @projectHomepage http://www.htmldrive.net/go/to/simple-images-scroller
* @projectDescription Simple images scroller with jquery plugin
* @author htmldrive.net
* More script and css style : htmldrive.net
* @version 1.0
* @license http://www.apache.org/licenses/LICENSE-2.0
*/
(function(a){
a.fn.scroller_roll=function(p){
var p=p||{};
var g=p&&p.time_interval?p.time_interval:"100";
var h=p&&p.title_show?p.title_show:"enable";
var i=p&&p.window_background_color?p.window_background_color:"white";
var j=p&&p.window_padding?p.window_padding:"5";
var k=p&&p.border_size?p.border_size:"1";
var l=p&&p.border_color?p.border_color:"black";
var m=p&&p.images_width?p.images_width:"45";
var n=p&&p.images_height?p.images_height:"70";
var o=p&&p.title_size?p.title_size:"12";
var q=p&&p.title_color?p.title_color:"blue";
var r=p&&p.show_count?p.show_count:"5";
var i_m = p&&p.images_margin?p.images_margin:"3";
j += "px";
k += "px";
m += "px";
n += "px";
o += "px";
var s;
var t=0;
var u;
var v;
var w;
var x;
var y=a(this);
var z=y.children("ul").children("li").length;
var A=Math.ceil(z/r);
if(y.find("ul").length==0||a("li").length==0){
dom.append("Require content");
return null
}
y.children("ul").children("li").children("a").children("img").css("width",m).css("height",n);
if(h=='enable'){
y.children("ul").children("li").children("a").each(function(){
$(this).append('<br/>'+$(this).attr("title"))
})
}
s_s_ul(y,j,k,l,i);
m=parseInt(m);
y.children("ul").children("li").css("width",m+"px");
y.children("ul").children("li").css("margin-left",i_m+"px");
y.children("ul").children("li").children("a").css("color",q);
y.children("ul").children("li").children("a").css("font-size",o);
y.hover(function(){
stop()
},function(){
play()
});
begin();
play();
function begin(){
x=y.children("ul").width();
y.children("ul").children("li").hide();
y.children("ul").children("li").slice(0,r).show();
u=y.children("ul").outerWidth();
v=y.children("ul").outerHeight();
y.children("ul").width(x);
y.width(u);
y.height(v);
y.children("ul").children("li").show();
y.css("position","relative");
y.children("ul").css("position","absolute");
y.children("ul").clone().prependTo(y);
j=parseInt(j);
y.children("ul").css("left","0px");
y.find("ul:last").css("left",x);
w=x-i_m;
}
function play(){
if(parseInt(y.find("ul").eq(t).css("left"))<=-(x)){
var a=x;
y.find("ul").eq(t).css("left",a);
if(t==0){
t=1
}else{
t=0
}
}
y.find("ul").each(function(){
$(this).css("left",(parseInt($(this).css("left"))-1)+"px")
});
s=setTimeout(play,g)
}
function stop(){
clearTimeout(s)
}
function s_s_ul(a,b,c,d,e){
b=parseInt(b);
c=parseInt(c);
var f="border: "+d+" solid "+" "+c+"px; padding:"+b+"px; background-color:"+e;
a.attr("style",f)
}
}
})(jQuery); | JavaScript |
switch(mod){
case "penduduk":
$('#tahun').numberbox({
min:0
});
$('#jumlah_penduduk').numberbox({
min:0,
groupSeparator:','
});
$('#jumlah_pencari_kerja').numberbox({
min:0,
groupSeparator:','
});
break;
case "headline":
break;
case "potensi":
$('#tahun').numberbox({
min:0
});
$('#jumlah').numberbox({
min:0,
groupSeparator:','
});
break;
case "pdrb":
$('#tahun').numberbox({
min:0
});
$('#pmdn').numberbox({
min:0,
groupSeparator:','
});
$('#pma').numberbox({
min:0,
groupSeparator:','
});
$('#pdrb').numberbox({
min:0,
groupSeparator:','
});
break;
case "ekonomi":
$('#tahun').numberbox({
min:0
});
$('#pendatan_kapita').numberbox({
min:0,
groupSeparator:','
});
$('#pdrb').numberbox({
min:0,
groupSeparator:','
});
$('#inflasi').numberbox({
min:0,
groupSeparator:','
});
break;
case "berita":
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
//$('#tool_vr').css('width',frmWidth-20)
if(dd<10){dd='0'+dd}
if(mm<10){mm='0'+mm}
today = yyyy+'-'+mm+'-'+dd;
val_date = today;
console.log(today);
$('#tanggal').datebox({
required: true,
formatter: formatDate }
);
$('#tanggal').datebox('setValue',today);
break;
}
$('#simpan').die();
$('#simpan').live('click',function(){
load_na('show');
if(mod=='headline' || mod=='berita' ){
tinyMCE.get("isi").save();
}
submitform1('form_'+mod,function(r){
if(r==1){
$.messager.alert("Sukses","Data Tersimpan",'info');
load_na('hide');
$(tabel).datagrid('reload');
if(mod!='berita'){
window_na_close();
}else{
$('#data_na').css('display','inline');$('#form_na').css('display','none');
}
}
else{
console.log(r);
$.messager.alert("Sukses","Data Gagal Disimpan",'error');
load_na('hide');
}
});
});
$('#batal').die();
$('#batal').live('click',function(){
if(mod!='berita'){
window_na_close();
}else{
//$('#data_na').css('display','inline');$('#form_na').css('display','none');
loadUrl(this,'adminpanel/getdisplay/get_formna/berita','Manajemen Konten BeritaBerita');
}
});
| JavaScript |
function msglogin() {
$.msgBox({
title: "Warning",
content: "Silahkan login terlebih dahulu.",
type: "warn",
buttons: [{ value: "Ok" }],
success: function (result) {
$("#username").focus();
}
});
}
tinyMCE.init({
// General options
mode : "textareas",
editor_selector : "thread_content",
theme : "modern",
skin : "lightgray",
skin_variant : "red",
plugins : "autolink,lists,pagebreak,layer,table,save,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,template,autosave",
//plugins : "advlist,anchor,autolink,autoresize,autosave,bbcode,charmap,code,compat3x,contextmenu,directionality,emoticons,example,example_dependency,fullpage,fullscreen,hr,image,importcss,insertdatetime,layer,legacyoutput,link,lists,media,nonbreaking,noneditable,pagebreak,paste,preview,print,save,searchreplace,spellchecker,tabfocus,table,template,textcolor,visualblocks,visualchars,wordcount",
// Theme options
theme_advanced_buttons1 : "fullscreen,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,formatselect,fontselect,fontsizeselect",
theme_advanced_buttons2 : "bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,image,code,|,forecolor,backcolor",
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "left",
theme_advanced_statusbar_location : "bottom",
theme_advanced_resizing: true,
theme_advanced_resizing_use_cookie : false,
// Example content CSS (should be your site CSS)
content_css : "tinymce/css/content.css",
// Drop lists for link/image/media/template dialogs
template_external_list_url : "tinymce/lists/template_list.js",
external_link_list_url : "tinymce/lists/link_list.js",
external_image_list_url : "tinymce/lists/image_list.js",
media_external_list_url : "tinymce/lists/media_list.js",
convert_urls: false,
}); | JavaScript |
var kolom ={};
var kolomkaku={};
var tabel = "#grid_"+mod;
switch(mod){
case "penduduk":
kolom[mod]=[
{field:'ck', checkbox:true},
{field:'tahun',title:'Tahun',width:150},
{field:'jml_penduduk',title:'Jml. Penduduk',width:250,align:'right'},
{field:'jumlah_pencari_kerja',title:'Jml. Pencari Kerja',width:200,align:'right'},
];
judul="Data Kependudukan";
break;
case "headline":
kolom[mod]=[
{field:'ck', checkbox:true},
{field:'judul',title:'Judul',width:150},
{field:'isi',title:'Isi Headline',width:550,align:'left'},
];
judul="Data Headline";
break;
case "potensi":
kolom[mod]=[
{field:'ck', checkbox:true},
{field:'komoditi',title:'Komoditi',width:450},
{field:'tahun',title:'Tahun',width:100,align:'center'},
{field:'jumlah',title:'Jumlah',width:100,align:'right'},
{field:'satuan',title:'Satuan',width:100,align:'center'},
];
judul="Data Potensi";
break;
case "pdrb":
kolom[mod]=[
{field:'ck', checkbox:true},
{field:'tahun',title:'Tahun',width:100,align:'center'},
{field:'pmdn',title:'PMDN',width:100,align:'right'},
{field:'satuan_pmdn',title:'Satuan',width:100,align:'center'},
{field:'pma',title:'PMA',width:100,align:'right'},
{field:'satuan_pma',title:'Satuan',width:100,align:'center'},
{field:'pdrb',title:'PDRB',width:100,align:'right'},
{field:'satuan_pdrb',title:'Satuan',width:100,align:'center'},
];
judul="Data PDRB";
break;
case "ekonomi":
kolom[mod]=[
{field:'ck', checkbox:true},
{field:'tahun',title:'Tahun',width:100,align:'center'},
{field:'pdrb',title:'PDRB',width:100,align:'right'},
{field:'satuan_pdrb',title:'Satuan',width:100,align:'center'},
{field:'pendatan_kapita',title:'Pendapatan PerKapita',width:150,align:'right'},
{field:'satuan_pendapatan',title:'Satuan',width:100,align:'center'},
{field:'inflasi',title:'Inflasi (%)',width:100,align:'right'},
];
judul="Data Pertumbuhan Ekonomi";
break;
}
$(tabel).datagrid({
title:judul,
height:frmHeight-200,
width:frmWidth-300,
iconCls: 'table',
rownumbers:true,
// fit:true,
striped:true,
pagination:true,
sortable:true,
url:host+"adminpanel/get_data/"+mod,
// fit:true,
nowrap: false,
singleSelect:true,
frozenColumns:[
kolomkaku[mod]
],
columns:[
kolom[mod]
],
toolbar:[
{
text:'Tambah',
iconCls:'add',
handler:function(){
cek_grid('add');
},
disabled:(mod=='headline' ? true : false)
},'-',
{
text:'Edit',
iconCls:'edit',
handler:function(){
cek_grid('edit');
}
},'-',
{
text:'Hapus',
iconCls:'remove',
handler:function(){
cek_grid('delete');
}
}
],
});
function cek_grid(tbl){
var w,h,t;
var row = $(tabel).datagrid('getSelected');
switch(mod){
case "penduduk":
w=frmWidth-800;
h=frmHeight-280;
t="Form Data Kependudukan";
break;
case "headline":
w=frmWidth-600;
h=frmHeight-150;
t="Form Data Headline";
break;
case "potensi":
t="Form Data Potensi";
break;
case "pdrb":
w=frmWidth-800;
h=frmHeight-150;
t="Form Data PDRB";
break;
case "ekonomi":
w=frmWidth-800;
h=frmHeight-150;
t="Form Data Pertumbuhan Ekonomi";
break;
}
if(tbl!='add'){
if(row){
if(tbl=='delete'){
$.messager.confirm('Confirm','Yakin Data Ini Akan Dihapus ?',function(r){
if (r==true){
$.post(host+'adminpanel/hapus/'+mod,{id:row.id,},function(resp){
if(resp==1){$.messager.alert("Data","Data Sudah Terhapus",'info');$(tabel).datagrid('reload');}
});
}
});
}
else{
$.post(host+'adminpanel/get_formna/'+mod,{sts:'edit',id:row.id},function(r){
window_na(r,t,w,h);
tinyMCE.init({
selector : "textarea",
plugins : "pagebreak,table,code,save,insertdatetime,preview,media,searchreplace,contextmenu,paste,directionality,image",
});
});
}
}
else{$.messager.alert("Data","Pilih Salah Satu Data",'error');}
}
else{
$.post(host+'adminpanel/get_formna/'+mod,{sts:'add'},function(r){
window_na(r,t,w,h);
});
}
} | JavaScript |
// Copyright 2010 htmldrive.net Inc.
/**
* @projectHomepage http://www.htmldrive.net/welcome/amazon-scroller
* @projectDescription Amazon style image and title scroller
* @author htmldrive.net
* More script and css style : htmldrive.net
* @version 1.0
* @license http://www.apache.org/licenses/LICENSE-2.0
*/
(function(a){
a.fn.amazon_scroller=function(p){
var p=p||{};
var g=p&&p.scroller_time_interval?p.scroller_time_interval:"3000";
var h=p&&p.scroller_title_show?p.scroller_title_show:"enable";
var i=p&&p.scroller_window_background_color?p.scroller_window_background_color:"white";
var j=p&&p.scroller_window_padding?p.scroller_window_padding:"0";
var k=p&&p.scroller_border_size?p.scroller_border_size:"1";
var l=p&&p.scroller_border_color?p.scroller_border_color:"black";
var m=p&&p.scroller_images_width?p.scroller_images_width:"70";
var n=p&&p.scroller_images_height?p.scroller_images_height:"50";
var o=p&&p.scroller_title_size?p.scroller_title_size:"12";
var q=p&&p.scroller_title_color?p.scroller_title_color:"blue";
var r=p&&p.scroller_show_count?p.scroller_show_count:"3";
var d=p&&p.directory?p.directory:"images";
j += "px";
k += "px";
m += "px";
n += "px";
o += "px";
var dom=a(this);
var s;
var t=0;
var u;
var v;
var w=dom.find("ul:first").children("li").length;
var x=Math.ceil(w/r);
if(dom.find("ul").length==0||dom.find("li").length==0){
dom.append("Require content");
return null
}
dom.find("ul:first").children("li").children("a").children("img").css("width",m).css("height",n);
if(h=='enable'){
dom.find("ul:first").children("li").children("a").each(function(){
$(this).append('<div class="amazon_scroller_title">'+$(this).attr("title")+'</div>')
})
dom.find("ul:first").children("li").css("height",n+o+"px");
}else{
dom.find("ul:first").children("li").css("height",n+"px");
}
dom.find(".amazon_scroller_title").height(parseInt(o)+"px");
s_s_ul(dom,j,k,l,i);
s_s_nav(dom.find(".amazon_scroller_nav"),d);
m=parseInt(m);
dom.find("ul:first").children("li").css("width",m+"px");
n=parseInt(n);
dom.find("ul:first").children("li").children("a").css("color",q);
dom.find("ul:first").children("li").children("a").css("font-size",o);
begin();
s=setTimeout(play,g);
dom.find(".amazon_scroller_nav").children("li").hover(
function(){
if($(this).parent().children().index($(this))==0){
$(this).css("background-position","left -50px");
}else if($(this).parent().children().index($(this))==1){
$(this).css("background-position","right -50px");
}
},
function(){
if($(this).parent().children().index($(this))==0){
$(this).css("background-position","left top");
}else if($(this).parent().children().index($(this))==1){
$(this).css("background-position","right top");
}
}
);
dom.find(".amazon_scroller_nav").children("li").click(function(){
if($(this).parent().children().index($(this))==0){
previous()
}else if($(this).parent().children().index($(this))==1){
next()
}
});
dom.hover(
function(){
clearTimeout(s);
},
function(){
s=setTimeout(play,g);
}
);
function begin(){
var a=dom.find("ul:first").children("li").outerWidth(true)*w;
dom.find("ul:first").children("li").hide();
dom.find("ul:first").children("li").slice(0,r).show();
u=dom.find("ul:first").outerWidth();
v=dom.find("ul:first").outerHeight();
dom.find("ul:first").width(a);
dom.width(u+60);
dom.height(v);
dom.children(".amazon_scroller_mask").width(u);
dom.children(".amazon_scroller_mask").height(v);
dom.find("ul:first").children("li").show();
dom.css("position","relative");
dom.find("ul:first").css("position","absolute");
dom.children(".amazon_scroller_mask").width(u);
dom.children(".amazon_scroller_mask").height(v);
dom.find(".amazon_scroller_nav").css('top',(v-50)/2+parseInt(j)+"px");
dom.find(".amazon_scroller_nav").width(u+60)
dom.find("ul:first").clone().appendTo(dom.children(".amazon_scroller_mask"));
dom.children(".amazon_scroller_mask").find("ul:last").css("left",a);
}
function previous(){
clearTimeout(s);
if(t > 0){
t--;
dom.children(".amazon_scroller_mask").find("ul").animate({
left: '+='+(m+10)
},500);
}
}
function next(){
play();
}
function play(){
clearTimeout(s);
t++;
var a = dom.find("ul:first").children("li").outerWidth(true)*w;
if(t >= w+1){
t = 0;
dom.children(".amazon_scroller_mask").find("ul:first").css("left","0px");
dom.children(".amazon_scroller_mask").find("ul:last").css("left",a);
s=setTimeout(play,0);
}else{
dom.children(".amazon_scroller_mask").find("ul").animate({
left: '-='+(m+10)
},500);
s=setTimeout(play,g);
}
}
function s_s_ul(a,b,c,d,e){
b=parseInt(b);
c=parseInt(c);
var f="border: "+d+" solid "+" "+c+"px; padding:"+b+"px; background-color:"+e;
a.attr("style",f)
}
function s_s_nav(a,d){
var b=a.children("li:first");
var c=a.children("li:last");
a.children("li").css("width","18px");
a.children("li").css("height","50px");
a.children("li").css('background-image','url("'+d+'/arrow.gif")');
c.css('background-position','right top');
a.children("li").css('background-repeat','no-repeat');
c.css('right','0px');
b.css('left','0px');
}
}
})(jQuery); | JavaScript |
var frmHeight=getClientHeight();
var frmWidth=getClientWidth();
function getClientHeight(){
var theHeight;
if (window.innerHeight) {
theHeight=window.innerHeight;
}
else if (document.documentElement && document.documentElement.clientHeight) {
theHeight=document.documentElement.clientHeight;
}
else if (document.body) {
theHeight=document.body.clientHeight;
}
return theHeight;
}
function getClientWidth(){
var theWidth;
if (window.innerWidth)
theWidth=window.innerWidth;
else if (document.documentElement && document.documentElement.clientWidth)
theWidth=document.documentElement.clientWidth;
else if (document.body)
theWidth=document.body.clientWidth;
return theWidth;
}
function loadUrl(obj,url,judul,desc){
var urls=host+url;
//$.blockUI({ css: {backgroundColor: '#DF4E49', color: '#fff'}, message: '<h3> <img src="'+host+'assets/images/loading-oi.gif" /> Harap Tunggu...</h3>', baseZ: 10000 });
$("#page").html("").addClass("loading");
$.post(urls,function (html){
$("#page").html(html).removeClass("loading");
$('#judul_na').html(judul);
//$.unblockUI();
//$('.blockUI').css('display','none')
});
}
function blokuinya(parcok){
/*if(parcok == 'add'){
$.blockUI({ css: {backgroundColor: '#DF4E49', color: '#fff'}, message: '<h3> <img src="'+host+'assets/images/loading-oi.gif" /> Harap Tunggu...</h3>', baseZ: 10000 });
}else{
$.unblockUI();
}*/
}
function submitform1(frm,func){
var url = $('#'+frm).attr("action");
/*$.blockUI({ css: {backgroundColor: '#DF4E49', color: '#fff'}, message: '<h3> <img src="'+host+'assets/images/loading-oi.gif" /> Harap Tunggu...</h3>', baseZ: 10000 });*/
$('#'+frm).form('submit',{
url:url,
onSubmit: function(){
return $(this).form('validate');
},
success:function(data){
if (func == undefined ){
if (data == "1"){
alert('Data Sudah Disimpan ');
//$.unblockUI();
}else{
alert('Data Gagal Tersimpan');
// $.unblockUI();
}
}else{
func(data);
//$.unblockUI();
}
},
error:function(data){
if (func == undefined ){
alert('Data Gagal Tersimpan');
//$.unblockUI();
}else{
func(data);
//$.unblockUI();
}
}
});
}
function submitform(frm,func){
var url = $('#'+frm).attr("action");
var a=$('#'+frm).serialize();
$.ajax({
type:'post',
url:url,
data:a,
beforeSend:function(){
//launchpreloader();
},
complete:function(){
// stopPreloader();
},
success:function(data){
if (func == undefined ){
if (data == "1"){
pesan('Data Saved ','Success');
}else{
pesan(data,'Result');
}
}else{
func(data);
}
},
error:function(data){
if (func == undefined ){
pesan(data,'Error');
}else{
func(data);
}
}
});
}
function bar_chart(id,data,xseries,formatnya,tickser,judul,colors,xjudul,yjudul){
//alert(formatnya);
plot1 = $.jqplot(id, [data], {
animate: true,
// Will animate plot on calls to plot1.replot({resetAxes:true})
animateReplot: true,
title: (judul == undefined ? "" : judul),
seriesColors : colors,
series: [{renderer:$.jqplot.BarRenderer,pointLabels: {show: true}}],
axesDefaults: {
tickRenderer: $.jqplot.CanvasAxisTickRenderer
},
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: tickser,
label:(xjudul == undefined ? "" : xjudul)
},
yaxis: {
tickOptions: {
formatString: (formatnya == undefined ? "%'d" : formatnya)
},
rendererOptions: {
forceTickAt0: true
},
labelRenderer: $.jqplot.CanvasAxisLabelRenderer,
label:(yjudul == undefined ? "" : yjudul)
},
},
});
}
function chart_na(id_selector,type,title,subtitle,title_y,data_x,data_y,satuan){
$('#'+id_selector).highcharts({
chart: {
type: type
},
title: {
text: title
},
subtitle: {
text: subtitle
},
xAxis: {
categories: data_x
},
yAxis: {
min: 0,
title: {
text: title_y
}
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.1f} '+satuan+'</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: data_y
});
}
function windowLoading(html,judul,width,height){
divcontainerz = "win"+Math.floor(Math.random()*9999);
$("<div id="+divcontainerz+"></div>").appendTo("body");
divcontainerz = "#"+divcontainerz;
$(divcontainerz).html(html);
$(divcontainerz).css('padding','5px');
$(divcontainerz).window({
title:judul,
width:width,
height:height,
autoOpen:false,
modal:true,
maximizable:false,
resizable:false,
minimizable:false,
closable:false,
collapsible:false
});
$(divcontainerz).window('open');
}
function winLoadingClose(){
$(divcontainerz).window('close');
//$(divcontainer).html('');
}
function loadingna(){
windowLoading("<img src='"+host+"assets/images/loading.gif' style='position: fixed;top: 50%;left: 50%;margin-top: -10px;margin-left: -25px;'/>","Please Wait",200,100);
}
var container3;
function window_na(html,judul,width,height){
container3 = "win"+Math.floor(Math.random()*9999);
$("<div id="+container3+"></div>").appendTo("body");
container3 = "#"+container3;
$(container3).html(html);
$(container3).css('padding','5px');
$(container3).window({
title:judul,
width:width,
height:height,
autoOpen:false,
maximizable:false,
minimizable: false,
collapsible: false,
resizable: false,
closable:true,
modal:true,
onBeforeClose:function(){
$(container3).window("close",true);
//$(container3).window("destroy",true);
}
});
$(container3).window('open');
}
function window_na_close(){
$(container3).html('');
$(container3).window('close');
//$(container3).window("destroy",true);
}
function load_na(sts){
if(sts=='show') $('#loading-status').show();
else $('#loading-status').hide();
}
function formatDate(date) {
var bulan=date.getMonth() +1;
var tgl=date.getDate();
if(bulan < 10){
bulan='0'+bulan;
}
if(tgl < 10){
tgl='0'+tgl;
}
return date.getFullYear() + "-" + bulan + "-" + tgl;
}
| JavaScript |
/*!
* jQuery Form Plugin
* version: 3.45.0-2013.10.17
* Requires jQuery v1.5 or later
* Copyright (c) 2013 M. Alsup
* Examples and documentation at: http://malsup.com/jquery/form/
* Project repository: https://github.com/malsup/form
* Dual licensed under the MIT and GPL licenses.
* https://github.com/malsup/form#copyright-and-license
*/
/*global ActiveXObject */
;(function($) {
"use strict";
/*
Usage Note:
-----------
Do not use both ajaxSubmit and ajaxForm on the same form. These
functions are mutually exclusive. Use ajaxSubmit if you want
to bind your own submit handler to the form. For example,
$(document).ready(function() {
$('#myForm').on('submit', function(e) {
e.preventDefault(); // <-- important
$(this).ajaxSubmit({
target: '#output'
});
});
});
Use ajaxForm when you want the plugin to manage all the event binding
for you. For example,
$(document).ready(function() {
$('#myForm').ajaxForm({
target: '#output'
});
});
You can also use ajaxForm with delegation (requires jQuery v1.7+), so the
form does not have to exist when you invoke ajaxForm:
$('#myForm').ajaxForm({
delegation: true,
target: '#output'
});
When using ajaxForm, the ajaxSubmit function will be invoked for you
at the appropriate time.
*/
/**
* Feature detection
*/
var feature = {};
feature.fileapi = $("<input type='file'/>").get(0).files !== undefined;
feature.formdata = window.FormData !== undefined;
var hasProp = !!$.fn.prop;
// attr2 uses prop when it can but checks the return type for
// an expected string. this accounts for the case where a form
// contains inputs with names like "action" or "method"; in those
// cases "prop" returns the element
$.fn.attr2 = function() {
if ( ! hasProp )
return this.attr.apply(this, arguments);
var val = this.prop.apply(this, arguments);
if ( ( val && val.jquery ) || typeof val === 'string' )
return val;
return this.attr.apply(this, arguments);
};
/**
* ajaxSubmit() provides a mechanism for immediately submitting
* an HTML form using AJAX.
*/
$.fn.ajaxSubmit = function(options) {
/*jshint scripturl:true */
// fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
if (!this.length) {
log('ajaxSubmit: skipping submit process - no element selected');
return this;
}
var method, action, url, $form = this;
if (typeof options == 'function') {
options = { success: options };
}
else if ( options === undefined ) {
options = {};
}
method = options.type || this.attr2('method');
action = options.url || this.attr2('action');
url = (typeof action === 'string') ? $.trim(action) : '';
url = url || window.location.href || '';
if (url) {
// clean url (don't include hash vaue)
url = (url.match(/^([^#]+)/)||[])[1];
}
options = $.extend(true, {
url: url,
success: $.ajaxSettings.success,
type: method || $.ajaxSettings.type,
iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank'
}, options);
// hook for manipulating the form data before it is extracted;
// convenient for use with rich editors like tinyMCE or FCKEditor
var veto = {};
this.trigger('form-pre-serialize', [this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
return this;
}
// provide opportunity to alter form data before it is serialized
if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSerialize callback');
return this;
}
var traditional = options.traditional;
if ( traditional === undefined ) {
traditional = $.ajaxSettings.traditional;
}
var elements = [];
var qx, a = this.formToArray(options.semantic, elements);
if (options.data) {
options.extraData = options.data;
qx = $.param(options.data, traditional);
}
// give pre-submit callback an opportunity to abort the submit
if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSubmit callback');
return this;
}
// fire vetoable 'validate' event
this.trigger('form-submit-validate', [a, this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
return this;
}
var q = $.param(a, traditional);
if (qx) {
q = ( q ? (q + '&' + qx) : qx );
}
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 callbacks = [];
if (options.resetForm) {
callbacks.push(function() { $form.resetForm(); });
}
if (options.clearForm) {
callbacks.push(function() { $form.clearForm(options.includeHidden); });
}
// 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) {
var fn = options.replaceTarget ? 'replaceWith' : 'html';
$(options.target)[fn](data).each(oldSuccess, arguments);
});
}
else if (options.success) {
callbacks.push(options.success);
}
options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg
var context = options.context || this ; // jQuery 1.4+ supports scope context
for (var i=0, max=callbacks.length; i < max; i++) {
callbacks[i].apply(context, [data, status, xhr || $form, $form]);
}
};
if (options.error) {
var oldError = options.error;
options.error = function(xhr, status, error) {
var context = options.context || this;
oldError.apply(context, [xhr, status, error, $form]);
};
}
if (options.complete) {
var oldComplete = options.complete;
options.complete = function(xhr, status) {
var context = options.context || this;
oldComplete.apply(context, [xhr, status, $form]);
};
}
// are there files to upload?
// [value] (issue #113), also see comment:
// https://github.com/malsup/form/commit/588306aedba1de01388032d5f42a60159eea9228#commitcomment-2180219
var fileInputs = $('input[type=file]:enabled', this).filter(function() { return $(this).val() !== ''; });
var hasFileInputs = fileInputs.length > 0;
var mp = 'multipart/form-data';
var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp);
var fileAPI = feature.fileapi && feature.formdata;
log("fileAPI :" + fileAPI);
var shouldUseFrame = (hasFileInputs || multipart) && !fileAPI;
var jqxhr;
// options.iframe allows user to force iframe mode
// 06-NOV-09: now defaulting to iframe mode if file input is detected
if (options.iframe !== false && (options.iframe || shouldUseFrame)) {
// hack to fix Safari hang (thanks to Tim Molendijk for this)
// see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
if (options.closeKeepAlive) {
$.get(options.closeKeepAlive, function() {
jqxhr = fileUploadIframe(a);
});
}
else {
jqxhr = fileUploadIframe(a);
}
}
else if ((hasFileInputs || multipart) && fileAPI) {
jqxhr = fileUploadXhr(a);
}
else {
jqxhr = $.ajax(options);
}
$form.removeData('jqxhr').data('jqxhr', jqxhr);
// clear element array
for (var k=0; k < elements.length; k++)
elements[k] = null;
// fire 'notify' event
this.trigger('form-submit-notify', [this, options]);
return this;
// utility fn for deep serialization
function deepSerialize(extraData){
var serialized = $.param(extraData, options.traditional).split('&');
var len = serialized.length;
var result = [];
var i, part;
for (i=0; i < len; i++) {
// #252; undo param space replacement
serialized[i] = serialized[i].replace(/\+/g,' ');
part = serialized[i].split('=');
// #278; use array instead of object storage, favoring array serializations
result.push([decodeURIComponent(part[0]), decodeURIComponent(part[1])]);
}
return result;
}
// XMLHttpRequest Level 2 file uploads (big hat tip to francois2metz)
function fileUploadXhr(a) {
var formdata = new FormData();
for (var i=0; i < a.length; i++) {
formdata.append(a[i].name, a[i].value);
}
if (options.extraData) {
var serializedData = deepSerialize(options.extraData);
for (i=0; i < serializedData.length; i++)
if (serializedData[i])
formdata.append(serializedData[i][0], serializedData[i][1]);
}
options.data = null;
var s = $.extend(true, {}, $.ajaxSettings, options, {
contentType: false,
processData: false,
cache: false,
type: method || 'POST'
});
if (options.uploadProgress) {
// workaround because jqXHR does not expose upload property
s.xhr = function() {
var xhr = $.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function(event) {
var percent = 0;
var position = event.loaded || event.position; /*event.position is deprecated*/
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
options.uploadProgress(event, position, total, percent);
}, false);
}
return xhr;
};
}
s.data = null;
var beforeSend = s.beforeSend;
s.beforeSend = function(xhr, o) {
//Send FormData() provided by user
if (options.formData)
o.data = options.formData;
else
o.data = formdata;
if(beforeSend)
beforeSend.call(this, xhr, o);
};
return $.ajax(s);
}
// private function for handling file uploads (hat tip to YAHOO!)
function fileUploadIframe(a) {
var form = $form[0], el, i, s, g, id, $io, io, xhr, sub, n, timedOut, timeoutHandle;
var deferred = $.Deferred();
// #341
deferred.abort = function(status) {
xhr.abort(status);
};
if (a) {
// ensure that every serialized input is still enabled
for (i=0; i < elements.length; i++) {
el = $(elements[i]);
if ( hasProp )
el.prop('disabled', false);
else
el.removeAttr('disabled');
}
}
s = $.extend(true, {}, $.ajaxSettings, options);
s.context = s.context || s;
id = 'jqFormIO' + (new Date().getTime());
if (s.iframeTarget) {
$io = $(s.iframeTarget);
n = $io.attr2('name');
if (!n)
$io.attr2('name', id);
else
id = n;
}
else {
$io = $('<iframe name="' + id + '" src="'+ s.iframeSrc +'" />');
$io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
}
io = $io[0];
xhr = { // mock object
aborted: 0,
responseText: null,
responseXML: null,
status: 0,
statusText: 'n/a',
getAllResponseHeaders: function() {},
getResponseHeader: function() {},
setRequestHeader: function() {},
abort: function(status) {
var e = (status === 'timeout' ? 'timeout' : 'aborted');
log('aborting upload... ' + e);
this.aborted = 1;
try { // #214, #257
if (io.contentWindow.document.execCommand) {
io.contentWindow.document.execCommand('Stop');
}
}
catch(ignore) {}
$io.attr('src', s.iframeSrc); // abort op in progress
xhr.error = e;
if (s.error)
s.error.call(s.context, xhr, e, status);
if (g)
$.event.trigger("ajaxError", [xhr, s, e]);
if (s.complete)
s.complete.call(s.context, xhr, e);
}
};
g = s.global;
// trigger ajax global events so that activity/block indicators work like normal
if (g && 0 === $.active++) {
$.event.trigger("ajaxStart");
}
if (g) {
$.event.trigger("ajaxSend", [xhr, s]);
}
if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) {
if (s.global) {
$.active--;
}
deferred.reject();
return deferred;
}
if (xhr.aborted) {
deferred.reject();
return deferred;
}
// add submitting element to data if we know it
sub = form.clk;
if (sub) {
n = sub.name;
if (n && !sub.disabled) {
s.extraData = s.extraData || {};
s.extraData[n] = sub.value;
if (sub.type == "image") {
s.extraData[n+'.x'] = form.clk_x;
s.extraData[n+'.y'] = form.clk_y;
}
}
}
var CLIENT_TIMEOUT_ABORT = 1;
var SERVER_ABORT = 2;
function getDoc(frame) {
/* it looks like contentWindow or contentDocument do not
* carry the protocol property in ie8, when running under ssl
* frame.document is the only valid response document, since
* the protocol is know but not on the other two objects. strange?
* "Same origin policy" http://en.wikipedia.org/wiki/Same_origin_policy
*/
var doc = null;
// IE8 cascading access check
try {
if (frame.contentWindow) {
doc = frame.contentWindow.document;
}
} catch(err) {
// IE8 access denied under ssl & missing protocol
log('cannot get iframe.contentWindow document: ' + err);
}
if (doc) { // successful getting content
return doc;
}
try { // simply checking may throw in ie8 under ssl or mismatched protocol
doc = frame.contentDocument ? frame.contentDocument : frame.document;
} catch(err) {
// last attempt
log('cannot get iframe.contentDocument: ' + err);
doc = frame.document;
}
return doc;
}
// Rails CSRF hack (thanks to Yvan Barthelemy)
var csrf_token = $('meta[name=csrf-token]').attr('content');
var csrf_param = $('meta[name=csrf-param]').attr('content');
if (csrf_param && csrf_token) {
s.extraData = s.extraData || {};
s.extraData[csrf_param] = csrf_token;
}
// take a breath so that pending repaints get some cpu time before the upload starts
function doSubmit() {
// make sure form attrs are set
var t = $form.attr2('target'), a = $form.attr2('action');
// update form attrs in IE friendly way
form.setAttribute('target',id);
if (!method || /post/i.test(method) ) {
form.setAttribute('method', 'POST');
}
if (a != s.url) {
form.setAttribute('action', s.url);
}
// ie borks in some cases when setting encoding
if (! s.skipEncodingOverride && (!method || /post/i.test(method))) {
$form.attr({
encoding: 'multipart/form-data',
enctype: 'multipart/form-data'
});
}
// support timout
if (s.timeout) {
timeoutHandle = setTimeout(function() { timedOut = true; cb(CLIENT_TIMEOUT_ABORT); }, s.timeout);
}
// look for server aborts
function checkState() {
try {
var state = getDoc(io).readyState;
log('state = ' + state);
if (state && state.toLowerCase() == 'uninitialized')
setTimeout(checkState,50);
}
catch(e) {
log('Server abort: ' , e, ' (', e.name, ')');
cb(SERVER_ABORT);
if (timeoutHandle)
clearTimeout(timeoutHandle);
timeoutHandle = undefined;
}
}
// add "extra" data to form if provided in options
var extraInputs = [];
try {
if (s.extraData) {
for (var n in s.extraData) {
if (s.extraData.hasOwnProperty(n)) {
// if using the $.param format that allows for multiple values with the same name
if($.isPlainObject(s.extraData[n]) && s.extraData[n].hasOwnProperty('name') && s.extraData[n].hasOwnProperty('value')) {
extraInputs.push(
$('<input type="hidden" name="'+s.extraData[n].name+'">').val(s.extraData[n].value)
.appendTo(form)[0]);
} else {
extraInputs.push(
$('<input type="hidden" name="'+n+'">').val(s.extraData[n])
.appendTo(form)[0]);
}
}
}
}
if (!s.iframeTarget) {
// add iframe to doc and submit the form
$io.appendTo('body');
}
if (io.attachEvent)
io.attachEvent('onload', cb);
else
io.addEventListener('load', cb, false);
setTimeout(checkState,15);
try {
form.submit();
} catch(err) {
// just in case form has element with name/id of 'submit'
var submitFn = document.createElement('form').submit;
submitFn.apply(form);
}
}
finally {
// reset attrs and remove "extra" input elements
form.setAttribute('action',a);
if(t) {
form.setAttribute('target', t);
} else {
$form.removeAttr('target');
}
$(extraInputs).remove();
}
}
if (s.forceSync) {
doSubmit();
}
else {
setTimeout(doSubmit, 10); // this lets dom updates render
}
var data, doc, domCheckCount = 50, callbackProcessed;
function cb(e) {
if (xhr.aborted || callbackProcessed) {
return;
}
doc = getDoc(io);
if(!doc) {
log('cannot access response document');
e = SERVER_ABORT;
}
if (e === CLIENT_TIMEOUT_ABORT && xhr) {
xhr.abort('timeout');
deferred.reject(xhr, 'timeout');
return;
}
else if (e == SERVER_ABORT && xhr) {
xhr.abort('server abort');
deferred.reject(xhr, 'error', 'server abort');
return;
}
if (!doc || doc.location.href == s.iframeSrc) {
// response not received yet
if (!timedOut)
return;
}
if (io.detachEvent)
io.detachEvent('onload', cb);
else
io.removeEventListener('load', cb, false);
var status = 'success', errMsg;
try {
if (timedOut) {
throw 'timeout';
}
var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc);
log('isXml='+isXml);
if (!isXml && window.opera && (doc.body === null || !doc.body.innerHTML)) {
if (--domCheckCount) {
// in some browsers (Opera) the iframe DOM is not always traversable when
// the onload callback fires, so we loop a bit to accommodate
log('requeing onLoad callback, DOM not available');
setTimeout(cb, 250);
return;
}
// let this fall through because server response could be an empty document
//log('Could not access iframe DOM after mutiple tries.');
//throw 'DOMException: not available';
}
//log('response detected');
var docRoot = doc.body ? doc.body : doc.documentElement;
xhr.responseText = docRoot ? docRoot.innerHTML : null;
xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
if (isXml)
s.dataType = 'xml';
xhr.getResponseHeader = function(header){
var headers = {'content-type': s.dataType};
return headers[header.toLowerCase()];
};
// support for XHR 'status' & 'statusText' emulation :
if (docRoot) {
xhr.status = Number( docRoot.getAttribute('status') ) || xhr.status;
xhr.statusText = docRoot.getAttribute('statusText') || xhr.statusText;
}
var dt = (s.dataType || '').toLowerCase();
var scr = /(json|script|text)/.test(dt);
if (scr || s.textarea) {
// see if user embedded response in textarea
var ta = doc.getElementsByTagName('textarea')[0];
if (ta) {
xhr.responseText = ta.value;
// support for XHR 'status' & 'statusText' emulation :
xhr.status = Number( ta.getAttribute('status') ) || xhr.status;
xhr.statusText = ta.getAttribute('statusText') || xhr.statusText;
}
else if (scr) {
// account for browsers injecting pre around json response
var pre = doc.getElementsByTagName('pre')[0];
var b = doc.getElementsByTagName('body')[0];
if (pre) {
xhr.responseText = pre.textContent ? pre.textContent : pre.innerText;
}
else if (b) {
xhr.responseText = b.textContent ? b.textContent : b.innerText;
}
}
}
else if (dt == 'xml' && !xhr.responseXML && xhr.responseText) {
xhr.responseXML = toXml(xhr.responseText);
}
try {
data = httpData(xhr, dt, s);
}
catch (err) {
status = 'parsererror';
xhr.error = errMsg = (err || status);
}
}
catch (err) {
log('error caught: ',err);
status = 'error';
xhr.error = errMsg = (err || status);
}
if (xhr.aborted) {
log('upload aborted');
status = null;
}
if (xhr.status) { // we've set xhr.status
status = (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) ? 'success' : 'error';
}
// ordering of these callbacks/triggers is odd, but that's how $.ajax does it
if (status === 'success') {
if (s.success)
s.success.call(s.context, data, 'success', xhr);
deferred.resolve(xhr.responseText, 'success', xhr);
if (g)
$.event.trigger("ajaxSuccess", [xhr, s]);
}
else if (status) {
if (errMsg === undefined)
errMsg = xhr.statusText;
if (s.error)
s.error.call(s.context, xhr, status, errMsg);
deferred.reject(xhr, 'error', errMsg);
if (g)
$.event.trigger("ajaxError", [xhr, s, errMsg]);
}
if (g)
$.event.trigger("ajaxComplete", [xhr, s]);
if (g && ! --$.active) {
$.event.trigger("ajaxStop");
}
if (s.complete)
s.complete.call(s.context, xhr, status);
callbackProcessed = true;
if (s.timeout)
clearTimeout(timeoutHandle);
// clean up
setTimeout(function() {
if (!s.iframeTarget)
$io.remove();
else //adding else to clean up existing iframe response.
$io.attr('src', s.iframeSrc);
xhr.responseXML = null;
}, 100);
}
var toXml = $.parseXML || function(s, doc) { // use parseXML if available (jQuery 1.5+)
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.nodeName != 'parsererror') ? doc : null;
};
var parseJSON = $.parseJSON || function(s) {
/*jslint evil:true */
return window['eval']('(' + s + ')');
};
var httpData = function( xhr, type, s ) { // mostly lifted from jq1.4.4
var ct = xhr.getResponseHeader('content-type') || '',
xml = type === 'xml' || !type && ct.indexOf('xml') >= 0,
data = xml ? xhr.responseXML : xhr.responseText;
if (xml && data.documentElement.nodeName === 'parsererror') {
if ($.error)
$.error('parsererror');
}
if (s && s.dataFilter) {
data = s.dataFilter(data, type);
}
if (typeof data === 'string') {
if (type === 'json' || !type && ct.indexOf('json') >= 0) {
data = parseJSON(data);
} else if (type === "script" || !type && ct.indexOf("javascript") >= 0) {
$.globalEval(data);
}
}
return data;
};
return deferred;
}
};
/**
* 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.
*
* 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.
*/
$.fn.ajaxForm = function(options) {
options = options || {};
options.delegation = options.delegation && $.isFunction($.fn.on);
// in jQuery 1.3+ we can fix mistakes with the ready state
if (!options.delegation && this.length === 0) {
var o = { s: this.selector, c: this.context };
if (!$.isReady && o.s) {
log('DOM not ready, queuing ajaxForm');
$(function() {
$(o.s,o.c).ajaxForm(options);
});
return this;
}
// is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)'));
return this;
}
if ( options.delegation ) {
$(document)
.off('submit.form-plugin', this.selector, doAjaxSubmit)
.off('click.form-plugin', this.selector, captureSubmittingElement)
.on('submit.form-plugin', this.selector, options, doAjaxSubmit)
.on('click.form-plugin', this.selector, options, captureSubmittingElement);
return this;
}
return this.ajaxFormUnbind()
.bind('submit.form-plugin', options, doAjaxSubmit)
.bind('click.form-plugin', options, captureSubmittingElement);
};
// private event handlers
function doAjaxSubmit(e) {
/*jshint validthis:true */
var options = e.data;
if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed
e.preventDefault();
$(e.target).ajaxSubmit(options); // #365
}
}
function captureSubmittingElement(e) {
/*jshint validthis:true */
var target = e.target;
var $el = $(target);
if (!($el.is("[type=submit],[type=image]"))) {
// is this a child element of the submit el? (ex: a span within a button)
var t = $el.closest('[type=submit]');
if (t.length === 0) {
return;
}
target = t[0];
}
var form = this;
form.clk = target;
if (target.type == 'image') {
if (e.offsetX !== undefined) {
form.clk_x = e.offsetX;
form.clk_y = e.offsetY;
} else if (typeof $.fn.offset == 'function') {
var offset = $el.offset();
form.clk_x = e.pageX - offset.left;
form.clk_y = e.pageY - offset.top;
} else {
form.clk_x = e.pageX - target.offsetLeft;
form.clk_y = e.pageY - target.offsetTop;
}
}
// clear form vars
setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100);
}
// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
$.fn.ajaxFormUnbind = function() {
return this.unbind('submit.form-plugin click.form-plugin');
};
/**
* 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.
*/
$.fn.formToArray = function(semantic, elements) {
var a = [];
if (this.length === 0) {
return a;
}
var form = this[0];
var els = semantic ? form.getElementsByTagName('*') : form.elements;
if (!els) {
return a;
}
var i,j,n,v,el,max,jmax;
for(i=0, max=els.length; i < max; i++) {
el = els[i];
n = el.name;
if (!n || el.disabled) {
continue;
}
if (semantic && form.clk && el.type == "image") {
// handle image inputs on the fly when semantic == true
if(form.clk == el) {
a.push({name: n, value: $(el).val(), type: el.type });
a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
}
continue;
}
v = $.fieldValue(el, true);
if (v && v.constructor == Array) {
if (elements)
elements.push(el);
for(j=0, jmax=v.length; j < jmax; j++) {
a.push({name: n, value: v[j]});
}
}
else if (feature.fileapi && el.type == 'file') {
if (elements)
elements.push(el);
var files = el.files;
if (files.length) {
for (j=0; j < files.length; j++) {
a.push({name: n, value: files[j], type: el.type});
}
}
else {
// #180
a.push({ name: n, value: '', type: el.type });
}
}
else if (v !== null && typeof v != 'undefined') {
if (elements)
elements.push(el);
a.push({name: n, value: v, type: el.type, required: el.required});
}
}
if (!semantic && form.clk) {
// input type=='image' are not found in elements array! handle it here
var $input = $(form.clk), input = $input[0];
n = input.name;
if (n && !input.disabled && input.type == 'image') {
a.push({name: n, value: $input.val()});
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
*/
$.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
*/
$.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 = $('input[type=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 = $('input[type=checkbox]').fieldValue();
* // if neither checkbox is checked
* v === undefined
* // if both checkboxes are checked
* v == ['B1', 'B2']
*
* var v = $('input[type=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.
*/
$.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;
}
if (v.constructor == Array)
$.merge(val, v);
else
val.push(v);
}
return val;
};
/**
* Returns the value of the field element.
*/
$.fieldValue = function(el, successful) {
var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
if (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) {
var v = op.value;
if (!v) { // extra pain for IE...
v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value;
}
if (one) {
return v;
}
a.push(v);
}
}
return a;
}
return $(el).val();
};
/**
* 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
*/
$.fn.clearForm = function(includeHidden) {
return this.each(function() {
$('input,select,textarea', this).clearFields(includeHidden);
});
};
/**
* Clears the selected form elements.
*/
$.fn.clearFields = $.fn.clearInputs = function(includeHidden) {
var re = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list
return this.each(function() {
var t = this.type, tag = this.tagName.toLowerCase();
if (re.test(t) || tag == 'textarea') {
this.value = '';
}
else if (t == 'checkbox' || t == 'radio') {
this.checked = false;
}
else if (tag == 'select') {
this.selectedIndex = -1;
}
else if (t == "file") {
if (/MSIE/.test(navigator.userAgent)) {
$(this).replaceWith($(this).clone(true));
} else {
$(this).val('');
}
}
else if (includeHidden) {
// includeHidden can be the value true, or it can be a selector string
// indicating a special test; for example:
// $('#myForm').clearForm('.special:hidden')
// the above would clean hidden inputs that have the class of 'special'
if ( (includeHidden === true && /hidden/.test(t)) ||
(typeof includeHidden == 'string' && $(this).is(includeHidden)) )
this.value = '';
}
});
};
/**
* Resets the form data. Causes all form elements to be reset to their original value.
*/
$.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.
*/
$.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.
*/
$.fn.selected = 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').selected(false);
}
this.selected = select;
}
});
};
// expose debug var
$.fn.ajaxSubmit.debug = false;
// helper fn for console logging
function log() {
if (!$.fn.ajaxSubmit.debug)
return;
var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,'');
if (window.console && window.console.log) {
window.console.log(msg);
}
else if (window.opera && window.opera.postError) {
window.opera.postError(msg);
}
}
})( (typeof(jQuery) != 'undefined') ? jQuery : window.Zepto ); | JavaScript |
var App = function () {
var isMainPage = false;
var isMapPage = false;
var isIE8 = false;
var handleJQVMAP = function () {
if (!sample_data) {
return;
}
var showMap = function (name) {
jQuery('.vmaps').hide();
jQuery('#vmap_' + name).show();
}
var setMap = function (name) {
var data = {
map: 'world_en',
backgroundColor: null,
borderColor: '#333333',
borderOpacity: 0.5,
borderWidth: 1,
color: '#c6c6c6',
enableZoom: true,
hoverColor: '#3daced',
hoverOpacity: null,
values: sample_data,
normalizeFunction: 'linear',
scaleColors: ['#e8e8e8', '#b0b0b0'],
selectedColor: '#3daced',
selectedRegion: null,
showTooltip: true,
onLabelShow: function (event, label, code) {
},
onRegionOver: function (event, code) {
if (code == 'ca') {
event.preventDefault();
}
},
onRegionClick: function (element, code, region) {
var message = 'You clicked "' + region + '" which has the code: ' + code.toUpperCase();
alert(message);
}
};
data.map = name + '_en';
var map = jQuery('#vmap_' + name);
map.width(map.parent().parent().width());
map.show();
map.vectorMap(data);
map.hide();
}
setMap("world");
setMap("usa");
setMap("europe");
setMap("russia");
setMap("germany");
showMap("world");
jQuery('#regional_stat_world').click(function () {
showMap("world");
});
jQuery('#regional_stat_usa').click(function () {
showMap("usa");
});
jQuery('#regional_stat_europe').click(function () {
showMap("europe");
});
jQuery('#regional_stat_russia').click(function () {
showMap("russia");
});
jQuery('#regional_stat_germany').click(function () {
showMap("germany");
});
$('#region_statistics_loading').hide();
$('#region_statistics_content').show();
}
var handleAllJQVMAP = function () {
if (!sample_data) {
return;
}
var setMap = function (name) {
var data = {
map: 'world_en',
backgroundColor: null,
borderColor: '#333333',
borderOpacity: 0.5,
borderWidth: 1,
color: '#c6c6c6',
enableZoom: true,
hoverColor: '#3daced',
hoverOpacity: null,
values: sample_data,
normalizeFunction: 'linear',
scaleColors: ['#e8e8e8', '#b0b0b0'],
selectedColor: '#3daced',
selectedRegion: null,
showTooltip: true,
onRegionOver: function (event, code) {
//sample to interact with map
if (code == 'ca') {
event.preventDefault();
}
},
onRegionClick: function (element, code, region) {
//sample to interact with map
var message = 'You clicked "' + region + '" which has the code: ' + code.toUpperCase();
alert(message);
}
};
data.map = name + '_en';
var map = jQuery('#vmap_' + name);
map.width(map.parent().width());
map.vectorMap(data);
}
setMap("world");
setMap("usa");
setMap("europe");
setMap("russia");
setMap("germany");
}
var handleDashboardCalendar = function () {
if (!jQuery().fullCalendar) {
return;
}
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var h = {};
if ($(window).width() <= 320) {
h = {
left: 'title, prev,next',
center: '',
right: 'today,month,agendaWeek,agendaDay'
};
} else {
h = {
left: 'title',
center: '',
right: 'prev,next,today,month,agendaWeek,agendaDay'
};
}
$('#calendar').html("");
$('#calendar').fullCalendar({
header: h,
editable: true,
events: [{
title: 'All Day Event',
start: new Date(y, m, 1),
className: 'label label-default',
}, {
title: 'Long Event',
start: new Date(y, m, d - 5),
end: new Date(y, m, d - 2),
className: 'label label-success',
}, {
title: 'Repeating Event',
start: new Date(y, m, d - 3, 16, 0),
allDay: false,
className: 'label label-default',
}, {
title: 'Repeating Event',
start: new Date(y, m, d + 4, 16, 0),
allDay: false,
className: 'label label-important',
}, {
title: 'Meeting',
start: new Date(y, m, d, 10, 30),
allDay: false,
className: 'label label-info',
}, {
title: 'Lunch',
start: new Date(y, m, d, 12, 0),
end: new Date(y, m, d, 14, 0),
allDay: false,
className: 'label label-warning',
}, {
title: 'Birthday Party',
start: new Date(y, m, d + 1, 19, 0),
end: new Date(y, m, d + 1, 22, 30),
allDay: false,
className: 'label label-success',
}, {
title: 'Click for Google',
start: new Date(y, m, 28),
end: new Date(y, m, 29),
url: 'http://google.com/',
className: 'label label-warning',
}]
});
}
var handleCalendar = function () {
if (!jQuery().fullCalendar) {
return;
}
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var h = {};
if ($(window).width() <= 320) {
h = {
left: 'title, prev,next',
center: '',
right: 'today,month,agendaWeek,agendaDay'
};
} else {
h = {
left: 'title',
center: '',
right: 'prev,next,today,month,agendaWeek,agendaDay'
};
}
var initDrag = function (el) {
// create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
// it doesn't need to have a start or end
var eventObject = {
title: $.trim(el.text()) // use the element's text as the event title
};
// store the Event Object in the DOM element so we can get to it later
el.data('eventObject', eventObject);
// make the event draggable using jQuery UI
el.draggable({
zIndex: 999,
revert: true, // will cause the event to go back to its
revertDuration: 0 // original position after the drag
});
}
var addEvent = function (title, priority) {
title = title.length == 0 ? "Untitled Event" : title;
priority = priority.length == 0 ? "default" : priority;
var html = $('<div data-class="label label-' + priority + '" class="external-event label label-' + priority + '">' + title + '</div>');
jQuery('#event_box').append(html);
initDrag(html);
}
$('#external-events div.external-event').each(function () {
initDrag($(this))
});
$('#event_add').click(function () {
var title = $('#event_title').val();
var priority = $('#event_priority').val();
addEvent(title, priority);
});
//modify chosen options
var handleDropdown = function () {
$('#event_priority_chzn .chzn-search').hide(); //hide search box
$('#event_priority_chzn_o_1').html('<span class="label label-default">' + $('#event_priority_chzn_o_1').text() + '</span>');
$('#event_priority_chzn_o_2').html('<span class="label label-success">' + $('#event_priority_chzn_o_2').text() + '</span>');
$('#event_priority_chzn_o_3').html('<span class="label label-info">' + $('#event_priority_chzn_o_3').text() + '</span>');
$('#event_priority_chzn_o_4').html('<span class="label label-warning">' + $('#event_priority_chzn_o_4').text() + '</span>');
$('#event_priority_chzn_o_5').html('<span class="label label-important">' + $('#event_priority_chzn_o_5').text() + '</span>');
}
$('#event_priority_chzn').click(handleDropdown);
//predefined events
addEvent("My Event 1", "default");
addEvent("My Event 2", "success");
addEvent("My Event 3", "info");
addEvent("My Event 4", "warning");
addEvent("My Event 5", "important");
addEvent("My Event 6", "success");
addEvent("My Event 7", "info");
addEvent("My Event 8", "warning");
addEvent("My Event 9", "success");
addEvent("My Event 10", "default");
$('#calendar').fullCalendar({
header: h,
editable: true,
droppable: true, // this allows things to be dropped onto the calendar !!!
drop: function (date, allDay) { // this function is called when something is dropped
// retrieve the dropped element's stored Event Object
var originalEventObject = $(this).data('eventObject');
// we need to copy it, so that multiple events don't have a reference to the same object
var copiedEventObject = $.extend({}, originalEventObject);
// assign it the date that was reported
copiedEventObject.start = date;
copiedEventObject.allDay = allDay;
copiedEventObject.className = $(this).attr("data-class");
// render the event on the calendar
// the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
$('#calendar').fullCalendar('renderEvent', copiedEventObject, true);
// is the "remove after drop" checkbox checked?
if ($('#drop-remove').is(':checked')) {
// if so, remove the element from the "Draggable Events" list
$(this).remove();
}
},
events: [{
title: 'All Day Event',
start: new Date(y, m, 1),
className: 'label label-default',
}, {
title: 'Long Event',
start: new Date(y, m, d - 5),
end: new Date(y, m, d - 2),
className: 'label label-success',
}, {
id: 999,
title: 'Repeating Event',
start: new Date(y, m, d - 3, 16, 0),
allDay: false,
className: 'label label-default',
}, {
id: 999,
title: 'Repeating Event',
start: new Date(y, m, d + 4, 16, 0),
allDay: false,
className: 'label label-important',
}, {
title: 'Meeting',
start: new Date(y, m, d, 10, 30),
allDay: false,
className: 'label label-info',
}, {
title: 'Lunch',
start: new Date(y, m, d, 12, 0),
end: new Date(y, m, d, 14, 0),
allDay: false,
className: 'label label-warning',
}, {
title: 'Birthday Party',
start: new Date(y, m, d + 1, 19, 0),
end: new Date(y, m, d + 1, 22, 30),
allDay: false,
className: 'label label-success',
}, {
title: 'Click for Google',
start: new Date(y, m, 28),
end: new Date(y, m, 29),
url: 'http://google.com/',
className: 'label label-warning',
}]
});
}
var handleChat = function () {
var cont = $('#chats');
var list = $('.chats', cont);
var form = $('.chat-form', cont);
var input = $('input', form);
var btn = $('.btn', form);
var handleClick = function () {
var text = input.val();
if (text.length == 0) {
return;
}
var time = new Date();
var time_str = time.toString('MMM dd, yyyy HH:MM');
var tpl = '';
tpl += '<li class="out">';
tpl += '<img class="avatar" alt="" src="img/avatar1.jpg"/>';
tpl += '<div class="message">';
tpl += '<span class="arrow"></span>';
tpl += '<a href="#" class="name">Sumon Ahmed</a> ';
tpl += '<span class="datetime">at ' + time_str + '</span>';
tpl += '<span class="body">';
tpl += text;
tpl += '</span>';
tpl += '</div>';
tpl += '</li>';
var msg = list.append(tpl);
input.val("");
$('.scroller', cont).slimScroll({
scrollTo: list.height()
});
}
btn.click(handleClick);
input.keypress(function (e) {
if (e.which == 13) {
handleClick();
return false; //<---- Add this line
}
});
}
var handleClockfaceTimePickers = function () {
if (!jQuery().clockface) {
return;
}
$('#clockface_1').clockface();
$('#clockface_2').clockface({
format: 'HH:mm',
trigger: 'manual'
});
$('#clockface_2_toggle-btn').click(function (e) {
e.stopPropagation();
$('#clockface_2').clockface('toggle');
});
$('#clockface_3').clockface({
format: 'H:mm'
}).clockface('show', '14:30');
}
var handlePortletSortable = function () {
if (!jQuery().sortable) {
return;
}
$(".sortable").sortable({
connectWith: '.sortable',
iframeFix: false,
items: 'div.widget',
opacity: 0.8,
helper: 'original',
revert: true,
forceHelperSize: true,
placeholder: 'sortable-box-placeholder round-all',
forcePlaceholderSize: true,
tolerance: 'pointer'
});
}
var handleMainMenu = function () {
jQuery('#sidebar .has-sub > a').click(function () {
var last = jQuery('.has-sub.open', $('#sidebar'));
last.removeClass("open");
jQuery('.arrow', last).removeClass("open");
jQuery('.sub', last).slideUp(200);
var sub = jQuery(this).next();
if (sub.is(":visible")) {
jQuery('.arrow', jQuery(this)).removeClass("open");
jQuery(this).parent().removeClass("open");
sub.slideUp(200);
} else {
jQuery('.arrow', jQuery(this)).addClass("open");
jQuery(this).parent().addClass("open");
sub.slideDown(200);
}
});
}
var handleWidgetTools = function () {
jQuery('.widget .tools .icon-remove').click(function () {
jQuery(this).parents(".widget").parent().remove();
});
jQuery('.widget .tools .icon-refresh').click(function () {
var el = jQuery(this).parents(".widget");
App.blockUI(el);
window.setTimeout(function () {
App.unblockUI(el);
}, 1000);
});
jQuery('.widget .tools .icon-chevron-down, .widget .tools .icon-chevron-up').click(function () {
var el = jQuery(this).parents(".widget").children(".widget-body");
if (jQuery(this).hasClass("icon-chevron-down")) {
jQuery(this).removeClass("icon-chevron-down").addClass("icon-chevron-up");
el.slideUp(200);
} else {
jQuery(this).removeClass("icon-chevron-up").addClass("icon-chevron-down");
el.slideDown(200);
}
});
}
var handleDashboardCharts = function () {
// used by plot functions
var data = [];
var totalPoints = 200;
// random data generator for plot charts
function getRandomData() {
if (data.length > 0) data = data.slice(1);
// do a random walk
while (data.length < totalPoints) {
var prev = data.length > 0 ? data[data.length - 1] : 50;
var y = prev + Math.random() * 10 - 5;
if (y < 0) y = 0;
if (y > 100) y = 100;
data.push(y);
}
// zip the generated y values with the x values
var res = [];
for (var i = 0; i < data.length; ++i) res.push([i, data[i]])
return res;
}
if (!jQuery.plot) {
return;
}
function randValue() {
return (Math.floor(Math.random() * (1 + 40 - 20))) + 20;
}
var pageviews = [
[1, randValue()],
[2, randValue()],
[3, 2 + randValue()],
[4, 3 + randValue()],
[5, 5 + randValue()],
[6, 10 + randValue()],
[7, 15 + randValue()],
[8, 20 + randValue()],
[9, 25 + randValue()],
[10, 30 + randValue()],
[11, 35 + randValue()],
[12, 25 + randValue()],
[13, 15 + randValue()],
[14, 20 + randValue()],
[15, 45 + randValue()],
[16, 50 + randValue()],
[17, 65 + randValue()],
[18, 70 + randValue()],
[19, 85 + randValue()],
[20, 80 + randValue()],
[21, 75 + randValue()],
[22, 80 + randValue()],
[23, 75 + randValue()],
[24, 70 + randValue()],
[25, 65 + randValue()],
[26, 75 + randValue()],
[27, 80 + randValue()],
[28, 85 + randValue()],
[29, 90 + randValue()],
[30, 95 + randValue()]
];
var visitors = [
[1, randValue() - 5],
[2, randValue() - 5],
[3, randValue() - 5],
[4, 6 + randValue()],
[5, 5 + randValue()],
[6, 20 + randValue()],
[7, 25 + randValue()],
[8, 36 + randValue()],
[9, 26 + randValue()],
[10, 38 + randValue()],
[11, 39 + randValue()],
[12, 50 + randValue()],
[13, 51 + randValue()],
[14, 12 + randValue()],
[15, 13 + randValue()],
[16, 14 + randValue()],
[17, 15 + randValue()],
[18, 15 + randValue()],
[19, 16 + randValue()],
[20, 17 + randValue()],
[21, 18 + randValue()],
[22, 19 + randValue()],
[23, 20 + randValue()],
[24, 21 + randValue()],
[25, 14 + randValue()],
[26, 24 + randValue()],
[27, 25 + randValue()],
[28, 26 + randValue()],
[29, 27 + randValue()],
[30, 31 + randValue()]
];
$('#site_statistics_loading').hide();
$('#site_statistics_content').show();
var plot = $.plot($("#site_statistics"), [{
data: pageviews,
label: "Unique Visits"
}, {
data: visitors,
label: "Page Views"
}], {
series: {
lines: {
show: true,
lineWidth: 2,
fill: true,
fillColor: {
colors: [{
opacity: 0.05
}, {
opacity: 0.01
}]
}
},
points: {
show: true
},
shadowSize: 2
},
grid: {
hoverable: true,
clickable: true,
tickColor: "#eee",
borderWidth: 0
},
colors: ["#A5D16C", "#FCB322", "#32C2CD"],
xaxis: {
ticks: 11,
tickDecimals: 0
},
yaxis: {
ticks: 11,
tickDecimals: 0
}
});
function showTooltip(x, y, contents) {
$('<div id="tooltip">' + contents + '</div>').css({
position: 'absolute',
display: 'none',
top: y + 5,
left: x + 15,
border: '1px solid #333',
padding: '4px',
color: '#fff',
'border-radius': '3px',
'background-color': '#333',
opacity: 0.80
}).appendTo("body").fadeIn(200);
}
var previousPoint = null;
$("#site_statistics").bind("plothover", function (event, pos, item) {
$("#x").text(pos.x.toFixed(2));
$("#y").text(pos.y.toFixed(2));
if (item) {
if (previousPoint != item.dataIndex) {
previousPoint = item.dataIndex;
$("#tooltip").remove();
var x = item.datapoint[0].toFixed(2),
y = item.datapoint[1].toFixed(2);
showTooltip(item.pageX, item.pageY, item.series.label + " of " + x + " = " + y);
}
} else {
$("#tooltip").remove();
previousPoint = null;
}
});
//server load
var options = {
series: {
shadowSize: 1
},
lines: {
show: true,
lineWidth: 0.5,
fill: true,
fillColor: {
colors: [{
opacity: 0.1
}, {
opacity: 1
}]
}
},
yaxis: {
min: 0,
max: 100,
tickFormatter: function (v) {
return v + "%";
}
},
xaxis: {
show: false
},
colors: ["#A5D16C"],
grid: {
tickColor: "#eaeaea",
borderWidth: 0
}
};
$('#load_statistics_loading').hide();
$('#load_statistics_content').show();
var updateInterval = 30;
var plot = $.plot($("#load_statistics"), [getRandomData()], options);
function update() {
plot.setData([getRandomData()]);
plot.draw();
setTimeout(update, updateInterval);
}
update();
}
var handleCharts = function () {
// used by plot functions
var data = [];
var totalPoints = 250;
// random data generator for plot charts
function getRandomData() {
if (data.length > 0) data = data.slice(1);
// do a random walk
while (data.length < totalPoints) {
var prev = data.length > 0 ? data[data.length - 1] : 50;
var y = prev + Math.random() * 10 - 5;
if (y < 0) y = 0;
if (y > 100) y = 100;
data.push(y);
}
// zip the generated y values with the x values
var res = [];
for (var i = 0; i < data.length; ++i) res.push([i, data[i]])
return res;
}
if (!jQuery.plot) {
return;
}
if ($("#chart_1").size() == 0) {
return;
}
//Basic Chart
function chart1() {
var d1 = [];
for (var i = 0; i < Math.PI * 2; i += 0.25)
d1.push([i, Math.sin(i)]);
var d2 = [];
for (var i = 0; i < Math.PI * 2; i += 0.25)
d2.push([i, Math.cos(i)]);
var d3 = [];
for (var i = 0; i < Math.PI * 2; i += 0.1)
d3.push([i, Math.tan(i)]);
$.plot($("#chart_1"), [{
label: "sin(x)",
data: d1
}, {
label: "cos(x)",
data: d2
}, {
label: "tan(x)",
data: d3
}], {
series: {
lines: {
show: true
},
points: {
show: true
}
},
xaxis: {
ticks: [0, [Math.PI / 2, "\u03c0/2"],
[Math.PI, "\u03c0"],
[Math.PI * 3 / 2, "3\u03c0/2"],
[Math.PI * 2, "2\u03c0"]
]
},
yaxis: {
ticks: 10,
min: -2,
max: 2
},
grid: {
backgroundColor: {
colors: ["#fff", "#eee"]
}
}
});
}
//Interactive Chart
function chart2() {
function randValue() {
return (Math.floor(Math.random() * (1 + 40 - 20))) + 20;
}
var pageviews = [
[1, randValue()],
[2, randValue()],
[3, 2 + randValue()],
[4, 3 + randValue()],
[5, 5 + randValue()],
[6, 10 + randValue()],
[7, 15 + randValue()],
[8, 20 + randValue()],
[9, 25 + randValue()],
[10, 30 + randValue()],
[11, 35 + randValue()],
[12, 25 + randValue()],
[13, 15 + randValue()],
[14, 20 + randValue()],
[15, 45 + randValue()],
[16, 50 + randValue()],
[17, 65 + randValue()],
[18, 70 + randValue()],
[19, 85 + randValue()],
[20, 80 + randValue()],
[21, 75 + randValue()],
[22, 80 + randValue()],
[23, 75 + randValue()],
[24, 70 + randValue()],
[25, 65 + randValue()],
[26, 75 + randValue()],
[27, 80 + randValue()],
[28, 85 + randValue()],
[29, 90 + randValue()],
[30, 95 + randValue()]
];
var visitors = [
[1, randValue() - 5],
[2, randValue() - 5],
[3, randValue() - 5],
[4, 6 + randValue()],
[5, 5 + randValue()],
[6, 20 + randValue()],
[7, 25 + randValue()],
[8, 36 + randValue()],
[9, 26 + randValue()],
[10, 38 + randValue()],
[11, 39 + randValue()],
[12, 50 + randValue()],
[13, 51 + randValue()],
[14, 12 + randValue()],
[15, 13 + randValue()],
[16, 14 + randValue()],
[17, 15 + randValue()],
[18, 15 + randValue()],
[19, 16 + randValue()],
[20, 17 + randValue()],
[21, 18 + randValue()],
[22, 19 + randValue()],
[23, 20 + randValue()],
[24, 21 + randValue()],
[25, 14 + randValue()],
[26, 24 + randValue()],
[27, 25 + randValue()],
[28, 26 + randValue()],
[29, 27 + randValue()],
[30, 31 + randValue()]
];
var plot = $.plot($("#chart_2"), [{
data: pageviews,
label: "Unique Visits"
}, {
data: visitors,
label: "Page Views"
}], {
series: {
lines: {
show: true,
lineWidth: 2,
fill: true,
fillColor: {
colors: [{
opacity: 0.05
}, {
opacity: 0.01
}]
}
},
points: {
show: true
},
shadowSize: 2
},
grid: {
hoverable: true,
clickable: true,
tickColor: "#eee",
borderWidth: 0
},
colors: ["#FCB322", "#A5D16C", "#52e136"],
xaxis: {
ticks: 11,
tickDecimals: 0
},
yaxis: {
ticks: 11,
tickDecimals: 0
}
});
function showTooltip(x, y, contents) {
$('<div id="tooltip">' + contents + '</div>').css({
position: 'absolute',
display: 'none',
top: y + 5,
left: x + 15,
border: '1px solid #333',
padding: '4px',
color: '#fff',
'border-radius': '3px',
'background-color': '#333',
opacity: 0.80
}).appendTo("body").fadeIn(200);
}
var previousPoint = null;
$("#chart_2").bind("plothover", function (event, pos, item) {
$("#x").text(pos.x.toFixed(2));
$("#y").text(pos.y.toFixed(2));
if (item) {
if (previousPoint != item.dataIndex) {
previousPoint = item.dataIndex;
$("#tooltip").remove();
var x = item.datapoint[0].toFixed(2),
y = item.datapoint[1].toFixed(2);
showTooltip(item.pageX, item.pageY, item.series.label + " of " + x + " = " + y);
}
} else {
$("#tooltip").remove();
previousPoint = null;
}
});
}
//Tracking Curves
function chart3() {
//tracking curves:
var sin = [],
cos = [];
for (var i = 0; i < 14; i += 0.1) {
sin.push([i, Math.sin(i)]);
cos.push([i, Math.cos(i)]);
}
plot = $.plot($("#chart_3"), [{
data: sin,
label: "sin(x) = -0.00"
}, {
data: cos,
label: "cos(x) = -0.00"
}], {
series: {
lines: {
show: true
}
},
crosshair: {
mode: "x"
},
grid: {
hoverable: true,
autoHighlight: false
},
colors: ["#FCB322", "#A5D16C", "#52e136"],
yaxis: {
min: -1.2,
max: 1.2
}
});
var legends = $("#chart_3 .legendLabel");
legends.each(function () {
// fix the widths so they don't jump around
$(this).css('width', $(this).width());
});
var updateLegendTimeout = null;
var latestPosition = null;
function updateLegend() {
updateLegendTimeout = null;
var pos = latestPosition;
var axes = plot.getAxes();
if (pos.x < axes.xaxis.min || pos.x > axes.xaxis.max || pos.y < axes.yaxis.min || pos.y > axes.yaxis.max) return;
var i, j, dataset = plot.getData();
for (i = 0; i < dataset.length; ++i) {
var series = dataset[i];
// find the nearest points, x-wise
for (j = 0; j < series.data.length; ++j)
if (series.data[j][0] > pos.x) break;
// now interpolate
var y, p1 = series.data[j - 1],
p2 = series.data[j];
if (p1 == null) y = p2[1];
else if (p2 == null) y = p1[1];
else y = p1[1] + (p2[1] - p1[1]) * (pos.x - p1[0]) / (p2[0] - p1[0]);
legends.eq(i).text(series.label.replace(/=.*/, "= " + y.toFixed(2)));
}
}
$("#chart_3").bind("plothover", function (event, pos, item) {
latestPosition = pos;
if (!updateLegendTimeout) updateLegendTimeout = setTimeout(updateLegend, 50);
});
}
//Dynamic Chart
function chart4() {
//server load
var options = {
series: {
shadowSize: 1
},
lines: {
show: true,
lineWidth: 0.5,
fill: true,
fillColor: {
colors: [{
opacity: 0.1
}, {
opacity: 1
}]
}
},
yaxis: {
min: 0,
max: 100,
tickFormatter: function (v) {
return v + "%";
}
},
xaxis: {
show: false
},
colors: ["#6ef146"],
grid: {
tickColor: "#a8a3a3",
borderWidth: 0
}
};
var updateInterval = 30;
var plot = $.plot($("#chart_4"), [getRandomData()], options);
function update() {
plot.setData([getRandomData()]);
plot.draw();
setTimeout(update, updateInterval);
}
update();
}
//bars with controls
function chart5() {
var d1 = [];
for (var i = 0; i <= 10; i += 1)
d1.push([i, parseInt(Math.random() * 30)]);
var d2 = [];
for (var i = 0; i <= 10; i += 1)
d2.push([i, parseInt(Math.random() * 30)]);
var d3 = [];
for (var i = 0; i <= 10; i += 1)
d3.push([i, parseInt(Math.random() * 30)]);
var stack = 0,
bars = true,
lines = false,
steps = false;
function plotWithOptions() {
$.plot($("#chart_5"), [d1, d2, d3], {
series: {
stack: stack,
lines: {
show: lines,
fill: true,
steps: steps
},
bars: {
show: bars,
barWidth: 0.6
}
}
});
}
$(".stackControls input").click(function (e) {
e.preventDefault();
stack = $(this).val() == "With stacking" ? true : null;
plotWithOptions();
});
$(".graphControls input").click(function (e) {
e.preventDefault();
bars = $(this).val().indexOf("Bars") != -1;
lines = $(this).val().indexOf("Lines") != -1;
steps = $(this).val().indexOf("steps") != -1;
plotWithOptions();
});
plotWithOptions();
}
//graph
function graphs() {
var graphData = [];
var series = Math.floor(Math.random() * 10) + 1;
for (var i = 0; i < series; i++) {
graphData[i] = {
label: "Series" + (i + 1),
data: Math.floor((Math.random() - 1) * 100) + 1
}
}
$.plot($("#graph_1"), graphData, {
series: {
pie: {
show: true,
radius: 1,
label: {
show: true,
radius: 1,
formatter: function (label, series) {
return '<div style="font-size:8pt;text-align:center;padding:2px;color:white;">' + label + '<br/>' + Math.round(series.percent) + '%</div>';
},
background: {
opacity: 0.8
}
}
}
},
legend: {
show: false
}
});
$.plot($("#graph_2"), graphData, {
series: {
pie: {
show: true,
radius: 1,
label: {
show: true,
radius: 3 / 4,
formatter: function (label, series) {
return '<div style="font-size:8pt;text-align:center;padding:2px;color:white;">' + label + '<br/>' + Math.round(series.percent) + '%</div>';
},
background: {
opacity: 0.5
}
}
}
},
legend: {
show: false
}
});
$.plot($("#graph_3"), graphData, {
series: {
pie: {
show: true
}
},
grid: {
hoverable: true,
clickable: true
}
});
$("#graph_3").bind("plothover", pieHover);
$("#graph_3").bind("plotclick", pieClick);
function pieHover(event, pos, obj) {
if (!obj) return;
percent = parseFloat(obj.series.percent).toFixed(2);
$("#hover").html('<span style="font-weight: bold; color: ' + obj.series.color + '">' + obj.series.label + ' (' + percent + '%)</span>');
}
function pieClick(event, pos, obj) {
if (!obj) return;
percent = parseFloat(obj.series.percent).toFixed(2);
alert('' + obj.series.label + ': ' + percent + '%');
}
$.plot($("#graph_4"), graphData, {
series: {
pie: {
innerRadius: 0.5,
show: true
}
}
});
}
chart1();
chart2();
chart3();
chart4();
chart5();
graphs();
}
var handleFancyBox = function () {
if (!jQuery().fancybox) {
return;
}
if (jQuery(".fancybox-button").size() > 0) {
jQuery(".fancybox-button").fancybox({
groupAttr: 'data-rel',
prevEffect: 'none',
nextEffect: 'none',
closeBtn: true,
helpers: {
title: {
type: 'inside'
}
}
});
}
}
var handleLoginForm = function () {
jQuery('#forget-password').click(function () {
jQuery('#loginform').hide();
jQuery('#forgotform').show(200);
});
jQuery('#forget-btn').click(function () {
jQuery('#loginform').slideDown(200);
jQuery('#forgotform').slideUp(200);
});
}
var handleFixInputPlaceholderForIE = function () {
//fix html5 placeholder attribute for ie7 & ie8
if (jQuery.browser.msie && jQuery.browser.version.substr(0, 1) <= 9) { // ie7&ie8
jQuery('input[placeholder], textarea[placeholder]').each(function () {
var input = jQuery(this);
jQuery(input).val(input.attr('placeholder'));
jQuery(input).focus(function () {
if (input.val() == input.attr('placeholder')) {
input.val('');
}
});
jQuery(input).blur(function () {
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.val(input.attr('placeholder'));
}
});
});
}
}
var handleStyler = function () {
var scrollHeight = '25px';
jQuery('#theme-change').click(function () {
if ($(this).attr("opened") && !$(this).attr("opening") && !$(this).attr("closing")) {
$(this).removeAttr("opened");
$(this).attr("closing", "1");
$("#theme-change").css("overflow", "hidden").animate({
width: '20px',
height: '22px',
'padding-top': '3px'
}, {
complete: function () {
$(this).removeAttr("closing");
$("#theme-change .settings").hide();
}
});
} else if (!$(this).attr("closing") && !$(this).attr("opening")) {
$(this).attr("opening", "1");
$("#theme-change").css("overflow", "visible").animate({
width: '190px',
height: scrollHeight,
'padding-top': '3px'
}, {
complete: function () {
$(this).removeAttr("opening");
$(this).attr("opened", 1);
}
});
$("#theme-change .settings").show();
}
});
jQuery('#theme-change .colors span').click(function () {
var color = $(this).attr("data-style");
setColor(color);
});
jQuery('#theme-change .layout input').change(function () {
setLayout();
});
var setColor = function (color) {
$('#style_color').attr("href", host+"assets/css/style_" + color + ".css");
}
}
var handlePulsate = function () {
if (!jQuery().pulsate) {
return;
}
if (isIE8 == true) {
return; // pulsate plugin does not support IE8 and below
}
if (jQuery().pulsate) {
jQuery('#pulsate-regular').pulsate({
color: "#bf1c56"
});
jQuery('#pulsate-once').click(function () {
$(this).pulsate({
color: "#399bc3",
repeat: false
});
});
jQuery('#pulsate-hover').pulsate({
color: "#5ebf5e",
repeat: false,
onHover: true
});
jQuery('#pulsate-crazy').click(function () {
$(this).pulsate({
color: "#fdbe41",
reach: 50,
repeat: 10,
speed: 100,
glow: true
});
});
}
}
var handlePeity = function () {
if (!jQuery().peity) {
return;
}
if (jQuery.browser.msie && jQuery.browser.version.substr(0, 2) <= 8) { // ie7&ie8
return;
}
$(".stat.bad .line-chart").peity("line", {
height: 20,
width: 50,
colour: "#d12610",
strokeColour: "#666"
}).show();
$(".stat.bad .bar-chart").peity("bar", {
height: 20,
width: 50,
colour: "#d12610",
strokeColour: "#666"
}).show();
$(".stat.ok .line-chart").peity("line", {
height: 20,
width: 50,
colour: "#37b7f3",
strokeColour: "#757575"
}).show();
$(".stat.ok .bar-chart").peity("bar", {
height: 20,
width: 50,
colour: "#37b7f3"
}).show();
$(".stat.good .line-chart").peity("line", {
height: 20,
width: 50,
colour: "#52e136"
}).show();
$(".stat.good .bar-chart").peity("bar", {
height: 20,
width: 50,
colour: "#52e136"
}).show();
//
$(".stat.bad.huge .line-chart").peity("line", {
height: 20,
width: 40,
colour: "#d12610",
strokeColour: "#666"
}).show();
$(".stat.bad.huge .bar-chart").peity("bar", {
height: 20,
width: 40,
colour: "#d12610",
strokeColour: "#666"
}).show();
$(".stat.ok.huge .line-chart").peity("line", {
height: 20,
width: 40,
colour: "#37b7f3",
strokeColour: "#757575"
}).show();
$(".stat.ok.huge .bar-chart").peity("bar", {
height: 20,
width: 40,
colour: "#37b7f3"
}).show();
$(".stat.good.huge .line-chart").peity("line", {
height: 20,
width: 40,
colour: "#52e136"
}).show();
$(".stat.good.huge .bar-chart").peity("bar", {
height: 20,
width: 40,
colour: "#52e136"
}).show();
}
var handleDeviceWidth = function () {
function fixWidth(e) {
var winHeight = $(window).height();
var winWidth = $(window).width();
//alert(winWidth);
//for tablet and small desktops
if (winWidth < 1125 && winWidth > 767) {
$(".responsive").each(function () {
var forTablet = $(this).attr('data-tablet');
var forDesktop = $(this).attr('data-desktop');
if (forTablet) {
$(this).removeClass(forDesktop);
$(this).addClass(forTablet);
}
});
} else {
$(".responsive").each(function () {
var forTablet = $(this).attr('data-tablet');
var forDesktop = $(this).attr('data-desktop');
if (forTablet) {
$(this).removeClass(forTablet);
$(this).addClass(forDesktop);
}
});
}
}
fixWidth();
running = false;
jQuery(window).resize(function () {
if (running == false) {
running = true;
setTimeout(function () {
// fix layout width
fixWidth();
// fix calendar width by just reinitializing
handleDashboardCalendar();
if (isMainPage) {
handleDashboardCalendar(); // handles full calendar for main page
} else {
handleCalendar(); // handles full calendars
}
// fix vector maps width
if (isMainPage) {
jQuery('.vmaps').each(function () {
var map = jQuery(this);
map.width(map.parent().parent().width());
});
}
if (isMapPage) {
jQuery('.vmaps').each(function () {
var map = jQuery(this);
map.width(map.parent().width());
});
}
// fix event form chosen dropdowns
$('#event_priority_chzn').width($('#event_title').width() + 15);
$('#event_priority_chzn .chzn-drop').width($('#event_title').width() + 13);
$(".chzn-select").val('').trigger("liszt:updated");
//finish
running = false;
}, 200); // wait for 200ms on resize event
}
});
}
var handleGritterNotifications = function () {
if (!jQuery.gritter) {
return;
}
$('#gritter-sticky').click(function () {
var unique_id = $.gritter.add({
// (string | mandatory) the heading of the notification
title: 'This is a sticky notice!',
// (string | mandatory) the text inside the notification
text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus eget tincidunt velit. Cum sociis natoque penatibus et <a href="#" style="color:#ccc">magnis dis parturient</a> montes, nascetur ridiculus mus.',
// (string | optional) the image to display on the left
image: 'img/avatar-mini.png',
// (bool | optional) if you want it to fade out on its own or just sit there
sticky: true,
// (int | optional) the time you want it to be alive for before fading out
time: '',
// (string | optional) the class name you want to apply to that specific message
class_name: 'my-sticky-class'
});
return false;
});
$('#gritter-regular').click(function () {
$.gritter.add({
// (string | mandatory) the heading of the notification
title: 'This is a regular notice!',
// (string | mandatory) the text inside the notification
text: 'This will fade out after a certain amount of time. Vivamus eget tincidunt velit. Cum sociis natoque penatibus et <a href="#" style="color:#ccc">magnis dis parturient</a> montes, nascetur ridiculus mus.',
// (string | optional) the image to display on the left
image: 'img/avatar-mini.png',
// (bool | optional) if you want it to fade out on its own or just sit there
sticky: false,
// (int | optional) the time you want it to be alive for before fading out
time: ''
});
return false;
});
$('#gritter-max').click(function () {
$.gritter.add({
// (string | mandatory) the heading of the notification
title: 'This is a notice with a max of 3 on screen at one time!',
// (string | mandatory) the text inside the notification
text: 'This will fade out after a certain amount of time. Vivamus eget tincidunt velit. Cum sociis natoque penatibus et <a href="#" style="color:#ccc">magnis dis parturient</a> montes, nascetur ridiculus mus.',
// (string | optional) the image to display on the left
image: 'img/avatar-mini.png',
// (bool | optional) if you want it to fade out on its own or just sit there
sticky: false,
// (function) before the gritter notice is opened
before_open: function () {
if ($('.gritter-item-wrapper').length == 3) {
// Returning false prevents a new gritter from opening
return false;
}
}
});
return false;
});
$('#gritter-without-image').click(function () {
$.gritter.add({
// (string | mandatory) the heading of the notification
title: 'This is a notice without an image!',
// (string | mandatory) the text inside the notification
text: 'This will fade out after a certain amount of time. Vivamus eget tincidunt velit. Cum sociis natoque penatibus et <a href="#" style="color:#ccc">magnis dis parturient</a> montes, nascetur ridiculus mus.'
});
return false;
});
$('#gritter-light').click(function () {
$.gritter.add({
// (string | mandatory) the heading of the notification
title: 'This is a light notification',
// (string | mandatory) the text inside the notification
text: 'Just add a "gritter-light" class_name to your $.gritter.add or globally to $.gritter.options.class_name',
class_name: 'gritter-light'
});
return false;
});
$("#gritter-remove-all").click(function () {
$.gritter.removeAll();
return false;
});
}
var handleTooltip = function () {
jQuery('.tooltips').tooltip();
}
var handlePopover = function () {
jQuery('.popovers').popover();
}
var handleChoosenSelect = function () {
if (!jQuery().chosen) {
return;
}
$(".chosen").chosen();
$(".chosen-with-diselect").chosen({
allow_single_deselect: true
});
}
var handleUniform = function () {
if (!jQuery().uniform) {
return;
}
if (test = $("input[type=checkbox]:not(.toggle), input[type=radio]:not(.toggle)")) {
test.uniform();
}
}
var handleWysihtml5 = function () {
if (!jQuery().wysihtml5) {
return;
}
if ($('.wysihtml5').size() > 0) {
$('.wysihtml5').wysihtml5();
}
}
var handleToggleButtons = function () {
if (!jQuery().toggleButtons) {
return;
}
$('.basic-toggle-button').toggleButtons();
$('.text-toggle-button').toggleButtons({
width: 200,
label: {
enabled: "Lorem Ipsum",
disabled: "Dolor Sit"
}
});
$('.danger-toggle-button').toggleButtons({
style: {
// Accepted values ["primary", "danger", "info", "success", "warning"] or nothing
enabled: "danger",
disabled: "info"
}
});
$('.info-toggle-button').toggleButtons({
style: {
enabled: "info",
disabled: ""
}
});
$('.success-toggle-button').toggleButtons({
style: {
enabled: "success",
disabled: "danger"
}
});
$('.warning-toggle-button').toggleButtons({
style: {
enabled: "warning",
disabled: "success"
}
});
$('.height-toggle-button').toggleButtons({
height: 100,
font: {
'line-height': '100px',
'font-size': '20px',
'font-style': 'italic'
}
});
$('.not-animated-toggle-button').toggleButtons({
animated: false
});
$('.transition-value-toggle-button').toggleButtons({
transitionspeed: 1 // default value: 0.05
});
}
var handleTables = function () {
if (!jQuery().dataTable) {
return;
}
// begin first table
$('#sample_1').dataTable({
"sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
"sPaginationType": "bootstrap",
"oLanguage": {
"sLengthMenu": "_MENU_ records per page",
"oPaginate": {
"sPrevious": "Prev",
"sNext": "Next"
}
},
"aoColumnDefs": [{
'bSortable': false,
'aTargets': [0]
}]
});
jQuery('#sample_1 .group-checkable').change(function () {
var set = jQuery(this).attr("data-set");
var checked = jQuery(this).is(":checked");
jQuery(set).each(function () {
if (checked) {
$(this).attr("checked", true);
} else {
$(this).attr("checked", false);
}
});
jQuery.uniform.update(set);
});
jQuery('#sample_1_wrapper .dataTables_filter input').addClass("input-medium"); // modify table search input
jQuery('#sample_1_wrapper .dataTables_length select').addClass("input-mini"); // modify table per page dropdown
// begin second table
$('#sample_2').dataTable({
"sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
"sPaginationType": "bootstrap",
"oLanguage": {
"sLengthMenu": "_MENU_ per page",
"oPaginate": {
"sPrevious": "Prev",
"sNext": "Next"
}
},
"aoColumnDefs": [{
'bSortable': false,
'aTargets': [0]
}]
});
jQuery('#sample_2 .group-checkable').change(function () {
var set = jQuery(this).attr("data-set");
var checked = jQuery(this).is(":checked");
jQuery(set).each(function () {
if (checked) {
$(this).attr("checked", true);
} else {
$(this).attr("checked", false);
}
});
jQuery.uniform.update(set);
});
jQuery('#sample_2_wrapper .dataTables_filter input').addClass("input-small"); // modify table search input
jQuery('#sample_2_wrapper .dataTables_length select').addClass("input-mini"); // modify table per page dropdown
// begin: third table
$('#sample_3').dataTable({
"sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
"sPaginationType": "bootstrap",
"oLanguage": {
"sLengthMenu": "_MENU_ per page",
"oPaginate": {
"sPrevious": "Prev",
"sNext": "Next"
}
},
"aoColumnDefs": [{
'bSortable': false,
'aTargets': [0]
}]
});
jQuery('#sample_3 .group-checkable').change(function () {
var set = jQuery(this).attr("data-set");
var checked = jQuery(this).is(":checked");
jQuery(set).each(function () {
if (checked) {
$(this).attr("checked", true);
} else {
$(this).attr("checked", false);
}
});
jQuery.uniform.update(set);
});
jQuery('#sample_3_wrapper .dataTables_filter input').addClass("input-small"); // modify table search input
jQuery('#sample_3_wrapper .dataTables_length select').addClass("input-mini"); // modify table per page dropdown
}
var handleDateTimePickers = function () {
if (!jQuery().daterangepicker) {
return;
}
$('.date-range').daterangepicker();
$('#dashboard-report-range').daterangepicker({
ranges: {
'Today': ['today', 'today'],
'Yesterday': ['yesterday', 'yesterday'],
'Last 7 Days': [Date.today().add({
days: -6
}), 'today'],
'Last 30 Days': [Date.today().add({
days: -29
}), 'today'],
'This Month': [Date.today().moveToFirstDayOfMonth(), Date.today().moveToLastDayOfMonth()],
'Last Month': [Date.today().moveToFirstDayOfMonth().add({
months: -1
}), Date.today().moveToFirstDayOfMonth().add({
days: -1
})]
},
opens: 'left',
format: 'MM/dd/yyyy',
separator: ' to ',
startDate: Date.today().add({
days: -29
}),
endDate: Date.today(),
minDate: '01/01/2012',
maxDate: '12/31/2014',
locale: {
applyLabel: 'Submit',
fromLabel: 'From',
toLabel: 'To',
customRangeLabel: 'Custom Range',
daysOfWeek: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
firstDay: 1
},
showWeekNumbers: true,
buttonClasses: ['btn-danger']
},
function (start, end) {
App.blockUI(jQuery("#page"));
setTimeout(function () {
App.unblockUI(jQuery("#page"));
$.gritter.add({
title: 'Dashboard',
text: 'Dashboard date range updated.'
});
App.scrollTo();
}, 1000);
$('#dashboard-report-range span').html(start.toString('MMMM d, yyyy') + ' - ' + end.toString('MMMM d, yyyy'));
});
$('#dashboard-report-range span').html(Date.today().add({
days: -29
}).toString('MMMM d, yyyy') + ' - ' + Date.today().toString('MMMM d, yyyy'));
$('#form-date-range').daterangepicker({
ranges: {
'Today': ['today', 'today'],
'Yesterday': ['yesterday', 'yesterday'],
'Last 7 Days': [Date.today().add({
days: -6
}), 'today'],
'Last 30 Days': [Date.today().add({
days: -29
}), 'today'],
'This Month': [Date.today().moveToFirstDayOfMonth(), Date.today().moveToLastDayOfMonth()],
'Last Month': [Date.today().moveToFirstDayOfMonth().add({
months: -1
}), Date.today().moveToFirstDayOfMonth().add({
days: -1
})]
},
opens: 'right',
format: 'MM/dd/yyyy',
separator: ' to ',
startDate: Date.today().add({
days: -29
}),
endDate: Date.today(),
minDate: '01/01/2012',
maxDate: '12/31/2014',
locale: {
applyLabel: 'Submit',
fromLabel: 'From',
toLabel: 'To',
customRangeLabel: 'Custom Range',
daysOfWeek: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
firstDay: 1
},
showWeekNumbers: true,
buttonClasses: ['btn-danger']
},
function (start, end) {
$('#form-date-range span').html(start.toString('MMMM d, yyyy') + ' - ' + end.toString('MMMM d, yyyy'));
});
$('#form-date-range span').html(Date.today().add({
days: -29
}).toString('MMMM d, yyyy') + ' - ' + Date.today().toString('MMMM d, yyyy'));
if (!jQuery().datepicker || !jQuery().timepicker) {
return;
}
$('.date-picker').datepicker();
$('.timepicker-default').timepicker();
$('.timepicker-24').timepicker({
minuteStep: 1,
showSeconds: true,
showMeridian: false
});
}
var handleColorPicker = function () {
if (!jQuery().colorpicker) {
return;
}
$('.colorpicker-default').colorpicker({
format: 'hex'
});
$('.colorpicker-rgba').colorpicker();
}
var handleAccordions = function () {
$(".accordion").collapse().height('auto');
}
var handleScrollers = function () {
if (!jQuery().slimScroll) {
return;
}
$('.scroller').each(function () {
$(this).slimScroll({
//start: $('.blah:eq(1)'),
height: $(this).attr("data-height"),
alwaysVisible: ($(this).attr("data-always-visible") == "1" ? true : false),
railVisible: ($(this).attr("data-rail-visible") == "1" ? true : false),
disableFadeOut: true
});
});
}
var handleFormWizards = function () {
if (!jQuery().bootstrapWizard) {
return;
}
$('#form_wizard_1').bootstrapWizard({
'nextSelector': '.button-next',
'previousSelector': '.button-previous',
onTabClick: function (tab, navigation, index) {
alert('on tab click disabled');
return false;
},
onNext: function (tab, navigation, index) {
var total = navigation.find('li').length;
var current = index + 1;
// set wizard title
$('.step-title', $('#form_wizard_1')).text('Step ' + (index + 1) + ' of ' + total);
// set done steps
jQuery('li', $('#form_wizard_1')).removeClass("done");
var li_list = navigation.find('li');
for (var i = 0; i < index; i++) {
jQuery(li_list[i]).addClass("done");
}
if (current == 1) {
$('#form_wizard_1').find('.button-previous').hide();
} else {
$('#form_wizard_1').find('.button-previous').show();
}
if (current >= total) {
$('#form_wizard_1').find('.button-next').hide();
$('#form_wizard_1').find('.button-submit').show();
} else {
$('#form_wizard_1').find('.button-next').show();
$('#form_wizard_1').find('.button-submit').hide();
}
App.scrollTo($('.page-title'));
},
onPrevious: function (tab, navigation, index) {
var total = navigation.find('li').length;
var current = index + 1;
// set wizard title
$('.step-title', $('#form_wizard_1')).text('Step ' + (index + 1) + ' of ' + total);
// set done steps
jQuery('li', $('#form_wizard_1')).removeClass("done");
var li_list = navigation.find('li');
for (var i = 0; i < index; i++) {
jQuery(li_list[i]).addClass("done");
}
if (current == 1) {
$('#form_wizard_1').find('.button-previous').hide();
} else {
$('#form_wizard_1').find('.button-previous').show();
}
if (current >= total) {
$('#form_wizard_1').find('.button-next').hide();
$('#form_wizard_1').find('.button-submit').show();
} else {
$('#form_wizard_1').find('.button-next').show();
$('#form_wizard_1').find('.button-submit').hide();
}
App.scrollTo($('.page-title'));
},
onTabShow: function (tab, navigation, index) {
var total = navigation.find('li').length;
var current = index + 1;
var $percent = (current / total) * 100;
$('#form_wizard_1').find('.bar').css({
width: $percent + '%'
});
}
});
$('#form_wizard_1').find('.button-previous').hide();
$('#form_wizard_1 .button-submit').click(function () {
alert('Finished!');
}).hide();
}
var handleTagsInput = function () {
if (!jQuery().tagsInput) {
return;
}
$('#tags_1').tagsInput({
width: 'auto'
});
$('#tags_2').tagsInput({
width: 240
});
}
var handleGoTop = function () {
/* set variables locally for increased performance */
jQuery('#footer .go-top').click(function () {
App.scrollTo();
});
}
// this is optional to use if you want animated show/hide. But plot charts can make the animation slow.
var handleSidebarTogglerAnimated = function () {
$('.sidebar-toggler').click(function () {
if ($('#sidebar > ul').is(":visible") === true) {
$('#main-content').animate({
'margin-left': '25px'
});
$('#sidebar').animate({
'margin-left': '-190px'
}, {
complete: function () {
$('#sidebar > ul').hide();
$("#container").addClass("sidebar-closed");
}
});
} else {
$('#main-content').animate({
'margin-left': '215px'
});
$('#sidebar > ul').show();
$('#sidebar').animate({
'margin-left': '0'
}, {
complete: function () {
$("#container").removeClass("sidebar-closed");
}
});
}
})
}
// by default used simple show/hide without animation due to the issue with handleSidebarTogglerAnimated.
var handleSidebarToggler = function () {
$('.sidebar-toggler').click(function () {
if ($('#sidebar > ul').is(":visible") === true) {
$('#main-content').css({
'margin-left': '25px'
});
$('#sidebar').css({
'margin-left': '-190px'
});
$('#sidebar > ul').hide();
$("#container").addClass("sidebar-closed");
} else {
$('#main-content').css({
'margin-left': '215px'
});
$('#sidebar > ul').show();
$('#sidebar').css({
'margin-left': '0'
});
$("#container").removeClass("sidebar-closed");
}
})
}
return {
//main function to initiate template pages
init: function () {
if (jQuery.browser.msie && jQuery.browser.version.substr(0, 1) == 8) {
isIE8 = true; // checkes for IE8 browser version
$('.visible-ie8').show();
}
handleDeviceWidth(); // handles proper responsive features of the page
handleChoosenSelect(); // handles bootstrap chosen dropdowns
if (isMainPage) {
handleDashboardCharts(); // handles plot charts for main page
handleJQVMAP(); // handles vector maps for home page
handleDashboardCalendar(); // handles full calendar for main page
handleChat() // handles dashboard chat
} else {
handleCalendar(); // handles full calendars
handlePortletSortable(); // handles portlet draggable sorting
}
if (isMapPage) {
handleAllJQVMAP(); // handles vector maps for interactive map page
}
handleScrollers(); // handles slim scrolling contents
handleUniform(); // handles uniform elements
handleClockfaceTimePickers(); //handles form clockface timepickers
handleTagsInput() // handles tag input elements
handleTables(); // handles data tables
handleCharts(); // handles plot charts
handleWidgetTools(); // handles portlet action bar functionality(refresh, configure, toggle, remove)
handlePulsate(); // handles pulsate functionality on page elements
handlePeity(); // handles pierty bar and line charts
handleGritterNotifications(); // handles gritter notifications
handleTooltip(); // handles bootstrap tooltips
handlePopover(); // handles bootstrap popovers
handleToggleButtons(); // handles form toogle buttons
handleWysihtml5(); //handles WYSIWYG Editor
handleDateTimePickers(); //handles form timepickers
handleColorPicker(); // handles form color pickers
handleFancyBox(); // handles fancy box image previews
handleStyler(); // handles style customer tool
handleMainMenu(); // handles main menu
handleFixInputPlaceholderForIE(); // fixes/enables html5 placeholder attribute for IE9, IE8
handleGoTop(); //handles scroll to top functionality in the footer
handleAccordions();
handleFormWizards();
handleSidebarToggler();
if (isMainPage) { // this is for demo purpose. you may remove handleIntro function for your project
handleIntro();
}
},
// login page setup
initLogin: function () {
handleLoginForm();
handleFixInputPlaceholderForIE();
},
// wrapper function for page element pulsate
pulsate: function (el, options) {
var opt = jQuery.extend(options, {
color: '#d12610', // set the color of the pulse
reach: 15, // how far the pulse goes in px
speed: 300, // how long one pulse takes in ms
pause: 0, // how long the pause between pulses is in ms
glow: false, // if the glow should be shown too
repeat: 1, // will repeat forever if true, if given a number will repeat for that many times
onHover: false // if true only pulsate if user hovers over the element
});
jQuery(el).pulsate(opt);
},
// wrapper function to scroll to an element
scrollTo: function (el) {
pos = el ? el.offset().top : 0;
jQuery('html,body').animate({
scrollTop: pos
}, 'slow');
},
// wrapper function to block element(indicate loading)
blockUI: function (el, loaderOnTop) {
lastBlockedUI = el;
jQuery(el).block({
message: '<img src="img/loading.gif" align="absmiddle">',
css: {
border: 'none',
padding: '2px',
backgroundColor: 'none'
},
overlayCSS: {
backgroundColor: '#000',
opacity: 0.05,
cursor: 'wait'
}
});
},
// wrapper function to un-block element(finish loading)
unblockUI: function (el) {
jQuery(el).unblock({
onUnblock: function () {
jQuery(el).removeAttr("style");
}
});
},
// set main page
setMainPage: function (flag) {
isMainPage = flag;
},
// set map page
setMapPage: function (flag) {
isMapPage = flag;
}
};
//input mask
$('.inputmask').inputmask();
}();
//tooltips
$('.element').tooltip();
// Slider input js
try{
jQuery("#Slider1").slider({ from: 5, to: 50, step: 2.5, round: 1, dimension: ' $', skin: "round_plastic" });
jQuery("#Slider2").slider({ from: 5000, to: 150000, heterogeneity: ['50/50000'], step: 1000, dimension: ' $', skin: "round_plastic" });
jQuery("#Slider3").slider({ from: 1, to: 30, heterogeneity: ['50/5', '75/15'], scale: [1, '|', 3, '|', '5', '|', 15, '|', 30], limits: false, step: 1, dimension: '', skin: "round_plastic" });
jQuery("#Slider4").slider({ from: 480, to: 1020, step: 15, dimension: '', scale: ['8:00', '9:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00'], limits: false, skin: "round_plastic", calculate: function( value ){
var hours = Math.floor( value / 60 );
var mins = ( value - hours*60 );
return (hours < 10 ? "0"+hours : hours) + ":" + ( mins == 0 ? "00" : mins );
}});
} catch (e){
errorMessage(e);
}
//knob
//$(".knob").knob();
| JavaScript |
$(function() {
var app;
_.templateSettings = {
interpolate : /\{\{(.+?)\}\}/g, // print value: {{ value_name }}
evaluate : /\{%([\s\S]+?)%\}/g, // excute code: {% code_to_execute %}
escape : /\{%-([\s\S]+?)%\}/g
}; // excape H
app = {
pageIndex: [0, 0, 0],
page: 15,
tabIndex: 0,
ajaxLoading: true,
schemeListData : [],
angle : 0,
photoIndex : 0,
isBind : true,
initialize: function() {
this.initDomNode();
this.bindEvents();
},
initDomNode: function() {
this.schemeManage = $('#schemeManage');
this.schemeBody = $('.scheme-body', this.schemeManage);
this.schemeInput = $('.scheme-input', this.schemeManage);
this.schemeSearch = $('.scheme-search', this.schemeManage);
this.schemeTree = $('.scheme-tree', this.schemeManage);
this.schemeTab = $('.scheme-tab', this.schemeManage);
this.schemeSummary = $('.scheme-summary', this.schemeManage);
this.schemeMoney = $('.scheme-money', this.schemeManage);
this.schemeList = $('.scheme-list', this.schemeManage);
this.rmPic = $('.remove-picture', this.schemeManage);
this.bdPic = $('.bind-picture', this.schemeManage);
this.schemeChecked = $('.scheme-checked', this.schemeManage);
this.schemePicBtn = $('.scheme-pic-btn', this.schemeManage);
this.reimbursementTree = $('.scheme-tree', this.schemeManage);
this.schemeReviewBtn = $('.scheme-review', this.schemeManage);
this.schemeSelect = $('.scheme-select', this.schemeManage);
this.schemeUploadBtn = $('.scheme-upload', this.schemeManage);
this.loading = $('#dataLoading');
this.uploadForm = $('#uploadSchemeForm');
this.confrimUploadBtn = $('#confrim-upload');
this.popup = $('#myModal');
},
bindEvents: function() {
var that;
that = this;
this.schemeSearch.on('click', function() { //执行案搜索菜单
that.loading.show();
that.requestSchemeTree();
});
// this.schemeInput.on('keyup', function(e) { //执行案搜索菜单
// e.stopPropagation();
// if (e.keyCode == 13) {
// that.loading.show();
// that.requestSchemeTree();
// }
// });
this.schemeInput.on('keydown', function(e) { //执行案搜索菜单
e.stopPropagation();
if (e.keyCode == 13) {
that.loading.show();
that.requestSchemeTree();
e.preventDefault();
return false;
}
});
this.schemeTree.on('click', 'dt, dd', function(e) { //请求执行案id对应的图片列表 根节点为1 二级节点为2
var val;
if (e.target != this) {
return;
}
val = $.trim($(this).text());
that.schemeId = val;
that.schemeTab.find('li').first().addClass('active').siblings().removeClass('active');
$(this).addClass('on').siblings().removeClass('on');
that.loading.show();
e.target.tagName.toUpperCase() == 'DT' ? that.requestSchemeList(val, 1) : that.requestSchemeList(val, 2);
});
this.rmPic.on('click', function() { //删除图片
that.loading.show();
that.removePic();
});
this.bdPic.on('click', function() { //绑定图片
that.loading.show();
that.bindPic();
});
this.schemeTab.on('click', 'a', function(e) { //图片类型Tab切换
e.preventDefault();
that.switchTab($(this));
});
this.schemeChecked.on('change', function() { //全选图片
$('input:checkbox', this.schemeList).prop('checked', $(this).is(':checked'));
});
this.schemeList.on('change', 'input:checkbox', function() { //图片列表中checkbox
var checked;
checked = $(this).is(':checked');
!checked && that.schemeChecked.prop('checked', checked);
});
this.schemePicBtn.on('click', 'button', function() {
var isBind;
that.loading.show();
isBind = $(this).hasClass('pic-bind-ok');
that.isBind = isBind;
that.schemeList.empty();
that.schemeTab.find('li').first().addClass('active').siblings().removeClass('active');
isBind ? that.requestSchemeList() : that.requestunBindSchemeList();
isBind ? that.bdPic.hide() : that.bdPic.css('display', 'inline-block');
});
$(window).scroll(function(){
that.loadMoreCase();
});
this.schemeList.on('click', 'a', function(e){
e.preventDefault();
that.angle = 0;
that.photoIndex = $(this).closest('li').index();
$('img', that.popup).css({
WebkitTransform : 'rotate(0deg)',
MozTransform : 'rotate(0deg)',
MsTransform : 'rotate(0deg)',
OTransform : 'rotate(0deg)',
transform : 'rotate(0deg)'
});
that.popup.find('img').prop('src', $(this).children('img').prop('src'));
});
this.popup.on('click', 'a', function(e){
var action;
e.preventDefault();
action = $(this).data('action');
action = action.replace(/^\w/, function(str){
return str.toUpperCase();
});
that['pic'+action] && that['pic'+action]();
});
this.schemeList.on('click', '.edit-money', function(){
that.editMoney($(this));
});
this.schemeList.on('click', '.update-money', function(){
that.updateMoney($(this));
});
this.schemeList.on('click', '.to-location-pic', function(){
that.toLocationPic($(this));
});
this.schemeList.on('click', '.to-unlocation-pic', function(){
that.toUnLocationPic($(this));
});
this.uploadForm.find('input').on('change', function(e){
console.log(e);
if(e.target.files[0].size > 10240 * 1000){
alert('所选文件体积不得超过 10MB!');
return
}
if(e.target.files[0].type.indexOf('exe')!=-1 || e.target.files[0].type.indexOf('dll')!=-1){
alert('文件类型不合法!');
return;
}
that.uploadSchemeFormFile = e.target.files[0];
});
this.confrimUploadBtn.on('click', function(e){
e.preventDefault();
that.uploadSchemePic();
});
this.schemeManage.on('click', '.scheme-rm', function(){
that.rmScheme();
});
},
sendToServer: function(opt) {
var base, url, type, that;
that = this;
base = 'http://218.89.135.237:9000/API/WEB/';
url = base + opt.apiName;
type = opt.type ? opt.type : 'GET';
$.ajax({
type: type,
url: url,
async: true,
data: opt.data,
// timeout: 15000,
dataType: 'json'
}).done(function(data) {
// console.log(data);
if (data.IsSuccessfully) {
opt.success && opt.success(data);
} else {
opt.error && opt.error(data);
alert(data.ErrorMessage);
}
that.loading.hide();
}).fail(function(xhr, ajaxOptions, thrownError) {
// console.log(arguments);
that.loading.hide();
alert('error code: ' + xhr.status + '\n ajaxOptions:' + ajaxOptions + '\n message: ' + thrownError + '\n APIName:' + opt.apiName);
});
},
sendFileToServer: function(opt) {
var base, url, type, that;
that = this;
base = 'http://218.89.135.237:9000/API/WEB/';
url = base + opt.apiName;
type = opt.type ? opt.type : 'GET';
$.ajax({
type: type,
url: url,
async: true,
data: opt.data,
processData: false,
contentType: false
// timeout: 15000,
// dataType: 'json'
}).done(function(data) {
// console.log(data);
if (data.IsSuccessfully) {
opt.success && opt.success(data);
} else {
opt.error && opt.error(data);
alert(data.ErrorMessage);
}
that.loading.hide();
}).fail(function(xhr, ajaxOptions, thrownError) {
// console.log(arguments);
that.loading.hide();
alert('error code: ' + xhr.status + '\n ajaxOptions:' + ajaxOptions + '\n message: ' + thrownError + '\n APIName:' + opt.apiName);
});
},
requestSchemeTree: function() {
var that, opt, id;
id = $.trim(this.schemeInput.val());
this.rootId = id;
opt = {
apiName: 'SchemeManagement/GetSchemeDetailList.ashx',
data: {
schemeID: id
},
success: this.schemeTreeSuccess.bind(this)
};
this.sendToServer(opt);
},
schemeTreeSuccess: function(data) {
data.id = this.rootId;
this.schemeTree.html(_.template($('#schemeTreeTmpl').html(), data));
},
requestSchemeList: function(id, level) {
var opt;
id = id || this.schemeId;
if(id==null || id ==''){
this.loading.hide();
return;
}
level = level || (id.indexOf('-') != -1 ? 2 : 1);
this.schemeUploadBtn.toggle(level == 2);
opt = {
apiName: 'SchemeManagement/GetSchemeDetailInfo.ashx',
data: {
schemeID: id,
levelID: level
},
success: this.schemeListSuccess.bind(this)
};
// this.ajaxLoading = false;
this.sendToServer(opt);
},
requestunBindSchemeList: function(id) {
var opt;
id = id || this.rootId;
if(id==null || id ==''){
this.loading.hide();
return;
}
id = id.split('-')[0];
opt = {
apiName: 'SchemeManagement/GetUnbindingPictures.ashx',
data: {
schemeID: id
},
success: this.schemeListSuccess.bind(this)
};
this.schemeUploadBtn.hide();
// this.ajaxLoading = false;
this.sendToServer(opt);
},
schemeListSuccess: function(data) {
var page;
data.schemeId = this.schemeId;
this.paging(data); //分页
this.schemeList.empty();
if(this.isBind){
this.schemeMoney.empty();
this.schemeSummary.empty();
}
this.schemeList.html(_.template($('#schemeListTmpl').html(), {
initIndex : 0,
Pictures: this.schemeListData[0][0]
}));
this.schemeBody.show();
// this.schemeList.addClass('type'+this.tabIndex);
this.pageIndex = [0, 0, 0];
// this.photoIndex = 0;
this.schemeChecked.prop('checked', false).parent().removeClass('checked');
this.schemeTab.find('li').first().addClass('active').siblings().removeClass('active');
data.SchemeDetailInfo && this.setSchemeSummary(data.SchemeDetailInfo);
data.TotalPictureCount && this.schemeMoney.html(_.template($('#schemeMoneyTmpl').html(), data));
},
paging: function(data) {
this.handlePaging(data.PricePicture, 0);
this.handlePaging(data.LocationPicture, 1);
this.handlePaging(data.NoLocationPicture, 2);
this.handlePaging(data.uploadFiles, 3);
},
handlePaging:function(data, index){
var arr, result, page;
arr = [];
result = [];
page = this.page;
if (!data) {
return;
}
for (var i = 0, l = data.length; i < l;) {
arr.push(data[i]);
i++;
if (i % page == 0 || i == l) {
result.push(arr);
arr = [];
}
}
// console.log(result);
this.schemeListData[index] = result;
},
setSchemeSummary: function(str) {
var arr, kv, data, key, val;
arr = [];
key = [];
val = [];
if (str != null && str != '') {
arr = str.split(',');
for (var i = 0, l = arr.length; i < l; i++) {
kv = arr[i].split(':');
key.push(kv[0]);
val.push(kv[1]);
}
}
data = {
key: key,
val: val
};
this.schemeSummary.html(_.template($('#schemeSummaryTmpl').html(), data));
},
getCheckedPic: function() {
var arr, pic, status;
arr = [];
pic = [];
status = false;
$('input:checked', this.schemeList).each(function(index, item) {
arr.push($(item).val());
pic.push($(item));
status = !status ? $(item).data('status') == '已审核' : status;
});
// console.log(arr);
this.checkedPic = pic;
this.checkedPicStatus = status;
return arr;
},
removePic: function() {
var opt, id;
id = this.getCheckedPic();
if(this.checkedPicStatus){
alert('当前选择中包含已审核项目,不能删除!');
this.loading.hide();
return;
}
opt = {
apiName: 'SchemeManagement/DeleteSchemePicture.ashx',
data: {
pictureID: id.join(',')
},
type:'POST',
success: this.removePicSuccess.bind(this)
};
this.sendToServer(opt);
},
removePicSuccess: function(data) {
var pic;
pic = this.checkedPic;
for (var i = 0, l = pic.length; i < l; i++) {
pic[i].closest('.thumbnail').parent().remove();
}
alert('成功删除图片!');
this.requestSchemeList();
},
bindPic: function() {
var opt;
data = this.getCheckedPic();
opt = {
apiName: 'SchemeManagement/BindingPicture.ashx',
data: {
schemeDetailID: this.schemeId,
pictureID: data.join(',')
},
type:'POST',
success: this.bindPicSuccess.bind(this)
};
this.sendToServer(opt);
},
bindPicSuccess: function(data) {
alert('成功绑定图片!');
this.schemeTab.find('li').first().addClass('active').siblings().removeClass('active');
this.requestunBindSchemeList();
},
switchTab: function(target) {
var index, arr;
index = target.parent().index();
// this.photoIndex=0;
if(!this.schemeListData[0]){
return;
}
target.parent().addClass('active').siblings().removeClass('active');
this.schemeChecked.prop('checked', false).parent().removeClass('checked');
this.tabIndex = index;
this.pageIndex[index] = 0;
this.schemeList.html(_.template($('#schemeListTmpl').html(), {
initIndex : 0,
Pictures: this.schemeListData[index][0]
}));
},
loadMoreCase:function(){
var scrollBottom;
scrollBottom = $(document).height() - $(window).height() - $(window).scrollTop();
if(scrollBottom < 50){
// if(this.ajaxLoading){
// return;
// }
// this.ajaxLoading = true;
this.pageIndex[this.tabIndex]++;
this.renderPage();
// this.ajaxLoading = false;
}
},
renderPage:function(){
var index, data, len;
index = this.pageIndex[this.tabIndex];
data = this.schemeListData[this.tabIndex] && this.schemeListData[this.tabIndex][index];
if(!data){
return;
}
len = this.schemeList.find('.span4').length;
this.schemeList.append(_.template($('#schemeListTmpl').html(), {initIndex:len, Pictures:data}));
},
picTurnLeft:function(){
this.angle-=45;
this.turnPic();
},
picTurnRight:function(){
this.angle+=45;
this.turnPic();
},
turnPic:function(){
// console.log(this.angle);
$('img', this.popup).css({
WebkitTransform : 'rotate('+this.angle+'deg)',
MozTransform : 'rotate('+this.angle+'deg)',
MsTransform : 'rotate('+this.angle+'deg)',
OTransform : 'rotate('+this.angle+'deg)',
transform : 'rotate('+this.angle+'deg)'
});
},
picPrev:function(){
if(this.photoIndex<=0){
alert('亲,已经是第一张图片了');
return;
}
this.photoIndex-=1;
this.picShow();
},
picNext:function(){
if(this.photoIndex>=this.schemeList.find('li').length-1){
alert('亲,已经是最后一张图片了');
return;
}
this.photoIndex+=1;
this.picShow();
},
picShow:function(){
var src;
src = this.schemeList.find('li').eq(this.photoIndex).find('img').prop('src');
this.popup.find('img').prop('src', src);
},
editMoney:function(target){
var m1, num, input, editBtn, updateBtn;
m1 = target.closest('.caption').find('.item-price');
num = $.trim(m1.find('strong').text());
input = target.closest('.caption').find('.price-input');
editBtn = target.closest('.caption').find('.edit-money');
updateBtn = target.closest('.caption').find('.update-money');
this.moneyField = m1;
this.moneyInput = input;
this.editMoneyBtn = editBtn;
this.updateMoneyBtn = updateBtn;
editBtn.hide();
m1.hide();
input.val(num).show();
updateBtn.css({display:'inline-block'});
},
updateMoney:function(target){
var opt, input, id, money, re;
re = /^(([1-9]{1}\d*)|([0]{1}))(\.(\d){1,2})?$/;
id = target.data('id');
input = target.closest('.caption').find('.price-input');
money = $.trim(input.val());
if(money =='' || !re.test(money)){
alert('输入的金额格式不正确,请检查!');
return;
}
this.money = money;
opt = {
apiName: 'ApplyForReimbursement/ModifyPicturePrice.ashx',
data: {
pictureID: id,
price : money
},
success: this.updateMoneySuccess.bind(this)
};
this.sendToServer(opt);
},
updateMoneySuccess:function(data){
this.moneyField.html('金额:¥ <strong>'+this.money+'</strong>').show();
this.moneyInput.hide();
this.editMoneyBtn.show();
this.updateMoneyBtn.hide();
alert('更新金额成功!');
},
toLocationPic:function(target){
var opt, id, type;
id = target.data('id');
type = target.data('pic-type');
opt = {
apiName: 'SchemeManagement/ChangePictureType.ashx',
data: {
pictureID: id,
currentPictureType : type,
targetPictureType : 0
},
success: this.toLocationPicSuccess.bind(this)
};
this.sendToServer(opt);
},
toLocationPicSuccess:function(data){
alert('已成功切换到定位照片!');
this.requestSchemeList();
},
toUnLocationPic:function(target){
var opt, id, type;
id = target.data('id');
type = target.data('pic-type');
opt = {
apiName: 'SchemeManagement/ChangePictureType.ashx',
data: {
pictureID: id,
currentPictureType : type,
targetPictureType : 2
},
success: this.toUnLocationPicSuccess.bind(this)
};
this.sendToServer(opt);
},
toUnLocationPicSuccess:function(data){
alert('已成功切换到非定位照片!');
this.requestSchemeList();
},
uploadSchemePic:function(){
var form, opt, file;
if(!this.uploadSchemeFormFile){
alert('请选择需要上传的文件!');
return;
}
form = new FormData();
note = $.trim(this.uploadForm.find('textarea').val());
form.append('schemeDetailID', this.schemeId);
form.append('file', this.uploadSchemeFormFile);
form.append('remark', note);
opt = {
apiName: 'SchemeManagement/UploadFile.ashx',
data: form,
type:'POST',
success: this.uploadSchemePicSuccess.bind(this)
};
this.sendFileToServer(opt);
},
uploadSchemePicSuccess:function(){
alert('提交成功!');
$('#uploadSchemePic').modal('hide');
this.requestSchemeList();
this.uploadSchemeFormFile = null;
},
rmScheme:function(){
var opt, id;
id = this.schemeId;
opt = {
apiName: 'SchemeManagement/DeleteSchemeDetailInfo.ashx',
data: {
schemeDetailID: id
},
success: this.rmSchemeSuccess.bind(this)
};
this.sendToServer(opt);
},
rmSchemeSuccess:function(){
alert('删除方案成功!');
this.schemeBody.hide();
this.schemeSummary.empty();
this.schemeList.empty();
this.schemeMoney.empty();
this.schemeSearch.click();
}
};
app.initialize();
return app;
}); | JavaScript |
/**
* Unicorn Admin Template
* Diablo9983 -> diablo9983@gmail.com
**/
$(document).ready(function(){
$('input[type=checkbox],input[type=radio],input[type=file]').uniform();
// $('select').select2();
$('.colorpicker').colorpicker();
$('.datepicker').datepicker();
});
| JavaScript |
$(function() {
var app;
_.templateSettings = {
interpolate : /\{\{(.+?)\}\}/g, // print value: {{ value_name }}
evaluate : /\{%([\s\S]+?)%\}/g, // excute code: {% code_to_execute %}
escape : /\{%-([\s\S]+?)%\}/g
}; // excape H
app = {
pageIndex: [0, 0, 0, 0, 0],
pageInfoIndex:[0],
page: 15,
tabIndex: 0,
ajaxLoading: true,
infoListData:[],
picListData : [],
infoDate:[],
angle : 0,
photoIndex : 0,
isBind : true,
initialize: function() {
this.initDomNode();
this.bindEvents();
this.requestUserCity();
$('#datepicker').datepicker({
language: "zh-CN",
weekStart: 7,
todayHighlight: true,
autoclose: true
});
},
initDomNode: function() {
this.box = $('#infoSearch');
this.resultBox = $('.result-box', this.box);
this.searchBtn = $('.info-search-btn', this.box);
this.sellerName = $('.seller-name', this.box);
this.sellerCity = $('.seller-city', this.box);
this.clientName = $('.client-name', this.box);
this.picTimeStart = $('.pic-time-start', this.box);
this.picTimeEnd = $('.pic-time-end', this.box);
this.infoListTable = $('.info-list-table', this.box);
this.pageInfoTable = $('.page-info-table', this.box);
this.pageStatis = $('.page-statis', this.box);
this.picList = $('.pic-list', this.box);
this.loading = $('#dataLoading');
this.cityList = $('#city-list');
this.confirmCity = $('#confirm-city');
this.cityBtn = $('#city-list-btn');
this.popup = $('#myModal');
this.schemeTab = $('.scheme-tab', this.box);
},
bindEvents: function() {
var that;
that = this;
this.searchBtn.on('click', function() { //执行案搜索菜单
that.loading.show();
that.infoListTable.empty();
that.resultBox.addClass('hide fade');
that.requestInfoList(true);
});
this.infoListTable.on('click', '.rm-info-btn', function(e){
e.preventDefault();
that.loading.show();
that.rmInfo($(this).data('id'));
});
this.pageInfoTable.on('click', function(e){
var index;
e.preventDefault();
index = that.pageInfoIndex[0];
$(this).hasClass('prev') ? index-- : index++;
if(index <0){
index = 0;
alert('亲,已经是第一页了!');
}
if(index > that.pages){
index = that.pages;
alert('亲,已经是最后一页了!');
}
that.pageInfoIndex[0] = index;
that.navToPage();
});
this.infoListTable.on('click', '.view-pic-btn', function(e){
var id;
id = $(this).data('id');
that.loading.show();
that.requestPicList(id);
that.searchId = id;
});
this.picList.on('click', 'a', function(e){
e.preventDefault();
that.angle = 0;
that.photoIndex = $(this).closest('li').index();
$('img', that.popup).css({
WebkitTransform : 'rotate(0deg)',
MozTransform : 'rotate(0deg)',
MsTransform : 'rotate(0deg)',
OTransform : 'rotate(0deg)',
transform : 'rotate(0deg)'
});
that.popup.find('img').prop('src', $(this).children('img').prop('src'));
});
this.popup.on('click', 'a', function(e){
var action;
e.preventDefault();
action = $(this).data('action');
action = action.replace(/^\w/, function(str){
return str.toUpperCase();
});
that['pic'+action] && that['pic'+action]();
});
this.schemeTab.on('click', 'a', function(e) { //图片类型Tab切换
e.preventDefault();
that.switchTab($(this));
});
this.picList.on('click', '.rm-pic', function() { //删除图片
that.loading.show();
that.removePic($(this).data('id'));
});
this.sellerCity.on('focus', function(){
that.cityBtn.trigger('click');
});
this.confirmCity.on('click', function(){
that.setCityVal();
});
$(window).scroll(function(){
that.loadMoreCase();
});
},
sendToServer: function(opt) {
var base, url, type, that;
that = this;
base = 'http://218.89.135.237:9000/API/WEB/';
url = base + opt.apiName;
type = opt.type ? opt.type : 'GET';
$.ajax({
type: type,
url: url,
async: true,
data: opt.data,
// timeout: 15000,
dataType: 'json'
}).done(function(data) {
// console.log(data);
if (data.IsSuccessfully) {
opt.success && opt.success(data);
} else {
opt.error && opt.error(data);
alert(data.ErrorMessage);
}
that.loading.hide();
}).fail(function(xhr, ajaxOptions, thrownError) {
// console.log(arguments);
that.loading.hide();
alert('error code: ' + xhr.status + '\n ajaxOptions:' + ajaxOptions + '\n message: ' + thrownError + '\n APIName:' + opt.apiName);
});
},
verFormData:function(){
var status, data;
status = true;
data = this.getFormData();
for(var item in data){
if(item == 'city' || item == 'clientName' || item == 'startDate' || item == 'endDate'){
continue;
}
status = status && data[item] != '';
}
return status;
},
getFormData:function(){
var startDate, endDate;
startDate = $.trim(this.picTimeStart.val());
endDate = $.trim(this.picTimeEnd.val());
return {
salesCompanyName : $.trim(this.sellerName.val()),
city : $.trim(this.sellerCity.val()),
clientName : $.trim(this.clientName.val()),
startDate : this.formatTime(startDate),
endDate : this.formatTime(endDate)
}
},
formatTime:function(str){
var arr;
arr = [];
if(str == ''){
return;
}
arr = str.split(/\D/);
arr.splice(3,1);
return arr.join('-');
},
requestInfoList:function(isTrigger){
var opt, data;
if(isTrigger){
if(!this.verFormData()){
alert('经销商名称不能为空!');
this.loading.hide();
return;
}
}
data = this.getFormData();
this.initData = data;
this.infoDate = [data.startDate, data.endDate];
opt = {
apiName: 'ClientManagement/SearchClientInfo.ashx',
data: data,
success: this.infoListSuccess.bind(this)
};
this.sendToServer(opt);
},
infoListSuccess:function(data){
this.infoTablePaging(data); //分页
this.infoListTable.html(_.template($('#infoListTableTmpl').html(), {
ImportClients: this.infoListData[0][0]
}));
this.pageIndex = [0];
this.upatePageStatis();
this.resultBox.removeClass('hide fade');
},
upatePageStatis:function(){
this.pageStatis.html('第'+(this.pageInfoIndex[0] +1) +'页 共'+(this.pages+1)+'页');
},
navToPage:function(){
this.infoListTable.html(_.template($('#infoListTableTmpl').html(), {
ImportClients: this.infoListData[0][this.pageInfoIndex[0]]
}));
this.upatePageStatis();
},
rmInfo:function(id){
var opt;
opt = {
apiName: 'ClientManagement/DeleteClientInfo.ashx',
data: {clientMaterialID : id},
success: this.rmInfoSuccess.bind(this)
};
this.sendToServer(opt);
},
rmInfoSuccess: function(data){
alert('删除操作已成功!');
this.requestInfoList();
},
infoTablePaging:function(data){
this.handleInfoTablePaging(data.ImportClients, 0);
},
handleInfoTablePaging:function(data, index){
var arr, result, page;
arr = [];
result = [];
page = 5;
if (!data) {
return;
}
for (var i = 0, l = data.length; i < l;) {
arr.push(data[i]);
i++;
if (i % page == 0 || i == l) {
result.push(arr);
arr = [];
}
}
this.pages = result.length - 1 ; //此处从0开始计算
// console.log(result);
this.infoListData[index] = result;
},
requestPicList:function(id){
var opt;
id = id || this.searchId;
opt = {
apiName: 'ClientManagement/GetSingleClientPictures.ashx',
data: {
clientMaterialID : id,
startDate : this.infoDate[0],
endDate : this.infoDate[1]
},
success: this.picListSuccess.bind(this)
};
this.picList.empty();
this.sendToServer(opt);
},
picListSuccess: function(data){
this.groupPicList(data);
this.picList.html(_.template($('#picListTmpl').html(), {
initIndex : 0,
ClientPictures: this.picListData[0][0]
}));
this.pageIndex = [0, 0, 0, 0, 0];
this.schemeTab.find('li').first().addClass('active').siblings().removeClass('active');
},
groupPicList:function(data){ //分组图片数据
var arr;
arr = [[], [], [], [], []];
_.each(data.ClientPictures, function(item){
arr[item.PictureType].push(item);
});
// console.log(arr);
// this.picListData = arr;
this.paging(arr);
},
paging: function(data) {
this.handlePaging(data[0], 0);
this.handlePaging(data[1], 1);
this.handlePaging(data[2], 2);
this.handlePaging(data[3], 3);
this.handlePaging(data[4], 4);
},
handlePaging:function(data, index){
var arr, result, page;
arr = [];
result = [];
page = this.page;
if (!data) {
return;
}
for (var i = 0, l = data.length; i < l;) {
arr.push(data[i]);
i++;
if (i % page == 0 || i == l) {
result.push(arr);
arr = [];
}
}
// console.log(result);
this.picListData[index] = result;
},
setSchemeSummary: function(str) {
var arr, kv, data, key, val;
arr = [];
key = [];
val = [];
if (str != null && str != '') {
arr = str.split(',');
for (var i = 0, l = arr.length; i < l; i++) {
kv = arr[i].split(':');
key.push(kv[0]);
val.push(kv[1]);
}
}
data = {
key: key,
val: val
};
this.schemeSummary.html(_.template($('#schemeSummaryTmpl').html(), data));
},
getCheckedPic: function() {
var arr, pic, status;
arr = [];
pic = [];
status = false;
$('input:checked', this.schemeList).each(function(index, item) {
arr.push($(item).val());
pic.push($(item));
status = !status ? $(item).data('status') == '已审核' : status;
});
// console.log(arr);
this.checkedPic = pic;
this.checkedPicStatus = status;
return arr;
},
removePic: function(id) {
var opt;
opt = {
apiName: 'ClientManagement/DeletePicture.ashx',
data: {
pictureID: id
},
success: this.removePicSuccess.bind(this)
};
this.sendToServer(opt);
},
removePicSuccess: function(data) {
alert('成功删除图片!');
this.requestPicList();
},
switchTab: function(target) {
var index, arr;
index = target.parent().index();
// this.photoIndex=0;
if(!this.picListData[0]){
return;
}
target.parent().addClass('active').siblings().removeClass('active');
this.tabIndex = index;
this.pageIndex[index] = 0;
this.picList.html(_.template($('#picListTmpl').html(), {
initIndex : 0,
ClientPictures: this.picListData[index][0]
}));
},
loadMoreCase:function(){
var scrollBottom;
scrollBottom = $(document).height() - $(window).height() - $(window).scrollTop();
if(scrollBottom < 50){
// if(this.ajaxLoading){
// return;
// }
// this.ajaxLoading = true;
// console.log('xxx');
this.pageIndex[this.tabIndex]++;
this.renderPage();
// this.ajaxLoading = false;
}
},
renderPage:function(){
var index, data, len;
index = this.pageIndex[this.tabIndex];
data = this.picListData[this.tabIndex] && this.picListData[this.tabIndex][index];
if(!data){
return;
}
len = this.picList.find('.span3').length;
this.picList.append(_.template($('#picListTmpl').html(), {initIndex:len, ClientPictures:data}));
},
picTurnLeft:function(){
this.angle-=45;
this.turnPic();
},
picTurnRight:function(){
this.angle+=45;
this.turnPic();
},
turnPic:function(){
// console.log(this.angle);
$('img', this.popup).css({
WebkitTransform : 'rotate('+this.angle+'deg)',
MozTransform : 'rotate('+this.angle+'deg)',
MsTransform : 'rotate('+this.angle+'deg)',
OTransform : 'rotate('+this.angle+'deg)',
transform : 'rotate('+this.angle+'deg)'
});
},
picPrev:function(){
if(this.photoIndex<=0){
alert('亲,已经是第一张图片了');
return;
}
this.photoIndex-=1;
this.picShow();
},
picNext:function(){
if(this.photoIndex>=this.picList.find('li').length-1){
alert('亲,已经是最后一张图片了');
return;
}
this.photoIndex+=1;
this.picShow();
},
picShow:function(){
var src;
src = this.picList.find('li').eq(this.photoIndex).find('img').prop('src');
this.popup.find('img').prop('src', src);
},
requestUserCity:function(){
var opt;
opt = {
apiName: 'ClientManagement/GetUserOperationCities.ashx',
success: this.userCitySuccess.bind(this)
};
this.sendToServer(opt);
},
userCitySuccess:function(data){
this.cityList.html(_.template($('#cityListTmpl').html(), data));
},
setCityVal: function(){
var arr;
arr = [];
this.cityList.find(':checked').each(function(){
arr.push($(this).val());
});
this.sellerCity.val(arr.join(','));
}
};
app.initialize();
return app;
}); | JavaScript |
/**
* Unicorn Admin Template
* Diablo9983 -> diablo9983@gmail.com
**/
$(document).ready(function(){
// === Sidebar navigation === //
$('.submenu > a').click(function(e)
{
e.preventDefault();
var submenu = $(this).siblings('ul');
var li = $(this).parents('li');
var submenus = $('#sidebar li.submenu ul');
var submenus_parents = $('#sidebar li.submenu');
if(li.hasClass('open'))
{
if(($(window).width() > 768) || ($(window).width() < 479)) {
submenu.slideUp();
} else {
submenu.fadeOut(250);
}
li.removeClass('open');
} else
{
if(($(window).width() > 768) || ($(window).width() < 479)) {
submenus.slideUp();
submenu.slideDown();
} else {
submenus.fadeOut(250);
submenu.fadeIn(250);
}
submenus_parents.removeClass('open');
li.addClass('open');
}
});
var ul = $('#sidebar > ul');
$('#sidebar > a').click(function(e)
{
e.preventDefault();
var sidebar = $('#sidebar');
if(sidebar.hasClass('open'))
{
sidebar.removeClass('open');
ul.slideUp(250);
} else
{
sidebar.addClass('open');
ul.slideDown(250);
}
});
// === Resize window related === //
$(window).resize(function()
{
if($(window).width() > 479)
{
ul.css({'display':'block'});
$('#content-header .btn-group').css({width:'auto'});
}
if($(window).width() < 479)
{
ul.css({'display':'none'});
fix_position();
}
if($(window).width() > 768)
{
$('#user-nav > ul').css({width:'auto',margin:'0'});
$('#content-header .btn-group').css({width:'auto'});
}
});
if($(window).width() < 468)
{
ul.css({'display':'none'});
fix_position();
}
if($(window).width() > 479)
{
$('#content-header .btn-group').css({width:'auto'});
ul.css({'display':'block'});
}
// === Tooltips === //
$('.tip').tooltip();
$('.tip-left').tooltip({ placement: 'left' });
$('.tip-right').tooltip({ placement: 'right' });
$('.tip-top').tooltip({ placement: 'top' });
$('.tip-bottom').tooltip({ placement: 'bottom' });
// === Search input typeahead === //
$('#search input[type=text]').typeahead({
source: ['Dashboard','Form elements','Common Elements','Validation','Wizard','Buttons','Icons','Interface elements','Support','Calendar','Gallery','Reports','Charts','Graphs','Widgets'],
items: 4
});
// === Fixes the position of buttons group in content header and top user navigation === //
function fix_position()
{
var uwidth = $('#user-nav > ul').width();
$('#user-nav > ul').css({width:uwidth,'margin-left':'-' + uwidth / 2 + 'px'});
var cwidth = $('#content-header .btn-group').width();
$('#content-header .btn-group').css({width:cwidth,'margin-left':'-' + uwidth / 2 + 'px'});
}
// === Style switcher === //
$('#style-switcher i').click(function()
{
if($(this).hasClass('open'))
{
$(this).parent().animate({marginRight:'-=220'});
$(this).removeClass('open');
} else
{
$(this).parent().animate({marginRight:'+=220'});
$(this).addClass('open');
}
$(this).toggleClass('icon-arrow-left');
$(this).toggleClass('icon-arrow-right');
});
$('#style-switcher a').click(function()
{
var style = $(this).attr('href').replace('#','');
$('.skin-color').attr('href','css/unicorn.'+style+'.css');
$(this).siblings('a').css({'border-color':'transparent'});
$(this).css({'border-color':'#aaaaaa'});
});
});
| JavaScript |
$(function() {
var app;
_.templateSettings = {
interpolate : /\{\{(.+?)\}\}/g, // print value: {{ value_name }}
evaluate : /\{%([\s\S]+?)%\}/g, // excute code: {% code_to_execute %}
escape : /\{%-([\s\S]+?)%\}/g
}; // excape H
app = {
pageIndex: [0, 0, 0],
page: 15,
tabIndex: 0,
ajaxLoading: true,
schemeListData : [],
angle : 0,
photoIndex : 0,
initialize: function() {
this.initDomNode();
this.bindEvents();
},
initDomNode: function() {
this.schemeManage = $('#schemeManage');
this.schemeBody = $('.scheme-body', this.schemeManage);
this.schemeInput = $('.scheme-input', this.schemeManage);
this.schemeSearch = $('.scheme-search', this.schemeManage);
this.schemeTree = $('.scheme-tree', this.schemeManage);
this.schemeTab = $('.scheme-tab', this.schemeManage);
this.schemeSummary = $('.scheme-summary', this.schemeManage);
this.schemeMoney = $('.scheme-money', this.schemeManage);
this.schemeList = $('.scheme-list', this.schemeManage);
this.rmPic = $('.remove-picture', this.schemeManage);
this.bdPic = $('.bind-picture', this.schemeManage);
this.schemeChecked = $('.scheme-checked', this.schemeManage);
this.schemePicBtn = $('.scheme-pic-btn', this.schemeManage);
this.reimbursementTree = $('.scheme-tree', this.schemeManage);
this.schemeReviewBtn = $('.scheme-review', this.schemeManage);
this.schemeUnReviewBtn = $('.scheme-unreview', this.schemeManage);
this.schemeSelect = $('.scheme-select', this.schemeManage);
this.loading = $('#dataLoading');
this.popup = $('#myModal');
},
bindEvents: function() {
var that;
that = this;
this.schemeSearch.on('click', function() { //执行案搜索菜单
that.loading.show();
that.requestSchemeTree();
});
this.schemeInput.on('keydown', function(e) { //执行案搜索菜单
if (e.keyCode == 13) {
that.loading.show();
that.requestSchemeTree();
e.preventDefault();
return false;
}
});
this.schemeTree.on('click', 'dt, dd', function(e) { //请求执行案id对应的图片列表 根节点为1 二级节点为2
var val, tag;
if (e.target != this) {
return;
}
that.loading.show();
val = $.trim($(this).text());
that.schemeId = val;
that.schemeTree.find('on').removeClass('on');
$(this).addClass('on').siblings().removeClass('on');
that.schemeTab.find('li').first().addClass('active').siblings().removeClass('active');
that.requestSchemeList(val);
if(e.target.tagName.toUpperCase() == 'DT' && val.split('-').length ==2){
that.getMappingColumns();
that.schemeSelect.show();
}else{
that.schemeSelect.hide();
}
});
this.rmPic.on('click', function() { //删除图片
that.loading.show();
that.removePic();
});
this.bdPic.on('click', function() { //绑定图片
that.loading.show();
that.bindPic();
});
this.schemeTab.on('click', 'a', function(e) { //图片类型Tab切换
e.preventDefault();
that.switchTab($(this));
});
this.schemeChecked.on('change', function() { //全选图片
$('input:checkbox', this.schemeList).prop('checked', $(this).is(':checked'));
});
this.schemeList.on('change', 'input:checkbox', function() { //图片列表中checkbox
var checked;
checked = $(this).is(':checked');
!checked && that.schemeChecked.prop('checked', checked);
});
this.schemePicBtn.on('click', 'button', function() {
var isBind;
that.loading.show();
isBind = $(this).hasClass('pic-bind-ok');
isBind ? that.requestSchemeList() : that.requestunBindSchemeList();
isBind ? that.bdPic.hide() : that.bdPic.css('display', 'inline-block');
});
$(window).scroll(function(){
that.loadMoreCase();
});
this.schemeList.on('click', 'a', function(e){
e.preventDefault();
that.angle = 0;
that.photoIndex = $(this).closest('li').index();
$('img', that.popup).css({
WebkitTransform : 'rotate(0deg)',
MozTransform : 'rotate(0deg)',
MsTransform : 'rotate(0deg)',
OTransform : 'rotate(0deg)',
transform : 'rotate(0deg)'
});
that.popup.find('img').prop('src', $(this).children('img').prop('src'));
});
this.popup.on('click', 'a', function(e){
var action;
e.preventDefault();
action = $(this).data('action');
action = action.replace(/^\w/, function(str){
return str.toUpperCase();
});
that['pic'+action] && that['pic'+action]();
});
this.schemeSelect.on('change', function() {
var val;
val = $.trim($(this).val());
that.schemeId = val;
that.requestSchemeList(val, 3);
});
this.schemeReviewBtn.on('click', function() { //通过审核
that.schemeReview();
});
this.schemeUnReviewBtn.on('click', function() { //通过审核
that.schemeUnReview();
});
this.schemeList.on('click', '.edit-money', function(){
that.editMoney($(this));
});
this.schemeList.on('click', '.update-money', function(){
that.updateMoney($(this));
});
this.schemeList.on('click', '.to-location-pic', function(){
that.toLocationPic($(this));
});
this.schemeList.on('click', '.to-unlocation-pic', function(){
that.toUnLocationPic($(this));
});
},
sendToServer: function(opt) {
var base, url, type, that;
that = this;
base = 'http://218.89.135.237:9000/API/WEB/';
url = base + opt.apiName;
type = opt.type ? opt.type : 'GET';
$.ajax({
type: type,
url: url,
async: true,
data: opt.data,
// timeout: 15000,
dataType: 'json'
}).done(function(data) {
// console.log(data);
if (data.IsSuccessfully) {
opt.success && opt.success(data);
} else {
opt.error && opt.error(data);
alert(data.ErrorMessage);
}
that.loading.hide();
}).fail(function(xhr, ajaxOptions, thrownError) {
// console.log(arguments);
that.loading.hide();
alert('error code: ' + xhr.status + '\n ajaxOptions:' + ajaxOptions + '\n message: ' + thrownError + '\n APIName:' + opt.apiName);
});
},
requestSchemeTree: function() {
var that, opt, id;
id = $.trim(this.schemeInput.val());
this.rootId = id;
opt = {
apiName: 'ApplyForReimbursement/GetReimbursementTree.ashx',
data: {
programID: id
},
success: this.schemeTreeSuccess.bind(this)
};
this.sendToServer(opt);
},
schemeTreeSuccess: function(data) {
data.id = this.rootId;
this.schemeTree.html(_.template($('#schemeTreeTmpl').html(), data));
},
requestSchemeList: function(id, level) {
var opt;
id = id || this.schemeId;
if(id==null || id ==''){
this.loading.hide();
return;
}
level = id.split('-').length;
opt = {
apiName: 'ApplyForReimbursement/GetDetailInfo.ashx',
data: {
schemeID: id,
levelID: level
},
success: this.schemeListSuccess.bind(this)
};
this.sendToServer(opt);
},
requestunBindSchemeList: function(id) {
var opt;
id = id || this.rootId;
if(id==null || id ==''){
this.loading.hide();
return;
}
id = id.split('-')[0];
opt = {
apiName: 'SchemeManagement/GetUnbindingPictures.ashx',
data: {
schemeID: id
},
success: this.schemeListSuccess.bind(this)
};
// this.ajaxLoading = false;
this.sendToServer(opt);
},
schemeListSuccess: function(data) {
var page;
data.schemeId = this.schemeId;
this.paging(data); //分页
this.schemeList.empty();
this.schemeSummary.empty();
this.schemeMoney.empty();
this.schemeList.html(_.template($('#schemeListTmpl').html(), {
initIndex : 0,
Pictures: this.schemeListData[0][0]
}));
this.schemeBody.show();
this.schemeChecked.prop('checked', false).parent().removeClass('checked');
this.schemeTab.find('li').first().addClass('active').siblings().removeClass('active');
this.pageIndex = [0, 0, 0];
data.SchemeDetailInfo && this.setSchemeSummary(data.SchemeDetailInfo);
data.TotalPictureCount && this.schemeMoney.html(_.template($('#schemeMoneyTmpl').html(), data));
},
paging: function(data) {
this.handlePaging(data.PricePicture, 0);
this.handlePaging(data.LocationPicture, 1);
this.handlePaging(data.NoLocationPicture, 2);
this.handlePaging(data.uploadFiles, 3);
},
handlePaging:function(data, index){
var arr, result, page;
arr = [];
result = [];
page = this.page;
if (!data) {
return;
}
for (var i = 0, l = data.length; i < l;) {
arr.push(data[i]);
i++;
if (i % page == 0 || i == l) {
result.push(arr);
arr = [];
}
}
// console.log(result);
this.schemeListData[index] = result;
},
setSchemeSummary: function(str) {
var arr, kv, data, key, val;
arr = [];
key = [];
val = [];
if (str != null && str != '') {
arr = str.split(',');
for (var i = 0, l = arr.length; i < l; i++) {
kv = arr[i].split(':');
key.push(kv[0]);
val.push(kv[1]);
}
}
data = {
key: key,
val: val
};
this.schemeSummary.html(_.template($('#schemeSummaryTmpl').html(), data));
},
getCheckedPic: function() {
var arr, pic;
arr = [];
pic = [];
$('input:checked', this.schemeList).each(function(index, item) {
$(item).is(':visible') && arr.push($(item).val());
$(item).is(':visible') && pic.push($(item));
});
// console.log(arr);
this.checkedPic = pic;
return arr;
},
removePic: function() {
var opt, id;
id = this.getCheckedPic();
opt = {
apiName: 'SchemeManagement/DeleteSchemePicture.ashx',
data: {
pictureID: id.join(',')
},
success: this.removePicSuccess.bind(this)
};
this.sendToServer(opt);
},
removePicSuccess: function(data) {
var pic;
pic = this.checkedPic;
for (var i = 0, l = pic.length; i < l; i++) {
pic[i].closest('.thumbnail').parent().remove();
}
// console.log('成功删除图片!');
},
bindPic: function() {
var opt;
data = this.getCheckedPic();
opt = {
apiName: 'SchemeManagement/BindingPicture.ashx',
data: {
schemeDetailID: this.schemeId,
pictureID: data.join(',')
},
success: this.bindPicSuccess.bind(this)
};
this.sendToServer(opt);
},
bindPicSuccess: function(data) {
alert('成功绑定图片!');
this.schemeTab.find('li').first().addClass('active').siblings().removeClass('active');
this.requestunBindSchemeList();
},
switchTab: function(target) {
var index, arr;
index = target.parent().index();
// this.photoIndex=0;
if(!this.schemeListData[0]){
return;
}
target.parent().addClass('active').siblings().removeClass('active');
this.tabIndex = index;
this.pageIndex[index] = 0;
this.schemeList.html(_.template($('#schemeListTmpl').html(), {
initIndex : 0,
Pictures: this.schemeListData[index][0]
}));
},
loadMoreCase:function(){
var scrollBottom;
scrollBottom = $(document).height() - $(window).height() - $(window).scrollTop();
if(scrollBottom < 50){
// if(this.ajaxLoading){
// return;
// }
// this.ajaxLoading = true;
this.pageIndex[this.tabIndex]++;
this.renderPage();
// this.ajaxLoading = false;
}
},
renderPage:function(){
var index, data, len;
index = this.pageIndex[this.tabIndex];
data = this.schemeListData[this.tabIndex] && this.schemeListData[this.tabIndex][index];
if(!data){
return;
}
len = this.schemeList.find('.span4').length;
this.schemeList.append(_.template($('#schemeListTmpl').html(), {initIndex:len, Pictures:data}));
},
picTurnLeft:function(){
this.angle-=45;
this.turnPic();
},
picTurnRight:function(){
this.angle+=45;
this.turnPic();
},
turnPic:function(){
// console.log(this.angle);
$('img', this.popup).css({
WebkitTransform : 'rotate('+this.angle+'deg)',
MozTransform : 'rotate('+this.angle+'deg)',
MsTransform : 'rotate('+this.angle+'deg)',
OTransform : 'rotate('+this.angle+'deg)',
transform : 'rotate('+this.angle+'deg)'
});
},
picPrev:function(){
if(this.photoIndex<=0){
alert('亲,已经是第一张图片了');
return;
}
this.photoIndex-=1;
this.picShow();
},
picNext:function(){
if(this.photoIndex>=this.schemeList.find('li').length-1){
alert('亲,已经是最后一张图片了');
return;
}
this.photoIndex+=1;
this.picShow();
},
picShow:function(){
var src;
src = this.schemeList.find('li').eq(this.photoIndex).find('img').prop('src');
this.popup.find('img').prop('src', src);
},
getMappingColumns: function() {
var opt;
opt = {
apiName: 'ApplyForReimbursement/GetMappingColumns.ashx',
data: {
schemeID: this.schemeId
},
success: this.mappingColumnsSuccess.bind(this)
};
this.sendToServer(opt);
},
mappingColumnsSuccess: function(data) {
this.schemeSelect.html(_.template($('#schemeSelectTmpl').html(), data));
},
schemeReview: function() {
var opt, data;
data = this.getCheckedPic();
if(data.length > 100){
alert('审核图片数量不能超过100张!');
return;
}
opt = {
apiName: 'ApplyForReimbursement/AuditedPicture.ashx',
data: {
pictureID: data.join(',')
},
success: this.schemeReviewSuccess.bind(this)
};
this.sendToServer(opt);
},
schemeReviewSuccess: function(data) {
alert('审核成功!');
this.requestSchemeList();
},
schemeUnReview: function() {
var opt, data;
data = this.getCheckedPic();
opt = {
apiName: 'ApplyForReimbursement/CancelAuditedPicture.ashx',
data: {
pictureID: data.join(',')
},
success: this.schemeUnReviewSuccess.bind(this)
};
this.sendToServer(opt);
},
schemeUnReviewSuccess: function(data) {
alert('审核已成功撤销!');
this.requestSchemeList();
},
editMoney:function(target){
var m1, num, input, editBtn, updateBtn;
m1 = target.closest('.caption').find('.item-price');
num = $.trim(m1.find('strong').text());
input = target.closest('.caption').find('.price-input');
editBtn = target.closest('.caption').find('.edit-money');
updateBtn = target.closest('.caption').find('.update-money');
this.moneyField = m1;
this.moneyInput = input;
this.editMoneyBtn = editBtn;
this.updateMoneyBtn = updateBtn;
editBtn.hide();
m1.hide();
input.val(num).show();
updateBtn.css({display:'inline-block'});
},
updateMoney:function(target){
var opt, input, id, money, re;
re = /^(([1-9]{1}\d*)|([0]{1}))(\.(\d){1,2})?$/;
id = target.data('id');
input = target.closest('.caption').find('.price-input');
money = $.trim(input.val());
if(money =='' || !re.test(money)){
alert('输入的金额格式不正确,请检查!');
return;
}
this.money = money;
opt = {
apiName: 'ApplyForReimbursement/ModifyPicturePrice.ashx',
data: {
pictureID: id,
price : money
},
success: this.updateMoneySuccess.bind(this)
};
this.sendToServer(opt);
},
updateMoneySuccess:function(data){
this.moneyField.html('金额:¥ <strong>'+this.money+'</strong>').show();
this.moneyInput.hide();
this.editMoneyBtn.show();
this.updateMoneyBtn.hide();
alert('更新金额成功!');
},
toLocationPic:function(target){
var opt, id, type;
id = target.data('id');
type = target.data('pic-type');
opt = {
apiName: 'SchemeManagement/ChangePictureType.ashx',
data: {
pictureID: id,
currentPictureType : type,
targetPictureType : 0
},
success: this.toLocationPicSuccess.bind(this)
};
this.sendToServer(opt);
},
toLocationPicSuccess:function(data){
alert('已成功切换到定位照片!');
this.requestSchemeList();
},
toUnLocationPic:function(target){
var opt, id, type;
id = target.data('id');
type = target.data('pic-type');
opt = {
apiName: 'SchemeManagement/ChangePictureType.ashx',
data: {
pictureID: id,
currentPictureType : type,
targetPictureType : 2
},
success: this.toUnLocationPicSuccess.bind(this)
};
this.sendToServer(opt);
},
toUnLocationPicSuccess:function(data){
alert('已成功切换到非定位照片!');
this.requestSchemeList();
}
};
app.initialize();
return app;
}); | JavaScript |
/*
Uniform v1.7.5
Copyright © 2009 Josh Pyles / Pixelmatrix Design LLC
http://pixelmatrixdesign.com
Requires jQuery 1.4 or newer
Much thanks to Thomas Reynolds and Buck Wilson for their help and advice on this
Disabling text selection is made possible by Mathias Bynens <http://mathiasbynens.be/>
and his noSelect plugin. <http://github.com/mathiasbynens/noSelect-jQuery-Plugin>
Also, thanks to David Kaneda and Eugene Bond for their contributions to the plugin
License:
MIT License - http://www.opensource.org/licenses/mit-license.php
Enjoy!
*/
(function($) {
$.uniform = {
options: {
selectClass: 'selector',
radioClass: 'radio',
checkboxClass: 'checker',
fileClass: 'uploader',
filenameClass: 'filename',
fileBtnClass: 'action',
fileDefaultText: 'No file selected',
fileBtnText: 'Choose File',
checkedClass: 'checked',
focusClass: 'focus',
disabledClass: 'disabled',
buttonClass: 'button',
activeClass: 'active',
hoverClass: 'hover',
useID: true,
idPrefix: 'uniform',
resetSelector: false,
autoHide: true
},
elements: []
};
// if($.browser.msie && $.browser.version < 7){
// $.support.selectOpacity = false;
// }else{
$.support.selectOpacity = true;
// }
$.fn.uniform = function(options) {
options = $.extend($.uniform.options, options);
var el = this;
//code for specifying a reset button
if(options.resetSelector != false){
$(options.resetSelector).mouseup(function(){
function resetThis(){
$.uniform.update(el);
}
setTimeout(resetThis, 10);
});
}
function doInput(elem){
$el = $(elem);
$el.addClass($el.attr("type"));
storeElement(elem);
}
function doTextarea(elem){
$(elem).addClass("uniform");
storeElement(elem);
}
function doButton(elem){
var $el = $(elem);
var divTag = $("<div>"),
spanTag = $("<span>");
divTag.addClass(options.buttonClass);
if(options.useID && $el.attr("id") != "") divTag.attr("id", options.idPrefix+"-"+$el.attr("id"));
var btnText;
if($el.is("a") || $el.is("button")){
btnText = $el.text();
}else if($el.is(":submit") || $el.is(":reset") || $el.is("input[type=button]")){
btnText = $el.attr("value");
}
btnText = btnText == "" ? $el.is(":reset") ? "Reset" : "Submit" : btnText;
spanTag.html(btnText);
$el.css("opacity", 0);
$el.wrap(divTag);
$el.wrap(spanTag);
//redefine variables
divTag = $el.closest("div");
spanTag = $el.closest("span");
if($el.is(":disabled")) divTag.addClass(options.disabledClass);
divTag.bind({
"mouseenter.uniform": function(){
divTag.addClass(options.hoverClass);
},
"mouseleave.uniform": function(){
divTag.removeClass(options.hoverClass);
divTag.removeClass(options.activeClass);
},
"mousedown.uniform touchbegin.uniform": function(){
divTag.addClass(options.activeClass);
},
"mouseup.uniform touchend.uniform": function(){
divTag.removeClass(options.activeClass);
},
"click.uniform touchend.uniform": function(e){
if($(e.target).is("span") || $(e.target).is("div")){
if(elem[0].dispatchEvent){
var ev = document.createEvent('MouseEvents');
ev.initEvent( 'click', true, true );
elem[0].dispatchEvent(ev);
}else{
elem[0].click();
}
}
}
});
elem.bind({
"focus.uniform": function(){
divTag.addClass(options.focusClass);
},
"blur.uniform": function(){
divTag.removeClass(options.focusClass);
}
});
$.uniform.noSelect(divTag);
storeElement(elem);
}
function doSelect(elem){
var $el = $(elem);
var divTag = $('<div />'),
spanTag = $('<span />');
if(!$el.css("display") == "none" && options.autoHide){
divTag.hide();
}
divTag.addClass(options.selectClass);
if(options.useID && elem.attr("id") != ""){
divTag.attr("id", options.idPrefix+"-"+elem.attr("id"));
}
var selected = elem.find(":selected:first");
if(selected.length == 0){
selected = elem.find("option:first");
}
spanTag.html(selected.html());
elem.css('opacity', 0);
elem.wrap(divTag);
elem.before(spanTag);
//redefine variables
divTag = elem.parent("div");
spanTag = elem.siblings("span");
elem.bind({
"change.uniform": function() {
spanTag.text(elem.find(":selected").html());
divTag.removeClass(options.activeClass);
},
"focus.uniform": function() {
divTag.addClass(options.focusClass);
},
"blur.uniform": function() {
divTag.removeClass(options.focusClass);
divTag.removeClass(options.activeClass);
},
"mousedown.uniform touchbegin.uniform": function() {
divTag.addClass(options.activeClass);
},
"mouseup.uniform touchend.uniform": function() {
divTag.removeClass(options.activeClass);
},
"click.uniform touchend.uniform": function(){
divTag.removeClass(options.activeClass);
},
"mouseenter.uniform": function() {
divTag.addClass(options.hoverClass);
},
"mouseleave.uniform": function() {
divTag.removeClass(options.hoverClass);
divTag.removeClass(options.activeClass);
},
"keyup.uniform": function(){
spanTag.text(elem.find(":selected").html());
}
});
//handle disabled state
if($(elem).attr("disabled")){
//box is checked by default, check our box
divTag.addClass(options.disabledClass);
}
$.uniform.noSelect(spanTag);
storeElement(elem);
}
function doCheckbox(elem){
var $el = $(elem);
var divTag = $('<div />'),
spanTag = $('<span />');
if(!$el.css("display") == "none" && options.autoHide){
divTag.hide();
}
divTag.addClass(options.checkboxClass);
//assign the id of the element
if(options.useID && elem.attr("id") != ""){
divTag.attr("id", options.idPrefix+"-"+elem.attr("id"));
}
//wrap with the proper elements
$(elem).wrap(divTag);
$(elem).wrap(spanTag);
//redefine variables
spanTag = elem.parent();
divTag = spanTag.parent();
//hide normal input and add focus classes
$(elem)
.css("opacity", 0)
.bind({
"focus.uniform": function(){
divTag.addClass(options.focusClass);
},
"blur.uniform": function(){
divTag.removeClass(options.focusClass);
},
"click.uniform touchend.uniform": function(){
if(!$(elem).attr("checked")){
//box was just unchecked, uncheck span
spanTag.removeClass(options.checkedClass);
}else{
//box was just checked, check span.
spanTag.addClass(options.checkedClass);
}
},
"mousedown.uniform touchbegin.uniform": function() {
divTag.addClass(options.activeClass);
},
"mouseup.uniform touchend.uniform": function() {
divTag.removeClass(options.activeClass);
},
"mouseenter.uniform": function() {
divTag.addClass(options.hoverClass);
},
"mouseleave.uniform": function() {
divTag.removeClass(options.hoverClass);
divTag.removeClass(options.activeClass);
}
});
//handle defaults
if($(elem).attr("checked")){
//box is checked by default, check our box
spanTag.addClass(options.checkedClass);
}
//handle disabled state
if($(elem).attr("disabled")){
//box is checked by default, check our box
divTag.addClass(options.disabledClass);
}
storeElement(elem);
}
function doRadio(elem){
var $el = $(elem);
var divTag = $('<div />'),
spanTag = $('<span />');
if(!$el.css("display") == "none" && options.autoHide){
divTag.hide();
}
divTag.addClass(options.radioClass);
if(options.useID && elem.attr("id") != ""){
divTag.attr("id", options.idPrefix+"-"+elem.attr("id"));
}
//wrap with the proper elements
$(elem).wrap(divTag);
$(elem).wrap(spanTag);
//redefine variables
spanTag = elem.parent();
divTag = spanTag.parent();
//hide normal input and add focus classes
$(elem)
.css("opacity", 0)
.bind({
"focus.uniform": function(){
divTag.addClass(options.focusClass);
},
"blur.uniform": function(){
divTag.removeClass(options.focusClass);
},
"click.uniform touchend.uniform": function(){
if(!$(elem).attr("checked")){
//box was just unchecked, uncheck span
spanTag.removeClass(options.checkedClass);
}else{
//box was just checked, check span
var classes = options.radioClass.split(" ")[0];
$("." + classes + " span." + options.checkedClass + ":has([name='" + $(elem).attr('name') + "'])").removeClass(options.checkedClass);
spanTag.addClass(options.checkedClass);
}
},
"mousedown.uniform touchend.uniform": function() {
if(!$(elem).is(":disabled")){
divTag.addClass(options.activeClass);
}
},
"mouseup.uniform touchbegin.uniform": function() {
divTag.removeClass(options.activeClass);
},
"mouseenter.uniform touchend.uniform": function() {
divTag.addClass(options.hoverClass);
},
"mouseleave.uniform": function() {
divTag.removeClass(options.hoverClass);
divTag.removeClass(options.activeClass);
}
});
//handle defaults
if($(elem).attr("checked")){
//box is checked by default, check span
spanTag.addClass(options.checkedClass);
}
//handle disabled state
if($(elem).attr("disabled")){
//box is checked by default, check our box
divTag.addClass(options.disabledClass);
}
storeElement(elem);
}
function doFile(elem){
//sanitize input
var $el = $(elem);
var divTag = $('<div />'),
filenameTag = $('<span>'+options.fileDefaultText+'</span>'),
btnTag = $('<span>'+options.fileBtnText+'</span>');
if(!$el.css("display") == "none" && options.autoHide){
divTag.hide();
}
divTag.addClass(options.fileClass);
filenameTag.addClass(options.filenameClass);
btnTag.addClass(options.fileBtnClass);
if(options.useID && $el.attr("id") != ""){
divTag.attr("id", options.idPrefix+"-"+$el.attr("id"));
}
//wrap with the proper elements
$el.wrap(divTag);
$el.after(btnTag);
$el.after(filenameTag);
//redefine variables
divTag = $el.closest("div");
filenameTag = $el.siblings("."+options.filenameClass);
btnTag = $el.siblings("."+options.fileBtnClass);
//set the size
if(!$el.attr("size")){
var divWidth = divTag.width();
//$el.css("width", divWidth);
$el.attr("size", divWidth/10);
}
//actions
var setFilename = function()
{
var filename = $el.val();
if (filename === '')
{
filename = options.fileDefaultText;
}
else
{
filename = filename.split(/[\/\\]+/);
filename = filename[(filename.length-1)];
}
filenameTag.text(filename);
};
// Account for input saved across refreshes
setFilename();
$el
.css("opacity", 0)
.bind({
"focus.uniform": function(){
divTag.addClass(options.focusClass);
},
"blur.uniform": function(){
divTag.removeClass(options.focusClass);
},
"mousedown.uniform": function() {
if(!$(elem).is(":disabled")){
divTag.addClass(options.activeClass);
}
},
"mouseup.uniform": function() {
divTag.removeClass(options.activeClass);
},
"mouseenter.uniform": function() {
divTag.addClass(options.hoverClass);
},
"mouseleave.uniform": function() {
divTag.removeClass(options.hoverClass);
divTag.removeClass(options.activeClass);
}
});
// IE7 doesn't fire onChange until blur or second fire.
// if ($.browser.msie){
// // IE considers browser chrome blocking I/O, so it
// // suspends tiemouts until after the file has been selected.
// $el.bind('click.uniform.ie7', function() {
// setTimeout(setFilename, 0);
// });
// }else{
// All other browsers behave properly
$el.bind('change.uniform', setFilename);
// }
//handle defaults
if($el.attr("disabled")){
//box is checked by default, check our box
divTag.addClass(options.disabledClass);
}
$.uniform.noSelect(filenameTag);
$.uniform.noSelect(btnTag);
storeElement(elem);
}
$.uniform.restore = function(elem){
if(elem == undefined){
elem = $($.uniform.elements);
}
$(elem).each(function(){
if($(this).is(":checkbox")){
//unwrap from span and div
$(this).unwrap().unwrap();
}else if($(this).is("select")){
//remove sibling span
$(this).siblings("span").remove();
//unwrap parent div
$(this).unwrap();
}else if($(this).is(":radio")){
//unwrap from span and div
$(this).unwrap().unwrap();
}else if($(this).is(":file")){
//remove sibling spans
$(this).siblings("span").remove();
//unwrap parent div
$(this).unwrap();
}else if($(this).is("button, :submit, :reset, a, input[type='button']")){
//unwrap from span and div
$(this).unwrap().unwrap();
}
//unbind events
$(this).unbind(".uniform");
//reset inline style
$(this).css("opacity", "1");
//remove item from list of uniformed elements
var index = $.inArray($(elem), $.uniform.elements);
$.uniform.elements.splice(index, 1);
});
};
function storeElement(elem){
//store this element in our global array
elem = $(elem).get();
if(elem.length > 1){
$.each(elem, function(i, val){
$.uniform.elements.push(val);
});
}else{
$.uniform.elements.push(elem);
}
}
//noSelect v1.0
$.uniform.noSelect = function(elem) {
function f() {
return false;
};
$(elem).each(function() {
this.onselectstart = this.ondragstart = f; // Webkit & IE
$(this)
.mousedown(f) // Webkit & Opera
.css({ MozUserSelect: 'none' }); // Firefox
});
};
$.uniform.update = function(elem){
if(elem == undefined){
elem = $($.uniform.elements);
}
//sanitize input
elem = $(elem);
elem.each(function(){
//do to each item in the selector
//function to reset all classes
var $e = $(this);
if($e.is("select")){
//element is a select
var spanTag = $e.siblings("span");
var divTag = $e.parent("div");
divTag.removeClass(options.hoverClass+" "+options.focusClass+" "+options.activeClass);
//reset current selected text
spanTag.html($e.find(":selected").html());
if($e.is(":disabled")){
divTag.addClass(options.disabledClass);
}else{
divTag.removeClass(options.disabledClass);
}
}else if($e.is(":checkbox")){
//element is a checkbox
var spanTag = $e.closest("span");
var divTag = $e.closest("div");
divTag.removeClass(options.hoverClass+" "+options.focusClass+" "+options.activeClass);
spanTag.removeClass(options.checkedClass);
if($e.is(":checked")){
spanTag.addClass(options.checkedClass);
}
if($e.is(":disabled")){
divTag.addClass(options.disabledClass);
}else{
divTag.removeClass(options.disabledClass);
}
}else if($e.is(":radio")){
//element is a radio
var spanTag = $e.closest("span");
var divTag = $e.closest("div");
divTag.removeClass(options.hoverClass+" "+options.focusClass+" "+options.activeClass);
spanTag.removeClass(options.checkedClass);
if($e.is(":checked")){
spanTag.addClass(options.checkedClass);
}
if($e.is(":disabled")){
divTag.addClass(options.disabledClass);
}else{
divTag.removeClass(options.disabledClass);
}
}else if($e.is(":file")){
var divTag = $e.parent("div");
var filenameTag = $e.siblings(options.filenameClass);
btnTag = $e.siblings(options.fileBtnClass);
divTag.removeClass(options.hoverClass+" "+options.focusClass+" "+options.activeClass);
filenameTag.text($e.val());
if($e.is(":disabled")){
divTag.addClass(options.disabledClass);
}else{
divTag.removeClass(options.disabledClass);
}
}else if($e.is(":submit") || $e.is(":reset") || $e.is("button") || $e.is("a") || elem.is("input[type=button]")){
var divTag = $e.closest("div");
divTag.removeClass(options.hoverClass+" "+options.focusClass+" "+options.activeClass);
if($e.is(":disabled")){
divTag.addClass(options.disabledClass);
}else{
divTag.removeClass(options.disabledClass);
}
}
});
};
return this.each(function() {
if($.support.selectOpacity){
var elem = $(this);
if(elem.is("select")){
//element is a select
if(elem.attr("multiple") != true){
//element is not a multi-select
if(elem.attr("size") == undefined || elem.attr("size") <= 1){
doSelect(elem);
}
}
}else if(elem.is(":checkbox")){
//element is a checkbox
doCheckbox(elem);
}else if(elem.is(":radio")){
//element is a radio
doRadio(elem);
}else if(elem.is(":file")){
//element is a file upload
doFile(elem);
}else if(elem.is(":text, :password, input[type='email']")){
doInput(elem);
}else if(elem.is("textarea")){
doTextarea(elem);
}else if(elem.is("a") || elem.is(":submit") || elem.is(":reset") || elem.is("button") || elem.is("input[type=button]")){
doButton(elem);
}
}
});
};
})(jQuery); | JavaScript |
!function(){
/*
WebOS.init
ʼ
*/
J.ready(function(){
Panel_Body.init();
Panel_Desktop.init();
Panel_topbar.init();
Panel_toolbar.init();
Panel_Deskdiv.init();
Panel_Body.addPanel(Panel_Desktop);
Panel_Body.addPanel(Panel_topbar);
Panel_Body.addPanel(Panel_toolbar);
Panel_Desktop.addPanel(Panel_Deskdiv);
Panel_Deskdiv
.space({top:31,bottom:31})
.refresh();
});/*
WebOS.panel
面板文件
*/
Panel_Body=function(me){
return me={
init:function(){
me.create();
me.setEvent();
},
create:function(){
me.box=J('body').attr('id','Panel_Body');
},
setEvent:function(){
},
addPanel:function(panel){
me.box.append(panel.box);
}
};
}();
Panel_Desktop=function(me){
return me={
init:function(){
me.create();
me.setEvent();
me.background('#3165a8');
},
create:function(){
me.box=J.node('<div id="Panel_Desktop"></div>');
},
setEvent:function(){
me.box.on('contextmenu',function(e){
e.stopPropagation();
e.preventDefault();
});
},
background:function(bgStyle){
me.box.css('background',bgStyle);
},
addPanel:function(panel){
me.box.append(panel.box);
}
};
}();
Panel_topbar=function(me){
return me={
init:function(){
me.create();
me.setEvent();
},
create:function(){
me.box=J.node('<div id="Panel_topbar"></div>');
},
setEvent:function(){
}
};
}();
Panel_toolbar=function(me){
return me={
init:function(){
me.create();
me.setEvent();
},
create:function(){
me.box=J.node('<div id="Panel_toolbar"></div>');
},
setEvent:function(){
}
};
}();
Panel_Deskdiv=function(me){
return me={
init:function(){
me.create();
me.setEvent();
},
create:function(){
me.box=J.node('<div id="Panel_Deskdiv"></div>');
},
setEvent:function(){
me.refreshCall=[];
J(window).on('resize',function(){
me.refresh();
});
},
onrefresh:function(callback){
me.refreshCall.push(callback);
},
refresh:function(){
J.each(me.refreshCall,function(){
this();
});
return me;
},
space:function(ops){
('top' in ops)&&this.box.top(ops.top);
('right' in ops)&&this.box.css('right',ops.right);
('bottom' in ops)&&this.box.css('bottom',ops.bottom);
('left' in ops)&&this.box.left(ops.left);
return me;
},
end:0
};
}();
}(); | JavaScript |
/**//**//**//**//**//**//*
** ==================================================================================================
** 类名:1k.js
** 版本:1.0
** 功能:js类库
** 示例:
---------------------------------------------------------------------------------------------------
文档:http://www.1kjs.com/lib/doc/
---------------------------------------------------------------------------------------------------
** 作者:zjfeihu
** 邮件:zjfeihu@126.com
** 创建:2011/08/01
** 更新:2011/08/27
** 类库地址:http://www.1kjs.com/lib/
** ==================================================================================================
**/!function(){
var $PID=1,
$WIN=window,
$DOC=document,
$DE=$DOC.documentElement,
$HEAD=$g('head')?$g('head')[0]:$g('html')[0],
$Class=function(){
var initializing=0,fnTest=/\b_super\b/,
Class=function(){};
Class.prototype={
ops:function(o1,o2){
o2=o2||{};
for(var key in o1){
this['_'+key]=key in o2?o2[key]:o1[key];
}
}
};
Class.extend=function(prop){
var _super = this.prototype;
initializing=1;//锁定初始化,阻止超类执行初始化
var _prototype=new this();//只是通过此来继承,而非创建类
initializing=0;//解锁初始化
function fn(name, fn) {
return function() {
this._super = _super[name];//保存超类方法,此this后面通过apply改变成本体类引用
var ret = fn.apply(this, arguments);//创建方法,并且改变this指向
return ret;//返回刚才创建的方法
};
}
var _mtd;//临时变量,存方法
for (var name in prop){//遍历传进来的所有方法
_mtd=prop[name];
_prototype[name] =(typeof _mtd=='function'&&
typeof _super[name]=='function'&&
fnTest.test(_mtd))?fn(name,_mtd):_mtd;//假如传进来的是函数,进行是否调用超类的检测来决定是否保存超类
}
function F(arg1) {//构造函数,假如没有被初始化,并且有初始化函数,执行初始化
if(this.constructor!=Object){
return new F({
FID:'JClassArguments',
val:arguments
});
}
if (!initializing&&this.init){
if(arg1&&arg1.FID&&arg1.FID=='JClassArguments'){
this.init.apply(this, arg1.val);
}else{
this.init.apply(this, arguments);
}
this.init=null;
};
}
F.prototype=_prototype;//创建。。。
F.constructor=F;//修正用
F.extend=arguments.callee;
return F;
};
return Class;
}(),
$EVENTQUEUE={},
$E_add=function(){
if($DOC.attachEvent){
return function(node,type,fn){
node.attachEvent('on'+type,fn);
};
}else{
return function(node,type,fn){
node.addEventListener(type,fn,false);
};
}
}(),
$ready=function(){
var isReady=false, //判断onDOMReady方法是否已经被执行过
readyList= [],//把需要执行的方法先暂存在这个数组里
timer,//定时器句柄
ready=function(fn) {
if (isReady){
fn();
}else{
readyList.push(fn);
}
},
onDOMReady=function(){
for(var i=0,lg=readyList.length;i<lg;i++){
readyList[i]();
}
readyList = null;
},
bindReady = function(evt){
if(isReady)return;
isReady=true;
onDOMReady();
if($DOC.removeEventListener){
$DOC.removeEventListener("DOMContentLoaded",bindReady,false);
}else if($DOC.attachEvent){
$DOC.detachEvent("onreadystatechange", bindReady);
if($WIN == $WIN.top){
clearInterval(timer);
timer = null;
}
}
};
if($DOC.addEventListener){
$DOC.addEventListener("DOMContentLoaded", bindReady, false);
}else if($DOC.attachEvent){
$DOC.attachEvent("onreadystatechange", function(){
if((/loaded|complete/).test($DOC.readyState))bindReady();
});
if($WIN == $WIN.top){
timer = setInterval(function(){
try{
isReady||$DOC.documentElement.doScroll('left');//在IE下用能否执行doScroll判断dom是否加载完毕
}catch(e){
return;
}
bindReady();
},5);
}
}
return ready;
}(),
//浏览器相关
$browser=function(){
var ua=navigator.userAgent.toLowerCase(),
sys={},
s;
(s = ua.match(/msie ([\d.]+)/)) ? sys.ie = s[1] :
(s = ua.match(/firefox\/([\d.]+)/)) ? sys.firefox = s[1] :
(s = ua.match(/chrome\/([\d.]+)/)) ? sys.chrome = s[1] :
(s = ua.match(/opera.([\d.]+)/)) ? sys.opera = s[1] :
(s = ua.match(/version\/([\d.]+).*safari/)) ? sys.safari = s[1] : 0;
return sys;
}(),
$isIE6=/MSIE\s*6.0/i.test(navigator.appVersion),
$XHR=function(){
return $WIN.XMLHttpRequest||function(X){
var xstr=[0,'Microsoft.XMLHTTP','MSXML2.XMLHTTP.3.0','MSXML2.XMLHTTP'],
i=4;
while(--i){
try {
X = new ActiveXObject(xstr[i]);
return function(){return X;}
}catch(e){
;;;alert('ajax对象不存在!');
}
}
}();
}(),
$scrollTop=function(){
var tr,
cr=$browser.chrome;
return function(y,t,tp){
var ds=cr?$DOC.body:$DE;
switch(arguments.length){
case 0:return ds['scrollTop'];
case 1:return ds['scrollTop']=y;
default:
var s0=0,
s1=Math.ceil(t/16),
z0=ds['scrollTop'],
tp=$EASING[tp||'circOut'],
zc=y-z0;
!function(me){
clearTimeout(tr);
me=arguments.callee;
tr=setTimeout(function(){
if(s0<s1){
ds['scrollTop']=tp(s0,z0,zc,s1);
me();
}else{
ds['scrollTop']=y;
clearTimeout(tr);
}
s0++;
},16);
}();
}
};
}(),
$ANIMEQUEQU={},
$EASING={
//t:当前步数
//b:开始位置
//c:总改变量
//d:总步数
Linear: function(t,b,c,d){ return c*t/d + b; },
slowIn:function(t,b,c,d){return c*(t/=d)*t + b;},
slowOut:function(t,b,c,d){return -c *(t/=d)*(t-2) + b;},
slowBoth:function(t,b,c,d){
if ((t/=d/2) < 1) return c/2*t*t + b;
return -c/2 * ((--t)*(t-2) - 1) + b;
},
In: function(t,b,c,d){
return c*(t/=d)*t*t*t + b;
},
Out: function(t,b,c,d){
return -c * ((t=t/d-1)*t*t*t - 1) + b;
},
Both: function(t,b,c,d){
if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
return -c/2 * ((t-=2)*t*t*t - 2) + b;
},
fastIn: function(t,b,c,d){
return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
},
fastOut: function(t,b,c,d){
return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
},
fastBoth: function(t,b,c,d){
if (t==0) return b;
if (t==d) return b+c;
if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
},
circIn: function(t,b,c,d){
return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
},
circOut: function(t,b,c,d){
return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
},
circBoth: function(t,b,c,d){
if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
},
elasticIn: function(t,b,c,d,a,p){
if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3;
if (!a || a < Math.abs(c)) { a=c; var s=p/4; }
else var s = p/(2*Math.PI) * Math.asin (c/a);
return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
},
elasticOut: function(t,b,c,d,a,p){
if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3;
if (!a || a < Math.abs(c)) { a=c; var s=p/4; }
else var s = p/(2*Math.PI) * Math.asin (c/a);
return (a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b);
},
elasticBoth: function(t,b,c,d,a,p){
if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5);
if (!a || a < Math.abs(c)) { a=c; var s=p/4; }
else var s = p/(2*Math.PI) * Math.asin (c/a);
if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
},
backIn: function(t,b,c,d,s){
if (s == undefined) s = 1.70158;
return c*(t/=d)*t*((s+1)*t - s) + b;
},
backOut: function(t,b,c,d,s){
if (s == undefined) s = 1.70158;
return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
},
backBoth: function(t,b,c,d,s){
if (s == undefined) s = 1.70158;
if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
},
bounceIn: function(t,b,c,d){
return c - $EASING.bounceOut(d-t, 0, c, d) + b;
},
bounceOut: function(t,b,c,d){
if ((t/=d) < (1/2.75)) {
return c*(7.5625*t*t) + b;
} else if (t < (2/2.75)) {
return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
} else if (t < (2.5/2.75)) {
return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
} else {
return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
}
},
bounceBoth: function(t,b,c,d){
if (t < d/2) return $EASING.bounceIn(t*2, 0, c, d) * .5 + b;
else return $EASING.bounceOut(t*2-d, 0, c, d) * .5 + c*.5 + b;
}
},
$DRAGQUEQU={},
$drag=$Class.extend({
init:function(node,ops){
this.node=node;
this.ops({
before:0,//拖动前
after:0,//拖动完成
runing:0,//拖动中
clone:0,//是否clone节点
lockx:0,//锁定x方向
locky:0,//锁定y方向
range:-1//拖动范围控制
},ops);
this.addHand(ops.hand||node);
},
addHand:function(hand){
$bind(hand,'mousedown',this._beforeDrag,this);
},
rmvHand:function(hand){
$bind(hand,'mousedown',this._beforeDrag,this);
},
_beforeDrag:function(evt){
if(evt.mouseKey!='left')return;
evt.stopPropagation();
var node=this.node,
clone=$clone(node,true),
offset=$offset(node),
marginLeft=$cssnum(node,'marginLeft'),
marginTop=$cssnum(node,'marginTop');
$css(clone,{
position:'absolute',
zIndex:9999,
left:offset.left-marginLeft,
top:offset.top-marginTop,
width:$cssnum(node,'width'),
height:$cssnum(node,'height')
});
$append($g('body')[0],clone);
this._style=clone.style;
this._offsetX=evt.clientX-clone.offsetLeft+marginLeft;
this._offsetY=evt.clientY-clone.offsetTop+marginTop;
$bind($DOC,'mousemove',this._draging,this);
$bind($DOC,'mouseup',this._drop,this);
if($browser.ie){
this._focusHand=evt.target;
$bind(this._focusHand,'losecapture',this._drop,this);
this._focusHand.setCapture(false);
}else{
var self=this;
this._win_blur=$WIN.onblur||null;
$WIN.onblur=function(){
self._win_blur&&self._win_blur();
self._drop(evt);
};
evt.preventDefault();
}
this._before&&this._before(evt);
if(this._range==-1){//限制在窗口内
this._minX=0;
this._minY=0;
this._maxX=$DE.clientWidth-clone.offsetWidth-marginLeft-$cssnum(clone,'marginRight');
this._maxY=$DE.clientHeight-clone.offsetHeight-marginTop-$cssnum(clone,'marginBottom');
}else if(this._range){
var range=$g(this._range),
ro=$offset(range),
rw=range.offsetWidth,
rh=range.offsetHeight,
bl=$css(range,'borderLeftWidth'),
br=$css(range,'borderRightWidth'),
bt=$css(range,'borderTopWidth'),
bb=$css(range,'borderBottomWidth');
this._minX=ro.left+bl;
this._minY=ro.top+bt;
this._maxX=ro.left+rw-br-clone.offsetWidth-marginLeft-$cssnum(clone,'marginRight');
this._maxY=ro.top+rh-bb-clone.offsetHeight-marginTop-$cssnum(clone,'marginBottom');
}
},
_draging:function(evt){
$WIN.getSelection?$WIN.getSelection().removeAllRanges():$DOC.selection.empty();
var left=evt.clientX-this._offsetX,
top=evt.clientY-this._offsetY;
if(this._range){
left=Math.min(Math.max(left,this._minX),this._maxX);
top=Math.min(Math.max(top,this._minY),this._maxY);
}
if(!this._lockx)this._style.left=left+'px';
if(!this._locky)this._style.top=top+'px';
this._runing&&this._runing(evt);
},
_drop:function(evt){
$unbind($DOC,'mousemove',this._draging,this);
$unbind($DOC,'mouseup',this._drop,this);
if($browser.ie){
$unbind(this._focusHand,'losecapture',this._drop,this);
this._focusHand.releaseCapture();
}else{
$WIN.onblur=this._win_blur;
}
this._after&&this._after(evt);
}
});
function $1kjs(selector,context){
switch(typeof selector){
case 'function':;
case 'string':;
case 'object':
if(selector==null||selector==undefined)return null;
var jn = new $_1kjs(selector,context);
return jn.node?jn:null;
}
}
function $_1kjs(selector,context){
if(selector==$DOC||selector==$WIN||$isNode(selector)){
this.node=selector;
}else{
var result=$g(selector,context);
if(result==null)return null;
if(result.nodeName){
this.node=result;
}else{
this.nodes=result;
this.node=result[0];
}
}
}
function $box(func,arg1,arg2,arg3){
var result=func.call(this,this.node,arg1,arg2,arg3);
if(this.nodes&&result==this){
var i=1;
while(this.nodes[i]){
func.call(this,this.nodes[i],arg1,arg2,arg3);
i++;
}
return this;
}else{
return result;
}
}
function $g(selector,context){
var root=$DOC,
id,
tag,
cls,
attr,
nodes,
reNodes=[];
if(typeof selector=='object')return selector;//传入节点
if(/^#[\w\-]+$/.test(selector)){
return $DOC.getElementById(selector.substr(1));
}
selector=selector.match(/^(?:#([\w\-]+))?\s*(?:(\w+))?(?:\.([\w\-]+))?(?:\[(.+)\])?$/);
if(selector){
id=selector[1];
tag=selector[2];
cls=selector[3];
attr=selector[4];
}else{
return null;
}
if(id){
root=$DOC.getElementById(id);
if(!root)return null;
}else if(typeof context=='object'){
root=context;
}
nodes=root.getElementsByTagName(tag||'*');
if(cls||attr){
if(cls){
if(!tag&&root.getElementsByClassName){
reNodes=root.getElementsByClassName(cls);
}else{
reNodes=[];
var re=RegExp('(^|\\s)'+cls+'($|\\s)');
for(var i=0,lg=nodes.length;i<lg;i++){
re.test(nodes[i].className)&&reNodes.push(nodes[i]);
}
}
}
if(attr){
if(cls)nodes=reNodes.slice(0);
reNodes=[];
attr=attr.split('=');
if(attr.length==2){
var key=attr[0].split('!'),
val=attr[1]||'';
if(key.length>1){//=前面跟!
key=key[0];
for(var i=0,l=nodes.length; i<l; i++){
nodes[i].getAttribute(key)!=val && reNodes.push(nodes[i]);
}
}else{
for(var i=0,l=nodes.length; i<l; i++){
nodes[i].getAttribute(key)==val && reNodes.push(nodes[i]);
}
}
}else{
for(var i=0,l=nodes.length; i<l; i++){
nodes[i].hasAttribute(attr) && reNodes.push(nodes[i]);
}
}
}
}else{
for(var i=0,lg=nodes.length;i<lg;i++){
reNodes[i]=nodes[i];
}
}
return reNodes.length?reNodes:null;
}
function $child(node,index){
var child = [],
i=0,
ol = node.childNodes;
while(ol[i]){
ol[i].nodeType==1 && child.push(ol[i]);
i++;
}
if(index>-1){
child= child[index];
}else if(index<0){
child= child[child.length+index];
}else if(typeof index=='string'){
var nodes=$g(index,node),
reNode=[];
$each(nodes,function(){
if(this.parentNode==node){
reNode.push(this);
}
});
if(reNode.length){
return reNode;
}
}
return child;
}
function $sibling(node,selector){
var parent=node.parentNode,
_node,
nodes=selector?$g(selector,node.parentNode):node.parentNode.childNodes,
re=[],
i=0;
while(_node=nodes[i++]){
if(_node.parentNode==parent&&node!=_node&&_node.nodeType==1)re.push(_node);
}
return re.length?re:null;
}
function $parent(node,selector){
if(selector==undefined){
return node.parentNode;
}else if(selector>0){
selector++;
while(selector--){
node=node.parentNode;
}
return node;
}else{
selector=selector.match(/^(?:#([\w\-]+))?\s*(?:(\w+))?(?:.([\w\-]+))?(?:\[(.+)\])?$/);
if(selector){
var id=selector[1],
tag=selector[2],
cls=selector[3],
attr=selector[4];
tag=tag&&tag.toUpperCase();
attr=attr&&attr.split('=');
}else{
return null;
}
if(id){
return $g(id);
}else{
while(node=node.parentNode){
if(
(!cls||cls&&$hcls(node,cls))
&&(!tag||node.nodeName==tag)
&&(!attr||$attr(node,attr[0])==attr[1])
){
return node;
}
}
}
}
return null;
}
function $prev(node){
while(node=node.previousSibling){
if(node.nodeType==1){
return node;
}
}
}
function $next(node){
while(node=node.nextSibling){
if(node.nodeType==1){
return node;
}
}
}
function $node(node){
if($isNode(node))return node;
if($is1kjs(node))return node.node;
if(node.indexOf('<')>-1){//非标准创建节点
var prarent=$DOC.createElement('div');
prarent.innerHTML=node;
return prarent.firstChild;
}else{
return $DOC.createElement(node);
}
}
function $append(node,newNode,index){
if($isArray(newNode)){
var root=$DOC.createDocumentFragment();
$each(newNode,function(){
root.appendChild($node(this));
});
newNode=root;
}else{
newNode=$node(newNode);
}
if(index==undefined){
node.appendChild(newNode);
return this;
}
var child=node.childNodes;
if(!$browser.ie){//过滤非Element节点
var _child=[];
for(var i=0,lg=child.length;i<lg;i++){
if(child[i].nodeType==1)_child.push(child[i]);
}
child=_child;
}
if(index>-1){
child= child[index];
}else if(index<0){
child= child[child.length+index+1]?child[child.length+index+1]:child[0];
}
if(child){
child.parentNode.insertBefore(newNode,child);
}else{
node.appendChild(newNode);
}
return this;
}
function $insert(node,newNode,flag){
newNode=$node(newNode);
if(flag){
while(node.nextSibling){
node=node.nextSibling;
if(node.nodeType==1){
node.parentNode.insertBefore(newNode,node);
return this;
}
}
node.parentNode.appendChild(newNode);
}else{
node.parentNode.insertBefore(newNode,node);
}
return this;
}
function $remove(node){
node.parentNode.removeChild(node);
return this;
}
function $clone(node,flag){
node=node.cloneNode(flag);
return node;
}
function $replace(node,newNode){
node.parentNode.replaceChild($node(newNode),node);
return this;
}
function $cls(node,cls1,cls2){
if(cls2){
node.className=(' '+node.className+' ')
.replace(new RegExp('\\s+'+cls2+'\\s+'),' '+cls1+' ')
.replace(/^\s+|\s+$/g,'');
}else{
if(!cls1){
return node.className;
}
var _exp=cls1.substr(0,1),
_cls=cls1.substr(1);
if(_exp=='+'){
if(!$hcls(node,_cls))node.className+=' '+_cls.split(',').join(' ');
}else if(_exp=='-'){
node.className=(' '+node.className+' ')
.replace(new RegExp('\\s+('+_cls.split(',').join('|')+')(?=\\s+)','g'),'')
.replace(/^\s+|\s+$/g,'');
}else if(cls1){
return $hcls(node,cls1);
}
}
return this;
}
function $addpx(attr,val){
if(/width|height|left|top|right|bottom|margin|padding/.test(attr)&&/^[\-\d.]+$/.test(val)){//数值属性
return val+'px';//加px
}
return val;
}
function $rmvpx(attr,val){
if(/px$/.test(val))return parseFloat(val);//去除px
return val;
}
function $css(node,name,value){
if(typeof value!='undefined'){
name=name.replace(/-(\w)/g,function(_,$1){
return $1.toUpperCase();
});
node.style[name]=$addpx(name,value);
}else if(typeof name=='object'){
for(var key in name){
$css(node,key,name[key]);
//node.style[key]=$addpx(key,name[key]);
}
}else{
if(name.indexOf(':')==-1){//无‘:’,比如'background:red'
name=name.replace(/-(\w)/g,function(_,$1){
return $1.toUpperCase();
});
return $rmvpx(name,node.style&&node.style[name]||(node.currentStyle||$DOC.defaultView.getComputedStyle(node,null))[name]);
}else{
var cssObj=name.replace(/;$/,'').split(';'),
cssText;
for(var i=0,lg=cssObj.length;i<lg;i++){
cssText=cssObj[i].split(':');
$css(node,cssText.shift(),cssText.join(':'));
//?$css(node,cssText[0],cssText[1]);//background:url(http://www....)bug
}
}
}
return this;
}
function $cssnum(node,attr){
var val=+$css(node,attr)||0;
if(/^width|height|left|top$/.test(attr)){
switch(attr){
case 'left':return val||node.offsetLeft-$cssnum(node,'marginLeft');
case 'top':return val||node.offsetTop-$cssnum(node,'marginTop');
case 'width':return val
||(node.offsetWidth
-$cssnum(node,'paddingLeft')
-$cssnum(node,'paddingRight')
-$cssnum(node,'borderLeftWidth')
-$cssnum(node,'borderRightWidth')
);
case 'height':return val
||(node.offsetHeight
-$cssnum(node,'paddingTop')
-$cssnum(node,'paddingBottom')
-$cssnum(node,'borderTopWidth')
-$cssnum(node,'borderBottomWidth')
);
}
}
return val;
}
function $left(node,value){
if(value!=undefined){
return $css(node,'left',value);
}
return $cssnum(node,'left');
}
function $top(node,value){
if(value!=undefined){
return $css(node,'top',value);
}
return $cssnum(node,'top');
}
function $width(node,value){
if(value!=undefined){
return $css(node,'width',value);
}
return $cssnum(node,'width');
}
function $height(node,value){
if(value!=undefined){
return $css(node,'height',value);
}
return $cssnum(node,'height');
}
function $offset(node){
var top = 0, left = 0;
if ( "getBoundingClientRect" in $DE){
//jquery方法
var box = node.getBoundingClientRect(),
body = $DOC.body,
clientTop = $DE.clientTop || body.clientTop || 0,
clientLeft = $DE.clientLeft || body.clientLeft || 0,
top = box.top + ($WIN.pageYOffset || $DE && $DE.scrollTop || body.scrollTop ) - clientTop,
left = box.left + ($WIN.pageXOffset || $DE && $DE.scrollLeft || body.scrollLeft) - clientLeft;
}else{
do{
top += node.offsetTop || 0;
left += node.offsetLeft || 0;
node = node.offsetParent;
} while (node);
}
return {left:left, top:top,width:node.offsetWidth,height:node.offsetHeight};
}
function $opacity(node,opacity){
if($browser.ie){
if(typeof opacity=='undefined'){
var filter=$css(node,'filter');
if(filter){
return +filter.match(/(\d+)/)[0]/100;
}
return 1;
}
node.style.filter='Alpha(opacity='+opacity*100+')';
}else{
if(typeof opacity=='undefined'){
opacity=+$css(node,'opacity');
return opacity>-1?opacity:1;
}
node.style.opacity=opacity;
}
return this;
}
function $show(node){
node.style.display='block';
return this;
}
function $hide(node){
node.style.display='none';
return this;
}
function $hcls(node,cls){
if(new RegExp('\\s'+cls+'\\s').test(' '+node.className+' '))return !0;
return !1;
}
function $attr(node,name,value){
if(value===null){
node.removeAttribute(name);
}else if(value!=undefined){
if(typeof name=='object'){
for(var attr in name){
$attr(node,attr,name[attr]);
}
}else{
if(name=='style'){
node.style.cssText=value;
}else{
if(node[name]!=undefined){//优先设置js属性
node[name]=value;
}else{
node.setAttribute(name,value,2);
}
}
}
}else{
if(name=='style'){
return node.style.cssText;
}else{
if(name=='href'&&node.nodeName=='A'){
return node.getAttribute(name,2);
}else{
if(node[name]!=undefined){//优先获取js属性
return node[name];
}else{
var val=node.getAttribute(name);
return val==null?void(0):val;
}
}
}
}
return this;
}
function $html(node,html){
var type=typeof html,
_html='';
if(type=='undefined'){
return node.innerHTML;
}else if(type=='function'){
_html=html();
}else if(type=='object'){
$each(html,function(){
_html+=this;
});
}else{
_html=html;
}
if(node.nodeName=='SELECT'&&type!='undefined'&&$browser.ie){
var s=document.createElement('span');
s.innerHTML='<select>'+_html+'</select>';
node.innerHTML='';
$each($g('option',s),function(){
node.appendChild(this);
});
}else{
node.innerHTML=_html;
}
return this;
}
function $tag(node,nodeName){
if(typeof nodeName!='undefined'){
return nodeName==node.nodeName;
}
return node.nodeName;
}
function $contains(pnode,cnode){
if(cnode==pnode)return 1;
if(pnode.contains){//ie下判断是不是属于contains容器中的节点
if(pnode.contains(cnode)){
return 2;
}
}else if(pnode.compareDocumentPosition){//非ie下判断
if(pnode.compareDocumentPosition(cnode)==20){
return 2;
}
}
return 0;
}
function $val(node,val){
if(val==undefined)return node.value.replace(/^\s+|\s+$/g,'');
node.value=val;
return this;
}
function $Evt(evt){
var _evt={
native:evt,
type:evt.type,
keyCode:evt.keyCode,
clientX:evt.clientX,
clientY:evt.clientY,
target:evt.target||evt.srcElement,
fromTarget:evt.fromElement||(evt.type=='mouseover'?evt.relatedTarget:null),
toTarget:evt.toElement||(evt.type=='mouseout'?evt.relatedTarget:null),
stopPropagation:function(){
if(evt.stopPropagation){
evt.stopPropagation();
}else{
evt.cancelBubble=true;
}
},
mouseKey:($browser.ie?{1:'left',4:'middle',2:'right'}:{0:'left',1:'middle',2:'right'})[evt.button],
preventDefault:function(){
if(evt.preventDefault){
evt.preventDefault();
}else{
evt.returnValue = false;
}
}
};
return _evt;
}
function $bind(node,type,func,who){
if(!node.___EVENTID){//没有有事件队列
$EVENTQUEUE[node.___EVENTID=$PID++]=[];
}
var EQ=$EVENTQUEUE[node.___EVENTID];
if(!EQ[type]){//无该类型的事件队列
EQ[type]=[];
$E_add(node,type,function(evt){
var Q=EQ[type].slice(0);
while(Q[0]){
Q[0].func.call(Q[0].who,$Evt(evt));
Q.shift();
}
});
}
EQ[type].push({
func:func,
who:who||node
});
return this;
}
function $unbind(node,type,func,who){
var Q=$EVENTQUEUE[node.___EVENTID][type],i=0;
while(Q[i]){
if(Q[i].func==func&&Q[i].who==(who||node)){
Q.splice(i,1);break;
}
i++;
}
return this;
}
function $cookie(name,value,expire){
if(typeof value!='undefined'){
var exp = new Date();
exp.setTime(exp.getTime()+(value==null?-1:(expire||2592000000)));
$DOC.cookie=name+'='+escape(value)+';expires='+exp.toGMTString();
}else{
var arr = $DOC.cookie.match(new RegExp('(^| )'+name+'=([^;]*)(;|$)'));
return arr!=null?unescape(arr[2]):null;
}
}
function $each(obj,fn){
if($isArray(obj)){
for(var i=0,lg=obj.length;i<lg;i++){
fn.call(obj[i],i,obj[i]);
}
}else{
for(var i in obj){
fn.call(obj[i],i,obj[i]);
}
}
}
function $toJson(obj){
switch(typeof obj){
case 'object':
if(obj==null){
return obj;
}
var E,_json=[];
if(Object.prototype.toString.apply(obj) == '[object Array]'){
for(var e=0,L=obj.length;e<L;e++){
_json[e]=arguments.callee(obj[e]);
}
return '['+_json.join(',')+']';
}
for(e in obj){
_json.push('"'+e+'":'+arguments.callee(obj[e]));
}
return '{'+_json.join(',')+'}';
case 'function':
obj=''+obj;
case 'string':
return '"'+obj.replace(/"/g,'\\"')+'"';
case 'number':
case 'boolean':
case 'undefined':
return obj;
}
return obj;
}
function $param(obj,t){
var query=[];
if(typeof obj=='object'){
for(var E in obj){
if(/^e_/.test(E)){
query.push(E.substr(2)+'='+$encodeURL(obj[E]));
}else{
query.push(E+'='+obj[E]);
}
}
}
if(t)query.push('t='+(+new Date));
return query.join('&');
}
function $encodeHTML(str){
return str.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
}
function $decodeHTML(str){
return str.replace(/</g,'<').replace(/>/g,'>').replace(/&/g,'&');
}
function $encodeURL(str){
return str
.replace(/%/g,'%25')
.replace(/ /g,'%20')
.replace(/#/g,'%23')
.replace(/&/g,'%26')
.replace(/=/g,'%3D')
.replace(/\//g,'%2F')
.replace(/\?/g,'%3F')
.replace(/\+/g,'%2B');
}
function $tirm(str){
return str.replace(/^\s+|\s+$/g,'');
}
function $parseJson(str){
try{
return Function('return '+str)();
}catch(e){
return {};
}
}
function $post(url,callback,data){
var xmlhttp=new $XHR();
xmlhttp.open('post',url,true);
xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4){
if(xmlhttp.status==200){
callback&&callback(xmlhttp.responseText);
}else{
callback&&callback(null);
}
}
};
xmlhttp.send(typeof data=='object'?$param(data):data);
return xmlhttp;
}
function $get(url,callback,data){
var xmlhttp=new $XHR();
if(data)url+='?'+(typeof data=='object'?$param(data):data);
xmlhttp.open('get',url,true);
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4){
if(xmlhttp.status==200){
callback&&callback(xmlhttp.responseText);
}else{
callback&&callback(null);
}
}
};
xmlhttp.send(null);
return xmlhttp;
}
function $img(url,callback){
var img = new Image();
img.src = url;
if(img.complete){
return callback&&callback.call(img,img);
}
img.onload = function () {
callback&&callback.call(img,img);
};
return this;
}
function $js(url,callback,data,charset){
var s=$DOC.createElement('script');
if(data)url+='?'+(typeof data=='object'?$param(data):data);
s.src=url;
charset&&(s.charset=charset);
$HEAD.appendChild(s);
if(s.readyState){
s.onreadystatechange=function(){
if(s.readyState=='loaded'||s.readyState=='complete'){
callback&&callback();
$HEAD.removeChild(s);
}
};
}else{
s.onload=function(){
callback&&callback();
$HEAD.removeChild(s);
};
}
return this;
}
function $style(arg1){
if(typeof arg1=='object')arg1=arg1.join('');
if(/{[\w\W]+?}/.test(arg1)){//cssText
var s=$DOC.createElement('style');
s.type='text/css';
s.styleSheet&&(s.styleSheet.cssText=arg1)||s.appendChild($DOC.createTextNode(arg1));
}else{
var s=$DOC.createElement('link');
s.rel='stylesheet';
s.href=arg1;
}
$HEAD.appendChild(s);
return this;
}
function $isArray(obj){
return {}.toString.call(obj)=='[object Array]';
}
function $isNode(obj){
return obj&&obj.nodeType === 1;
}
function $is1kjs(obj){
return !!(obj&&$isNode(obj.node));
}
function $proxy(fn,who){
var args=[].slice.call(arguments,2);
return function(){
return fn.apply(who,[].concat.apply(args,arguments));
};
}
function $anime(node,args){
var ns=node.style,
mc=Math.ceil,
tp=$EASING[args.type||'Both'],
xc=0,//x方向改变量
yc=0,//y方向改变量
wc=0,//宽度改变量
ws=0,//宽度改变比例
hc=0,//高度改变量
hs=0,//高度改变比例
o0=0,//初始透明度
oc=0,//透明度改变
mx=0,//移动x标志
my=0,//移动x标志
rw=0,//改变宽度标志
rh=0,//改变高度标志
co=0,//改变透明度标志
x0,//left初始值
y0,//top初始值
w0,//宽度初始值
h0,//高度初始值
//run,//动画核心函数
opa0,
opac,
s0=0,//当前步数
s1=mc((args.t||1000)/16),//总步数,普通人眼能看到1/24秒,window反应时钟16ms,这里取32ms
timer,
end;
if($browser.ie&&$browser.ie<8){
$css(node,'zoom',1);
}
if(typeof args.w!='undefined'){
rw=1;
w0=$width(node);
if(typeof args.w=='number'){//数字参数,则为目标,字符串则为增量
wc=args.w-w0;
}else{
wc=+args.w;
}
if(args.ws){
x0=$left(node);
ws=args.ws;
}
}
if(typeof args.h!='undefined'){
rh=1;
h0=$height(node);
if(typeof args.h=='number'){
hc=args.h-h0;
}else{
hc=+args.h;
}
if(args.hs){
y0=$top(node);
hs=args.hs;
}
}
if(typeof args.x!='undefined'){
mx=1;
ws=0;
x0=$left(node);
if(typeof args.x=='number'){
xc=args.x-x0;
}else{
xc=+args.x;
}
}
if(typeof args.y!='undefined'){
my=1;
hs=0;
y0=$top(node);
if(typeof args.y=='number'){
yc=args.y-y0;
}else{
yc=+args.y;
}
}
if(args.o>=0){
co=1;
opa0=$opacity(node);
if(typeof args.o=='number'){
opac=args.o-opa0;
}else{
opac=+args.o;
}
}
if(mx||my||ws||hs){
if($css(node,'position')=='static'){
ns.position='relative';
}
if($browser.ie&&$browser.ie<7&&(rw||rh)){
ns.overflow='hidden';
}
}
function _doing(){
if(s0<s1){
if(mx){
ns.left=mc(tp(s0,x0,xc,s1))+'px';
}
if(rw){
var w=mc(tp(s0,w0,wc,s1));
ns.width = w+'px';
if(ws){
ns.left=x0+(-ws)*(w-w0)+'px';
}
}
if(my){
ns.top=mc(tp(s0,y0,yc,s1))+'px';
}
if(rh){
var h=mc(tp(s0,h0,hc,s1));
ns.height = h+'px';
if(hs){
ns.top=y0+(-hs)*(h-h0)+'px';
}
}
if(co){
$opacity(node,tp(s0,opa0,opac,s1));
}
s0++;
timer=setTimeout(_doing,15.6);
}else{
// 最终修正误差
if(mx){
ns.left=x0+xc+'px';
}
if(rw){
ns.width = w0+wc+'px';
if(ws)ns.left=x0+(-ws)*(wc)+'px';
}
if(my){
ns.top=y0+yc+'px';
}
if(rh){
ns.height = h0+hc+'px';
if(hs){
ns.top=y0+(-hs)*(hc)+'px';
}
}
if(co){
$opacity(node,opa0+opac);
}
args.after&&args.after();
}
args.running&&args.running();
}
args.before&&args.before();
timer=setTimeout(_doing,16);
return{
stop:function(){
if(!args.lock)clearTimeout(timer);
args.stop&&args.stop();
}
};
}
$1kjs.Class=function(ops){
//;;;if(!/object|function/.test(typeof ops)||ops==null){alert('参数类型不对!');};
return $Class.extend(typeof ops=='function'?ops():ops);
};
$1kjs.extend=function(name,fn){
$_1kjs.prototype[name]=fn;
};
$1kjs.widget=function(name,fn){
if(typeof fn=='function'){
$1kjs[name]=fn();
}else{
var Class=$Class.extend(fn);
$1kjs[name]=function(ops){
return new Class(ops);
};
}
};
$1kjs.g=$g;
$_1kjs.prototype.find=function(selector){
return $1kjs(selector,this.node);
};
$_1kjs.prototype.eq=function(i){
if(i<0)i=this.nodes.length+i;
return $1kjs(this.nodes[i]);
};
$_1kjs.prototype.child=function(index){
return $1kjs($child(this.node,index));
};
$_1kjs.prototype.sibling=function(selector){
return $1kjs($sibling(this.node,selector));
};
$_1kjs.prototype.parent=function(index){
return $1kjs($parent(this.node,index));
};
$_1kjs.prototype.prev=function(){
return $1kjs($prev(this.node));
};
$_1kjs.prototype.next=function(){
return $1kjs($next(this.node));
};
$_1kjs.prototype.each=function(func){
if(this.nodes){
var i=0;
while(this.nodes[i]){
func.call($1kjs(this.nodes[i]),i);
i++;
}
}else if(this.node){
func.call(this,0);
}
return this;
};
$1kjs.node=function(html){
return $1kjs($node(html));
};
$_1kjs.prototype.append=function(newNode,index){
return $box.call(this,$append,newNode,index);
};
$_1kjs.prototype.insert=function(newNode,flag){
return $box.call(this,$insert,newNode,flag);
};
$_1kjs.prototype.remove=function(){
return $box.call(this,$remove);
};
$_1kjs.prototype.clone=function(flag){
return $1kjs($clone(this.node,flag));
};
$_1kjs.prototype.replace=function(newNode){
return $box.call(this,$replace,newNode);
};
$_1kjs.prototype.cls=function(cls1,cls2){
return $box.call(this,$cls,cls1,cls2);
};
$_1kjs.prototype.css=function(name,value){
return $box.call(this,$css,name,value);
};
$_1kjs.prototype.px=function(name){
return $cssnum(this.node,name);
};
$_1kjs.prototype.left=function(value){
return $box.call(this,$left,value);
};
$_1kjs.prototype.top=function(value){
return $box.call(this,$top,value);
};
$_1kjs.prototype.width=function(value){
return $box.call(this,$width,value);
};
$_1kjs.prototype.height=function(value){
return $box.call(this,$height,value);
};
$_1kjs.prototype.offsetLeft=function(){
return $offset(this.node).left;
};
$_1kjs.prototype.offsetTop=function(){
return $offset(this.node).top;
};
$_1kjs.prototype.offset=function(){
return $offset(this.node);
};
$_1kjs.prototype.offsetWidth=function(){
return this.node.offsetWidth;
};
$_1kjs.prototype.offsetHeight=function(){
return this.node.offsetHeight;
};
$_1kjs.prototype.opacity=function(opacity){
return $box.call(this,$opacity,opacity);
};
$_1kjs.prototype.show=function(){
return $box.call(this,$show);
};
$_1kjs.prototype.hide=function(){
return $box.call(this,$hide);
};
$_1kjs.prototype.attr=function(name,value){
return $box.call(this,$attr,name,value);
};
$_1kjs.prototype.html=function(html){
return $box.call(this,$html,html);
};
$_1kjs.prototype.tag=function(nodeName){
return $tag(this.node,nodeName);
};
$_1kjs.prototype.contains=function(cnode){
return $contains(this.node,cnode);
};
$_1kjs.prototype.val=function(value){
return $box.call(this,$val,value);
};
$_1kjs.prototype.length=function(){
return this.nodes.length||1;
};
$1kjs.ready=$ready;
$_1kjs.prototype.on=function(type,func,who){
var result=$bind.call(this,this.node,type,func,who||this.node);
if(this.nodes&&result==this){
var i=1;
while(this.nodes[i]){
$bind.call(this,this.nodes[i],type,func,who||this.nodes[i]);
i++;
}
return this;
}else{
return result;
}
};
$_1kjs.prototype.un=function(type,func,who){
var result=$unbind.call(this,this.node,type,func,who||this.node);
if(this.nodes&&result==this){
var i=1;
while(this.nodes[i]){
$unbind.call(this,this.nodes[i],type,func,who||this.nodes[i]);
i++;
}
return this;
}else{
return result;
}
};
$_1kjs.prototype.click=function(func,who){
var result=$bind.call(this,this.node,'click',func,who||$1kjs(this.node));
if(this.nodes&&result==this){
var i=1;
while(this.nodes[i]){
$bind.call(this,this.nodes[i],'click',func,who||this.eq(i));
i++;
}
return this;
}else{
return result;
}
};
$_1kjs.prototype.hover=function(hover,out,who){
var node,
self=this;
if(this.nodes){
var i=0;
while(node=this.nodes[i]){
~function(_who){
var node=_who.node;
$bind(node,'mouseover',function(evt){
if(evt.fromTarget&&!$contains(node,evt.fromTarget))hover.call(who||_who,evt);
},who||_who);
$bind(node,'mouseout',function(evt){
if(!evt.toTarget||!$contains(node,evt.toTarget))out.call(who||_who,evt);
},who||_who);
}(this.eq(i));
i++;
}
}else{
node=this.node;
$bind(node,'mouseover',function(evt){
if(evt.fromTarget&&!$contains(node,evt.fromTarget))hover.call(who||self,evt);
},who||self);
$bind(node,'mouseout',function(evt){
if(!evt.toTarget||!$contains(node,evt.toTarget))out.call(who||self,evt);
},who||self);
}
return this;
};
$1kjs.browser=$browser;
$1kjs.isIE6=$isIE6;
$1kjs.cookie=$cookie;
$1kjs.each=$each;
$1kjs.toJson=$toJson;
$1kjs.param=$param;
$1kjs.tirm=$tirm;
$1kjs.encodeURL=$encodeURL;
$1kjs.encodeHTML=$encodeHTML;
$1kjs.decodeHTML=$decodeHTML;
$1kjs.parseJson=$parseJson;
$1kjs.post=$post;
$1kjs.get=$get;
$1kjs.img=$img;
$1kjs.js=$js;
$1kjs.css=$style;
$1kjs.isArray=$isArray;
$1kjs.isNode=$isNode;
$1kjs.docWidth=function(){
return $DE.clientWidth;
};
$1kjs.docHeight=function(){
return $DE.clientHeight;
};
$1kjs.scrollWidth=function(){
return $DE.scrollWidth;
};
$1kjs.scrollHeight=function(){
return Math.max($DE.scrollHeight,$DOC.body.scrollHeight);
};
$1kjs.scrollTop=function(){
return $scrollTop.apply(this,arguments);
};
$1kjs.scrollLeft=function(){
return $DE.scrollLeft+$DOC.body.scrollLeft;
};
$1kjs.proxy=$proxy;
$_1kjs.prototype.anime=function(args){
if(!this.node.___ANIMEID){
var pid=this.node.___ANIMEID=$PID;
$PID++;
args=args||{};
$ANIMEQUEQU[pid]=$anime(this.node,args);
}else{
var pid=this.node.___ANIMEID;
$ANIMEQUEQU[pid].stop();
$ANIMEQUEQU[pid]=$anime(this.node,args);
}
return $ANIMEQUEQU[pid];
};
$_1kjs.prototype.drag=function(ops){
if(!this.node.___DRAGID){
var pid=this.node.___DRAGID=$PID;
$PID++;
$DRAGQUEQU[pid]=$drag(this.node,ops||{});
}
return $DRAGQUEQU[this.node.___DRAGID];
};
this.$1kjs=$1kjs;
}();this.J=$1kjs; | JavaScript |
window.onload = function()
{
var copyP = document.createElement( 'p' ) ;
copyP.className = 'copyright' ;
copyP.innerHTML = '© 2007-2013 <a href="http://cksource.com" target="_blank">CKSource</a> - Frederico Knabben . All rights reserved.<br /><br />' ;
document.body.appendChild( document.createElement( 'hr' ) ) ;
document.body.appendChild( copyP ) ;
window.top.SetActiveTopic( window.location.pathname ) ;
}
| JavaScript |
/*
* CKFinder
* ========
* http://cksource.com/ckfinder
* Copyright (C) 2007-2014, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file, and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying, or distributing this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object for the Dutch
* language.
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['nl'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, niet beschikbaar</span>',
confirmCancel : 'Enkele opties zijn gewijzigd. Weet u zeker dat u dit dialoogvenster wilt sluiten?',
ok : 'OK',
cancel : 'Annuleren',
confirmationTitle : 'Bevestigen',
messageTitle : 'Informatie',
inputTitle : 'Vraag',
undo : 'Ongedaan maken',
redo : 'Opnieuw uitvoeren',
skip : 'Overslaan',
skipAll : 'Alles overslaan',
makeDecision : 'Welke actie moet uitgevoerd worden?',
rememberDecision: 'Onthoud mijn keuze'
},
// Language direction, 'ltr' or 'rtl'.
dir : 'ltr',
HelpLang : 'en',
LangCode : 'nl',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'd-m-yyyy H:MM',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Mappen',
FolderLoading : 'Laden...',
FolderNew : 'Vul de mapnaam in: ',
FolderRename : 'Vul de nieuwe mapnaam in: ',
FolderDelete : 'Weet je het zeker dat je de map "%1" wilt verwijderen?',
FolderRenaming : ' (Aanpassen...)',
FolderDeleting : ' (Verwijderen...)',
DestinationFolder : 'Destination Folder', // MISSING
// Files
FileRename : 'Vul de nieuwe bestandsnaam in: ',
FileRenameExt : 'Weet je zeker dat je de extensie wilt wijzigen? Het bestand kan onbruikbaar worden.',
FileRenaming : 'Aanpassen...',
FileDelete : 'Weet je zeker dat je het bestand "%1" wilt verwijderen?',
FilesDelete : 'Are you sure you want to delete %1 files?', // MISSING
FilesLoading : 'Laden...',
FilesEmpty : 'De map is leeg.',
DestinationFile : 'Destination File', // MISSING
SkippedFiles : 'List of skipped files:', // MISSING
// Basket
BasketFolder : 'Mandje',
BasketClear : 'Mandje legen',
BasketRemove : 'Verwijder uit het mandje',
BasketOpenFolder : 'Bovenliggende map openen',
BasketTruncateConfirm : 'Weet je zeker dat je alle bestand uit het mandje wilt verwijderen?',
BasketRemoveConfirm : 'Weet je zeker dat je het bestand "%1" uit het mandje wilt verwijderen?',
BasketRemoveConfirmMultiple : 'Do you really want to remove %1 files from the basket?', // MISSING
BasketEmpty : 'Geen bestanden in het mandje, sleep bestanden hierheen.',
BasketCopyFilesHere : 'Bestanden kopiëren uit het mandje',
BasketMoveFilesHere : 'Bestanden verplaatsen uit het mandje',
// Global messages
OperationCompletedSuccess : 'Operation completed successfully.', // MISSING
OperationCompletedErrors : 'Operation completed with errors.', // MISSING
FileError : '%s: %e', // MISSING
// Move and Copy files
MovedFilesNumber : 'Number of files moved: %s.', // MISSING
CopiedFilesNumber : 'Number of files copied: %s.', // MISSING
MoveFailedList : 'The following files could not be moved:<br />%s', // MISSING
CopyFailedList : 'The following files could not be copied:<br />%s', // MISSING
// Toolbar Buttons (some used elsewhere)
Upload : 'Uploaden',
UploadTip : 'Nieuw bestand uploaden',
Refresh : 'Vernieuwen',
Settings : 'Instellingen',
Help : 'Help',
HelpTip : 'Help',
// Context Menus
Select : 'Selecteer',
SelectThumbnail : 'Selecteer miniatuurafbeelding',
View : 'Bekijken',
Download : 'Downloaden',
NewSubFolder : 'Nieuwe onderliggende map',
Rename : 'Naam wijzigen',
Delete : 'Verwijderen',
DeleteFiles : 'Delete Files', // MISSING
CopyDragDrop : 'Hierheen kopiëren',
MoveDragDrop : 'Hierheen verplaatsen',
// Dialogs
RenameDlgTitle : 'Naam wijzigen',
NewNameDlgTitle : 'Nieuwe naam',
FileExistsDlgTitle : 'Bestand bestaat al',
SysErrorDlgTitle : 'Systeemfout',
FileOverwrite : 'Overschrijven',
FileAutorename : 'Automatisch hernoemen',
ManuallyRename : 'Manually rename', // MISSING
// Generic
OkBtn : 'OK',
CancelBtn : 'Annuleren',
CloseBtn : 'Sluiten',
// Upload Panel
UploadTitle : 'Nieuw bestand uploaden',
UploadSelectLbl : 'Selecteer het bestand om te uploaden',
UploadProgressLbl : '(Bezig met uploaden, even geduld a.u.b...)',
UploadBtn : 'Upload geselecteerde bestand',
UploadBtnCancel : 'Annuleren',
UploadNoFileMsg : 'Kies een bestand van je computer.',
UploadNoFolder : 'Selecteer a.u.b. een map voordat je gaat uploaden.',
UploadNoPerms : 'Uploaden bestand niet toegestaan.',
UploadUnknError : 'Fout bij het versturen van het bestand.',
UploadExtIncorrect : 'Bestandsextensie is niet toegestaan in deze map.',
// Flash Uploads
UploadLabel : 'Te uploaden bestanden',
UploadTotalFiles : 'Totaal aantal bestanden:',
UploadTotalSize : 'Totale grootte:',
UploadSend : 'Uploaden',
UploadAddFiles : 'Bestanden toevoegen',
UploadClearFiles : 'Bestanden wissen',
UploadCancel : 'Upload annuleren',
UploadRemove : 'Verwijderen',
UploadRemoveTip : 'Verwijder !f',
UploadUploaded : '!n% geüpload',
UploadProcessing : 'Verwerken...',
// Settings Panel
SetTitle : 'Instellingen',
SetView : 'Bekijken:',
SetViewThumb : 'Miniatuurafbeelding',
SetViewList : 'Lijst',
SetDisplay : 'Weergave:',
SetDisplayName : 'Bestandsnaam',
SetDisplayDate : 'Datum',
SetDisplaySize : 'Bestandsgrootte',
SetSort : 'Sorteren op:',
SetSortName : 'Op bestandsnaam',
SetSortDate : 'Op datum',
SetSortSize : 'Op grootte',
SetSortExtension : 'Op bestandsextensie',
// Status Bar
FilesCountEmpty : '<Lege map>',
FilesCountOne : '1 bestand',
FilesCountMany : '%1 bestanden',
// Size and Speed
Kb : '%1 KB',
Mb : '%1 MB',
Gb : '%1 GB',
SizePerSecond : '%1/s',
// Connector Error Messages.
ErrorUnknown : 'Het was niet mogelijk om deze actie uit te voeren. (Fout %1)',
Errors :
{
10 : 'Ongeldig commando.',
11 : 'Het bestandstype komt niet voor in de aanvraag.',
12 : 'Het gevraagde brontype is niet geldig.',
102 : 'Ongeldige bestands- of mapnaam.',
103 : 'Het verzoek kon niet worden voltooid vanwege autorisatie beperkingen.',
104 : 'Het verzoek kon niet worden voltooid door beperkingen in de rechten op het bestandssysteem.',
105 : 'Ongeldige bestandsextensie.',
109 : 'Ongeldige aanvraag.',
110 : 'Onbekende fout.',
111 : 'It was not possible to complete the request due to resulting file size.', // MISSING
115 : 'Er bestaat al een bestand of map met deze naam.',
116 : 'Map niet gevonden, vernieuw de mappenlijst of kies een andere map.',
117 : 'Bestand niet gevonden, vernieuw de mappenlijst of kies een andere map.',
118 : 'Bron- en doelmap zijn gelijk.',
201 : 'Er bestaat al een bestand met dezelfde naam. Het geüploade bestand is hernoemd naar: "%1".',
202 : 'Ongeldige bestand.',
203 : 'Ongeldige bestand. Het bestand is te groot.',
204 : 'De geüploade file is kapot.',
205 : 'Er is geen hoofdmap gevonden.',
206 : 'Het uploaden van het bestand is om veiligheidsredenen afgebroken. Er is HTML code in het bestand aangetroffen.',
207 : 'Het geüploade bestand is hernoemd naar: "%1".',
300 : 'Bestand(en) verplaatsen is mislukt.',
301 : 'Bestand(en) kopiëren is mislukt.',
500 : 'Het uploaden van een bestand is momenteel niet mogelijk. Contacteer de beheerder en controleer het CKFinder configuratiebestand.',
501 : 'De ondersteuning voor miniatuurafbeeldingen is uitgeschakeld.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'De bestandsnaam mag niet leeg zijn.',
FileExists : 'Bestand %s bestaat al.',
FolderEmpty : 'De mapnaam mag niet leeg zijn.',
FolderExists : 'Folder %s already exists.', // MISSING
FolderNameExists : 'Folder already exists.', // MISSING
FileInvChar : 'De bestandsnaam mag de volgende tekens niet bevatten: \n\\ / : * ? " < > |',
FolderInvChar : 'De mapnaam mag de volgende tekens niet bevatten: \n\\ / : * ? " < > |',
PopupBlockView : 'Het was niet mogelijk om dit bestand in een nieuw venster te openen. Configureer de browser zodat het de popups van deze website niet blokkeert.',
XmlError : 'Het is niet gelukt om de XML van de webserver te laden.',
XmlEmpty : 'Het is niet gelukt om de XML van de webserver te laden. De server gaf een leeg resultaat terug.',
XmlRawResponse : 'Origineel resultaat van de server: %s'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : '%s herschalen',
sizeTooBig : 'Het is niet mogelijk om een breedte of hoogte in te stellen die groter is dan de originele afmetingen (%size).',
resizeSuccess : 'De afbeelding is met succes herschaald.',
thumbnailNew : 'Miniatuurafbeelding maken',
thumbnailSmall : 'Klein (%s)',
thumbnailMedium : 'Medium (%s)',
thumbnailLarge : 'Groot (%s)',
newSize : 'Nieuwe afmetingen instellen',
width : 'Breedte',
height : 'Hoogte',
invalidHeight : 'Ongeldige hoogte.',
invalidWidth : 'Ongeldige breedte.',
invalidName : 'Ongeldige bestandsnaam.',
newImage : 'Nieuwe afbeelding maken',
noExtensionChange : 'De bestandsextensie kan niet worden gewijzigd.',
imageSmall : 'Bronafbeelding is te klein.',
contextMenuName : 'Herschalen',
lockRatio : 'Afmetingen vergrendelen',
resetSize : 'Afmetingen resetten'
},
// Fileeditor plugin
Fileeditor :
{
save : 'Opslaan',
fileOpenError : 'Kan het bestand niet openen.',
fileSaveSuccess : 'Bestand is succesvol opgeslagen.',
contextMenuName : 'Wijzigen',
loadingFile : 'Bestand laden, even geduld a.u.b...'
},
Maximize :
{
maximize : 'Maximaliseren',
minimize : 'Minimaliseren'
},
Gallery :
{
current : 'Afbeelding {current} van {total}'
},
Zip :
{
extractHereLabel : 'Extract here', // MISSING
extractToLabel : 'Extract to...', // MISSING
downloadZipLabel : 'Download as zip', // MISSING
compressZipLabel : 'Compress to zip', // MISSING
removeAndExtract : 'Remove existing and extract', // MISSING
extractAndOverwrite : 'Extract overwriting existing files', // MISSING
extractSuccess : 'File extracted successfully.' // MISSING
},
Search :
{
searchPlaceholder : 'Zoeken'
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://cksource.com/ckfinder
* Copyright (C) 2007-2014, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file, and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying, or distributing this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object for the Italian
* language.
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['it'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, non disponibile</span>',
confirmCancel : 'Alcune delle opzioni sono state cambiate. Sei sicuro di voler chiudere la finestra di dialogo?',
ok : 'OK',
cancel : 'Annulla',
confirmationTitle : 'Confermare',
messageTitle : 'Informazione',
inputTitle : 'Domanda',
undo : 'Annulla',
redo : 'Ripristina',
skip : 'Ignora',
skipAll : 'Ignora tutti',
makeDecision : 'Che azione prendere?',
rememberDecision: 'Ricorda mia decisione'
},
// Language direction, 'ltr' or 'rtl'.
dir : 'ltr',
HelpLang : 'en',
LangCode : 'it',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'dd/mm/yyyy HH:MM',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Cartelle',
FolderLoading : 'Caricando...',
FolderNew : 'Nome della cartella: ',
FolderRename : 'Nuovo nome della cartella: ',
FolderDelete : 'Se sicuro di voler eliminare la cartella "%1"?',
FolderRenaming : ' (Rinominando...)',
FolderDeleting : ' (Eliminando...)',
DestinationFolder : 'Destination Folder', // MISSING
// Files
FileRename : 'Nuovo nome del file: ',
FileRenameExt : 'Sei sicure di voler cambiare la estensione del file? Il file può risultare inusabile.',
FileRenaming : 'Rinominando...',
FileDelete : 'Sei sicuro di voler eliminare il file "%1"?',
FilesDelete : 'Are you sure you want to delete %1 files?', // MISSING
FilesLoading : 'Caricamento in corso...',
FilesEmpty : 'Cartella vuota',
DestinationFile : 'Destination File', // MISSING
SkippedFiles : 'List of skipped files:', // MISSING
// Basket
BasketFolder : 'Cestino',
BasketClear : 'Svuota Cestino',
BasketRemove : 'Rimuove dal Cestino',
BasketOpenFolder : 'Apre Cartella Superiore',
BasketTruncateConfirm : 'Sei sicuro di voler svuotare il cestino?',
BasketRemoveConfirm : 'Sei sicuro di voler rimuovere il file "%1" dal cestino?',
BasketRemoveConfirmMultiple : 'Do you really want to remove %1 files from the basket?', // MISSING
BasketEmpty : 'Nessun file nel cestino, si deve prima trascinare qualcuno.',
BasketCopyFilesHere : 'Copia i File dal Cestino',
BasketMoveFilesHere : 'Muove i File dal Cestino',
// Global messages
OperationCompletedSuccess : 'Operation completed successfully.', // MISSING
OperationCompletedErrors : 'Operation completed with errors.', // MISSING
FileError : '%s: %e', // MISSING
// Move and Copy files
MovedFilesNumber : 'Number of files moved: %s.', // MISSING
CopiedFilesNumber : 'Number of files copied: %s.', // MISSING
MoveFailedList : 'The following files could not be moved:<br />%s', // MISSING
CopyFailedList : 'The following files could not be copied:<br />%s', // MISSING
// Toolbar Buttons (some used elsewhere)
Upload : 'Upload',
UploadTip : 'Carica Nuovo File',
Refresh : 'Aggiorna',
Settings : 'Configurazioni',
Help : 'Aiuto',
HelpTip : 'Aiuto (Inglese)',
// Context Menus
Select : 'Seleziona',
SelectThumbnail : 'Seleziona la miniatura',
View : 'Vedi',
Download : 'Scarica',
NewSubFolder : 'Nuova Sottocartella',
Rename : 'Rinomina',
Delete : 'Elimina',
DeleteFiles : 'Delete Files', // MISSING
CopyDragDrop : 'Copia qui',
MoveDragDrop : 'Muove qui',
// Dialogs
RenameDlgTitle : 'Rinomina',
NewNameDlgTitle : 'Nuovo nome',
FileExistsDlgTitle : 'Il file già esiste',
SysErrorDlgTitle : 'Errore di Sistema',
FileOverwrite : 'Sovrascrivere',
FileAutorename : 'Rinomina automaticamente',
ManuallyRename : 'Manually rename', // MISSING
// Generic
OkBtn : 'OK',
CancelBtn : 'Anulla',
CloseBtn : 'Chiudi',
// Upload Panel
UploadTitle : 'Carica Nuovo File',
UploadSelectLbl : 'Seleziona il file',
UploadProgressLbl : '(Caricamento in corso, attendere prego...)',
UploadBtn : 'Carica File',
UploadBtnCancel : 'Annulla',
UploadNoFileMsg : 'Seleziona il file da caricare',
UploadNoFolder : 'Seleziona il file prima di caricare.',
UploadNoPerms : 'Non è permesso il caricamento di file.',
UploadUnknError : 'Errore nel caricamento del file.',
UploadExtIncorrect : 'In questa cartella non sono permessi file con questa estensione.',
// Flash Uploads
UploadLabel : 'File da Caricare',
UploadTotalFiles : 'File:',
UploadTotalSize : 'Dimensione:',
UploadSend : 'Upload',
UploadAddFiles : 'Aggiungi File',
UploadClearFiles : 'Elimina File',
UploadCancel : 'Annulla il Caricamento',
UploadRemove : 'Rimuovi',
UploadRemoveTip : 'Rimuove !f',
UploadUploaded : '!n% caricato',
UploadProcessing : 'Attendere...',
// Settings Panel
SetTitle : 'Configurazioni',
SetView : 'Vedi:',
SetViewThumb : 'Anteprima',
SetViewList : 'Lista',
SetDisplay : 'Informazioni:',
SetDisplayName : 'Nome del File',
SetDisplayDate : 'Data',
SetDisplaySize : 'Dimensione',
SetSort : 'Ordina:',
SetSortName : 'per Nome',
SetSortDate : 'per Data',
SetSortSize : 'per Dimensione',
SetSortExtension : 'per Estensione',
// Status Bar
FilesCountEmpty : '<Nessun file>',
FilesCountOne : '1 file',
FilesCountMany : '%1 file',
// Size and Speed
Kb : '%1 KB',
Mb : '%1 MB',
Gb : '%1 GB',
SizePerSecond : '%1/s',
// Connector Error Messages.
ErrorUnknown : 'Impossibile completare la richiesta. (Errore %1)',
Errors :
{
10 : 'Commando non valido.',
11 : 'Il tipo di risorsa non è stato specificato nella richiesta.',
12 : 'Il tipo di risorsa richiesto non è valido.',
102 : 'Nome di file o cartella non valido.',
103 : 'Non è stato possibile completare la richiesta a causa di restrizioni di autorizazione.',
104 : 'Non è stato possibile completare la richiesta a causa di restrizioni nei permessi del file system.',
105 : 'L\'estensione del file non è valida.',
109 : 'Richiesta invalida.',
110 : 'Errore sconosciuto.',
111 : 'It was not possible to complete the request due to resulting file size.', // MISSING
115 : 'Un file o cartella con lo stesso nome è già esistente.',
116 : 'Cartella non trovata. Prego aggiornare e riprovare.',
117 : 'File non trovato. Prego aggirnare la lista dei file e riprovare.',
118 : 'Il percorso di origine e di destino sono uguali.',
201 : 'Un file con lo stesso nome è già disponibile. Il file caricato è stato rinominato in "%1".',
202 : 'File invalido.',
203 : 'File invalido. La dimensione del file eccede i limiti del sistema.',
204 : 'Il file caricato è corrotto.',
205 : 'Il folder temporario non è disponibile new server.',
206 : 'Upload annullato per motivi di sicurezza. Il file contiene dati in formatto HTML.',
207 : 'Il file caricato è stato rinominato a "%1".',
300 : 'Non è stato possibile muovere i file.',
301 : 'Non è stato possibile copiare i file.',
500 : 'Questo programma è disabilitato per motivi di sicurezza. Prego contattare l\'amministratore del sistema e verificare le configurazioni di CKFinder.',
501 : 'Il supporto alle anteprime non è attivo.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Il nome del file non può essere vuoto.',
FileExists : 'File %s già esiste.',
FolderEmpty : 'Il nome della cartella non può essere vuoto.',
FolderExists : 'Folder %s already exists.', // MISSING
FolderNameExists : 'Folder already exists.', // MISSING
FileInvChar : 'I seguenti caratteri non possono essere usati per comporre il nome del file: \n\\ / : * ? " < > |',
FolderInvChar : 'I seguenti caratteri non possono essere usati per comporre il nome della cartella: \n\\ / : * ? " < > |',
PopupBlockView : 'Non è stato possile aprire il file in una nuova finestra. Prego configurare il browser e disabilitare i blocchi delle popup.',
XmlError : 'Non è stato possibile caricare la risposta XML dal server.',
XmlEmpty : 'Non è stato possibile caricare la risposta XML dal server. La risposta è vuota.',
XmlRawResponse : 'Risposta originale inviata dal server: %s'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Ridimensiona %s',
sizeTooBig : 'Non si può usare valori di altezza e larghezza che siano maggiore che le dimensioni originali (%size).',
resizeSuccess : 'Immagine ridimensionata.',
thumbnailNew : 'Crea una nuova thumbnail',
thumbnailSmall : 'Piccolo (%s)',
thumbnailMedium : 'Medio (%s)',
thumbnailLarge : 'Grande (%s)',
newSize : 'Nuove dimensioni',
width : 'Larghezza',
height : 'Altezza',
invalidHeight : 'Altezza non valida.',
invalidWidth : 'Larghezza non valida.',
invalidName : 'Nome del file non valido.',
newImage : 'Crea nuova immagine',
noExtensionChange : 'L\'estensione del file non può essere cambiata.',
imageSmall : 'L\'immagine originale è molto piccola.',
contextMenuName : 'Ridimensiona',
lockRatio : 'Blocca rapporto',
resetSize : 'Reimposta dimensione'
},
// Fileeditor plugin
Fileeditor :
{
save : 'Salva',
fileOpenError : 'Non è stato possibile aprire il file.',
fileSaveSuccess : 'File salvato.',
contextMenuName : 'Modifica',
loadingFile : 'Attendere prego. Caricamento del file in corso...'
},
Maximize :
{
maximize : 'Massimizza',
minimize : 'Minimizza'
},
Gallery :
{
current : 'Immagine {current} di {total}'
},
Zip :
{
extractHereLabel : 'Extract here', // MISSING
extractToLabel : 'Extract to...', // MISSING
downloadZipLabel : 'Download as zip', // MISSING
compressZipLabel : 'Compress to zip', // MISSING
removeAndExtract : 'Remove existing and extract', // MISSING
extractAndOverwrite : 'Extract overwriting existing files', // MISSING
extractSuccess : 'File extracted successfully.' // MISSING
},
Search :
{
searchPlaceholder : 'Ricerca'
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://cksource.com/ckfinder
* Copyright (C) 2007-2014, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file, and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying, or distributing this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object for the German
* language.
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['de'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, nicht verfügbar</span>',
confirmCancel : 'Einige Optionen wurden geändert. Wollen Sie den Dialog dennoch schließen?',
ok : 'OK',
cancel : 'Abbrechen',
confirmationTitle : 'Bestätigung',
messageTitle : 'Information',
inputTitle : 'Frage',
undo : 'Rückgängig',
redo : 'Wiederherstellen',
skip : 'Überspringen',
skipAll : 'Alle überspringen',
makeDecision : 'Bitte Auswahl treffen.',
rememberDecision: 'Entscheidung merken'
},
// Language direction, 'ltr' or 'rtl'.
dir : 'ltr',
HelpLang : 'en',
LangCode : 'de',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'd.m.yyyy H:MM',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Verzeichnisse',
FolderLoading : 'Laden...',
FolderNew : 'Bitte geben Sie den neuen Verzeichnisnamen an: ',
FolderRename : 'Bitte geben Sie den neuen Verzeichnisnamen an: ',
FolderDelete : 'Wollen Sie wirklich den Ordner "%1" löschen?',
FolderRenaming : ' (Umbenennen...)',
FolderDeleting : ' (Löschen...)',
DestinationFolder : 'Destination Folder', // MISSING
// Files
FileRename : 'Bitte geben Sie den neuen Dateinamen an: ',
FileRenameExt : 'Wollen Sie wirklich die Dateierweiterung ändern? Die Datei könnte unbrauchbar werden!',
FileRenaming : 'Umbennenen...',
FileDelete : 'Wollen Sie wirklich die Datei "%1" löschen?',
FilesDelete : 'Are you sure you want to delete %1 files?', // MISSING
FilesLoading : 'Laden...',
FilesEmpty : 'Verzeichnis ist leer.',
DestinationFile : 'Destination File', // MISSING
SkippedFiles : 'List of skipped files:', // MISSING
// Basket
BasketFolder : 'Korb',
BasketClear : 'Korb löschen',
BasketRemove : 'Aus dem Korb entfernen',
BasketOpenFolder : 'Übergeordneten Ordner öffnen',
BasketTruncateConfirm : 'Wollen Sie wirklich alle Dateien aus dem Korb entfernen?',
BasketRemoveConfirm : 'Wollen Sie wirklich die Datei "%1" aus dem Korb entfernen?',
BasketRemoveConfirmMultiple : 'Do you really want to remove %1 files from the basket?', // MISSING
BasketEmpty : 'Keine Dateien im Korb, einfach welche reinziehen.',
BasketCopyFilesHere : 'Dateien aus dem Korb kopieren',
BasketMoveFilesHere : 'Dateien aus dem Korb verschieben',
// Global messages
OperationCompletedSuccess : 'Operation completed successfully.', // MISSING
OperationCompletedErrors : 'Operation completed with errors.', // MISSING
FileError : '%s: %e', // MISSING
// Move and Copy files
MovedFilesNumber : 'Number of files moved: %s.', // MISSING
CopiedFilesNumber : 'Number of files copied: %s.', // MISSING
MoveFailedList : 'The following files could not be moved:<br />%s', // MISSING
CopyFailedList : 'The following files could not be copied:<br />%s', // MISSING
// Toolbar Buttons (some used elsewhere)
Upload : 'Hochladen',
UploadTip : 'Neue Datei hochladen',
Refresh : 'Aktualisieren',
Settings : 'Einstellungen',
Help : 'Hilfe',
HelpTip : 'Hilfe',
// Context Menus
Select : 'Auswählen',
SelectThumbnail : 'Miniatur auswählen',
View : 'Ansehen',
Download : 'Herunterladen',
NewSubFolder : 'Neues Unterverzeichnis',
Rename : 'Umbenennen',
Delete : 'Löschen',
DeleteFiles : 'Delete Files', // MISSING
CopyDragDrop : 'Hierher kopieren',
MoveDragDrop : 'Hierher verschieben',
// Dialogs
RenameDlgTitle : 'Umbenennen',
NewNameDlgTitle : 'Neuer Name',
FileExistsDlgTitle : 'Datei existiert bereits',
SysErrorDlgTitle : 'Systemfehler',
FileOverwrite : 'Überschreiben',
FileAutorename : 'Automatisch umbenennen',
ManuallyRename : 'Manually rename', // MISSING
// Generic
OkBtn : 'OK',
CancelBtn : 'Abbrechen',
CloseBtn : 'Schließen',
// Upload Panel
UploadTitle : 'Neue Datei hochladen',
UploadSelectLbl : 'Bitte wählen Sie die Datei aus',
UploadProgressLbl : '(Die Daten werden übertragen, bitte warten...)',
UploadBtn : 'Ausgewählte Datei hochladen',
UploadBtnCancel : 'Abbrechen',
UploadNoFileMsg : 'Bitte wählen Sie eine Datei auf Ihrem Computer aus.',
UploadNoFolder : 'Bitte ein Verzeichnis vor dem Hochladen wählen.',
UploadNoPerms : 'Datei hochladen nicht erlaubt.',
UploadUnknError : 'Fehler bei Dateitragung.',
UploadExtIncorrect : 'Dateinamekürzel nicht in diesem Verzeichnis erlaubt.',
// Flash Uploads
UploadLabel : 'Dateien zum Hochladen',
UploadTotalFiles : 'Gesamtanzahl Dateien:',
UploadTotalSize : 'Gesamtgröße:',
UploadSend : 'Hochladen',
UploadAddFiles : 'Datei hinzufügen',
UploadClearFiles : 'Dateiliste löschen',
UploadCancel : 'Upload abbrechen',
UploadRemove : 'Entfernen',
UploadRemoveTip : 'Entfernen !f',
UploadUploaded : 'Hochgeladen !n%',
UploadProcessing : 'In Arbeit...',
// Settings Panel
SetTitle : 'Einstellungen',
SetView : 'Ansicht:',
SetViewThumb : 'Miniaturansicht',
SetViewList : 'Liste',
SetDisplay : 'Anzeige:',
SetDisplayName : 'Dateiname',
SetDisplayDate : 'Datum',
SetDisplaySize : 'Dateigröße',
SetSort : 'Sortierung:',
SetSortName : 'nach Dateinamen',
SetSortDate : 'nach Datum',
SetSortSize : 'nach Größe',
SetSortExtension : 'nach Dateiendung',
// Status Bar
FilesCountEmpty : '<Leeres Verzeichnis>',
FilesCountOne : '1 Datei',
FilesCountMany : '%1 Datei',
// Size and Speed
Kb : '%1 KB',
Mb : '%1 MB',
Gb : '%1 GB',
SizePerSecond : '%1/s',
// Connector Error Messages.
ErrorUnknown : 'Ihre Anfrage konnte nicht bearbeitet werden. (Fehler %1)',
Errors :
{
10 : 'Unbekannter Befehl.',
11 : 'Der Ressourcentyp wurde nicht spezifiziert.',
12 : 'Der Ressourcentyp ist nicht gültig.',
102 : 'Ungültiger Datei oder Verzeichnisname.',
103 : 'Ihre Anfrage konnte wegen Authorisierungseinschränkungen nicht durchgeführt werden.',
104 : 'Ihre Anfrage konnte wegen Dateisystemeinschränkungen nicht durchgeführt werden.',
105 : 'Invalid file extension.',
109 : 'Unbekannte Anfrage.',
110 : 'Unbekannter Fehler.',
111 : 'It was not possible to complete the request due to resulting file size.', // MISSING
115 : 'Es existiert bereits eine Datei oder ein Ordner mit dem gleichen Namen.',
116 : 'Verzeichnis nicht gefunden. Bitte aktualisieren Sie die Anzeige und versuchen es noch einmal.',
117 : 'Datei nicht gefunden. Bitte aktualisieren Sie die Dateiliste und versuchen es noch einmal.',
118 : 'Quell- und Zielpfad sind gleich.',
201 : 'Es existiert bereits eine Datei unter gleichem Namen. Die hochgeladene Datei wurde unter "%1" gespeichert.',
202 : 'Ungültige Datei.',
203 : 'ungültige Datei. Die Dateigröße ist zu groß.',
204 : 'Die hochgeladene Datei ist korrupt.',
205 : 'Es existiert kein temp. Ordner für das Hochladen auf den Server.',
206 : 'Das Hochladen wurde aus Sicherheitsgründen abgebrochen. Die Datei enthält HTML-Daten.',
207 : 'Die hochgeladene Datei wurde unter "%1" gespeichert.',
300 : 'Verschieben der Dateien fehlgeschlagen.',
301 : 'Kopieren der Dateien fehlgeschlagen.',
500 : 'Der Dateibrowser wurde aus Sicherheitsgründen deaktiviert. Bitte benachrichtigen Sie Ihren Systemadministrator und prüfen Sie die Konfigurationsdatei.',
501 : 'Die Miniaturansicht wurde deaktivert.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Der Dateinamen darf nicht leer sein.',
FileExists : 'Datei %s existiert bereits.',
FolderEmpty : 'Der Verzeichnisname darf nicht leer sein.',
FolderExists : 'Folder %s already exists.', // MISSING
FolderNameExists : 'Folder already exists.', // MISSING
FileInvChar : 'Der Dateinamen darf nicht eines der folgenden Zeichen enthalten: \n\\ / : * ? " < > |',
FolderInvChar : 'Der Verzeichnisname darf nicht eines der folgenden Zeichen enthalten: \n\\ / : * ? " < > |',
PopupBlockView : 'Die Datei konnte nicht in einem neuen Fenster geöffnet werden. Bitte deaktivieren Sie in Ihrem Browser alle Popup-Blocker für diese Seite.',
XmlError : 'Es war nicht möglich die XML-Antwort von dem Server herunterzuladen.',
XmlEmpty : 'Es war nicht möglich die XML-Antwort von dem Server herunterzuladen. Der Server hat eine leere Nachricht zurückgeschickt.',
XmlRawResponse : 'Raw-Antwort vom Server: %s'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Größenänderung %s',
sizeTooBig : 'Bildgröße kann nicht größer als das Originalbild werden (%size).',
resizeSuccess : 'Bildgröße erfolgreich geändert.',
thumbnailNew : 'Neues Vorschaubild erstellen',
thumbnailSmall : 'Klein (%s)',
thumbnailMedium : 'Mittel (%s)',
thumbnailLarge : 'Groß (%s)',
newSize : 'Eine neue Größe setzen',
width : 'Breite',
height : 'Höhe',
invalidHeight : 'Ungültige Höhe.',
invalidWidth : 'Ungültige Breite.',
invalidName : 'Ungültiger Name.',
newImage : 'Neues Bild erstellen',
noExtensionChange : 'Dateierweiterung kann nicht geändert werden.',
imageSmall : 'Bildgröße zu klein.',
contextMenuName : 'Größenänderung',
lockRatio : 'Größenverhältnis beibehalten',
resetSize : 'Größe zurücksetzen'
},
// Fileeditor plugin
Fileeditor :
{
save : 'Speichern',
fileOpenError : 'Datei kann nicht geöffnet werden.',
fileSaveSuccess : 'Datei erfolgreich gespeichert.',
contextMenuName : 'Bearbeitung',
loadingFile : 'Datei wird geladen, einen Moment noch...'
},
Maximize :
{
maximize : 'Maximieren',
minimize : 'Minimieren'
},
Gallery :
{
current : 'Bild {current} von {total}'
},
Zip :
{
extractHereLabel : 'Extract here', // MISSING
extractToLabel : 'Extract to...', // MISSING
downloadZipLabel : 'Download as zip', // MISSING
compressZipLabel : 'Compress to zip', // MISSING
removeAndExtract : 'Remove existing and extract', // MISSING
extractAndOverwrite : 'Extract overwriting existing files', // MISSING
extractSuccess : 'File extracted successfully.' // MISSING
},
Search :
{
searchPlaceholder : 'Suche'
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://cksource.com/ckfinder
* Copyright (C) 2007-2014, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file, and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying, or distributing this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object for the Polish
* language.
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['pl'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, wyłączone</span>',
confirmCancel : 'Pewne opcje zostały zmienione. Czy na pewno zamknąć okno dialogowe?',
ok : 'OK',
cancel : 'Anuluj',
confirmationTitle : 'Potwierdzenie',
messageTitle : 'Informacja',
inputTitle : 'Pytanie',
undo : 'Cofnij',
redo : 'Ponów',
skip : 'Pomiń',
skipAll : 'Pomiń wszystkie',
makeDecision : 'Wybierz jedną z opcji:',
rememberDecision: 'Zapamiętaj mój wybór'
},
// Language direction, 'ltr' or 'rtl'.
dir : 'ltr',
HelpLang : 'pl',
LangCode : 'pl',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'yyyy-mm-dd HH:MM',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Foldery',
FolderLoading : 'Ładowanie...',
FolderNew : 'Podaj nazwę nowego folderu: ',
FolderRename : 'Podaj nową nazwę folderu: ',
FolderDelete : 'Czy na pewno chcesz usunąć folder "%1"?',
FolderRenaming : ' (Zmieniam nazwę...)',
FolderDeleting : ' (Kasowanie...)',
DestinationFolder : 'Folder docelowy',
// Files
FileRename : 'Podaj nową nazwę pliku: ',
FileRenameExt : 'Czy na pewno chcesz zmienić rozszerzenie pliku? Może to spowodować problemy z otwieraniem pliku przez innych użytkowników.',
FileRenaming : 'Zmieniam nazwę...',
FileDelete : 'Czy na pewno chcesz usunąć plik "%1"?',
FilesDelete : 'Czy na pewno chcesz usunąć pliki (razem: %1)?',
FilesLoading : 'Ładowanie...',
FilesEmpty : 'Folder jest pusty',
DestinationFile : 'Plik docelowy',
SkippedFiles : 'Lista pominiętych plików:',
// Basket
BasketFolder : 'Koszyk',
BasketClear : 'Wyczyść koszyk',
BasketRemove : 'Usuń z koszyka',
BasketOpenFolder : 'Otwórz folder z plikiem',
BasketTruncateConfirm : 'Czy naprawdę chcesz usunąć wszystkie pliki z koszyka?',
BasketRemoveConfirm : 'Czy naprawdę chcesz usunąć plik "%1" z koszyka?',
BasketRemoveConfirmMultiple : 'Czy naprawdę chcesz usunąć pliki (razem: %1) z koszyka?',
BasketEmpty : 'Brak plików w koszyku. Aby dodać plik, przeciągnij i upuść (drag\'n\'drop) dowolny plik do koszyka.',
BasketCopyFilesHere : 'Skopiuj pliki z koszyka',
BasketMoveFilesHere : 'Przenieś pliki z koszyka',
// Global messages
OperationCompletedSuccess : 'Operation completed successfully.', // MISSING
OperationCompletedErrors : 'Operation completed with errors.', // MISSING
FileError : '%s: %e', // MISSING
// Move and Copy files
MovedFilesNumber : 'Number of files moved: %s.', // MISSING
CopiedFilesNumber : 'Number of files copied: %s.', // MISSING
MoveFailedList : 'The following files could not be moved:<br />%s', // MISSING
CopyFailedList : 'The following files could not be copied:<br />%s', // MISSING
// Toolbar Buttons (some used elsewhere)
Upload : 'Wyślij',
UploadTip : 'Wyślij plik',
Refresh : 'Odśwież',
Settings : 'Ustawienia',
Help : 'Pomoc',
HelpTip : 'Wskazówka',
// Context Menus
Select : 'Wybierz',
SelectThumbnail : 'Wybierz miniaturkę',
View : 'Zobacz',
Download : 'Pobierz',
NewSubFolder : 'Nowy podfolder',
Rename : 'Zmień nazwę',
Delete : 'Usuń',
DeleteFiles : 'Usuń pliki',
CopyDragDrop : 'Skopiuj tutaj',
MoveDragDrop : 'Przenieś tutaj',
// Dialogs
RenameDlgTitle : 'Zmiana nazwy',
NewNameDlgTitle : 'Nowa nazwa',
FileExistsDlgTitle : 'Plik już istnieje',
SysErrorDlgTitle : 'Błąd systemu',
FileOverwrite : 'Nadpisz',
FileAutorename : 'Zmień automatycznie nazwę',
ManuallyRename : 'Zmień nazwę ręcznie',
// Generic
OkBtn : 'OK',
CancelBtn : 'Anuluj',
CloseBtn : 'Zamknij',
// Upload Panel
UploadTitle : 'Wyślij plik',
UploadSelectLbl : 'Wybierz plik',
UploadProgressLbl : '(Trwa wysyłanie pliku, proszę czekać...)',
UploadBtn : 'Wyślij wybrany plik',
UploadBtnCancel : 'Anuluj',
UploadNoFileMsg : 'Wybierz plik ze swojego komputera.',
UploadNoFolder : 'Wybierz folder przed wysłaniem pliku.',
UploadNoPerms : 'Wysyłanie plików nie jest dozwolone.',
UploadUnknError : 'Błąd podczas wysyłania pliku.',
UploadExtIncorrect : 'Rozszerzenie pliku nie jest dozwolone w tym folderze.',
// Flash Uploads
UploadLabel : 'Pliki do wysłania',
UploadTotalFiles : 'Ilość razem:',
UploadTotalSize : 'Rozmiar razem:',
UploadSend : 'Wyślij',
UploadAddFiles : 'Dodaj pliki',
UploadClearFiles : 'Wyczyść wszystko',
UploadCancel : 'Anuluj wysyłanie',
UploadRemove : 'Usuń',
UploadRemoveTip : 'Usuń !f',
UploadUploaded : 'Wysłano: !n%',
UploadProcessing : 'Przetwarzanie...',
// Settings Panel
SetTitle : 'Ustawienia',
SetView : 'Widok:',
SetViewThumb : 'Miniaturki',
SetViewList : 'Lista',
SetDisplay : 'Wyświetlanie:',
SetDisplayName : 'Nazwa pliku',
SetDisplayDate : 'Data',
SetDisplaySize : 'Rozmiar pliku',
SetSort : 'Sortowanie:',
SetSortName : 'wg nazwy pliku',
SetSortDate : 'wg daty',
SetSortSize : 'wg rozmiaru',
SetSortExtension : 'wg rozszerzenia',
// Status Bar
FilesCountEmpty : '<Pusty folder>',
FilesCountOne : '1 plik',
FilesCountMany : 'Ilość plików: %1',
// Size and Speed
Kb : '%1 KB',
Mb : '%1 MB',
Gb : '%1 GB',
SizePerSecond : '%1/s',
// Connector Error Messages.
ErrorUnknown : 'Wykonanie operacji zakończyło się niepowodzeniem. (Błąd %1)',
Errors :
{
10 : 'Nieprawidłowe polecenie (command).',
11 : 'Brak wymaganego parametru: typ danych (resource type).',
12 : 'Nieprawidłowy typ danych (resource type).',
102 : 'Nieprawidłowa nazwa pliku lub folderu.',
103 : 'Wykonanie operacji nie jest możliwe: brak uprawnień.',
104 : 'Wykonanie operacji nie powiodło się z powodu niewystarczających uprawnień do systemu plików.',
105 : 'Nieprawidłowe rozszerzenie.',
109 : 'Nieprawiłowe żądanie.',
110 : 'Niezidentyfikowany błąd.',
111 : 'Wykonanie operacji nie powiodło się z powodu zbyt dużego rozmiaru pliku wynikowego.',
115 : 'Plik lub folder o podanej nazwie już istnieje.',
116 : 'Nie znaleziono folderu. Odśwież panel i spróbuj ponownie.',
117 : 'Nie znaleziono pliku. Odśwież listę plików i spróbuj ponownie.',
118 : 'Ścieżki źródłowa i docelowa są jednakowe.',
201 : 'Plik o podanej nazwie już istnieje. Nazwa przesłanego pliku została zmieniona na "%1".',
202 : 'Nieprawidłowy plik.',
203 : 'Nieprawidłowy plik. Plik przekracza dozwolony rozmiar.',
204 : 'Przesłany plik jest uszkodzony.',
205 : 'Brak folderu tymczasowego na serwerze do przesyłania plików.',
206 : 'Przesyłanie pliku zakończyło się niepowodzeniem z powodów bezpieczeństwa. Plik zawiera dane przypominające HTML.',
207 : 'Nazwa przesłanego pliku została zmieniona na "%1".',
300 : 'Przenoszenie nie powiodło się.',
301 : 'Kopiowanie nie powiodo się.',
500 : 'Menedżer plików jest wyłączony z powodów bezpieczeństwa. Skontaktuj się z administratorem oraz sprawdź plik konfiguracyjny CKFindera.',
501 : 'Tworzenie miniaturek jest wyłączone.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Nazwa pliku nie może być pusta.',
FileExists : 'Plik %s już istnieje.',
FolderEmpty : 'Nazwa folderu nie może być pusta.',
FolderExists : 'Folder %s już istnieje.',
FolderNameExists : 'Folder już istnieje.',
FileInvChar : 'Nazwa pliku nie może zawierać żadnego z podanych znaków: \n\\ / : * ? " < > |',
FolderInvChar : 'Nazwa folderu nie może zawierać żadnego z podanych znaków: \n\\ / : * ? " < > |',
PopupBlockView : 'Otwarcie pliku w nowym oknie nie powiodło się. Należy zmienić konfigurację przeglądarki i wyłączyć wszelkie blokady okienek popup dla tej strony.',
XmlError : 'Nie można poprawnie załadować odpowiedzi XML z serwera WWW.',
XmlEmpty : 'Nie można załadować odpowiedzi XML z serwera WWW. Serwer zwrócił pustą odpowiedź.',
XmlRawResponse : 'Odpowiedź serwera: %s'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Zmiana rozmiaru %s',
sizeTooBig : 'Nie możesz zmienić wysokości lub szerokości na wartość większą od oryginalnego rozmiaru (%size).',
resizeSuccess : 'Obrazek został pomyślnie przeskalowany.',
thumbnailNew : 'Utwórz nową miniaturkę',
thumbnailSmall : 'Mała (%s)',
thumbnailMedium : 'Średnia (%s)',
thumbnailLarge : 'Duża (%s)',
newSize : 'Podaj nowe wymiary',
width : 'Szerokość',
height : 'Wysokość',
invalidHeight : 'Nieprawidłowa wysokość.',
invalidWidth : 'Nieprawidłowa szerokość.',
invalidName : 'Nieprawidłowa nazwa pliku.',
newImage : 'Utwórz nowy obrazek',
noExtensionChange : 'Rozszerzenie pliku nie może zostac zmienione.',
imageSmall : 'Plik źródłowy jest zbyt mały.',
contextMenuName : 'Zmień rozmiar',
lockRatio : 'Zablokuj proporcje',
resetSize : 'Przywróć rozmiar'
},
// Fileeditor plugin
Fileeditor :
{
save : 'Zapisz',
fileOpenError : 'Nie udało się otworzyć pliku.',
fileSaveSuccess : 'Plik został zapisany pomyślnie.',
contextMenuName : 'Edytuj',
loadingFile : 'Trwa ładowanie pliku, proszę czekać...'
},
Maximize :
{
maximize : 'Maksymalizuj',
minimize : 'Minimalizuj'
},
Gallery :
{
current : 'Obrazek {current} z {total}'
},
Zip :
{
extractHereLabel : 'Wypakuj tutaj',
extractToLabel : 'Wypakuj do...',
downloadZipLabel : 'Pobierz jako zip',
compressZipLabel : 'Kompresuj do zip',
removeAndExtract : 'Usuń poprzedni i wypakuj',
extractAndOverwrite : 'Wypakuj do bieżącego nadpisując istniejące pliki',
extractSuccess : 'Plik został pomyślnie wypakowany.'
},
Search :
{
searchPlaceholder : 'Szukaj'
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://cksource.com/ckfinder
* Copyright (C) 2007-2014, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file, and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying, or distributing this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object for the Vietnamese
* language.
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['vi'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, không khả dụng</span>',
confirmCancel : 'Vài tùy chọn đã thay đổi. Bạn có muốn đóng hộp thoại?',
ok : 'OK',
cancel : 'Hủy',
confirmationTitle : 'Xác nhận',
messageTitle : 'Thông tin',
inputTitle : 'Câu hỏi',
undo : 'Hoàn tác',
redo : 'Làm lại',
skip : 'Bỏ qua',
skipAll : 'Bỏ qua tất cả',
makeDecision : 'Chọn hành động nào?',
rememberDecision: 'Ghi nhớ quyết định này'
},
// Language direction, 'ltr' or 'rtl'.
dir : 'ltr',
HelpLang : 'en',
LangCode : 'vi',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'd/m/yyyy h:MM aa',
DateAmPm : ['SA', 'CH'],
// Folders
FoldersTitle : 'Thư mục',
FolderLoading : 'Đang tải...',
FolderNew : 'Xin chọn tên cho thư mục mới: ',
FolderRename : 'Xin chọn tên mới cho thư mục: ',
FolderDelete : 'Bạn có chắc muốn xóa thư mục "%1"?',
FolderRenaming : ' (Đang đổi tên...)',
FolderDeleting : ' (Đang xóa...)',
DestinationFolder : 'Destination Folder', // MISSING
// Files
FileRename : 'Xin nhập tên tập tin mới: ',
FileRenameExt : 'Bạn có chắc muốn đổi phần mở rộng? Tập tin có thể sẽ không dùng được.',
FileRenaming : 'Đang đổi tên...',
FileDelete : 'Bạn có chắc muốn xóa tập tin "%1"?',
FilesDelete : 'Are you sure you want to delete %1 files?', // MISSING
FilesLoading : 'Đang tải...',
FilesEmpty : 'Thư mục trống.',
DestinationFile : 'Destination File', // MISSING
SkippedFiles : 'List of skipped files:', // MISSING
// Basket
BasketFolder : 'Rổ',
BasketClear : 'Dọn rổ',
BasketRemove : 'Xóa khỏi rổ',
BasketOpenFolder : 'Mở thư mục cha',
BasketTruncateConfirm : 'Bạn có chắc muốn bỏ tất cả tập tin trong rổ?',
BasketRemoveConfirm : 'Bạn có chắc muốn bỏ tập tin "%1" khỏi rổ?',
BasketRemoveConfirmMultiple : 'Do you really want to remove %1 files from the basket?', // MISSING
BasketEmpty : 'Không có tập tin trong rổ, hãy kéo và thả tập tin vào rổ.',
BasketCopyFilesHere : 'Chép tập tin từ rổ',
BasketMoveFilesHere : 'Chuyển tập tin từ rổ',
// Global messages
OperationCompletedSuccess : 'Operation completed successfully.', // MISSING
OperationCompletedErrors : 'Operation completed with errors.', // MISSING
FileError : '%s: %e', // MISSING
// Move and Copy files
MovedFilesNumber : 'Number of files moved: %s.', // MISSING
CopiedFilesNumber : 'Number of files copied: %s.', // MISSING
MoveFailedList : 'The following files could not be moved:<br />%s', // MISSING
CopyFailedList : 'The following files could not be copied:<br />%s', // MISSING
// Toolbar Buttons (some used elsewhere)
Upload : 'Tải lên',
UploadTip : 'Tải tập tin mới',
Refresh : 'Làm tươi',
Settings : 'Thiết lập',
Help : 'Hướng dẫn',
HelpTip : 'Hướng dẫn',
// Context Menus
Select : 'Chọn',
SelectThumbnail : 'Chọn ảnh mẫu',
View : 'Xem',
Download : 'Tải về',
NewSubFolder : 'Tạo thư mục con',
Rename : 'Đổi tên',
Delete : 'Xóa',
DeleteFiles : 'Delete Files', // MISSING
CopyDragDrop : 'Sao chép ở đây',
MoveDragDrop : 'Di chuyển ở đây',
// Dialogs
RenameDlgTitle : 'Đổi tên',
NewNameDlgTitle : 'Tên mới',
FileExistsDlgTitle : 'Tập tin đã tồn tại',
SysErrorDlgTitle : 'Lỗi hệ thống',
FileOverwrite : 'Ghi đè',
FileAutorename : 'Tự đổi tên',
ManuallyRename : 'Manually rename', // MISSING
// Generic
OkBtn : 'OK',
CancelBtn : 'Hủy bỏ',
CloseBtn : 'Đóng',
// Upload Panel
UploadTitle : 'Tải tập tin mới',
UploadSelectLbl : 'Chọn tập tin tải lên',
UploadProgressLbl : '(Đang tải lên, vui lòng chờ...)',
UploadBtn : 'Tải tập tin đã chọn',
UploadBtnCancel : 'Hủy bỏ',
UploadNoFileMsg : 'Xin chọn một tập tin trong máy tính.',
UploadNoFolder : 'Xin chọn thư mục trước khi tải lên.',
UploadNoPerms : 'Không được phép tải lên.',
UploadUnknError : 'Lỗi khi tải tập tin.',
UploadExtIncorrect : 'Kiểu tập tin không được chấp nhận trong thư mục này.',
// Flash Uploads
UploadLabel : 'Tập tin sẽ tải:',
UploadTotalFiles : 'Tổng số tập tin:',
UploadTotalSize : 'Dung lượng tổng cộng:',
UploadSend : 'Tải lên',
UploadAddFiles : 'Thêm tập tin',
UploadClearFiles : 'Xóa tập tin',
UploadCancel : 'Hủy tải',
UploadRemove : 'Xóa',
UploadRemoveTip : 'Xóa !f',
UploadUploaded : 'Đã tải !n%',
UploadProcessing : 'Đang xử lí...',
// Settings Panel
SetTitle : 'Thiết lập',
SetView : 'Xem:',
SetViewThumb : 'Ảnh mẫu',
SetViewList : 'Danh sách',
SetDisplay : 'Hiển thị:',
SetDisplayName : 'Tên tập tin',
SetDisplayDate : 'Ngày',
SetDisplaySize : 'Dung lượng',
SetSort : 'Sắp xếp:',
SetSortName : 'theo tên',
SetSortDate : 'theo ngày',
SetSortSize : 'theo dung lượng',
SetSortExtension : 'theo phần mở rộng',
// Status Bar
FilesCountEmpty : '<Thư mục rỗng>',
FilesCountOne : '1 tập tin',
FilesCountMany : '%1 tập tin',
// Size and Speed
Kb : '%1 KB',
Mb : '%1 MB',
Gb : '%1 GB',
SizePerSecond : '%1/s',
// Connector Error Messages.
ErrorUnknown : 'Không thể hoàn tất yêu cầu. (Lỗi %1)',
Errors :
{
10 : 'Lệnh không hợp lệ.',
11 : 'Kiểu tài nguyên không được chỉ định trong yêu cầu.',
12 : 'Kiểu tài nguyên yêu cầu không hợp lệ.',
102 : 'Tên tập tin hay thư mục không hợp lệ.',
103 : 'Không thể hoàn tất yêu cầu vì giới hạn quyền.',
104 : 'Không thể hoàn tất yêu cầu vì giới hạn quyền của hệ thống tập tin.',
105 : 'Phần mở rộng tập tin không hợp lệ.',
109 : 'Yêu cầu không hợp lệ.',
110 : 'Lỗi không xác định.',
111 : 'It was not possible to complete the request due to resulting file size.', // MISSING
115 : 'Tập tin hoặc thư mục cùng tên đã tồn tại.',
116 : 'Không thấy thư mục. Hãy làm tươi và thử lại.',
117 : 'Không thấy tập tin. Hãy làm tươi và thử lại.',
118 : 'Đường dẫn nguồn và đích giống nhau.',
201 : 'Tập tin cùng tên đã tồn tại. Tập tin vừa tải lên được đổi tên thành "%1".',
202 : 'Tập tin không hợp lệ.',
203 : 'Tập tin không hợp lệ. Dung lượng quá lớn.',
204 : 'Tập tin tải lên bị hỏng.',
205 : 'Không có thư mục tạm để tải tập tin.',
206 : 'Huỷ tải lên vì lí do bảo mật. Tập tin chứa dữ liệu giống HTML.',
207 : 'Tập tin được đổi tên thành "%1".',
300 : 'Di chuyển tập tin thất bại.',
301 : 'Chép tập tin thất bại.',
500 : 'Trình duyệt tập tin bị vô hiệu vì lí do bảo mật. Xin liên hệ quản trị hệ thống và kiểm tra tập tin cấu hình CKFinder.',
501 : 'Chức năng hỗ trợ ảnh mẫu bị vô hiệu.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Không thể để trống tên tập tin.',
FileExists : 'Tập tin %s đã tồn tại.',
FolderEmpty : 'Không thể để trống tên thư mục.',
FolderExists : 'Folder %s already exists.', // MISSING
FolderNameExists : 'Folder already exists.', // MISSING
FileInvChar : 'Tên tập tin không thể chưa các kí tự: \n\\ / : * ? " < > |',
FolderInvChar : 'Tên thư mục không thể chứa các kí tự: \n\\ / : * ? " < > |',
PopupBlockView : 'Không thể mở tập tin trong cửa sổ mới. Hãy kiểm tra trình duyệt và tắt chức năng chặn popup trên trang web này.',
XmlError : 'Không thể nạp hồi đáp XML từ máy chủ web.',
XmlEmpty : 'Không thể nạp hồi đáp XML từ máy chủ web. Dữ liệu rỗng.',
XmlRawResponse : 'Hồi đáp thô từ máy chủ: %s'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Đổi kích thước %s',
sizeTooBig : 'Không thể đặt chiều cao hoặc rộng to hơn kích thước gốc (%size).',
resizeSuccess : 'Đổi kích thước ảnh thành công.',
thumbnailNew : 'Tạo ảnh mẫu mới',
thumbnailSmall : 'Nhỏ (%s)',
thumbnailMedium : 'Vừa (%s)',
thumbnailLarge : 'Lớn (%s)',
newSize : 'Chọn kích thước mới',
width : 'Rộng',
height : 'Cao',
invalidHeight : 'Chiều cao không hợp lệ.',
invalidWidth : 'Chiều rộng không hợp lệ.',
invalidName : 'Tên tập tin không hợp lệ.',
newImage : 'Tạo ảnh mới',
noExtensionChange : 'Không thể thay đổi phần mở rộng.',
imageSmall : 'Ảnh nguồn quá nhỏ.',
contextMenuName : 'Đổi kích thước',
lockRatio : 'Khoá tỉ lệ',
resetSize : 'Đặt lại kích thước'
},
// Fileeditor plugin
Fileeditor :
{
save : 'Lưu',
fileOpenError : 'Không thể mở tập tin.',
fileSaveSuccess : 'Lưu tập tin thành công.',
contextMenuName : 'Sửa',
loadingFile : 'Đang tải tập tin, xin chờ...'
},
Maximize :
{
maximize : 'Cực đại hóa',
minimize : 'Cực tiểu hóa'
},
Gallery :
{
current : 'Hình thứ {current} trên {total}'
},
Zip :
{
extractHereLabel : 'Extract here', // MISSING
extractToLabel : 'Extract to...', // MISSING
downloadZipLabel : 'Download as zip', // MISSING
compressZipLabel : 'Compress to zip', // MISSING
removeAndExtract : 'Remove existing and extract', // MISSING
extractAndOverwrite : 'Extract overwriting existing files', // MISSING
extractSuccess : 'File extracted successfully.' // MISSING
},
Search :
{
searchPlaceholder : 'Tìm kiếm'
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://cksource.com/ckfinder
* Copyright (C) 2007-2014, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file, and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying, or distributing this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object for the Hungarian
* language.
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['hu'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, nem elérhető</span>',
confirmCancel : 'Az űrlap tartalma megváltozott, ám a változásokat nem rögzítette. Biztosan be szeretné zárni az űrlapot?',
ok : 'Rendben',
cancel : 'Mégsem',
confirmationTitle : 'Megerősítés',
messageTitle : 'Információ',
inputTitle : 'Kérdés',
undo : 'Visszavonás',
redo : 'Ismétlés',
skip : 'Kihagy',
skipAll : 'Mindet kihagy',
makeDecision : 'Mi történjen a fájllal?',
rememberDecision: 'Jegyezze meg a választásomat'
},
// Language direction, 'ltr' or 'rtl'.
dir : 'ltr',
HelpLang : 'en',
LangCode : 'hu',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'yyyy.mm.dd. HH:MM',
DateAmPm : ['de.', 'du.'],
// Folders
FoldersTitle : 'Mappák',
FolderLoading : 'Betöltés...',
FolderNew : 'Kérem adja meg a mappa nevét: ',
FolderRename : 'Kérem adja meg a mappa új nevét: ',
FolderDelete : 'Biztosan törölni szeretné a következő mappát: "%1"?',
FolderRenaming : ' (átnevezés...)',
FolderDeleting : ' (törlés...)',
DestinationFolder : 'Cél mappa',
// Files
FileRename : 'Kérem adja meg a fájl új nevét: ',
FileRenameExt : 'Biztosan szeretné módosítani a fájl kiterjesztését? A fájl esetleg használhatatlan lesz.',
FileRenaming : 'Átnevezés...',
FileDelete : 'Biztosan törli a következő fájlt: "%1"?',
FilesDelete : 'Biztosan törli a kijelölt %1 fájlt?',
FilesLoading : 'Betöltés...',
FilesEmpty : 'A mappa üres.',
DestinationFile : 'Cél fájl',
SkippedFiles : 'A kihagyott fájlok listája:',
// Basket
BasketFolder : 'Kosár',
BasketClear : 'Kosár ürítése',
BasketRemove : 'Törlés a kosárból',
BasketOpenFolder : 'A fájlt tartalmazó mappa megnyitása',
BasketTruncateConfirm : 'Biztosan szeretne minden fájlt törölni a kosárból?',
BasketRemoveConfirm : 'Biztosan törölni szeretné a(z) "%1" nevű fájlt a kosárból?',
BasketRemoveConfirmMultiple : 'Biztosan törölni szeretné a kijelült %1 fájlt a kosárból?',
BasketEmpty : 'Nincsenek fájlok a kosárban.',
BasketCopyFilesHere : 'Fájlok másolása a kosárból',
BasketMoveFilesHere : 'Fájlok áthelyezése a kosárból',
// Global messages
OperationCompletedSuccess : 'A művelet sikeresen befejeződött.',
OperationCompletedErrors : 'A művelet közben hiba történt.',
FileError : '%s: %e',
// Move and Copy files
MovedFilesNumber : 'Az áthelyezett fájlok száma: %s.',
CopiedFilesNumber : 'A másolt fájlok száma: %s.',
MoveFailedList : 'A következő fájlok nem helyezhetőek át:<br />%s',
CopyFailedList : 'A következő fájlok nem másolhatóak:<br />%s',
// Toolbar Buttons (some used elsewhere)
Upload : 'Feltöltés',
UploadTip : 'Új fájl feltöltése',
Refresh : 'Frissítés',
Settings : 'Beállítások',
Help : 'Súgó',
HelpTip : 'Súgó (angolul)',
// Context Menus
Select : 'Kiválaszt',
SelectThumbnail : 'Bélyegkép kiválasztása',
View : 'Megtekintés',
Download : 'Letöltés',
NewSubFolder : 'Új almappa',
Rename : 'Átnevezés',
Delete : 'Törlés',
DeleteFiles : 'Fájlok törlése',
CopyDragDrop : 'Másolás ide',
MoveDragDrop : 'Áthelyezés ide',
// Dialogs
RenameDlgTitle : 'Átnevezés',
NewNameDlgTitle : 'Új név',
FileExistsDlgTitle : 'A fájl már létezik',
SysErrorDlgTitle : 'Rendszerhiba',
FileOverwrite : 'Felülír',
FileAutorename : 'Automatikus átnevezés',
ManuallyRename : 'Átnevezés',
// Generic
OkBtn : 'OK',
CancelBtn : 'Mégsem',
CloseBtn : 'Bezárás',
// Upload Panel
UploadTitle : 'Új fájl feltöltése',
UploadSelectLbl : 'Válassza ki a feltölteni kívánt fájlt',
UploadProgressLbl : '(A feltöltés folyamatban, kérem várjon...)',
UploadBtn : 'A kiválasztott fájl feltöltése',
UploadBtnCancel : 'Mégsem',
UploadNoFileMsg : 'Kérem válassza ki a fájlt a számítógépéről.',
UploadNoFolder : 'A feltöltés előtt válasszon mappát.',
UploadNoPerms : 'A fájlok feltöltése nem engedélyezett.',
UploadUnknError : 'Hiba a fájl feltöltése közben.',
UploadExtIncorrect : 'A fájl kiterjesztése nem engedélyezett ebben a mappában.',
// Flash Uploads
UploadLabel : 'Feltöltendő fájlok',
UploadTotalFiles : 'Összes fájl:',
UploadTotalSize : 'Összméret:',
UploadSend : 'Feltöltés',
UploadAddFiles : 'Fájl hozzáadása',
UploadClearFiles : 'Feltöltési lista törlése',
UploadCancel : 'Feltöltés megszakítása',
UploadRemove : 'Eltávolít',
UploadRemoveTip : 'Fájl eltávolítása a listáról: !f',
UploadUploaded : 'Feltöltve !n%',
UploadProcessing : 'Feldolgozás...',
// Settings Panel
SetTitle : 'Beállítások',
SetView : 'Nézet:',
SetViewThumb : 'bélyegképes',
SetViewList : 'listás',
SetDisplay : 'Megjelenik:',
SetDisplayName : 'fájl neve',
SetDisplayDate : 'dátum',
SetDisplaySize : 'fájlméret',
SetSort : 'Rendezés:',
SetSortName : 'fájlnév',
SetSortDate : 'dátum',
SetSortSize : 'méret',
SetSortExtension : 'kiterjesztés',
// Status Bar
FilesCountEmpty : '<üres mappa>',
FilesCountOne : '1 fájl',
FilesCountMany : '%1 fájl',
// Size and Speed
Kb : '%1 KB',
Mb : '%1 MB',
Gb : '%1 GB',
SizePerSecond : '%1/s',
// Connector Error Messages.
ErrorUnknown : 'A parancsot nem sikerült végrehajtani. (Hiba: %1)',
Errors :
{
10 : 'Érvénytelen parancs.',
11 : 'A fájl típusa nem lett a kérés során beállítva.',
12 : 'A kívánt fájl típus érvénytelen.',
102 : 'Érvénytelen fájl vagy könyvtárnév.',
103 : 'Hitelesítési problémák miatt nem sikerült a kérést teljesíteni.',
104 : 'Jogosultsági problémák miatt nem sikerült a kérést teljesíteni.',
105 : 'Érvénytelen fájl kiterjesztés.',
109 : 'Érvénytelen kérés.',
110 : 'Ismeretlen hiba.',
111 : 'A kérés nem teljesíthető a létrejövő fájl mérete miatt.',
115 : 'A fálj vagy mappa már létezik ezen a néven.',
116 : 'Mappa nem található. Kérem frissítsen és próbálja újra.',
117 : 'Fájl nem található. Kérem frissítsen és próbálja újra.',
118 : 'A forrás és a cél azonos.',
201 : 'Ilyen nevű fájl már létezett. A feltöltött fájl a következőre lett átnevezve: "%1".',
202 : 'Érvénytelen fájl.',
203 : 'Érvénytelen fájl. A fájl mérete túl nagy.',
204 : 'A feltöltött fájl hibás.',
205 : 'A szerveren nem található a feltöltéshez ideiglenes mappa.',
206 : 'A fájl feltötése biztonsági okból megszakadt. A fájl HTML adatokat tartalmaz.',
207 : 'El fichero subido ha sido renombrado como "%1".',
300 : 'A fájl(ok) áthelyezése sikertelen.',
301 : 'A fájl(ok) másolása sikertelen.',
500 : 'A fájl-tallózó biztonsági okok miatt nincs engedélyezve. Kérem vegye fel a kapcsolatot a rendszer üzemeltetőjével és ellenőrizze a CKFinder konfigurációs fájlt.',
501 : 'A bélyegkép támogatás nincs engedélyezve.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'A fájl neve nem lehet üres.',
FileExists : 'A(z) %s fájl már létezik.',
FolderEmpty : 'A mappa neve nem lehet üres.',
FolderExists : 'A(z) %s mappa már létezik.',
FolderNameExists : 'A mappa létezik.',
FileInvChar : 'A fájl neve nem tartalmazhatja a következő karaktereket: \n\\ / : * ? " < > |',
FolderInvChar : 'A mappa neve nem tartalmazhatja a következő karaktereket: \n\\ / : * ? " < > |',
PopupBlockView : 'A felugró ablak megnyitása nem sikerült. Kérem ellenőrizze a böngészője beállításait és tiltsa le a felugró ablakokat blokkoló alkalmazásait erre a honlapra.',
XmlError : 'A webszervertől érkező XML válasz nem dolgozható fel megfelelően.',
XmlEmpty : 'A webszervertől érkező XML válasz nem dolgozható fel. A szerver üres választ küldött.',
XmlRawResponse : 'A szerver az alábbi választ adta: %s'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Kép átméretezése: %s',
sizeTooBig : 'Nem adható meg az eredeti fájlnál nagyobb méret (%size).',
resizeSuccess : 'A kép sikeresen átméretezve.',
thumbnailNew : 'Új bélyegkép létrehozása',
thumbnailSmall : 'Kicsi (%s)',
thumbnailMedium : 'Közepes (%s)',
thumbnailLarge : 'Nagy (%s)',
newSize : 'Adja meg az új méretet',
width : 'Szélesség',
height : 'Magasság',
invalidHeight : 'Érvénytelen magasság.',
invalidWidth : 'Érvénytelen szélesség.',
invalidName : 'Érvénytelen fájlnév.',
newImage : 'Létrehozás új fotóként',
noExtensionChange : 'A fájl kiterjesztése nem változtatható.',
imageSmall : 'Az eredeti fotó mérete túl kicsi.',
contextMenuName : 'Átméretezés',
lockRatio : 'Arány megtartása',
resetSize : 'Eredeti méret'
},
// Fileeditor plugin
Fileeditor :
{
save : 'Mentés',
fileOpenError : 'A fájl nem nyitható meg.',
fileSaveSuccess : 'A fájl sikeresen mentve.',
contextMenuName : 'Szerkesztés',
loadingFile : 'Fájl betöltése, kérem várjon...'
},
Maximize :
{
maximize : 'Teljes méret',
minimize : 'Kis méret'
},
Gallery :
{
current : 'Fotó: {current} / {total}'
},
Zip :
{
extractHereLabel : 'Kicsomagolás ide',
extractToLabel : 'Kicsomagolás új mappába...',
downloadZipLabel : 'Letöltés zip fájlként',
compressZipLabel : 'Becsomagolás zip fájlba',
removeAndExtract : 'Létező törlése és kicsomagolás',
extractAndOverwrite : 'Létező felülírása és kicsomagolás',
extractSuccess : 'A fájl kicsomagolása megtörtént.'
},
Search :
{
searchPlaceholder : 'Keresés'
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://cksource.com/ckfinder
* Copyright (C) 2007-2014, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file, and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying, or distributing this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object for the Croatian
* language.
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['hr'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, nedostupno</span>',
confirmCancel : 'Neke od opcija su promjenjene. Sigurno želite zatvoriti prozor??',
ok : 'U redu',
cancel : 'Poništi',
confirmationTitle : 'Potvrda',
messageTitle : 'Informacija',
inputTitle : 'Pitanje',
undo : 'Poništi',
redo : 'Preuredi',
skip : 'Preskoči',
skipAll : 'Preskoči sve',
makeDecision : 'Što bi trebali napraviti?',
rememberDecision: 'Zapamti moj izbor'
},
// Language direction, 'ltr' or 'rtl'.
dir : 'ltr',
HelpLang : 'en',
LangCode : 'hr',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'm/d/yyyy h:MM aa',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Direktoriji',
FolderLoading : 'Učitavam...',
FolderNew : 'Unesite novo ime direktorija: ',
FolderRename : 'Unesite novo ime direktorija: ',
FolderDelete : 'Sigurno želite obrisati direktorij "%1"?',
FolderRenaming : ' (Mijenjam ime...)',
FolderDeleting : ' (Brišem...)',
DestinationFolder : 'Destination Folder', // MISSING
// Files
FileRename : 'Unesite novo ime datoteke: ',
FileRenameExt : 'Sigurno želite promijeniti vrstu datoteke? Datoteka može postati neiskoristiva.',
FileRenaming : 'Mijenjam ime...',
FileDelete : 'Sigurno želite obrisati datoteku "%1"?',
FilesDelete : 'Are you sure you want to delete %1 files?', // MISSING
FilesLoading : 'Učitavam...',
FilesEmpty : 'Direktorij je prazan.',
DestinationFile : 'Destination File', // MISSING
SkippedFiles : 'List of skipped files:', // MISSING
// Basket
BasketFolder : 'Košara',
BasketClear : 'Isprazni košaru',
BasketRemove : 'Ukloni iz košare',
BasketOpenFolder : 'Otvori nadređeni direktorij',
BasketTruncateConfirm : 'Sigurno želite obrisati sve datoteke iz košare?',
BasketRemoveConfirm : 'Sigurno želite obrisati datoteku "%1" iz košare?',
BasketRemoveConfirmMultiple : 'Do you really want to remove %1 files from the basket?', // MISSING
BasketEmpty : 'Nema niti jedne datoteke, ubacite koju.',
BasketCopyFilesHere : 'Kopiraj datoteke iz košare',
BasketMoveFilesHere : 'Premjesti datoteke iz košare',
// Global messages
OperationCompletedSuccess : 'Operation completed successfully.', // MISSING
OperationCompletedErrors : 'Operation completed with errors.', // MISSING
FileError : '%s: %e', // MISSING
// Move and Copy files
MovedFilesNumber : 'Number of files moved: %s.', // MISSING
CopiedFilesNumber : 'Number of files copied: %s.', // MISSING
MoveFailedList : 'The following files could not be moved:<br />%s', // MISSING
CopyFailedList : 'The following files could not be copied:<br />%s', // MISSING
// Toolbar Buttons (some used elsewhere)
Upload : 'Pošalji',
UploadTip : 'Pošalji nove datoteke na server',
Refresh : 'Osvježi',
Settings : 'Postavke',
Help : 'Pomoć',
HelpTip : 'Pomoć',
// Context Menus
Select : 'Odaberi',
SelectThumbnail : 'Odaberi manju sliku',
View : 'Pogledaj',
Download : 'Skini',
NewSubFolder : 'Novi poddirektorij',
Rename : 'Promijeni naziv',
Delete : 'Obriši',
DeleteFiles : 'Delete Files', // MISSING
CopyDragDrop : 'Kopiraj ovdje',
MoveDragDrop : 'Premjesti ovdje',
// Dialogs
RenameDlgTitle : 'Promijeni naziv',
NewNameDlgTitle : 'Novi naziv',
FileExistsDlgTitle : 'Datoteka već postoji',
SysErrorDlgTitle : 'Greška sustava',
FileOverwrite : 'Prepiši',
FileAutorename : 'Automatska promjena naziva',
ManuallyRename : 'Manually rename', // MISSING
// Generic
OkBtn : 'U redu',
CancelBtn : 'Poništi',
CloseBtn : 'Zatvori',
// Upload Panel
UploadTitle : 'Pošalji novu datoteku',
UploadSelectLbl : 'Odaberi datoteku za slanje',
UploadProgressLbl : '(Slanje u tijeku, molimo pričekajte...)',
UploadBtn : 'Pošalji odabranu datoteku',
UploadBtnCancel : 'Poništi',
UploadNoFileMsg : 'Odaberite datoteku na Vašem računalu.',
UploadNoFolder : 'Odaberite direktorije prije slanja.',
UploadNoPerms : 'Slanje datoteka nije dozvoljeno.',
UploadUnknError : 'Greška kod slanja datoteke.',
UploadExtIncorrect : 'Vrsta datoteka nije dozvoljena.',
// Flash Uploads
UploadLabel : 'Datoteka za slanje:',
UploadTotalFiles : 'Ukupno datoteka:',
UploadTotalSize : 'Ukupna veličina:',
UploadSend : 'Pošalji',
UploadAddFiles : 'Dodaj datoteke',
UploadClearFiles : 'Izbaci datoteke',
UploadCancel : 'Poništi slanje',
UploadRemove : 'Ukloni',
UploadRemoveTip : 'Ukloni !f',
UploadUploaded : 'Poslano !n%',
UploadProcessing : 'Obrađujem...',
// Settings Panel
SetTitle : 'Postavke',
SetView : 'Pregled:',
SetViewThumb : 'Mala slika',
SetViewList : 'Lista',
SetDisplay : 'Prikaz:',
SetDisplayName : 'Naziv datoteke',
SetDisplayDate : 'Datum',
SetDisplaySize : 'Veličina datoteke',
SetSort : 'Sortiranje:',
SetSortName : 'po nazivu',
SetSortDate : 'po datumu',
SetSortSize : 'po veličini',
SetSortExtension : 'po vrsti datoteke',
// Status Bar
FilesCountEmpty : '<Prazan direktorij>',
FilesCountOne : '1 datoteka',
FilesCountMany : '%1 datoteka',
// Size and Speed
Kb : '%1 KB',
Mb : '%1 MB',
Gb : '%1 GB',
SizePerSecond : '%1/s',
// Connector Error Messages.
ErrorUnknown : 'Nije moguće završiti zahtjev. (Greška %1)',
Errors :
{
10 : 'Nepoznata naredba.',
11 : 'Nije navedena vrsta u zahtjevu.',
12 : 'Zatražena vrsta nije važeća.',
102 : 'Neispravno naziv datoteke ili direktoija.',
103 : 'Nije moguće izvršiti zahtjev zbog ograničenja pristupa.',
104 : 'Nije moguće izvršiti zahtjev zbog ograničenja postavka sustava.',
105 : 'Nedozvoljena vrsta datoteke.',
109 : 'Nedozvoljen zahtjev.',
110 : 'Nepoznata greška.',
111 : 'It was not possible to complete the request due to resulting file size.', // MISSING
115 : 'Datoteka ili direktorij s istim nazivom već postoji.',
116 : 'Direktorij nije pronađen. Osvježite stranicu i pokušajte ponovo.',
117 : 'Datoteka nije pronađena. Osvježite listu datoteka i pokušajte ponovo.',
118 : 'Putanje izvora i odredišta su jednake.',
201 : 'Datoteka s istim nazivom već postoji. Poslana datoteka je promjenjena u "%1".',
202 : 'Neispravna datoteka.',
203 : 'Neispravna datoteka. Veličina datoteke je prevelika.',
204 : 'Poslana datoteka je neispravna.',
205 : 'Ne postoji privremeni direktorij za slanje na server.',
206 : 'Slanje je poništeno zbog sigurnosnih postavki. Naziv datoteke sadrži HTML podatke.',
207 : 'Poslana datoteka je promjenjena u "%1".',
300 : 'Premještanje datoteke(a) nije uspjelo.',
301 : 'Kopiranje datoteke(a) nije uspjelo.',
500 : 'Pretraživanje datoteka nije dozvoljeno iz sigurnosnih razloga. Molimo kontaktirajte administratora sustava kako bi provjerili postavke CKFinder konfiguracijske datoteke.',
501 : 'The thumbnails support is disabled.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Naziv datoteke ne može biti prazan.',
FileExists : 'Datoteka %s već postoji.',
FolderEmpty : 'Naziv direktorija ne može biti prazan.',
FolderExists : 'Folder %s already exists.', // MISSING
FolderNameExists : 'Folder already exists.', // MISSING
FileInvChar : 'Naziv datoteke ne smije sadržavati niti jedan od sljedećih znakova: \n\\ / : * ? " < > |',
FolderInvChar : 'Naziv direktorija ne smije sadržavati niti jedan od sljedećih znakova: \n\\ / : * ? " < > |',
PopupBlockView : 'Nije moguće otvoriti datoteku u novom prozoru. Promijenite postavke svog Internet preglednika i isključite sve popup blokere za ove web stranice.',
XmlError : 'Nije moguće učitati XML odgovor od web servera.',
XmlEmpty : 'Nije moguće učitati XML odgovor od web servera. Server je vratio prazan odgovor.',
XmlRawResponse : 'Odgovor servera: %s'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Promijeni veličinu %s',
sizeTooBig : 'Nije moguće postaviti veličinu veću od originala (%size).',
resizeSuccess : 'Slika je uspješno promijenjena.',
thumbnailNew : 'Napravi malu sliku',
thumbnailSmall : 'Mala (%s)',
thumbnailMedium : 'Srednja (%s)',
thumbnailLarge : 'Velika (%s)',
newSize : 'Postavi novu veličinu',
width : 'Širina',
height : 'Visina',
invalidHeight : 'Neispravna visina.',
invalidWidth : 'Neispravna širina.',
invalidName : 'Neispravan naziv datoteke.',
newImage : 'Napravi novu sliku',
noExtensionChange : 'Vrsta datoteke se ne smije mijenjati.',
imageSmall : 'Izvorna slika je premala.',
contextMenuName : 'Promijeni veličinu',
lockRatio : 'Zaključaj odnose',
resetSize : 'Vrati veličinu'
},
// Fileeditor plugin
Fileeditor :
{
save : 'Snimi',
fileOpenError : 'Nije moguće otvoriti datoteku.',
fileSaveSuccess : 'Datoteka je uspješno snimljena.',
contextMenuName : 'Promjeni',
loadingFile : 'Učitavam, molimo pričekajte...'
},
Maximize :
{
maximize : 'Povećaj',
minimize : 'Smanji'
},
Gallery :
{
current : 'Slika {current} od {total}'
},
Zip :
{
extractHereLabel : 'Extract here', // MISSING
extractToLabel : 'Extract to...', // MISSING
downloadZipLabel : 'Download as zip', // MISSING
compressZipLabel : 'Compress to zip', // MISSING
removeAndExtract : 'Remove existing and extract', // MISSING
extractAndOverwrite : 'Extract overwriting existing files', // MISSING
extractSuccess : 'File extracted successfully.' // MISSING
},
Search :
{
searchPlaceholder : 'Traži'
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://cksource.com/ckfinder
* Copyright (C) 2007-2014, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file, and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying, or distributing this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object for the Russian
* language.
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['ru'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, недоступно</span>',
confirmCancel : 'Внесенные вами изменения будут утеряны. Вы уверены?',
ok : 'OK',
cancel : 'Отмена',
confirmationTitle : 'Подтверждение',
messageTitle : 'Информация',
inputTitle : 'Вопрос',
undo : 'Отменить',
redo : 'Повторить',
skip : 'Пропустить',
skipAll : 'Пропустить все',
makeDecision : 'Что следует сделать?',
rememberDecision: 'Запомнить мой выбор'
},
// Language direction, 'ltr' or 'rtl'.
dir : 'ltr',
HelpLang : 'en',
LangCode : 'ru',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'dd.mm.yyyy H:MM',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Папки',
FolderLoading : 'Загрузка...',
FolderNew : 'Пожалуйста, введите новое имя папки: ',
FolderRename : 'Пожалуйста, введите новое имя папки: ',
FolderDelete : 'Вы уверены, что хотите удалить папку "%1"?',
FolderRenaming : ' (Переименовываю...)',
FolderDeleting : ' (Удаляю...)',
DestinationFolder : 'Destination Folder', // MISSING
// Files
FileRename : 'Пожалуйста, введите новое имя файла: ',
FileRenameExt : 'Вы уверены, что хотите изменить расширение файла? Файл может стать недоступным.',
FileRenaming : 'Переименовываю...',
FileDelete : 'Вы уверены, что хотите удалить файл "%1"?',
FilesDelete : 'Are you sure you want to delete %1 files?', // MISSING
FilesLoading : 'Загрузка...',
FilesEmpty : 'Пустая папка',
DestinationFile : 'Destination File', // MISSING
SkippedFiles : 'List of skipped files:', // MISSING
// Basket
BasketFolder : 'Корзина',
BasketClear : 'Очистить корзину',
BasketRemove : 'Убрать из корзины',
BasketOpenFolder : 'Перейти в папку этого файла',
BasketTruncateConfirm : 'Вы точно хотите очистить корзину?',
BasketRemoveConfirm : 'Вы точно хотите убрать файл "%1" из корзины?',
BasketRemoveConfirmMultiple : 'Do you really want to remove %1 files from the basket?', // MISSING
BasketEmpty : 'В корзине пока нет файлов, добавьте новые с помощью драг-н-дропа (перетащите файл в корзину).',
BasketCopyFilesHere : 'Скопировать файл из корзины',
BasketMoveFilesHere : 'Переместить файл из корзины',
// Global messages
OperationCompletedSuccess : 'Operation completed successfully.', // MISSING
OperationCompletedErrors : 'Operation completed with errors.', // MISSING
FileError : '%s: %e', // MISSING
// Move and Copy files
MovedFilesNumber : 'Number of files moved: %s.', // MISSING
CopiedFilesNumber : 'Number of files copied: %s.', // MISSING
MoveFailedList : 'The following files could not be moved:<br />%s', // MISSING
CopyFailedList : 'The following files could not be copied:<br />%s', // MISSING
// Toolbar Buttons (some used elsewhere)
Upload : 'Загрузить файл',
UploadTip : 'Загрузить новый файл',
Refresh : 'Обновить список',
Settings : 'Настройка',
Help : 'Помощь',
HelpTip : 'Помощь',
// Context Menus
Select : 'Выбрать',
SelectThumbnail : 'Выбрать миниатюру',
View : 'Посмотреть',
Download : 'Сохранить',
NewSubFolder : 'Новая папка',
Rename : 'Переименовать',
Delete : 'Удалить',
DeleteFiles : 'Delete Files', // MISSING
CopyDragDrop : 'Копировать',
MoveDragDrop : 'Переместить',
// Dialogs
RenameDlgTitle : 'Переименовать',
NewNameDlgTitle : 'Новое имя',
FileExistsDlgTitle : 'Файл уже существует',
SysErrorDlgTitle : 'Системная ошибка',
FileOverwrite : 'Заменить файл',
FileAutorename : 'Автоматически переименовывать',
ManuallyRename : 'Manually rename', // MISSING
// Generic
OkBtn : 'ОК',
CancelBtn : 'Отмена',
CloseBtn : 'Закрыть',
// Upload Panel
UploadTitle : 'Загрузить новый файл',
UploadSelectLbl : 'Выбрать файл для загрузки',
UploadProgressLbl : '(Загрузка в процессе, пожалуйста подождите...)',
UploadBtn : 'Загрузить выбранный файл',
UploadBtnCancel : 'Отмена',
UploadNoFileMsg : 'Пожалуйста, выберите файл на вашем компьютере.',
UploadNoFolder : 'Пожалуйста, выберите папку, в которую вы хотите загрузить файл.',
UploadNoPerms : 'Загрузка файлов запрещена.',
UploadUnknError : 'Ошибка при передаче файла.',
UploadExtIncorrect : 'В эту папку нельзя загружать файлы с таким расширением.',
// Flash Uploads
UploadLabel : 'Файлы для загрузки',
UploadTotalFiles : 'Всего файлов:',
UploadTotalSize : 'Общий размер:',
UploadSend : 'Загрузить файл',
UploadAddFiles : 'Добавить файлы',
UploadClearFiles : 'Очистить',
UploadCancel : 'Отменить загрузку',
UploadRemove : 'Убрать',
UploadRemoveTip : 'Убрать !f',
UploadUploaded : 'Загружено !n%',
UploadProcessing : 'Загружаю...',
// Settings Panel
SetTitle : 'Настройка',
SetView : 'Внешний вид:',
SetViewThumb : 'Миниатюры',
SetViewList : 'Список',
SetDisplay : 'Показывать:',
SetDisplayName : 'Имя файла',
SetDisplayDate : 'Дата',
SetDisplaySize : 'Размер файла',
SetSort : 'Сортировка:',
SetSortName : 'по имени файла',
SetSortDate : 'по дате',
SetSortSize : 'по размеру',
SetSortExtension : 'по расширению',
// Status Bar
FilesCountEmpty : '<Пустая папка>',
FilesCountOne : '1 файл',
FilesCountMany : '%1 файлов',
// Size and Speed
Kb : '%1 KБ',
Mb : '%1 MB', // MISSING
Gb : '%1 GB', // MISSING
SizePerSecond : '%1/s', // MISSING
// Connector Error Messages.
ErrorUnknown : 'Невозможно завершить запрос. (Ошибка %1)',
Errors :
{
10 : 'Неверная команда.',
11 : 'Тип ресурса не указан в запросе.',
12 : 'Неверный запрошенный тип ресурса.',
102 : 'Неверное имя файла или папки.',
103 : 'Невозможно завершить запрос из-за ограничений авторизации.',
104 : 'Невозможно завершить запрос из-за ограничения разрешений файловой системы.',
105 : 'Неверное расширение файла.',
109 : 'Неверный запрос.',
110 : 'Неизвестная ошибка.',
111 : 'It was not possible to complete the request due to resulting file size.', // MISSING
115 : 'Файл или папка с таким именем уже существует.',
116 : 'Папка не найдена. Пожалуйста, обновите вид папок и попробуйте еще раз.',
117 : 'Файл не найден. Пожалуйста, обновите список файлов и попробуйте еще раз.',
118 : 'Исходное расположение файла совпадает с указанным.',
201 : 'Файл с таким именем уже существует. Загруженный файл был переименован в "%1".',
202 : 'Неверный файл.',
203 : 'Неверный файл. Размер файла слишком большой.',
204 : 'Загруженный файл поврежден.',
205 : 'Недоступна временная папка для загрузки файлов на сервер.',
206 : 'Загрузка отменена из-за соображений безопасности. Файл содержит похожие на HTML данные.',
207 : 'Загруженный файл был переименован в "%1".',
300 : 'Произошла ошибка при перемещении файла(ов).',
301 : 'Произошла ошибка при копировании файла(ов).',
500 : 'Браузер файлов отключен из-за соображений безопасности. Пожалуйста, сообщите вашему системному администратру и проверьте конфигурационный файл CKFinder.',
501 : 'Поддержка миниатюр отключена.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Имя файла не может быть пустым.',
FileExists : 'Файл %s уже существует.',
FolderEmpty : 'Имя папки не может быть пустым.',
FolderExists : 'Folder %s already exists.', // MISSING
FolderNameExists : 'Folder already exists.', // MISSING
FileInvChar : 'Имя файла не может содержать любой из перечисленных символов: \n\\ / : * ? " < > |',
FolderInvChar : 'Имя папки не может содержать любой из перечисленных символов: \n\\ / : * ? " < > |',
PopupBlockView : 'Невозможно открыть файл в новом окне. Пожалуйста, проверьте настройки браузера и отключите блокировку всплывающих окон для этого сайта.',
XmlError : 'Ошибка при разборе XML-ответа сервера.',
XmlEmpty : 'Невозможно прочитать XML-ответ сервера, получена пустая строка.',
XmlRawResponse : 'Необработанный ответ сервера: %s'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Изменить размеры %s',
sizeTooBig : 'Нельзя указывать размеры больше, чем у оригинального файла (%size).',
resizeSuccess : 'Размеры успешно изменены.',
thumbnailNew : 'Создать миниатюру(ы)',
thumbnailSmall : 'Маленькая (%s)',
thumbnailMedium : 'Средняя (%s)',
thumbnailLarge : 'Большая (%s)',
newSize : 'Установить новые размеры',
width : 'Ширина',
height : 'Высота',
invalidHeight : 'Высота должна быть числом больше нуля.',
invalidWidth : 'Ширина должна быть числом больше нуля.',
invalidName : 'Неверное имя файла.',
newImage : 'Сохранить как новый файл',
noExtensionChange : 'Не удалось поменять расширение файла.',
imageSmall : 'Исходная картинка слишком маленькая.',
contextMenuName : 'Изменить размер',
lockRatio : 'Сохранять пропорции',
resetSize : 'Вернуть обычные размеры'
},
// Fileeditor plugin
Fileeditor :
{
save : 'Сохранить',
fileOpenError : 'Не удалось открыть файл.',
fileSaveSuccess : 'Файл успешно сохранен.',
contextMenuName : 'Редактировать',
loadingFile : 'Файл загружается, пожалуйста подождите...'
},
Maximize :
{
maximize : 'Развернуть',
minimize : 'Свернуть'
},
Gallery :
{
current : 'Image {current} of {total}' // MISSING
},
Zip :
{
extractHereLabel : 'Extract here', // MISSING
extractToLabel : 'Extract to...', // MISSING
downloadZipLabel : 'Download as zip', // MISSING
compressZipLabel : 'Compress to zip', // MISSING
removeAndExtract : 'Remove existing and extract', // MISSING
extractAndOverwrite : 'Extract overwriting existing files', // MISSING
extractSuccess : 'File extracted successfully.' // MISSING
},
Search :
{
searchPlaceholder : 'Поиск'
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://cksource.com/ckfinder
* Copyright (C) 2007-2014, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file, and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying, or distributing this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object for the Swedish
* language.
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['sv'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, Ej tillgänglig</span>',
confirmCancel : 'Några av alternativen har ändrats. Är du säker på att du vill stänga dialogrutan?',
ok : 'OK',
cancel : 'Avbryt',
confirmationTitle : 'Bekräftelse',
messageTitle : 'Information',
inputTitle : 'Fråga',
undo : 'Ångra',
redo : 'Gör om',
skip : 'Hoppa över',
skipAll : 'Hoppa över alla',
makeDecision : 'Vilken åtgärd ska utföras?',
rememberDecision: 'Kom ihåg mitt val'
},
// Language direction, 'ltr' or 'rtl'.
dir : 'ltr',
HelpLang : 'en',
LangCode : 'sv',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'yyyy-mm-dd HH:MM',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Mappar',
FolderLoading : 'Laddar...',
FolderNew : 'Skriv namnet på den nya mappen: ',
FolderRename : 'Skriv det nya namnet på mappen: ',
FolderDelete : 'Är du säker på att du vill radera mappen "%1"?',
FolderRenaming : ' (Byter mappens namn...)',
FolderDeleting : ' (Raderar...)',
DestinationFolder : 'Destination Folder', // MISSING
// Files
FileRename : 'Skriv det nya filnamnet: ',
FileRenameExt : 'Är du säker på att du vill ändra filändelsen? Filen kan bli oanvändbar.',
FileRenaming : 'Byter filnamn...',
FileDelete : 'Är du säker på att du vill radera filen "%1"?',
FilesDelete : 'Are you sure you want to delete %1 files?', // MISSING
FilesLoading : 'Laddar...',
FilesEmpty : 'Mappen är tom.',
DestinationFile : 'Destination File', // MISSING
SkippedFiles : 'List of skipped files:', // MISSING
// Basket
BasketFolder : 'Filkorg',
BasketClear : 'Rensa filkorgen',
BasketRemove : 'Ta bort från korgen',
BasketOpenFolder : 'Öppna överliggande mapp',
BasketTruncateConfirm : 'Vill du verkligen ta bort alla filer från korgen?',
BasketRemoveConfirm : 'Vill du verkligen ta bort filen "%1" från korgen?',
BasketRemoveConfirmMultiple : 'Do you really want to remove %1 files from the basket?', // MISSING
BasketEmpty : 'Inga filer i korgen, dra och släpp några.',
BasketCopyFilesHere : 'Kopiera filer från korgen',
BasketMoveFilesHere : 'Flytta filer från korgen',
// Global messages
OperationCompletedSuccess : 'Operation completed successfully.', // MISSING
OperationCompletedErrors : 'Operation completed with errors.', // MISSING
FileError : '%s: %e', // MISSING
// Move and Copy files
MovedFilesNumber : 'Number of files moved: %s.', // MISSING
CopiedFilesNumber : 'Number of files copied: %s.', // MISSING
MoveFailedList : 'The following files could not be moved:<br />%s', // MISSING
CopyFailedList : 'The following files could not be copied:<br />%s', // MISSING
// Toolbar Buttons (some used elsewhere)
Upload : 'Ladda upp',
UploadTip : 'Ladda upp en ny fil',
Refresh : 'Uppdatera',
Settings : 'Inställningar',
Help : 'Hjälp',
HelpTip : 'Hjälp',
// Context Menus
Select : 'Infoga bild',
SelectThumbnail : 'Infoga som tumnagel',
View : 'Visa',
Download : 'Ladda ner',
NewSubFolder : 'Ny Undermapp',
Rename : 'Byt namn',
Delete : 'Radera',
DeleteFiles : 'Delete Files', // MISSING
CopyDragDrop : 'Kopiera hit',
MoveDragDrop : 'Flytta hit',
// Dialogs
RenameDlgTitle : 'Byt namn',
NewNameDlgTitle : 'Nytt namn',
FileExistsDlgTitle : 'Filen finns redan',
SysErrorDlgTitle : 'Systemfel',
FileOverwrite : 'Skriv över',
FileAutorename : 'Auto-namnändring',
ManuallyRename : 'Manually rename', // MISSING
// Generic
OkBtn : 'OK',
CancelBtn : 'Avbryt',
CloseBtn : 'Stäng',
// Upload Panel
UploadTitle : 'Ladda upp en ny fil',
UploadSelectLbl : 'Välj fil att ladda upp',
UploadProgressLbl : '(Laddar upp filen, var god vänta...)',
UploadBtn : 'Ladda upp den valda filen',
UploadBtnCancel : 'Avbryt',
UploadNoFileMsg : 'Välj en fil från din dator.',
UploadNoFolder : 'Välj en mapp före uppladdning.',
UploadNoPerms : 'Filuppladdning ej tillåten.',
UploadUnknError : 'Fel vid filuppladdning.',
UploadExtIncorrect : 'Filändelsen är inte tillåten i denna mapp.',
// Flash Uploads
UploadLabel : 'Filer att ladda upp',
UploadTotalFiles : 'Totalt antal filer:',
UploadTotalSize : 'Total storlek:',
UploadSend : 'Ladda upp',
UploadAddFiles : 'Lägg till filer',
UploadClearFiles : 'Rensa filer',
UploadCancel : 'Avbryt uppladdning',
UploadRemove : 'Ta bort',
UploadRemoveTip : 'Ta bort !f',
UploadUploaded : 'Uppladdat !n%',
UploadProcessing : 'Bearbetar...',
// Settings Panel
SetTitle : 'Inställningar',
SetView : 'Visa:',
SetViewThumb : 'Tumnaglar',
SetViewList : 'Lista',
SetDisplay : 'Visa:',
SetDisplayName : 'Filnamn',
SetDisplayDate : 'Datum',
SetDisplaySize : 'Storlek',
SetSort : 'Sortering:',
SetSortName : 'Filnamn',
SetSortDate : 'Datum',
SetSortSize : 'Storlek',
SetSortExtension : 'Filändelse',
// Status Bar
FilesCountEmpty : '<Tom Mapp>',
FilesCountOne : '1 fil',
FilesCountMany : '%1 filer',
// Size and Speed
Kb : '%1 KB',
Mb : '%1 MB',
Gb : '%1 GB',
SizePerSecond : '%1/s',
// Connector Error Messages.
ErrorUnknown : 'Begäran kunde inte utföras eftersom ett fel uppstod. (Fel %1)',
Errors :
{
10 : 'Ogiltig begäran.',
11 : 'Resursens typ var inte specificerad i förfrågan.',
12 : 'Den efterfrågade resurstypen är inte giltig.',
102 : 'Ogiltigt fil- eller mappnamn.',
103 : 'Begäran kunde inte utföras p.g.a. restriktioner av rättigheterna.',
104 : 'Begäran kunde inte utföras p.g.a. restriktioner av rättigheter i filsystemet.',
105 : 'Ogiltig filändelse.',
109 : 'Ogiltig begäran.',
110 : 'Okänt fel.',
111 : 'It was not possible to complete the request due to resulting file size.', // MISSING
115 : 'En fil eller mapp med aktuellt namn finns redan.',
116 : 'Mappen kunde inte hittas. Var god uppdatera sidan och försök igen.',
117 : 'Filen kunde inte hittas. Var god uppdatera sidan och försök igen.',
118 : 'Sökväg till källa och mål är identisk.',
201 : 'En fil med aktuellt namn fanns redan. Den uppladdade filen har döpts om till "%1".',
202 : 'Ogiltig fil.',
203 : 'Ogiltig fil. Filen var för stor.',
204 : 'Den uppladdade filen var korrupt.',
205 : 'En tillfällig mapp för uppladdning är inte tillgänglig på servern.',
206 : 'Uppladdningen stoppades av säkerhetsskäl. Filen innehåller HTML-liknande data.',
207 : 'Den uppladdade filen har döpts om till "%1".',
300 : 'Flytt av fil(er) misslyckades.',
301 : 'Kopiering av fil(er) misslyckades.',
500 : 'Filhanteraren har stoppats av säkerhetsskäl. Var god kontakta administratören för att kontrollera konfigurationsfilen för CKFinder.',
501 : 'Stöd för tumnaglar har stängts av.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Filnamnet får inte vara tomt.',
FileExists : 'Filen %s finns redan.',
FolderEmpty : 'Mappens namn får inte vara tomt.',
FolderExists : 'Folder %s already exists.', // MISSING
FolderNameExists : 'Folder already exists.', // MISSING
FileInvChar : 'Filnamnet får inte innehålla något av följande tecken: \n\\ / : * ? " < > |',
FolderInvChar : 'Mappens namn får inte innehålla något av följande tecken: \n\\ / : * ? " < > |',
PopupBlockView : 'Det gick inte att öppna filen i ett nytt fönster. Ändra inställningarna i din webbläsare så att den tillåter popup-fönster på den här webbplatsen.',
XmlError : 'Det gick inte att ladda XML-svaret från webbservern ordentligt.',
XmlEmpty : 'Det gick inte att ladda XML-svaret från webbservern. Servern returnerade ett tomt svar.',
XmlRawResponse : 'Svar från servern: %s'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Storleksändra %s',
sizeTooBig : 'Bildens höjd eller bredd kan inte vara större än originalfilens storlek (%size).',
resizeSuccess : 'Storleksändring lyckades.',
thumbnailNew : 'Skapa en ny tumnagel',
thumbnailSmall : 'Liten (%s)',
thumbnailMedium : 'Mellan (%s)',
thumbnailLarge : 'Stor (%s)',
newSize : 'Välj en ny storlek',
width : 'Bredd',
height : 'Höjd',
invalidHeight : 'Ogiltig höjd.',
invalidWidth : 'Ogiltig bredd.',
invalidName : 'Ogiltigt filnamn.',
newImage : 'Skapa en ny bild',
noExtensionChange : 'Filändelsen kan inte ändras.',
imageSmall : 'Originalbilden är för liten.',
contextMenuName : 'Ändra storlek',
lockRatio : 'Lås höjd/bredd förhållanden',
resetSize : 'Återställ storlek'
},
// Fileeditor plugin
Fileeditor :
{
save : 'Spara',
fileOpenError : 'Kan inte öppna filen.',
fileSaveSuccess : 'Filen sparades.',
contextMenuName : 'Redigera',
loadingFile : 'Laddar fil, var god vänta...'
},
Maximize :
{
maximize : 'Maximera',
minimize : 'Minimera'
},
Gallery :
{
current : 'Bild {current} av {total}'
},
Zip :
{
extractHereLabel : 'Extract here', // MISSING
extractToLabel : 'Extract to...', // MISSING
downloadZipLabel : 'Download as zip', // MISSING
compressZipLabel : 'Compress to zip', // MISSING
removeAndExtract : 'Remove existing and extract', // MISSING
extractAndOverwrite : 'Extract overwriting existing files', // MISSING
extractSuccess : 'File extracted successfully.' // MISSING
},
Search :
{
searchPlaceholder : 'Sök'
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://cksource.com/ckfinder
* Copyright (C) 2007-2014, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file, and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying, or distributing this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object, for the Turkish
* language.
*
* Turkish translation by Abdullah M CEYLAN a.k.a. Kenan Balamir. Updated.
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['tr'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility"> öğesi, mevcut değil</span>',
confirmCancel : 'Bazı seçenekler değiştirildi. Pencereyi kapatmak istiyor musunuz?',
ok : 'Tamam',
cancel : 'Vazgeç',
confirmationTitle : 'Onay',
messageTitle : 'Bilgi',
inputTitle : 'Soru',
undo : 'Geri Al',
redo : 'Yinele',
skip : 'Atla',
skipAll : 'Tümünü Atla',
makeDecision : 'Hangi işlem yapılsın?',
rememberDecision: 'Kararımı hatırla'
},
// Language direction, 'ltr' or 'rtl'.
dir : 'ltr',
HelpLang : 'en',
LangCode : 'tr',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'd/m/yyyy h:MM aa',
DateAmPm : ['GN', 'GC'],
// Folders
FoldersTitle : 'Klasörler',
FolderLoading : 'Yükleniyor...',
FolderNew : 'Lütfen yeni klasör adını yazın: ',
FolderRename : 'Lütfen yeni klasör adını yazın: ',
FolderDelete : '"%1" klasörünü silmek istediğinizden emin misiniz?',
FolderRenaming : ' (Yeniden adlandırılıyor...)',
FolderDeleting : ' (Siliniyor...)',
DestinationFolder : 'Destination Folder', // MISSING
// Files
FileRename : 'Lütfen yeni dosyanın adını yazın: ',
FileRenameExt : 'Dosya uzantısını değiştirmek istiyor musunuz? Bu, dosyayı kullanılamaz hale getirebilir.',
FileRenaming : 'Yeniden adlandırılıyor...',
FileDelete : '"%1" dosyasını silmek istediğinizden emin misiniz?',
FilesDelete : 'Are you sure you want to delete %1 files?', // MISSING
FilesLoading : 'Yükleniyor...',
FilesEmpty : 'Klasör boş',
DestinationFile : 'Destination File', // MISSING
SkippedFiles : 'List of skipped files:', // MISSING
// Basket
BasketFolder : 'Sepet',
BasketClear : 'Sepeti temizle',
BasketRemove : 'Sepetten sil',
BasketOpenFolder : 'Üst klasörü aç',
BasketTruncateConfirm : 'Sepetteki tüm dosyaları silmek istediğinizden emin misiniz?',
BasketRemoveConfirm : 'Sepetteki %1% dosyasını silmek istediğinizden emin misiniz?',
BasketRemoveConfirmMultiple : 'Do you really want to remove %1 files from the basket?', // MISSING
BasketEmpty : 'Sepette hiç dosya yok, birkaç tane sürükleyip bırakabilirsiniz',
BasketCopyFilesHere : 'Sepetten Dosya Kopyala',
BasketMoveFilesHere : 'Sepetten Dosya Taşı',
// Global messages
OperationCompletedSuccess : 'Operation completed successfully.', // MISSING
OperationCompletedErrors : 'Operation completed with errors.', // MISSING
FileError : '%s: %e', // MISSING
// Move and Copy files
MovedFilesNumber : 'Number of files moved: %s.', // MISSING
CopiedFilesNumber : 'Number of files copied: %s.', // MISSING
MoveFailedList : 'The following files could not be moved:<br />%s', // MISSING
CopyFailedList : 'The following files could not be copied:<br />%s', // MISSING
// Toolbar Buttons (some used elsewhere)
Upload : 'Yükle',
UploadTip : 'Yeni Dosya Yükle',
Refresh : 'Yenile',
Settings : 'Ayarlar',
Help : 'Yardım',
HelpTip : 'Yardım',
// Context Menus
Select : 'Seç',
SelectThumbnail : 'Önizleme Olarak Seç',
View : 'Görüntüle',
Download : 'İndir',
NewSubFolder : 'Yeni Altklasör',
Rename : 'Yeniden Adlandır',
Delete : 'Sil',
DeleteFiles : 'Delete Files', // MISSING
CopyDragDrop : 'Buraya kopyala',
MoveDragDrop : 'Buraya taşı',
// Dialogs
RenameDlgTitle : 'Yeniden Adlandır',
NewNameDlgTitle : 'Yeni Adı',
FileExistsDlgTitle : 'Dosya zaten var',
SysErrorDlgTitle : 'Sistem hatası',
FileOverwrite : 'Üzerine yaz',
FileAutorename : 'Oto-Yeniden Adlandır',
ManuallyRename : 'Manually rename', // MISSING
// Generic
OkBtn : 'Tamam',
CancelBtn : 'Vazgeç',
CloseBtn : 'Kapat',
// Upload Panel
UploadTitle : 'Yeni Dosya Yükle',
UploadSelectLbl : 'Yüklenecek dosyayı seçin',
UploadProgressLbl : '(Yükleniyor, lütfen bekleyin...)',
UploadBtn : 'Seçili Dosyayı Yükle',
UploadBtnCancel : 'Vazgeç',
UploadNoFileMsg : 'Lütfen bilgisayarınızdan dosya seçin',
UploadNoFolder : 'Lütfen yüklemeden önce klasör seçin.',
UploadNoPerms : 'Dosya yüklemeye izin verilmiyor.',
UploadUnknError : 'Dosya gönderme hatası.',
UploadExtIncorrect : 'Bu dosya uzantısına, bu klasörde izin verilmiyor.',
// Flash Uploads
UploadLabel : 'Gönderilecek Dosyalar',
UploadTotalFiles : 'Toplam Dosyalar:',
UploadTotalSize : 'Toplam Büyüklük:',
UploadSend : 'Yükle',
UploadAddFiles : 'Dosyaları Ekle',
UploadClearFiles : 'Dosyaları Temizle',
UploadCancel : 'Göndermeyi İptal Et',
UploadRemove : 'Sil',
UploadRemoveTip : '!f sil',
UploadUploaded : '!n% gönderildi',
UploadProcessing : 'Gönderiliyor...',
// Settings Panel
SetTitle : 'Ayarlar',
SetView : 'Görünüm:',
SetViewThumb : 'Önizlemeler',
SetViewList : 'Liste',
SetDisplay : 'Gösterim:',
SetDisplayName : 'Dosya adı',
SetDisplayDate : 'Tarih',
SetDisplaySize : 'Dosya boyutu',
SetSort : 'Sıralama:',
SetSortName : 'Dosya adına göre',
SetSortDate : 'Tarihe göre',
SetSortSize : 'Boyuta göre',
SetSortExtension : 'Uzantısına göre',
// Status Bar
FilesCountEmpty : '<Klasörde Dosya Yok>',
FilesCountOne : '1 dosya',
FilesCountMany : '%1 dosya',
// Size and Speed
Kb : '%1 KB',
Mb : '%1 MB',
Gb : '%1 GB',
SizePerSecond : '%1/sn',
// Connector Error Messages.
ErrorUnknown : 'İsteğinizi yerine getirmek mümkün değil. (Hata %1)',
Errors :
{
10 : 'Geçersiz komut.',
11 : 'İstekte kaynak türü belirtilmemiş.',
12 : 'Talep edilen kaynak türü geçersiz.',
102 : 'Geçersiz dosya ya da klasör adı.',
103 : 'Kimlik doğrulama kısıtlamaları nedeni ile talebinizi yerine getiremiyoruz.',
104 : 'Dosya sistemi kısıtlamaları nedeni ile talebinizi yerine getiremiyoruz.',
105 : 'Geçersiz dosya uzantısı.',
109 : 'Geçersiz istek.',
110 : 'Bilinmeyen hata.',
111 : 'It was not possible to complete the request due to resulting file size.', // MISSING
115 : 'Aynı isimde bir dosya ya da klasör zaten var.',
116 : 'Klasör bulunamadı. Lütfen yenileyin ve tekrar deneyin.',
117 : 'Dosya bulunamadı. Lütfen dosya listesini yenileyin ve tekrar deneyin.',
118 : 'Kaynak ve hedef yol aynı!',
201 : 'Aynı ada sahip bir dosya zaten var. Yüklenen dosyanın adı "%1" olarak değiştirildi.',
202 : 'Geçersiz dosya',
203 : 'Geçersiz dosya. Dosya boyutu çok büyük.',
204 : 'Yüklenen dosya bozuk.',
205 : 'Dosyaları yüklemek için gerekli geçici klasör sunucuda bulunamadı.',
206 : 'Güvenlik nedeni ile yükleme iptal edildi. Dosya HTML benzeri veri içeriyor.',
207 : 'Yüklenen dosyanın adı "%1" olarak değiştirildi.',
300 : 'Dosya taşıma işlemi başarısız.',
301 : 'Dosya kopyalama işlemi başarısız.',
500 : 'Güvenlik nedeni ile dosya gezgini devredışı bırakıldı. Lütfen sistem yöneticiniz ile irtibata geçin ve CKFinder yapılandırma dosyasını kontrol edin.',
501 : 'Önizleme desteği devredışı.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Dosya adı boş olamaz',
FileExists : '%s dosyası zaten var',
FolderEmpty : 'Klasör adı boş olamaz',
FolderExists : 'Folder %s already exists.', // MISSING
FolderNameExists : 'Folder already exists.', // MISSING
FileInvChar : 'Dosya adının içermesi mümkün olmayan karakterler: \n\\ / : * ? " < > |',
FolderInvChar : 'Klasör adının içermesi mümkün olmayan karakterler: \n\\ / : * ? " < > |',
PopupBlockView : 'Dosyayı yeni pencerede açmak için, tarayıcı ayarlarından bu sitenin açılır pencerelerine izin vermeniz gerekiyor.',
XmlError : 'Web sunucusundan XML yanıtı düzgün bir şekilde yüklenemedi.',
XmlEmpty : 'Web sunucusundan XML yanıtı düzgün bir şekilde yüklenemedi. Sunucudan boş cevap döndü.',
XmlRawResponse : 'Sunucudan gelen ham mesaj: %s'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Boyutlandır: %s',
sizeTooBig : 'Yükseklik ve genişlik değeri orijinal boyuttan büyük olduğundan, işlem gerçekleştirilemedi (%size).',
resizeSuccess : 'Resim başarıyla yeniden boyutlandırıldı.',
thumbnailNew : 'Yeni önizleme oluştur',
thumbnailSmall : 'Küçük (%s)',
thumbnailMedium : 'Orta (%s)',
thumbnailLarge : 'Büyük (%s)',
newSize : 'Yeni boyutu ayarla',
width : 'Genişlik',
height : 'Yükseklik',
invalidHeight : 'Geçersiz yükseklik.',
invalidWidth : 'Geçersiz genişlik.',
invalidName : 'Geçersiz dosya adı.',
newImage : 'Yeni resim oluştur',
noExtensionChange : 'Dosya uzantısı değiştirilemedi.',
imageSmall : 'Kaynak resim çok küçük',
contextMenuName : 'Boyutlandır',
lockRatio : 'Oranı kilitle',
resetSize : 'Büyüklüğü sıfırla'
},
// Fileeditor plugin
Fileeditor :
{
save : 'Kaydet',
fileOpenError : 'Dosya açılamadı.',
fileSaveSuccess : 'Dosya başarıyla kaydedildi.',
contextMenuName : 'Düzenle',
loadingFile : 'Dosya yükleniyor, lütfen bekleyin...'
},
Maximize :
{
maximize : 'Büyült',
minimize : 'Küçült'
},
Gallery :
{
current : '{current} / {total} resim'
},
Zip :
{
extractHereLabel : 'Extract here', // MISSING
extractToLabel : 'Extract to...', // MISSING
downloadZipLabel : 'Download as zip', // MISSING
compressZipLabel : 'Compress to zip', // MISSING
removeAndExtract : 'Remove existing and extract', // MISSING
extractAndOverwrite : 'Extract overwriting existing files', // MISSING
extractSuccess : 'File extracted successfully.' // MISSING
},
Search :
{
searchPlaceholder : 'Ara'
}
};
| JavaScript |
/*
* CKFinder
* ========
* http://cksource.com/ckfinder
* Copyright (C) 2007-2014, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file, and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying, or distributing this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object for the French
* language.
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['fr'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, Inaccessible</span>',
confirmCancel : 'Certaines options ont été modifiées. Êtes-vous sûr de vouloir fermer cette fenêtre ?',
ok : 'OK',
cancel : 'Annuler',
confirmationTitle : 'Confirmation',
messageTitle : 'Information',
inputTitle : 'Question',
undo : 'Annuler',
redo : 'Rétablir',
skip : 'Passer',
skipAll : 'Passer tout',
makeDecision : 'Quelle action choisir ?',
rememberDecision: 'Se rappeler de la décision'
},
// Language direction, 'ltr' or 'rtl'.
dir : 'ltr',
HelpLang : 'en',
LangCode : 'fr',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'dd/mm/yyyy H:MM',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Dossiers',
FolderLoading : 'Chargement...',
FolderNew : 'Entrez le nouveau nom du dossier: ',
FolderRename : 'Entrez le nouveau nom du dossier: ',
FolderDelete : 'Êtes-vous sûr de vouloir effacer le dossier "%1"?',
FolderRenaming : ' (Renommage en cours...)',
FolderDeleting : ' (Suppression en cours...)',
DestinationFolder : 'Dossier de destination',
// Files
FileRename : 'Entrez le nouveau nom du fichier: ',
FileRenameExt : 'Êtes-vous sûr de vouloir changer l\'extension de ce fichier? Le fichier pourrait devenir inutilisable.',
FileRenaming : 'Renommage en cours...',
FileDelete : 'Êtes-vous sûr de vouloir effacer le fichier "%1"?',
FilesDelete : 'Êtes-vous sûr de vouloir supprimer %1 fichiers ?',
FilesLoading : 'Chargement...',
FilesEmpty : 'Répertoire vide',
DestinationFile : 'Fichier de destination',
SkippedFiles : 'Liste des fichiers ignorés : ',
// Basket
BasketFolder : 'Corbeille',
BasketClear : 'Vider la corbeille',
BasketRemove : 'Retirer de la corbeille',
BasketOpenFolder : 'Ouvrir le répertiore parent',
BasketTruncateConfirm : 'Êtes-vous sûr de vouloir supprimer tous les fichiers de la corbeille ?',
BasketRemoveConfirm : 'Êtes-vous sûr de vouloir supprimer le fichier "%1" de la corbeille ?',
BasketRemoveConfirmMultiple : 'Êtes-vous sûr de vouloir supprimer %1 fichiers de la corbeille ?',
BasketEmpty : 'Aucun fichier dans la corbeille, déposez en queques uns.',
BasketCopyFilesHere : 'Copier des fichiers depuis la corbeille',
BasketMoveFilesHere : 'Déplacer des fichiers depuis la corbeille',
// Global messages
OperationCompletedSuccess : 'Operation terminée avec succès.',
OperationCompletedErrors : 'Operation terminée avec des erreurs.',
FileError : '%s: %e',
// Move and Copy files
MovedFilesNumber : 'Nombre de fichiers déplacés : %s.',
CopiedFilesNumber : 'Nombre de fichiers copiés : %s.',
MoveFailedList : 'Les fichiers suivants ne peuvent être déplacés :<br />%s',
CopyFailedList : 'Les fichiers suivants ne peuvent être copiés :<br />%s',
// Toolbar Buttons (some used elsewhere)
Upload : 'Envoyer',
UploadTip : 'Envoyer un nouveau fichier',
Refresh : 'Rafraîchir',
Settings : 'Configuration',
Help : 'Aide',
HelpTip : 'Aide',
// Context Menus
Select : 'Choisir',
SelectThumbnail : 'Choisir une miniature',
View : 'Voir',
Download : 'Télécharger',
NewSubFolder : 'Nouveau sous-dossier',
Rename : 'Renommer',
Delete : 'Effacer',
DeleteFiles : 'Supprimer les fichiers',
CopyDragDrop : 'Copier ici',
MoveDragDrop : 'Déplacer ici',
// Dialogs
RenameDlgTitle : 'Renommer',
NewNameDlgTitle : 'Nouveau fichier',
FileExistsDlgTitle : 'Fichier déjà existant',
SysErrorDlgTitle : 'Erreur système',
FileOverwrite : 'Ré-écrire',
FileAutorename : 'Re-nommage automatique',
ManuallyRename : 'Renommage manuel',
// Generic
OkBtn : 'OK',
CancelBtn : 'Annuler',
CloseBtn : 'Fermer',
// Upload Panel
UploadTitle : 'Envoyer un nouveau fichier',
UploadSelectLbl : 'Sélectionner le fichier à télécharger',
UploadProgressLbl : '(Envoi en cours, veuillez patienter...)',
UploadBtn : 'Envoyer le fichier sélectionné',
UploadBtnCancel : 'Annuler',
UploadNoFileMsg : 'Sélectionner un fichier sur votre ordinateur.',
UploadNoFolder : 'Merci de sélectionner un répertoire avant l\'envoi.',
UploadNoPerms : 'L\'envoi de fichier n\'est pas autorisé.',
UploadUnknError : 'Erreur pendant l\'envoi du fichier.',
UploadExtIncorrect : 'L\'extension du fichier n\'est pas autorisée dans ce dossier.',
// Flash Uploads
UploadLabel : 'Fichier à envoyer',
UploadTotalFiles : 'Nombre de fichiers :',
UploadTotalSize : 'Poids total :',
UploadSend : 'Envoyer',
UploadAddFiles : 'Ajouter des fichiers',
UploadClearFiles : 'Supprimer les fichiers',
UploadCancel : 'Annuler l\'envoi',
UploadRemove : 'Retirer',
UploadRemoveTip : 'Retirer !f',
UploadUploaded : 'Téléchargement !n%',
UploadProcessing : 'Progression...',
// Settings Panel
SetTitle : 'Configuration',
SetView : 'Voir :',
SetViewThumb : 'Miniatures',
SetViewList : 'Liste',
SetDisplay : 'Affichage :',
SetDisplayName : 'Nom du fichier',
SetDisplayDate : 'Date',
SetDisplaySize : 'Taille du fichier',
SetSort : 'Classement :',
SetSortName : 'par nom de fichier',
SetSortDate : 'par date',
SetSortSize : 'par taille',
SetSortExtension : 'par extension de fichier',
// Status Bar
FilesCountEmpty : '<Dossier Vide>',
FilesCountOne : '1 fichier',
FilesCountMany : '%1 fichiers',
// Size and Speed
Kb : '%1 Ko',
Mb : '%1 Mo',
Gb : '%1 Go',
SizePerSecond : '%1/s',
// Connector Error Messages.
ErrorUnknown : 'La demande n\'a pas abouti. (Erreur %1)',
Errors :
{
10 : 'Commande invalide.',
11 : 'Le type de ressource n\'a pas été spécifié dans la commande.',
12 : 'Le type de ressource n\'est pas valide.',
102 : 'Nom de fichier ou de dossier invalide.',
103 : 'La demande n\'a pas abouti : problème d\'autorisations.',
104 : 'La demande n\'a pas abouti : problème de restrictions de permissions.',
105 : 'Extension de fichier invalide.',
109 : 'Demande invalide.',
110 : 'Erreur inconnue.',
111 : 'It was not possible to complete the request due to resulting file size.', // MISSING
115 : 'Un fichier ou un dossier avec ce nom existe déjà.',
116 : 'Ce dossier n\'existe pas. Veuillez rafraîchir la page et réessayer.',
117 : 'Ce fichier n\'existe pas. Veuillez rafraîchir la page et réessayer.',
118 : 'Les chemins vers la source et la cible sont les mêmes.',
201 : 'Un fichier avec ce nom existe déjà. Le fichier téléversé a été renommé en "%1".',
202 : 'Fichier invalide.',
203 : 'Fichier invalide. La taille est trop grande.',
204 : 'Le fichier téléversé est corrompu.',
205 : 'Aucun dossier temporaire n\'est disponible sur le serveur.',
206 : 'Envoi interrompu pour raisons de sécurité. Le fichier contient des données de type HTML.',
207 : 'Le fichier téléchargé a été renommé "%1".',
300 : 'Le déplacement des fichiers a échoué.',
301 : 'La copie des fichiers a échoué.',
500 : 'L\'interface de gestion des fichiers est désactivé. Contactez votre administrateur et vérifier le fichier de configuration de CKFinder.',
501 : 'La fonction "miniatures" est désactivée.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Le nom du fichier ne peut être vide.',
FileExists : 'Le fichier %s existes déjà.',
FolderEmpty : 'Le nom du dossier ne peut être vide.',
FolderExists : 'Le dossier %s existe déjà.',
FolderNameExists : 'Le dossier existe déjà.',
FileInvChar : 'Le nom du fichier ne peut pas contenir les charactères suivants : \n\\ / : * ? " < > |',
FolderInvChar : 'Le nom du dossier ne peut pas contenir les charactères suivants : \n\\ / : * ? " < > |',
PopupBlockView : 'Il n\'a pas été possible d\'ouvrir la nouvelle fenêtre. Désactiver votre bloqueur de fenêtres pour ce site.',
XmlError : 'Impossible de charger correctement la réponse XML du serveur web.',
XmlEmpty : 'Impossible de charger la réponse XML du serveur web. Le serveur a renvoyé une réponse vide.',
XmlRawResponse : 'Réponse du serveur : %s'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Redimensionner %s',
sizeTooBig : 'Impossible de modifier la hauteur ou la largeur de cette image pour une valeur plus grande que l\'original (%size).',
resizeSuccess : 'L\'image a été redimensionnée avec succès.',
thumbnailNew : 'Créer une nouvelle vignette',
thumbnailSmall : 'Petit (%s)',
thumbnailMedium : 'Moyen (%s)',
thumbnailLarge : 'Gros (%s)',
newSize : 'Déterminer les nouvelles dimensions',
width : 'Largeur',
height : 'Hauteur',
invalidHeight : 'Hauteur invalide.',
invalidWidth : 'Largeur invalide.',
invalidName : 'Nom de fichier incorrect.',
newImage : 'Créer une nouvelle image',
noExtensionChange : 'L\'extension du fichier ne peut pas être changé.',
imageSmall : 'L\'image est trop petit',
contextMenuName : 'Redimensionner',
lockRatio : 'Conserver les proportions',
resetSize : 'Taille d\'origine'
},
// Fileeditor plugin
Fileeditor :
{
save : 'Sauvegarder',
fileOpenError : 'Impossible d\'ouvrir le fichier',
fileSaveSuccess : 'Fichier sauvegardé avec succès.',
contextMenuName : 'Edition',
loadingFile : 'Chargement du fichier, veuillez patientez...'
},
Maximize :
{
maximize : 'Agrandir',
minimize : 'Minimiser'
},
Gallery :
{
current : 'Image {current} sur {total}'
},
Zip :
{
extractHereLabel : 'Décompresser ici',
extractToLabel : 'Décompresser vers...',
downloadZipLabel : 'Zipper et télécharger',
compressZipLabel : 'Zipper',
removeAndExtract : 'Supprimer les fichiers existants et décompresser',
extractAndOverwrite : 'Décompresser et remplacer les fichier existants',
extractSuccess : 'Les fichiers ont été décompressés avec succès.'
},
Search :
{
searchPlaceholder : 'Rechercher'
}
};
| JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.