code
stringlengths 501
5.19M
| package
stringlengths 2
81
| path
stringlengths 9
304
| filename
stringlengths 4
145
|
---|---|---|---|
================
Error handling
================
.. currentmodule:: zope.formlib.interfaces
These are a couple of functional tests that were written on-the-go ... In the
future this might become more extensive ...
Displaying invalidation errors
==============================
Validation errors, e.g. cause by invariants, are converted into readable text
by adapting them to `IWidgetInputErrorView`:
>>> from zope.publisher.browser import TestRequest
>>> from zope.interface.exceptions import Invalid
>>> from zope.component import getMultiAdapter
>>> from zope.formlib.interfaces import IWidgetInputErrorView
>>> error = Invalid("You are wrong!")
>>> message = getMultiAdapter((error, TestRequest()),
... IWidgetInputErrorView).snippet()
>>> message
'<span class="error">You are wrong!</span>'
Interface invariant methods raise `zope.interface.Invalid` exception. Test if
this exception gets handled by the error_views.
>>> myError = Invalid('My error message')
>>> import zope.formlib.form
>>> mybase = zope.formlib.form.FormBase(None, TestRequest())
>>> mybase.errors = (myError,)
>>> save = mybase.error_views()
>>> next(save)
'<span class="error">My error message</span>'
Now we need to set up the translation framework:
>>> from zope import component, interface
>>> from zope.i18n.interfaces import INegotiator
>>> @interface.implementer(INegotiator)
... class Negotiator:
... def getLanguage(*ignored): return 'test'
>>> component.provideUtility(Negotiator())
>>> from zope.i18n.testmessagecatalog import TestMessageFallbackDomain
>>> component.provideUtility(TestMessageFallbackDomain)
And yes, we can even handle an i18n message in an Invalid exception:
>>> from zope.i18nmessageid import MessageFactory
>>> _ = MessageFactory('my.domain')
>>> myError = Invalid(_('My i18n error message'))
>>> mybase = zope.formlib.form.FormBase(None, TestRequest())
>>> mybase.errors = (myError,)
>>> save = mybase.error_views()
>>> next(save)
'<span class="error">[[my.domain][My i18n error message]]</span>'
Displaying widget input errors
==============================
`WidgetInputError` exceptions also work with i18n messages:
>>> from zope.formlib.interfaces import WidgetInputError
>>> myError = WidgetInputError(
... field_name='summary',
... widget_title=_('Summary'),
... errors=_('Foo'))
>>> mybase = zope.formlib.form.FormBase(None, TestRequest())
>>> mybase.errors = (myError,)
>>> save = mybase.error_views()
>>> next(save)
'[[my.domain][Summary]]: <span class="error">[[my.domain][Foo]]</span>'
| zope.formlib | /zope.formlib-6.0.tar.gz/zope.formlib-6.0/src/zope/formlib/errors.rst | errors.rst |
"""Browser widgets for text-like data
"""
__docformat__ = 'restructuredtext'
from zope.browserpage import ViewPageTemplateFile
from zope.interface import implementer
from zope.schema import getFieldNamesInOrder
from zope import component
from zope.formlib.interfaces import IInputWidget
from zope.formlib.interfaces import IWidgetInputErrorView
from zope.formlib.utility import applyWidgetsChanges
from zope.formlib.utility import setUpWidgets
from zope.formlib.widget import BrowserWidget
from zope.formlib.widget import InputWidget
class ObjectWidgetView:
template = ViewPageTemplateFile('objectwidget.pt')
def __init__(self, context, request):
self.context = context
self.request = request
def __call__(self):
return self.template()
@implementer(IInputWidget)
class ObjectWidget(BrowserWidget, InputWidget):
"""A widget over an Interface that contains Fields.
``factory``
factory used to create content that this widget (field) represents
``*_widget``
Optional CustomWidgets used to generate widgets for the fields in this
widget
"""
_object = None # the object value (from setRenderedValue & request)
_request_parsed = False
def __init__(self, context, request, factory, **kw):
super().__init__(context, request)
# define view that renders the widget
self.view = ObjectWidgetView(self, request)
# factory used to create content that this widget (field)
# represents
self.factory = factory
# handle foo_widget specs being passed in
self.names = getFieldNamesInOrder(self.context.schema)
for k, v in kw.items():
if k.endswith('_widget'):
setattr(self, k, v)
# set up my subwidgets
self._setUpEditWidgets()
def setPrefix(self, prefix):
super().setPrefix(prefix)
self._setUpEditWidgets()
def _setUpEditWidgets(self):
# subwidgets need a new name
setUpWidgets(self, self.context.schema, IInputWidget,
prefix=self.name, names=self.names,
context=self.context)
def __call__(self):
return self.view()
def legendTitle(self):
return self.context.title or self.context.__name__
def getSubWidget(self, name):
return getattr(self, '%s_widget' % name)
def subwidgets(self):
return [self.getSubWidget(name) for name in self.names]
def hidden(self):
"""Render the object as hidden fields."""
result = []
for name in self.names:
result.append(self.getSubwidget(name).hidden())
return "".join(result)
def error(self):
if self._error:
errormessages = []
keys = sorted(self._error.keys())
for key in keys:
errormessages.append(str(key) + ': ')
errormessages.append(component.getMultiAdapter(
(self._error[key], self.request),
IWidgetInputErrorView).snippet())
errormessages.append(str(key) + ', ')
return ''.join(errormessages[0:-1])
return ""
def getInputValue(self):
"""Return converted and validated widget data.
The value for this field will be represented as an `ObjectStorage`
instance which holds the subfield values as attributes. It will
need to be converted by higher-level code into some more useful
object (note that the default EditView calls `applyChanges`, which
does this).
"""
errors = []
content = self.factory()
for name in self.names:
try:
setattr(content, name, self.getSubWidget(name).getInputValue())
except Exception as e:
errors.append(e)
if self._error is None:
self._error = {}
if name not in self._error:
self._error[name] = e
if errors:
raise errors[0]
return content
def applyChanges(self, content):
"""See `zope.formlib.interfaces.IInputWidget.applyChanges`"""
field = self.context
# create our new object value
value = field.query(content, None)
if value is None:
# TODO: ObjectCreatedEvent here would be nice
value = self.factory()
# apply sub changes, see if there *are* any changes
# TODO: ObjectModifiedEvent here would be nice
changes = applyWidgetsChanges(self, field.schema, target=value,
names=self.names)
# if there's changes, then store the new value on the content
if changes:
field.set(content, value)
# TODO: If value implements ILocation, set name to field name and
# parent to content
return changes
def hasInput(self):
"""Is there input data for the field
Return ``True`` if there is data and ``False`` otherwise.
"""
for name in self.names:
if self.getSubWidget(name).hasInput():
return True
return False
def setRenderedValue(self, value):
"""Set the default data for the widget.
The given value should be used even if the user has entered
data.
"""
# re-call setupwidgets with the content
self._setUpEditWidgets()
for name in self.names:
self.getSubWidget(name).setRenderedValue(
getattr(value, name, None)) | zope.formlib | /zope.formlib-6.0.tar.gz/zope.formlib-6.0/src/zope/formlib/objectwidget.py | objectwidget.py |
Functional tests to verify bugs are gone
========================================
`setupWidgets` and `DISPLAY_UNWRITEABLE`
++++++++++++++++++++++++++++++++++++++++
This is to verify that bug #219948 is gone: setupWidgets doesn't check for
write access on the adapter.
Create a form containg two interfaces:
>>> import zope.formlib.tests
>>> class MyFormBase(object):
... form_fields = zope.formlib.form.FormFields(
... zope.formlib.tests.IOrder, zope.formlib.tests.IDescriptive,
... render_context=zope.formlib.interfaces.DISPLAY_UNWRITEABLE).omit(
... 'now')
>>> class MyEditForm(MyFormBase, zope.formlib.form.EditForm):
... pass
Instanciate the context objects and the form:
>>> import zope.publisher.browser
>>> request = zope.publisher.browser.TestRequest()
>>> order = zope.formlib.tests.Order()
>>> form = MyEditForm(order, request)
When we render the form, the fields of IDescriptive are read only because we
have no write access (this is configured in ftesting.zcml), the others are
writable[#needsinteraction]_:
>>> form.setUpWidgets()
>>> form.widgets['title']
<zope.formlib.widget.DisplayWidget object at 0x...>
>>> form.widgets['name']
<zope.formlib.textwidgets.TextWidget object at 0x...>
Make sure we have the same behaviour for non-edit forms:
>>> class MyForm(MyFormBase, zope.formlib.form.Form):
... pass
>>> import zope.publisher.browser
>>> request = zope.publisher.browser.TestRequest()
>>> order = zope.formlib.tests.Order()
>>> form = MyForm(order, request)
>>> form.setUpWidgets()
>>> form.widgets['title']
<zope.formlib.widget.DisplayWidget object at 0x...>
>>> form.widgets['name']
<zope.formlib.textwidgets.TextWidget object at 0x...>
Clean up:
>>> zope.security.management.endInteraction()
.. [#needsinteraction]
>>> import zope.security.management
>>> import zope.security.testing
>>> request.setPrincipal(zope.security.management.system_user)
>>> zope.security.management.newInteraction(request)
| zope.formlib | /zope.formlib-6.0.tar.gz/zope.formlib-6.0/src/zope/formlib/bugs.rst | bugs.rst |
function moveItems(from, to)
{
// shortcuts for selection fields
var src = document.getElementById(from);
var tgt = document.getElementById(to);
if (src.selectedIndex == -1) selectionError();
else
{
// iterate over all selected items
// --> attribute "selectedIndex" doesn't support multiple selection.
// Anyway, it works here, as a moved item isn't selected anymore,
// thus "selectedIndex" indicating the "next" selected item :)
while (src.selectedIndex > -1)
if (src.options[src.selectedIndex].selected)
{
// create a new virtal object with values of item to copy
temp = new Option(src.options[src.selectedIndex].text,
src.options[src.selectedIndex].value);
// append virtual object to targe
tgt.options[tgt.length] = temp;
// want to select newly created item
temp.selected = true;
// delete moved item in source
src.options[src.selectedIndex] = null;
}
}
}
// move item from "from" selection to "to" selection
function from2to(name)
{
moveItems(name+".from", name+".to");
copyDataForSubmit(name);
}
// move item from "to" selection back to "from" selection
function to2from(name)
{
moveItems(name+".to", name+".from");
copyDataForSubmit(name);
}
function swapFields(a, b)
{
// swap text
var temp = a.text;
a.text = b.text;
b.text = temp;
// swap value
temp = a.value;
a.value = b.value;
b.value = temp;
// swap selection
temp = a.selected;
a.selected = b.selected;
b.selected = temp;
}
// move selected item in "to" selection one up
function moveUp(name)
{
// shortcuts for selection field
var toSel = document.getElementById(name+".to");
if (toSel.selectedIndex == -1)
selectionError();
else if (toSel.options[0].selected)
alert("Cannot move further up!");
else for (var i = 0; toSel.length > i; i++)
if (toSel.options[i].selected)
{
swapFields(toSel.options[i-1], toSel.options[i]);
copyDataForSubmit(name);
}
}
// move selected item in "to" selection one down
function moveDown(name)
{
// shortcuts for selection field
var toSel = document.getElementById(name+".to");
if (toSel.selectedIndex == -1) {
selectionError();
} else if (toSel.options[toSel.length-1].selected) {
alert("Cannot move further down!");
} else {
for (var i = toSel.length-1; i >= 0; i--) {
if (toSel.options[i].selected) {
swapFields(toSel.options[i+1], toSel.options[i]);
}
}
copyDataForSubmit(name);
}
}
// copy each item of "toSel" into one hidden input field
function copyDataForSubmit(name)
{
// shortcuts for selection field and hidden data field
var toSel = document.getElementById(name+".to");
var toDataContainer = document.getElementById(name+".toDataContainer");
// delete all child nodes (--> complete content) of "toDataContainer" span
while (toDataContainer.hasChildNodes())
toDataContainer.removeChild(toDataContainer.firstChild);
// create new hidden input fields - one for each selection item of
// "to" selection
for (var i = 0; toSel.options.length > i; i++)
{
// create virtual node with suitable attributes
var newNode = document.createElement("input");
newNode.setAttribute("name", name.replace(/-/g, '.')+':list');
newNode.setAttribute("type", "hidden");
newNode.setAttribute("value", toSel.options[i].value);
// actually append virtual node to DOM tree
toDataContainer.appendChild(newNode);
}
}
// error message for missing selection
function selectionError()
{alert("Must select something!")} | zope.formlib | /zope.formlib-6.0.tar.gz/zope.formlib-6.0/src/zope/formlib/js/ordered_selection.js | ordered_selection.js |
===============
API Reference
===============
zope.formlib.interfaces
=======================
.. automodule:: zope.formlib.interfaces
zope.formlib.boolwidgets
========================
.. automodule:: zope.formlib.boolwidgets
zope.formlib.errors
===================
.. automodule:: zope.formlib.errors
zope.formlib.exception
======================
.. automodule:: zope.formlib.exception
zope.formlib.form
=================
.. automodule:: zope.formlib.form
zope.formlib.i18n
=================
.. automodule:: zope.formlib.i18n
zope.formlib.itemswidgets
=========================
.. automodule:: zope.formlib.itemswidgets
zope.formlib.namedtemplate
==========================
.. automodule:: zope.formlib.namedtemplate
zope.formlib.objectwidget
=========================
.. automodule:: zope.formlib.objectwidget
zope.formlib.sequencewidget
===========================
.. automodule:: zope.formlib.sequencewidget
zope.formlib.source
===================
.. automodule:: zope.formlib.source
zope.formlib.textwidgets
========================
.. automodule:: zope.formlib.textwidgets
zope.formlib.utility
====================
.. automodule:: zope.formlib.utility
zope.formlib.widget
===================
.. automodule:: zope.formlib.widget
zope.formlib.widgets
====================
.. automodule:: zope.formlib.widgets
| zope.formlib | /zope.formlib-6.0.tar.gz/zope.formlib-6.0/docs/api/index.rst | index.rst |
import os
import shutil
from zope.fssync import fsutil
class FileCopier(object):
"""Copy from a normal file tree into an fssync checkout."""
def __init__(self, sync):
self.sync = sync
def copy(self, source, target, children=True):
if os.path.isdir(source):
os.mkdir(target)
shutil.copymode(source, target)
self.addEntry(source, target)
if children:
queue = self.listDirectory(source)
while queue:
fn = queue.pop(0)
src = os.path.join(source, fn)
dst = os.path.join(target, fn)
if os.path.isdir(src):
os.mkdir(dst)
shutil.copymode(src, dst)
self.addEntry(src, dst)
queue.extend([os.path.join(fn, f)
for f in self.listDirectory(src)])
else:
shutil.copy(src, dst)
self.addEntry(src, dst)
else:
shutil.copy(source, target)
self.addEntry(source, target)
def addEntry(self, source, target):
self.sync.add(target)
def listDirectory(self, dir):
return [fn
for fn in os.listdir(dir)
if fn != "@@Zope"
if not self.sync.fsmerger.ignore(fn)]
class ObjectCopier(FileCopier):
"""Copy objects from an fssync checkout into an fssync checkout."""
def addEntry(self, source, target):
type, factory = self.sync.metadata.gettypeinfo(source)
self._syncadd(target, type, factory)
self._copyspecials(source, target, fsutil.getextra)
self._copyspecials(source, target, fsutil.getannotations)
def _syncadd(self, target, type, factory):
self.sync.add(target, type, factory)
def _copyspecials(self, source, target, getwhat):
src = getwhat(source)
if os.path.isdir(src):
dst = getwhat(target)
fsutil.ensuredir(dst)
copier = SpecialCopier(self.sync)
for name in self.sync.metadata.getnames(src):
# copy a single child
copier.copy(os.path.join(src, name), os.path.join(dst, name))
self.sync.metadata.flush()
def listDirectory(self, dir):
# We don't need to worry about fsmerger.ignore() since we're
# only relying on metadata to generate the list of names.
return self.sync.metadata.getnames(dir)
class SpecialCopier(ObjectCopier):
"""Copy extras and annotations as part of an object copy.
This is a specialized copier that doesn't expect the original to
have a path.
"""
def _syncadd(self, target, type, factory):
self.sync.basicadd(target, type, factory) | zope.fssync | /zope.fssync-3.6.1.zip/zope.fssync-3.6.1/src/zope/fssync/copier.py | copier.py |
__docformat__ = 'restructuredtext'
from cStringIO import StringIO
from cPickle import Unpickler
from zope import component
from zope import interface
from zope import traversing
from zope import location
from zope.location.interfaces import ILocation
from zope.location.traversing import LocationPhysicallyLocatable
from zope.traversing.interfaces import IContainmentRoot
from zope.xmlpickle import xmlpickle
import interfaces
PARENT_MARKER = ".."
def getPath(obj):
path = LocationPhysicallyLocatable(obj).getPath()
return path.encode('utf-8')
class PathPersistentIdGenerator(object):
"""Uses traversal paths as persistent ids.
>>> root = TLocation()
>>> interface.directlyProvides(root, IContainmentRoot)
>>> o1 = TLocation(); o1.__parent__ = root; o1.__name__ = 'o1'
>>> o2 = TLocation(); o2.__parent__ = root; o2.__name__ = 'o2'
>>> o3 = TLocation(); o3.__parent__ = o1; o3.__name__ = 'o3'
>>> root.o1 = o1
>>> root.o2 = o2
>>> o1.foo = o2
>>> o1.o3 = o3
>>> gen = PathPersistentIdGenerator(StandardPickler(o1))
>>> gen.id(root)
'..'
>>> gen.id(o2)
'/o2'
>>> gen.id(o3)
>>> gen.id(o1)
>>> gen = PathPersistentIdGenerator(StandardPickler(o3))
>>> gen.id(root)
'/'
"""
interface.implements(interfaces.IPersistentIdGenerator)
component.adapts(interfaces.IPickler)
root = None
def __init__(self, pickler):
self.pickler = pickler
top = self.location = pickler.context
self.parent = getattr(top, "__parent__", None)
if ILocation.providedBy(top):
try:
self.root = LocationPhysicallyLocatable(top).getRoot()
except TypeError:
pass
def id(self, object):
if self.parent is None:
return None
if ILocation.providedBy(object):
if location.inside(object, self.location):
return None
elif object is self.parent:
# emit special parent marker
return PARENT_MARKER
elif location.inside(object, self.root):
return getPath(object)
elif object.__parent__ is None:
return None
raise ValueError(
"object implementing ILocation found outside tree")
else:
return None
class PathPersistentLoader(object):
"""Loads objects from paths.
Uses path traversal if the context of the adapted
Unpickler is locatable."""
interface.implements(interfaces.IPersistentIdLoader)
component.adapts(interfaces.IUnpickler)
def __init__(self, unpickler):
context = self.parent = unpickler.context
self.root = None
if ILocation.providedBy(context):
locatable = LocationPhysicallyLocatable(context)
__traceback_info__ = (context, locatable)
try:
self.root = locatable.getRoot()
except TypeError:
pass
if self.root is not None:
traverser = traversing.interfaces.ITraverser(self.root)
self.traverse = traverser.traverse
def load(self, path):
"""Loads the object.
Returns the context of the adapted Unpickler if a PARENT_MARKER
is found.
"""
if path == PARENT_MARKER:
return self.parent
if path[:1] == "/":
# outside object:
if path == "/":
return self.root
else:
return self.traverse(path[1:])
raise ValueError("unknown persistent object reference: %r" % path)
class StandardPickler(object):
"""A pickler that uses the standard pickle format.
Calls an IPersistentIdGenerator multi adapter.
Uses the _PicklerThatSortsDictItems to ensure that pickles
are repeatable.
"""
interface.implements(interfaces.IPickler)
component.adapts(interface.Interface)
def __init__(self, context):
self.context = context
def dump(self, writeable):
pickler = xmlpickle._PicklerThatSortsDictItems(writeable, 0)
generator = interfaces.IPersistentIdGenerator(self, None)
if generator is not None:
pickler.persistent_id = generator.id
pickler.dump(self.context)
def dumps(self):
stream = StringIO()
self.dump(stream)
return stream.getvalue()
class StandardUnpickler(object):
"""An unpickler for a standard pickle format.
Calls an IPersistentIdLoader multi adapter.
"""
interface.implements(interfaces.IUnpickler)
component.adapts(interface.Interface)
def __init__(self, context):
self.context = context
def load(self, readable):
unpickler = Unpickler(readable)
loader = interfaces.IPersistentIdLoader(self, None)
if loader is not None:
unpickler.persistent_load = loader.load
return unpickler.load()
def loads(self, pickle):
return self.load(StringIO(pickle))
class XMLPickler(StandardPickler):
"""A pickler that uses a XML format.
The current implementation assumes that the pickle can be
hold in memory completely.
"""
interface.implements(interfaces.IPickler)
component.adapts(interface.Interface)
def dump(self, writeable):
stream = StringIO()
super(XMLPickler, self).dump(stream)
p = stream.getvalue()
writeable.write(xmlpickle.toxml(p))
class XMLUnpickler(StandardUnpickler):
"""A pickler that uses a XML format.
The current implementation assumes that the pickle can be
hold in memory completely.
"""
def load(self, readable):
pickle = xmlpickle.fromxml(readable.read())
return super(XMLUnpickler, self).load(StringIO(pickle))
from zope.location.location import Location
class TLocation(Location):
"""Simple traversable location used in examples."""
interface.implements(traversing.interfaces.ITraverser)
def traverse(self, path, default=None, request=None):
o = self
for name in path.split(u'/'):
o = getattr(o, name)
return o
class DataLocation(TLocation):
"""Sample data container class used in doctests."""
def __init__(self, name, parent, data):
self.__name__ = name
self.__parent__ = parent
if parent is not None:
setattr(parent, name, self)
self.data = data
super(DataLocation, self).__init__() | zope.fssync | /zope.fssync-3.6.1.zip/zope.fssync-3.6.1/src/zope/fssync/pickle.py | pickle.py |
__docformat__ = "reStructuredText"
from zope import interface
import zope.interface.common.mapping
from zope import component
from zope import schema
from zope import lifecycleevent
class ISynchronizableExtras(interface.common.mapping.IMapping):
"""A mapping of selected object attributes."""
class ISynchronizableAnnotations(interface.common.mapping.IMapping):
"""A mapping of synchronizable annotation namespaces."""
def modify(target):
"""Modifies the target annotations.
Transfers the synchronizable namespaces to the target annotations.
Returns an lifecycleevent.interfaces.IModificationDescription
if changes were detected, None othewise.
"""
class IObjectSynchronized(lifecycleevent.interfaces.IModificationDescription):
"""A unspecific modification description.
Basically says that an object has changed during a sync
operation. If you can say more specific things you should
use other modification descriptions.
"""
class IRepository(interface.Interface):
"""A target system that stores objects as files or directories."""
chunk_size = schema.Int(
title=u"Chunk Size",
description=u"The chunk size.",
default=32768)
case_insensitive = schema.Bool(
title=u"Case Insensitive",
description=u"Is this repository case insensitive?",
default=False)
def getMetadata():
"""Returns a metadata database for the repository.
"""
def disambiguate(dirpath, name):
"""Disambiguates a name in a directory.
"""
def dirname(path):
"""Returns the dirname."""
def join(path, *names):
"""Returns a joined path."""
def normalize(name):
"""Normalize a filename.
"""
def encode(path, encoding=None):
"""Encodes a path in its normalized form."""
def writeable(path):
"""Returns a writeable file handler."""
def readable(path):
"""Returns a readable file handler."""
class IPickler(interface.Interface):
"""A pickler."""
def dump(writeable):
"""Dumps a pickable object to a writeable file-like object."""
class IUnpickler(interface.Interface):
"""An unpickler."""
def load(readable):
"""Loads a pickled object from a readable file-like object."""
class IEntryId(interface.Interface):
"""Returns an id that can be saved in a metadata database.
The id must be 'stringifiable'.
"""
def __str__():
"""Returns a string representation.
The encoding should be 'UTF-8'.
"""
class IPersistentIdGenerator(interface.Interface):
"""Generates a pickable persistent references."""
def id(self, obj):
"""Returns a persistent reference."""
class IPersistentIdLoader(interface.Interface):
def load(self, id):
"""Resolves a persistent reference."""
class IWriteable(interface.Interface):
"""A writeable file handle."""
def write(data):
"""Writes the data."""
def close():
"""Closes the file-like object.
Ensures that pending data are written.
"""
class IReadable(interface.Interface):
"""A readable file handle."""
def read(bytes=None):
"""Reads the number of bytes or all data if bytes is None."""
def close():
"""Closes the file handle."""
class ISyncTask(interface.Interface):
"""Base interface for ICheckout, ICommit, and ICheck.
The repository may be a filesystem, an archive, a database,
or something else that is able to store serialized data.
"""
repository = schema.Object(
IRepository,
title=u"Repository",
description=u"The repository that contains the serialized data.")
context = schema.Object(
interface.Interface,
title=u"Context",
description=u"Context of reference")
def __init__(getSynchronizer, repository, context=None):
"""Inits the task with a getSynchronizer lookup function,
a repository, and an optional context.
"""
class ICheckout(ISyncTask):
"""Checkout objects from a content space to a repository.
"""
def perform(obj, name, location=''):
"""Check an object out to the repository.
obj -- The object to be checked out
name -- The name of the object
location -- The directory or path where the object will go
"""
class ICheckin(ISyncTask):
"""Import objects from the repository to a content space.
"""
def perform(obj, name, location=''):
"""Performs a checkin.
obj -- The object to be checked in
name -- The name of the object
location -- The location where the object will go
Raises a ``SynchronizationError`` if the object
already exists at the given location.
"""
class ICheck(ISyncTask):
"""Check that the repository is consistent with the object database."""
def perform(container, name, fspath):
"""Compare an object or object tree from a repository.
If the originals in the repository are not uptodate, errors
are reported by a errors() call.
Invalid object names are reported by raising
``SynchronizationError``.
"""
def errors():
"""Returns a list of paths with errors."""
class ICommit(ISyncTask):
"""Commits a repository to a content space."""
def perform(container, name, fspath, context=None):
"""Synchronize an object or object tree from a repository.
"""
class IFileSystemRepository(IRepository):
"""A filesystem repository.
Stores the data in a directory tree on the filesystem.
"""
class IArchiveRepository(IRepository):
"""A repository that stores the data in a single file."""
def iterPaths():
"""Iterates over all paths in the archive."""
class IVersionControlRepository(IRepository):
"""A repository that stores the data in a version control system."""
class ISVNRepository(IRepository):
"""A repository that stores the data in a subversion checkout."""
class ISynchronizerFactory(component.interfaces.IFactory):
"""A factory for synchronizer, i.e. serializers/de-serializers.
The factory should be registered as a named utility with
the dotted name of the adapted class as the lookup key.
The default factory should be registered without a name.
The call of the factory should return
- an `IDirectorySynchronizer` adapter for the object if the
object is represented as a directory.
- an `IFileSynchronizer` adapter for the object if the
object is represented as a file.
"""
class ISerializer(interface.Interface):
"""Base interface for object serializer."""
def getObject():
"""Return the serializable entry."""
def metadata():
"""Returns a mapping with metadata.
The keys must be attribute names, the values utf-8 encoded strings.
"""
def annotations():
"""Return annotations for the entry.
Returns None if the serializer provides
it's own representation
"""
def extras():
"""Return extra data for the entry.
Returns None if the serializer provides it's own
representation of extras.
"""
class IDeserializer(interface.Interface):
"""The inverse operator of an ISerializer.
Deserializer consume serialized data and provide
write access to parts of the deserialized objects.
"""
def setmetadata(metadata):
"""Sets entry metadata.
Returns an lifecycleevent.interfaces.IModificationDescription
if relevant changes were detected, None othewise.
"""
def setannotations(annotations):
"""Sets deserialized annotations.
Returns an lifecycleevent.interfaces.IModificationDescription
if relevant changes were detected, None othewise.
"""
def setextras(extras):
"""Sets deserialized extra data.
Returns an lifecycleevent.interfaces.IModificationDescription
if relevant changes were detected, None othewise.
"""
class ISynchronizer(ISerializer, IDeserializer):
"""A base interface for synchronizers."""
class IFileSerializer(ISerializer):
"""Writes data to a file-like object."""
def dump(writeable):
"""Dump the file content to a writeable file handle."""
class IFileDeserializer(IDeserializer):
"""Reads data from a file-like object."""
def load(readable):
"""Reads serialized file content."""
class IFileSynchronizer(IFileSerializer, IFileDeserializer):
"""A sycnronizer for file-like objects."""
class IDefaultSynchronizer(IFileSynchronizer):
"""A serializer that uses an IPickler."""
class IDirectorySerializer(ISerializer):
"""Provides access to a dirctory listing."""
def __getitem__(key, value):
"""Gets an item."""
def iteritems():
"""Return an iterable directory listing of name, obj tuples."""
class IDirectoryDeserializer(IDeserializer):
"""Writes deserialized data into a directory-like object."""
def __setitem__(key, value):
"""Sets an item."""
def __delitem__(key):
"""Deletes an item."""
class IDirectorySynchronizer(ISynchronizer,
IDirectorySerializer, IDirectoryDeserializer):
"""A synchronizer for directory-like objects."""
def traverseName(name):
"""Traverses the name."""
class IObjectGenerator(interface.Interface):
"""A generator for objects with a special create protocol."""
def create(context, name):
"""Creates the object in the given context."""
class IFileGenerator(interface.Interface):
"""A generator that applies if no other file deserializers can be found."""
def create(context, readable, extension=None):
"""Creates a new file object and initializes it with the readable data.
Uses the optional file extension to determine the file type.
"""
def load(file, readable):
"""Consumes readable data for the generated file."""
class IDirectoryGenerator(IObjectGenerator):
"""A generator that applies if no other directory factories can be found."""
def getSynchronizer(obj):
"""Returns the class based synchronizer or the default synchronizer.""" | zope.fssync | /zope.fssync-3.6.1.zip/zope.fssync-3.6.1/src/zope/fssync/interfaces.py | interfaces.py |
import copy
import os
import sys
import unicodedata
import zope.interface
import metadata
import interfaces
from fsutil import Error
unwanted = ("", os.curdir, os.pardir)
class Repository(object):
"""Represents a repository that uses filepaths.
Possible examples are filesystems, SNARF-archives,
zip-archives, svn-repository, etc.
This base class also handles case insensitive filenames
and provides methods to resolve ambiguities.
"""
zope.interface.implements(interfaces.IRepository)
chunk_size = 32768
def __init__(self, case_insensitive=False, enforce_nfd=False, metadata=None):
self.case_insensitive = case_insensitive
self.enforce_nfd = enforce_nfd
self.files = {} # Keeps references to normalized filenames
# which have been used
self.disambiguated = {} # reserved disambiguated paths
self.metadata = metadata
def getMetadata(self):
"""Returns a metadata database.
This implementation returns an empty database
which reads the metadata on demand.
"""
if self.metadata is None:
return metadata.Metadata()
return self.metadata
def disambiguate(self, dirpath, name):
"""Disambiguates a name in a directory.
Adds a number to the file and leaves the case untouched.
"""
if self.case_insensitive or self.enforce_nfd:
if self.enforce_nfd:
dirpath = self._toNFD(dirpath)
name = self._toNFD(name)
disambiguated = self.disambiguated.setdefault(dirpath, set())
dot = name.rfind('.')
if dot >= 0:
suffix = name[dot:]
name = name[:dot]
else:
suffix = ''
n = name + suffix
normalized = self.normalize(n)
i = 1
while normalized in disambiguated:
n = name + '-' + str(i) + suffix
normalized = self.normalize(n)
i += 1
disambiguated.add(normalized)
return n
return name
def dirname(self, path):
"""Returns the dirname."""
return os.path.dirname(path)
def join(self, path, *names):
"""Returns a joined path."""
return os.path.join(path, *names)
def _toNFD(self, name):
"""Helper to ensure NFD encoding.
Linux and (most?) other Unix-like operating systems use the normalization
form C (NFC) for UTF-8 encoding by default but do not enforce this.
Darwin, the base of Macintosh OSX, enforces normalization form D (NFD),
where a few characters are encoded in a different way.
"""
if isinstance(name, unicode):
name = unicodedata.normalize("NFD", name)
elif sys.getfilesystemencoding() == 'utf-8':
name = unicode(name, encoding='utf-8')
name = unicodedata.normalize("NFD", name)
name = name.encode('utf-8')
return name
def _toNFC(self, name):
"""Helper to ensure NFC encoding.
Linux and (most?) other Unix-like operating systems use the normalization
form C (NFC) for UTF-8 encoding by default but do not enforce this.
Darwin, the base of Macintosh OSX, enforces normalization form D (NFD),
where a few characters are encoded in a different way.
"""
if isinstance(name, unicode):
name = unicodedata.normalize("NFC", name)
elif sys.getfilesystemencoding() == 'utf-8':
name = unicode(name, encoding='utf-8')
name = unicodedata.normalize("NFC", name)
name = name.encode('utf-8')
return name
def normalize(self, name):
"""Normalize a filename.
Uses lower case filenames if the repository is case sensitive.
"""
if self.enforce_nfd:
name = self._toNFD(name)
if self.case_insensitive:
name = name.lower()
return name
def encode(self, path, encoding=None):
"""Encodes a path in its normalized form.
Uses the filesystem encoding as a default encoding. Assumes that the given path
is also encoded in the filesystem encoding.
"""
fsencoding = sys.getfilesystemencoding()
if encoding is None:
encoding = fsencoding
if isinstance(path, unicode):
return self.normalize(path).encode(encoding)
return unicode(path, encoding=fsencoding).encode(encoding)
def writeable(self, path):
"""Must be overwritten.
"""
pass
def readable(self, path):
"""Must be overwritten."""
pass
def readFile(self, path):
"""Convenient method for reading a whole file."""
fp = self.readable(path)
try:
data = fp.read()
return data
finally:
fp.close()
def compare(self, readable1, readable2):
if readable1 is None:
return False
if readable2 is None:
return False
try:
for chunk in readable1.read(self.chunk_size):
size = len(chunk)
echo = readable2.read(size)
if echo != chunk:
return False
return True
finally:
readable1.close()
readable1.close()
class FileSystemRepository(Repository):
"""A filesystem repository that keeps track of already written files."""
zope.interface.implements(interfaces.IFileSystemRepository)
def exists(self, path):
"""Returns a joined path."""
return os.path.exists(path)
def isdir(self, path):
"""Checks whether the path corresponds to a directory."""
return os.path.isdir(path)
def readable(self, path):
"""Returns a file like object that is open for read operations."""
fp = self.files[path] = file(path, 'rb')
return fp
def writeable(self, path):
"""Returns a file like object that open for write operations.
"""
dirname = self.dirname(path)
self.ensuredir(dirname)
fp = self.files[path] = file(path, 'wb')
return fp
def split(self, path):
"""Split a path, making sure that the tail returned is real."""
head, tail = os.path.split(path)
if tail in unwanted:
newpath = os.path.normpath(path)
head, tail = os.path.split(newpath)
if tail in unwanted:
newpath = os.path.realpath(path)
head, tail = os.path.split(newpath)
if head == newpath or tail in unwanted:
raise Error("path '%s' is the filesystem root", path)
if not head:
head = os.curdir
return head, tail
def ensuredir(self, path):
"""Make sure that the given path is a directory, creating it if necessary.
This may raise OSError if the creation operation fails.
"""
if not os.path.isdir(path):
os.makedirs(path)
class SnarfMetadata(metadata.Metadata):
"""A metadata implementation that reads the metadata from a SNARF archive."""
def __init__(self, repository):
super(SnarfMetadata, self).__init__()
self.repository = repository
if not repository.stream:
return
for path in repository.iterPaths():
if path.endswith(repository.join('@@Zope', 'Entries.xml')):
dm = metadata.DirectoryManager.__new__(metadata.DirectoryManager)
dm.zdir = repository.dirname(path)
dm.efile = path
text = repository.readFile(path)
dm.entries = metadata.load_entries(text)
dm.originals = copy.deepcopy(dm.entries)
key = repository.dirname(dm.zdir)
self.cache[key] = dm
def getentry(self, file):
"""Return the metadata entry for a given file (or directory).
Modifying the dict that is returned will cause the changes to
the metadata to be written out when flush() is called. If
there is no metadata entry for the file, return a new empty
dict, modifications to which will also be flushed.
"""
dir, base = self.repository.split(file)
return self.getmanager(dir).getentry(base)
def getmanager(self, dir):
if dir not in self.cache:
self.cache[dir] = metadata.DirectoryManager(dir)
return self.cache[dir]
class SnarfReadable(object):
"""Mimics read access to a serialized SNARF file."""
def __init__(self, repository, path):
self.stream = repository.stream
self.startpos = repository.readpos[path]
self.size = repository.sizes[path]
self.name = path
def seek(self, offset, whence=0):
if whence == 0:
self.stream.seek(self.startpos + offset)
return offset
elif whence == 1:
return self.seek(self.tell() + offset)
elif whence == 2:
return self.seek(self.size + offset)
def tell(self):
return self.stream.tell() - self.startpos
def readline(self):
self.stream.readline()
def read(self, bytes=None):
if bytes is None or bytes is -1:
rest = self.size - self.tell()
return self.stream.read(rest)
rest = self.size - self.tell()
if bytes > rest:
return self.stream.read(rest)
return self.stream.read(bytes)
def close(self):
pass
class SnarfWriteable(object):
"""Mimics write access to a SNARF archive."""
def __init__(self, repository, path, pos):
stream = self.stream = repository.stream
self.name = path
self.pos = pos # pos of dummy length
self.start = stream.tell()
self.format = repository.len_format
def write(self, data):
self.stream.write(data)
self.stream.flush()
def close(self):
self.stream.flush()
pos = self.stream.tell()
size = pos - self.start
self.stream.seek(self.pos)
self.stream.write(self.format % size)
self.stream.seek(pos)
class SnarfRepository(FileSystemRepository):
"""A SNARF repository that stores a directory tree in a single archive."""
zope.interface.implements(interfaces.IArchiveRepository)
len_format = '%08d' # format of file length indicator
def __init__(self, stream, case_insensitive=False, enforce_nfd=False):
super(SnarfRepository, self).__init__(case_insensitive=case_insensitive,
enforce_nfd=enforce_nfd)
self.stream = stream
self.readpos = {}
self.sizes = {}
self.directories = set()
def getMetadata(self):
"""Returns a special metadata database which reads directly
from the SNARF archive."""
return SnarfMetadata(self)
def isdir(self, path):
"""Returns True iff the path matches a directory name.
Since SNARF refers only implicitely to dirnames all filenames
are scanned in the worst case.
"""
if path in self.files or path in self.readpos:
return False
return path in self.directories
def ensuredir(self, path):
"""Does nothing since a snarf treats directories implicitely."""
pass
def split(self, path):
return os.path.split(path)
def writeable(self, path):
"""Returns a file like object that is open for write operations.
Writes a dummy length indicator and a path. The returned
SnarfWriteable overwrites the length indicator on close.
"""
pos = self.stream.tell()
dummy = self.len_format % 0
self.stream.write("%s %s\n" % (dummy, path.encode('utf-8')))
fp = self.files[path] = SnarfWriteable(self, path, pos)
return fp
def readable(self, path):
fp = self.files[path] = SnarfReadable(self, path)
fp.seek(0)
return fp
def exists(self, path):
if not self.readpos:
self._scan()
return path in self.readpos or path in self.directories
def iterPaths(self):
if not self.readpos:
self._scan()
return self.readpos.iterkeys()
def readFile(self, path):
self.stream.seek(self.readpos[path])
return self.stream.read(self.sizes[path])
def _scan(self):
"""Scans the archive and reads all positions of files into a cache."""
self.stream.seek(0)
self.readpos = {}
pos = 0
while True:
infoline = self.stream.readline()
if not infoline:
break
if not infoline.endswith("\n"):
raise IOError("incomplete info line %r" % infoline)
offset = len(infoline)
infoline = infoline[:-1]
sizestr, path = infoline.split(" ", 1)
size = int(sizestr)
self.sizes[path] = size
pos = self.readpos[path] = pos + offset
self.directories.add(self.dirname(path))
pos += size
self.stream.seek(pos) | zope.fssync | /zope.fssync-3.6.1.zip/zope.fssync-3.6.1/src/zope/fssync/repository.py | repository.py |
==========================
Filesystem Synchronization
==========================
This package provides an API for the synchronization of Python objects
with a serialized filesystem representation. This API does not address
security issues. (See zope.app.fssync for a protected web-based API).
This API is Zope and ZODB independent.
The main use cases are
- data export / import (e.g. moving data from one place to another)
- content management (e.g. managing a wiki or other collections of
documents offline)
The target representation depends on your use case. In the use case of
data export/import, for instance, it is crucial that all data are
exported as completely as possible. Since the data need not be read
by humans in most circumstances a pickle format may be the most
complete and easy one to use.
In the use case of content management it may be more important that
all metadata are readable by humans. In this case another format,
e.g. RDFa, may be more appropriate.
Main components
===============
A synchronizer serializes content objects and stores the serialized
data in a repository in an application specific format. It uses
deserializers to read the object back into the content space.
The serialization format must be rich enough to preserve various forms
of references which should be reestablished on deserialization.
All these components should be replaceable. Application may use
different serialization formats with different references for
different purposes (e.g. backup vs. content management) and different
target systems (e.g. a zip archive vs. a svn repository).
The main components are:
- ISyncTasks like Checkout, Check, and Commit which synchronize
a content space with a repository. These tasks uses serializers
to produce serialized data for a repository in an application
specific format. They use deserializers to read the data back.
The default implementation uses xmlpickle for python objects,
data streams for file contents, and special directories for
extras and metadata. Alternative implementations may use
standard pickles, a human readable format like RDFa, or
application specific formats.
- ISynchronizer: Synchronizers produce serialized pieces of a
Python object (the ISerializer part of a synchronizer) and
consume serialized data to (re-)create Python objects (the
IDeserializer part of a synchronizer).
- IPickler: An adapter that determines the pickle format.
- IRepository: represents a target system that can be used
to read and write serialized data.
Let's take some samples:
>>> from StringIO import StringIO
>>> from zope import interface
>>> from zope import component
>>> from zope.fssync import interfaces
>>> from zope.fssync import task
>>> from zope.fssync import synchronizer
>>> from zope.fssync import repository
>>> from zope.fssync import pickle
>>> class A(object):
... data = 'data of a'
>>> class B(A):
... pass
>>> a = A()
>>> b = B()
>>> b.data = 'data of b'
>>> b.extra = 'extra of b'
>>> root = dict(a=a, b=b)
Persistent References
=====================
Many applications use more than one system of persistent references.
Zope, for instance, uses p_oids, int ids, key references,
traversal paths, dotted names, named utilities, etc.
Other systems might use generic reference systems like global unique
ids or primary keys together with domain specific references, like
emails, URI, postal addresses, code numbers, etc.
All these references are candidates for exportable references as long
as they can be resolved on import or reimport.
In our example we use simple integer ids:
>>> class GlobalIds(object):
... ids = dict()
... count = 0
... def getId(self, obj):
... for k, v in self.ids.iteritems():
... if obj == v:
... return k
... def register(self, obj):
... uid = self.getId(obj)
... if uid is not None:
... return uid
... self.count += 1
... self.ids[self.count] = obj
... return self.count
... def resolve(self, uid):
... return self.ids.get(int(uid), None)
>>> globalIds = GlobalIds()
>>> globalIds.register(a)
1
>>> globalIds.register(b)
2
>>> globalIds.register(root)
3
In our example we use the int ids as a substitute for the default path
references which are the most common references in Zope.
In our examples we use a SnarfRepository which can easily be examined:
>>> snarf = repository.SnarfRepository(StringIO())
>>> checkout = task.Checkout(synchronizer.getSynchronizer, snarf)
Snarf is a Zope3 specific archive format where the key
need is for simple software. The format is dead simple: each file
is represented by the string
'<size> <pathname>\n'
followed by exactly <size> bytes. Directories are not represented
explicitly.
Entry Ids
=========
Persistent ids are also used in the metadata files of fssync.
The references are generated by an IEntryId adapter which must
have a string representation in order to be saveable in a text file.
Typically these object ids correspond to the persistent pickle ids, but
this is not necessarily the case.
Since we do not have paths we use our integer ids:
>>> @component.adapter(interface.Interface)
... @interface.implementer(interfaces.IEntryId)
... def entryId(obj):
... global globalIds
... return globalIds.getId(obj)
>>> component.provideAdapter(entryId)
Synchronizer
============
In the use case of data export / import it is crucial that fssync is
able to serialize "all" object data. Note that it isn't always obvious
what data is intrinsic to an object. Therefore we must provide
special serialization / de-serialization tools which take care of
writing and reading "all" data.
An obvious solution would be to use inheriting synchronization
adapters. But this solution bears a risk. If someone created a subclass
and forgot to create an adapter, then their data would be serialized
incompletely. To give an example: What happens if someone has a
serialization adapter for class Person which serializes every aspect of
Person instances and defines a subclass Employee(Person) later on?
If the Employee class has some extra aspects (for example additional
attributes like insurance id, wage, etc.) these would never be serialized
as long as there is no special serialization adapter for Employees
which handles this extra aspects. The behavior is different if the
adapters are looked up by their dotted class name (i.e. the most specific
class) and not their class or interface (which might led to adapters
written for super classes). If no specific adapter exists a default
serializer (e.g a xmlpickler) can serialize the object completely. So
even if you forget to provide special serializers for all your classes
you can be sure that your data are complete.
Since the component architecture doesn't support adapters that work
one class only (not their subclasses), we register the adapter classes
as named ISynchronizerFactory utilities and use the dotted name of the
class as lookup key. The default synchronizer is registered as a
unnamed ISynchronizerFactory utility. This synchronizer ensures that
all data are pickled to the target repository.
>>> component.provideUtility(synchronizer.DefaultSynchronizer,
... provides=interfaces.ISynchronizerFactory)
All special synchronizers are registered for a specific content class and
not an abstract interface. The class is represented by the dotted class
name in the factory registration:
>>> class AFileSynchronizer(synchronizer.Synchronizer):
... interface.implements(interfaces.IFileSynchronizer)
... def dump(self, writeable):
... writeable.write(self.context.data)
... def load(self, readable):
... self.context.data = readable.read()
>>> component.provideUtility(AFileSynchronizer,
... interfaces.ISynchronizerFactory,
... name=synchronizer.dottedname(A))
The lookup of the utilities by the dotted class name is handled
by the getSynchronizer function, which first tries to find
a named utility. The IDefaultSynchronizer utility is used as a fallback:
>>> synchronizer.getSynchronizer(a)
<zope.fssync.doctest.AFileSynchronizer object at ...>
If no named adapter is registered it returns the registered unnamed default
adapter (as long as the permissions allow this):
>>> synchronizer.getSynchronizer(b)
<zope.fssync.synchronizer.DefaultSynchronizer object at ...>
This default serializer typically uses a pickle format, which is determined
by the IPickler adapter. Here we use Zope's xmlpickle.
>>> component.provideAdapter(pickle.XMLPickler)
>>> component.provideAdapter(pickle.XMLUnpickler)
For container like objects we must provide an adapter that maps the
container to a directory. In our example we use the buildin dict class:
>>> component.provideUtility(synchronizer.DirectorySynchronizer,
... interfaces.ISynchronizerFactory,
... name=synchronizer.dottedname(dict))
Now we can export the object to the snarf archive:
>>> checkout.perform(root, 'test')
>>> print snarf.stream.getvalue()
00000213 @@Zope/Entries.xml
<?xml version='1.0' encoding='utf-8'?>
<entries>
<entry name="test"
keytype="__builtin__.str"
type="__builtin__.dict"
factory="__builtin__.dict"
id="3"
/>
</entries>
00000339 test/@@Zope/Entries.xml
<?xml version='1.0' encoding='utf-8'?>
<entries>
<entry name="a"
keytype="__builtin__.str"
type="zope.fssync.doctest.A"
factory="zope.fssync.doctest.A"
id="1"
/>
<entry name="b"
keytype="__builtin__.str"
type="zope.fssync.doctest.B"
id="2"
/>
</entries>
00000009 test/a
data of a00000370 test/b
<?xml version="1.0" encoding="utf-8" ?>
<pickle>
<object>
<klass>
<global name="B" module="zope.fssync.doctest"/>
</klass>
<attributes>
<attribute name="data">
<string>data of b</string>
</attribute>
<attribute name="extra">
<string>extra of b</string>
</attribute>
</attributes>
</object>
</pickle>
<BLANKLINE>
After the registration of the necessary generators we can reimport the
serialized data from the repository:
>>> component.provideUtility(synchronizer.FileGenerator(),
... provides=interfaces.IFileGenerator)
>>> target = {}
>>> commit = task.Commit(synchronizer.getSynchronizer, snarf)
>>> commit.perform(target, 'root', 'test')
>>> sorted(target.keys())
['root']
>>> sorted(target['root'].keys())
['a', 'b']
>>> target['root']['a'].data
'data of a'
>>> target['root']['b'].extra
'extra of b'
If we want to commit the data back into the original place we must check
whether the repository is still consistent with the original content.
We modify the objects in place to see what happens:
>>> check = task.Check(synchronizer.getSynchronizer, snarf)
>>> check.check(root, '', 'test')
>>> check.errors()
[]
>>> root['a'].data = 'overwritten'
>>> root['b'].extra = 'overwritten'
>>> check = task.Check(synchronizer.getSynchronizer, snarf)
>>> check.check(root, '', 'test')
>>> check.errors()
['test/a', 'test/b']
>>> commit.perform(root, '', 'test')
>>> sorted(root.keys())
['a', 'b']
>>> root['a'].data
'data of a'
>>> root['b'].extra
'extra of b'
>>> del root['a']
>>> commit.perform(root, '', 'test')
>>> sorted(root.keys())
['a', 'b']
>>> del root['b']
>>> commit.perform(root, '', 'test')
>>> sorted(root.keys())
['a', 'b']
>>> del root['a']
>>> del root['b']
>>> commit.perform(root, '', 'test')
>>> sorted(root.keys())
['a', 'b']
Pickling
========
In many data structures, large, complex objects are composed of
smaller objects. These objects are typically stored in one of two
ways:
1. The smaller objects are stored inside the larger object.
2. The smaller objects are allocated in their own location,
and the larger object stores references to them.
In case 1 the object is self-contained and can be pickled
completely. This is the default behavior of the fssync pickler:
>>> pickler = interfaces.IPickler([42])
>>> pickler
<zope.fssync.pickle.XMLPickler object at ...>
>>> print pickler.dumps()
<?xml version="1.0" encoding="utf-8" ?>
<pickle>
<list>
<int>42</int>
</list>
</pickle>
<BLANKLINE>
Case 2 is more complex since the pickler has to take persistent
references into account.
>>> class Complex(object):
... def __init__(self, part1, part2):
... self.part1 = part1
... self.part2 = part2
Everthing here depends on the definition of what we consider to be an intrinsic
reference. In the examples above we simply considered all objects as intrinsic.
>>> from zope.fssync import pickle
>>> c = root['c'] = Complex(a, b)
>>> stream = StringIO()
>>> print interfaces.IPickler(c).dumps()
<?xml version="1.0" encoding="utf-8" ?>
<pickle>
<initialized_object>
<klass>
<global id="o0" name="_reconstructor" module="copy_reg"/>
</klass>
<arguments>
<tuple>
<global name="Complex" module="zope.fssync.doctest"/>
<global id="o1" name="object" module="__builtin__"/>
<none/>
</tuple>
</arguments>
<state>
<dictionary>
<item key="part1">
<object>
<klass>
<global name="A" module="zope.fssync.doctest"/>
</klass>
<attributes>
<attribute name="data">
<string>data of a</string>
</attribute>
</attributes>
</object>
</item>
<item key="part2">
<object>
<klass>
<global name="B" module="zope.fssync.doctest"/>
</klass>
<attributes>
<attribute name="data">
<string>data of b</string>
</attribute>
<attribute name="extra">
<string>overwritten</string>
</attribute>
</attributes>
</object>
</item>
</dictionary>
</state>
</initialized_object>
</pickle>
<BLANKLINE>
In order to use persistent references we must define a
PersistentIdGenerator for our pickler, which determines whether
an object should be pickled completely or only by reference:
>>> class PersistentIdGenerator(object):
... interface.implements(interfaces.IPersistentIdGenerator)
... component.adapts(interfaces.IPickler)
... def __init__(self, pickler):
... self.pickler = pickler
... def id(self, obj):
... if isinstance(obj, Complex):
... return None
... return globalIds.getId(obj)
>>> component.provideAdapter(PersistentIdGenerator)
>>> globalIds.register(a)
1
>>> globalIds.register(b)
2
>>> globalIds.register(root)
3
>>> xml = interfaces.IPickler(c).dumps()
>>> print xml
<?xml version="1.0" encoding="utf-8" ?>
<pickle>
<object>
<klass>
<global name="Complex" module="zope.fssync.doctest"/>
</klass>
<attributes>
<attribute name="part1">
<persistent> <string>1</string> </persistent>
</attribute>
<attribute name="part2">
<persistent> <string>2</string> </persistent>
</attribute>
</attributes>
</object>
</pickle>
<BLANKLINE>
The persistent ids can be loaded if we define and register
a IPersistentIdLoader adapter first:
>>> class PersistentIdLoader(object):
... interface.implements(interfaces.IPersistentIdLoader)
... component.adapts(interfaces.IUnpickler)
... def __init__(self, unpickler):
... self.unpickler = unpickler
... def load(self, id):
... global globalIds
... return globalIds.resolve(id)
>>> component.provideAdapter(PersistentIdLoader)
>>> c2 = interfaces.IUnpickler(None).loads(xml)
>>> c2.part1 == a
True
Annotations, Extras, and Metadata
=================================
Complex objects often combine metadata and content data in various ways.
The fssync package allows to distinguish between file content, extras,
annotations, and fssync specific metadata:
- The file content or body is directly stored in a corresponding
file.
- The extras are object attributes which are part of the object but not
part of the file content. They are typically store in extra files.
- Annotations are content related metadata which can be stored as
attribute annotations or outside the object itself. They are typically
stored in seperate pickles for each annotation namespace.
- Metadata directly related to fssync are stored in Entries.xml
files.
Where exactly these aspects are stored is defined in the
synchronization format. The default format uses a @@Zope directory with
subdirectories for object extras and annotations. These @@Zope directories
also contain an Entries.xml metadata file which defines the following
attributes:
- id: the system id of the object, in Zope typically a traversal path
- name: the filename of the serialized object
- factory: the factory of the object, typically a dotted name of a class
- type: a type identifier for pickled objects without factory
- provides: directly provided interfaces of the object
- key: the original name in the content space which is used
in cases where the repository is not able to store this key
unambigously
- binary: a flag that prevents merging of binary data
- flag: a status flag with the values 'added' or 'removed'
In part the metadata have to be delivered by the synchronizer. The base
synchronizer, for instance, returns the directly provided interfaces
of an object as part of it's metadata:
>>> class IMarkerInterface(interface.Interface):
... pass
>>> interface.directlyProvides(a, IMarkerInterface)
>>> pprint(synchronizer.Synchronizer(a).metadata())
{'factory': 'zope.fssync.doctest.A',
'provides': 'zope.fssync.doctest.IMarkerInterface'}
The setmetadata method can be used to write metadata
back to an object. Which metadata are consumed is up to the
synchronizer:
>>> metadata = {'provides': 'zope.fssync.doctest.IMarkerInterface'}
>>> synchronizer.Synchronizer(b).setmetadata(metadata)
>>> [x for x in interface.directlyProvidedBy(b)]
[<InterfaceClass zope.fssync.doctest.IMarkerInterface>]
In order to serialize annotations we must first provide a
ISynchronizableAnnotations adapter:
>>> snarf = repository.SnarfRepository(StringIO())
>>> checkout = task.Checkout(synchronizer.getSynchronizer, snarf)
>>> from zope import annotation
>>> from zope.annotation.attribute import AttributeAnnotations
>>> component.provideAdapter(AttributeAnnotations)
>>> class IAnnotatableSample(interface.Interface):
... pass
>>> class AnnotatableSample(object):
... interface.implements(IAnnotatableSample,
... annotation.interfaces.IAttributeAnnotatable)
... data = 'Main file content'
... extra = None
>>> sample = AnnotatableSample()
>>> class ITestAnnotations(interface.Interface):
... a = interface.Attribute('A')
... b = interface.Attribute('B')
>>> import persistent
>>> class TestAnnotations(persistent.Persistent):
... interface.implements(ITestAnnotations,
... annotation.interfaces.IAnnotations)
... component.adapts(IAnnotatableSample)
... def __init__(self):
... self.a = None
... self.b = None
>>> component.provideAdapter(synchronizer.SynchronizableAnnotations)
>>> from zope.annotation.factory import factory
>>> component.provideAdapter(factory(TestAnnotations))
>>> ITestAnnotations(sample).a = 'annotation a'
>>> ITestAnnotations(sample).a
'annotation a'
>>> sample.extra = 'extra'
Without a special serializer the annotations are pickled since
the annotations are stored in the __annotions__ attribute:
>>> root = dict()
>>> root['test'] = sample
>>> checkout.perform(root, 'test')
>>> print snarf.stream.getvalue()
00000197 @@Zope/Entries.xml
<?xml version='1.0' encoding='utf-8'?>
<entries>
<entry name="test"
keytype="__builtin__.str"
type="__builtin__.dict"
factory="__builtin__.dict"
/>
</entries>
00000182 test/@@Zope/Entries.xml
<?xml version='1.0' encoding='utf-8'?>
<entries>
<entry name="test"
keytype="__builtin__.str"
type="zope.fssync.doctest.AnnotatableSample"
/>
</entries>
00001929 test/test
<?xml version="1.0" encoding="utf-8" ?>
<pickle>
<object>
<klass>
<global name="AnnotatableSample" module="zope.fssync.doctest"/>
</klass>
...
</attributes>
</object>
</pickle>
<BLANKLINE>
If we provide a directory serializer for annotations and extras we get a
file for each extra attribute and annotation namespace.
>>> component.provideUtility(
... synchronizer.DirectorySynchronizer,
... interfaces.ISynchronizerFactory,
... name=synchronizer.dottedname(synchronizer.Extras))
>>> component.provideUtility(
... synchronizer.DirectorySynchronizer,
... interfaces.ISynchronizerFactory,
... name=synchronizer.dottedname(
... synchronizer.SynchronizableAnnotations))
Since the annotations are already handled by the Synchronizer base class
we only need to specify the extra attribute here:
>>> class SampleFileSynchronizer(synchronizer.Synchronizer):
... interface.implements(interfaces.IFileSynchronizer)
... def dump(self, writeable):
... writeable.write(self.context.data)
... def extras(self):
... return synchronizer.Extras(extra=self.context.extra)
... def load(self, readable):
... self.context.data = readable.read()
>>> component.provideUtility(SampleFileSynchronizer,
... interfaces.ISynchronizerFactory,
... name=synchronizer.dottedname(AnnotatableSample))
>>> interface.directlyProvides(sample, IMarkerInterface)
>>> root['test'] = sample
>>> checkout.perform(root, 'test')
>>> print snarf.stream.getvalue()
00000197 @@Zope/Entries.xml
<?xml version='1.0' encoding='utf-8'?>
<entries>
<entry name="test"
keytype="__builtin__.str"
type="__builtin__.dict"
factory="__builtin__.dict"
/>
</entries>
00000182 test/@@Zope/Entries.xml
<?xml version='1.0' encoding='utf-8'?>
<entries>
<entry name="test"
keytype="__builtin__.str"
type="zope.fssync.doctest.AnnotatableSample"
/>
</entries>
00001929 test/test
<?xml version="1.0" encoding="utf-8" ?>
<pickle>
<object>
<klass>
<global name="AnnotatableSample" module="zope.fssync.doctest"/>
</klass>
<attributes>
<attribute name="__annotations__">
...
</attribute>
<attribute name="extra">
<string>extra</string>
</attribute>
</attributes>
</object>
</pickle>
00000197 @@Zope/Entries.xml
<?xml version='1.0' encoding='utf-8'?>
<entries>
<entry name="test"
keytype="__builtin__.str"
type="__builtin__.dict"
factory="__builtin__.dict"
/>
</entries>
00000296 test/@@Zope/Entries.xml
<?xml version='1.0' encoding='utf-8'?>
<entries>
<entry name="test"
keytype="__builtin__.str"
type="zope.fssync.doctest.AnnotatableSample"
factory="zope.fssync.doctest.AnnotatableSample"
provides="zope.fssync.doctest.IMarkerInterface"
/>
</entries>
00000211 test/@@Zope/Annotations/test/@@Zope/Entries.xml
<?xml version='1.0' encoding='utf-8'?>
<entries>
<entry name="zope.fssync.doctest.TestAnnotations"
keytype="__builtin__.str"
type="zope.fssync.doctest.TestAnnotations"
/>
</entries>
00000617 test/@@Zope/Annotations/test/zope.fssync.doctest.TestAnnotations
<?xml version="1.0" encoding="utf-8" ?>
<pickle>
...
</pickle>
00000161 test/@@Zope/Extra/test/@@Zope/Entries.xml
<?xml version='1.0' encoding='utf-8'?>
<entries>
<entry name="extra"
keytype="__builtin__.str"
type="__builtin__.str"
/>
</entries>
00000082 test/@@Zope/Extra/test/extra
<?xml version="1.0" encoding="utf-8" ?>
<pickle> <string>extra</string> </pickle>
00000017 test/test
Main file content
The annotations and extras can of course also be deserialized. The default
deserializer handles both cases:
>>> target = {}
>>> commit = task.Commit(synchronizer.getSynchronizer, snarf)
>>> commit.perform(target, 'root', 'test')
>>> result = target['root']['test']
>>> result.extra
'extra'
>>> ITestAnnotations(result).a
'annotation a'
Since we use an IDirectorySynchronizer each extra attribute and
annotation namespace get's it's own file:
>>> for path in sorted(snarf.iterPaths()):
... print path
@@Zope/Entries.xml
test/@@Zope/Annotations/test/@@Zope/Entries.xml
test/@@Zope/Annotations/test/zope.fssync.doctest.TestAnnotations
test/@@Zope/Entries.xml
test/@@Zope/Extra/test/@@Zope/Entries.xml
test/@@Zope/Extra/test/extra
test/test
The number of files can be reduced if we provide the default synchronizer
which uses a single file for all annotations and a single file for
all extras:
>>> component.provideUtility(
... synchronizer.DefaultSynchronizer,
... interfaces.ISynchronizerFactory,
... name=synchronizer.dottedname(synchronizer.Extras))
>>> component.provideUtility(
... synchronizer.DefaultSynchronizer,
... interfaces.ISynchronizerFactory,
... name=synchronizer.dottedname(
... synchronizer.SynchronizableAnnotations))
>>> root['test'] = sample
>>> snarf = repository.SnarfRepository(StringIO())
>>> checkout.repository = snarf
>>> checkout.perform(root, 'test')
>>> for path in sorted(snarf.iterPaths()):
... print path
@@Zope/Entries.xml
test/@@Zope/Annotations/test
test/@@Zope/Entries.xml
test/@@Zope/Extra/test
test/test
The annotations and extras can of course also be deserialized. The default
deserializer handles both
>>> target = {}
>>> commit = task.Commit(synchronizer.getSynchronizer, snarf)
>>> commit.perform(target, 'root', 'test')
>>> result = target['root']['test']
>>> result.extra
'extra'
>>> ITestAnnotations(result).a
'annotation a'
>>> [x for x in interface.directlyProvidedBy(result)]
[<InterfaceClass zope.fssync.doctest.IMarkerInterface>]
If we encounter an error, or multiple errors, while commiting we'll
see them in the traceback.
>>> def bad_sync(container, key, fspath, add_callback):
... raise ValueError('1','2','3')
>>> target = {}
>>> commit = task.Commit(synchronizer.getSynchronizer, snarf)
>>> old_sync_new = commit.synchNew
>>> commit.synchNew = bad_sync
>>> commit.perform(target, 'root', 'test')
Traceback (most recent call last):
...
Exception: test: '1', '2', '3'
Notice that if we encounter multiple exceptions we print them all
out at the end.
>>> old_sync_old = commit.synchOld
>>> commit.synchOld = bad_sync
>>> commit.perform(target, 'root', 'test')
Traceback (most recent call last):
...
Exceptions:
test: '1', '2', '3'
test: '1', '2', '3'
>>> commit.synchNew = old_sync_new
>>> commit.synchOld = old_sync_old
| zope.fssync | /zope.fssync-3.6.1.zip/zope.fssync-3.6.1/src/zope/fssync/README.txt | README.txt |
import os
import copy
from cStringIO import StringIO
from os.path import exists, isfile, split, join, realpath, normcase
from xml.sax import ContentHandler, parseString
from xml.sax.saxutils import quoteattr
import fsutil
case_insensitive = (normcase("ABC") == normcase("abc"))
class Metadata(object):
def __init__(self):
"""Constructor."""
self.cache = {} # Keyed by normcase(dirname(realpath(file)))
self.originals = {} # Original copy as read from file
def getnames(self, dir):
"""Return the names of known non-empty metadata entries, sorted."""
entries = self.getmanager(dir).entries
names = [name for name, entry in entries.iteritems() if entry]
names.sort()
return names
def getentry(self, file):
"""Return the metadata entry for a given file (or directory).
Modifying the dict that is returned will cause the changes to
the metadata to be written out when flush() is called. If
there is no metadata entry for the file, return a new empty
dict, modifications to which will also be flushed.
"""
file = realpath(file)
dir, base = split(file)
return self.getmanager(dir).getentry(base)
def gettypeinfo(self, path):
entry = self.getentry(path)
return entry.get("type"), entry.get("factory")
def getmanager(self, dir):
dir = realpath(dir)
key = normcase(dir)
if key not in self.cache:
self.cache[key] = DirectoryManager(dir)
return self.cache[key]
def flush(self):
errors = []
for dirinfo in self.cache.itervalues():
try:
dirinfo.flush()
except (IOError, OSError), err:
errors.append(err)
if errors:
if len(errors) == 1:
raise
else:
raise IOError(tuple(errors))
def added(self):
"""Adds an 'added' flag to all metadata entries."""
for dirinfo in self.cache.itervalues():
for entry in dirinfo.entries.itervalues():
entry["flag"] = "added"
class DirectoryManager(object):
def __init__(self, dir):
self.zdir = join(dir, "@@Zope")
self.efile = join(self.zdir, "Entries.xml")
if isfile(self.efile):
self.entries = load_entries_path(self.efile)
else:
self.entries = {}
self.originals = copy.deepcopy(self.entries)
def ensure(self):
"""Dump the entries even if there's an empty set."""
self._dump(self._get_live())
def flush(self):
"""Dump the entries if different from the set stored on disk."""
live = self._get_live()
if live != self.originals:
if exists(self.efile) or live:
self._dump(live)
self.originals = copy.deepcopy(live)
def _get_live(self):
"""Retrieve the set of all 'live' entries."""
live = {}
for name, entry in self.entries.iteritems():
if entry:
live[name] = entry
return live
def _dump(self, live):
"""Write entries to disk."""
data = dump_entries(live)
if not exists(self.zdir):
os.makedirs(self.zdir)
f = open(self.efile, "wb")
try:
f.write(data)
finally:
f.close()
def getentry(self, name):
"""Return a single named entry.
If there's no matching entry, an empty entry is created.
"""
name = fsutil.encode(name)
if name in self.entries:
return self.entries[name]
if case_insensitive:
# Look for a case-insensitive match -- expensive!
# TODO: There's no test case for this code!
nbase = normcase(name)
matches = [b for b in self.entries if normcase(b) == nbase]
if matches:
if len(matches) > 1:
raise KeyError("multiple entries match %r" % nbase)
return self.entries[matches[0]]
# Create a new entry
self.entries[name] = entry = {}
return entry
def dump_entries(entries):
sio = StringIO()
sio.write("<?xml version='1.0' encoding='utf-8'?>\n")
sio.write("<entries>\n")
names = entries.keys()
names.sort()
for name in names:
entry = entries[name]
name = fsutil.encode(name, 'utf-8')
sio.write(" <entry name=")
sio.write(quoteattr(name))
for k, v in entry.iteritems():
if v is None:
continue
k = fsutil.encode(k, 'utf-8')
v = fsutil.encode(v, 'utf-8')
sio.write("\n %s=%s" % (k, quoteattr(v)))
sio.write("\n />\n")
sio.write("</entries>\n")
return sio.getvalue()
def load_entries(text):
ch = EntriesHandler()
try:
parseString(text, ch)
except FoundXMLPickle:
from zope.xmlpickle import loads
return loads(text)
else:
return ch.entries
def load_entries_path(path):
f = open(path, 'rb')
try:
return load_entries(f.read())
finally:
f.close()
class EntriesHandler(ContentHandler):
def __init__(self):
self.first = True
self.stack = []
self.entries = {}
def startElement(self, name, attrs):
if self.first:
if name == "pickle":
raise FoundXMLPickle()
elif name != "entries":
raise InvalidEntriesFile()
else:
self.first = False
if name == "entry":
if self.stack[-1] != "entries":
raise InvalidEntriesFile("illegal element nesting")
else:
entryname = attrs.getValue("name")
entryname = fsutil.encode(entryname)
entry = {}
for n in attrs.getNames():
if n != "name":
entry[n] = attrs.getValue(n)
self.entries[entryname] = entry
elif name == "entries":
if self.stack:
raise InvalidEntriesFile(
"<entries> must be the document element")
else:
raise InvalidEntriesFile("unknown element <%s>" % name)
self.stack.append(name)
def endElement(self, name):
old = self.stack.pop()
assert name == old, "%r != %r" % (name, old)
def characters(self, data):
if data.strip():
raise InvalidEntriesFile(
"arbitrary character data not supported: %r" % data.strip())
class FoundXMLPickle(Exception):
"""Raised by EntriesHandler when the document appears to be an XML
pickle."""
class InvalidEntriesFile(Exception):
"""Raised by EntriesHandler when the document has an unsupposed
document element.""" | zope.fssync | /zope.fssync-3.6.1.zip/zope.fssync-3.6.1/src/zope/fssync/metadata.py | metadata.py |
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Interfaces for filesystem synchronization.
$Id: interfaces.py 73003 2007-03-06 10:34:19Z oestermeier $
"""
from zope import interface
from zope import component
from zope import annotation
from zope import lifecycleevent
from zope.dottedname.resolve import resolve
from zope.filerepresentation.interfaces import IFileFactory
from zope.filerepresentation.interfaces import IDirectoryFactory
import interfaces
def dottedname(klass):
return "%s.%s" % (klass.__module__, klass.__name__)
class MissingSynchronizer(Exception):
pass
class Extras(dict):
"""A serializable mapping of object attributes."""
interface.implements(interfaces.ISynchronizableExtras)
class SynchronizableAnnotations(dict):
"""A serializable mapping of annotations."""
interface.implements(interfaces.ISynchronizableAnnotations)
component.adapts(annotation.interfaces.IAnnotations)
def modify(self, target):
"""Transfers the namespaces to the target annotations.
Returns a lifecycleevent.interfaces.ISequence modification
descriptor or None if nothing changed.
"""
target.update(self)
modified = []
for key, value in self.items():
old = interfaces.IPickler(target.get(key)).dumps()
target[key] = value
if old != interfaces.IPickler(value).dumps():
modified.append(key)
if modified:
return lifecycleevent.Sequence(
annotation.interfaces.IAnnotations,
modified)
return None
class Synchronizer(object):
"""A convenient base class for serializers."""
interface.implements(interfaces.ISynchronizer)
def __init__(self, context):
self.context = context
def getObject(self):
return self.context
def metadata(self):
"""Returns a mapping for the metadata entries."""
result = dict(factory=dottedname(self.context.__class__))
ifaces = interface.directlyProvidedBy(self.context)
if ifaces:
result['provides'] = ' '.join([dottedname(i) for i in ifaces])
return result
def setmetadata(self, metadata):
"""Loads metadata from a dict.
Specializations should return an IModificationDescription
if a ModifiedEvent should be thrown.
"""
provides = metadata.get('provides')
if provides:
for dottedname in provides.split():
iface = resolve(dottedname)
interface.alsoProvides(self.context, iface)
return None
def extras(self):
return None
def annotations(self):
ann = annotation.interfaces.IAnnotations(self.context, None)
if ann is not None:
return interfaces.ISynchronizableAnnotations(ann, None)
def setannotations(self, annotations):
"""Consumes de-serialized annotations."""
ann = annotation.interfaces.IAnnotations(self.context, None)
if ann is not None:
sann = interfaces.ISynchronizableAnnotations(annotations, None)
if sann is not None:
return sann.modify(ann)
def setextras(self, extras):
"""Consumes de-serialized extra attributes.
Returns an unspecific IModificationDescription.
Application specific adapters may provide more informative
descriptors.
"""
modified = []
for key, value in extras.iteritems():
if hasattr(self.context, key):
if getattr(self.context, key) != value:
modified.append(key)
setattr(self.context, key, value)
if modified:
return lifecycleevent.Attributes(None, modified)
return None
class FileSynchronizer(Synchronizer):
"""A convenient base class for file serializers."""
interface.implements(interfaces.IFileSynchronizer)
def dump(self, writeable):
pass
def load(self, readable):
pass
class DefaultSynchronizer(FileSynchronizer):
"""A synchronizer that stores an object as an xml pickle."""
interface.implements(interfaces.IDefaultSynchronizer)
def __init__(self, context):
self.context = context
def metadata(self):
"""Returns None.
A missing factory indicates that the object has
has to be unpickled.
"""
return None
def extras(self):
"""Returns None.
A pickle is self contained."""
return None
def annotations(self):
"""Returns None.
The annotations are already stored in the pickle.
This is only the right thing if the annotations are
stored in the object's attributes (such as IAttributeAnnotatable);
if that's not the case, then either this method needs to be
overridden or this class shouldn't be used."""
return None
def dump(self, writeable):
"""Dumps the xml pickle."""
interfaces.IPickler(self.context).dump(writeable)
def load(self, readable):
raise NotImplementedError
class DirectorySynchronizer(Synchronizer):
"""A serializer that stores objects as directory-like objects.
"""
interface.implements(interfaces.IDirectorySynchronizer)
def __getitem__(self, name):
"""Traverses the name in the given context.
"""
return self.context[name]
def iteritems(self):
return self.context.items()
def update(self, items):
"""Updates the context."""
self.context.update(items)
def __setitem__(self, name, obj):
"""Sets the item."""
self.context[name] = obj
def __delitem__(self, name):
"""Deletes ths item."""
del self.context[name]
class FileGenerator(object):
"""A generator that creates file-like objects
from a serialized representation.
Should be registered as the IFileGenerator utility
and be used if no other class-based serializer can be found.
"""
interface.implements(interfaces.IFileGenerator)
def create(self, location, name, extension):
"""Creates a file.
This implementation uses the registered zope.filerepresentation adapters.
"""
factory = component.queryAdapter(location, IFileFactory, extension)
if factory is None:
factory = IFileFactory(location, None)
if factory is not None:
return factory(name, None, '')
def load(self, obj, readable):
obj.data = readable.read()
class DirectoryGenerator(object):
"""A generator that creates a directory-like object
from a serialized representation.
Should be registered as the IDirectoryGenerator utility
and be used if no other class-based serializer can be found.
"""
interface.implements(interfaces.IDirectoryGenerator)
def create(self, location, name):
"""Creates a directory like object.
This implementation uses the registered zope.filerepresentation adapters.
"""
factory = component.queryAdapter(location, IDirectoryFactory)
if factory is None:
factory = IDirectoryFactory(location, None)
if factory is not None:
return factory(name)
def getSynchronizer(obj, raise_error=False):
"""Looks up a synchronizer.
Sometimes no serializer might be defined or sometimes access
to a serializer may be forbidden. We return None in those cases.
Those cases may be unexpected and it may be a problem that
the data are not completely serialized. If raise_error is True
we raise a MissingSynchronizer in those cases.
"""
dn = dottedname(obj.__class__)
factory = component.queryUtility(interfaces.ISynchronizerFactory, name=dn)
if factory is None:
factory = component.queryUtility(interfaces.ISynchronizerFactory)
if factory is None:
if raise_error:
raise MissingSynchronizer(dn)
return None
return factory(obj) | zope.fssync | /zope.fssync-3.6.1.zip/zope.fssync-3.6.1/src/zope/fssync/synchronizer.py | synchronizer.py |
import os
import zope.interface
import zope.component
import zope.traversing.api
import zope.event
import zope.lifecycleevent
import zope.dottedname.resolve
import metadata
import interfaces
import synchronizer
import fsutil
from synchronizer import dottedname
class SynchronizationError(Exception):
pass
@zope.component.adapter(zope.interface.Interface)
@zope.interface.implementer(interfaces.IEntryId)
def EntryId(obj):
try:
path = zope.traversing.api.getPath(obj)
return path.encode('utf-8')
except (TypeError, KeyError, AttributeError):
# this case can be triggered for persistent objects that don't
# have a name in the content space (annotations, extras)
return None
class ObjectSynchronized(object):
"""A default modification description for synchronized objects."""
zope.interface.implements(interfaces.IObjectSynchronized)
class SyncTask(object):
"""Convenient base class for synchronization tasks."""
def __init__(self, getSynchronizer,
repository,
context=None):
self.getSynchronizer = getSynchronizer
self.repository = repository
self.context = context
class Checkout(SyncTask):
"""Checkout of a content space into a repository."""
zope.interface.implements(interfaces.ICheckout)
def perform(self, ob, name, location=''):
"""Check an object out.
ob -- The object to be checked out
name -- The name of the object
location -- The directory or path where the object will go
"""
root = dict()
self.context = root[name] = ob
self.dump(synchronizer.DirectorySynchronizer(root), location)
def serializableItems(self, items, dirpath):
"""Returns items which have synchronizer.
Returns a tuple of disambiguated name, original key, and synchronizer.
"""
result = []
repository = self.repository
if items is not None:
for key, value in items:
synchronizer = self.getSynchronizer(value, raise_error=False)
if synchronizer is not None:
name = repository.disambiguate(dirpath, key)
result.append((name, key, synchronizer))
return sorted(result)
def dump(self, synchronizer, path):
if synchronizer is None:
return
if interfaces.IDirectorySynchronizer.providedBy(synchronizer):
items = self.serializableItems(synchronizer.iteritems(), path)
self.dumpSpecials(path, items)
for name, key, s in items: # recurse down the tree
self.dump(s, self.repository.join(path, name))
elif interfaces.IFileSynchronizer.providedBy(synchronizer):
fp = self.repository.writeable(path)
synchronizer.dump(fp)
fp.close()
else:
raise SynchronizationError("invalid synchronizer")
def dumpMetadata(self, epath, entries):
xml = metadata.dump_entries(entries)
fp = self.repository.writeable(epath)
fp.write(xml)
fp.close()
def dumpSpecials(self, path, items):
entries = {}
repository = self.repository
zdir = repository.join(path, '@@Zope')
epath = repository.join(zdir, 'Entries.xml')
for name, key, s in items:
obj = s.getObject()
entry = dict(type=typeIdentifier(obj))
metadata = s.metadata()
if metadata:
for k, v in metadata.items():
if v:
entry[k] = v
objid = getEntryId(obj)
if objid:
entry['id'] = str(objid)
if key != name:
entry['key'] = key
entry['keytype'] = dottedname(key.__class__)
entries[name] = entry
if path:
self.dumpMetadata(epath, entries)
adir = repository.join(zdir, 'Annotations')
for name, key, s in items:
dir = repository.join(adir, name)
annotations = s.annotations()
if annotations:
synchronizer = self.getSynchronizer(annotations)
if synchronizer is not None:
self.dump(synchronizer, dir)
edir = repository.join(zdir, 'Extra')
for name, key, s in items:
dir = repository.join(edir, name)
extras = s.extras()
if extras:
synchronizer = self.getSynchronizer(extras)
if synchronizer is not None:
self.dump(synchronizer, dir)
if not path:
self.dumpMetadata(epath, entries)
class Exceptions(Exception):
# We use this to pluralize "Exception".
pass
class Commit(SyncTask):
"""Commit changes from a repository to the object database.
The repository's originals must be consistent with the object
database; this should be checked beforehand by a `Check` instance
with the same arguments.
"""
zope.interface.implements(interfaces.ICommit)
debug = False
def __init__(self, getSynchronizer, repository):
super(Commit, self).__init__(getSynchronizer, repository)
self.metadata = self.repository.getMetadata()
self.errors = []
def perform(self, container, name, fspath):
callbacks = []
add_callback = callbacks.append
self.synchronize(container, name, fspath, add_callback)
# check for errors
if self.errors:
if len(self.errors) == 1:
raise Exception(self.errors[0])
else:
raise Exceptions("\n ".join([""] + self.errors))
# process callbacks
passes = 0
callbacks = [cb for cb in callbacks if cb is not None]
while passes < 10 and callbacks:
new_callbacks = []
for callback in callbacks:
new_callbacks.append(callback())
callbacks = [cb for cb in new_callbacks if cb is not None]
passes += 1
# fail if there are still callbacks after 10 passes. this
# suggests an infinate loop in callback creation.
if callbacks:
raise SynchronizationError(
'Too many synchronizer callback passes %s' % callbacks)
def synchronize(self, container, name, fspath, add_callback):
"""Synchronize an object or object tree from a repository.
``SynchronizationError`` is raised for errors that can't be
corrected by a update operation, including invalid object
names.
"""
self.context = container
modifications = []
if invalidName(name):
raise SynchronizationError("invalid separator in name %r" % name)
if not name:
self.synchDirectory(container, fspath, add_callback)
else:
synchronizer = self.getSynchronizer(container)
key = originalKey(fspath, name, self.metadata)
try:
traverseKey(container, key)
except:
try:
self.synchNew(container, key, fspath, add_callback)
except Exception, e:
self.errors.append('%s: %s' % (
fspath, ', '.join(repr(x) for x in e.args)))
return
else:
try:
modified = self.synchOld(container, key, fspath,
add_callback)
except Exception, e:
self.errors.append('%s: %s' % (
fspath, ', '.join(repr(x) for x in e.args)))
return
if modified:
modifications.append(modified)
# Now update extra and annotations
try:
obj = traverseKey(container, key)
except:
pass
else:
metadata = self.metadata.getentry(fspath)
synchronizer = self.getSynchronizer(obj)
modified = synchronizer.setmetadata(metadata)
if modified:
modifications.append(modified)
extrapath = fsutil.getextra(fspath)
if self.repository.exists(extrapath):
extras = synchronizer.extras()
extras = self.synchSpecials(extrapath, extras, add_callback)
modified = synchronizer.setextras(extras)
if modified:
modifications.append(modified)
annpath = fsutil.getannotations(fspath)
if self.repository.exists(annpath):
annotations = synchronizer.annotations()
annotations = self.synchSpecials(annpath, annotations,
add_callback)
modified = synchronizer.setannotations(annotations)
if modified:
modifications.append(modified)
if modifications:
zope.event.notify(
zope.lifecycleevent.ObjectModifiedEvent(
obj,
*modifications))
def synchSpecials(self, fspath, specials, add_callback):
"""Synchronize an extra or annotation mapping."""
md = self.metadata.getmanager(fspath)
entries = md.entries
synchronizer = self.getSynchronizer(specials)
if interfaces.IDirectorySynchronizer.providedBy(synchronizer):
for name, entry in entries.items():
path = self.repository.join(fspath, name)
self.synchronize(specials, name, path, add_callback)
else:
if interfaces.IDefaultSynchronizer.providedBy(synchronizer):
fp = self.repository.readable(fspath)
unpickler = interfaces.IUnpickler(self.context)
specials = unpickler.load(fp)
fp.close()
elif interfaces.IFileSynchronizer.providedBy(synchronizer):
fp = self.repository.readable(fspath)
add_callback(synchronizer.load(fp))
fp.close()
return specials
def synchDirectory(self, container, fspath, add_callback):
"""Helper to synchronize a directory."""
adapter = self.getSynchronizer(container)
nameset = {}
if interfaces.IDirectorySynchronizer.providedBy(adapter):
for key, obj in adapter.iteritems():
nameset[key] = self.repository.join(fspath, key)
else:
# Annotations, Extra
for key in container:
nameset[key] = self.repository.join(fspath, key)
for name in self.metadata.getnames(fspath):
nameset[name] = self.repository.join(fspath, name)
# Sort the list of keys for repeatability
names_paths = nameset.items()
names_paths.sort()
subdirs = []
# Do the non-directories first.
# This ensures that the objects are created before dealing
# with Annotations/Extra for those objects.
for name, path in names_paths:
if self.repository.isdir(path):
subdirs.append((name, path))
else:
self.synchronize(container, name, path, add_callback)
# Now do the directories
for name, path in subdirs:
self.synchronize(container, name, path, add_callback)
def synchNew(self, container, name, fspath, add_callback):
"""Helper to synchronize a new object."""
entry = self.metadata.getentry(fspath)
if entry:
# In rare cases (e.g. if the original name and replicated name
# differ and the replica has been deleted) we can get
# something apparently new that is marked for deletion. Since the
# names are provided by the synchronizer we must at least
# inform the synchronizer.
if entry.get("flag") == "removed":
self.deleteItem(container, name)
return
obj = self.createObject(container, name, entry, fspath,
add_callback)
synchronizer = self.getSynchronizer(obj)
if interfaces.IDirectorySynchronizer.providedBy(synchronizer):
self.synchDirectory(obj, fspath, add_callback)
def synchOld(self, container, name, fspath, add_callback):
"""Helper to synchronize an existing object."""
modification = None
entry = self.metadata.getentry(fspath)
if entry.get("flag") == "removed":
self.deleteItem(container, name)
return
if not entry:
# This object was not included on the filesystem; skip it
return
key = originalKey(fspath, name, self.metadata)
obj = traverseKey(container, key)
synchronizer = self.getSynchronizer(obj)
if interfaces.IDirectorySynchronizer.providedBy(synchronizer):
self.synchDirectory(obj, fspath, add_callback)
else:
type = entry.get("type")
if type and typeIdentifier(obj) != type:
self.createObject(container, key, entry, fspath, add_callback,
replace=True)
else:
original_fn = fsutil.getoriginal(fspath)
if self.repository.exists(original_fn):
original = self.repository.readable(original_fn)
replica = self.repository.readable(fspath)
new = not self.repository.compare(original, replica)
else:
# value appears to exist in the object tree, but
# may have been created as a side effect of an
# addition in the parent; this can easily happen
# in the extra or annotation data for an object
# copied from another using "zsync copy" (for
# example)
new = True
if new:
if not entry.get("factory"):
# If there's no factory, we can't call load
self.createObject(container, key, entry, fspath,
add_callback, True)
obj = traverseKey(container, key)
modification = ObjectSynchronized()
else:
fp = self.repository.readable(fspath)
modified = not compare(fp, synchronizer)
if modified:
fp.seek(0)
add_callback(synchronizer.load(fp))
modification = ObjectSynchronized()
fp.close()
return modification
def createObject(self, container, name, entry, fspath, add_callback,
replace=False):
"""Helper to create a deserialized object."""
factory_name = entry.get("factory")
type = entry.get("type")
isdir = self.repository.isdir(fspath)
added = False
if factory_name:
generator = zope.component.queryUtility(interfaces.IObjectGenerator,
name=factory_name)
if generator is not None:
obj = generator.create(container, name)
added = True
else:
try:
obj = resolveDottedname(factory_name)()
except TypeError:
raise fsutil.Error("Don't know how to create %s" % factory_name)
synchronizer = self.getSynchronizer(obj)
if interfaces.IDefaultSynchronizer.providedBy(synchronizer):
fp = self.repository.readable(fspath)
unpickler = interfaces.IUnpickler(self.context)
obj = unpickler.load(fp)
fp.close()
elif interfaces.IFileSynchronizer.providedBy(synchronizer):
fp = self.repository.readable(fspath)
add_callback(synchronizer.load(fp))
fp.close()
elif type:
fp = self.repository.readable(fspath)
unpickler = interfaces.IUnpickler(self.context)
obj = unpickler.load(fp)
else:
if isdir:
generator = zope.component.queryUtility(
interfaces.IDirectoryGenerator)
else:
generator = zope.component.queryUtility(
interfaces.IFileGenerator)
isuffix = name.rfind(".")
if isuffix >= 0:
suffix = name[isuffix:]
else:
suffix = "."
if generator is None:
msg = "Don't know how to create object for %s"
raise fsutil.Error(msg % fspath)
if isdir:
obj = generator.create(container, name)
else:
obj = generator.create(container, name, suffix)
fp = self.repository.readable(fspath)
if obj is None:
pickler = interfaces.IUnpickler(self.context)
obj = pickler.load(fp)
else:
add_callback(generator.load(obj, fp))
fp.close()
if not added:
self.setItem(container, name, obj, replace)
return obj
def setItem(self, container, key, obj, replace=False):
"""Helper to set an item in a container.
Uses the synchronizer for the container if a synchronizer is available.
"""
dir = self.getSynchronizer(container)
if interfaces.IDirectorySynchronizer.providedBy(dir):
if not replace:
zope.event.notify(zope.lifecycleevent.ObjectCreatedEvent(obj))
if replace:
del dir[key]
dir[key] = obj
else:
container[key] = obj
def deleteItem(self, container, key):
"""Helper to delete an item from a container.
Uses the synchronizer if possible.
"""
dir = self.getSynchronizer(container)
if interfaces.IDirectorySynchronizer.providedBy(dir):
del dir[key]
else:
del container[key]
class Checkin(Commit):
zope.interface.implements(interfaces.ICheckin)
def perform(self, container, name, fspath):
"""Checkin a new object tree.
Raises a ``SynchronizationError`` if the name already exists
in the object database.
"""
callbacks = []
add_callback = callbacks.append
self.context = container # use container as context of reference
self.metadata.added()
try:
traverseKey(container, name)
except:
self.synchronize(container, name, fspath, add_callback)
else:
raise SynchronizationError("object already exists %r" % name)
# check for errors
if self.errors:
if len(self.errors) == 1:
raise Exception(self.errors[0])
else:
raise Exceptions("\n ".join([""] + self.errors))
# process callbacks
passes = 0
callbacks = [cb for cb in callbacks if cb is not None]
while passes < 10 and callbacks:
new_callbacks = []
for callback in callbacks:
new_callbacks.append(callback())
callbacks = [cb for cb in new_callbacks if cb is not None]
passes += 1
# fail if there are still callbacks after 10 passes. this
# suggests an infinate loop in callback creation.
if callbacks:
raise SynchronizationError(
'Too many synchronizer callback passes %s' % callbacks)
class Check(SyncTask):
"""Check that a repository is consistent with the object database.
"""
zope.interface.implements(interfaces.ICheck)
def __init__(self, getSynchronizer, repository,
raise_on_conflicts=False):
super(Check, self).__init__(getSynchronizer, repository)
self.metadata = repository.getMetadata()
self.conflicts = []
self.raise_on_conflicts = raise_on_conflicts
def errors(self):
"""Return a list of errors (conflicts).
The return value is a list of filesystem pathnames for which
a conflict exists. A conflict usually refers to a file that
was modified on the filesystem while the corresponding object
was also modified in the database. Other forms of conflicts
are possible, e.g. a file added while an object was added in
the corresponding place, or inconsistent labeling of the
filesystem objects (e.g. an existing file marked as removed,
or a non-existing file marked as added).
"""
return self.conflicts
def conflict(self, fspath):
"""Helper to report a conflict.
Conflicts can be retrieved by calling `errors()`.
"""
if self.raise_on_conflicts:
raise SynchronizationError(fspath)
if fspath not in self.conflicts:
self.conflicts.append(fspath)
def check(self, container, name, fspath):
"""Compare an object or object tree from the filesystem.
If the originals on the filesystem are not uptodate, errors
are reported by calling `conflict()`.
Invalid object names are reported by raising
``SynchronizationError``.
"""
self.context = container
if invalidName(name):
raise SynchronizationError("invalid separator in name %r" % name)
if not name:
self.checkDirectory(container, fspath)
else:
key = originalKey(fspath, name, self.metadata)
try:
traverseKey(container, key)
except:
self.checkNew(fspath)
else:
self.checkOld(container, key, fspath)
# Now check extra and annotations
try:
obj = traverseKey(container, key)
except:
pass
else:
adapter = self.getSynchronizer(obj)
extras = adapter.extras()
extrapath = fsutil.getextra(fspath)
if extras and self.repository.exists(extrapath):
self.checkSpecials(extras, extrapath)
annotations = adapter.annotations()
annpath = fsutil.getannotations(fspath)
if annotations and self.repository.exists(annpath):
self.checkSpecials(annotations, annpath)
def checkSpecials(self, container, fspath):
"""Helper to check a directory."""
nameset = {}
for key in container:
nameset[key] = 1
for name in self.metadata.getnames(fspath):
nameset[name] = 1
# Sort the list of keys for repeatability
names = nameset.keys()
names.sort()
for name in names:
self.check(container, name, self.repository.join(fspath, name))
def checkDirectory(self, container, fspath):
"""Helper to check a directory."""
adapter = self.getSynchronizer(container)
nameset = {}
if interfaces.IDirectorySynchronizer.providedBy(adapter):
for key, obj in adapter.iteritems():
nameset[key] = 1
else:
for key in container:
nameset[key] = 1
for name in self.metadata.getnames(fspath):
nameset[name] = 1
# Sort the list of keys for repeatability
names = nameset.keys()
names.sort()
for name in names:
self.check(container, name, self.repository.join(fspath, name))
def checkNew(self, fspath):
"""Helper to check a new object."""
entry = self.metadata.getentry(fspath)
if entry:
if entry.get("flag") != "added":
self.conflict(fspath)
else:
if not self.repository.exists(fspath):
self.conflict(fspath)
if self.repository.isdir(fspath):
# Recursively check registered contents
for name in self.metadata.getnames(fspath):
self.checkNew(self.repository.join(fspath, name))
def checkOld(self, container, name, fspath):
"""Helper to check an existing object."""
entry = self.metadata.getentry(fspath)
if not entry:
self.conflict(fspath)
if "conflict" in entry:
self.conflict(fspath)
flag = entry.get("flag")
if flag == "removed":
if self.repository.exists(fspath):
self.conflict(fspath)
else:
if not self.repository.exists(fspath):
self.conflict(fspath)
key = originalKey(fspath, name, self.metadata)
obj = traverseKey(container, key)
adapter = self.getSynchronizer(obj)
if interfaces.IDirectorySynchronizer.providedBy(adapter):
if flag != "removed" or self.repository.exists(fspath):
self.checkDirectory(obj, fspath)
else:
if flag == "added":
self.conflict(fspath)
oldfspath = fsutil.getoriginal(fspath)
if self.repository.exists(oldfspath):
cmppath = oldfspath
else:
cmppath = fspath
fp = self.repository.readable(cmppath)
if not compare(fp, adapter):
self.conflict(fspath)
fp.close()
def getEntryId(obj):
"""Shortcut for adapter lookup."""
return zope.component.queryAdapter(obj, interfaces.IEntryId)
def invalidName(name):
return (os.sep in name or
(os.altsep and os.altsep in name) or
name == "." or
name == ".." or
"/" in name)
def traverseKey(container, key):
return container[key]
def typeIdentifier(obj):
return synchronizer.dottedname(obj.__class__)
def originalKey(fspath, name, metadata):
"""Reconstructs the original key from the metadata database."""
entry = metadata.getentry(fspath)
keytype = entry.get('keytype')
key = entry.get('key', name)
if keytype:
keytype = resolveDottedname(keytype)
if keytype == key.__class__:
return key
if keytype == unicode:
return unicode(name, encoding='utf-8')
return keytype(name)
return name
def resolveDottedname(dottedname):
factory = zope.dottedname.resolve.resolve(dottedname)
if factory == eval:
raise TypeError('invalid factory type')
return factory
def compare(readable, dumper):
"""Help function for the comparison of a readable and a synchronizer.
Simulates a writeable that raises an exception if the serializer
dumps data which do not match the content of the readable.
"""
class Failed(Exception):
pass
class Comparable(object):
def write(self, data):
echo = readable.read(len(data))
if echo != data:
raise Failed
try:
comparable = Comparable()
dumper.dump(comparable)
return readable.read() == ''
except Failed:
return False
class ComparePickles(object):
def __init__(self, context, pickler):
self.context = context
self.pickler = pickler
def dump(self, writeable):
self.pickler.dump(self.context, writeable) | zope.fssync | /zope.fssync-3.6.1.zip/zope.fssync-3.6.1/src/zope/fssync/task.py | task.py |
import shutil
import zope.interface
import os.path
import py.path
import repository
import metadata
import interfaces
import task
class VersionControlRepository(repository.FileSystemRepository):
"""Version Control Repository.
(hopefully) version control system agnostic.
"""
zope.interface.implements(interfaces.IVersionControlRepository)
def __init__(self):
super(VersionControlRepository, self).__init__()
self.clear()
def sync(self, object, message=''):
self.save(object)
self.up()
self.resolve()
self.load(object)
self.commit(message)
def clear(self):
self._added_by_save = []
self._deleted_by_save = []
def up(self):
raise NotImplementedError
def resolve(self):
raise NotImplementedError
def commit(self, message):
raise NotImplementedError
class SVNChanges(object):
"""A collector for changes in a SVN repository."""
def __init__(self, before, after):
self.added = sorted(after - before)
self.deleted = sorted(before - after)
def accept(self):
for path in self.deleted:
if path.check(versioned=True):
path.remove()
if path.check():
shutil.rmtree(str(path))
class SVNDirectoryManager(metadata.DirectoryManager):
"""Keeps fssync metadata of objects under version control."""
def __init__(self, wcpath):
self.entries = {}
for path in wcpath.listdir():
if path.check(versioned=True):
self.entries[path.basename] = dict(name=path.basename)
def getentry(self, name):
if name not in self.entries:
return dict(name=name, flag='removed')
return self.entries.get(name, {})
class SVNMetadata(metadata.Metadata):
"""Reads the metadata from a SVN repository."""
def __init__(self, repository):
super(SVNMetadata, self).__init__()
self.repository = repository
def getentry(self, file):
"""Return the metadata entry for a given file (or directory).
Modifying the dict that is returned will cause the changes to
the metadata to be written out when flush() is called. If
there is no metadata entry for the file, return a new empty
dict, modifications to which will also be flushed.
"""
dir, base = self.repository.split(file)
return self.getmanager(dir).getentry(base)
def getmanager(self, dir):
dir = self.repository.fullpath(dir)
if dir not in self.cache:
self.cache[dir] = SVNDirectoryManager(dir)
return self.cache[dir]
class SVNRepository(VersionControlRepository):
"""A subversion repository."""
zope.interface.implements(interfaces.ISVNRepository)
debug = False
def __init__(self, path):
self.svnwc = py.path.svnwc(path)
allpaths = self.svnwc.visit(rec=True)
self.before = set(allpaths)
self.after = set(allpaths)
super(SVNRepository, self).__init__()
def up(self):
self.svnwc.update()
def fullpath(self, relpath):
return self.svnwc.join(relpath)
def getMetadata(self):
"""Returns a special metadata database which reads directly
from the SVN repository."""
return SVNMetadata(self)
def clear(self):
super(SVNRepository, self).clear()
self.before = self.after
self.after = set()
def changes(self):
return SVNChanges(self.before, self.after)
def isdir(self, path):
return self.svnwc.join(path).check(dir=True)
def split(self, path):
if isinstance(path, str):
return os.path.split(path)
return path.dirpath(), path.basename
def ensuredir(self, path):
dir = self.svnwc.ensure(path, directory=True)
self.after.add(dir)
return dir
def readable(self, path):
"""Returns a file like object that is open for read operations."""
realpath = self.svnwc.join(path)
fp = self.files[path] = realpath.open('rb')
return fp
def writeable(self, path):
"""Returns a file like object that is open for write operations.
XXX: Ignores all files with @@ at the moment. These files
should not be generated at all.
"""
if '@@' in path:
class DummyStream(object):
def write(self, data):
pass
def close(self):
pass
return DummyStream()
wcpath = self.svnwc.join(path)
self.svnwc.ensure(path)
fp = self.files[path] = wcpath.open('wb')
while len(str(wcpath)) > len(str(self.svnwc)):
self.after.add(wcpath)
wcpath = wcpath.dirpath()
return fp
class SVNSyncTask(task.SyncTask):
"""A sync task that performs a complete update cycle."""
def resolve(self):
pass
def commit(self, message):
self.repository.commit(message)
def perform(self, container, name, message=''):
self.repository.debug = True
export = task.Checkout(self.getSynchronizer, self.repository)
export.perform(container[name], name)
self.repository.up()
load = task.Commit(self.getSynchronizer, self.repository)
load.debug = True
load.perform(container, name, name) | zope.fssync | /zope.fssync-3.6.1.zip/zope.fssync-3.6.1/src/zope/fssync/svn.py | svn.py |
import os
import sys
import unicodedata
class Error(Exception):
"""User-level error, e.g. non-existent file.
This can be used in several ways:
1) raise Error("message")
2) raise Error("message %r %r" % (arg1, arg2))
3) raise Error("message %r %r", arg1, arg2)
4) raise Error("message", arg1, arg2)
- Forms 2-4 are equivalent.
- Form 4 assumes that "message" contains no % characters.
- When using forms 2 and 3, all % formats are supported.
- Form 2 has the disadvantage that when you specify a single
argument that happens to be a tuple, it may get misinterpreted.
- The message argument is required.
- Any number of arguments after that is allowed.
"""
def __init__(self, msg, *args):
self.msg = msg
self.args = args
def __str__(self):
msg, args = self.msg, self.args
if args:
if "%" in msg:
msg = msg % args
else:
msg += " "
msg += " ".join(map(repr, args))
return str(msg)
def __repr__(self):
return "%s%r" % (self.__class__.__name__, (self.msg,)+self.args)
unwanted = ("", os.curdir, os.pardir)
nczope = os.path.normcase("@@Zope")
def getoriginal(path):
"""Return the path of the Original file corresponding to path."""
return getspecial(path, "Original")
def getextra(path):
"""Return the path of the Extra directory corresponding to path."""
return getspecial(path, "Extra")
def getannotations(path):
"""Return the path of the Annotations directory corresponding to path."""
return getspecial(path, "Annotations")
def getspecial(path, what):
"""Helper for getoriginal(), getextra(), getannotations()."""
head, tail = os.path.split(path)
return os.path.join(head, "@@Zope", what, tail)
def split(path):
"""Split a path, making sure that the tail returned is real."""
head, tail = os.path.split(path)
if tail in unwanted:
newpath = os.path.normpath(path)
head, tail = os.path.split(newpath)
if tail in unwanted:
newpath = os.path.realpath(path)
head, tail = os.path.split(newpath)
if head == newpath or tail in unwanted:
raise Error("path '%s' is the filesystem root", path)
if not head:
head = os.curdir
return head, tail
def ensuredir(path):
"""Make sure that the given path is a directory, creating it if necessary.
This may raise OSError if the creation operation fails.
"""
if not os.path.isdir(path):
os.makedirs(path)
def normalize(name):
"""Normalize a filename to normalization form C.
Linux and (most?) other Unix-like operating systems use the normalization
form C (NFC) for UTF-8 encoding by default but do not enforce this.
Darwin, the base of Macintosh OSX, enforces normalization form D (NFD),
where a few characters are encoded in a different way.
"""
if sys.platform == 'darwin':
if isinstance(name, unicode):
name = unicodedata.normalize("NFC", name)
elif sys.getfilesystemencoding() == 'utf-8':
name = unicode(name, encoding='utf-8')
name = unicodedata.normalize("NFC", name)
name = name.encode('utf-8')
return name
def encode(path, encoding=None):
"""Encodes a path in its normalized form.
Uses the filesystem encoding as a default encoding. Assumes that the given path
is also encoded in the filesystem encoding.
"""
fsencoding = sys.getfilesystemencoding()
if encoding is None:
encoding = fsencoding
if isinstance(path, unicode):
return path.encode(encoding)
return unicode(path, encoding=fsencoding).encode(encoding) | zope.fssync | /zope.fssync-3.6.1.zip/zope.fssync-3.6.1/src/zope/fssync/fsutil.py | fsutil.py |
import os
import shutil
from os.path import basename, dirname, exists, isfile, isdir, join, normcase
from zope.xmlpickle import dumps
from zope.fssync.merger import Merger
from zope.fssync import fsutil
class FSMerger(object):
"""Higher-level three-way file and directory merger.
If overwrite_local is True, then local should be replaced with
the remote, regardless of local changes.
"""
def __init__(self, metadata, reporter, overwrite_local=False):
"""Constructor.
Arguments are a metadata database and a reporting function.
"""
self.metadata = metadata
self.reporter = reporter
self.merger = Merger(metadata)
self.overwrite_local = overwrite_local
def merge(self, local, remote):
"""Merge remote file or directory into local file or directory."""
if ((isfile(local) or not exists(local))
and
(isfile(remote) or not exists(remote))):
self.merge_files(local, remote)
elif ((isdir(local) or not exists(local))
and
(isdir(remote) or not exists(remote))):
self.merge_dirs(local, remote)
else:
# One is a file, the other is a directory.
if self.local_modifications(local):
# We have local modifications, so we cannot replace
# the local object without loss.
# SVN reports a failure here and so do we
self.reporter("C %s" % local)
return
# Since this is more
# like a conflict that should be resolved one could
# also make a backup and report a warning.
# self.backup(local)
# self.reporter("B %s" % local)
else:
# If we have no local modifications we
# simply replace the local object with it's
# remote counterpart.
self.remove(local)
self.merge(local, remote)
return
flag = self.metadata.getentry(local).get("flag")
self.merge_extra(local, remote, flag)
self.merge_annotations(local, remote, flag)
if not exists(local) and not self.metadata.getentry(local):
self.remove_special(local, "Extra")
self.remove_special(local, "Annotations")
self.remove_special(local, "Original")
def local_modifications(self, local):
"""Helper to check for local modifications."""
lentry = self.metadata.getentry(local)
flag = lentry.get("flag")
if flag == 'added':
return True
if isdir(local):
locals = [join(local, name)
for name in os.listdir(local)]
for path in locals:
if self.local_modifications(path):
return True
return False
else:
original = fsutil.getoriginal(local)
if not exists(original):
return True
return not self.merger.cmpfile(local, original)
def backup(self, local):
"""Helper to preserve unmergeable local files."""
appendix = '.OLD'
target = local + appendix
count = 0
while exists(target):
count += 1
target = "%s%s%s" % (local, appendix, count)
shutil.move(local, target)
def remove(self, local):
"""Helper to remove a local file or directory."""
if isdir(local):
try:
shutil.rmtree(local)
self.reportdir("D", local)
except os.error:
self.reportdir("?", local)
else:
try:
os.remove(local)
self.remove_special(local, "Original")
self.reporter("D %s" % local)
except:
self.reporter("? %s" % local)
def merge_extra(self, local, remote, flag):
"""Helper to merge the Extra trees."""
lextra = fsutil.getextra(local)
rextra = fsutil.getextra(remote)
self.merge_dirs(lextra, rextra, flag=flag, special=True)
def merge_annotations(self, local, remote, flag):
"""Helper to merge the Anotations trees."""
lannotations = fsutil.getannotations(local)
rannotations = fsutil.getannotations(remote)
self.merge_dirs(lannotations, rannotations, flag=flag, special=True)
def remove_special(self, local, what):
"""Helper to remove an Original, Extra or Annotations file/tree."""
target = fsutil.getspecial(local, what)
dir = dirname(target)
if exists(target):
if isdir(target):
shutil.rmtree(target)
else:
# When should this ever happen?
os.remove(target)
# remove the specials directory only if it's empty
if isdir(dir):
try:
os.rmdir(dir)
except os.error:
pass
def merge_files(self, local, remote):
"""Merge remote file into local file."""
# Reset sticky conflict if file was removed
entry = self.metadata.getentry(local)
conflict = entry.get("conflict")
if conflict and not os.path.exists(local):
del entry["conflict"]
original = fsutil.getoriginal(local)
action, state = self.merger.classify_files(local, original, remote)
if action == 'Merge' and state == 'Modified' and self.overwrite_local:
action = 'Copy'
state = 'Uptodate'
state = self.merger.merge_files(local, original, remote,
action, state) or state
self.reportaction(action, state, local)
def merge_dirs(self, localdir, remotedir, flag=None, special=False):
"""Merge remote directory into local directory."""
#uo: How do we handle unicode filenames?
lentrynames = self.metadata.getnames(localdir)
rentrynames = self.metadata.getnames(remotedir)
lentry = self.metadata.getentry(localdir)
rentry = self.metadata.getentry(remotedir)
if not lentrynames and not rentrynames:
if not lentry:
if not rentry:
if exists(localdir) and not special:
self.reportdir("?", localdir)
else:
if not exists(localdir):
self.make_dir(localdir)
lentry.update(rentry)
self.reportdir("N", localdir)
else:
# call make_dir() to create @@Zope and store metadata
self.make_dir(localdir)
self.reportdir("*", localdir)
return
if lentry.get("flag") == "added":
if not rentry:
self.reportdir("A", localdir)
else:
self.reportdir("U", localdir)
del lentry["flag"]
return
if lentry.get("flag") == "removed":
if rentry:
self.reportdir("R", localdir)
else:
self.reportdir("D", localdir)
lentry.clear()
return
if not rentry:
self.clear_dir(localdir)
return
if not special:
flag = lentry.get("flag")
if exists(localdir):
if flag == "added":
if exists(remotedir):
self.reportdir("U", localdir)
if "flag" in lentry:
del lentry["flag"]
else:
self.reportdir("A", localdir)
else:
if rentry or exists(remotedir):
self.reportdir("/", localdir)
else:
# Tree removed remotely, must recurse down locally
for name in lentrynames:
# merge() removes the local copies since the
# remote versions are gone, unless there have
# been local changes.
self.merge(join(localdir, name), join(remotedir, name))
if flag != "added":
self.clear_dir(localdir)
return
lnames = dict([(normcase(name), name)
for name in os.listdir(localdir)])
else:
if flag == "removed":
self.reportdir("R", localdir)
return # There's no point in recursing down!
if rentry or rentrynames:
# remote directory is new
self.make_dir(localdir)
lentry.update(rentry)
self.reportdir("N", localdir)
lnames = {}
for name in lentrynames:
lnames[normcase(name)] = name
if exists(remotedir):
rnames = dict([(normcase(name), name)
for name in os.listdir(remotedir)])
else:
rnames = {}
for name in rentrynames:
rnames[normcase(name)] = name
names = {}
names.update(lnames)
names.update(rnames)
if fsutil.nczope in names:
del names[fsutil.nczope]
# TODO: We must find a better way to avoid
# the problem that unicode paths and str paths occur together
# in the names dict
for k, v in names.items():
if not isinstance(k, unicode):
del names[k]
k = unicode(k, encoding='utf-8')
if not isinstance(v, unicode):
v = unicode(v, encoding='utf-8')
names[k] = v
ncnames = sorted(names.keys())
for ncname in ncnames:
name = names[ncname]
self.merge(join(localdir, name), join(remotedir, name))
def make_dir(self, localdir):
"""Helper to create a local directory.
This also creates the @@Zope subdirectory and places an empty
Entries.xml file in it.
"""
fsutil.ensuredir(localdir)
localzopedir = join(localdir, "@@Zope")
fsutil.ensuredir(localzopedir)
efile = join(localzopedir, "Entries.xml")
if not os.path.exists(efile):
data = dumps({})
f = open(efile, "w")
try:
f.write(data)
finally:
f.close()
def clear_dir(self, localdir):
"""Helper to get rid of a local directory.
This zaps the directory's @@Zope subdirectory, but not other
files/directories that might still exist.
It doesn't deal with extras and annotations for the directory
itself, though.
"""
lentry = self.metadata.getentry(localdir)
lentry.clear()
localzopedir = join(localdir, "@@Zope")
if os.path.isdir(localzopedir):
shutil.rmtree(localzopedir)
try:
os.rmdir(localdir)
except os.error:
self.reportdir("?", localdir)
else:
self.reportdir("D", localdir)
def reportdir(self, letter, localdir):
"""Helper to report something for a directory.
This adds a separator (e.g. '/') to the end of the pathname to
signal that it is a directory.
"""
if letter == "?" and self.ignore(localdir):
letter = "*"
self.reporter("%s %s" % (letter, join(localdir, "")))
def reportaction(self, action, state, local):
"""Helper to report an action and a resulting state.
This always results in exactly one line being reported.
Report letters are:
C -- conflicting changes not resolved (not committed)
U -- file brought up to date (possibly created)
M -- modified (not committed)
A -- added (not committed)
R -- removed (not committed)
D -- file deleted
? -- file exists locally but not remotely
* -- nothing happened
"""
assert action in ('Fix', 'Copy', 'Merge', 'Delete', 'Nothing'), action
assert state in ('Conflict', 'Uptodate', 'Modified', 'Spurious',
'Added', 'Removed', 'Nonexistent'), state
letter = "*"
if state == "Conflict":
letter = "C"
elif state == "Uptodate":
if action in ("Copy", "Fix", "Merge"):
letter = "U"
elif state == "Modified":
letter = "M"
elif state == "Added":
letter = "A"
elif state == "Removed":
letter = "R"
elif state == "Spurious":
if not self.ignore(local):
letter = "?"
elif state == "Nonexistent":
if action == "Delete":
letter = "D"
self.reporter("%s %s" % (letter, local))
def ignore(self, path):
# TODO: This should have a larger set of default patterns to
# ignore, and honor .cvsignore
fn = basename(path)
return (fn.endswith("~")
# CVS crud (retrieved older versions):
or fn.startswith(".#")
# special names from various revision control systems:
or fn in (".cvsignore", "CVS", "RCS", "SCCS", ".svn")) | zope.fssync | /zope.fssync-3.6.1.zip/zope.fssync-3.6.1/src/zope/fssync/fsmerger.py | fsmerger.py |
import os
import shutil
import filecmp
import commands
from os.path import exists, isfile, dirname
from zope.fssync import fsutil
class Merger(object):
"""Augmented three-way file merges.
An augmented merge takes into account three files and two metadata
entries. The files are labeled local, original, and remote. The
metadata entries are for local and remote. A remote metadata
entry is either empty or non-empty. Empty means the file does not
exist remotely, non-empty means it does exist remotely. We also
have to take into account the possibility that the existence of
the file belies what the entry declares. A local metadata entry
can have those states, and in addition, if non-empty, it can be
flagged as added or removed. Again, the existence of the file may
bely what the entry claims. The original file serves the obvious
purpose. Its existence, too, can be inconsistent with the state
indicated by the metadata entries.
To find the metadata entry for a file, we use an abstraction
called the metadata database; for our purposes, all we need is
that the metadata database supports a getentry() method which
returns the metadata as a dict. Changes to this dict will cause
changes to the metadata.
The purpose of the merge_files() method is to merging the remote
changes into the local copy as the best it can, resolving
inconsistencies if possible. It should not raise an exception
unless there are file/directory permission problems. Its return
value is an indicator of the final state.
The classify_files() methods is a helper for merge_files(); it
looks at all the evidence and decides what merge_files() should
do, without actually touching any files or metadata. Possible
actions are:
Fix -- copy the remote copy to the local original, nothing else
Copy -- copy the remote copy over the local copy and original
Merge -- merge the remote copy into the local copy
(this may cause merge conflicts when executed);
copy the remote copy to the local original
Delete -- delete the local copy and original
Nothing -- do nothing
The original file is made a copy of the remote file for actions
Fix, Copy and Merge; it is deleted for action Delete; it is
untouched for action Nothing.
The classify_files() method should also indicate the final state
of the local copy after the action is taken:
Conflict -- there is a conflict of some kind
Uptodate -- the local copy is the same as the remote copy
Modified -- the local copy is marked (to be) modified
Added -- the local copy is marked (to be) added
Removed -- the local copy is marked (to be) removed
Spurious -- there is an unregistered local file only
Nonexistent -- there is nothing locally or remotely
For Conflict, Added and Removed, the action will always be
Nothing. The difference between Removed and Nonexistent is that
Nonexistent means the file doesn't exist remotely either, while
Removed means that on the next commit the file should be removed
from the remote store. Similarly, Added means the file should be
added remotely on the next commit, and Modified means that the
file should be changed remotely to match the local copy at the
next commit.
Note that carrying out the Merge action can change the resulting
state to become Conflict instead of Modified, if there are merge
conflicts (which classify_files() can't detect without doing more
work than reasonable).
"""
def __init__(self, metadata):
"""Constructor.
The argument is the metadata database, which has a single
method: getentry(file) which returns a dict containing the
metadata for that file. Changes to this dict will be
preserved when the database is written back (not by the Merger
class). To delete all metadata for a file, call the dict's
clear() method.
We pass in the metadata database rather than inheriting from
it, in part because this makes testing with a Mock metadata
database easier.
"""
self.metadata = metadata
def getentry(self, file):
"""Helper to abstract away the existence of self.metadata."""
return self.metadata.getentry(file)
def merge_files(self, local, original, remote, action, state):
"""Merge files.
The action and state arguments correspond to the return value
of classify_files().
Return the state as returned by the second return value of
classify_files(). This is either the argument state or
recalculated based upon the effect of the action.
"""
method = getattr(self, "merge_files_" + action.lower())
return method(local, original, remote) or state
def merge_files_nothing(self, local, original, remote):
return None
def merge_files_delete(self, local, original, remote):
if isfile(local):
os.remove(local)
if isfile(original):
os.remove(original)
self.getentry(local).clear()
return None
def merge_files_copy(self, local, original, remote):
try:
shutil.copy(remote, local)
except IOError, msg:
import pdb; pdb.set_trace()
fsutil.ensuredir(dirname(original))
shutil.copy(remote, original)
self.getentry(local).update(self.getentry(remote))
self.clearflag(local)
return None
def merge_files_merge(self, local, original, remote):
# TODO: This is platform dependent
if exists(original):
origfile = original
else:
origfile = "/dev/null"
# commands.mkarg() is undocumented; maybe use fssync.quote()
cmd = "diff3 -m -E %s %s %s" % (commands.mkarg(local),
commands.mkarg(origfile),
commands.mkarg(remote))
pipe = os.popen(cmd, "r")
output = pipe.read()
sts = pipe.close()
if output or not sts:
f = open(local, "wb")
try:
f.write(output)
finally:
f.close()
fsutil.ensuredir(dirname(original))
shutil.copy(remote, original)
self.getentry(local).update(self.getentry(remote))
self.clearflag(local)
if sts:
self.getentry(local)["conflict"] = "yes"
return "Conflict"
else:
return "Modified"
def merge_files_fix(self, local, original, remote):
fsutil.ensuredir(dirname(original))
shutil.copy(remote, original)
self.clearflag(local)
self.getentry(local).update(self.getentry(remote))
return None
def clearflag(self, file):
"""Helper to clear the added/removed metadata flag."""
metadata = self.getentry(file)
if "flag" in metadata:
del metadata["flag"]
def classify_files(self, local, original, remote):
"""Classify file changes.
Arguments are pathnames to the local, original, and remote
copies.
Return a pair of strings (action, state) where action is one
of 'Fix', 'Copy', 'Merge', 'Delete' or 'Nothing', and state is
one of 'Conflict', 'Uptodate', 'Modified', 'Added', 'Removed',
'Spurious' or 'Nonexistent'.
"""
lmeta = self.getentry(local)
rmeta = self.getentry(remote)
# Special-case sticky conflict
if "conflict" in lmeta:
return ("Nothing", "Conflict")
# Sort out cases involving additions or removals
if not lmeta and not rmeta:
if exists(local):
return ("Nothing", "Spurious")
else:
# Why are we here?
# classify_files() should not have been called in this case.
return ("Nothing", "Nonexistent")
if lmeta.get("flag") == "added":
# Added locally
if not rmeta:
# Nothing remotely
return ("Nothing", "Added")
else:
# Added remotely too! Merge, unless trivial conflict
if self.cmpfile(local, remote):
return ("Fix", "Uptodate")
else:
# CVS would say "move local file out of the way"
if rmeta.get("binary") == "true" or lmeta.get("binary") == "true":
return ("Nothing", "Conflict")
else:
return ("Merge", "Modified")
if rmeta and not lmeta:
# Added remotely
return ("Copy", "Uptodate")
if lmeta.get("flag") == "removed":
if not rmeta:
# Removed remotely too
return ("Delete", "Nonexistent")
else:
# Removed locally
if self.cmpfile(original, remote):
return ("Nothing", "Removed")
else:
return ("Nothing", "Conflict")
if lmeta and not rmeta:
assert lmeta.get("flag") is None
# Removed remotely
return ("Delete", "Nonexistent")
if lmeta.get("flag") is None and not exists(local):
# Lost locally
if rmeta:
return ("Copy", "Uptodate")
else:
return ("Delete", "Nonexistent")
# Sort out cases involving simple changes to files
if self.cmpfile(original, remote):
# No remote changes; classify local changes
if self.cmpfile(local, original):
# No changes
return ("Nothing", "Uptodate")
else:
# Only local changes
return ("Nothing", "Modified")
else:
# Some remote changes; classify local changes
if self.cmpfile(local, original):
# Only remote changes
return ("Copy", "Uptodate")
else:
if self.cmpfile(local, remote):
# We're lucky -- local and remote changes are the same
return ("Fix", "Uptodate")
else:
# Changes on both sides, three-way merge needed
if rmeta.get("binary") == "true" or lmeta.get("binary") == "true":
return ("Nothing", "Conflict")
else:
return ("Merge", "Modified")
def cmpfile(self, file1, file2):
"""Helper to compare two files.
Return True iff the files both exist and are equal.
"""
if not (isfile(file1) and isfile(file2)):
return False
return filecmp.cmp(file1, file2, shallow=False) | zope.fssync | /zope.fssync-3.6.1.zip/zope.fssync-3.6.1/src/zope/fssync/merger.py | merger.py |
import os
import fsutil
class Snarfer(object):
"""Snarfer -- write an archive to a stream."""
def __init__(self, ostr):
"""Constructor. The argument is the output stream."""
self.ostr = ostr
def add(self, fspath, path):
if os.path.isdir(fspath):
self.addtree(fspath, path + "/")
elif os.path.isfile(fspath):
self.addfile(fspath, path)
def addtree(self, root, prefix="", filter=None):
"""Snarf a directory tree.
root -- the root of the tree in the filesystem.
prefix -- optional snarf path prefix, either empty or ending in '/'.
filter -- optional filter predicate.
"""
if prefix:
assert prefix[0] != "/"
assert prefix[-1] == "/"
if filter is None:
def filter(fspath):
return True
names = os.listdir(root)
names.sort()
self.adddir(prefix)
for name in names:
fspath = os.path.join(root, name)
if not filter(fspath):
continue
if os.path.isdir(fspath):
self.addtree(fspath, prefix + name + "/", filter)
elif os.path.isfile(fspath):
self.addfile(fspath, prefix + name)
def addfile(self, fspath, path):
"""Snarf a single file given by fspath."""
assert path[-1] != "/"
f = open(fspath, "rb")
try:
f.seek(0, 2)
size = f.tell()
f.seek(0)
self.addstream(f, size, path)
finally:
f.close()
def adddir(self, path):
path = fsutil.encode(path, 'utf-8')
self.ostr.write("0 %s\n" % path)
def addstream(self, istr, size, path):
"""Snarf a single file from a data stream.
istr -- the input stream;
size -- the number of bytes to read from istr;
path -- the snarf path.
Raises IOError if reading istr returns an EOF condition before
size bytes have been read.
"""
path = fsutil.encode(path, 'utf-8')
self.ostr.write("%d %s\n" % (size, path))
copybytes(size, istr, self.ostr)
class Unsnarfer(object):
"""Unsnarfer -- read an archive from a stream."""
def __init__(self, istr):
"""Constructor. The argument is the input stream."""
self.istr = istr
def unsnarf(self, root):
"""Unsnarf the entire archive into a directory tree.
root -- the root of the directory tree where to write.
"""
self.root = root
while True:
infoline = self.istr.readline()
if not infoline:
break
if not infoline.endswith("\n"):
raise IOError("incomplete info line %r" % infoline)
infoline = infoline[:-1]
sizestr, path = infoline.split(" ", 1)
size = int(sizestr)
if size == 0 and (path == "" or path.endswith("/")):
self.makedir(path)
else:
f = self.createfile(path)
try:
copybytes(size, self.istr, f)
finally:
f.close()
def makedir(self, path):
if path.endswith('/'):
path = path[:-1]
fspath = self.translatepath(path)
self.ensuredir(fspath)
def createfile(self, path):
fspath = self.translatepath(path)
self.ensuredir(os.path.dirname(fspath))
return open(fspath, "wb")
def ensuredir(self, fspath):
if not os.path.isdir(fspath):
os.makedirs(fspath)
def translatepath(self, path):
if path == "":
return self.root
if ":" in path and os.name != "posix":
raise IOError("path cannot contain colons: $r" % path)
if "\\" in path and os.name != "posix":
raise IOError("path cannot contain backslashes: %r" % path)
parts = path.split("/")
for forbidden in "", ".", "..", os.curdir, os.pardir:
if forbidden in parts:
raise IOError("forbidden part %r in path: %r" %
(forbidden, path))
return os.path.join(self.root, *parts)
def copybytes(size, istr, ostr, bufsize=8192):
aim = size - bufsize
pos = 0
while pos < aim:
data = istr.read(bufsize)
if not data:
raise IOError("not enough data read from input stream")
pos += len(data)
ostr.write(data)
while pos < size:
data = istr.read(size - pos)
if not data:
raise IOError("not enough data read from input stream")
pos += len(data)
ostr.write(data) | zope.fssync | /zope.fssync-3.6.1.zip/zope.fssync-3.6.1/src/zope/fssync/snarf.py | snarf.py |
=========
CHANGES
=========
5.1.0 (2022-02-11)
==================
- Drop support for Python 3.4.
- Add support for Python 3.8, 3.9 and 3.10.
5.0.0 (2019-09-23)
==================
- Add support for transaction managers operating in explicit mode.
Schema managers were previously required not to commit transactions
in their ``evolve`` or ``install`` methods, but a loophole was open
to allow them to commit "if there were no subsequent operations".
That loophole is now closed, at least in explicit mode. See `issue 8
<https://github.com/zopefoundation/zope.generations/issues/8>`_.
4.1.0 (2018-10-23)
==================
- Add support for Python 3.7.
4.0.0 (2017-07-20)
==================
- Dropped support for Python 2.6 and 3.3.
- Added support for Python 3.4, 3.5, 3.6, PyPy2 and PyPy3.
4.0.0a1 (2013-02-25)
====================
- Added support for Python 3.3.
- Replaced deprecated ``zope.interface.implements`` usage with equivalent
``zope.interface.implementer`` decorator.
- Dropped support for Python 2.4 and 2.5.
3.7.1 (2011-12-22)
==================
- Removed buildout part which was used during development but does not
compile on Windows.
- Generation scripts add a transaction note.
3.7.0 (2010-09-18)
==================
- Initial release extracted from ``zope.app.generations``.
- Generations key (stored in database root) has been changed from
``zope.app.generations`` to ``zope.generations``. Migration is done when
``evolve`` is run the first time by coping the existing generations data
over to the new key. So the old and the new key can be used in parallel.
| zope.generations | /zope.generations-5.1.0.tar.gz/zope.generations-5.1.0/CHANGES.rst | CHANGES.rst |
==================
zope.generations
==================
.. image:: https://img.shields.io/pypi/v/zope.generations.svg
:target: https://pypi.org/project/zope.generations/
:alt: Latest Version
.. image:: https://img.shields.io/pypi/pyversions/zope.generations.svg
:target: https://pypi.org/project/zope.generations/
:alt: Supported Python versions
.. image:: https://readthedocs.org/projects/zopegenerations/badge/?version=latest
:target: https://zopegenerations.readthedocs.io/en/latest/?badge=latest
:alt: Documentation Status
.. image:: https://github.com/zopefoundation/zope.generations/actions/workflows/tests.yml/badge.svg
:target: https://github.com/zopefoundation/zope.generations/actions/workflows/tests.yml
:alt: Build Status
.. image:: https://coveralls.io/repos/github/zopefoundation/zope.generations/badge.svg
:target: https://coveralls.io/github/zopefoundation/zope.generations
:alt: Code Coverage
Generations are a way of updating objects in the database when the application
schema changes. An application schema is essentially the structure of data,
the structure of classes in the case of ZODB or the table descriptions in the
case of a relational database.
See https://zopegenerations.readthedocs.io/ for complete documentation.
| zope.generations | /zope.generations-5.1.0.tar.gz/zope.generations-5.1.0/README.rst | README.rst |
=============
Generations
=============
.. currentmodule:: zope.generations.generations
Generations are a way of updating objects in the database when the application
schema changes. An application schema is essentially the structure of data,
the structure of classes in the case of ZODB or the table descriptions in the
case of a relational database.
When you change your application's data structures, for example,
you change the semantic meaning of an existing field in a class, you will
have a problem with databases that were created before your change. For a
more thorough discussion and possible solutions, see
http://wiki.zope.org/zope3/DatabaseGenerations
We will be using the component architecture, and we will need a database and a
connection:
>>> try:
... from html import escape
... except ImportError:
... from cgi import escape
>>> from pprint import pprint
>>> from zope.interface import implementer
>>> import transaction
>>> from ZODB.MappingStorage import DB
>>> db = DB()
>>> conn = db.open()
>>> tx = transaction.begin()
>>> root = conn.root()
Imagine that our application is an oracle: you can teach it to react to
phrases. Let's keep it simple and store the data in a dict:
>>> root['answers'] = {'Hello': 'Hi & how do you do?',
... 'Meaning of life?': '42',
... 'four < ?': 'four < five'}
>>> import transaction
>>> tx.commit()
Initial setup
=============
Here's some generations-specific code. We will create and register a
SchemaManager. SchemaManagers are responsible for the actual updates of the
database. This one will be just a dummy. The point here is to make the
generations module aware that our application supports generations.
The :class:`default implementation of SchemaManager
<SchemaManager>` is not suitable for this
test because it uses Python modules to manage generations. For now, it
will be just fine, since we don't want it to do anything just yet.
>>> from zope.generations.interfaces import ISchemaManager
>>> from zope.generations.generations import SchemaManager
>>> import zope.component
>>> dummy_manager = SchemaManager(minimum_generation=0, generation=0)
>>> zope.component.provideUtility(
... dummy_manager, ISchemaManager, name='some.app')
'some.app' is a unique identifier. You should use a URI or the dotted name
of your package.
When you start Zope and a database is opened, an event
``IDatabaseOpenedWithRoot`` is sent. Zope registers
`evolveMinimumSubscriber` by default as a handler for this event.
Let's simulate this:
>>> class DatabaseOpenedEventStub(object):
... def __init__(self, database):
... self.database = database
>>> event = DatabaseOpenedEventStub(db)
>>> from zope.generations.generations import evolveMinimumSubscriber
>>> evolveMinimumSubscriber(event)
The consequence of this action is that now the database contains the fact
that our current schema number is 0. When we update the schema, Zope3 will
have an idea of what the starting point was. Here, see?
>>> from zope.generations.generations import generations_key
>>> tx = transaction.begin()
>>> root[generations_key]['some.app']
0
>>> tx.abort()
In real life you should never have to bother with this key directly,
but you should be aware that it exists.
Upgrade scenario
================
Back to the story. Some time passes and one of our clients gets hacked because
we forgot to escape HTML special characters! The horror! We must fix this
problem ASAP without losing any data. We decide to use generations to impress
our peers.
Let's update the schema manager (drop the old one and install a new custom
one):
>>> from zope.component import globalregistry
>>> gsm = globalregistry.getGlobalSiteManager()
>>> gsm.unregisterUtility(provided=ISchemaManager, name='some.app')
True
>>> @implementer(ISchemaManager)
... class MySchemaManager(object):
...
... minimum_generation = 1
... generation = 2
...
... def evolve(self, context, generation):
... root = context.connection.root()
... answers = root['answers']
... if generation == 1:
... for question, answer in list(answers.items()):
... answers[question] = escape(answer)
... elif generation == 2:
... for question, answer in list(answers.items()):
... del answers[question]
... answers[escape(question)] = answer
... else:
... raise ValueError("Bummer")
... root['answers'] = answers # ping persistence
>>> manager = MySchemaManager()
>>> zope.component.provideUtility(manager, ISchemaManager, name='some.app')
We have set *minimum_generation* to 1. That means that our application
will refuse to run with a database older than generation 1. The *generation*
attribute is set to 2, which means that the latest generation that this
SchemaManager knows about is 2.
`evolve` is the workhorse here. Its job is to get the database from
``generation - 1`` to *generation*. It gets a context which has the
attribute ``connection``, which is a connection to the ZODB. You can use
that to change objects like in this example.
In this particular implementation generation 1 escapes the answers (say,
critical, because they can be entered by anyone!), generation 2 escapes the
questions (say, less important, because these can be entered by authorized
personell only).
In fact, you don't really need a custom implementation of
`~zope.generations.interfaces.ISchemaManager`. One is available at
`SchemaManager`, and we have used it for a dummy previously. It uses
Python modules for organization of evolver functions. See its
docstring for more information.
In real life you will have much more complex object structures than
the one here. To make your life easier, there are two very useful
functions available in :mod:`zope.generations.utility`:
`~.findObjectsMatching` and `~.findObjectsProviding`. They will dig
through containers recursively to help you seek out old objects that
you wish to update, by interface or by some other criteria. They are
easy to understand, check their docstrings.
Generations in action
=====================
So, our furious client downloads our latest code and restarts Zope. The event
is automatically sent again:
>>> event = DatabaseOpenedEventStub(db)
>>> evolveMinimumSubscriber(event)
Shazam! The client is happy again!
>>> tx = transaction.begin()
>>> pprint(root['answers'])
{'Hello': 'Hi & how do you do?',
'Meaning of life?': '42',
'four < ?': 'four < five'}
Because `evolveMinimumSubscriber` is very lazy, it only updates the
database just enough so that your application can use it (to the
*minimum_generation*, that is). Indeed, the marker indicates that the
database generation has been bumped to 1:
>>> root[generations_key]['some.app']
1
>>> tx.abort()
We see that generations are working, so we decide to take the next step
and evolve to generation 2. Let's see how this can be done manually:
>>> from zope.generations.generations import evolve
>>> evolve(db)
>>> tx = transaction.begin()
>>> pprint(root['answers'])
{'Hello': 'Hi & how do you do?',
'Meaning of life?': '42',
'four < ?': 'four < five'}
>>> root[generations_key]['some.app']
2
>>> tx.abort()
Default behaviour of `evolve` upgrades to the latest generation provided by
the SchemaManager. You can use the *how* argument to `evolve` when you want
just to check if you need to update or if you want to be lazy like the
subscriber which we have called previously.
Ordering of schema managers
===========================
Frequently subsystems used to compose an application rely on other
subsystems to operate properly. If both subsystems provide schema
managers, it is often helpful to know the order in which the evolvers
will be invoked. This allows a framework and it's clients to be able
to evolve in concert, and the clients can know that the framework will
be evolved before or after itself.
This can be accomplished by controlling the names of the schema
manager utilities. The schema managers are run in the order
determined by sorting their names.
>>> manager1 = SchemaManager(minimum_generation=0, generation=0)
>>> manager2 = SchemaManager(minimum_generation=0, generation=0)
>>> zope.component.provideUtility(
... manager1, ISchemaManager, name='another.app')
>>> zope.component.provideUtility(
... manager2, ISchemaManager, name='another.app-extension')
Notice how the name of the first package is used to create a namespace
for dependent packages. This is not a requirement of the framework,
but a convenient pattern for this usage.
Let's evolve the database to establish these generations:
>>> event = DatabaseOpenedEventStub(db)
>>> evolveMinimumSubscriber(event)
>>> root[generations_key]['another.app']
0
>>> root[generations_key]['another.app-extension']
0
Let's assume that for some reason each of these subsystems needs to
add a generation, and that generation 1 of 'another.app-extension'
depends on generation 1 of 'another.app'. We'll need to provide
schema managers for each that record that they've been run so we can
verify the result:
>>> gsm.unregisterUtility(provided=ISchemaManager, name='another.app')
True
>>> gsm.unregisterUtility(
... provided=ISchemaManager, name='another.app-extension')
True
>>> @implementer(ISchemaManager)
... class FoundationSchemaManager(object):
...
... minimum_generation = 1
... generation = 1
...
... def evolve(self, context, generation):
... root = context.connection.root()
... ordering = root.get('ordering', [])
... if generation == 1:
... ordering.append('foundation 1')
... print('foundation generation 1')
... else:
... raise ValueError("Bummer")
... root['ordering'] = ordering # ping persistence
>>> @implementer(ISchemaManager)
... class DependentSchemaManager(object):
...
... minimum_generation = 1
... generation = 1
...
... def evolve(self, context, generation):
... root = context.connection.root()
... ordering = root.get('ordering', [])
... if generation == 1:
... ordering.append('dependent 1')
... print('dependent generation 1')
... else:
... raise ValueError("Bummer")
... root['ordering'] = ordering # ping persistence
>>> manager1 = FoundationSchemaManager()
>>> manager2 = DependentSchemaManager()
>>> zope.component.provideUtility(
... manager1, ISchemaManager, name='another.app')
>>> zope.component.provideUtility(
... manager2, ISchemaManager, name='another.app-extension')
Evolving the database now will always run the 'another.app' evolver
before the 'another.app-extension' evolver:
>>> event = DatabaseOpenedEventStub(db)
>>> evolveMinimumSubscriber(event)
foundation generation 1
dependent generation 1
>>> root['ordering']
['foundation 1', 'dependent 1']
Installation
============
In the the example above, we manually initialized the answers. We
shouldn't have to do that manually. The application should be able to
do that automatically.
`~zope.generations.interfaces.IInstallableSchemaManager` extends
`~zope.generations.interfaces.ISchemaManager`, providing an install
method for performing an intial installation of an application. This
is a better alternative than registering database-opened subscribers.
Let's define a new schema manager that includes installation:
>>> gsm.unregisterUtility(provided=ISchemaManager, name='some.app')
True
>>> from zope.generations.interfaces import IInstallableSchemaManager
>>> @implementer(IInstallableSchemaManager)
... class MySchemaManager(object):
...
... minimum_generation = 1
... generation = 2
...
... def install(self, context):
... root = context.connection.root()
... root['answers'] = {'Hello': 'Hi & how do you do?',
... 'Meaning of life?': '42',
... 'four < ?': 'four < five'}
...
... def evolve(self, context, generation):
... root = context.connection.root()
... answers = root['answers']
... if generation == 1:
... for question, answer in answers.items():
... answers[question] = escape(answer)
... elif generation == 2:
... for question, answer in answers.items():
... del answers[question]
... answers[escape(question)] = answer
... else:
... raise ValueError("Bummer")
... root['answers'] = answers # ping persistence
>>> manager = MySchemaManager()
>>> zope.component.provideUtility(manager, ISchemaManager, name='some.app')
Now, lets open a new database:
>>> conn.close()
>>> db.close()
>>> db = DB()
>>> tx = transaction.begin()
>>> conn = db.open()
>>> 'answers' in conn.root()
False
>>> tx.abort()
>>> event = DatabaseOpenedEventStub(db)
>>> evolveMinimumSubscriber(event)
>>> tx = transaction.begin()
>>> root = conn.root()
>>> pprint(root['answers'])
{'Hello': 'Hi & how do you do?',
'Meaning of life?': '42',
'four < ?': 'four < five'}
>>> root[generations_key]['some.app']
2
>>> tx.abort()
>>> conn.close()
The ZODB transaction log notes that our install script was executed
>>> [it.description for it in db.storage.iterator()][-1]
u'some.app: running install generation'
>>> db.close()
| zope.generations | /zope.generations-5.1.0.tar.gz/zope.generations-5.1.0/src/zope/generations/README.rst | README.rst |
"""Interfaces for support for application database generations."""
import zope.interface
class GenerationError(Exception):
"""A database generation is invalid."""
class GenerationTooHigh(GenerationError):
"""A database generation is higher than an application generation."""
class GenerationTooLow(GenerationError):
"""A database generation is lower than application minimum generation."""
class UnableToEvolve(GenerationError):
"""A database can't evolve to an application minimum generation."""
class ISchemaManager(zope.interface.Interface):
"""Manage schema evolution for an application."""
minimum_generation = zope.interface.Attribute(
"Minimum supported schema generation")
generation = zope.interface.Attribute(
"Current schema generation")
def evolve(context, generation):
"""Evolve a database to the given schema generation.
The database should be assumed to be at the schema generation
one less than the given `generation` argument. In other words,
the `evolve` method is only required to make one evolutionary
step.
The `context` argument has a connection attribute, providing a
database connection to be used to change the database. A
`context` argument is passed rather than a connection to make
it possible to provide additional information later, if it
becomes necessary.
This method should *not* commit a transaction. The transaction
will be committed by the caller if there is no error. The
method may create savepoints.
.. versionchanged:: 5.0
Previously this documentation contained a provision for committing
the transaction "if there are no subsequent operations." That
was unclear and incompatible with explicit transaction managers.
Now, this method must *never* commit the transaction.
"""
def getInfo(generation):
"""Return an information string about the evolution that is used to
upgrade to the specified generation.
If no information is available, `None` should be returned.
"""
class IInstallableSchemaManager(ISchemaManager):
"""Manage schema evolution for an application, including installation."""
def install(context):
"""Perform any initial installation tasks
The application has never had the application installed
before. The schema manager should bring the database to the
current generation.
This method should *not* commit a transaction. The transaction
will be committed by the caller if there is no error. The
method may create savepoints.
.. versionchanged:: 5.0
Previously this documentation contained a provision for committing
the transaction "if there are no subsequent operations." That
was unclear and incompatible with explicit transaction managers.
Now, this method must *never* commit the transaction.
""" | zope.generations | /zope.generations-5.1.0.tar.gz/zope.generations-5.1.0/src/zope/generations/interfaces.py | interfaces.py |
"""Support for application database generations."""
import logging
import transaction
import zope.component
import zope.interface
from .interfaces import GenerationTooHigh, GenerationTooLow, UnableToEvolve
from .interfaces import ISchemaManager, IInstallableSchemaManager
logger = logging.getLogger('zope.generations')
old_generations_key = 'zope.app.generations'
generations_key = 'zope.generations'
@zope.interface.implementer(IInstallableSchemaManager)
class SchemaManager(object):
"""Schema manager
Schema managers implement `IInstallableSchemaManager` using
scripts provided as module methods. You create a schema
manager by providing mimumum and maximum generations and a
package providing modules named ``evolveN``, where ``N`` is a
generation number. Each module provides a function, ``evolve``
that evolves a database from the previous generation.
For the sake of the example, we'll use the demo package defined
in here. See the modules there for simple examples of evolution
scripts.
So, if we'll create a SchemaManager:
>>> manager = SchemaManager(1, 3, 'zope.generations.demo')
and we'll create a test database and context:
>>> from ZODB.MappingStorage import DB
>>> db = DB()
>>> context = Context()
>>> context.connection = db.open()
Then we'll evolve the database from generation 1 to 3:
>>> import transaction
>>> tx = transaction.begin()
>>> manager.evolve(context, 2)
>>> manager.evolve(context, 3)
>>> tx.commit()
The demo evolvers simply record their data in a root key:
>>> from zope.generations.demo import key
>>> tx = transaction.begin()
>>> conn = db.open()
>>> conn.root()[key]
(2, 3)
You can get the information for each evolver by specifying the
destination generation of the evolver as argument to the `getInfo()`
method:
>>> manager.getInfo(1)
'Evolver 1'
>>> manager.getInfo(2)
'Evolver 2'
>>> manager.getInfo(3) is None
True
If a package provides an install script, then it will be called
when the manager's intall method is called:
>>> tx.abort()
>>> tx = transaction.begin()
>>> del conn.root()[key]
>>> tx.commit()
>>> tx = transaction.begin()
>>> conn.root().get(key)
>>> manager.install(context)
>>> tx.commit()
>>> tx = transaction.begin()
>>> conn.root()[key]
('installed',)
If there is not install script, the manager will do nothing on
an install:
>>> manager = SchemaManager(1, 3, 'zope.generations.demo2')
>>> manager.install(context)
We handle ImportErrors within the script specially, so they get
promoted:
>>> manager = SchemaManager(1, 3, 'zope.generations.demo3')
>>> manager.install(context)
Traceback (most recent call last):
ImportError: No module named nonexistingmodule
We'd better clean up:
>>> tx.abort()
>>> context.connection.close()
>>> conn.close()
>>> db.close()
"""
def __init__(self, minimum_generation=0, generation=0, package_name=None):
if generation < minimum_generation:
raise ValueError("generation is less than minimum_generation",
generation, minimum_generation)
if minimum_generation < 0:
raise ValueError("generations must be non-negative",
minimum_generation)
if generation and not package_name:
raise ValueError("A package name must be supplied if the"
" generation is non-zero")
self.minimum_generation = minimum_generation
self.generation = generation
self.package_name = package_name
def evolve(self, context, generation):
"""Evolve a database to reflect software/schema changes."""
name = "%s.evolve%d" % (self.package_name, generation)
evolver = __import__(name, {}, {}, ['*'])
evolver.evolve(context)
def install(self, context):
"""Evolve a database to reflect software/schema changes."""
if self.package_name is None:
return
name = "%s.install" % self.package_name
try:
evolver = __import__(name, {}, {}, ['*'])
except ImportError as m:
if str(m) not in ('No module named %s' % name,
"No module named '%s'" % name,
'No module named install'):
# This was an import error *within* the module, so we re-raise.
raise
else:
evolver.evolve(context)
def getInfo(self, generation):
"""Get the information from the evolver function's doc string."""
evolver = __import__(
"%s.evolve%d" % (self.package_name, generation),
{}, {}, ['*'])
return evolver.evolve.__doc__
class Context(object):
connection = None
def findManagers():
# Hook to let Chris use this for Zope 2
return zope.component.getUtilitiesFor(ISchemaManager)
def PersistentDict():
# Another hook to let Chris use this for Zope 2
import persistent.mapping
return persistent.mapping.PersistentMapping()
#: Constant for the *how* argument to `evolve` indicating
#: to evolve to the current generation.
#:
#: .. seealso:: `evolveSubscriber`
EVOLVE = 'EVOLVE'
#: Constant for the *how* argument to `evolve` indicating
#: to perform no evolutions.
#:
#: .. seealso:: `evolveNotSubscriber`
EVOLVENOT = 'EVOLVENOT'
#: Constant for the *how* argument to `evolve` indicating
#: to evolve to the minimum required generation.
#:
#: .. seealso:: `evolveMinimumSubscriber`
EVOLVEMINIMUM = 'EVOLVEMINIMUM'
def evolve(db, how=EVOLVE):
"""Evolve a database
We evolve a database using registered application schema managers.
Here's an example (silly) schema manager:
>>> from zope.generations.interfaces import ISchemaManager
>>> @zope.interface.implementer(ISchemaManager)
... class FauxApp(object):
...
... erron = None # Raise an error is asked to evolve to this
...
... def __init__(self, name, minimum_generation, generation):
... self.name, self.generation = name, generation
... self.minimum_generation = minimum_generation
...
... def evolve(self, context, generation):
... if generation == self.erron:
... raise ValueError(generation)
...
... context.connection.root()[self.name] = generation
Evolving a database will cause log messages to be written, so we need a
logging handler:
>>> from zope.testing import loggingsupport
>>> loghandler = loggingsupport.InstalledHandler('zope.generations')
>>> def print_log():
... print(loghandler)
... loghandler.clear()
Now, we'll create and register some handlers:
>>> import zope.component
>>> app1 = FauxApp('app1', 0, 1)
>>> zope.component.provideUtility(app1, ISchemaManager, name='app1')
>>> app2 = FauxApp('app2', 5, 11)
>>> zope.component.provideUtility(app2, ISchemaManager, name='app2')
If we create a new database, and evolve it, we'll simply update
the generation data:
>>> from ZODB.MappingStorage import DB
>>> db = DB(database_name='testdb')
>>> evolve(db)
>>> conn = db.open()
>>> root = conn.root()
>>> root[generations_key]['app1']
1
>>> root[generations_key]['app2']
11
>>> print_log()
zope.generations INFO
testdb: evolving in mode EVOLVE
But nothing will have been done to the database:
>>> root.get('app1')
>>> root.get('app2')
Now if we increase the generation of one of the apps:
>>> app1.generation += 1
>>> evolve(db)
>>> print_log()
zope.generations INFO
testdb: evolving in mode EVOLVE
zope.generations INFO
testdb/app1: currently at generation 1, targetting generation 2
zope.generations DEBUG
testdb/app1: evolving to generation 2
zope.generations DEBUG
testdb/app2: up-to-date at generation 11
We'll see that the generation data has updated:
>>> root[generations_key]['app1']
2
>>> root[generations_key]['app2']
11
And that the database was updated for that application:
>>> root.get('app1')
2
>>> root.get('app2')
And that the transaction record got a note
>>> [it.description for it in conn.db().storage.iterator()][-1]
u'app1: evolving to generation 2'
If there is an error updating a particular generation, but the
generation is greater than the minimum generation, then we won't
get an error from evolve, but we will get a log message.
>>> app1.erron = 4
>>> app1.generation = 7
>>> evolve(db)
>>> print_log()
zope.generations INFO
testdb: evolving in mode EVOLVE
zope.generations INFO
testdb/app1: currently at generation 2, targetting generation 7
zope.generations DEBUG
testdb/app1: evolving to generation 3
zope.generations DEBUG
testdb/app1: evolving to generation 4
zope.generations ERROR
testdb/app1: failed to evolve to generation 4
zope.generations DEBUG
testdb/app2: up-to-date at generation 11
The database will have been updated for previous generations:
>>> root[generations_key]['app1']
3
>>> root.get('app1')
3
If we set the minimum generation for app1 to something greater than 3:
>>> app1.minimum_generation = 4
Then we'll get an error if we try to evolve, since we can't get
past 3 and 3 is less than 4:
>>> evolve(db)
Traceback (most recent call last):
...
UnableToEvolve: (4, u'app1', 7)
We'll also get a log entry:
>>> print_log()
zope.generations INFO
testdb: evolving in mode EVOLVE
zope.generations INFO
testdb/app1: currently at generation 3, targetting generation 7
zope.generations DEBUG
testdb/app1: evolving to generation 4
zope.generations ERROR
testdb/app1: failed to evolve to generation 4
So far, we've used evolve in its default policy, in which we evolve
as far as we can up to the current generation. There are two
other policies:
EVOLVENOT -- Don't evolve, but make sure that the application is
at the minimum generation
EVOLVEMINIMUM -- Evolve only to the minimum generation
Let's change unset erron for app1 so we don't get an error when we
try to evolve.
>>> app1.erron = None
Now, we'll call evolve with EVOLVENOT:
>>> evolve(db, EVOLVENOT)
Traceback (most recent call last):
...
GenerationTooLow: (3, u'app1', 4)
>>> print_log()
zope.generations INFO
testdb: evolving in mode EVOLVENOT
zope.generations ERROR
testdb/app1: current generation too low (3 < 4) but mode is EVOLVENOT
We got an error because we aren't at the minimum generation for
app1. The database generation for app1 is still 3 because we
didn't do any evolution:
>>> root[generations_key]['app1']
3
>>> root.get('app1')
3
Now, if we use EVOLVEMINIMUM instead, we'll evolve to the minimum
generation:
>>> evolve(db, EVOLVEMINIMUM)
>>> root[generations_key]['app1']
4
>>> root.get('app1')
4
>>> print_log()
zope.generations INFO
testdb: evolving in mode EVOLVEMINIMUM
zope.generations INFO
testdb/app1: currently at generation 3, targetting generation 4
zope.generations DEBUG
testdb/app1: evolving to generation 4
zope.generations DEBUG
testdb/app2: up-to-date at generation 11
If we happen to install an app that has a generation that is less
than the database generation, we'll get an error, because there is
no way to get the database to a generation that the app
understands:
>>> app1.generation = 2
>>> app1.minimum_generation = 0
>>> evolve(db)
Traceback (most recent call last):
...
GenerationTooHigh: (4, u'app1', 2)
>>> print_log()
zope.generations INFO
testdb: evolving in mode EVOLVE
zope.generations ERROR
testdb/app1: current generation too high (4 > 2)
We'd better clean up:
>>> from zope.testing.cleanup import tearDown
>>> loghandler.uninstall()
>>> conn.close()
>>> db.close()
>>> tearDown()
"""
db_name = db.database_name or 'main db'
logger.info('%s: evolving in mode %s',
db_name, how)
conn = db.open()
try:
context = Context()
context.connection = conn
with transaction.manager:
root = conn.root()
generations = root.get(generations_key)
if generations is None:
# backward compatibility with zope.app.generations
generations = root.get(old_generations_key)
if generations is not None:
# switch over to new generations_key
root[generations_key] = generations
else:
generations = root[generations_key] = PersistentDict()
for key, manager in sorted(findManagers()):
with transaction.manager as tx:
generation = generations.get(key)
if generation == manager.generation:
logger.debug('%s/%s: up-to-date at generation %s',
db_name, key, generation)
continue
if generation is None:
# This is a new database, so no old data
if IInstallableSchemaManager.providedBy(manager):
try:
tx.note('%s: running install generation'
% key)
logger.info("%s/%s: running install generation",
db_name, key)
manager.install(context)
except: # noqa: E722 do not use bare 'except'
logger.exception("%s/%s: failed to run install",
db_name, key)
raise
generations[key] = manager.generation
continue
if generation > manager.generation:
logger.error('%s/%s: current generation too high (%d > %d)',
db_name, key,
generation, manager.generation)
raise GenerationTooHigh(generation, key, manager.generation)
if generation < manager.minimum_generation:
if how == EVOLVENOT:
logger.error('%s/%s: current generation too low '
'(%d < %d) but mode is %s',
db_name, key,
generation, manager.minimum_generation,
how)
raise GenerationTooLow(
generation, key, manager.minimum_generation)
else:
if how != EVOLVE:
continue
if how == EVOLVEMINIMUM:
target = manager.minimum_generation
else:
target = manager.generation
logger.info(
'%s/%s: currently at generation %d, targetting generation %d',
db_name, key, generation, target)
while generation < target:
generation += 1
tx = transaction.begin()
try:
tx.note('%s: evolving to generation %d'
% (key, generation))
logger.debug('%s/%s: evolving to generation %d',
db_name, key, generation)
manager.evolve(context, generation)
generations[key] = generation
tx.commit()
except: # noqa: E722 do not use bare 'except'
# An unguarded handler is intended here
tx.abort()
logger.exception(
"%s/%s: failed to evolve to generation %d",
db_name, key, generation)
if generation <= manager.minimum_generation:
raise UnableToEvolve(generation, key,
manager.generation)
break
finally:
conn.close()
def evolveSubscriber(event):
"""
A subscriber for :class:`zope.processlifetime.IDatabaseOpenedWithRoot` that
evolves all components to their current generation.
If you want to use this subscriber, you must register it.
"""
evolve(event.database, EVOLVE)
def evolveNotSubscriber(event):
"""
A subscriber for :class:`zope.processlifetime.IDatabaseOpenedWithRoot` that
does no evolution, merele verifying that all components are at the required
minimum version.
If you want to use this subscriber, you must register it.
"""
evolve(event.database, EVOLVENOT)
def evolveMinimumSubscriber(event):
"""
A subscriber for :class:`zope.processlifetime.IDatabaseOpenedWithRoot` that
evolves all components to their required minimum version.
This is registered in this package's ``subscriber.zcml`` file.
"""
evolve(event.database, EVOLVEMINIMUM) | zope.generations | /zope.generations-5.1.0.tar.gz/zope.generations-5.1.0/src/zope/generations/generations.py | generations.py |
def findObjectsMatching(root, condition):
"""Find all objects in the root that match the condition.
The condition is a callable Python object that takes an object as an
argument and must return `True` or `False`.
All sub-objects of the root will also be searched recursively. All mapping
objects providing ``values()`` are supported.
Example:
>>> class A(dict):
... def __init__(self, name):
... self.name = name
>>> class B(dict):
... def __init__(self, name):
... self.name = name
>>> class C(dict):
... def __init__(self, name):
... self.name = name
>>> tree = A('a1')
>>> tree['b1'] = B('b1')
>>> tree['c1'] = C('c1')
>>> tree['b1']['a2'] = A('a2')
>>> tree['b1']['b2'] = B('b2')
>>> tree['b1']['b2']['c2'] = C('c2')
>>> tree['b1']['b2']['a3'] = A('a3')
Find all instances of class A:
>>> matches = findObjectsMatching(tree, lambda x: isinstance(x, A))
>>> names = [x.name for x in matches]
>>> names.sort()
>>> names
['a1', 'a2', 'a3']
Find all objects having a '2' in the name:
>>> matches = findObjectsMatching(tree, lambda x: '2' in x.name)
>>> names = [x.name for x in matches]
>>> names.sort()
>>> names
['a2', 'b2', 'c2']
If there is no ``values`` on the root, we stop:
>>> root = [1, 2, 3]
>>> found = list(findObjectsMatching(root, lambda x: True))
>>> found == [root]
True
"""
if condition(root):
yield root
if hasattr(root, 'values'):
for subobj in root.values():
for match in findObjectsMatching(subobj, condition):
yield match
def findObjectsProviding(root, interface):
"""Find all objects in the root that provide the specified interface.
All sub-objects of the root will also be searched recursively.
Example:
>>> from zope.interface import Interface, implementer
>>> class IA(Interface):
... pass
>>> class IB(Interface):
... pass
>>> class IC(IA):
... pass
>>> @implementer(IA)
... class A(dict):
... def __init__(self, name):
... self.name = name
>>> @implementer(IB)
... class B(dict):
... def __init__(self, name):
... self.name = name
>>> @implementer(IC)
... class C(dict):
... def __init__(self, name):
... self.name = name
>>> tree = A('a1')
>>> tree['b1'] = B('b1')
>>> tree['c1'] = C('c1')
>>> tree['b1']['a2'] = A('a2')
>>> tree['b1']['b2'] = B('b2')
>>> tree['b1']['b2']['c2'] = C('c2')
>>> tree['b1']['b2']['a3'] = A('a3')
Find all objects that provide IB:
>>> matches = findObjectsProviding(tree, IB)
>>> names = [x.name for x in matches]
>>> names.sort()
>>> names
['b1', 'b2']
Find all objects that provide IA:
>>> matches = findObjectsProviding(tree, IA)
>>> names = [x.name for x in matches]
>>> names.sort()
>>> names
['a1', 'a2', 'a3', 'c1', 'c2']
"""
for match in findObjectsMatching(root, interface.providedBy):
yield match
try:
import zope.app.publication.zopepublication
except ImportError:
# 'Application' is what ZopePublication uses, up through at least
# 4.3.1
#: The name of the root folder.
#: If ``zope.app.publication.zopepublication`` is available,
#: this is imported from there.
ROOT_NAME = 'Application'
else: # pragma: no cover
#: The name of the root folder.
#: If ``zope.app.publication.zopepublication`` is available,
#: this is imported from there.
ROOT_NAME = zope.app.publication.zopepublication.ZopePublication.root_name
def getRootFolder(context):
"""Get the root folder of the ZODB.
We need some set up. Create a database:
>>> from ZODB.MappingStorage import DB
>>> from zope.generations.generations import Context
>>> import transaction
>>> db = DB()
>>> context = Context()
>>> tx = transaction.begin()
>>> context.connection = db.open()
>>> root = context.connection.root()
Add a root folder:
>>> from zope.site.folder import rootFolder
>>> root[ROOT_NAME] = rootFolder()
>>> tx.commit()
>>> tx = transaction.begin()
Now we can get the root folder using the function:
>>> getRootFolder(context) # doctest: +ELLIPSIS
<zope.site.folder.Folder object at ...>
We'd better clean up:
>>> tx.abort()
>>> context.connection.close()
>>> db.close()
"""
return context.connection.root().get(ROOT_NAME, None) | zope.generations | /zope.generations-5.1.0.tar.gz/zope.generations-5.1.0/src/zope/generations/utility.py | utility.py |
===================
API Documentation
===================
.. there's actually nothing present in this module,
but it provides a place to link to.
.. automodule:: zope.generations
zope.generations.interfaces
===========================
.. automodule:: zope.generations.interfaces
zope.generations.generations
============================
.. automodule:: zope.generations.generations
zope.generations.utility
========================
.. automodule:: zope.generations.utility
Configuration
=============
There are two ZCML files included in this package.
configure.zcml
--------------
.. literalinclude:: ../src/zope/generations/configure.zcml
:language: xml
subscriber.zcml
---------------
.. literalinclude:: ../src/zope/generations/subscriber.zcml
:language: xml
| zope.generations | /zope.generations-5.1.0.tar.gz/zope.generations-5.1.0/docs/api.rst | api.rst |
__docformat__ = "reStructuredText"
import datetime
import zope.lifecycleevent
import zope.event
import zope.file.contenttype
import zope.file.interfaces
import zope.formlib.form
import zope.html.field
import zope.html.interfaces
import zope.mimetype.interfaces
from zope import mimetype
from zope.interface.common import idatetime
from i18n import _
UNIVERSAL_CHARSETS = ("utf-8", "utf-16", "utf-16be", "utf-16le")
def get_rendered_text(form):
f = form.context.open("r")
data = f.read()
f.close()
ci = mimetype.interfaces.IContentInfo(form.context)
return ci.decode(data)
class BaseEditingView(zope.formlib.form.Form):
# initial value helpers:
def get_rendered_isFragment(self):
info = zope.html.interfaces.IEditableHtmlInformation(self.context)
return info.isFragment
def get_rendered_encoding(self):
charset = self.context.parameters.get("charset")
if charset:
return zope.component.queryUtility(
mimetype.interfaces.ICharsetCodec, charset)
else:
return None
# field definitions:
view_fields = zope.formlib.form.Fields(
zope.html.interfaces.IEditableHtmlInformation,
)
view_fields["isFragment"].get_rendered = get_rendered_isFragment
encoding_field = zope.formlib.form.Field(
zope.schema.Choice(
__name__=_("encoding"),
title=_("Encoding"),
description=_("Character data encoding"),
source=mimetype.source.codecSource,
required=False,
))
encoding_field.get_rendered = get_rendered_encoding
reencode_field = zope.formlib.form.Field(
zope.schema.Bool(
__name__="reencode",
title=_("Re-encode"),
description=_("Enable encoding the text using UTF-8"
" instead of the original encoding."),
default=False,
)
)
msgCannotDecodeText = _("Can't decode text for editing; please specify"
" the document encoding.")
def setUpWidgets(self, ignore_request=False):
ci = mimetype.interfaces.IContentInfo(self.context)
self.have_text = "charset" in ci.effectiveParameters
fields = [self.view_fields]
if self.have_text:
if self.get_rendered_isFragment():
text_field = self.fragment_field
else:
text_field = self.document_field
fields.append(text_field)
if ci.effectiveParameters.get("charset") not in UNIVERSAL_CHARSETS:
fields.append(self.reencode_field)
else:
if not self.status:
self.status = self.msgCannotDecodeText
fields.append(self.encoding_field)
self.form_fields = zope.formlib.form.Fields(*fields)
super(BaseEditingView, self).setUpWidgets(
ignore_request=ignore_request)
def save_validator(self, action, data):
errs = self.validate(None, data)
if not self.have_text:
ifaces = zope.interface.providedBy(
zope.security.proxy.removeSecurityProxy(self.context))
for iface in ifaces:
if mimetype.interfaces.IContentTypeInterface.providedBy(iface):
break
else:
# Should never happen!
assert False, "this view has been mis-registered!"
errs += zope.file.contenttype.validateCodecUse(
self.context, iface, data.get("encoding"),
self.encoding_field)
return errs
@zope.formlib.form.action(_("Save"), validator=save_validator)
def save(self, action, data):
changed = False
context = self.context
if self.have_text:
changed = self.handle_text_update(data)
else:
# maybe we have a new encoding?
codec = data["encoding"]
if codec is None:
self.status = self.msgCannotDecodeText
else:
if "charset" in context.parameters:
old_codec = zope.component.queryUtility(
mimetype.interfaces.ICharsetCodec,
context.parameters["charset"])
else:
old_codec = None
if getattr(old_codec, "name", None) != codec.name:
# use the preferred charset for the new codec
new_charset = zope.component.getUtility(
mimetype.interfaces.ICodecPreferredCharset,
codec.name)
parameters = dict(context.parameters)
parameters["charset"] = new_charset.name
context.parameters = parameters
changed = True
# Deal with the isFragment flag:
info = zope.html.interfaces.IEditableHtmlInformation(context)
isFragment = data["isFragment"]
if isFragment != info.isFragment:
info.isFragment = data["isFragment"]
changed = True
# Set the status message:
if changed:
# Should this get done if only the isFragment changed?
zope.event.notify(
zope.lifecycleevent.ObjectModifiedEvent(context))
formatter = self.request.locale.dates.getFormatter(
'dateTime', 'medium')
now = datetime.datetime.now(idatetime.ITZInfo(self.request))
self.status = _("Updated on ${date_time}",
mapping={'date_time': formatter.format(now)})
elif not self.status:
self.status = _('No changes')
def handle_text_update(self, data):
text = data["text"]
if text != get_rendered_text(self):
ci = mimetype.interfaces.IContentInfo(self.context)
codec = ci.getCodec()
try:
textdata, consumed = codec.encode(text)
if consumed != len(text):
# XXX borked!
pass
except:
# The old encoding will no longer support the data, so
# switch to UTF-8:
if data.get("reencode"):
textdata = text.encode("utf-8")
parameters = dict(self.context.parameters)
parameters["charset"] = "utf-8"
self.context.parameters = parameters
else:
encoding = ci.effectiveParameters["charset"]
self.status = _(
"Can't encode text in current encoding (${encoding})"
"; check 'Re-encode' to enable conversion to UTF-8.",
mapping={"encoding": encoding})
self.form_reset = False
return False
# need to discard re-encode checkbox
f = self.context.open("w")
f.write(textdata)
f.close()
return True
class HtmlEditingView(BaseEditingView):
"""Editing view for HTML content."""
document_field = zope.formlib.form.Field(
zope.html.field.HtmlDocument(
__name__="text",
title=_("Text"),
description=_("Text of the document being edited."),
)
)
document_field.get_rendered = get_rendered_text
fragment_field = zope.formlib.form.Field(
zope.html.field.HtmlFragment(
__name__="text",
title=_("Text"),
description=_("Text of the fragment being edited."),
)
)
fragment_field.get_rendered = get_rendered_text
class XhtmlEditingView(BaseEditingView):
"""Editing view for XHTML content."""
document_field = zope.formlib.form.Field(
zope.html.field.XhtmlDocument(
__name__="text",
title=_("Text"),
description=_("Text of the document being edited."),
)
)
document_field.get_rendered = get_rendered_text
fragment_field = zope.formlib.form.Field(
zope.html.field.XhtmlFragment(
__name__="text",
title=_("Text"),
description=_("Text of the fragment being edited."),
)
)
fragment_field.get_rendered = get_rendered_text | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/browser.py | browser.py |
__docformat__ = "reStructuredText"
import zope.formlib
import zc.resourcelibrary
class FckeditorWidget(zope.formlib.widgets.TextAreaWidget):
editorWidth = 600
editorHeight = 400
fckVersion = '2.6.4.1'
configurationPath = "/@@/zope_fckconfig.js"
toolbarConfiguration = "zope"
def __call__(self):
zc.resourcelibrary.need("fckeditor")
#
# XXX The 'shortname' here needs some salt to ensure that
# multiple widgets with the same trailing name are
# distinguishable; some encoding of the full name seems
# appropriate, or a per-request counter would also do nicely.
#
d = {
"config": self.configurationPath,
"name": self.name,
"shortname": self.name.split('.', 1)[-1],
"toolbars": self.toolbarConfiguration,
"width": self.editorWidth,
"height": self.editorHeight,
"fckversion": self.fckVersion,
}
textarea = super(FckeditorWidget, self).__call__()
return textarea + (self.javascriptTemplate % d)
javascriptTemplate = '''
<script type="text/javascript" language="JavaScript">
var oFCKeditor_%(shortname)s = new FCKeditor(
"%(name)s", %(width)s, %(height)s, "%(toolbars)s");
oFCKeditor_%(shortname)s.BasePath = "/@@/fckeditor/%(fckversion)s/fckeditor/";
oFCKeditor_%(shortname)s.Config["CustomConfigurationsPath"] = "%(config)s";
oFCKeditor_%(shortname)s.ReplaceTextarea();
</script>
'''
class CkeditorWidget(zope.formlib.widgets.TextAreaWidget):
editorHeight = 400
fckVersion = '3.6.2'
configurationPath = "/@@/zope_ckconfig.js"
def __call__(self):
zc.resourcelibrary.need("ckeditor")
#
# XXX The 'shortname' here needs some salt to ensure that
# multiple widgets with the same trailing name are
# distinguishable; some encoding of the full name seems
# appropriate, or a per-request counter would also do nicely.
#
d = {
"config": self.configurationPath,
"name": self.name,
"shortname": self.name.split('.', 1)[-1],
"height": self.editorHeight,
"fckversion": self.fckVersion,
}
textarea = super(CkeditorWidget, self).__call__()
return textarea + (self.javascriptTemplate % d)
javascriptTemplate = '''
<script type="text/javascript" language="JavaScript">
var CKeditor_%(shortname)s = new CKEDITOR.replace("%(name)s",
{
height: %(height)s,
customConfig : "%(config)s",
}
);
</script>
''' | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/widget.py | widget.py |
=========================
HTML file editing support
=========================
This package contains support for editing HTML and XHTML inside a web
page using the FCKeditor as a widget. This is a fairly simple
application of FCKeditor, and simply instantiates a pre-configured
editor for each widget. There are no options to control the editors
individually.
In creating this, we ran into some limitations of the editor that are
worth being aware of. Noting these as limitations does not mean that
other editors do any better; what's available seems to be a mixed bag.
- The editor only deals with what can be contained inside a <body>
element; anything that goes outside that, including the <body> and
</body> tags, get lost or damaged. If there's any way to configure
FCKeditor to deal with such material, it isn't documented.
- There's no real control of the HTML source; whitespace is not
preserved as a programmer would expect. That's acceptable in many
use cases, but not all. Applications should avoid using this widget
if the original whitespace must be maintained.
Implementation problems
-----------------------
These are problems with the widget used to integrate FCKeditor rather
than problems with FCKeditor itself. These should be dealt with.
- The width of the editor is hardcoded; this should be either
configurable or the editor should stretch to fill the available
space. The sample uses of the FCKeditor don't seem to exhibit this
problem, so it can be better than it is.
- The height of the editor should be configurable in a way similar to
the configuration of the basic textarea widget.
Ideas for future development
----------------------------
These ideas might be interesting to pursue, but there are no specific
plans to do so at this time:
- Categorize the applications of the editor and provide alternate
toolbar configurations for those applications. There's a lot of
configurability in the editor itself, so it can be made to do
different things.
- Add support for some of the other fancy client-side HTML editors,
and allow a user preference to select which to use for what
applications, including the option of disabling the GUI editors when
detailed control over the HTML is needed (or for luddite users who
don't like the GUI editors).
XINHA (http://xinha.python-hosting.com/) appears to be an
interesting option as well, and may be more usable for applications
that want more than editing of small HTML fragments, especially if
the user is fairly HTML-savvy.
HTMLArea (http://www.dynarch.com/projects/htmlarea/) may become
interesting at some point, but a rough reading at this time
indicates that XINHA may be a more reasonable route.
More information about FCKeditor
--------------------------------
- http://www.fckeditor.net/
- http://discerning.com/topics/software/ttw.html
- http://www.phpsolvent.com/wordpress/?page_id=330
| zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/README.txt | README.txt |
__docformat__ = "reStructuredText"
import HTMLParser
import xml.parsers.expat
import persistent.dict
import zope.annotation.interfaces
import zope.file.interfaces
import zope.html.interfaces
import zope.interface
import zope.mimetype.types
# Use the package name as the annotation key:
KEY = __name__.rsplit(".", 1)[0]
class EditableHtmlInformation(object):
zope.interface.implements(
zope.html.interfaces.IEditableHtmlInformation)
_annotations = None
def __init__(self, file):
self.__parent__ = file
self.context = file
def _get_annotation(self):
if self._annotations is None:
self._annotations = zope.annotation.interfaces.IAnnotations(
self.context)
return self._annotations.get(KEY)
def _get_isFragment(self):
annotation = self._get_annotation()
if annotation is not None:
if "is_fragment" in annotation:
return annotation["is_fragment"]
# compute from data
f = zope.file.interfaces.IFile(self.context)
if zope.mimetype.types.IContentTypeTextHtml.providedBy(self.context):
isfrag = _is_html_fragment(f)
else:
isfrag = _is_xhtml_fragment(f)
return isfrag
def _set_isFragment(self, value):
value = bool(value)
if value != self.isFragment:
annotation = self._get_annotation()
if annotation is None:
annotation = persistent.dict.PersistentDict()
annotation["is_fragment"] = value
self._annotations[KEY] = annotation
isFragment = property(_get_isFragment, _set_isFragment)
def _is_xhtml_fragment(file):
f = file.open("r")
p = xml.parsers.expat.ParserCreate()
h = HTMLContentSniffer()
p.StartElementHandler = h.handle_starttag
p.CharacterDataHandler = h.handle_data
try:
p.Parse(f.read(2048))
except xml.parsers.expat.ExpatError:
# well-formedness failure; don't even pretend it might be a
# document (might not be a useful fragment either, though)
return True
return p.leading_content or p.first_element != "html"
def _is_html_fragment(file):
"""Return True iff `file` represents an HTML fragment."""
f = file.open("r")
p = HTMLContentSniffer()
p.feed(f.read(2048))
return p.leading_content or p.first_element != "html"
class HTMLContentSniffer(HTMLParser.HTMLParser):
first_element = None
leading_content = None
def handle_starttag(self, name, attrs):
if not self.first_element:
self.first_element = name
def handle_data(self, data):
if not self.first_element:
data = data.strip()
if data:
self.leading_content = True | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/docinfo.py | docinfo.py |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function(){if(window.CKEDITOR&&window.CKEDITOR.dom)return;if(!window.CKEDITOR)window.CKEDITOR=(function(){var a={timestamp:'B8DJ5M3',version:'3.6.2',revision:'7275',_:{},status:'unloaded',basePath:(function(){var d=window.CKEDITOR_BASEPATH||'';if(!d){var e=document.getElementsByTagName('script');for(var f=0;f<e.length;f++){var g=e[f].src.match(/(^|.*[\\\/])ckeditor(?:_basic)?(?:_source)?.js(?:\?.*)?$/i);if(g){d=g[1];break;}}}if(d.indexOf(':/')==-1)if(d.indexOf('/')===0)d=location.href.match(/^.*?:\/\/[^\/]*/)[0]+d;else d=location.href.match(/^[^\?]*\/(?:)/)[0]+d;if(!d)throw 'The CKEditor installation path could not be automatically detected. Please set the global variable "CKEDITOR_BASEPATH" before creating editor instances.';return d;})(),getUrl:function(d){if(d.indexOf(':/')==-1&&d.indexOf('/')!==0)d=this.basePath+d;if(this.timestamp&&d.charAt(d.length-1)!='/'&&!/[&?]t=/.test(d))d+=(d.indexOf('?')>=0?'&':'?')+'t='+this.timestamp;return d;}},b=window.CKEDITOR_GETURL;if(b){var c=a.getUrl;a.getUrl=function(d){return b.call(a,d)||c.call(a,d);};}return a;})();var a=CKEDITOR;if(!a.event){a.event=function(){};a.event.implementOn=function(b){var c=a.event.prototype;for(var d in c){if(b[d]==undefined)b[d]=c[d];}};a.event.prototype=(function(){var b=function(d){var e=d.getPrivate&&d.getPrivate()||d._||(d._={});return e.events||(e.events={});},c=function(d){this.name=d;this.listeners=[];};c.prototype={getListenerIndex:function(d){for(var e=0,f=this.listeners;e<f.length;e++){if(f[e].fn==d)return e;}return-1;}};return{on:function(d,e,f,g,h){var i=b(this),j=i[d]||(i[d]=new c(d));if(j.getListenerIndex(e)<0){var k=j.listeners;if(!f)f=this;if(isNaN(h))h=10;var l=this,m=function(o,p,q,r){var s={name:d,sender:this,editor:o,data:p,listenerData:g,stop:q,cancel:r,removeListener:function(){l.removeListener(d,e);}};e.call(f,s);return s.data;};m.fn=e;m.priority=h;for(var n=k.length-1;n>=0;n--){if(k[n].priority<=h){k.splice(n+1,0,m);return;}}k.unshift(m);}},fire:(function(){var d=false,e=function(){d=true;},f=false,g=function(){f=true;};return function(h,i,j){var k=b(this)[h],l=d,m=f;d=f=false;if(k){var n=k.listeners;if(n.length){n=n.slice(0);for(var o=0;o<n.length;o++){var p=n[o].call(this,j,i,e,g);if(typeof p!='undefined')i=p;if(d||f)break;}}}var q=f||(typeof i=='undefined'?false:i);d=l;f=m;return q;};})(),fireOnce:function(d,e,f){var g=this.fire(d,e,f);delete b(this)[d];return g;},removeListener:function(d,e){var f=b(this)[d];if(f){var g=f.getListenerIndex(e);if(g>=0)f.listeners.splice(g,1);
}},hasListeners:function(d){var e=b(this)[d];return e&&e.listeners.length>0;}};})();}if(!a.editor){a.ELEMENT_MODE_NONE=0;a.ELEMENT_MODE_REPLACE=1;a.ELEMENT_MODE_APPENDTO=2;a.editor=function(b,c,d,e){var f=this;f._={instanceConfig:b,element:c,data:e};f.elementMode=d||0;a.event.call(f);f._init();};a.editor.replace=function(b,c){var d=b;if(typeof d!='object'){d=document.getElementById(b);if(d&&d.tagName.toLowerCase() in {style:1,script:1,base:1,link:1,meta:1,title:1})d=null;if(!d){var e=0,f=document.getElementsByName(b);while((d=f[e++])&&d.tagName.toLowerCase()!='textarea'){}}if(!d)throw '[CKEDITOR.editor.replace] The element with id or name "'+b+'" was not found.';}d.style.visibility='hidden';return new a.editor(c,d,1);};a.editor.appendTo=function(b,c,d){var e=b;if(typeof e!='object'){e=document.getElementById(b);if(!e)throw '[CKEDITOR.editor.appendTo] The element with id "'+b+'" was not found.';}return new a.editor(c,e,2,d);};a.editor.prototype={_init:function(){var b=a.editor._pending||(a.editor._pending=[]);b.push(this);},fire:function(b,c){return a.event.prototype.fire.call(this,b,c,this);},fireOnce:function(b,c){return a.event.prototype.fireOnce.call(this,b,c,this);}};a.event.implementOn(a.editor.prototype,true);}if(!a.env)a.env=(function(){var b=navigator.userAgent.toLowerCase(),c=window.opera,d={ie:/*@cc_on!@*/false,opera:!!c&&c.version,webkit:b.indexOf(' applewebkit/')>-1,air:b.indexOf(' adobeair/')>-1,mac:b.indexOf('macintosh')>-1,quirks:document.compatMode=='BackCompat',mobile:b.indexOf('mobile')>-1,iOS:/(ipad|iphone|ipod)/.test(b),isCustomDomain:function(){if(!this.ie)return false;var g=document.domain,h=window.location.hostname;return g!=h&&g!='['+h+']';},secure:location.protocol=='https:'};d.gecko=navigator.product=='Gecko'&&!d.webkit&&!d.opera;var e=0;if(d.ie){e=parseFloat(b.match(/msie (\d+)/)[1]);d.ie8=!!document.documentMode;d.ie8Compat=document.documentMode==8;d.ie9Compat=document.documentMode==9;d.ie7Compat=e==7&&!document.documentMode||document.documentMode==7;d.ie6Compat=e<7||d.quirks;}if(d.gecko){var f=b.match(/rv:([\d\.]+)/);if(f){f=f[1].split('.');e=f[0]*10000+(f[1]||0)*100+ +(f[2]||0);}}if(d.opera)e=parseFloat(c.version());if(d.air)e=parseFloat(b.match(/ adobeair\/(\d+)/)[1]);if(d.webkit)e=parseFloat(b.match(/ applewebkit\/(\d+)/)[1]);d.version=e;d.isCompatible=d.iOS&&e>=534||!d.mobile&&(d.ie&&e>=6||d.gecko&&e>=10801||d.opera&&e>=9.5||d.air&&e>=1||d.webkit&&e>=522||false);d.cssClass='cke_browser_'+(d.ie?'ie':d.gecko?'gecko':d.opera?'opera':d.webkit?'webkit':'unknown');
if(d.quirks)d.cssClass+=' cke_browser_quirks';if(d.ie){d.cssClass+=' cke_browser_ie'+(d.version<7?'6':d.version>=8?document.documentMode:'7');if(d.quirks)d.cssClass+=' cke_browser_iequirks';}if(d.gecko&&e<10900)d.cssClass+=' cke_browser_gecko18';if(d.air)d.cssClass+=' cke_browser_air';return d;})();var b=a.env;var c=b.ie;if(a.status=='unloaded')(function(){a.event.implementOn(a);a.loadFullCore=function(){if(a.status!='basic_ready'){a.loadFullCore._load=1;return;}delete a.loadFullCore;var e=document.createElement('script');e.type='text/javascript';e.src=a.basePath+'ckeditor.js';document.getElementsByTagName('head')[0].appendChild(e);};a.loadFullCoreTimeout=0;a.replaceClass='ckeditor';a.replaceByClassEnabled=1;var d=function(e,f,g,h){if(b.isCompatible){if(a.loadFullCore)a.loadFullCore();var i=g(e,f,h);a.add(i);return i;}return null;};a.replace=function(e,f){return d(e,f,a.editor.replace);};a.appendTo=function(e,f,g){return d(e,f,a.editor.appendTo,g);};a.add=function(e){var f=this._.pending||(this._.pending=[]);f.push(e);};a.replaceAll=function(){var e=document.getElementsByTagName('textarea');for(var f=0;f<e.length;f++){var g=null,h=e[f];if(!h.name&&!h.id)continue;if(typeof arguments[0]=='string'){var i=new RegExp('(?:^|\\s)'+arguments[0]+'(?:$|\\s)');if(!i.test(h.className))continue;}else if(typeof arguments[0]=='function'){g={};if(arguments[0](h,g)===false)continue;}this.replace(h,g);}};(function(){var e=function(){var f=a.loadFullCore,g=a.loadFullCoreTimeout;if(a.replaceByClassEnabled)a.replaceAll(a.replaceClass);a.status='basic_ready';if(f&&f._load)f();else if(g)setTimeout(function(){if(a.loadFullCore)a.loadFullCore();},g*1000);};if(window.addEventListener)window.addEventListener('load',e,false);else if(window.attachEvent)window.attachEvent('onload',e);})();a.status='basic_loaded';})();})(); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/ckeditor_basic.js | ckeditor_basic.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.add('devtools',{lang:['en'],init:function(a){a._.showDialogDefinitionTooltips=1;},onLoad:function(){CKEDITOR.document.appendStyleText(CKEDITOR.config.devtools_styles||'#cke_tooltip { padding: 5px; border: 2px solid #333; background: #ffffff }#cke_tooltip h2 { font-size: 1.1em; border-bottom: 1px solid; margin: 0; padding: 1px; }#cke_tooltip ul { padding: 0pt; list-style-type: none; }');}});(function(){function a(d,e,f,g){var h=d.lang.devTools,i='<a href="http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.dialog.definition.'+(f?f.type=='text'?'textInput':f.type:'content')+'.html" target="_blank">'+(f?f.type:'content')+'</a>',j='<h2>'+h.title+'</h2>'+'<ul>'+'<li><strong>'+h.dialogName+'</strong> : '+e.getName()+'</li>'+'<li><strong>'+h.tabName+'</strong> : '+g+'</li>';if(f)j+='<li><strong>'+h.elementId+'</strong> : '+f.id+'</li>';j+='<li><strong>'+h.elementType+'</strong> : '+i+'</li>';return j+'</ul>';};function b(d,e,f,g,h,i){var j=e.getDocumentPosition(),k={'z-index':CKEDITOR.dialog._.currentZIndex+10,top:j.y+e.getSize('height')+'px'};c.setHtml(d(f,g,h,i));c.show();if(f.lang.dir=='rtl'){var l=CKEDITOR.document.getWindow().getViewPaneSize();k.right=l.width-j.x-e.getSize('width')+'px';}else k.left=j.x+'px';c.setStyles(k);};var c;CKEDITOR.on('reset',function(){c&&c.remove();c=null;});CKEDITOR.on('dialogDefinition',function(d){var e=d.editor;if(e._.showDialogDefinitionTooltips){if(!c){c=CKEDITOR.dom.element.createFromHtml('<div id="cke_tooltip" tabindex="-1" style="position: absolute"></div>',CKEDITOR.document);c.hide();c.on('mouseover',function(){this.show();});c.on('mouseout',function(){this.hide();});c.appendTo(CKEDITOR.document.getBody());}var f=d.data.definition.dialog,g=e.config.devtools_textCallback||a;f.on('load',function(){var h=f.parts.tabs.getChildren(),i;for(var j=0,k=h.count();j<k;j++){i=h.getItem(j);i.on('mouseover',function(){var l=this.$.id;b(g,this,e,f,null,l.substring(4,l.lastIndexOf('_')));});i.on('mouseout',function(){c.hide();});}f.foreach(function(l){if(l.type in {hbox:1,vbox:1})return;var m=l.getElement();if(m){m.on('mouseover',function(){b(g,this,e,f,l,f._.currentTabId);});m.on('mouseout',function(){c.hide();});}});});}});})(); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/plugins/devtools/plugin.js | plugin.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add('uicolor',function(a){var b,c,d,e=a.getUiColor(),f='cke_uicolor_picker'+CKEDITOR.tools.getNextNumber();function g(j){if(/^#/.test(j))j=window.YAHOO.util.Color.hex2rgb(j.substr(1));c.setValue(j,true);c.refresh(f);};function h(j,k){if(k||b._.contents.tab1.livePeview.getValue())a.setUiColor(j);b._.contents.tab1.configBox.setValue('config.uiColor = "#'+c.get('hex')+'"');};d={id:'yuiColorPicker',type:'html',html:"<div id='"+f+"' class='cke_uicolor_picker' style='width: 360px; height: 200px; position: relative;'></div>",onLoad:function(j){var k=CKEDITOR.getUrl('plugins/uicolor/yui/');c=new window.YAHOO.widget.ColorPicker(f,{showhsvcontrols:true,showhexcontrols:true,images:{PICKER_THUMB:k+'assets/picker_thumb.png',HUE_THUMB:k+'assets/hue_thumb.png'}});if(e)g(e);c.on('rgbChange',function(){b._.contents.tab1.predefined.setValue('');h('#'+c.get('hex'));});var l=new CKEDITOR.dom.nodeList(c.getElementsByTagName('input'));for(var m=0;m<l.count();m++)l.getItem(m).addClass('cke_dialog_ui_input_text');}};var i=true;return{title:a.lang.uicolor.title,minWidth:360,minHeight:320,onLoad:function(){b=this;this.setupContent();if(CKEDITOR.env.ie7Compat)b.parts.contents.setStyle('overflow','hidden');},contents:[{id:'tab1',label:'',title:'',expand:true,padding:0,elements:[d,{id:'tab1',type:'vbox',children:[{id:'livePeview',type:'checkbox',label:a.lang.uicolor.preview,'default':1,onLoad:function(){i=true;},onChange:function(){if(i)return;var j=this.getValue(),k=j?'#'+c.get('hex'):e;h(k,true);}},{type:'hbox',children:[{id:'predefined',type:'select','default':'',label:a.lang.uicolor.predefined,items:[[''],['Light blue','#9AB8F3'],['Sand','#D2B48C'],['Metallic','#949AAA'],['Purple','#C2A3C7'],['Olive','#A2C980'],['Happy green','#9BD446'],['Jezebel Blue','#14B8C4'],['Burn','#FF893A'],['Easy red','#FF6969'],['Pisces 3','#48B4F2'],['Aquarius 5','#487ED4'],['Absinthe','#A8CF76'],['Scrambled Egg','#C7A622'],['Hello monday','#8E8D80'],['Lovely sunshine','#F1E8B1'],['Recycled air','#B3C593'],['Down','#BCBCA4'],['Mark Twain','#CFE91D'],['Specks of dust','#D1B596'],['Lollipop','#F6CE23']],onChange:function(){var j=this.getValue();if(j){g(j);h(j);CKEDITOR.document.getById('predefinedPreview').setStyle('background',j);}else CKEDITOR.document.getById('predefinedPreview').setStyle('background','');},onShow:function(){var j=a.getUiColor();if(j)this.setValue(j);}},{id:'predefinedPreview',type:'html',html:'<div id="cke_uicolor_preview" style="border: 1px solid black; padding: 3px; width: 30px;"><div id="predefinedPreview" style="width: 30px; height: 30px;"> </div></div>'}]},{id:'configBox',type:'text',label:a.lang.uicolor.config,onShow:function(){var j=a.getUiColor();
if(j)this.setValue('config.uiColor = "'+j+'"');}}]}]}],buttons:[CKEDITOR.dialog.okButton]};}); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/plugins/uicolor/dialogs/uicolor.js | uicolor.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/*jsl:ignoreall*/
/*
Copyright (c) 2009, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.7.0
*/
if(typeof YAHOO=="undefined"||!YAHOO){var YAHOO={};}YAHOO.namespace=function(){var A=arguments,E=null,C,B,D;for(C=0;C<A.length;C=C+1){D=(""+A[C]).split(".");E=YAHOO;for(B=(D[0]=="YAHOO")?1:0;B<D.length;B=B+1){E[D[B]]=E[D[B]]||{};E=E[D[B]];}}return E;};YAHOO.log=function(D,A,C){var B=YAHOO.widget.Logger;if(B&&B.log){return B.log(D,A,C);}else{return false;}};YAHOO.register=function(A,E,D){var I=YAHOO.env.modules,B,H,G,F,C;if(!I[A]){I[A]={versions:[],builds:[]};}B=I[A];H=D.version;G=D.build;F=YAHOO.env.listeners;B.name=A;B.version=H;B.build=G;B.versions.push(H);B.builds.push(G);B.mainClass=E;for(C=0;C<F.length;C=C+1){F[C](B);}if(E){E.VERSION=H;E.BUILD=G;}else{YAHOO.log("mainClass is undefined for module "+A,"warn");}};YAHOO.env=YAHOO.env||{modules:[],listeners:[]};YAHOO.env.getVersion=function(A){return YAHOO.env.modules[A]||null;};YAHOO.env.ua=function(){var C={ie:0,opera:0,gecko:0,webkit:0,mobile:null,air:0,caja:0},B=navigator.userAgent,A;if((/KHTML/).test(B)){C.webkit=1;}A=B.match(/AppleWebKit\/([^\s]*)/);if(A&&A[1]){C.webkit=parseFloat(A[1]);if(/ Mobile\//.test(B)){C.mobile="Apple";}else{A=B.match(/NokiaN[^\/]*/);if(A){C.mobile=A[0];}}A=B.match(/AdobeAIR\/([^\s]*)/);if(A){C.air=A[0];}}if(!C.webkit){A=B.match(/Opera[\s\/]([^\s]*)/);if(A&&A[1]){C.opera=parseFloat(A[1]);A=B.match(/Opera Mini[^;]*/);if(A){C.mobile=A[0];}}else{A=B.match(/MSIE\s([^;]*)/);if(A&&A[1]){C.ie=parseFloat(A[1]);}else{A=B.match(/Gecko\/([^\s]*)/);if(A){C.gecko=1;A=B.match(/rv:([^\s\)]*)/);if(A&&A[1]){C.gecko=parseFloat(A[1]);}}}}}A=B.match(/Caja\/([^\s]*)/);if(A&&A[1]){C.caja=parseFloat(A[1]);}return C;}();(function(){YAHOO.namespace("util","widget","example");if("undefined"!==typeof YAHOO_config){var B=YAHOO_config.listener,A=YAHOO.env.listeners,D=true,C;if(B){for(C=0;C<A.length;C=C+1){if(A[C]==B){D=false;break;}}if(D){A.push(B);}}}})();YAHOO.lang=YAHOO.lang||{};(function(){var B=YAHOO.lang,F="[object Array]",C="[object Function]",A=Object.prototype,E=["toString","valueOf"],D={isArray:function(G){return A.toString.apply(G)===F;},isBoolean:function(G){return typeof G==="boolean";},isFunction:function(G){return A.toString.apply(G)===C;},isNull:function(G){return G===null;},isNumber:function(G){return typeof G==="number"&&isFinite(G);},isObject:function(G){return(G&&(typeof G==="object"||B.isFunction(G)))||false;},isString:function(G){return typeof G==="string";},isUndefined:function(G){return typeof G==="undefined";},_IEEnumFix:(YAHOO.env.ua.ie)?function(I,H){var G,K,J;for(G=0;G<E.length;G=G+1){K=E[G];J=H[K];if(B.isFunction(J)&&J!=A[K]){I[K]=J;}}}:function(){},extend:function(J,K,I){if(!K||!J){throw new Error("extend failed, please check that "+"all dependencies are included.");}var H=function(){},G;H.prototype=K.prototype;J.prototype=new H();J.prototype.constructor=J;J.superclass=K.prototype;if(K.prototype.constructor==A.constructor){K.prototype.constructor=K;}if(I){for(G in I){if(B.hasOwnProperty(I,G)){J.prototype[G]=I[G];}}B._IEEnumFix(J.prototype,I);}},augmentObject:function(K,J){if(!J||!K){throw new Error("Absorb failed, verify dependencies.");}var G=arguments,I,L,H=G[2];if(H&&H!==true){for(I=2;I<G.length;I=I+1){K[G[I]]=J[G[I]];}}else{for(L in J){if(H||!(L in K)){K[L]=J[L];}}B._IEEnumFix(K,J);}},augmentProto:function(J,I){if(!I||!J){throw new Error("Augment failed, verify dependencies.");}var G=[J.prototype,I.prototype],H;for(H=2;H<arguments.length;H=H+1){G.push(arguments[H]);}B.augmentObject.apply(this,G);},dump:function(G,L){var I,K,N=[],O="{...}",H="f(){...}",M=", ",J=" => ";if(!B.isObject(G)){return G+"";}else{if(G instanceof Date||("nodeType" in G&&"tagName" in G)){return G;}else{if(B.isFunction(G)){return H;}}}L=(B.isNumber(L))?L:3;if(B.isArray(G)){N.push("[");for(I=0,K=G.length;I<K;I=I+1){if(B.isObject(G[I])){N.push((L>0)?B.dump(G[I],L-1):O);}else{N.push(G[I]);}N.push(M);}if(N.length>1){N.pop();}N.push("]");}else{N.push("{");for(I in G){if(B.hasOwnProperty(G,I)){N.push(I+J);if(B.isObject(G[I])){N.push((L>0)?B.dump(G[I],L-1):O);}else{N.push(G[I]);}N.push(M);}}if(N.length>1){N.pop();}N.push("}");}return N.join("");},substitute:function(V,H,O){var L,K,J,R,S,U,Q=[],I,M="dump",P=" ",G="{",T="}",N;for(;;){L=V.lastIndexOf(G);if(L<0){break;}K=V.indexOf(T,L);if(L+1>=K){break;}I=V.substring(L+1,K);R=I;U=null;J=R.indexOf(P);if(J>-1){U=R.substring(J+1);R=R.substring(0,J);}S=H[R];if(O){S=O(R,S,U);}if(B.isObject(S)){if(B.isArray(S)){S=B.dump(S,parseInt(U,10));}else{U=U||"";N=U.indexOf(M);if(N>-1){U=U.substring(4);}if(S.toString===A.toString||N>-1){S=B.dump(S,parseInt(U,10));}else{S=S.toString();}}}else{if(!B.isString(S)&&!B.isNumber(S)){S="~-"+Q.length+"-~";Q[Q.length]=I;}}V=V.substring(0,L)+S+V.substring(K+1);}for(L=Q.length-1;L>=0;L=L-1){V=V.replace(new RegExp("~-"+L+"-~"),"{"+Q[L]+"}","g");}return V;},trim:function(G){try{return G.replace(/^\s+|\s+$/g,"");}catch(H){return G;}},merge:function(){var J={},H=arguments,G=H.length,I;for(I=0;I<G;I=I+1){B.augmentObject(J,H[I],true);}return J;},later:function(N,H,O,J,K){N=N||0;H=H||{};var I=O,M=J,L,G;if(B.isString(O)){I=H[O];}if(!I){throw new TypeError("method undefined");}if(!B.isArray(M)){M=[J];}L=function(){I.apply(H,M);};G=(K)?setInterval(L,N):setTimeout(L,N);return{interval:K,cancel:function(){if(this.interval){clearInterval(G);}else{clearTimeout(G);}}};},isValue:function(G){return(B.isObject(G)||B.isString(G)||B.isNumber(G)||B.isBoolean(G));}};B.hasOwnProperty=(A.hasOwnProperty)?function(G,H){return G&&G.hasOwnProperty(H);}:function(G,H){return !B.isUndefined(G[H])&&G.constructor.prototype[H]!==G[H];};D.augmentObject(B,D,true);YAHOO.util.Lang=B;B.augment=B.augmentProto;YAHOO.augment=B.augmentProto;YAHOO.extend=B.extend;})();YAHOO.register("yahoo",YAHOO,{version:"2.7.0",build:"1796"});(function(){YAHOO.env._id_counter=YAHOO.env._id_counter||0;var E=YAHOO.util,L=YAHOO.lang,m=YAHOO.env.ua,A=YAHOO.lang.trim,d={},h={},N=/^t(?:able|d|h)$/i,X=/color$/i,K=window.document,W=K.documentElement,e="ownerDocument",n="defaultView",v="documentElement",t="compatMode",b="offsetLeft",P="offsetTop",u="offsetParent",Z="parentNode",l="nodeType",C="tagName",O="scrollLeft",i="scrollTop",Q="getBoundingClientRect",w="getComputedStyle",a="currentStyle",M="CSS1Compat",c="BackCompat",g="class",F="className",J="",B=" ",s="(?:^|\\s)",k="(?= |$)",U="g",p="position",f="fixed",V="relative",j="left",o="top",r="medium",q="borderLeftWidth",R="borderTopWidth",D=m.opera,I=m.webkit,H=m.gecko,T=m.ie;E.Dom={CUSTOM_ATTRIBUTES:(!W.hasAttribute)?{"for":"htmlFor","class":F}:{"htmlFor":"for","className":g},get:function(y){var AA,Y,z,x,G;if(y){if(y[l]||y.item){return y;}if(typeof y==="string"){AA=y;y=K.getElementById(y);if(y&&y.id===AA){return y;}else{if(y&&K.all){y=null;Y=K.all[AA];for(x=0,G=Y.length;x<G;++x){if(Y[x].id===AA){return Y[x];}}}}return y;}if(y.DOM_EVENTS){y=y.get("element");}if("length" in y){z=[];for(x=0,G=y.length;x<G;++x){z[z.length]=E.Dom.get(y[x]);}return z;}return y;}return null;},getComputedStyle:function(G,Y){if(window[w]){return G[e][n][w](G,null)[Y];}else{if(G[a]){return E.Dom.IE_ComputedStyle.get(G,Y);}}},getStyle:function(G,Y){return E.Dom.batch(G,E.Dom._getStyle,Y);},_getStyle:function(){if(window[w]){return function(G,y){y=(y==="float")?y="cssFloat":E.Dom._toCamel(y);var x=G.style[y],Y;if(!x){Y=G[e][n][w](G,null);if(Y){x=Y[y];}}return x;};}else{if(W[a]){return function(G,y){var x;switch(y){case"opacity":x=100;try{x=G.filters["DXImageTransform.Microsoft.Alpha"].opacity;}catch(z){try{x=G.filters("alpha").opacity;}catch(Y){}}return x/100;case"float":y="styleFloat";default:y=E.Dom._toCamel(y);x=G[a]?G[a][y]:null;return(G.style[y]||x);}};}}}(),setStyle:function(G,Y,x){E.Dom.batch(G,E.Dom._setStyle,{prop:Y,val:x});},_setStyle:function(){if(T){return function(Y,G){var x=E.Dom._toCamel(G.prop),y=G.val;if(Y){switch(x){case"opacity":if(L.isString(Y.style.filter)){Y.style.filter="alpha(opacity="+y*100+")";if(!Y[a]||!Y[a].hasLayout){Y.style.zoom=1;}}break;case"float":x="styleFloat";default:Y.style[x]=y;}}else{}};}else{return function(Y,G){var x=E.Dom._toCamel(G.prop),y=G.val;if(Y){if(x=="float"){x="cssFloat";}Y.style[x]=y;}else{}};}}(),getXY:function(G){return E.Dom.batch(G,E.Dom._getXY);},_canPosition:function(G){return(E.Dom._getStyle(G,"display")!=="none"&&E.Dom._inDoc(G));},_getXY:function(){if(K[v][Q]){return function(y){var z,Y,AA,AF,AE,AD,AC,G,x,AB=Math.floor,AG=false;if(E.Dom._canPosition(y)){AA=y[Q]();AF=y[e];z=E.Dom.getDocumentScrollLeft(AF);Y=E.Dom.getDocumentScrollTop(AF);AG=[AB(AA[j]),AB(AA[o])];if(T&&m.ie<8){AE=2;AD=2;AC=AF[t];G=S(AF[v],q);x=S(AF[v],R);if(m.ie===6){if(AC!==c){AE=0;AD=0;}}if((AC==c)){if(G!==r){AE=parseInt(G,10);}if(x!==r){AD=parseInt(x,10);}}AG[0]-=AE;AG[1]-=AD;}if((Y||z)){AG[0]+=z;AG[1]+=Y;}AG[0]=AB(AG[0]);AG[1]=AB(AG[1]);}else{}return AG;};}else{return function(y){var x,Y,AA,AB,AC,z=false,G=y;if(E.Dom._canPosition(y)){z=[y[b],y[P]];x=E.Dom.getDocumentScrollLeft(y[e]);Y=E.Dom.getDocumentScrollTop(y[e]);AC=((H||m.webkit>519)?true:false);while((G=G[u])){z[0]+=G[b];z[1]+=G[P];if(AC){z=E.Dom._calcBorders(G,z);}}if(E.Dom._getStyle(y,p)!==f){G=y;while((G=G[Z])&&G[C]){AA=G[i];AB=G[O];if(H&&(E.Dom._getStyle(G,"overflow")!=="visible")){z=E.Dom._calcBorders(G,z);}if(AA||AB){z[0]-=AB;z[1]-=AA;}}z[0]+=x;z[1]+=Y;}else{if(D){z[0]-=x;z[1]-=Y;}else{if(I||H){z[0]+=x;z[1]+=Y;}}}z[0]=Math.floor(z[0]);z[1]=Math.floor(z[1]);}else{}return z;};}}(),getX:function(G){var Y=function(x){return E.Dom.getXY(x)[0];};return E.Dom.batch(G,Y,E.Dom,true);},getY:function(G){var Y=function(x){return E.Dom.getXY(x)[1];};return E.Dom.batch(G,Y,E.Dom,true);},setXY:function(G,x,Y){E.Dom.batch(G,E.Dom._setXY,{pos:x,noRetry:Y});},_setXY:function(G,z){var AA=E.Dom._getStyle(G,p),y=E.Dom.setStyle,AD=z.pos,Y=z.noRetry,AB=[parseInt(E.Dom.getComputedStyle(G,j),10),parseInt(E.Dom.getComputedStyle(G,o),10)],AC,x;if(AA=="static"){AA=V;y(G,p,AA);}AC=E.Dom._getXY(G);if(!AD||AC===false){return false;}if(isNaN(AB[0])){AB[0]=(AA==V)?0:G[b];}if(isNaN(AB[1])){AB[1]=(AA==V)?0:G[P];}if(AD[0]!==null){y(G,j,AD[0]-AC[0]+AB[0]+"px");}if(AD[1]!==null){y(G,o,AD[1]-AC[1]+AB[1]+"px");}if(!Y){x=E.Dom._getXY(G);if((AD[0]!==null&&x[0]!=AD[0])||(AD[1]!==null&&x[1]!=AD[1])){E.Dom._setXY(G,{pos:AD,noRetry:true});}}},setX:function(Y,G){E.Dom.setXY(Y,[G,null]);},setY:function(G,Y){E.Dom.setXY(G,[null,Y]);},getRegion:function(G){var Y=function(x){var y=false;if(E.Dom._canPosition(x)){y=E.Region.getRegion(x);}else{}return y;};return E.Dom.batch(G,Y,E.Dom,true);},getClientWidth:function(){return E.Dom.getViewportWidth();},getClientHeight:function(){return E.Dom.getViewportHeight();},getElementsByClassName:function(AB,AF,AC,AE,x,AD){AB=L.trim(AB);AF=AF||"*";AC=(AC)?E.Dom.get(AC):null||K;if(!AC){return[];}var Y=[],G=AC.getElementsByTagName(AF),z=E.Dom.hasClass;for(var y=0,AA=G.length;y<AA;++y){if(z(G[y],AB)){Y[Y.length]=G[y];}}if(AE){E.Dom.batch(Y,AE,x,AD);}return Y;},hasClass:function(Y,G){return E.Dom.batch(Y,E.Dom._hasClass,G);},_hasClass:function(x,Y){var G=false,y;if(x&&Y){y=E.Dom.getAttribute(x,F)||J;if(Y.exec){G=Y.test(y);}else{G=Y&&(B+y+B).indexOf(B+Y+B)>-1;}}else{}return G;},addClass:function(Y,G){return E.Dom.batch(Y,E.Dom._addClass,G);},_addClass:function(x,Y){var G=false,y;if(x&&Y){y=E.Dom.getAttribute(x,F)||J;if(!E.Dom._hasClass(x,Y)){E.Dom.setAttribute(x,F,A(y+B+Y));G=true;}}else{}return G;},removeClass:function(Y,G){return E.Dom.batch(Y,E.Dom._removeClass,G);},_removeClass:function(y,x){var Y=false,AA,z,G;if(y&&x){AA=E.Dom.getAttribute(y,F)||J;E.Dom.setAttribute(y,F,AA.replace(E.Dom._getClassRegex(x),J));z=E.Dom.getAttribute(y,F);if(AA!==z){E.Dom.setAttribute(y,F,A(z));Y=true;if(E.Dom.getAttribute(y,F)===""){G=(y.hasAttribute&&y.hasAttribute(g))?g:F;y.removeAttribute(G);}}}else{}return Y;},replaceClass:function(x,Y,G){return E.Dom.batch(x,E.Dom._replaceClass,{from:Y,to:G});
},_replaceClass:function(y,x){var Y,AB,AA,G=false,z;if(y&&x){AB=x.from;AA=x.to;if(!AA){G=false;}else{if(!AB){G=E.Dom._addClass(y,x.to);}else{if(AB!==AA){z=E.Dom.getAttribute(y,F)||J;Y=(B+z.replace(E.Dom._getClassRegex(AB),B+AA)).split(E.Dom._getClassRegex(AA));Y.splice(1,0,B+AA);E.Dom.setAttribute(y,F,A(Y.join(J)));G=true;}}}}else{}return G;},generateId:function(G,x){x=x||"yui-gen";var Y=function(y){if(y&&y.id){return y.id;}var z=x+YAHOO.env._id_counter++;if(y){if(y[e].getElementById(z)){return E.Dom.generateId(y,z+x);}y.id=z;}return z;};return E.Dom.batch(G,Y,E.Dom,true)||Y.apply(E.Dom,arguments);},isAncestor:function(Y,x){Y=E.Dom.get(Y);x=E.Dom.get(x);var G=false;if((Y&&x)&&(Y[l]&&x[l])){if(Y.contains&&Y!==x){G=Y.contains(x);}else{if(Y.compareDocumentPosition){G=!!(Y.compareDocumentPosition(x)&16);}}}else{}return G;},inDocument:function(G,Y){return E.Dom._inDoc(E.Dom.get(G),Y);},_inDoc:function(Y,x){var G=false;if(Y&&Y[C]){x=x||Y[e];G=E.Dom.isAncestor(x[v],Y);}else{}return G;},getElementsBy:function(Y,AF,AB,AD,y,AC,AE){AF=AF||"*";AB=(AB)?E.Dom.get(AB):null||K;if(!AB){return[];}var x=[],G=AB.getElementsByTagName(AF);for(var z=0,AA=G.length;z<AA;++z){if(Y(G[z])){if(AE){x=G[z];break;}else{x[x.length]=G[z];}}}if(AD){E.Dom.batch(x,AD,y,AC);}return x;},getElementBy:function(x,G,Y){return E.Dom.getElementsBy(x,G,Y,null,null,null,true);},batch:function(x,AB,AA,z){var y=[],Y=(z)?AA:window;x=(x&&(x[C]||x.item))?x:E.Dom.get(x);if(x&&AB){if(x[C]||x.length===undefined){return AB.call(Y,x,AA);}for(var G=0;G<x.length;++G){y[y.length]=AB.call(Y,x[G],AA);}}else{return false;}return y;},getDocumentHeight:function(){var Y=(K[t]!=M||I)?K.body.scrollHeight:W.scrollHeight,G=Math.max(Y,E.Dom.getViewportHeight());return G;},getDocumentWidth:function(){var Y=(K[t]!=M||I)?K.body.scrollWidth:W.scrollWidth,G=Math.max(Y,E.Dom.getViewportWidth());return G;},getViewportHeight:function(){var G=self.innerHeight,Y=K[t];if((Y||T)&&!D){G=(Y==M)?W.clientHeight:K.body.clientHeight;}return G;},getViewportWidth:function(){var G=self.innerWidth,Y=K[t];if(Y||T){G=(Y==M)?W.clientWidth:K.body.clientWidth;}return G;},getAncestorBy:function(G,Y){while((G=G[Z])){if(E.Dom._testElement(G,Y)){return G;}}return null;},getAncestorByClassName:function(Y,G){Y=E.Dom.get(Y);if(!Y){return null;}var x=function(y){return E.Dom.hasClass(y,G);};return E.Dom.getAncestorBy(Y,x);},getAncestorByTagName:function(Y,G){Y=E.Dom.get(Y);if(!Y){return null;}var x=function(y){return y[C]&&y[C].toUpperCase()==G.toUpperCase();};return E.Dom.getAncestorBy(Y,x);},getPreviousSiblingBy:function(G,Y){while(G){G=G.previousSibling;if(E.Dom._testElement(G,Y)){return G;}}return null;},getPreviousSibling:function(G){G=E.Dom.get(G);if(!G){return null;}return E.Dom.getPreviousSiblingBy(G);},getNextSiblingBy:function(G,Y){while(G){G=G.nextSibling;if(E.Dom._testElement(G,Y)){return G;}}return null;},getNextSibling:function(G){G=E.Dom.get(G);if(!G){return null;}return E.Dom.getNextSiblingBy(G);},getFirstChildBy:function(G,x){var Y=(E.Dom._testElement(G.firstChild,x))?G.firstChild:null;return Y||E.Dom.getNextSiblingBy(G.firstChild,x);},getFirstChild:function(G,Y){G=E.Dom.get(G);if(!G){return null;}return E.Dom.getFirstChildBy(G);},getLastChildBy:function(G,x){if(!G){return null;}var Y=(E.Dom._testElement(G.lastChild,x))?G.lastChild:null;return Y||E.Dom.getPreviousSiblingBy(G.lastChild,x);},getLastChild:function(G){G=E.Dom.get(G);return E.Dom.getLastChildBy(G);},getChildrenBy:function(Y,y){var x=E.Dom.getFirstChildBy(Y,y),G=x?[x]:[];E.Dom.getNextSiblingBy(x,function(z){if(!y||y(z)){G[G.length]=z;}return false;});return G;},getChildren:function(G){G=E.Dom.get(G);if(!G){}return E.Dom.getChildrenBy(G);},getDocumentScrollLeft:function(G){G=G||K;return Math.max(G[v].scrollLeft,G.body.scrollLeft);},getDocumentScrollTop:function(G){G=G||K;return Math.max(G[v].scrollTop,G.body.scrollTop);},insertBefore:function(Y,G){Y=E.Dom.get(Y);G=E.Dom.get(G);if(!Y||!G||!G[Z]){return null;}return G[Z].insertBefore(Y,G);},insertAfter:function(Y,G){Y=E.Dom.get(Y);G=E.Dom.get(G);if(!Y||!G||!G[Z]){return null;}if(G.nextSibling){return G[Z].insertBefore(Y,G.nextSibling);}else{return G[Z].appendChild(Y);}},getClientRegion:function(){var x=E.Dom.getDocumentScrollTop(),Y=E.Dom.getDocumentScrollLeft(),y=E.Dom.getViewportWidth()+Y,G=E.Dom.getViewportHeight()+x;return new E.Region(x,y,G,Y);},setAttribute:function(Y,G,x){G=E.Dom.CUSTOM_ATTRIBUTES[G]||G;Y.setAttribute(G,x);},getAttribute:function(Y,G){G=E.Dom.CUSTOM_ATTRIBUTES[G]||G;return Y.getAttribute(G);},_toCamel:function(Y){var x=d;function G(y,z){return z.toUpperCase();}return x[Y]||(x[Y]=Y.indexOf("-")===-1?Y:Y.replace(/-([a-z])/gi,G));},_getClassRegex:function(Y){var G;if(Y!==undefined){if(Y.exec){G=Y;}else{G=h[Y];if(!G){Y=Y.replace(E.Dom._patterns.CLASS_RE_TOKENS,"\\$1");G=h[Y]=new RegExp(s+Y+k,U);}}}return G;},_patterns:{ROOT_TAG:/^body|html$/i,CLASS_RE_TOKENS:/([\.\(\)\^\$\*\+\?\|\[\]\{\}])/g},_testElement:function(G,Y){return G&&G[l]==1&&(!Y||Y(G));},_calcBorders:function(x,y){var Y=parseInt(E.Dom[w](x,R),10)||0,G=parseInt(E.Dom[w](x,q),10)||0;if(H){if(N.test(x[C])){Y=0;G=0;}}y[0]+=G;y[1]+=Y;return y;}};var S=E.Dom[w];if(m.opera){E.Dom[w]=function(Y,G){var x=S(Y,G);if(X.test(G)){x=E.Dom.Color.toRGB(x);}return x;};}if(m.webkit){E.Dom[w]=function(Y,G){var x=S(Y,G);if(x==="rgba(0, 0, 0, 0)"){x="transparent";}return x;};}})();YAHOO.util.Region=function(C,D,A,B){this.top=C;this.y=C;this[1]=C;this.right=D;this.bottom=A;this.left=B;this.x=B;this[0]=B;this.width=this.right-this.left;this.height=this.bottom-this.top;};YAHOO.util.Region.prototype.contains=function(A){return(A.left>=this.left&&A.right<=this.right&&A.top>=this.top&&A.bottom<=this.bottom);};YAHOO.util.Region.prototype.getArea=function(){return((this.bottom-this.top)*(this.right-this.left));};YAHOO.util.Region.prototype.intersect=function(E){var C=Math.max(this.top,E.top),D=Math.min(this.right,E.right),A=Math.min(this.bottom,E.bottom),B=Math.max(this.left,E.left);if(A>=C&&D>=B){return new YAHOO.util.Region(C,D,A,B);
}else{return null;}};YAHOO.util.Region.prototype.union=function(E){var C=Math.min(this.top,E.top),D=Math.max(this.right,E.right),A=Math.max(this.bottom,E.bottom),B=Math.min(this.left,E.left);return new YAHOO.util.Region(C,D,A,B);};YAHOO.util.Region.prototype.toString=function(){return("Region {"+"top: "+this.top+", right: "+this.right+", bottom: "+this.bottom+", left: "+this.left+", height: "+this.height+", width: "+this.width+"}");};YAHOO.util.Region.getRegion=function(D){var F=YAHOO.util.Dom.getXY(D),C=F[1],E=F[0]+D.offsetWidth,A=F[1]+D.offsetHeight,B=F[0];return new YAHOO.util.Region(C,E,A,B);};YAHOO.util.Point=function(A,B){if(YAHOO.lang.isArray(A)){B=A[1];A=A[0];}YAHOO.util.Point.superclass.constructor.call(this,B,A,B,A);};YAHOO.extend(YAHOO.util.Point,YAHOO.util.Region);(function(){var B=YAHOO.util,A="clientTop",F="clientLeft",J="parentNode",K="right",W="hasLayout",I="px",U="opacity",L="auto",D="borderLeftWidth",G="borderTopWidth",P="borderRightWidth",V="borderBottomWidth",S="visible",Q="transparent",N="height",E="width",H="style",T="currentStyle",R=/^width|height$/,O=/^(\d[.\d]*)+(em|ex|px|gd|rem|vw|vh|vm|ch|mm|cm|in|pt|pc|deg|rad|ms|s|hz|khz|%){1}?/i,M={get:function(X,Z){var Y="",a=X[T][Z];if(Z===U){Y=B.Dom.getStyle(X,U);}else{if(!a||(a.indexOf&&a.indexOf(I)>-1)){Y=a;}else{if(B.Dom.IE_COMPUTED[Z]){Y=B.Dom.IE_COMPUTED[Z](X,Z);}else{if(O.test(a)){Y=B.Dom.IE.ComputedStyle.getPixel(X,Z);}else{Y=a;}}}}return Y;},getOffset:function(Z,e){var b=Z[T][e],X=e.charAt(0).toUpperCase()+e.substr(1),c="offset"+X,Y="pixel"+X,a="",d;if(b==L){d=Z[c];if(d===undefined){a=0;}a=d;if(R.test(e)){Z[H][e]=d;if(Z[c]>d){a=d-(Z[c]-d);}Z[H][e]=L;}}else{if(!Z[H][Y]&&!Z[H][e]){Z[H][e]=b;}a=Z[H][Y];}return a+I;},getBorderWidth:function(X,Z){var Y=null;if(!X[T][W]){X[H].zoom=1;}switch(Z){case G:Y=X[A];break;case V:Y=X.offsetHeight-X.clientHeight-X[A];break;case D:Y=X[F];break;case P:Y=X.offsetWidth-X.clientWidth-X[F];break;}return Y+I;},getPixel:function(Y,X){var a=null,b=Y[T][K],Z=Y[T][X];Y[H][K]=Z;a=Y[H].pixelRight;Y[H][K]=b;return a+I;},getMargin:function(Y,X){var Z;if(Y[T][X]==L){Z=0+I;}else{Z=B.Dom.IE.ComputedStyle.getPixel(Y,X);}return Z;},getVisibility:function(Y,X){var Z;while((Z=Y[T])&&Z[X]=="inherit"){Y=Y[J];}return(Z)?Z[X]:S;},getColor:function(Y,X){return B.Dom.Color.toRGB(Y[T][X])||Q;},getBorderColor:function(Y,X){var Z=Y[T],a=Z[X]||Z.color;return B.Dom.Color.toRGB(B.Dom.Color.toHex(a));}},C={};C.top=C.right=C.bottom=C.left=C[E]=C[N]=M.getOffset;C.color=M.getColor;C[G]=C[P]=C[V]=C[D]=M.getBorderWidth;C.marginTop=C.marginRight=C.marginBottom=C.marginLeft=M.getMargin;C.visibility=M.getVisibility;C.borderColor=C.borderTopColor=C.borderRightColor=C.borderBottomColor=C.borderLeftColor=M.getBorderColor;B.Dom.IE_COMPUTED=C;B.Dom.IE_ComputedStyle=M;})();(function(){var C="toString",A=parseInt,B=RegExp,D=YAHOO.util;D.Dom.Color={KEYWORDS:{black:"000",silver:"c0c0c0",gray:"808080",white:"fff",maroon:"800000",red:"f00",purple:"800080",fuchsia:"f0f",green:"008000",lime:"0f0",olive:"808000",yellow:"ff0",navy:"000080",blue:"00f",teal:"008080",aqua:"0ff"},re_RGB:/^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i,re_hex:/^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i,re_hex3:/([0-9A-F])/gi,toRGB:function(E){if(!D.Dom.Color.re_RGB.test(E)){E=D.Dom.Color.toHex(E);}if(D.Dom.Color.re_hex.exec(E)){E="rgb("+[A(B.$1,16),A(B.$2,16),A(B.$3,16)].join(", ")+")";}return E;},toHex:function(H){H=D.Dom.Color.KEYWORDS[H]||H;if(D.Dom.Color.re_RGB.exec(H)){var G=(B.$1.length===1)?"0"+B.$1:Number(B.$1),F=(B.$2.length===1)?"0"+B.$2:Number(B.$2),E=(B.$3.length===1)?"0"+B.$3:Number(B.$3);H=[G[C](16),F[C](16),E[C](16)].join("");}if(H.length<6){H=H.replace(D.Dom.Color.re_hex3,"$1$1");}if(H!=="transparent"&&H.indexOf("#")<0){H="#"+H;}return H.toLowerCase();}};}());YAHOO.register("dom",YAHOO.util.Dom,{version:"2.7.0",build:"1796"});YAHOO.util.CustomEvent=function(D,C,B,A){this.type=D;this.scope=C||window;this.silent=B;this.signature=A||YAHOO.util.CustomEvent.LIST;this.subscribers=[];if(!this.silent){}var E="_YUICEOnSubscribe";if(D!==E){this.subscribeEvent=new YAHOO.util.CustomEvent(E,this,true);}this.lastError=null;};YAHOO.util.CustomEvent.LIST=0;YAHOO.util.CustomEvent.FLAT=1;YAHOO.util.CustomEvent.prototype={subscribe:function(A,B,C){if(!A){throw new Error("Invalid callback for subscriber to '"+this.type+"'");}if(this.subscribeEvent){this.subscribeEvent.fire(A,B,C);}this.subscribers.push(new YAHOO.util.Subscriber(A,B,C));},unsubscribe:function(D,F){if(!D){return this.unsubscribeAll();}var E=false;for(var B=0,A=this.subscribers.length;B<A;++B){var C=this.subscribers[B];if(C&&C.contains(D,F)){this._delete(B);E=true;}}return E;},fire:function(){this.lastError=null;var K=[],E=this.subscribers.length;if(!E&&this.silent){return true;}var I=[].slice.call(arguments,0),G=true,D,J=false;if(!this.silent){}var C=this.subscribers.slice(),A=YAHOO.util.Event.throwErrors;for(D=0;D<E;++D){var M=C[D];if(!M){J=true;}else{if(!this.silent){}var L=M.getScope(this.scope);if(this.signature==YAHOO.util.CustomEvent.FLAT){var B=null;if(I.length>0){B=I[0];}try{G=M.fn.call(L,B,M.obj);}catch(F){this.lastError=F;if(A){throw F;}}}else{try{G=M.fn.call(L,this.type,I,M.obj);}catch(H){this.lastError=H;if(A){throw H;}}}if(false===G){if(!this.silent){}break;}}}return(G!==false);},unsubscribeAll:function(){var A=this.subscribers.length,B;for(B=A-1;B>-1;B--){this._delete(B);}this.subscribers=[];return A;},_delete:function(A){var B=this.subscribers[A];if(B){delete B.fn;delete B.obj;}this.subscribers.splice(A,1);},toString:function(){return"CustomEvent: "+"'"+this.type+"', "+"context: "+this.scope;}};YAHOO.util.Subscriber=function(A,B,C){this.fn=A;this.obj=YAHOO.lang.isUndefined(B)?null:B;this.overrideContext=C;};YAHOO.util.Subscriber.prototype.getScope=function(A){if(this.overrideContext){if(this.overrideContext===true){return this.obj;}else{return this.overrideContext;}}return A;};YAHOO.util.Subscriber.prototype.contains=function(A,B){if(B){return(this.fn==A&&this.obj==B);}else{return(this.fn==A);}};YAHOO.util.Subscriber.prototype.toString=function(){return"Subscriber { obj: "+this.obj+", overrideContext: "+(this.overrideContext||"no")+" }";};if(!YAHOO.util.Event){YAHOO.util.Event=function(){var H=false;var I=[];var J=[];var G=[];var E=[];var C=0;var F=[];var B=[];var A=0;var D={63232:38,63233:40,63234:37,63235:39,63276:33,63277:34,25:9};var K=YAHOO.env.ua.ie?"focusin":"focus";var L=YAHOO.env.ua.ie?"focusout":"blur";return{POLL_RETRYS:2000,POLL_INTERVAL:20,EL:0,TYPE:1,FN:2,WFN:3,UNLOAD_OBJ:3,ADJ_SCOPE:4,OBJ:5,OVERRIDE:6,lastError:null,isSafari:YAHOO.env.ua.webkit,webkit:YAHOO.env.ua.webkit,isIE:YAHOO.env.ua.ie,_interval:null,_dri:null,DOMReady:false,throwErrors:false,startInterval:function(){if(!this._interval){var M=this;var N=function(){M._tryPreloadAttach();};this._interval=setInterval(N,this.POLL_INTERVAL);}},onAvailable:function(S,O,Q,R,P){var M=(YAHOO.lang.isString(S))?[S]:S;for(var N=0;N<M.length;N=N+1){F.push({id:M[N],fn:O,obj:Q,overrideContext:R,checkReady:P});}C=this.POLL_RETRYS;this.startInterval();},onContentReady:function(P,M,N,O){this.onAvailable(P,M,N,O,true);},onDOMReady:function(M,N,O){if(this.DOMReady){setTimeout(function(){var P=window;if(O){if(O===true){P=N;}else{P=O;}}M.call(P,"DOMReady",[],N);},0);}else{this.DOMReadyEvent.subscribe(M,N,O);}},_addListener:function(O,M,Y,S,W,b){if(!Y||!Y.call){return false;}if(this._isValidCollection(O)){var Z=true;for(var T=0,V=O.length;T<V;++T){Z=this.on(O[T],M,Y,S,W)&&Z;}return Z;}else{if(YAHOO.lang.isString(O)){var R=this.getEl(O);if(R){O=R;}else{this.onAvailable(O,function(){YAHOO.util.Event.on(O,M,Y,S,W);});return true;}}}if(!O){return false;}if("unload"==M&&S!==this){J[J.length]=[O,M,Y,S,W];return true;}var N=O;if(W){if(W===true){N=S;}else{N=W;}}var P=function(c){return Y.call(N,YAHOO.util.Event.getEvent(c,O),S);};var a=[O,M,Y,P,N,S,W];var U=I.length;I[U]=a;if(this.useLegacyEvent(O,M)){var Q=this.getLegacyIndex(O,M);if(Q==-1||O!=G[Q][0]){Q=G.length;B[O.id+M]=Q;G[Q]=[O,M,O["on"+M]];E[Q]=[];O["on"+M]=function(c){YAHOO.util.Event.fireLegacyEvent(YAHOO.util.Event.getEvent(c),Q);};}E[Q].push(a);}else{try{this._simpleAdd(O,M,P,b);}catch(X){this.lastError=X;this.removeListener(O,M,Y);return false;}}return true;},addListener:function(N,Q,M,O,P){return this._addListener(N,Q,M,O,P,false);},addFocusListener:function(N,M,O,P){return this._addListener(N,K,M,O,P,true);},removeFocusListener:function(N,M){return this.removeListener(N,K,M);},addBlurListener:function(N,M,O,P){return this._addListener(N,L,M,O,P,true);},removeBlurListener:function(N,M){return this.removeListener(N,L,M);},fireLegacyEvent:function(R,P){var T=true,M,V,U,N,S;V=E[P].slice();for(var O=0,Q=V.length;O<Q;++O){U=V[O];if(U&&U[this.WFN]){N=U[this.ADJ_SCOPE];S=U[this.WFN].call(N,R);T=(T&&S);}}M=G[P];if(M&&M[2]){M[2](R);}return T;},getLegacyIndex:function(N,O){var M=this.generateId(N)+O;if(typeof B[M]=="undefined"){return -1;}else{return B[M];}},useLegacyEvent:function(M,N){return(this.webkit&&this.webkit<419&&("click"==N||"dblclick"==N));},removeListener:function(N,M,V){var Q,T,X;if(typeof N=="string"){N=this.getEl(N);}else{if(this._isValidCollection(N)){var W=true;for(Q=N.length-1;Q>-1;Q--){W=(this.removeListener(N[Q],M,V)&&W);}return W;}}if(!V||!V.call){return this.purgeElement(N,false,M);}if("unload"==M){for(Q=J.length-1;Q>-1;Q--){X=J[Q];if(X&&X[0]==N&&X[1]==M&&X[2]==V){J.splice(Q,1);return true;}}return false;}var R=null;var S=arguments[3];if("undefined"===typeof S){S=this._getCacheIndex(N,M,V);}if(S>=0){R=I[S];}if(!N||!R){return false;}if(this.useLegacyEvent(N,M)){var P=this.getLegacyIndex(N,M);var O=E[P];if(O){for(Q=0,T=O.length;Q<T;++Q){X=O[Q];if(X&&X[this.EL]==N&&X[this.TYPE]==M&&X[this.FN]==V){O.splice(Q,1);break;}}}}else{try{this._simpleRemove(N,M,R[this.WFN],false);}catch(U){this.lastError=U;return false;}}delete I[S][this.WFN];delete I[S][this.FN];
I.splice(S,1);return true;},getTarget:function(O,N){var M=O.target||O.srcElement;return this.resolveTextNode(M);},resolveTextNode:function(N){try{if(N&&3==N.nodeType){return N.parentNode;}}catch(M){}return N;},getPageX:function(N){var M=N.pageX;if(!M&&0!==M){M=N.clientX||0;if(this.isIE){M+=this._getScrollLeft();}}return M;},getPageY:function(M){var N=M.pageY;if(!N&&0!==N){N=M.clientY||0;if(this.isIE){N+=this._getScrollTop();}}return N;},getXY:function(M){return[this.getPageX(M),this.getPageY(M)];},getRelatedTarget:function(N){var M=N.relatedTarget;if(!M){if(N.type=="mouseout"){M=N.toElement;}else{if(N.type=="mouseover"){M=N.fromElement;}}}return this.resolveTextNode(M);},getTime:function(O){if(!O.time){var N=new Date().getTime();try{O.time=N;}catch(M){this.lastError=M;return N;}}return O.time;},stopEvent:function(M){this.stopPropagation(M);this.preventDefault(M);},stopPropagation:function(M){if(M.stopPropagation){M.stopPropagation();}else{M.cancelBubble=true;}},preventDefault:function(M){if(M.preventDefault){M.preventDefault();}else{M.returnValue=false;}},getEvent:function(O,M){var N=O||window.event;if(!N){var P=this.getEvent.caller;while(P){N=P.arguments[0];if(N&&Event==N.constructor){break;}P=P.caller;}}return N;},getCharCode:function(N){var M=N.keyCode||N.charCode||0;if(YAHOO.env.ua.webkit&&(M in D)){M=D[M];}return M;},_getCacheIndex:function(Q,R,P){for(var O=0,N=I.length;O<N;O=O+1){var M=I[O];if(M&&M[this.FN]==P&&M[this.EL]==Q&&M[this.TYPE]==R){return O;}}return -1;},generateId:function(M){var N=M.id;if(!N){N="yuievtautoid-"+A;++A;M.id=N;}return N;},_isValidCollection:function(N){try{return(N&&typeof N!=="string"&&N.length&&!N.tagName&&!N.alert&&typeof N[0]!=="undefined");}catch(M){return false;}},elCache:{},getEl:function(M){return(typeof M==="string")?document.getElementById(M):M;},clearCache:function(){},DOMReadyEvent:new YAHOO.util.CustomEvent("DOMReady",this),_load:function(N){if(!H){H=true;var M=YAHOO.util.Event;M._ready();M._tryPreloadAttach();}},_ready:function(N){var M=YAHOO.util.Event;if(!M.DOMReady){M.DOMReady=true;M.DOMReadyEvent.fire();M._simpleRemove(document,"DOMContentLoaded",M._ready);}},_tryPreloadAttach:function(){if(F.length===0){C=0;if(this._interval){clearInterval(this._interval);this._interval=null;}return;}if(this.locked){return;}if(this.isIE){if(!this.DOMReady){this.startInterval();return;}}this.locked=true;var S=!H;if(!S){S=(C>0&&F.length>0);}var R=[];var T=function(V,W){var U=V;if(W.overrideContext){if(W.overrideContext===true){U=W.obj;}else{U=W.overrideContext;}}W.fn.call(U,W.obj);};var N,M,Q,P,O=[];for(N=0,M=F.length;N<M;N=N+1){Q=F[N];if(Q){P=this.getEl(Q.id);if(P){if(Q.checkReady){if(H||P.nextSibling||!S){O.push(Q);F[N]=null;}}else{T(P,Q);F[N]=null;}}else{R.push(Q);}}}for(N=0,M=O.length;N<M;N=N+1){Q=O[N];T(this.getEl(Q.id),Q);}C--;if(S){for(N=F.length-1;N>-1;N--){Q=F[N];if(!Q||!Q.id){F.splice(N,1);}}this.startInterval();}else{if(this._interval){clearInterval(this._interval);this._interval=null;}}this.locked=false;},purgeElement:function(Q,R,T){var O=(YAHOO.lang.isString(Q))?this.getEl(Q):Q;var S=this.getListeners(O,T),P,M;if(S){for(P=S.length-1;P>-1;P--){var N=S[P];this.removeListener(O,N.type,N.fn);}}if(R&&O&&O.childNodes){for(P=0,M=O.childNodes.length;P<M;++P){this.purgeElement(O.childNodes[P],R,T);}}},getListeners:function(O,M){var R=[],N;if(!M){N=[I,J];}else{if(M==="unload"){N=[J];}else{N=[I];}}var T=(YAHOO.lang.isString(O))?this.getEl(O):O;for(var Q=0;Q<N.length;Q=Q+1){var V=N[Q];if(V){for(var S=0,U=V.length;S<U;++S){var P=V[S];if(P&&P[this.EL]===T&&(!M||M===P[this.TYPE])){R.push({type:P[this.TYPE],fn:P[this.FN],obj:P[this.OBJ],adjust:P[this.OVERRIDE],scope:P[this.ADJ_SCOPE],index:S});}}}}return(R.length)?R:null;},_unload:function(T){var N=YAHOO.util.Event,Q,P,O,S,R,U=J.slice(),M;for(Q=0,S=J.length;Q<S;++Q){O=U[Q];if(O){M=window;if(O[N.ADJ_SCOPE]){if(O[N.ADJ_SCOPE]===true){M=O[N.UNLOAD_OBJ];}else{M=O[N.ADJ_SCOPE];}}O[N.FN].call(M,N.getEvent(T,O[N.EL]),O[N.UNLOAD_OBJ]);U[Q]=null;}}O=null;M=null;J=null;if(I){for(P=I.length-1;P>-1;P--){O=I[P];if(O){N.removeListener(O[N.EL],O[N.TYPE],O[N.FN],P);}}O=null;}G=null;N._simpleRemove(window,"unload",N._unload);},_getScrollLeft:function(){return this._getScroll()[1];},_getScrollTop:function(){return this._getScroll()[0];},_getScroll:function(){var M=document.documentElement,N=document.body;if(M&&(M.scrollTop||M.scrollLeft)){return[M.scrollTop,M.scrollLeft];}else{if(N){return[N.scrollTop,N.scrollLeft];}else{return[0,0];}}},regCE:function(){},_simpleAdd:function(){if(window.addEventListener){return function(O,P,N,M){O.addEventListener(P,N,(M));};}else{if(window.attachEvent){return function(O,P,N,M){O.attachEvent("on"+P,N);};}else{return function(){};}}}(),_simpleRemove:function(){if(window.removeEventListener){return function(O,P,N,M){O.removeEventListener(P,N,(M));};}else{if(window.detachEvent){return function(N,O,M){N.detachEvent("on"+O,M);};}else{return function(){};}}}()};}();(function(){var EU=YAHOO.util.Event;EU.on=EU.addListener;EU.onFocus=EU.addFocusListener;EU.onBlur=EU.addBlurListener;
/* DOMReady: based on work by: Dean Edwards/John Resig/Matthias Miller */
if(EU.isIE){YAHOO.util.Event.onDOMReady(YAHOO.util.Event._tryPreloadAttach,YAHOO.util.Event,true);var n=document.createElement("p");EU._dri=setInterval(function(){try{n.doScroll("left");clearInterval(EU._dri);EU._dri=null;EU._ready();n=null;}catch(ex){}},EU.POLL_INTERVAL);}else{if(EU.webkit&&EU.webkit<525){EU._dri=setInterval(function(){var rs=document.readyState;if("loaded"==rs||"complete"==rs){clearInterval(EU._dri);EU._dri=null;EU._ready();}},EU.POLL_INTERVAL);}else{EU._simpleAdd(document,"DOMContentLoaded",EU._ready);}}EU._simpleAdd(window,"load",EU._load);EU._simpleAdd(window,"unload",EU._unload);EU._tryPreloadAttach();})();}YAHOO.util.EventProvider=function(){};YAHOO.util.EventProvider.prototype={__yui_events:null,__yui_subscribers:null,subscribe:function(A,C,F,E){this.__yui_events=this.__yui_events||{};var D=this.__yui_events[A];if(D){D.subscribe(C,F,E);
}else{this.__yui_subscribers=this.__yui_subscribers||{};var B=this.__yui_subscribers;if(!B[A]){B[A]=[];}B[A].push({fn:C,obj:F,overrideContext:E});}},unsubscribe:function(C,E,G){this.__yui_events=this.__yui_events||{};var A=this.__yui_events;if(C){var F=A[C];if(F){return F.unsubscribe(E,G);}}else{var B=true;for(var D in A){if(YAHOO.lang.hasOwnProperty(A,D)){B=B&&A[D].unsubscribe(E,G);}}return B;}return false;},unsubscribeAll:function(A){return this.unsubscribe(A);},createEvent:function(G,D){this.__yui_events=this.__yui_events||{};var A=D||{};var I=this.__yui_events;if(I[G]){}else{var H=A.scope||this;var E=(A.silent);var B=new YAHOO.util.CustomEvent(G,H,E,YAHOO.util.CustomEvent.FLAT);I[G]=B;if(A.onSubscribeCallback){B.subscribeEvent.subscribe(A.onSubscribeCallback);}this.__yui_subscribers=this.__yui_subscribers||{};var F=this.__yui_subscribers[G];if(F){for(var C=0;C<F.length;++C){B.subscribe(F[C].fn,F[C].obj,F[C].overrideContext);}}}return I[G];},fireEvent:function(E,D,A,C){this.__yui_events=this.__yui_events||{};var G=this.__yui_events[E];if(!G){return null;}var B=[];for(var F=1;F<arguments.length;++F){B.push(arguments[F]);}return G.fire.apply(G,B);},hasEvent:function(A){if(this.__yui_events){if(this.__yui_events[A]){return true;}}return false;}};(function(){var A=YAHOO.util.Event,C=YAHOO.lang;YAHOO.util.KeyListener=function(D,I,E,F){if(!D){}else{if(!I){}else{if(!E){}}}if(!F){F=YAHOO.util.KeyListener.KEYDOWN;}var G=new YAHOO.util.CustomEvent("keyPressed");this.enabledEvent=new YAHOO.util.CustomEvent("enabled");this.disabledEvent=new YAHOO.util.CustomEvent("disabled");if(C.isString(D)){D=document.getElementById(D);}if(C.isFunction(E)){G.subscribe(E);}else{G.subscribe(E.fn,E.scope,E.correctScope);}function H(O,N){if(!I.shift){I.shift=false;}if(!I.alt){I.alt=false;}if(!I.ctrl){I.ctrl=false;}if(O.shiftKey==I.shift&&O.altKey==I.alt&&O.ctrlKey==I.ctrl){var J,M=I.keys,L;if(YAHOO.lang.isArray(M)){for(var K=0;K<M.length;K++){J=M[K];L=A.getCharCode(O);if(J==L){G.fire(L,O);break;}}}else{L=A.getCharCode(O);if(M==L){G.fire(L,O);}}}}this.enable=function(){if(!this.enabled){A.on(D,F,H);this.enabledEvent.fire(I);}this.enabled=true;};this.disable=function(){if(this.enabled){A.removeListener(D,F,H);this.disabledEvent.fire(I);}this.enabled=false;};this.toString=function(){return"KeyListener ["+I.keys+"] "+D.tagName+(D.id?"["+D.id+"]":"");};};var B=YAHOO.util.KeyListener;B.KEYDOWN="keydown";B.KEYUP="keyup";B.KEY={ALT:18,BACK_SPACE:8,CAPS_LOCK:20,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,META:224,NUM_LOCK:144,PAGE_DOWN:34,PAGE_UP:33,PAUSE:19,PRINTSCREEN:44,RIGHT:39,SCROLL_LOCK:145,SHIFT:16,SPACE:32,TAB:9,UP:38};})();YAHOO.register("event",YAHOO.util.Event,{version:"2.7.0",build:"1796"});YAHOO.register("yahoo-dom-event", YAHOO, {version: "2.7.0", build: "1796"});
/*
Copyright (c) 2009, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.7.0
*/
if(!YAHOO.util.DragDropMgr){YAHOO.util.DragDropMgr=function(){var A=YAHOO.util.Event,B=YAHOO.util.Dom;return{useShim:false,_shimActive:false,_shimState:false,_debugShim:false,_createShim:function(){var C=document.createElement("div");C.id="yui-ddm-shim";if(document.body.firstChild){document.body.insertBefore(C,document.body.firstChild);}else{document.body.appendChild(C);}C.style.display="none";C.style.backgroundColor="red";C.style.position="absolute";C.style.zIndex="99999";B.setStyle(C,"opacity","0");this._shim=C;A.on(C,"mouseup",this.handleMouseUp,this,true);A.on(C,"mousemove",this.handleMouseMove,this,true);A.on(window,"scroll",this._sizeShim,this,true);},_sizeShim:function(){if(this._shimActive){var C=this._shim;C.style.height=B.getDocumentHeight()+"px";C.style.width=B.getDocumentWidth()+"px";C.style.top="0";C.style.left="0";}},_activateShim:function(){if(this.useShim){if(!this._shim){this._createShim();}this._shimActive=true;var C=this._shim,D="0";if(this._debugShim){D=".5";}B.setStyle(C,"opacity",D);this._sizeShim();C.style.display="block";}},_deactivateShim:function(){this._shim.style.display="none";this._shimActive=false;},_shim:null,ids:{},handleIds:{},dragCurrent:null,dragOvers:{},deltaX:0,deltaY:0,preventDefault:true,stopPropagation:true,initialized:false,locked:false,interactionInfo:null,init:function(){this.initialized=true;},POINT:0,INTERSECT:1,STRICT_INTERSECT:2,mode:0,_execOnAll:function(E,D){for(var F in this.ids){for(var C in this.ids[F]){var G=this.ids[F][C];if(!this.isTypeOfDD(G)){continue;}G[E].apply(G,D);}}},_onLoad:function(){this.init();A.on(document,"mouseup",this.handleMouseUp,this,true);A.on(document,"mousemove",this.handleMouseMove,this,true);A.on(window,"unload",this._onUnload,this,true);A.on(window,"resize",this._onResize,this,true);},_onResize:function(C){this._execOnAll("resetConstraints",[]);},lock:function(){this.locked=true;},unlock:function(){this.locked=false;},isLocked:function(){return this.locked;},locationCache:{},useCache:true,clickPixelThresh:3,clickTimeThresh:1000,dragThreshMet:false,clickTimeout:null,startX:0,startY:0,fromTimeout:false,regDragDrop:function(D,C){if(!this.initialized){this.init();}if(!this.ids[C]){this.ids[C]={};}this.ids[C][D.id]=D;},removeDDFromGroup:function(E,C){if(!this.ids[C]){this.ids[C]={};}var D=this.ids[C];if(D&&D[E.id]){delete D[E.id];}},_remove:function(E){for(var D in E.groups){if(D){var C=this.ids[D];if(C&&C[E.id]){delete C[E.id];}}}delete this.handleIds[E.id];},regHandle:function(D,C){if(!this.handleIds[D]){this.handleIds[D]={};}this.handleIds[D][C]=C;},isDragDrop:function(C){return(this.getDDById(C))?true:false;},getRelated:function(H,D){var G=[];for(var F in H.groups){for(var E in this.ids[F]){var C=this.ids[F][E];if(!this.isTypeOfDD(C)){continue;}if(!D||C.isTarget){G[G.length]=C;}}}return G;},isLegalTarget:function(G,F){var D=this.getRelated(G,true);for(var E=0,C=D.length;E<C;++E){if(D[E].id==F.id){return true;}}return false;},isTypeOfDD:function(C){return(C&&C.__ygDragDrop);},isHandle:function(D,C){return(this.handleIds[D]&&this.handleIds[D][C]);},getDDById:function(D){for(var C in this.ids){if(this.ids[C][D]){return this.ids[C][D];}}return null;},handleMouseDown:function(E,D){this.currentTarget=YAHOO.util.Event.getTarget(E);this.dragCurrent=D;var C=D.getEl();this.startX=YAHOO.util.Event.getPageX(E);this.startY=YAHOO.util.Event.getPageY(E);this.deltaX=this.startX-C.offsetLeft;this.deltaY=this.startY-C.offsetTop;this.dragThreshMet=false;this.clickTimeout=setTimeout(function(){var F=YAHOO.util.DDM;F.startDrag(F.startX,F.startY);F.fromTimeout=true;},this.clickTimeThresh);},startDrag:function(C,E){if(this.dragCurrent&&this.dragCurrent.useShim){this._shimState=this.useShim;this.useShim=true;}this._activateShim();clearTimeout(this.clickTimeout);var D=this.dragCurrent;if(D&&D.events.b4StartDrag){D.b4StartDrag(C,E);D.fireEvent("b4StartDragEvent",{x:C,y:E});}if(D&&D.events.startDrag){D.startDrag(C,E);D.fireEvent("startDragEvent",{x:C,y:E});}this.dragThreshMet=true;},handleMouseUp:function(C){if(this.dragCurrent){clearTimeout(this.clickTimeout);if(this.dragThreshMet){if(this.fromTimeout){this.fromTimeout=false;this.handleMouseMove(C);}this.fromTimeout=false;this.fireEvents(C,true);}else{}this.stopDrag(C);this.stopEvent(C);}},stopEvent:function(C){if(this.stopPropagation){YAHOO.util.Event.stopPropagation(C);}if(this.preventDefault){YAHOO.util.Event.preventDefault(C);}},stopDrag:function(E,D){var C=this.dragCurrent;if(C&&!D){if(this.dragThreshMet){if(C.events.b4EndDrag){C.b4EndDrag(E);C.fireEvent("b4EndDragEvent",{e:E});}if(C.events.endDrag){C.endDrag(E);C.fireEvent("endDragEvent",{e:E});}}if(C.events.mouseUp){C.onMouseUp(E);C.fireEvent("mouseUpEvent",{e:E});}}if(this._shimActive){this._deactivateShim();if(this.dragCurrent&&this.dragCurrent.useShim){this.useShim=this._shimState;this._shimState=false;}}this.dragCurrent=null;this.dragOvers={};},handleMouseMove:function(F){var C=this.dragCurrent;if(C){if(YAHOO.util.Event.isIE&&!F.button){this.stopEvent(F);return this.handleMouseUp(F);}else{if(F.clientX<0||F.clientY<0){}}if(!this.dragThreshMet){var E=Math.abs(this.startX-YAHOO.util.Event.getPageX(F));var D=Math.abs(this.startY-YAHOO.util.Event.getPageY(F));if(E>this.clickPixelThresh||D>this.clickPixelThresh){this.startDrag(this.startX,this.startY);}}if(this.dragThreshMet){if(C&&C.events.b4Drag){C.b4Drag(F);C.fireEvent("b4DragEvent",{e:F});}if(C&&C.events.drag){C.onDrag(F);C.fireEvent("dragEvent",{e:F});}if(C){this.fireEvents(F,false);}}this.stopEvent(F);}},fireEvents:function(V,L){var a=this.dragCurrent;if(!a||a.isLocked()||a.dragOnly){return;}var N=YAHOO.util.Event.getPageX(V),M=YAHOO.util.Event.getPageY(V),P=new YAHOO.util.Point(N,M),K=a.getTargetCoord(P.x,P.y),F=a.getDragEl(),E=["out","over","drop","enter"],U=new YAHOO.util.Region(K.y,K.x+F.offsetWidth,K.y+F.offsetHeight,K.x),I=[],D={},Q=[],c={outEvts:[],overEvts:[],dropEvts:[],enterEvts:[]};for(var S in this.dragOvers){var d=this.dragOvers[S];if(!this.isTypeOfDD(d)){continue;
}if(!this.isOverTarget(P,d,this.mode,U)){c.outEvts.push(d);}I[S]=true;delete this.dragOvers[S];}for(var R in a.groups){if("string"!=typeof R){continue;}for(S in this.ids[R]){var G=this.ids[R][S];if(!this.isTypeOfDD(G)){continue;}if(G.isTarget&&!G.isLocked()&&G!=a){if(this.isOverTarget(P,G,this.mode,U)){D[R]=true;if(L){c.dropEvts.push(G);}else{if(!I[G.id]){c.enterEvts.push(G);}else{c.overEvts.push(G);}this.dragOvers[G.id]=G;}}}}}this.interactionInfo={out:c.outEvts,enter:c.enterEvts,over:c.overEvts,drop:c.dropEvts,point:P,draggedRegion:U,sourceRegion:this.locationCache[a.id],validDrop:L};for(var C in D){Q.push(C);}if(L&&!c.dropEvts.length){this.interactionInfo.validDrop=false;if(a.events.invalidDrop){a.onInvalidDrop(V);a.fireEvent("invalidDropEvent",{e:V});}}for(S=0;S<E.length;S++){var Y=null;if(c[E[S]+"Evts"]){Y=c[E[S]+"Evts"];}if(Y&&Y.length){var H=E[S].charAt(0).toUpperCase()+E[S].substr(1),X="onDrag"+H,J="b4Drag"+H,O="drag"+H+"Event",W="drag"+H;if(this.mode){if(a.events[J]){a[J](V,Y,Q);a.fireEvent(J+"Event",{event:V,info:Y,group:Q});}if(a.events[W]){a[X](V,Y,Q);a.fireEvent(O,{event:V,info:Y,group:Q});}}else{for(var Z=0,T=Y.length;Z<T;++Z){if(a.events[J]){a[J](V,Y[Z].id,Q[0]);a.fireEvent(J+"Event",{event:V,info:Y[Z].id,group:Q[0]});}if(a.events[W]){a[X](V,Y[Z].id,Q[0]);a.fireEvent(O,{event:V,info:Y[Z].id,group:Q[0]});}}}}}},getBestMatch:function(E){var G=null;var D=E.length;if(D==1){G=E[0];}else{for(var F=0;F<D;++F){var C=E[F];if(this.mode==this.INTERSECT&&C.cursorIsOver){G=C;break;}else{if(!G||!G.overlap||(C.overlap&&G.overlap.getArea()<C.overlap.getArea())){G=C;}}}}return G;},refreshCache:function(D){var F=D||this.ids;for(var C in F){if("string"!=typeof C){continue;}for(var E in this.ids[C]){var G=this.ids[C][E];if(this.isTypeOfDD(G)){var H=this.getLocation(G);if(H){this.locationCache[G.id]=H;}else{delete this.locationCache[G.id];}}}}},verifyEl:function(D){try{if(D){var C=D.offsetParent;if(C){return true;}}}catch(E){}return false;},getLocation:function(H){if(!this.isTypeOfDD(H)){return null;}var F=H.getEl(),K,E,D,M,L,N,C,J,G;try{K=YAHOO.util.Dom.getXY(F);}catch(I){}if(!K){return null;}E=K[0];D=E+F.offsetWidth;M=K[1];L=M+F.offsetHeight;N=M-H.padding[0];C=D+H.padding[1];J=L+H.padding[2];G=E-H.padding[3];return new YAHOO.util.Region(N,C,J,G);},isOverTarget:function(K,C,E,F){var G=this.locationCache[C.id];if(!G||!this.useCache){G=this.getLocation(C);this.locationCache[C.id]=G;}if(!G){return false;}C.cursorIsOver=G.contains(K);var J=this.dragCurrent;if(!J||(!E&&!J.constrainX&&!J.constrainY)){return C.cursorIsOver;}C.overlap=null;if(!F){var H=J.getTargetCoord(K.x,K.y);var D=J.getDragEl();F=new YAHOO.util.Region(H.y,H.x+D.offsetWidth,H.y+D.offsetHeight,H.x);}var I=F.intersect(G);if(I){C.overlap=I;return(E)?true:C.cursorIsOver;}else{return false;}},_onUnload:function(D,C){this.unregAll();},unregAll:function(){if(this.dragCurrent){this.stopDrag();this.dragCurrent=null;}this._execOnAll("unreg",[]);this.ids={};},elementCache:{},getElWrapper:function(D){var C=this.elementCache[D];if(!C||!C.el){C=this.elementCache[D]=new this.ElementWrapper(YAHOO.util.Dom.get(D));}return C;},getElement:function(C){return YAHOO.util.Dom.get(C);},getCss:function(D){var C=YAHOO.util.Dom.get(D);return(C)?C.style:null;},ElementWrapper:function(C){this.el=C||null;this.id=this.el&&C.id;this.css=this.el&&C.style;},getPosX:function(C){return YAHOO.util.Dom.getX(C);},getPosY:function(C){return YAHOO.util.Dom.getY(C);},swapNode:function(E,C){if(E.swapNode){E.swapNode(C);}else{var F=C.parentNode;var D=C.nextSibling;if(D==E){F.insertBefore(E,C);}else{if(C==E.nextSibling){F.insertBefore(C,E);}else{E.parentNode.replaceChild(C,E);F.insertBefore(E,D);}}}},getScroll:function(){var E,C,F=document.documentElement,D=document.body;if(F&&(F.scrollTop||F.scrollLeft)){E=F.scrollTop;C=F.scrollLeft;}else{if(D){E=D.scrollTop;C=D.scrollLeft;}else{}}return{top:E,left:C};},getStyle:function(D,C){return YAHOO.util.Dom.getStyle(D,C);},getScrollTop:function(){return this.getScroll().top;},getScrollLeft:function(){return this.getScroll().left;},moveToEl:function(C,E){var D=YAHOO.util.Dom.getXY(E);YAHOO.util.Dom.setXY(C,D);},getClientHeight:function(){return YAHOO.util.Dom.getViewportHeight();},getClientWidth:function(){return YAHOO.util.Dom.getViewportWidth();},numericSort:function(D,C){return(D-C);},_timeoutCount:0,_addListeners:function(){var C=YAHOO.util.DDM;if(YAHOO.util.Event&&document){C._onLoad();}else{if(C._timeoutCount>2000){}else{setTimeout(C._addListeners,10);if(document&&document.body){C._timeoutCount+=1;}}}},handleWasClicked:function(C,E){if(this.isHandle(E,C.id)){return true;}else{var D=C.parentNode;while(D){if(this.isHandle(E,D.id)){return true;}else{D=D.parentNode;}}}return false;}};}();YAHOO.util.DDM=YAHOO.util.DragDropMgr;YAHOO.util.DDM._addListeners();}(function(){var A=YAHOO.util.Event;var B=YAHOO.util.Dom;YAHOO.util.DragDrop=function(E,C,D){if(E){this.init(E,C,D);}};YAHOO.util.DragDrop.prototype={events:null,on:function(){this.subscribe.apply(this,arguments);},id:null,config:null,dragElId:null,handleElId:null,invalidHandleTypes:null,invalidHandleIds:null,invalidHandleClasses:null,startPageX:0,startPageY:0,groups:null,locked:false,lock:function(){this.locked=true;},unlock:function(){this.locked=false;},isTarget:true,padding:null,dragOnly:false,useShim:false,_domRef:null,__ygDragDrop:true,constrainX:false,constrainY:false,minX:0,maxX:0,minY:0,maxY:0,deltaX:0,deltaY:0,maintainOffset:false,xTicks:null,yTicks:null,primaryButtonOnly:true,available:false,hasOuterHandles:false,cursorIsOver:false,overlap:null,b4StartDrag:function(C,D){},startDrag:function(C,D){},b4Drag:function(C){},onDrag:function(C){},onDragEnter:function(C,D){},b4DragOver:function(C){},onDragOver:function(C,D){},b4DragOut:function(C){},onDragOut:function(C,D){},b4DragDrop:function(C){},onDragDrop:function(C,D){},onInvalidDrop:function(C){},b4EndDrag:function(C){},endDrag:function(C){},b4MouseDown:function(C){},onMouseDown:function(C){},onMouseUp:function(C){},onAvailable:function(){},getEl:function(){if(!this._domRef){this._domRef=B.get(this.id);
}return this._domRef;},getDragEl:function(){return B.get(this.dragElId);},init:function(F,C,D){this.initTarget(F,C,D);A.on(this._domRef||this.id,"mousedown",this.handleMouseDown,this,true);for(var E in this.events){this.createEvent(E+"Event");}},initTarget:function(E,C,D){this.config=D||{};this.events={};this.DDM=YAHOO.util.DDM;this.groups={};if(typeof E!=="string"){this._domRef=E;E=B.generateId(E);}this.id=E;this.addToGroup((C)?C:"default");this.handleElId=E;A.onAvailable(E,this.handleOnAvailable,this,true);this.setDragElId(E);this.invalidHandleTypes={A:"A"};this.invalidHandleIds={};this.invalidHandleClasses=[];this.applyConfig();},applyConfig:function(){this.events={mouseDown:true,b4MouseDown:true,mouseUp:true,b4StartDrag:true,startDrag:true,b4EndDrag:true,endDrag:true,drag:true,b4Drag:true,invalidDrop:true,b4DragOut:true,dragOut:true,dragEnter:true,b4DragOver:true,dragOver:true,b4DragDrop:true,dragDrop:true};if(this.config.events){for(var C in this.config.events){if(this.config.events[C]===false){this.events[C]=false;}}}this.padding=this.config.padding||[0,0,0,0];this.isTarget=(this.config.isTarget!==false);this.maintainOffset=(this.config.maintainOffset);this.primaryButtonOnly=(this.config.primaryButtonOnly!==false);this.dragOnly=((this.config.dragOnly===true)?true:false);this.useShim=((this.config.useShim===true)?true:false);},handleOnAvailable:function(){this.available=true;this.resetConstraints();this.onAvailable();},setPadding:function(E,C,F,D){if(!C&&0!==C){this.padding=[E,E,E,E];}else{if(!F&&0!==F){this.padding=[E,C,E,C];}else{this.padding=[E,C,F,D];}}},setInitPosition:function(F,E){var G=this.getEl();if(!this.DDM.verifyEl(G)){if(G&&G.style&&(G.style.display=="none")){}else{}return;}var D=F||0;var C=E||0;var H=B.getXY(G);this.initPageX=H[0]-D;this.initPageY=H[1]-C;this.lastPageX=H[0];this.lastPageY=H[1];this.setStartPosition(H);},setStartPosition:function(D){var C=D||B.getXY(this.getEl());this.deltaSetXY=null;this.startPageX=C[0];this.startPageY=C[1];},addToGroup:function(C){this.groups[C]=true;this.DDM.regDragDrop(this,C);},removeFromGroup:function(C){if(this.groups[C]){delete this.groups[C];}this.DDM.removeDDFromGroup(this,C);},setDragElId:function(C){this.dragElId=C;},setHandleElId:function(C){if(typeof C!=="string"){C=B.generateId(C);}this.handleElId=C;this.DDM.regHandle(this.id,C);},setOuterHandleElId:function(C){if(typeof C!=="string"){C=B.generateId(C);}A.on(C,"mousedown",this.handleMouseDown,this,true);this.setHandleElId(C);this.hasOuterHandles=true;},unreg:function(){A.removeListener(this.id,"mousedown",this.handleMouseDown);this._domRef=null;this.DDM._remove(this);},isLocked:function(){return(this.DDM.isLocked()||this.locked);},handleMouseDown:function(J,I){var D=J.which||J.button;if(this.primaryButtonOnly&&D>1){return;}if(this.isLocked()){return;}var C=this.b4MouseDown(J),F=true;if(this.events.b4MouseDown){F=this.fireEvent("b4MouseDownEvent",J);}var E=this.onMouseDown(J),H=true;if(this.events.mouseDown){H=this.fireEvent("mouseDownEvent",J);}if((C===false)||(E===false)||(F===false)||(H===false)){return;}this.DDM.refreshCache(this.groups);var G=new YAHOO.util.Point(A.getPageX(J),A.getPageY(J));if(!this.hasOuterHandles&&!this.DDM.isOverTarget(G,this)){}else{if(this.clickValidator(J)){this.setStartPosition();this.DDM.handleMouseDown(J,this);this.DDM.stopEvent(J);}else{}}},clickValidator:function(D){var C=YAHOO.util.Event.getTarget(D);return(this.isValidHandleChild(C)&&(this.id==this.handleElId||this.DDM.handleWasClicked(C,this.id)));},getTargetCoord:function(E,D){var C=E-this.deltaX;var F=D-this.deltaY;if(this.constrainX){if(C<this.minX){C=this.minX;}if(C>this.maxX){C=this.maxX;}}if(this.constrainY){if(F<this.minY){F=this.minY;}if(F>this.maxY){F=this.maxY;}}C=this.getTick(C,this.xTicks);F=this.getTick(F,this.yTicks);return{x:C,y:F};},addInvalidHandleType:function(C){var D=C.toUpperCase();this.invalidHandleTypes[D]=D;},addInvalidHandleId:function(C){if(typeof C!=="string"){C=B.generateId(C);}this.invalidHandleIds[C]=C;},addInvalidHandleClass:function(C){this.invalidHandleClasses.push(C);},removeInvalidHandleType:function(C){var D=C.toUpperCase();delete this.invalidHandleTypes[D];},removeInvalidHandleId:function(C){if(typeof C!=="string"){C=B.generateId(C);}delete this.invalidHandleIds[C];},removeInvalidHandleClass:function(D){for(var E=0,C=this.invalidHandleClasses.length;E<C;++E){if(this.invalidHandleClasses[E]==D){delete this.invalidHandleClasses[E];}}},isValidHandleChild:function(F){var E=true;var H;try{H=F.nodeName.toUpperCase();}catch(G){H=F.nodeName;}E=E&&!this.invalidHandleTypes[H];E=E&&!this.invalidHandleIds[F.id];for(var D=0,C=this.invalidHandleClasses.length;E&&D<C;++D){E=!B.hasClass(F,this.invalidHandleClasses[D]);}return E;},setXTicks:function(F,C){this.xTicks=[];this.xTickSize=C;var E={};for(var D=this.initPageX;D>=this.minX;D=D-C){if(!E[D]){this.xTicks[this.xTicks.length]=D;E[D]=true;}}for(D=this.initPageX;D<=this.maxX;D=D+C){if(!E[D]){this.xTicks[this.xTicks.length]=D;E[D]=true;}}this.xTicks.sort(this.DDM.numericSort);},setYTicks:function(F,C){this.yTicks=[];this.yTickSize=C;var E={};for(var D=this.initPageY;D>=this.minY;D=D-C){if(!E[D]){this.yTicks[this.yTicks.length]=D;E[D]=true;}}for(D=this.initPageY;D<=this.maxY;D=D+C){if(!E[D]){this.yTicks[this.yTicks.length]=D;E[D]=true;}}this.yTicks.sort(this.DDM.numericSort);},setXConstraint:function(E,D,C){this.leftConstraint=parseInt(E,10);this.rightConstraint=parseInt(D,10);this.minX=this.initPageX-this.leftConstraint;this.maxX=this.initPageX+this.rightConstraint;if(C){this.setXTicks(this.initPageX,C);}this.constrainX=true;},clearConstraints:function(){this.constrainX=false;this.constrainY=false;this.clearTicks();},clearTicks:function(){this.xTicks=null;this.yTicks=null;this.xTickSize=0;this.yTickSize=0;},setYConstraint:function(C,E,D){this.topConstraint=parseInt(C,10);this.bottomConstraint=parseInt(E,10);this.minY=this.initPageY-this.topConstraint;this.maxY=this.initPageY+this.bottomConstraint;if(D){this.setYTicks(this.initPageY,D);
}this.constrainY=true;},resetConstraints:function(){if(this.initPageX||this.initPageX===0){var D=(this.maintainOffset)?this.lastPageX-this.initPageX:0;var C=(this.maintainOffset)?this.lastPageY-this.initPageY:0;this.setInitPosition(D,C);}else{this.setInitPosition();}if(this.constrainX){this.setXConstraint(this.leftConstraint,this.rightConstraint,this.xTickSize);}if(this.constrainY){this.setYConstraint(this.topConstraint,this.bottomConstraint,this.yTickSize);}},getTick:function(I,F){if(!F){return I;}else{if(F[0]>=I){return F[0];}else{for(var D=0,C=F.length;D<C;++D){var E=D+1;if(F[E]&&F[E]>=I){var H=I-F[D];var G=F[E]-I;return(G>H)?F[D]:F[E];}}return F[F.length-1];}}},toString:function(){return("DragDrop "+this.id);}};YAHOO.augment(YAHOO.util.DragDrop,YAHOO.util.EventProvider);})();YAHOO.util.DD=function(C,A,B){if(C){this.init(C,A,B);}};YAHOO.extend(YAHOO.util.DD,YAHOO.util.DragDrop,{scroll:true,autoOffset:function(C,B){var A=C-this.startPageX;var D=B-this.startPageY;this.setDelta(A,D);},setDelta:function(B,A){this.deltaX=B;this.deltaY=A;},setDragElPos:function(C,B){var A=this.getDragEl();this.alignElWithMouse(A,C,B);},alignElWithMouse:function(C,G,F){var E=this.getTargetCoord(G,F);if(!this.deltaSetXY){var H=[E.x,E.y];YAHOO.util.Dom.setXY(C,H);var D=parseInt(YAHOO.util.Dom.getStyle(C,"left"),10);var B=parseInt(YAHOO.util.Dom.getStyle(C,"top"),10);this.deltaSetXY=[D-E.x,B-E.y];}else{YAHOO.util.Dom.setStyle(C,"left",(E.x+this.deltaSetXY[0])+"px");YAHOO.util.Dom.setStyle(C,"top",(E.y+this.deltaSetXY[1])+"px");}this.cachePosition(E.x,E.y);var A=this;setTimeout(function(){A.autoScroll.call(A,E.x,E.y,C.offsetHeight,C.offsetWidth);},0);},cachePosition:function(B,A){if(B){this.lastPageX=B;this.lastPageY=A;}else{var C=YAHOO.util.Dom.getXY(this.getEl());this.lastPageX=C[0];this.lastPageY=C[1];}},autoScroll:function(J,I,E,K){if(this.scroll){var L=this.DDM.getClientHeight();var B=this.DDM.getClientWidth();var N=this.DDM.getScrollTop();var D=this.DDM.getScrollLeft();var H=E+I;var M=K+J;var G=(L+N-I-this.deltaY);var F=(B+D-J-this.deltaX);var C=40;var A=(document.all)?80:30;if(H>L&&G<C){window.scrollTo(D,N+A);}if(I<N&&N>0&&I-N<C){window.scrollTo(D,N-A);}if(M>B&&F<C){window.scrollTo(D+A,N);}if(J<D&&D>0&&J-D<C){window.scrollTo(D-A,N);}}},applyConfig:function(){YAHOO.util.DD.superclass.applyConfig.call(this);this.scroll=(this.config.scroll!==false);},b4MouseDown:function(A){this.setStartPosition();this.autoOffset(YAHOO.util.Event.getPageX(A),YAHOO.util.Event.getPageY(A));},b4Drag:function(A){this.setDragElPos(YAHOO.util.Event.getPageX(A),YAHOO.util.Event.getPageY(A));},toString:function(){return("DD "+this.id);}});YAHOO.util.DDProxy=function(C,A,B){if(C){this.init(C,A,B);this.initFrame();}};YAHOO.util.DDProxy.dragElId="ygddfdiv";YAHOO.extend(YAHOO.util.DDProxy,YAHOO.util.DD,{resizeFrame:true,centerFrame:false,createFrame:function(){var B=this,A=document.body;if(!A||!A.firstChild){setTimeout(function(){B.createFrame();},50);return;}var F=this.getDragEl(),E=YAHOO.util.Dom;if(!F){F=document.createElement("div");F.id=this.dragElId;var D=F.style;D.position="absolute";D.visibility="hidden";D.cursor="move";D.border="2px solid #aaa";D.zIndex=999;D.height="25px";D.width="25px";var C=document.createElement("div");E.setStyle(C,"height","100%");E.setStyle(C,"width","100%");E.setStyle(C,"background-color","#ccc");E.setStyle(C,"opacity","0");F.appendChild(C);A.insertBefore(F,A.firstChild);}},initFrame:function(){this.createFrame();},applyConfig:function(){YAHOO.util.DDProxy.superclass.applyConfig.call(this);this.resizeFrame=(this.config.resizeFrame!==false);this.centerFrame=(this.config.centerFrame);this.setDragElId(this.config.dragElId||YAHOO.util.DDProxy.dragElId);},showFrame:function(E,D){var C=this.getEl();var A=this.getDragEl();var B=A.style;this._resizeProxy();if(this.centerFrame){this.setDelta(Math.round(parseInt(B.width,10)/2),Math.round(parseInt(B.height,10)/2));}this.setDragElPos(E,D);YAHOO.util.Dom.setStyle(A,"visibility","visible");},_resizeProxy:function(){if(this.resizeFrame){var H=YAHOO.util.Dom;var B=this.getEl();var C=this.getDragEl();var G=parseInt(H.getStyle(C,"borderTopWidth"),10);var I=parseInt(H.getStyle(C,"borderRightWidth"),10);var F=parseInt(H.getStyle(C,"borderBottomWidth"),10);var D=parseInt(H.getStyle(C,"borderLeftWidth"),10);if(isNaN(G)){G=0;}if(isNaN(I)){I=0;}if(isNaN(F)){F=0;}if(isNaN(D)){D=0;}var E=Math.max(0,B.offsetWidth-I-D);var A=Math.max(0,B.offsetHeight-G-F);H.setStyle(C,"width",E+"px");H.setStyle(C,"height",A+"px");}},b4MouseDown:function(B){this.setStartPosition();var A=YAHOO.util.Event.getPageX(B);var C=YAHOO.util.Event.getPageY(B);this.autoOffset(A,C);},b4StartDrag:function(A,B){this.showFrame(A,B);},b4EndDrag:function(A){YAHOO.util.Dom.setStyle(this.getDragEl(),"visibility","hidden");},endDrag:function(D){var C=YAHOO.util.Dom;var B=this.getEl();var A=this.getDragEl();C.setStyle(A,"visibility","");C.setStyle(B,"visibility","hidden");YAHOO.util.DDM.moveToEl(B,A);C.setStyle(A,"visibility","hidden");C.setStyle(B,"visibility","");},toString:function(){return("DDProxy "+this.id);}});YAHOO.util.DDTarget=function(C,A,B){if(C){this.initTarget(C,A,B);}};YAHOO.extend(YAHOO.util.DDTarget,YAHOO.util.DragDrop,{toString:function(){return("DDTarget "+this.id);}});YAHOO.register("dragdrop",YAHOO.util.DragDropMgr,{version:"2.7.0",build:"1796"});/*
Copyright (c) 2009, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.7.0
*/
(function(){var B=YAHOO.util.Dom.getXY,A=YAHOO.util.Event,D=Array.prototype.slice;function C(G,E,F,H){C.ANIM_AVAIL=(!YAHOO.lang.isUndefined(YAHOO.util.Anim));if(G){this.init(G,E,true);this.initSlider(H);this.initThumb(F);}}YAHOO.lang.augmentObject(C,{getHorizSlider:function(F,G,I,H,E){return new C(F,F,new YAHOO.widget.SliderThumb(G,F,I,H,0,0,E),"horiz");},getVertSlider:function(G,H,E,I,F){return new C(G,G,new YAHOO.widget.SliderThumb(H,G,0,0,E,I,F),"vert");},getSliderRegion:function(G,H,J,I,E,K,F){return new C(G,G,new YAHOO.widget.SliderThumb(H,G,J,I,E,K,F),"region");},SOURCE_UI_EVENT:1,SOURCE_SET_VALUE:2,SOURCE_KEY_EVENT:3,ANIM_AVAIL:false},true);YAHOO.extend(C,YAHOO.util.DragDrop,{_mouseDown:false,dragOnly:true,initSlider:function(E){this.type=E;this.createEvent("change",this);this.createEvent("slideStart",this);this.createEvent("slideEnd",this);this.isTarget=false;this.animate=C.ANIM_AVAIL;this.backgroundEnabled=true;this.tickPause=40;this.enableKeys=true;this.keyIncrement=20;this.moveComplete=true;this.animationDuration=0.2;this.SOURCE_UI_EVENT=1;this.SOURCE_SET_VALUE=2;this.valueChangeSource=0;this._silent=false;this.lastOffset=[0,0];},initThumb:function(F){var E=this;this.thumb=F;F.cacheBetweenDrags=true;if(F._isHoriz&&F.xTicks&&F.xTicks.length){this.tickPause=Math.round(360/F.xTicks.length);}else{if(F.yTicks&&F.yTicks.length){this.tickPause=Math.round(360/F.yTicks.length);}}F.onAvailable=function(){return E.setStartSliderState();};F.onMouseDown=function(){E._mouseDown=true;return E.focus();};F.startDrag=function(){E._slideStart();};F.onDrag=function(){E.fireEvents(true);};F.onMouseUp=function(){E.thumbMouseUp();};},onAvailable:function(){this._bindKeyEvents();},_bindKeyEvents:function(){A.on(this.id,"keydown",this.handleKeyDown,this,true);A.on(this.id,"keypress",this.handleKeyPress,this,true);},handleKeyPress:function(F){if(this.enableKeys){var E=A.getCharCode(F);switch(E){case 37:case 38:case 39:case 40:case 36:case 35:A.preventDefault(F);break;default:}}},handleKeyDown:function(J){if(this.enableKeys){var G=A.getCharCode(J),F=this.thumb,H=this.getXValue(),E=this.getYValue(),I=true;switch(G){case 37:H-=this.keyIncrement;break;case 38:E-=this.keyIncrement;break;case 39:H+=this.keyIncrement;break;case 40:E+=this.keyIncrement;break;case 36:H=F.leftConstraint;E=F.topConstraint;break;case 35:H=F.rightConstraint;E=F.bottomConstraint;break;default:I=false;}if(I){if(F._isRegion){this._setRegionValue(C.SOURCE_KEY_EVENT,H,E,true);}else{this._setValue(C.SOURCE_KEY_EVENT,(F._isHoriz?H:E),true);}A.stopEvent(J);}}},setStartSliderState:function(){this.setThumbCenterPoint();this.baselinePos=B(this.getEl());this.thumb.startOffset=this.thumb.getOffsetFromParent(this.baselinePos);if(this.thumb._isRegion){if(this.deferredSetRegionValue){this._setRegionValue.apply(this,this.deferredSetRegionValue);this.deferredSetRegionValue=null;}else{this.setRegionValue(0,0,true,true,true);}}else{if(this.deferredSetValue){this._setValue.apply(this,this.deferredSetValue);this.deferredSetValue=null;}else{this.setValue(0,true,true,true);}}},setThumbCenterPoint:function(){var E=this.thumb.getEl();if(E){this.thumbCenterPoint={x:parseInt(E.offsetWidth/2,10),y:parseInt(E.offsetHeight/2,10)};}},lock:function(){this.thumb.lock();this.locked=true;},unlock:function(){this.thumb.unlock();this.locked=false;},thumbMouseUp:function(){this._mouseDown=false;if(!this.isLocked()&&!this.moveComplete){this.endMove();}},onMouseUp:function(){this._mouseDown=false;if(this.backgroundEnabled&&!this.isLocked()&&!this.moveComplete){this.endMove();}},getThumb:function(){return this.thumb;},focus:function(){this.valueChangeSource=C.SOURCE_UI_EVENT;var E=this.getEl();if(E.focus){try{E.focus();}catch(F){}}this.verifyOffset();return !this.isLocked();},onChange:function(E,F){},onSlideStart:function(){},onSlideEnd:function(){},getValue:function(){return this.thumb.getValue();},getXValue:function(){return this.thumb.getXValue();},getYValue:function(){return this.thumb.getYValue();},setValue:function(){var E=D.call(arguments);E.unshift(C.SOURCE_SET_VALUE);return this._setValue.apply(this,E);},_setValue:function(I,L,G,H,E){var F=this.thumb,K,J;if(!F.available){this.deferredSetValue=arguments;return false;}if(this.isLocked()&&!H){return false;}if(isNaN(L)){return false;}if(F._isRegion){return false;}this._silent=E;this.valueChangeSource=I||C.SOURCE_SET_VALUE;F.lastOffset=[L,L];this.verifyOffset(true);this._slideStart();if(F._isHoriz){K=F.initPageX+L+this.thumbCenterPoint.x;this.moveThumb(K,F.initPageY,G);}else{J=F.initPageY+L+this.thumbCenterPoint.y;this.moveThumb(F.initPageX,J,G);}return true;},setRegionValue:function(){var E=D.call(arguments);E.unshift(C.SOURCE_SET_VALUE);return this._setRegionValue.apply(this,E);},_setRegionValue:function(F,J,H,I,G,K){var L=this.thumb,E,M;if(!L.available){this.deferredSetRegionValue=arguments;return false;}if(this.isLocked()&&!G){return false;}if(isNaN(J)){return false;}if(!L._isRegion){return false;}this._silent=K;this.valueChangeSource=F||C.SOURCE_SET_VALUE;L.lastOffset=[J,H];this.verifyOffset(true);this._slideStart();E=L.initPageX+J+this.thumbCenterPoint.x;M=L.initPageY+H+this.thumbCenterPoint.y;this.moveThumb(E,M,I);return true;},verifyOffset:function(F){var G=B(this.getEl()),E=this.thumb;if(!this.thumbCenterPoint||!this.thumbCenterPoint.x){this.setThumbCenterPoint();}if(G){if(G[0]!=this.baselinePos[0]||G[1]!=this.baselinePos[1]){this.setInitPosition();this.baselinePos=G;E.initPageX=this.initPageX+E.startOffset[0];E.initPageY=this.initPageY+E.startOffset[1];E.deltaSetXY=null;this.resetThumbConstraints();return false;}}return true;},moveThumb:function(K,J,I,G){var L=this.thumb,M=this,F,E,H;if(!L.available){return;}L.setDelta(this.thumbCenterPoint.x,this.thumbCenterPoint.y);E=L.getTargetCoord(K,J);F=[Math.round(E.x),Math.round(E.y)];if(this.animate&&L._graduated&&!I){this.lock();this.curCoord=B(this.thumb.getEl());this.curCoord=[Math.round(this.curCoord[0]),Math.round(this.curCoord[1])];setTimeout(function(){M.moveOneTick(F);
},this.tickPause);}else{if(this.animate&&C.ANIM_AVAIL&&!I){this.lock();H=new YAHOO.util.Motion(L.id,{points:{to:F}},this.animationDuration,YAHOO.util.Easing.easeOut);H.onComplete.subscribe(function(){M.unlock();if(!M._mouseDown){M.endMove();}});H.animate();}else{L.setDragElPos(K,J);if(!G&&!this._mouseDown){this.endMove();}}}},_slideStart:function(){if(!this._sliding){if(!this._silent){this.onSlideStart();this.fireEvent("slideStart");}this._sliding=true;}},_slideEnd:function(){if(this._sliding&&this.moveComplete){var E=this._silent;this._sliding=false;this._silent=false;this.moveComplete=false;if(!E){this.onSlideEnd();this.fireEvent("slideEnd");}}},moveOneTick:function(F){var H=this.thumb,G=this,I=null,E,J;if(H._isRegion){I=this._getNextX(this.curCoord,F);E=(I!==null)?I[0]:this.curCoord[0];I=this._getNextY(this.curCoord,F);J=(I!==null)?I[1]:this.curCoord[1];I=E!==this.curCoord[0]||J!==this.curCoord[1]?[E,J]:null;}else{if(H._isHoriz){I=this._getNextX(this.curCoord,F);}else{I=this._getNextY(this.curCoord,F);}}if(I){this.curCoord=I;this.thumb.alignElWithMouse(H.getEl(),I[0]+this.thumbCenterPoint.x,I[1]+this.thumbCenterPoint.y);if(!(I[0]==F[0]&&I[1]==F[1])){setTimeout(function(){G.moveOneTick(F);},this.tickPause);}else{this.unlock();if(!this._mouseDown){this.endMove();}}}else{this.unlock();if(!this._mouseDown){this.endMove();}}},_getNextX:function(E,F){var H=this.thumb,J,G=[],I=null;if(E[0]>F[0]){J=H.tickSize-this.thumbCenterPoint.x;G=H.getTargetCoord(E[0]-J,E[1]);I=[G.x,G.y];}else{if(E[0]<F[0]){J=H.tickSize+this.thumbCenterPoint.x;G=H.getTargetCoord(E[0]+J,E[1]);I=[G.x,G.y];}else{}}return I;},_getNextY:function(E,F){var H=this.thumb,J,G=[],I=null;if(E[1]>F[1]){J=H.tickSize-this.thumbCenterPoint.y;G=H.getTargetCoord(E[0],E[1]-J);I=[G.x,G.y];}else{if(E[1]<F[1]){J=H.tickSize+this.thumbCenterPoint.y;G=H.getTargetCoord(E[0],E[1]+J);I=[G.x,G.y];}else{}}return I;},b4MouseDown:function(E){if(!this.backgroundEnabled){return false;}this.thumb.autoOffset();this.resetThumbConstraints();},onMouseDown:function(F){if(!this.backgroundEnabled||this.isLocked()){return false;}this._mouseDown=true;var E=A.getPageX(F),G=A.getPageY(F);this.focus();this._slideStart();this.moveThumb(E,G);},onDrag:function(F){if(this.backgroundEnabled&&!this.isLocked()){var E=A.getPageX(F),G=A.getPageY(F);this.moveThumb(E,G,true,true);this.fireEvents();}},endMove:function(){this.unlock();this.fireEvents();this.moveComplete=true;this._slideEnd();},resetThumbConstraints:function(){var E=this.thumb;E.setXConstraint(E.leftConstraint,E.rightConstraint,E.xTickSize);E.setYConstraint(E.topConstraint,E.bottomConstraint,E.xTickSize);},fireEvents:function(G){var F=this.thumb,I,H,E;if(!G){F.cachePosition();}if(!this.isLocked()){if(F._isRegion){I=F.getXValue();H=F.getYValue();if(I!=this.previousX||H!=this.previousY){if(!this._silent){this.onChange(I,H);this.fireEvent("change",{x:I,y:H});}}this.previousX=I;this.previousY=H;}else{E=F.getValue();if(E!=this.previousVal){if(!this._silent){this.onChange(E);this.fireEvent("change",E);}}this.previousVal=E;}}},toString:function(){return("Slider ("+this.type+") "+this.id);}});YAHOO.lang.augmentProto(C,YAHOO.util.EventProvider);YAHOO.widget.Slider=C;})();YAHOO.widget.SliderThumb=function(G,B,E,D,A,F,C){if(G){YAHOO.widget.SliderThumb.superclass.constructor.call(this,G,B);this.parentElId=B;}this.isTarget=false;this.tickSize=C;this.maintainOffset=true;this.initSlider(E,D,A,F,C);this.scroll=false;};YAHOO.extend(YAHOO.widget.SliderThumb,YAHOO.util.DD,{startOffset:null,dragOnly:true,_isHoriz:false,_prevVal:0,_graduated:false,getOffsetFromParent0:function(C){var A=YAHOO.util.Dom.getXY(this.getEl()),B=C||YAHOO.util.Dom.getXY(this.parentElId);return[(A[0]-B[0]),(A[1]-B[1])];},getOffsetFromParent:function(H){var A=this.getEl(),E,I,F,B,K,D,C,J,G;if(!this.deltaOffset){I=YAHOO.util.Dom.getXY(A);F=H||YAHOO.util.Dom.getXY(this.parentElId);E=[(I[0]-F[0]),(I[1]-F[1])];B=parseInt(YAHOO.util.Dom.getStyle(A,"left"),10);K=parseInt(YAHOO.util.Dom.getStyle(A,"top"),10);D=B-E[0];C=K-E[1];if(isNaN(D)||isNaN(C)){}else{this.deltaOffset=[D,C];}}else{J=parseInt(YAHOO.util.Dom.getStyle(A,"left"),10);G=parseInt(YAHOO.util.Dom.getStyle(A,"top"),10);E=[J+this.deltaOffset[0],G+this.deltaOffset[1]];}return E;},initSlider:function(D,C,A,E,B){this.initLeft=D;this.initRight=C;this.initUp=A;this.initDown=E;this.setXConstraint(D,C,B);this.setYConstraint(A,E,B);if(B&&B>1){this._graduated=true;}this._isHoriz=(D||C);this._isVert=(A||E);this._isRegion=(this._isHoriz&&this._isVert);},clearTicks:function(){YAHOO.widget.SliderThumb.superclass.clearTicks.call(this);this.tickSize=0;this._graduated=false;},getValue:function(){return(this._isHoriz)?this.getXValue():this.getYValue();},getXValue:function(){if(!this.available){return 0;}var A=this.getOffsetFromParent();if(YAHOO.lang.isNumber(A[0])){this.lastOffset=A;return(A[0]-this.startOffset[0]);}else{return(this.lastOffset[0]-this.startOffset[0]);}},getYValue:function(){if(!this.available){return 0;}var A=this.getOffsetFromParent();if(YAHOO.lang.isNumber(A[1])){this.lastOffset=A;return(A[1]-this.startOffset[1]);}else{return(this.lastOffset[1]-this.startOffset[1]);}},toString:function(){return"SliderThumb "+this.id;},onChange:function(A,B){}});(function(){var A=YAHOO.util.Event,B=YAHOO.widget;function C(I,F,H,D){var G=this,J={min:false,max:false},E,K;this.minSlider=I;this.maxSlider=F;this.activeSlider=I;this.isHoriz=I.thumb._isHoriz;E=this.minSlider.thumb.onMouseDown;K=this.maxSlider.thumb.onMouseDown;this.minSlider.thumb.onMouseDown=function(){G.activeSlider=G.minSlider;E.apply(this,arguments);};this.maxSlider.thumb.onMouseDown=function(){G.activeSlider=G.maxSlider;K.apply(this,arguments);};this.minSlider.thumb.onAvailable=function(){I.setStartSliderState();J.min=true;if(J.max){G.fireEvent("ready",G);}};this.maxSlider.thumb.onAvailable=function(){F.setStartSliderState();J.max=true;if(J.min){G.fireEvent("ready",G);}};I.onMouseDown=F.onMouseDown=function(L){return this.backgroundEnabled&&G._handleMouseDown(L);
};I.onDrag=F.onDrag=function(L){G._handleDrag(L);};I.onMouseUp=F.onMouseUp=function(L){G._handleMouseUp(L);};I._bindKeyEvents=function(){G._bindKeyEvents(this);};F._bindKeyEvents=function(){};I.subscribe("change",this._handleMinChange,I,this);I.subscribe("slideStart",this._handleSlideStart,I,this);I.subscribe("slideEnd",this._handleSlideEnd,I,this);F.subscribe("change",this._handleMaxChange,F,this);F.subscribe("slideStart",this._handleSlideStart,F,this);F.subscribe("slideEnd",this._handleSlideEnd,F,this);this.createEvent("ready",this);this.createEvent("change",this);this.createEvent("slideStart",this);this.createEvent("slideEnd",this);D=YAHOO.lang.isArray(D)?D:[0,H];D[0]=Math.min(Math.max(parseInt(D[0],10)|0,0),H);D[1]=Math.max(Math.min(parseInt(D[1],10)|0,H),0);if(D[0]>D[1]){D.splice(0,2,D[1],D[0]);}this.minVal=D[0];this.maxVal=D[1];this.minSlider.setValue(this.minVal,true,true,true);this.maxSlider.setValue(this.maxVal,true,true,true);}C.prototype={minVal:-1,maxVal:-1,minRange:0,_handleSlideStart:function(E,D){this.fireEvent("slideStart",D);},_handleSlideEnd:function(E,D){this.fireEvent("slideEnd",D);},_handleDrag:function(D){B.Slider.prototype.onDrag.call(this.activeSlider,D);},_handleMinChange:function(){this.activeSlider=this.minSlider;this.updateValue();},_handleMaxChange:function(){this.activeSlider=this.maxSlider;this.updateValue();},_bindKeyEvents:function(D){A.on(D.id,"keydown",this._handleKeyDown,this,true);A.on(D.id,"keypress",this._handleKeyPress,this,true);},_handleKeyDown:function(D){this.activeSlider.handleKeyDown.apply(this.activeSlider,arguments);},_handleKeyPress:function(D){this.activeSlider.handleKeyPress.apply(this.activeSlider,arguments);},setValues:function(H,K,I,E,J){var F=this.minSlider,M=this.maxSlider,D=F.thumb,L=M.thumb,N=this,G={min:false,max:false};if(D._isHoriz){D.setXConstraint(D.leftConstraint,L.rightConstraint,D.tickSize);L.setXConstraint(D.leftConstraint,L.rightConstraint,L.tickSize);}else{D.setYConstraint(D.topConstraint,L.bottomConstraint,D.tickSize);L.setYConstraint(D.topConstraint,L.bottomConstraint,L.tickSize);}this._oneTimeCallback(F,"slideEnd",function(){G.min=true;if(G.max){N.updateValue(J);setTimeout(function(){N._cleanEvent(F,"slideEnd");N._cleanEvent(M,"slideEnd");},0);}});this._oneTimeCallback(M,"slideEnd",function(){G.max=true;if(G.min){N.updateValue(J);setTimeout(function(){N._cleanEvent(F,"slideEnd");N._cleanEvent(M,"slideEnd");},0);}});F.setValue(H,I,E,false);M.setValue(K,I,E,false);},setMinValue:function(F,H,I,E){var G=this.minSlider,D=this;this.activeSlider=G;D=this;this._oneTimeCallback(G,"slideEnd",function(){D.updateValue(E);setTimeout(function(){D._cleanEvent(G,"slideEnd");},0);});G.setValue(F,H,I);},setMaxValue:function(D,H,I,F){var G=this.maxSlider,E=this;this.activeSlider=G;this._oneTimeCallback(G,"slideEnd",function(){E.updateValue(F);setTimeout(function(){E._cleanEvent(G,"slideEnd");},0);});G.setValue(D,H,I);},updateValue:function(J){var E=this.minSlider.getValue(),K=this.maxSlider.getValue(),F=false,D,M,H,I,L,G;if(E!=this.minVal||K!=this.maxVal){F=true;D=this.minSlider.thumb;M=this.maxSlider.thumb;H=this.isHoriz?"x":"y";G=this.minSlider.thumbCenterPoint[H]+this.maxSlider.thumbCenterPoint[H];I=Math.max(K-G-this.minRange,0);L=Math.min(-E-G-this.minRange,0);if(this.isHoriz){I=Math.min(I,M.rightConstraint);D.setXConstraint(D.leftConstraint,I,D.tickSize);M.setXConstraint(L,M.rightConstraint,M.tickSize);}else{I=Math.min(I,M.bottomConstraint);D.setYConstraint(D.leftConstraint,I,D.tickSize);M.setYConstraint(L,M.bottomConstraint,M.tickSize);}}this.minVal=E;this.maxVal=K;if(F&&!J){this.fireEvent("change",this);}},selectActiveSlider:function(H){var E=this.minSlider,D=this.maxSlider,J=E.isLocked()||!E.backgroundEnabled,G=D.isLocked()||!E.backgroundEnabled,F=YAHOO.util.Event,I;if(J||G){this.activeSlider=J?D:E;}else{if(this.isHoriz){I=F.getPageX(H)-E.thumb.initPageX-E.thumbCenterPoint.x;}else{I=F.getPageY(H)-E.thumb.initPageY-E.thumbCenterPoint.y;}this.activeSlider=I*2>D.getValue()+E.getValue()?D:E;}},_handleMouseDown:function(D){if(!D._handled){D._handled=true;this.selectActiveSlider(D);return B.Slider.prototype.onMouseDown.call(this.activeSlider,D);}else{return false;}},_handleMouseUp:function(D){B.Slider.prototype.onMouseUp.apply(this.activeSlider,arguments);},_oneTimeCallback:function(F,D,E){F.subscribe(D,function(){F.unsubscribe(D,arguments.callee);E.apply({},[].slice.apply(arguments));});},_cleanEvent:function(K,E){var J,I,D,G,H,F;if(K.__yui_events&&K.events[E]){for(I=K.__yui_events.length;I>=0;--I){if(K.__yui_events[I].type===E){J=K.__yui_events[I];break;}}if(J){H=J.subscribers;F=[];G=0;for(I=0,D=H.length;I<D;++I){if(H[I]){F[G++]=H[I];}}J.subscribers=F;}}}};YAHOO.lang.augmentProto(C,YAHOO.util.EventProvider);B.Slider.getHorizDualSlider=function(H,J,K,G,F,D){var I=new B.SliderThumb(J,H,0,G,0,0,F),E=new B.SliderThumb(K,H,0,G,0,0,F);return new C(new B.Slider(H,H,I,"horiz"),new B.Slider(H,H,E,"horiz"),G,D);};B.Slider.getVertDualSlider=function(H,J,K,G,F,D){var I=new B.SliderThumb(J,H,0,0,0,G,F),E=new B.SliderThumb(K,H,0,0,0,G,F);return new B.DualSlider(new B.Slider(H,H,I,"vert"),new B.Slider(H,H,E,"vert"),G,D);};YAHOO.widget.DualSlider=C;})();YAHOO.register("slider",YAHOO.widget.Slider,{version:"2.7.0",build:"1796"});/*
Copyright (c) 2009, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.7.0
*/
YAHOO.util.Attribute=function(B,A){if(A){this.owner=A;this.configure(B,true);}};YAHOO.util.Attribute.prototype={name:undefined,value:null,owner:null,readOnly:false,writeOnce:false,_initialConfig:null,_written:false,method:null,setter:null,getter:null,validator:null,getValue:function(){var A=this.value;if(this.getter){A=this.getter.call(this.owner,this.name);}return A;},setValue:function(F,B){var E,A=this.owner,C=this.name;var D={type:C,prevValue:this.getValue(),newValue:F};if(this.readOnly||(this.writeOnce&&this._written)){return false;}if(this.validator&&!this.validator.call(A,F)){return false;}if(!B){E=A.fireBeforeChangeEvent(D);if(E===false){return false;}}if(this.setter){F=this.setter.call(A,F,this.name);if(F===undefined){}}if(this.method){this.method.call(A,F,this.name);}this.value=F;this._written=true;D.type=C;if(!B){this.owner.fireChangeEvent(D);}return true;},configure:function(B,C){B=B||{};if(C){this._written=false;}this._initialConfig=this._initialConfig||{};for(var A in B){if(B.hasOwnProperty(A)){this[A]=B[A];if(C){this._initialConfig[A]=B[A];}}}},resetValue:function(){return this.setValue(this._initialConfig.value);},resetConfig:function(){this.configure(this._initialConfig,true);},refresh:function(A){this.setValue(this.value,A);}};(function(){var A=YAHOO.util.Lang;YAHOO.util.AttributeProvider=function(){};YAHOO.util.AttributeProvider.prototype={_configs:null,get:function(C){this._configs=this._configs||{};var B=this._configs[C];if(!B||!this._configs.hasOwnProperty(C)){return null;}return B.getValue();},set:function(D,E,B){this._configs=this._configs||{};var C=this._configs[D];if(!C){return false;}return C.setValue(E,B);},getAttributeKeys:function(){this._configs=this._configs;var C=[],B;for(B in this._configs){if(A.hasOwnProperty(this._configs,B)&&!A.isUndefined(this._configs[B])){C[C.length]=B;}}return C;},setAttributes:function(D,B){for(var C in D){if(A.hasOwnProperty(D,C)){this.set(C,D[C],B);}}},resetValue:function(C,B){this._configs=this._configs||{};if(this._configs[C]){this.set(C,this._configs[C]._initialConfig.value,B);return true;}return false;},refresh:function(E,C){this._configs=this._configs||{};var F=this._configs;E=((A.isString(E))?[E]:E)||this.getAttributeKeys();for(var D=0,B=E.length;D<B;++D){if(F.hasOwnProperty(E[D])){this._configs[E[D]].refresh(C);}}},register:function(B,C){this.setAttributeConfig(B,C);},getAttributeConfig:function(C){this._configs=this._configs||{};var B=this._configs[C]||{};var D={};for(C in B){if(A.hasOwnProperty(B,C)){D[C]=B[C];}}return D;},setAttributeConfig:function(B,C,D){this._configs=this._configs||{};C=C||{};if(!this._configs[B]){C.name=B;this._configs[B]=this.createAttribute(C);}else{this._configs[B].configure(C,D);}},configureAttribute:function(B,C,D){this.setAttributeConfig(B,C,D);},resetAttributeConfig:function(B){this._configs=this._configs||{};this._configs[B].resetConfig();},subscribe:function(B,C){this._events=this._events||{};if(!(B in this._events)){this._events[B]=this.createEvent(B);}YAHOO.util.EventProvider.prototype.subscribe.apply(this,arguments);},on:function(){this.subscribe.apply(this,arguments);},addListener:function(){this.subscribe.apply(this,arguments);},fireBeforeChangeEvent:function(C){var B="before";B+=C.type.charAt(0).toUpperCase()+C.type.substr(1)+"Change";C.type=B;return this.fireEvent(C.type,C);},fireChangeEvent:function(B){B.type+="Change";return this.fireEvent(B.type,B);},createAttribute:function(B){return new YAHOO.util.Attribute(B,this);}};YAHOO.augment(YAHOO.util.AttributeProvider,YAHOO.util.EventProvider);})();(function(){var B=YAHOO.util.Dom,C=YAHOO.util.AttributeProvider;var A=function(D,E){this.init.apply(this,arguments);};A.DOM_EVENTS={"click":true,"dblclick":true,"keydown":true,"keypress":true,"keyup":true,"mousedown":true,"mousemove":true,"mouseout":true,"mouseover":true,"mouseup":true,"focus":true,"blur":true,"submit":true,"change":true};A.prototype={DOM_EVENTS:null,DEFAULT_HTML_SETTER:function(F,D){var E=this.get("element");if(E){E[D]=F;}},DEFAULT_HTML_GETTER:function(D){var E=this.get("element"),F;if(E){F=E[D];}return F;},appendChild:function(D){D=D.get?D.get("element"):D;return this.get("element").appendChild(D);},getElementsByTagName:function(D){return this.get("element").getElementsByTagName(D);},hasChildNodes:function(){return this.get("element").hasChildNodes();},insertBefore:function(D,E){D=D.get?D.get("element"):D;E=(E&&E.get)?E.get("element"):E;return this.get("element").insertBefore(D,E);},removeChild:function(D){D=D.get?D.get("element"):D;return this.get("element").removeChild(D);},replaceChild:function(D,E){D=D.get?D.get("element"):D;E=E.get?E.get("element"):E;return this.get("element").replaceChild(D,E);},initAttributes:function(D){},addListener:function(H,G,I,F){var E=this.get("element")||this.get("id");F=F||this;var D=this;if(!this._events[H]){if(E&&this.DOM_EVENTS[H]){YAHOO.util.Event.addListener(E,H,function(J){if(J.srcElement&&!J.target){J.target=J.srcElement;}D.fireEvent(H,J);},I,F);}this.createEvent(H,this);}return YAHOO.util.EventProvider.prototype.subscribe.apply(this,arguments);},on:function(){return this.addListener.apply(this,arguments);},subscribe:function(){return this.addListener.apply(this,arguments);},removeListener:function(E,D){return this.unsubscribe.apply(this,arguments);},addClass:function(D){B.addClass(this.get("element"),D);},getElementsByClassName:function(E,D){return B.getElementsByClassName(E,D,this.get("element"));},hasClass:function(D){return B.hasClass(this.get("element"),D);},removeClass:function(D){return B.removeClass(this.get("element"),D);},replaceClass:function(E,D){return B.replaceClass(this.get("element"),E,D);},setStyle:function(E,D){return B.setStyle(this.get("element"),E,D);},getStyle:function(D){return B.getStyle(this.get("element"),D);},fireQueue:function(){var E=this._queue;for(var F=0,D=E.length;F<D;++F){this[E[F][0]].apply(this,E[F][1]);}},appendTo:function(E,F){E=(E.get)?E.get("element"):B.get(E);this.fireEvent("beforeAppendTo",{type:"beforeAppendTo",target:E});
F=(F&&F.get)?F.get("element"):B.get(F);var D=this.get("element");if(!D){return false;}if(!E){return false;}if(D.parent!=E){if(F){E.insertBefore(D,F);}else{E.appendChild(D);}}this.fireEvent("appendTo",{type:"appendTo",target:E});return D;},get:function(D){var F=this._configs||{},E=F.element;if(E&&!F[D]&&!YAHOO.lang.isUndefined(E.value[D])){this._setHTMLAttrConfig(D);}return C.prototype.get.call(this,D);},setAttributes:function(J,G){var E={},H=this._configOrder;for(var I=0,D=H.length;I<D;++I){if(J[H[I]]!==undefined){E[H[I]]=true;this.set(H[I],J[H[I]],G);}}for(var F in J){if(J.hasOwnProperty(F)&&!E[F]){this.set(F,J[F],G);}}},set:function(E,G,D){var F=this.get("element");if(!F){this._queue[this._queue.length]=["set",arguments];if(this._configs[E]){this._configs[E].value=G;}return;}if(!this._configs[E]&&!YAHOO.lang.isUndefined(F[E])){this._setHTMLAttrConfig(E);}return C.prototype.set.apply(this,arguments);},setAttributeConfig:function(D,E,F){this._configOrder.push(D);C.prototype.setAttributeConfig.apply(this,arguments);},createEvent:function(E,D){this._events[E]=true;return C.prototype.createEvent.apply(this,arguments);},init:function(E,D){this._initElement(E,D);},destroy:function(){var D=this.get("element");YAHOO.util.Event.purgeElement(D,true);this.unsubscribeAll();if(D&&D.parentNode){D.parentNode.removeChild(D);}this._queue=[];this._events={};this._configs={};this._configOrder=[];},_initElement:function(F,E){this._queue=this._queue||[];this._events=this._events||{};this._configs=this._configs||{};this._configOrder=[];E=E||{};E.element=E.element||F||null;var H=false;var D=A.DOM_EVENTS;this.DOM_EVENTS=this.DOM_EVENTS||{};for(var G in D){if(D.hasOwnProperty(G)){this.DOM_EVENTS[G]=D[G];}}if(typeof E.element==="string"){this._setHTMLAttrConfig("id",{value:E.element});}if(B.get(E.element)){H=true;this._initHTMLElement(E);this._initContent(E);}YAHOO.util.Event.onAvailable(E.element,function(){if(!H){this._initHTMLElement(E);}this.fireEvent("available",{type:"available",target:B.get(E.element)});},this,true);YAHOO.util.Event.onContentReady(E.element,function(){if(!H){this._initContent(E);}this.fireEvent("contentReady",{type:"contentReady",target:B.get(E.element)});},this,true);},_initHTMLElement:function(D){this.setAttributeConfig("element",{value:B.get(D.element),readOnly:true});},_initContent:function(D){this.initAttributes(D);this.setAttributes(D,true);this.fireQueue();},_setHTMLAttrConfig:function(D,F){var E=this.get("element");F=F||{};F.name=D;F.setter=F.setter||this.DEFAULT_HTML_SETTER;F.getter=F.getter||this.DEFAULT_HTML_GETTER;F.value=F.value||E[D];this._configs[D]=new YAHOO.util.Attribute(F,this);}};YAHOO.augment(A,C);YAHOO.util.Element=A;})();YAHOO.register("element",YAHOO.util.Element,{version:"2.7.0",build:"1796"});/*
Copyright (c) 2009, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.7.0
*/
YAHOO.util.Color=function(){var A="0",B=YAHOO.lang.isArray,C=YAHOO.lang.isNumber;return{real2dec:function(D){return Math.min(255,Math.round(D*256));},hsv2rgb:function(H,O,M){if(B(H)){return this.hsv2rgb.call(this,H[0],H[1],H[2]);}var D,I,L,G=Math.floor((H/60)%6),J=(H/60)-G,F=M*(1-O),E=M*(1-J*O),N=M*(1-(1-J)*O),K;switch(G){case 0:D=M;I=N;L=F;break;case 1:D=E;I=M;L=F;break;case 2:D=F;I=M;L=N;break;case 3:D=F;I=E;L=M;break;case 4:D=N;I=F;L=M;break;case 5:D=M;I=F;L=E;break;}K=this.real2dec;return[K(D),K(I),K(L)];},rgb2hsv:function(D,H,I){if(B(D)){return this.rgb2hsv.apply(this,D);}D/=255;H/=255;I/=255;var G,L,E=Math.min(Math.min(D,H),I),J=Math.max(Math.max(D,H),I),K=J-E,F;switch(J){case E:G=0;break;case D:G=60*(H-I)/K;if(H<I){G+=360;}break;case H:G=(60*(I-D)/K)+120;break;case I:G=(60*(D-H)/K)+240;break;}L=(J===0)?0:1-(E/J);F=[Math.round(G),L,J];return F;},rgb2hex:function(F,E,D){if(B(F)){return this.rgb2hex.apply(this,F);}var G=this.dec2hex;return G(F)+G(E)+G(D);},dec2hex:function(D){D=parseInt(D,10)|0;D=(D>255||D<0)?0:D;return(A+D.toString(16)).slice(-2).toUpperCase();},hex2dec:function(D){return parseInt(D,16);},hex2rgb:function(D){var E=this.hex2dec;return[E(D.slice(0,2)),E(D.slice(2,4)),E(D.slice(4,6))];},websafe:function(F,E,D){if(B(F)){return this.websafe.apply(this,F);}var G=function(H){if(C(H)){H=Math.min(Math.max(0,H),255);var I,J;for(I=0;I<256;I=I+51){J=I+51;if(H>=I&&H<=J){return(H-I>25)?J:I;}}}return H;};return[G(F),G(E),G(D)];}};}();(function(){var J=0,F=YAHOO.util,C=YAHOO.lang,D=YAHOO.widget.Slider,B=F.Color,E=F.Dom,I=F.Event,A=C.substitute,H="yui-picker";function G(L,K){J=J+1;K=K||{};if(arguments.length===1&&!YAHOO.lang.isString(L)&&!L.nodeName){K=L;L=K.element||null;}if(!L&&!K.element){L=this._createHostElement(K);}G.superclass.constructor.call(this,L,K);this.initPicker();}YAHOO.extend(G,YAHOO.util.Element,{ID:{R:H+"-r",R_HEX:H+"-rhex",G:H+"-g",G_HEX:H+"-ghex",B:H+"-b",B_HEX:H+"-bhex",H:H+"-h",S:H+"-s",V:H+"-v",PICKER_BG:H+"-bg",PICKER_THUMB:H+"-thumb",HUE_BG:H+"-hue-bg",HUE_THUMB:H+"-hue-thumb",HEX:H+"-hex",SWATCH:H+"-swatch",WEBSAFE_SWATCH:H+"-websafe-swatch",CONTROLS:H+"-controls",RGB_CONTROLS:H+"-rgb-controls",HSV_CONTROLS:H+"-hsv-controls",HEX_CONTROLS:H+"-hex-controls",HEX_SUMMARY:H+"-hex-summary",CONTROLS_LABEL:H+"-controls-label"},TXT:{ILLEGAL_HEX:"Illegal hex value entered",SHOW_CONTROLS:"Show color details",HIDE_CONTROLS:"Hide color details",CURRENT_COLOR:"Currently selected color: {rgb}",CLOSEST_WEBSAFE:"Closest websafe color: {rgb}. Click to select.",R:"R",G:"G",B:"B",H:"H",S:"S",V:"V",HEX:"#",DEG:"\u00B0",PERCENT:"%"},IMAGE:{PICKER_THUMB:"../../build/colorpicker/assets/picker_thumb.png",HUE_THUMB:"../../build/colorpicker/assets/hue_thumb.png"},DEFAULT:{PICKER_SIZE:180},OPT:{HUE:"hue",SATURATION:"saturation",VALUE:"value",RED:"red",GREEN:"green",BLUE:"blue",HSV:"hsv",RGB:"rgb",WEBSAFE:"websafe",HEX:"hex",PICKER_SIZE:"pickersize",SHOW_CONTROLS:"showcontrols",SHOW_RGB_CONTROLS:"showrgbcontrols",SHOW_HSV_CONTROLS:"showhsvcontrols",SHOW_HEX_CONTROLS:"showhexcontrols",SHOW_HEX_SUMMARY:"showhexsummary",SHOW_WEBSAFE:"showwebsafe",CONTAINER:"container",IDS:"ids",ELEMENTS:"elements",TXT:"txt",IMAGES:"images",ANIMATE:"animate"},skipAnim:true,_createHostElement:function(){var K=document.createElement("div");if(this.CSS.BASE){K.className=this.CSS.BASE;}return K;},_updateHueSlider:function(){var K=this.get(this.OPT.PICKER_SIZE),L=this.get(this.OPT.HUE);L=K-Math.round(L/360*K);if(L===K){L=0;}this.hueSlider.setValue(L,this.skipAnim);},_updatePickerSlider:function(){var L=this.get(this.OPT.PICKER_SIZE),M=this.get(this.OPT.SATURATION),K=this.get(this.OPT.VALUE);M=Math.round(M*L/100);K=Math.round(L-(K*L/100));this.pickerSlider.setRegionValue(M,K,this.skipAnim);},_updateSliders:function(){this._updateHueSlider();this._updatePickerSlider();},setValue:function(L,K){K=(K)||false;this.set(this.OPT.RGB,L,K);this._updateSliders();},hueSlider:null,pickerSlider:null,_getH:function(){var K=this.get(this.OPT.PICKER_SIZE),L=(K-this.hueSlider.getValue())/K;L=Math.round(L*360);return(L===360)?0:L;},_getS:function(){return this.pickerSlider.getXValue()/this.get(this.OPT.PICKER_SIZE);},_getV:function(){var K=this.get(this.OPT.PICKER_SIZE);return(K-this.pickerSlider.getYValue())/K;},_updateSwatch:function(){var M=this.get(this.OPT.RGB),O=this.get(this.OPT.WEBSAFE),N=this.getElement(this.ID.SWATCH),L=M.join(","),K=this.get(this.OPT.TXT);E.setStyle(N,"background-color","rgb("+L+")");N.title=A(K.CURRENT_COLOR,{"rgb":"#"+this.get(this.OPT.HEX)});N=this.getElement(this.ID.WEBSAFE_SWATCH);L=O.join(",");E.setStyle(N,"background-color","rgb("+L+")");N.title=A(K.CLOSEST_WEBSAFE,{"rgb":"#"+B.rgb2hex(O)});},_getValuesFromSliders:function(){this.set(this.OPT.RGB,B.hsv2rgb(this._getH(),this._getS(),this._getV()));},_updateFormFields:function(){this.getElement(this.ID.H).value=this.get(this.OPT.HUE);this.getElement(this.ID.S).value=this.get(this.OPT.SATURATION);this.getElement(this.ID.V).value=this.get(this.OPT.VALUE);this.getElement(this.ID.R).value=this.get(this.OPT.RED);this.getElement(this.ID.R_HEX).innerHTML=B.dec2hex(this.get(this.OPT.RED));this.getElement(this.ID.G).value=this.get(this.OPT.GREEN);this.getElement(this.ID.G_HEX).innerHTML=B.dec2hex(this.get(this.OPT.GREEN));this.getElement(this.ID.B).value=this.get(this.OPT.BLUE);this.getElement(this.ID.B_HEX).innerHTML=B.dec2hex(this.get(this.OPT.BLUE));this.getElement(this.ID.HEX).value=this.get(this.OPT.HEX);},_onHueSliderChange:function(N){var L=this._getH(),K=B.hsv2rgb(L,1,1),M="rgb("+K.join(",")+")";this.set(this.OPT.HUE,L,true);E.setStyle(this.getElement(this.ID.PICKER_BG),"background-color",M);if(this.hueSlider.valueChangeSource!==D.SOURCE_SET_VALUE){this._getValuesFromSliders();}this._updateFormFields();this._updateSwatch();},_onPickerSliderChange:function(M){var L=this._getS(),K=this._getV();this.set(this.OPT.SATURATION,Math.round(L*100),true);this.set(this.OPT.VALUE,Math.round(K*100),true);if(this.pickerSlider.valueChangeSource!==D.SOURCE_SET_VALUE){this._getValuesFromSliders();
}this._updateFormFields();this._updateSwatch();},_getCommand:function(K){var L=I.getCharCode(K);if(L===38){return 3;}else{if(L===13){return 6;}else{if(L===40){return 4;}else{if(L>=48&&L<=57){return 1;}else{if(L>=97&&L<=102){return 2;}else{if(L>=65&&L<=70){return 2;}else{if("8, 9, 13, 27, 37, 39".indexOf(L)>-1||K.ctrlKey||K.metaKey){return 5;}else{return 0;}}}}}}}},_useFieldValue:function(L,K,N){var M=K.value;if(N!==this.OPT.HEX){M=parseInt(M,10);}if(M!==this.get(N)){this.set(N,M);}},_rgbFieldKeypress:function(M,K,O){var N=this._getCommand(M),L=(M.shiftKey)?10:1;switch(N){case 6:this._useFieldValue.apply(this,arguments);break;case 3:this.set(O,Math.min(this.get(O)+L,255));this._updateFormFields();break;case 4:this.set(O,Math.max(this.get(O)-L,0));this._updateFormFields();break;default:}},_hexFieldKeypress:function(L,K,N){var M=this._getCommand(L);if(M===6){this._useFieldValue.apply(this,arguments);}},_hexOnly:function(L,K){var M=this._getCommand(L);switch(M){case 6:case 5:case 1:break;case 2:if(K!==true){break;}default:I.stopEvent(L);return false;}},_numbersOnly:function(K){return this._hexOnly(K,true);},getElement:function(K){return this.get(this.OPT.ELEMENTS)[this.get(this.OPT.IDS)[K]];},_createElements:function(){var N,M,P,O,L,K=this.get(this.OPT.IDS),Q=this.get(this.OPT.TXT),S=this.get(this.OPT.IMAGES),R=function(U,V){var W=document.createElement(U);if(V){C.augmentObject(W,V,true);}return W;},T=function(U,V){var W=C.merge({autocomplete:"off",value:"0",size:3,maxlength:3},V);W.name=W.id;return new R(U,W);};L=this.get("element");N=new R("div",{id:K[this.ID.PICKER_BG],className:"yui-picker-bg",tabIndex:-1,hideFocus:true});M=new R("div",{id:K[this.ID.PICKER_THUMB],className:"yui-picker-thumb"});P=new R("img",{src:S.PICKER_THUMB});M.appendChild(P);N.appendChild(M);L.appendChild(N);N=new R("div",{id:K[this.ID.HUE_BG],className:"yui-picker-hue-bg",tabIndex:-1,hideFocus:true});M=new R("div",{id:K[this.ID.HUE_THUMB],className:"yui-picker-hue-thumb"});P=new R("img",{src:S.HUE_THUMB});M.appendChild(P);N.appendChild(M);L.appendChild(N);N=new R("div",{id:K[this.ID.CONTROLS],className:"yui-picker-controls"});L.appendChild(N);L=N;N=new R("div",{className:"hd"});M=new R("a",{id:K[this.ID.CONTROLS_LABEL],href:"#"});N.appendChild(M);L.appendChild(N);N=new R("div",{className:"bd"});L.appendChild(N);L=N;N=new R("ul",{id:K[this.ID.RGB_CONTROLS],className:"yui-picker-rgb-controls"});M=new R("li");M.appendChild(document.createTextNode(Q.R+" "));O=new T("input",{id:K[this.ID.R],className:"yui-picker-r"});M.appendChild(O);N.appendChild(M);M=new R("li");M.appendChild(document.createTextNode(Q.G+" "));O=new T("input",{id:K[this.ID.G],className:"yui-picker-g"});M.appendChild(O);N.appendChild(M);M=new R("li");M.appendChild(document.createTextNode(Q.B+" "));O=new T("input",{id:K[this.ID.B],className:"yui-picker-b"});M.appendChild(O);N.appendChild(M);L.appendChild(N);N=new R("ul",{id:K[this.ID.HSV_CONTROLS],className:"yui-picker-hsv-controls"});M=new R("li");M.appendChild(document.createTextNode(Q.H+" "));O=new T("input",{id:K[this.ID.H],className:"yui-picker-h"});M.appendChild(O);M.appendChild(document.createTextNode(" "+Q.DEG));N.appendChild(M);M=new R("li");M.appendChild(document.createTextNode(Q.S+" "));O=new T("input",{id:K[this.ID.S],className:"yui-picker-s"});M.appendChild(O);M.appendChild(document.createTextNode(" "+Q.PERCENT));N.appendChild(M);M=new R("li");M.appendChild(document.createTextNode(Q.V+" "));O=new T("input",{id:K[this.ID.V],className:"yui-picker-v"});M.appendChild(O);M.appendChild(document.createTextNode(" "+Q.PERCENT));N.appendChild(M);L.appendChild(N);N=new R("ul",{id:K[this.ID.HEX_SUMMARY],className:"yui-picker-hex_summary"});M=new R("li",{id:K[this.ID.R_HEX]});N.appendChild(M);M=new R("li",{id:K[this.ID.G_HEX]});N.appendChild(M);M=new R("li",{id:K[this.ID.B_HEX]});N.appendChild(M);L.appendChild(N);N=new R("div",{id:K[this.ID.HEX_CONTROLS],className:"yui-picker-hex-controls"});N.appendChild(document.createTextNode(Q.HEX+" "));M=new T("input",{id:K[this.ID.HEX],className:"yui-picker-hex",size:6,maxlength:6});N.appendChild(M);L.appendChild(N);L=this.get("element");N=new R("div",{id:K[this.ID.SWATCH],className:"yui-picker-swatch"});L.appendChild(N);N=new R("div",{id:K[this.ID.WEBSAFE_SWATCH],className:"yui-picker-websafe-swatch"});L.appendChild(N);},_attachRGBHSV:function(L,K){I.on(this.getElement(L),"keydown",function(N,M){M._rgbFieldKeypress(N,this,K);},this);I.on(this.getElement(L),"keypress",this._numbersOnly,this,true);I.on(this.getElement(L),"blur",function(N,M){M._useFieldValue(N,this,K);},this);},_updateRGB:function(){var K=[this.get(this.OPT.RED),this.get(this.OPT.GREEN),this.get(this.OPT.BLUE)];this.set(this.OPT.RGB,K);this._updateSliders();},_initElements:function(){var O=this.OPT,N=this.get(O.IDS),L=this.get(O.ELEMENTS),K,M,P;for(K in this.ID){if(C.hasOwnProperty(this.ID,K)){N[this.ID[K]]=N[K];}}M=E.get(N[this.ID.PICKER_BG]);if(!M){this._createElements();}else{}for(K in N){if(C.hasOwnProperty(N,K)){M=E.get(N[K]);P=E.generateId(M);N[K]=P;N[N[K]]=P;L[P]=M;}}},initPicker:function(){this._initSliders();this._bindUI();this.syncUI(true);},_initSliders:function(){var K=this.ID,L=this.get(this.OPT.PICKER_SIZE);this.hueSlider=D.getVertSlider(this.getElement(K.HUE_BG),this.getElement(K.HUE_THUMB),0,L);this.pickerSlider=D.getSliderRegion(this.getElement(K.PICKER_BG),this.getElement(K.PICKER_THUMB),0,L,0,L);this.set(this.OPT.ANIMATE,this.get(this.OPT.ANIMATE));},_bindUI:function(){var K=this.ID,L=this.OPT;this.hueSlider.subscribe("change",this._onHueSliderChange,this,true);this.pickerSlider.subscribe("change",this._onPickerSliderChange,this,true);I.on(this.getElement(K.WEBSAFE_SWATCH),"click",function(M){this.setValue(this.get(L.WEBSAFE));},this,true);I.on(this.getElement(K.CONTROLS_LABEL),"click",function(M){this.set(L.SHOW_CONTROLS,!this.get(L.SHOW_CONTROLS));I.preventDefault(M);},this,true);this._attachRGBHSV(K.R,L.RED);this._attachRGBHSV(K.G,L.GREEN);this._attachRGBHSV(K.B,L.BLUE);this._attachRGBHSV(K.H,L.HUE);
this._attachRGBHSV(K.S,L.SATURATION);this._attachRGBHSV(K.V,L.VALUE);I.on(this.getElement(K.HEX),"keydown",function(N,M){M._hexFieldKeypress(N,this,L.HEX);},this);I.on(this.getElement(this.ID.HEX),"keypress",this._hexOnly,this,true);I.on(this.getElement(this.ID.HEX),"blur",function(N,M){M._useFieldValue(N,this,L.HEX);},this);},syncUI:function(K){this.skipAnim=K;this._updateRGB();this.skipAnim=false;},_updateRGBFromHSV:function(){var L=[this.get(this.OPT.HUE),this.get(this.OPT.SATURATION)/100,this.get(this.OPT.VALUE)/100],K=B.hsv2rgb(L);this.set(this.OPT.RGB,K);this._updateSliders();},_updateHex:function(){var N=this.get(this.OPT.HEX),K=N.length,O,M,L;if(K===3){O=N.split("");for(M=0;M<K;M=M+1){O[M]=O[M]+O[M];}N=O.join("");}if(N.length!==6){return false;}L=B.hex2rgb(N);this.setValue(L);},_hideShowEl:function(M,K){var L=(C.isString(M)?this.getElement(M):M);E.setStyle(L,"display",(K)?"":"none");},initAttributes:function(K){K=K||{};G.superclass.initAttributes.call(this,K);this.setAttributeConfig(this.OPT.PICKER_SIZE,{value:K.size||this.DEFAULT.PICKER_SIZE});this.setAttributeConfig(this.OPT.HUE,{value:K.hue||0,validator:C.isNumber});this.setAttributeConfig(this.OPT.SATURATION,{value:K.saturation||0,validator:C.isNumber});this.setAttributeConfig(this.OPT.VALUE,{value:C.isNumber(K.value)?K.value:100,validator:C.isNumber});this.setAttributeConfig(this.OPT.RED,{value:C.isNumber(K.red)?K.red:255,validator:C.isNumber});this.setAttributeConfig(this.OPT.GREEN,{value:C.isNumber(K.green)?K.green:255,validator:C.isNumber});this.setAttributeConfig(this.OPT.BLUE,{value:C.isNumber(K.blue)?K.blue:255,validator:C.isNumber});this.setAttributeConfig(this.OPT.HEX,{value:K.hex||"FFFFFF",validator:C.isString});this.setAttributeConfig(this.OPT.RGB,{value:K.rgb||[255,255,255],method:function(O){this.set(this.OPT.RED,O[0],true);this.set(this.OPT.GREEN,O[1],true);this.set(this.OPT.BLUE,O[2],true);var Q=B.websafe(O),P=B.rgb2hex(O),N=B.rgb2hsv(O);this.set(this.OPT.WEBSAFE,Q,true);this.set(this.OPT.HEX,P,true);if(N[1]){this.set(this.OPT.HUE,N[0],true);}this.set(this.OPT.SATURATION,Math.round(N[1]*100),true);this.set(this.OPT.VALUE,Math.round(N[2]*100),true);},readonly:true});this.setAttributeConfig(this.OPT.CONTAINER,{value:null,method:function(N){if(N){N.showEvent.subscribe(function(){this.pickerSlider.focus();},this,true);}}});this.setAttributeConfig(this.OPT.WEBSAFE,{value:K.websafe||[255,255,255]});var M=K.ids||C.merge({},this.ID),L;if(!K.ids&&J>1){for(L in M){if(C.hasOwnProperty(M,L)){M[L]=M[L]+J;}}}this.setAttributeConfig(this.OPT.IDS,{value:M,writeonce:true});this.setAttributeConfig(this.OPT.TXT,{value:K.txt||this.TXT,writeonce:true});this.setAttributeConfig(this.OPT.IMAGES,{value:K.images||this.IMAGE,writeonce:true});this.setAttributeConfig(this.OPT.ELEMENTS,{value:{},readonly:true});this.setAttributeConfig(this.OPT.SHOW_CONTROLS,{value:C.isBoolean(K.showcontrols)?K.showcontrols:true,method:function(N){var O=E.getElementsByClassName("bd","div",this.getElement(this.ID.CONTROLS))[0];this._hideShowEl(O,N);this.getElement(this.ID.CONTROLS_LABEL).innerHTML=(N)?this.get(this.OPT.TXT).HIDE_CONTROLS:this.get(this.OPT.TXT).SHOW_CONTROLS;}});this.setAttributeConfig(this.OPT.SHOW_RGB_CONTROLS,{value:C.isBoolean(K.showrgbcontrols)?K.showrgbcontrols:true,method:function(N){this._hideShowEl(this.ID.RGB_CONTROLS,N);}});this.setAttributeConfig(this.OPT.SHOW_HSV_CONTROLS,{value:C.isBoolean(K.showhsvcontrols)?K.showhsvcontrols:false,method:function(N){this._hideShowEl(this.ID.HSV_CONTROLS,N);if(N&&this.get(this.OPT.SHOW_HEX_SUMMARY)){this.set(this.OPT.SHOW_HEX_SUMMARY,false);}}});this.setAttributeConfig(this.OPT.SHOW_HEX_CONTROLS,{value:C.isBoolean(K.showhexcontrols)?K.showhexcontrols:false,method:function(N){this._hideShowEl(this.ID.HEX_CONTROLS,N);}});this.setAttributeConfig(this.OPT.SHOW_WEBSAFE,{value:C.isBoolean(K.showwebsafe)?K.showwebsafe:true,method:function(N){this._hideShowEl(this.ID.WEBSAFE_SWATCH,N);}});this.setAttributeConfig(this.OPT.SHOW_HEX_SUMMARY,{value:C.isBoolean(K.showhexsummary)?K.showhexsummary:true,method:function(N){this._hideShowEl(this.ID.HEX_SUMMARY,N);if(N&&this.get(this.OPT.SHOW_HSV_CONTROLS)){this.set(this.OPT.SHOW_HSV_CONTROLS,false);}}});this.setAttributeConfig(this.OPT.ANIMATE,{value:C.isBoolean(K.animate)?K.animate:true,method:function(N){if(this.pickerSlider){this.pickerSlider.animate=N;this.hueSlider.animate=N;}}});this.on(this.OPT.HUE+"Change",this._updateRGBFromHSV,this,true);this.on(this.OPT.SATURATION+"Change",this._updateRGBFromHSV,this,true);this.on(this.OPT.VALUE+"Change",this._updateRGBFromHSV,this,true);this.on(this.OPT.RED+"Change",this._updateRGB,this,true);this.on(this.OPT.GREEN+"Change",this._updateRGB,this,true);this.on(this.OPT.BLUE+"Change",this._updateRGB,this,true);this.on(this.OPT.HEX+"Change",this._updateHex,this,true);this._initElements();}});YAHOO.widget.ColorPicker=G;})();YAHOO.register("colorpicker",YAHOO.widget.ColorPicker,{version:"2.7.0",build:"1796"});
/*
Copyright (c) 2009, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.7.0
*/
(function(){var B=YAHOO.util;var A=function(D,C,E,F){if(!D){}this.init(D,C,E,F);};A.NAME="Anim";A.prototype={toString:function(){var C=this.getEl()||{};var D=C.id||C.tagName;return(this.constructor.NAME+": "+D);},patterns:{noNegatives:/width|height|opacity|padding/i,offsetAttribute:/^((width|height)|(top|left))$/,defaultUnit:/width|height|top$|bottom$|left$|right$/i,offsetUnit:/\d+(em|%|en|ex|pt|in|cm|mm|pc)$/i},doMethod:function(C,E,D){return this.method(this.currentFrame,E,D-E,this.totalFrames);},setAttribute:function(C,F,E){var D=this.getEl();if(this.patterns.noNegatives.test(C)){F=(F>0)?F:0;}if("style" in D){B.Dom.setStyle(D,C,F+E);}else{if(C in D){D[C]=F;}}},getAttribute:function(C){var E=this.getEl();var G=B.Dom.getStyle(E,C);if(G!=="auto"&&!this.patterns.offsetUnit.test(G)){return parseFloat(G);}var D=this.patterns.offsetAttribute.exec(C)||[];var H=!!(D[3]);var F=!!(D[2]);if("style" in E){if(F||(B.Dom.getStyle(E,"position")=="absolute"&&H)){G=E["offset"+D[0].charAt(0).toUpperCase()+D[0].substr(1)];}else{G=0;}}else{if(C in E){G=E[C];}}return G;},getDefaultUnit:function(C){if(this.patterns.defaultUnit.test(C)){return"px";}return"";},setRuntimeAttribute:function(D){var I;var E;var F=this.attributes;this.runtimeAttributes[D]={};var H=function(J){return(typeof J!=="undefined");};if(!H(F[D]["to"])&&!H(F[D]["by"])){return false;}I=(H(F[D]["from"]))?F[D]["from"]:this.getAttribute(D);if(H(F[D]["to"])){E=F[D]["to"];}else{if(H(F[D]["by"])){if(I.constructor==Array){E=[];for(var G=0,C=I.length;G<C;++G){E[G]=I[G]+F[D]["by"][G]*1;}}else{E=I+F[D]["by"]*1;}}}this.runtimeAttributes[D].start=I;this.runtimeAttributes[D].end=E;this.runtimeAttributes[D].unit=(H(F[D].unit))?F[D]["unit"]:this.getDefaultUnit(D);return true;},init:function(E,J,I,C){var D=false;var F=null;var H=0;E=B.Dom.get(E);this.attributes=J||{};this.duration=!YAHOO.lang.isUndefined(I)?I:1;this.method=C||B.Easing.easeNone;this.useSeconds=true;this.currentFrame=0;this.totalFrames=B.AnimMgr.fps;this.setEl=function(M){E=B.Dom.get(M);};this.getEl=function(){return E;};this.isAnimated=function(){return D;};this.getStartTime=function(){return F;};this.runtimeAttributes={};this.animate=function(){if(this.isAnimated()){return false;}this.currentFrame=0;this.totalFrames=(this.useSeconds)?Math.ceil(B.AnimMgr.fps*this.duration):this.duration;if(this.duration===0&&this.useSeconds){this.totalFrames=1;}B.AnimMgr.registerElement(this);return true;};this.stop=function(M){if(!this.isAnimated()){return false;}if(M){this.currentFrame=this.totalFrames;this._onTween.fire();}B.AnimMgr.stop(this);};var L=function(){this.onStart.fire();this.runtimeAttributes={};for(var M in this.attributes){this.setRuntimeAttribute(M);}D=true;H=0;F=new Date();};var K=function(){var O={duration:new Date()-this.getStartTime(),currentFrame:this.currentFrame};O.toString=function(){return("duration: "+O.duration+", currentFrame: "+O.currentFrame);};this.onTween.fire(O);var N=this.runtimeAttributes;for(var M in N){this.setAttribute(M,this.doMethod(M,N[M].start,N[M].end),N[M].unit);}H+=1;};var G=function(){var M=(new Date()-F)/1000;var N={duration:M,frames:H,fps:H/M};N.toString=function(){return("duration: "+N.duration+", frames: "+N.frames+", fps: "+N.fps);};D=false;H=0;this.onComplete.fire(N);};this._onStart=new B.CustomEvent("_start",this,true);this.onStart=new B.CustomEvent("start",this);this.onTween=new B.CustomEvent("tween",this);this._onTween=new B.CustomEvent("_tween",this,true);this.onComplete=new B.CustomEvent("complete",this);this._onComplete=new B.CustomEvent("_complete",this,true);this._onStart.subscribe(L);this._onTween.subscribe(K);this._onComplete.subscribe(G);}};B.Anim=A;})();YAHOO.util.AnimMgr=new function(){var C=null;var B=[];var A=0;this.fps=1000;this.delay=1;this.registerElement=function(F){B[B.length]=F;A+=1;F._onStart.fire();this.start();};this.unRegister=function(G,F){F=F||E(G);if(!G.isAnimated()||F==-1){return false;}G._onComplete.fire();B.splice(F,1);A-=1;if(A<=0){this.stop();}return true;};this.start=function(){if(C===null){C=setInterval(this.run,this.delay);}};this.stop=function(H){if(!H){clearInterval(C);for(var G=0,F=B.length;G<F;++G){this.unRegister(B[0],0);}B=[];C=null;A=0;}else{this.unRegister(H);}};this.run=function(){for(var H=0,F=B.length;H<F;++H){var G=B[H];if(!G||!G.isAnimated()){continue;}if(G.currentFrame<G.totalFrames||G.totalFrames===null){G.currentFrame+=1;if(G.useSeconds){D(G);}G._onTween.fire();}else{YAHOO.util.AnimMgr.stop(G,H);}}};var E=function(H){for(var G=0,F=B.length;G<F;++G){if(B[G]==H){return G;}}return -1;};var D=function(G){var J=G.totalFrames;var I=G.currentFrame;var H=(G.currentFrame*G.duration*1000/G.totalFrames);var F=(new Date()-G.getStartTime());var K=0;if(F<G.duration*1000){K=Math.round((F/H-1)*G.currentFrame);}else{K=J-(I+1);}if(K>0&&isFinite(K)){if(G.currentFrame+K>=J){K=J-(I+1);}G.currentFrame+=K;}};};YAHOO.util.Bezier=new function(){this.getPosition=function(E,D){var F=E.length;var C=[];for(var B=0;B<F;++B){C[B]=[E[B][0],E[B][1]];}for(var A=1;A<F;++A){for(B=0;B<F-A;++B){C[B][0]=(1-D)*C[B][0]+D*C[parseInt(B+1,10)][0];C[B][1]=(1-D)*C[B][1]+D*C[parseInt(B+1,10)][1];}}return[C[0][0],C[0][1]];};};(function(){var A=function(F,E,G,H){A.superclass.constructor.call(this,F,E,G,H);};A.NAME="ColorAnim";A.DEFAULT_BGCOLOR="#fff";var C=YAHOO.util;YAHOO.extend(A,C.Anim);var D=A.superclass;var B=A.prototype;B.patterns.color=/color$/i;B.patterns.rgb=/^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i;B.patterns.hex=/^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i;B.patterns.hex3=/^#?([0-9A-F]{1})([0-9A-F]{1})([0-9A-F]{1})$/i;B.patterns.transparent=/^transparent|rgba\(0, 0, 0, 0\)$/;B.parseColor=function(E){if(E.length==3){return E;}var F=this.patterns.hex.exec(E);if(F&&F.length==4){return[parseInt(F[1],16),parseInt(F[2],16),parseInt(F[3],16)];}F=this.patterns.rgb.exec(E);if(F&&F.length==4){return[parseInt(F[1],10),parseInt(F[2],10),parseInt(F[3],10)];}F=this.patterns.hex3.exec(E);if(F&&F.length==4){return[parseInt(F[1]+F[1],16),parseInt(F[2]+F[2],16),parseInt(F[3]+F[3],16)];
}return null;};B.getAttribute=function(E){var G=this.getEl();if(this.patterns.color.test(E)){var I=YAHOO.util.Dom.getStyle(G,E);var H=this;if(this.patterns.transparent.test(I)){var F=YAHOO.util.Dom.getAncestorBy(G,function(J){return !H.patterns.transparent.test(I);});if(F){I=C.Dom.getStyle(F,E);}else{I=A.DEFAULT_BGCOLOR;}}}else{I=D.getAttribute.call(this,E);}return I;};B.doMethod=function(F,J,G){var I;if(this.patterns.color.test(F)){I=[];for(var H=0,E=J.length;H<E;++H){I[H]=D.doMethod.call(this,F,J[H],G[H]);}I="rgb("+Math.floor(I[0])+","+Math.floor(I[1])+","+Math.floor(I[2])+")";}else{I=D.doMethod.call(this,F,J,G);}return I;};B.setRuntimeAttribute=function(F){D.setRuntimeAttribute.call(this,F);if(this.patterns.color.test(F)){var H=this.attributes;var J=this.parseColor(this.runtimeAttributes[F].start);var G=this.parseColor(this.runtimeAttributes[F].end);if(typeof H[F]["to"]==="undefined"&&typeof H[F]["by"]!=="undefined"){G=this.parseColor(H[F].by);for(var I=0,E=J.length;I<E;++I){G[I]=J[I]+G[I];}}this.runtimeAttributes[F].start=J;this.runtimeAttributes[F].end=G;}};C.ColorAnim=A;})();
/*
TERMS OF USE - EASING EQUATIONS
Open source under the BSD License.
Copyright 2001 Robert Penner All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
YAHOO.util.Easing={easeNone:function(B,A,D,C){return D*B/C+A;},easeIn:function(B,A,D,C){return D*(B/=C)*B+A;},easeOut:function(B,A,D,C){return -D*(B/=C)*(B-2)+A;},easeBoth:function(B,A,D,C){if((B/=C/2)<1){return D/2*B*B+A;}return -D/2*((--B)*(B-2)-1)+A;},easeInStrong:function(B,A,D,C){return D*(B/=C)*B*B*B+A;},easeOutStrong:function(B,A,D,C){return -D*((B=B/C-1)*B*B*B-1)+A;},easeBothStrong:function(B,A,D,C){if((B/=C/2)<1){return D/2*B*B*B*B+A;}return -D/2*((B-=2)*B*B*B-2)+A;},elasticIn:function(C,A,G,F,B,E){if(C==0){return A;}if((C/=F)==1){return A+G;}if(!E){E=F*0.3;}if(!B||B<Math.abs(G)){B=G;var D=E/4;}else{var D=E/(2*Math.PI)*Math.asin(G/B);}return -(B*Math.pow(2,10*(C-=1))*Math.sin((C*F-D)*(2*Math.PI)/E))+A;},elasticOut:function(C,A,G,F,B,E){if(C==0){return A;}if((C/=F)==1){return A+G;}if(!E){E=F*0.3;}if(!B||B<Math.abs(G)){B=G;var D=E/4;}else{var D=E/(2*Math.PI)*Math.asin(G/B);}return B*Math.pow(2,-10*C)*Math.sin((C*F-D)*(2*Math.PI)/E)+G+A;},elasticBoth:function(C,A,G,F,B,E){if(C==0){return A;}if((C/=F/2)==2){return A+G;}if(!E){E=F*(0.3*1.5);}if(!B||B<Math.abs(G)){B=G;var D=E/4;}else{var D=E/(2*Math.PI)*Math.asin(G/B);}if(C<1){return -0.5*(B*Math.pow(2,10*(C-=1))*Math.sin((C*F-D)*(2*Math.PI)/E))+A;}return B*Math.pow(2,-10*(C-=1))*Math.sin((C*F-D)*(2*Math.PI)/E)*0.5+G+A;},backIn:function(B,A,E,D,C){if(typeof C=="undefined"){C=1.70158;}return E*(B/=D)*B*((C+1)*B-C)+A;},backOut:function(B,A,E,D,C){if(typeof C=="undefined"){C=1.70158;}return E*((B=B/D-1)*B*((C+1)*B+C)+1)+A;},backBoth:function(B,A,E,D,C){if(typeof C=="undefined"){C=1.70158;}if((B/=D/2)<1){return E/2*(B*B*(((C*=(1.525))+1)*B-C))+A;}return E/2*((B-=2)*B*(((C*=(1.525))+1)*B+C)+2)+A;},bounceIn:function(B,A,D,C){return D-YAHOO.util.Easing.bounceOut(C-B,0,D,C)+A;},bounceOut:function(B,A,D,C){if((B/=C)<(1/2.75)){return D*(7.5625*B*B)+A;}else{if(B<(2/2.75)){return D*(7.5625*(B-=(1.5/2.75))*B+0.75)+A;}else{if(B<(2.5/2.75)){return D*(7.5625*(B-=(2.25/2.75))*B+0.9375)+A;}}}return D*(7.5625*(B-=(2.625/2.75))*B+0.984375)+A;},bounceBoth:function(B,A,D,C){if(B<C/2){return YAHOO.util.Easing.bounceIn(B*2,0,D,C)*0.5+A;}return YAHOO.util.Easing.bounceOut(B*2-C,0,D,C)*0.5+D*0.5+A;}};(function(){var A=function(H,G,I,J){if(H){A.superclass.constructor.call(this,H,G,I,J);}};A.NAME="Motion";var E=YAHOO.util;YAHOO.extend(A,E.ColorAnim);var F=A.superclass;var C=A.prototype;C.patterns.points=/^points$/i;C.setAttribute=function(G,I,H){if(this.patterns.points.test(G)){H=H||"px";F.setAttribute.call(this,"left",I[0],H);F.setAttribute.call(this,"top",I[1],H);}else{F.setAttribute.call(this,G,I,H);}};C.getAttribute=function(G){if(this.patterns.points.test(G)){var H=[F.getAttribute.call(this,"left"),F.getAttribute.call(this,"top")];}else{H=F.getAttribute.call(this,G);}return H;};C.doMethod=function(G,K,H){var J=null;if(this.patterns.points.test(G)){var I=this.method(this.currentFrame,0,100,this.totalFrames)/100;J=E.Bezier.getPosition(this.runtimeAttributes[G],I);}else{J=F.doMethod.call(this,G,K,H);}return J;};C.setRuntimeAttribute=function(P){if(this.patterns.points.test(P)){var H=this.getEl();var J=this.attributes;var G;var L=J["points"]["control"]||[];var I;var M,O;if(L.length>0&&!(L[0] instanceof Array)){L=[L];}else{var K=[];for(M=0,O=L.length;M<O;++M){K[M]=L[M];}L=K;}if(E.Dom.getStyle(H,"position")=="static"){E.Dom.setStyle(H,"position","relative");}if(D(J["points"]["from"])){E.Dom.setXY(H,J["points"]["from"]);
}else{E.Dom.setXY(H,E.Dom.getXY(H));}G=this.getAttribute("points");if(D(J["points"]["to"])){I=B.call(this,J["points"]["to"],G);var N=E.Dom.getXY(this.getEl());for(M=0,O=L.length;M<O;++M){L[M]=B.call(this,L[M],G);}}else{if(D(J["points"]["by"])){I=[G[0]+J["points"]["by"][0],G[1]+J["points"]["by"][1]];for(M=0,O=L.length;M<O;++M){L[M]=[G[0]+L[M][0],G[1]+L[M][1]];}}}this.runtimeAttributes[P]=[G];if(L.length>0){this.runtimeAttributes[P]=this.runtimeAttributes[P].concat(L);}this.runtimeAttributes[P][this.runtimeAttributes[P].length]=I;}else{F.setRuntimeAttribute.call(this,P);}};var B=function(G,I){var H=E.Dom.getXY(this.getEl());G=[G[0]-H[0]+I[0],G[1]-H[1]+I[1]];return G;};var D=function(G){return(typeof G!=="undefined");};E.Motion=A;})();(function(){var D=function(F,E,G,H){if(F){D.superclass.constructor.call(this,F,E,G,H);}};D.NAME="Scroll";var B=YAHOO.util;YAHOO.extend(D,B.ColorAnim);var C=D.superclass;var A=D.prototype;A.doMethod=function(E,H,F){var G=null;if(E=="scroll"){G=[this.method(this.currentFrame,H[0],F[0]-H[0],this.totalFrames),this.method(this.currentFrame,H[1],F[1]-H[1],this.totalFrames)];}else{G=C.doMethod.call(this,E,H,F);}return G;};A.getAttribute=function(E){var G=null;var F=this.getEl();if(E=="scroll"){G=[F.scrollLeft,F.scrollTop];}else{G=C.getAttribute.call(this,E);}return G;};A.setAttribute=function(E,H,G){var F=this.getEl();if(E=="scroll"){F.scrollLeft=H[0];F.scrollTop=H[1];}else{C.setAttribute.call(this,E,H,G);}};B.Scroll=D;})();YAHOO.register("animation",YAHOO.util.Anim,{version:"2.7.0",build:"1799"}); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/plugins/uicolor/yui/yui.js | yui.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add('a11yHelp',function(a){var b=a.lang.accessibilityHelp,c=CKEDITOR.tools.getNextId(),d={8:'BACKSPACE',9:'TAB',13:'ENTER',16:'SHIFT',17:'CTRL',18:'ALT',19:'PAUSE',20:'CAPSLOCK',27:'ESCAPE',33:'PAGE UP',34:'PAGE DOWN',35:'END',36:'HOME',37:'LEFT ARROW',38:'UP ARROW',39:'RIGHT ARROW',40:'DOWN ARROW',45:'INSERT',46:'DELETE',91:'LEFT WINDOW KEY',92:'RIGHT WINDOW KEY',93:'SELECT KEY',96:'NUMPAD 0',97:'NUMPAD 1',98:'NUMPAD 2',99:'NUMPAD 3',100:'NUMPAD 4',101:'NUMPAD 5',102:'NUMPAD 6',103:'NUMPAD 7',104:'NUMPAD 8',105:'NUMPAD 9',106:'MULTIPLY',107:'ADD',109:'SUBTRACT',110:'DECIMAL POINT',111:'DIVIDE',112:'F1',113:'F2',114:'F3',115:'F4',116:'F5',117:'F6',118:'F7',119:'F8',120:'F9',121:'F10',122:'F11',123:'F12',144:'NUM LOCK',145:'SCROLL LOCK',186:'SEMI-COLON',187:'EQUAL SIGN',188:'COMMA',189:'DASH',190:'PERIOD',191:'FORWARD SLASH',192:'GRAVE ACCENT',219:'OPEN BRACKET',220:'BACK SLASH',221:'CLOSE BRAKET',222:'SINGLE QUOTE'};d[CKEDITOR.ALT]='ALT';d[CKEDITOR.SHIFT]='SHIFT';d[CKEDITOR.CTRL]='CTRL';var e=[CKEDITOR.ALT,CKEDITOR.SHIFT,CKEDITOR.CTRL];function f(j){var k,l,m=[];for(var n=0;n<e.length;n++){l=e[n];k=j/e[n];if(k>1&&k<=2){j-=l;m.push(d[l]);}}m.push(d[j]||String.fromCharCode(j));return m.join('+');};var g=/\$\{(.*?)\}/g;function h(j,k){var l=a.config.keystrokes,m,n=l.length;for(var o=0;o<n;o++){m=l[o];if(m[1]==k)break;}return f(m[0]);};function i(){var j='<div class="cke_accessibility_legend" role="document" aria-labelledby="'+c+'_arialbl" tabIndex="-1">%1</div>'+'<span id="'+c+'_arialbl" class="cke_voice_label">'+b.contents+' </span>',k='<h1>%1</h1><dl>%2</dl>',l='<dt>%1</dt><dd>%2</dd>',m=[],n=b.legend,o=n.length;for(var p=0;p<o;p++){var q=n[p],r=[],s=q.items,t=s.length;for(var u=0;u<t;u++){var v=s[u],w;w=l.replace('%1',v.name).replace('%2',v.legend.replace(g,h));r.push(w);}m.push(k.replace('%1',q.name).replace('%2',r.join('')));}return j.replace('%1',m.join(''));};return{title:b.title,minWidth:600,minHeight:400,contents:[{id:'info',label:a.lang.common.generalTab,expand:true,elements:[{type:'html',id:'legends',style:'white-space:normal;',focus:function(){},html:i()+'<style type="text/css">'+'.cke_accessibility_legend'+'{'+'width:600px;'+'height:400px;'+'padding-right:5px;'+'overflow-y:auto;'+'overflow-x:hidden;'+'}'+'.cke_browser_quirks .cke_accessibility_legend,'+'.cke_browser_ie6 .cke_accessibility_legend'+'{'+'height:390px'+'}'+'.cke_accessibility_legend *'+'{'+'white-space:normal;'+'}'+'.cke_accessibility_legend h1'+'{'+'font-size: 20px;'+'border-bottom: 1px solid #AAA;'+'margin: 5px 0px 15px;'+'}'+'.cke_accessibility_legend dl'+'{'+'margin-left: 5px;'+'}'+'.cke_accessibility_legend dt'+'{'+'font-size: 13px;'+'font-weight: bold;'+'}'+'.cke_accessibility_legend dd'+'{'+'margin:10px'+'}'+'</style>'}]}],buttons:[CKEDITOR.dialog.cancelButton]};
}); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/plugins/a11yhelp/dialogs/a11yhelp.js | a11yhelp.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('a11yhelp','en',{accessibilityHelp:{title:'Accessibility Instructions',contents:'Help Contents. To close this dialog press ESC.',legend:[{name:'General',items:[{name:'Editor Toolbar',legend:'Press ${toolbarFocus} to navigate to the toolbar. Move to the next and previous toolbar group with TAB and SHIFT-TAB. Move to the next and previous toolbar button with RIGHT ARROW or LEFT ARROW. Press SPACE or ENTER to activate the toolbar button.'},{name:'Editor Dialog',legend:'Inside a dialog, press TAB to navigate to next dialog field, press SHIFT + TAB to move to previous field, press ENTER to submit dialog, press ESC to cancel dialog. For dialogs that have multiple tab pages, press ALT + F10 to navigate to tab-list. Then move to next tab with TAB OR RIGTH ARROW. Move to previous tab with SHIFT + TAB or LEFT ARROW. Press SPACE or ENTER to select the tab page.'},{name:'Editor Context Menu',legend:'Press ${contextMenu} or APPLICATION KEY to open context-menu. Then move to next menu option with TAB or DOWN ARROW. Move to previous option with SHIFT+TAB or UP ARROW. Press SPACE or ENTER to select the menu option. Open sub-menu of current option wtih SPACE or ENTER or RIGHT ARROW. Go back to parent menu item with ESC or LEFT ARROW. Close context menu with ESC.'},{name:'Editor List Box',legend:'Inside a list-box, move to next list item with TAB OR DOWN ARROW. Move to previous list item with SHIFT + TAB or UP ARROW. Press SPACE or ENTER to select the list option. Press ESC to close the list-box.'},{name:'Editor Element Path Bar',legend:'Press ${elementsPathFocus} to navigate to the elements path bar. Move to next element button with TAB or RIGHT ARROW. Move to previous button with SHIFT+TAB or LEFT ARROW. Press SPACE or ENTER to select the element in editor.'}]},{name:'Commands',items:[{name:' Undo command',legend:'Press ${undo}'},{name:' Redo command',legend:'Press ${redo}'},{name:' Bold command',legend:'Press ${bold}'},{name:' Italic command',legend:'Press ${italic}'},{name:' Underline command',legend:'Press ${underline}'},{name:' Link command',legend:'Press ${link}'},{name:' Toolbar Collapse command',legend:'Press ${toolbarCollapse}'},{name:' Accessibility Help',legend:'Press ${a11yHelp}'}]}]}}); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/plugins/a11yhelp/lang/en.js | en.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('a11yhelp','he',{accessibilityHelp:{title:'הוראות נגישות',contents:'הוראות נגישות. לסגירה לחץ אסקייפ (ESC).',legend:[{name:'כללי',items:[{name:'סרגל הכלים',legend:'לחץ על ${toolbarFocus} כדי לנווט לסרגל הכלים. עבור לכפתור הבא עם מקש הטאב (TAB) או חץ שמאלי. עבור לכפתור הקודם עם מקש השיפט (SHIFT) + טאב (TAB) או חץ ימני. לחץ רווח או אנטר (ENTER) כדי להפעיל את הכפתור הנבחר.'},{name:'דיאלוגים (חלונות תשאול)',legend:'בתוך דיאלוג, לחץ טאב (TAB) כדי לנווט לשדה הבא, לחץ שיפט (SHIFT) + טאב (TAB) כדי לנווט לשדה הקודם, לחץ אנטר (ENTER) כדי לשלוח את הדיאלוג, לחץ אסקייפ (ESC) כדי לבטל. בתוך דיאלוגים בעלי מספר טאבים (לשוניות), לחץ אלט (ALT) + F10 כדי לנווט לשורת הטאבים. נווט לטאב הבא עם טאב (TAB) או חץ שמאלי. עבור לטאב הקודם עם שיפט (SHIFT) + טאב (TAB) או חץ שמאלי. לחץ רווח או אנטר (ENTER) כדי להיכנס לטאב.'},{name:'תפריט ההקשר (Context Menu)',legend:'לחץ ${contextMenu} או APPLICATION KEYכדי לפתוח את תפריט ההקשר. עבור לאפשרות הבאה עם טאב (TAB) או חץ למטה. עבור לאפשרות הקודמת עם שיפט (SHIFT) + טאב (TAB) או חץ למעלה. לחץ רווח או אנטר (ENTER) כדי לבחור את האפשרות. פתח את תת התפריט (Sub-menu) של האפשרות הנוכחית עם רווח או אנטר (ENTER) או חץ שמאלי. חזור לתפריט האב עם אסקייפ (ESC) או חץ שמאלי. סגור את תפריט ההקשר עם אסקייפ (ESC).'},{name:'תפריטים צפים (List boxes)',legend:'בתוך תפריט צף, עבור לפריט הבא עם טאב (TAB) או חץ למטה. עבור לתפריט הקודם עם שיפט (SHIFT) + טאב (TAB) or חץ עליון. Press SPACE or ENTER to select the list option. Press ESC to close the list-box.'},{name:'עץ אלמנטים (Elements Path)',legend:'לחץ ${elementsPathFocus} כדי לנווט לעץ האלמנטים. עבור לפריט הבא עם טאב (TAB) או חץ ימני. עבור לפריט הקודם עם שיפט (SHIFT) + טאב (TAB) או חץ שמאלי. לחץ רווח או אנטר (ENTER) כדי לבחור את האלמנט בעורך.'}]},{name:'פקודות',items:[{name:' ביטול צעד אחרון',legend:'לחץ ${undo}'},{name:' חזרה על צעד אחרון',legend:'לחץ ${redo}'},{name:' הדגשה',legend:'לחץ ${bold}'},{name:' הטייה',legend:'לחץ ${italic}'},{name:' הוספת קו תחתון',legend:'לחץ ${underline}'},{name:' הוספת לינק',legend:'לחץ ${link}'},{name:' כיווץ סרגל הכלים',legend:'לחץ ${toolbarCollapse}'},{name:' הוראות נגישות',legend:'לחץ ${a11yHelp}'}]}]}});CKEDITOR.plugins.setLang('a11yhelp','he',{accessibilityHelp:{title:'הוראות נגישות',contents:'הוראות נגישות. לסגירה לחץ אסקייפ (ESC).',legend:[{name:'כללי',items:[{name:'סרגל הכלים',legend:'לחץ על ${toolbarFocus} כדי לנווט לסרגל הכלים. עבור לכפתור הבא עם מקש הטאב (TAB) או חץ שמאלי. עבור לכפתור הקודם עם מקש השיפט (SHIFT) + טאב (TAB) או חץ ימני. לחץ רווח או אנטר (ENTER) כדי להפעיל את הכפתור הנבחר.'},{name:'דיאלוגים (חלונות תשאול)',legend:'בתוך דיאלוג, לחץ טאב (TAB) כדי לנווט לשדה הבא, לחץ שיפט (SHIFT) + טאב (TAB) כדי לנווט לשדה הקודם, לחץ אנטר (ENTER) כדי לשלוח את הדיאלוג, לחץ אסקייפ (ESC) כדי לבטל. בתוך דיאלוגים בעלי מספר טאבים (לשוניות), לחץ אלט (ALT) + F10 כדי לנווט לשורת הטאבים. נווט לטאב הבא עם טאב (TAB) או חץ שמאלי. עבור לטאב הקודם עם שיפט (SHIFT) + טאב (TAB) או חץ שמאלי. לחץ רווח או אנטר (ENTER) כדי להיכנס לטאב.'},{name:'תפריט ההקשר (Context Menu)',legend:'לחץ ${contextMenu} או APPLICATION KEYכדי לפתוח את תפריט ההקשר. עבור לאפשרות הבאה עם טאב (TAB) או חץ למטה. עבור לאפשרות הקודמת עם שיפט (SHIFT) + טאב (TAB) או חץ למעלה. לחץ רווח או אנטר (ENTER) כדי לבחור את האפשרות. פתח את תת התפריט (Sub-menu) של האפשרות הנוכחית עם רווח או אנטר (ENTER) או חץ שמאלי. חזור לתפריט האב עם אסקייפ (ESC) או חץ שמאלי. סגור את תפריט ההקשר עם אסקייפ (ESC).'},{name:'תפריטים צפים (List boxes)',legend:'בתוך תפריט צף, עבור לפריט הבא עם טאב (TAB) או חץ למטה. עבור לתפריט הקודם עם שיפט (SHIFT) + טאב (TAB) or חץ עליון. Press SPACE or ENTER to select the list option. Press ESC to close the list-box.'},{name:'עץ אלמנטים (Elements Path)',legend:'לחץ ${elementsPathFocus} כדי לנווט לעץ האלמנטים. עבור לפריט הבא עם טאב (TAB) או חץ ימני. עבור לפריט הקודם עם שיפט (SHIFT) + טאב (TAB) או חץ שמאלי. לחץ רווח או אנטר (ENTER) כדי לבחור את האלמנט בעורך.'}]},{name:'פקודות',items:[{name:' ביטול צעד אחרון',legend:'לחץ ${undo}'},{name:' חזרה על צעד אחרון',legend:'לחץ ${redo}'},{name:' הדגשה',legend:'לחץ ${bold}'},{name:' הטייה',legend:'לחץ ${italic}'},{name:' הוספת קו תחתון',legend:'לחץ ${underline}'},{name:' הוספת לינק',legend:'לחץ ${link}'},{name:' כיווץ סרגל הכלים',legend:'לחץ ${toolbarCollapse}'},{name:' הוראות נגישות',legend:'לחץ ${a11yHelp}'}]}]}}); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/plugins/a11yhelp/lang/he.js | he.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add('docProps',function(a){var b=a.lang.docprops,c=a.lang.common,d={};function e(n,o){var p=function(){q(this);o(this,this._.parentDialog);},q=function(s){s.removeListener('ok',p);s.removeListener('cancel',q);},r=function(s){s.on('ok',p);s.on('cancel',q);};a.execCommand(n);if(a._.storedDialogs.colordialog)r(a._.storedDialogs.colordialog);else CKEDITOR.on('dialogDefinition',function(s){if(s.data.name!=n)return;var t=s.data.definition;s.removeListener();t.onLoad=CKEDITOR.tools.override(t.onLoad,function(u){return function(){r(this);t.onLoad=u;if(typeof u=='function')u.call(this);};});});};function f(){var n=this.getDialog(),o=n.getContentElement('general',this.id+'Other');if(!o)return;if(this.getValue()=='other'){o.getInputElement().removeAttribute('readOnly');o.focus();o.getElement().removeClass('cke_disabled');}else{o.getInputElement().setAttribute('readOnly',true);o.getElement().addClass('cke_disabled');}};function g(n,o,p){return function(q,r,s){var t=d,u=typeof p!='undefined'?p:this.getValue();if(!u&&n in t)t[n].remove();else if(u&&n in t)t[n].setAttribute('content',u);else if(u){var v=new CKEDITOR.dom.element('meta',a.document);v.setAttribute(o?'http-equiv':'name',n);v.setAttribute('content',u);s.append(v);}};};function h(n,o){return function(){var p=d,q=n in p?p[n].getAttribute('content')||'':'';if(o)return q;this.setValue(q);return null;};};function i(n){return function(o,p,q,r){r.removeAttribute('margin'+n);var s=this.getValue();if(s!=='')r.setStyle('margin-'+n,CKEDITOR.tools.cssLength(s));else r.removeStyle('margin-'+n);};};function j(n){var o={},p=n.getElementsByTag('meta'),q=p.count();for(var r=0;r<q;r++){var s=p.getItem(r);o[s.getAttribute(s.hasAttribute('http-equiv')?'http-equiv':'name').toLowerCase()]=s;}return o;};function k(n,o,p){n.removeStyle(o);if(n.getComputedStyle(o)!=p)n.setStyle(o,p);};var l=function(n,o,p){return{type:'hbox',padding:0,widths:['60%','40%'],children:[CKEDITOR.tools.extend({type:'text',id:n,label:b[o]},p||{},1),{type:'button',id:n+'Choose',label:b.chooseColor,className:'colorChooser',onClick:function(){var q=this;e('colordialog',function(r){var s=q.getDialog();s.getContentElement(s._.currentTabId,n).setValue(r.getContentElement('picker','selectedColor').getValue());});}}]};},m='javascript:void((function(){'+encodeURIComponent('document.open();'+(CKEDITOR.env.isCustomDomain()?"document.domain='"+document.domain+"';":'')+'document.write( \'<html style="background-color: #ffffff; height: 100%"><head></head><body style="width: 100%; height: 100%; margin: 0px">'+b.previewHtml+"</body></html>' );"+'document.close();')+'})())';
return{title:b.title,minHeight:330,minWidth:500,onShow:function(){var n=a.document,o=n.getElementsByTag('html').getItem(0),p=n.getHead(),q=n.getBody();d=j(n);this.setupContent(n,o,p,q);},onHide:function(){d={};},onOk:function(){var n=a.document,o=n.getElementsByTag('html').getItem(0),p=n.getHead(),q=n.getBody();this.commitContent(n,o,p,q);},contents:[{id:'general',label:c.generalTab,elements:[{type:'text',id:'title',label:b.docTitle,setup:function(n){this.setValue(n.getElementsByTag('title').getItem(0).data('cke-title'));},commit:function(n,o,p,q,r){if(r)return;n.getElementsByTag('title').getItem(0).data('cke-title',this.getValue());}},{type:'hbox',children:[{type:'select',id:'dir',label:c.langDir,style:'width: 100%',items:[[c.notSet,''],[c.langDirLtr,'ltr'],[c.langDirRtl,'rtl']],setup:function(n,o,p,q){this.setValue(q.getDirection()||'');},commit:function(n,o,p,q){var r=this.getValue();if(r)q.setAttribute('dir',r);else q.removeAttribute('dir');q.removeStyle('direction');}},{type:'text',id:'langCode',label:c.langCode,setup:function(n,o){this.setValue(o.getAttribute('xml:lang')||o.getAttribute('lang')||'');},commit:function(n,o,p,q,r){if(r)return;var s=this.getValue();if(s)o.setAttributes({'xml:lang':s,lang:s});else o.removeAttributes({'xml:lang':1,lang:1});}}]},{type:'hbox',children:[{type:'select',id:'charset',label:b.charset,style:'width: 100%',items:[[c.notSet,''],[b.charsetASCII,'us-ascii'],[b.charsetCE,'iso-8859-2'],[b.charsetCT,'big5'],[b.charsetCR,'iso-8859-5'],[b.charsetGR,'iso-8859-7'],[b.charsetJP,'iso-2022-jp'],[b.charsetKR,'iso-2022-kr'],[b.charsetTR,'iso-8859-9'],[b.charsetUN,'utf-8'],[b.charsetWE,'iso-8859-1'],[b.other,'other']],'default':'',onChange:function(){var n=this;n.getDialog().selectedCharset=n.getValue()!='other'?n.getValue():'';f.call(n);},setup:function(){var q=this;q.metaCharset='charset' in d;var n=h(q.metaCharset?'charset':'content-type',1,1),o=n.call(q);!q.metaCharset&&o.match(/charset=[^=]+$/)&&(o=o.substring(o.indexOf('=')+1));if(o){q.setValue(o.toLowerCase());if(!q.getValue()){q.setValue('other');var p=q.getDialog().getContentElement('general','charsetOther');p&&p.setValue(o);}q.getDialog().selectedCharset=o;}f.call(q);},commit:function(n,o,p,q,r){var v=this;if(r)return;var s=v.getValue(),t=v.getDialog().getContentElement('general','charsetOther');s=='other'&&(s=t?t.getValue():'');s&&!v.metaCharset&&(s=(d['content-type']?d['content-type'].getAttribute('content').split(';')[0]:'text/html')+'; charset='+s);var u=g(v.metaCharset?'charset':'content-type',1,s);
u.call(v,n,o,p);}},{type:'text',id:'charsetOther',label:b.charsetOther,onChange:function(){this.getDialog().selectedCharset=this.getValue();}}]},{type:'hbox',children:[{type:'select',id:'docType',label:b.docType,style:'width: 100%',items:[[c.notSet,''],['XHTML 1.1','<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">'],['XHTML 1.0 Transitional','<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'],['XHTML 1.0 Strict','<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'],['XHTML 1.0 Frameset','<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">'],['HTML 5','<!DOCTYPE html>'],['HTML 4.01 Transitional','<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">'],['HTML 4.01 Strict','<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">'],['HTML 4.01 Frameset','<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'],['HTML 3.2','<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">'],['HTML 2.0','<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">'],[b.other,'other']],onChange:f,setup:function(){var o=this;if(a.docType){o.setValue(a.docType);if(!o.getValue()){o.setValue('other');var n=o.getDialog().getContentElement('general','docTypeOther');n&&n.setValue(a.docType);}}f.call(o);},commit:function(n,o,p,q,r){if(r)return;var s=this.getValue(),t=this.getDialog().getContentElement('general','docTypeOther');a.docType=s=='other'?t?t.getValue():'':s;}},{type:'text',id:'docTypeOther',label:b.docTypeOther}]},{type:'checkbox',id:'xhtmlDec',label:b.xhtmlDec,setup:function(){this.setValue(!!a.xmlDeclaration);},commit:function(n,o,p,q,r){if(r)return;if(this.getValue()){a.xmlDeclaration='<?xml version="1.0" encoding="'+(this.getDialog().selectedCharset||'utf-8')+'"?>';o.setAttribute('xmlns','http://www.w3.org/1999/xhtml');}else{a.xmlDeclaration='';o.removeAttribute('xmlns');}}}]},{id:'design',label:b.design,elements:[{type:'hbox',widths:['60%','40%'],children:[{type:'vbox',children:[l('txtColor','txtColor',{setup:function(n,o,p,q){this.setValue(q.getComputedStyle('color'));},commit:function(n,o,p,q,r){if(this.isChanged()||r){q.removeAttribute('text');var s=this.getValue();if(s)q.setStyle('color',s);else q.removeStyle('color');}}}),l('bgColor','bgColor',{setup:function(n,o,p,q){var r=q.getComputedStyle('background-color')||'';
this.setValue(r=='transparent'?'':r);},commit:function(n,o,p,q,r){if(this.isChanged()||r){q.removeAttribute('bgcolor');var s=this.getValue();if(s)q.setStyle('background-color',s);else k(q,'background-color','transparent');}}}),{type:'hbox',widths:['60%','40%'],padding:1,children:[{type:'text',id:'bgImage',label:b.bgImage,setup:function(n,o,p,q){var r=q.getComputedStyle('background-image')||'';if(r=='none')r='';else r=r.replace(/url\(\s*(["']?)\s*([^\)]*)\s*\1\s*\)/i,function(s,t,u){return u;});this.setValue(r);},commit:function(n,o,p,q){q.removeAttribute('background');var r=this.getValue();if(r)q.setStyle('background-image','url('+r+')');else k(q,'background-image','none');}},{type:'button',id:'bgImageChoose',label:c.browseServer,style:'display:inline-block;margin-top:10px;',hidden:true,filebrowser:'design:bgImage'}]},{type:'checkbox',id:'bgFixed',label:b.bgFixed,setup:function(n,o,p,q){this.setValue(q.getComputedStyle('background-attachment')=='fixed');},commit:function(n,o,p,q){if(this.getValue())q.setStyle('background-attachment','fixed');else k(q,'background-attachment','scroll');}}]},{type:'vbox',children:[{type:'html',id:'marginTitle',html:'<div style="text-align: center; margin: 0px auto; font-weight: bold">'+b.margin+'</div>'},{type:'text',id:'marginTop',label:b.marginTop,style:'width: 80px; text-align: center',align:'center',inputStyle:'text-align: center',setup:function(n,o,p,q){this.setValue(q.getStyle('margin-top')||q.getAttribute('margintop')||'');},commit:i('top')},{type:'hbox',children:[{type:'text',id:'marginLeft',label:b.marginLeft,style:'width: 80px; text-align: center',align:'center',inputStyle:'text-align: center',setup:function(n,o,p,q){this.setValue(q.getStyle('margin-left')||q.getAttribute('marginleft')||'');},commit:i('left')},{type:'text',id:'marginRight',label:b.marginRight,style:'width: 80px; text-align: center',align:'center',inputStyle:'text-align: center',setup:function(n,o,p,q){this.setValue(q.getStyle('margin-right')||q.getAttribute('marginright')||'');},commit:i('right')}]},{type:'text',id:'marginBottom',label:b.marginBottom,style:'width: 80px; text-align: center',align:'center',inputStyle:'text-align: center',setup:function(n,o,p,q){this.setValue(q.getStyle('margin-bottom')||q.getAttribute('marginbottom')||'');},commit:i('bottom')}]}]}]},{id:'meta',label:b.meta,elements:[{type:'textarea',id:'metaKeywords',label:b.metaKeywords,setup:h('keywords'),commit:g('keywords')},{type:'textarea',id:'metaDescription',label:b.metaDescription,setup:h('description'),commit:g('description')},{type:'text',id:'metaAuthor',label:b.metaAuthor,setup:h('author'),commit:g('author')},{type:'text',id:'metaCopyright',label:b.metaCopyright,setup:h('copyright'),commit:g('copyright')}]},{id:'preview',label:c.preview,elements:[{type:'html',id:'previewHtml',html:'<iframe src="'+m+'" style="width: 100%; height: 310px" hidefocus="true" frameborder="0" '+'id="cke_docProps_preview_iframe"></iframe>',onLoad:function(){this.getDialog().on('selectPage',function(n){if(n.data.page=='preview'){var o=this;
setTimeout(function(){var p=CKEDITOR.document.getById('cke_docProps_preview_iframe').getFrameDocument(),q=p.getElementsByTag('html').getItem(0),r=p.getHead(),s=p.getBody();o.commitContent(p,q,r,s,1);},50);}});CKEDITOR.document.getById('cke_docProps_preview_iframe').getAscendant('table').setStyle('height','100%');}}]}]};}); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/plugins/docprops/dialogs/docprops.js | docprops.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add('smiley',function(a){var b=a.config,c=a.lang.smiley,d=b.smiley_images,e=b.smiley_columns||8,f,g,h=function(o){var p=o.data.getTarget(),q=p.getName();if(q=='a')p=p.getChild(0);else if(q!='img')return;var r=p.getAttribute('cke_src'),s=p.getAttribute('title'),t=a.document.createElement('img',{attributes:{src:r,'data-cke-saved-src':r,title:s,alt:s,width:p.$.width,height:p.$.height}});a.insertElement(t);g.hide();o.data.preventDefault();},i=CKEDITOR.tools.addFunction(function(o,p){o=new CKEDITOR.dom.event(o);p=new CKEDITOR.dom.element(p);var q,r,s=o.getKeystroke(),t=a.lang.dir=='rtl';switch(s){case 38:if(q=p.getParent().getParent().getPrevious()){r=q.getChild([p.getParent().getIndex(),0]);r.focus();}o.preventDefault();break;case 40:if(q=p.getParent().getParent().getNext()){r=q.getChild([p.getParent().getIndex(),0]);if(r)r.focus();}o.preventDefault();break;case 32:h({data:o});o.preventDefault();break;case t?37:39:case 9:if(q=p.getParent().getNext()){r=q.getChild(0);r.focus();o.preventDefault(true);}else if(q=p.getParent().getParent().getNext()){r=q.getChild([0,0]);if(r)r.focus();o.preventDefault(true);}break;case t?39:37:case CKEDITOR.SHIFT+9:if(q=p.getParent().getPrevious()){r=q.getChild(0);r.focus();o.preventDefault(true);}else if(q=p.getParent().getParent().getPrevious()){r=q.getLast().getChild(0);r.focus();o.preventDefault(true);}break;default:return;}}),j=CKEDITOR.tools.getNextId()+'_smiley_emtions_label',k=['<div><span id="'+j+'" class="cke_voice_label">'+c.options+'</span>','<table role="listbox" aria-labelledby="'+j+'" style="width:100%;height:100%" cellspacing="2" cellpadding="2"',CKEDITOR.env.ie&&CKEDITOR.env.quirks?' style="position:absolute;"':'','><tbody>'],l=d.length;for(f=0;f<l;f++){if(f%e===0)k.push('<tr>');var m='cke_smile_label_'+f+'_'+CKEDITOR.tools.getNextNumber();k.push('<td class="cke_dark_background cke_centered" style="vertical-align: middle;"><a href="javascript:void(0)" role="option"',' aria-posinset="'+(f+1)+'"',' aria-setsize="'+l+'"',' aria-labelledby="'+m+'"',' class="cke_smile cke_hand" tabindex="-1" onkeydown="CKEDITOR.tools.callFunction( ',i,', event, this );">','<img class="cke_hand" title="',b.smiley_descriptions[f],'" cke_src="',CKEDITOR.tools.htmlEncode(b.smiley_path+d[f]),'" alt="',b.smiley_descriptions[f],'"',' src="',CKEDITOR.tools.htmlEncode(b.smiley_path+d[f]),'"',CKEDITOR.env.ie?" onload=\"this.setAttribute('width', 2); this.removeAttribute('width');\" ":'','><span id="'+m+'" class="cke_voice_label">'+b.smiley_descriptions[f]+'</span>'+'</a>','</td>');
if(f%e==e-1)k.push('</tr>');}if(f<e-1){for(;f<e-1;f++)k.push('<td></td>');k.push('</tr>');}k.push('</tbody></table></div>');var n={type:'html',id:'smileySelector',html:k.join(''),onLoad:function(o){g=o.sender;},focus:function(){var o=this;setTimeout(function(){var p=o.getElement().getElementsByTag('a').getItem(0);p.focus();},0);},onClick:h,style:'width: 100%; border-collapse: separate;'};return{title:a.lang.smiley.title,minWidth:270,minHeight:120,contents:[{id:'tab1',label:'',title:'',expand:true,padding:0,elements:[n]}],buttons:[CKEDITOR.dialog.cancelButton]};}); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/plugins/smiley/dialogs/smiley.js | smiley.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add('specialchar',function(a){var b,c=a.lang.specialChar,d=function(j){var k,l;if(j.data)k=j.data.getTarget();else k=new CKEDITOR.dom.element(j);if(k.getName()=='a'&&(l=k.getChild(0).getHtml())){k.removeClass('cke_light_background');b.hide();var m=a.document.createElement('span');m.setHtml(l);a.insertText(m.getText());}},e=CKEDITOR.tools.addFunction(d),f,g=function(j,k){var l;k=k||j.data.getTarget();if(k.getName()=='span')k=k.getParent();if(k.getName()=='a'&&(l=k.getChild(0).getHtml())){if(f)h(null,f);var m=b.getContentElement('info','htmlPreview').getElement();b.getContentElement('info','charPreview').getElement().setHtml(l);m.setHtml(CKEDITOR.tools.htmlEncode(l));k.getParent().addClass('cke_light_background');f=k;}},h=function(j,k){k=k||j.data.getTarget();if(k.getName()=='span')k=k.getParent();if(k.getName()=='a'){b.getContentElement('info','charPreview').getElement().setHtml(' ');b.getContentElement('info','htmlPreview').getElement().setHtml(' ');k.getParent().removeClass('cke_light_background');f=undefined;}},i=CKEDITOR.tools.addFunction(function(j){j=new CKEDITOR.dom.event(j);var k=j.getTarget(),l,m,n=j.getKeystroke(),o=a.lang.dir=='rtl';switch(n){case 38:if(l=k.getParent().getParent().getPrevious()){m=l.getChild([k.getParent().getIndex(),0]);m.focus();h(null,k);g(null,m);}j.preventDefault();break;case 40:if(l=k.getParent().getParent().getNext()){m=l.getChild([k.getParent().getIndex(),0]);if(m&&m.type==1){m.focus();h(null,k);g(null,m);}}j.preventDefault();break;case 32:d({data:j});j.preventDefault();break;case o?37:39:case 9:if(l=k.getParent().getNext()){m=l.getChild(0);if(m.type==1){m.focus();h(null,k);g(null,m);j.preventDefault(true);}else h(null,k);}else if(l=k.getParent().getParent().getNext()){m=l.getChild([0,0]);if(m&&m.type==1){m.focus();h(null,k);g(null,m);j.preventDefault(true);}else h(null,k);}break;case o?39:37:case CKEDITOR.SHIFT+9:if(l=k.getParent().getPrevious()){m=l.getChild(0);m.focus();h(null,k);g(null,m);j.preventDefault(true);}else if(l=k.getParent().getParent().getPrevious()){m=l.getLast().getChild(0);m.focus();h(null,k);g(null,m);j.preventDefault(true);}else h(null,k);break;default:return;}});return{title:c.title,minWidth:430,minHeight:280,buttons:[CKEDITOR.dialog.cancelButton],charColumns:17,onLoad:function(){var j=this.definition.charColumns,k=a.config.extraSpecialChars,l=a.config.specialChars,m=CKEDITOR.tools.getNextId()+'_specialchar_table_label',n=['<table role="listbox" aria-labelledby="'+m+'"'+' style="width: 320px; height: 100%; border-collapse: separate;"'+' align="center" cellspacing="2" cellpadding="2" border="0">'],o=0,p=l.length,q,r;
while(o<p){n.push('<tr>');for(var s=0;s<j;s++,o++){if(q=l[o]){r='';if(q instanceof Array){r=q[1];q=q[0];}else{var t=q.replace('&','').replace(';','').replace('#','');r=c[t]||q;}var u='cke_specialchar_label_'+o+'_'+CKEDITOR.tools.getNextNumber();n.push('<td class="cke_dark_background" style="cursor: default" role="presentation"><a href="javascript: void(0);" role="option" aria-posinset="'+(o+1)+'"',' aria-setsize="'+p+'"',' aria-labelledby="'+u+'"',' style="cursor: inherit; display: block; height: 1.25em; margin-top: 0.25em; text-align: center;" title="',CKEDITOR.tools.htmlEncode(r),'" onkeydown="CKEDITOR.tools.callFunction( '+i+', event, this )"'+' onclick="CKEDITOR.tools.callFunction('+e+', this); return false;"'+' tabindex="-1">'+'<span style="margin: 0 auto;cursor: inherit">'+q+'</span>'+'<span class="cke_voice_label" id="'+u+'">'+r+'</span></a>');}else n.push('<td class="cke_dark_background"> ');n.push('</td>');}n.push('</tr>');}n.push('</tbody></table>','<span id="'+m+'" class="cke_voice_label">'+c.options+'</span>');this.getContentElement('info','charContainer').getElement().setHtml(n.join(''));},contents:[{id:'info',label:a.lang.common.generalTab,title:a.lang.common.generalTab,padding:0,align:'top',elements:[{type:'hbox',align:'top',widths:['320px','90px'],children:[{type:'html',id:'charContainer',html:'',onMouseover:g,onMouseout:h,focus:function(){var j=this.getElement().getElementsByTag('a').getItem(0);setTimeout(function(){j.focus();g(null,j);},0);},onShow:function(){var j=this.getElement().getChild([0,0,0,0,0]);setTimeout(function(){j.focus();g(null,j);},0);},onLoad:function(j){b=j.sender;}},{type:'hbox',align:'top',widths:['100%'],children:[{type:'vbox',align:'top',children:[{type:'html',html:'<div></div>'},{type:'html',id:'charPreview',className:'cke_dark_background',style:"border:1px solid #eeeeee;font-size:28px;height:40px;width:70px;padding-top:9px;font-family:'Microsoft Sans Serif',Arial,Helvetica,Verdana;text-align:center;",html:'<div> </div>'},{type:'html',id:'htmlPreview',className:'cke_dark_background',style:"border:1px solid #eeeeee;font-size:14px;height:20px;width:70px;padding-top:2px;font-family:'Microsoft Sans Serif',Arial,Helvetica,Verdana;text-align:center;",html:'<div> </div>'}]}]}]}]}]};}); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/plugins/specialchar/dialogs/specialchar.js | specialchar.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('specialchar','en',{euro:'Euro sign',lsquo:'Left single quotation mark',rsquo:'Right single quotation mark',ldquo:'Left double quotation mark',rdquo:'Right double quotation mark',ndash:'En dash',mdash:'Em dash',iexcl:'Inverted exclamation mark',cent:'Cent sign',pound:'Pound sign',curren:'Currency sign',yen:'Yen sign',brvbar:'Broken bar',sect:'Section sign',uml:'Diaeresis',copy:'Copyright sign',ordf:'Feminine ordinal indicator',laquo:'Left-pointing double angle quotation mark',not:'Not sign',reg:'Registered sign',macr:'Macron',deg:'Degree sign',sup2:'Superscript two',sup3:'Superscript three',acute:'Acute accent',micro:'Micro sign',para:'Pilcrow sign',middot:'Middle dot',cedil:'Cedilla',sup1:'Superscript one',ordm:'Masculine ordinal indicator',raquo:'Right-pointing double angle quotation mark',frac14:'Vulgar fraction one quarter',frac12:'Vulgar fraction one half',frac34:'Vulgar fraction three quarters',iquest:'Inverted question mark',Agrave:'Latin capital letter A with grave accent',Aacute:'Latin capital letter A with acute accent',Acirc:'Latin capital letter A with circumflex',Atilde:'Latin capital letter A with tilde',Auml:'Latin capital letter A with diaeresis',Aring:'Latin capital letter A with ring above',AElig:'Latin Capital letter Æ',Ccedil:'Latin capital letter C with cedilla',Egrave:'Latin capital letter E with grave accent',Eacute:'Latin capital letter E with acute accent',Ecirc:'Latin capital letter E with circumflex',Euml:'Latin capital letter E with diaeresis',Igrave:'Latin capital letter I with grave accent',Iacute:'Latin capital letter I with acute accent',Icirc:'Latin capital letter I with circumflex',Iuml:'Latin capital letter I with diaeresis',ETH:'Latin capital letter Eth',Ntilde:'Latin capital letter N with tilde',Ograve:'Latin capital letter O with grave accent',Oacute:'Latin capital letter O with acute accent',Ocirc:'Latin capital letter O with circumflex',Otilde:'Latin capital letter O with tilde',Ouml:'Latin capital letter O with diaeresis',times:'Multiplication sign',Oslash:'Latin capital letter O with stroke',Ugrave:'Latin capital letter U with grave accent',Uacute:'Latin capital letter U with acute accent',Ucirc:'Latin capital letter U with circumflex',Uuml:'Latin capital letter U with diaeresis',Yacute:'Latin capital letter Y with acute accent',THORN:'Latin capital letter Thorn',szlig:'Latin small letter sharp s',agrave:'Latin small letter a with grave accent',aacute:'Latin small letter a with acute accent',acirc:'Latin small letter a with circumflex',atilde:'Latin small letter a with tilde',auml:'Latin small letter a with diaeresis',aring:'Latin small letter a with ring above',aelig:'Latin small letter æ',ccedil:'Latin small letter c with cedilla',egrave:'Latin small letter e with grave accent',eacute:'Latin small letter e with acute accent',ecirc:'Latin small letter e with circumflex',euml:'Latin small letter e with diaeresis',igrave:'Latin small letter i with grave accent',iacute:'Latin small letter i with acute accent',icirc:'Latin small letter i with circumflex',iuml:'Latin small letter i with diaeresis',eth:'Latin small letter eth',ntilde:'Latin small letter n with tilde',ograve:'Latin small letter o with grave accent',oacute:'Latin small letter o with acute accent',ocirc:'Latin small letter o with circumflex',otilde:'Latin small letter o with tilde',ouml:'Latin small letter o with diaeresis',divide:'Division sign',oslash:'Latin small letter o with stroke',ugrave:'Latin small letter u with grave accent',uacute:'Latin small letter u with acute accent',ucirc:'Latin small letter u with circumflex',uuml:'Latin small letter u with diaeresis',yacute:'Latin small letter y with acute accent',thorn:'Latin small letter thorn',yuml:'Latin small letter y with diaeresis',OElig:'Latin capital ligature OE',oelig:'Latin small ligature oe',372:'Latin capital letter W with circumflex',374:'Latin capital letter Y with circumflex',373:'Latin small letter w with circumflex',375:'Latin small letter y with circumflex',sbquo:'Single low-9 quotation mark',8219:'Single high-reversed-9 quotation mark',bdquo:'Double low-9 quotation mark',hellip:'Horizontal ellipsis',trade:'Trade mark sign',9658:'Black right-pointing pointer',bull:'Bullet',rarr:'Rightwards arrow',rArr:'Rightwards double arrow',hArr:'Left right double arrow',diams:'Black diamond suit',asymp:'Almost equal to'}); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/plugins/specialchar/lang/en.js | en.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function(){var a=function(b,c){var d=1,e=2,f=4,g=8,h=/^\s*(\d+)((px)|\%)?\s*$/i,i=/(^\s*(\d+)((px)|\%)?\s*$)|^$/i,j=/^\d+px$/,k=function(){var C=this.getValue(),D=this.getDialog(),E=C.match(h);if(E){if(E[2]=='%')p(D,false);C=E[1];}if(D.lockRatio){var F=D.originalElement;if(F.getCustomData('isReady')=='true')if(this.id=='txtHeight'){if(C&&C!='0')C=Math.round(F.$.width*(C/F.$.height));if(!isNaN(C))D.setValueOf('info','txtWidth',C);}else{if(C&&C!='0')C=Math.round(F.$.height*(C/F.$.width));if(!isNaN(C))D.setValueOf('info','txtHeight',C);}}l(D);},l=function(C){if(!C.originalElement||!C.preview)return 1;C.commitContent(f,C.preview);return 0;};function m(){var C=arguments,D=this.getContentElement('advanced','txtdlgGenStyle');D&&D.commit.apply(D,C);this.foreach(function(E){if(E.commit&&E.id!='txtdlgGenStyle')E.commit.apply(E,C);});};var n;function o(C){if(n)return;n=1;var D=this.getDialog(),E=D.imageElement;if(E){this.commit(d,E);C=[].concat(C);var F=C.length,G;for(var H=0;H<F;H++){G=D.getContentElement.apply(D,C[H].split(':'));G&&G.setup(d,E);}}n=0;};var p=function(C,D){if(!C.getContentElement('info','ratioLock'))return null;var E=C.originalElement;if(!E)return null;if(D=='check'){if(!C.userlockRatio&&E.getCustomData('isReady')=='true'){var F=C.getValueOf('info','txtWidth'),G=C.getValueOf('info','txtHeight'),H=E.$.width*1000/E.$.height,I=F*1000/G;C.lockRatio=false;if(!F&&!G)C.lockRatio=true;else if(!isNaN(H)&&!isNaN(I))if(Math.round(H)==Math.round(I))C.lockRatio=true;}}else if(D!=undefined)C.lockRatio=D;else{C.userlockRatio=1;C.lockRatio=!C.lockRatio;}var J=CKEDITOR.document.getById(w);if(C.lockRatio)J.removeClass('cke_btn_unlocked');else J.addClass('cke_btn_unlocked');J.setAttribute('aria-checked',C.lockRatio);if(CKEDITOR.env.hc){var K=J.getChild(0);K.setHtml(C.lockRatio?CKEDITOR.env.ie?'■':'▣':CKEDITOR.env.ie?'□':'▢');}return C.lockRatio;},q=function(C){var D=C.originalElement;if(D.getCustomData('isReady')=='true'){var E=C.getContentElement('info','txtWidth'),F=C.getContentElement('info','txtHeight');E&&E.setValue(D.$.width);F&&F.setValue(D.$.height);}l(C);},r=function(C,D){if(C!=d)return;function E(J,K){var L=J.match(h);if(L){if(L[2]=='%'){L[1]+='%';p(F,false);}return L[1];}return K;};var F=this.getDialog(),G='',H=this.id=='txtWidth'?'width':'height',I=D.getAttribute(H);if(I)G=E(I,G);G=E(D.getStyle(H),G);this.setValue(G);},s,t=function(){var C=this.originalElement;C.setCustomData('isReady','true');C.removeListener('load',t);C.removeListener('error',u);C.removeListener('abort',u);
CKEDITOR.document.getById(y).setStyle('display','none');if(!this.dontResetSize)q(this);if(this.firstLoad)CKEDITOR.tools.setTimeout(function(){p(this,'check');},0,this);this.firstLoad=false;this.dontResetSize=false;},u=function(){var E=this;var C=E.originalElement;C.removeListener('load',t);C.removeListener('error',u);C.removeListener('abort',u);var D=CKEDITOR.getUrl(b.skinPath+'images/noimage.png');if(E.preview)E.preview.setAttribute('src',D);CKEDITOR.document.getById(y).setStyle('display','none');p(E,false);},v=function(C){return CKEDITOR.tools.getNextId()+'_'+C;},w=v('btnLockSizes'),x=v('btnResetSize'),y=v('ImagePreviewLoader'),z=v('ImagePreviewBox'),A=v('previewLink'),B=v('previewImage');return{title:b.lang.image[c=='image'?'title':'titleButton'],minWidth:420,minHeight:360,onShow:function(){var I=this;I.imageElement=false;I.linkElement=false;I.imageEditMode=false;I.linkEditMode=false;I.lockRatio=true;I.userlockRatio=0;I.dontResetSize=false;I.firstLoad=true;I.addLink=false;var C=I.getParentEditor(),D=I.getParentEditor().getSelection(),E=D.getSelectedElement(),F=E&&E.getAscendant('a');CKEDITOR.document.getById(y).setStyle('display','none');s=new CKEDITOR.dom.element('img',C.document);I.preview=CKEDITOR.document.getById(B);I.originalElement=C.document.createElement('img');I.originalElement.setAttribute('alt','');I.originalElement.setCustomData('isReady','false');if(F){I.linkElement=F;I.linkEditMode=true;var G=F.getChildren();if(G.count()==1){var H=G.getItem(0).getName();if(H=='img'||H=='input'){I.imageElement=G.getItem(0);if(I.imageElement.getName()=='img')I.imageEditMode='img';else if(I.imageElement.getName()=='input')I.imageEditMode='input';}}if(c=='image')I.setupContent(e,F);}if(E&&E.getName()=='img'&&!E.data('cke-realelement')||E&&E.getName()=='input'&&E.getAttribute('type')=='image'){I.imageEditMode=E.getName();I.imageElement=E;}if(I.imageEditMode){I.cleanImageElement=I.imageElement;I.imageElement=I.cleanImageElement.clone(true,true);I.setupContent(d,I.imageElement);}else I.imageElement=C.document.createElement('img');p(I,true);if(!CKEDITOR.tools.trim(I.getValueOf('info','txtUrl'))){I.preview.removeAttribute('src');I.preview.setStyle('display','none');}},onOk:function(){var D=this;if(D.imageEditMode){var C=D.imageEditMode;if(c=='image'&&C=='input'&&confirm(b.lang.image.button2Img)){C='img';D.imageElement=b.document.createElement('img');D.imageElement.setAttribute('alt','');b.insertElement(D.imageElement);}else if(c!='image'&&C=='img'&&confirm(b.lang.image.img2Button)){C='input';
D.imageElement=b.document.createElement('input');D.imageElement.setAttributes({type:'image',alt:''});b.insertElement(D.imageElement);}else{D.imageElement=D.cleanImageElement;delete D.cleanImageElement;}}else{if(c=='image')D.imageElement=b.document.createElement('img');else{D.imageElement=b.document.createElement('input');D.imageElement.setAttribute('type','image');}D.imageElement.setAttribute('alt','');}if(!D.linkEditMode)D.linkElement=b.document.createElement('a');D.commitContent(d,D.imageElement);D.commitContent(e,D.linkElement);if(!D.imageElement.getAttribute('style'))D.imageElement.removeAttribute('style');if(!D.imageEditMode){if(D.addLink){if(!D.linkEditMode){b.insertElement(D.linkElement);D.linkElement.append(D.imageElement,false);}else b.insertElement(D.imageElement);}else b.insertElement(D.imageElement);}else if(!D.linkEditMode&&D.addLink){b.insertElement(D.linkElement);D.imageElement.appendTo(D.linkElement);}else if(D.linkEditMode&&!D.addLink){b.getSelection().selectElement(D.linkElement);b.insertElement(D.imageElement);}},onLoad:function(){var D=this;if(c!='image')D.hidePage('Link');var C=D._.element.getDocument();if(D.getContentElement('info','ratioLock')){D.addFocusable(C.getById(x),5);D.addFocusable(C.getById(w),5);}D.commitContent=m;},onHide:function(){var C=this;if(C.preview)C.commitContent(g,C.preview);if(C.originalElement){C.originalElement.removeListener('load',t);C.originalElement.removeListener('error',u);C.originalElement.removeListener('abort',u);C.originalElement.remove();C.originalElement=false;}delete C.imageElement;},contents:[{id:'info',label:b.lang.image.infoTab,accessKey:'I',elements:[{type:'vbox',padding:0,children:[{type:'hbox',widths:['280px','110px'],align:'right',children:[{id:'txtUrl',type:'text',label:b.lang.common.url,required:true,onChange:function(){var C=this.getDialog(),D=this.getValue();if(D.length>0){C=this.getDialog();var E=C.originalElement;C.preview.removeStyle('display');E.setCustomData('isReady','false');var F=CKEDITOR.document.getById(y);if(F)F.setStyle('display','');E.on('load',t,C);E.on('error',u,C);E.on('abort',u,C);E.setAttribute('src',D);s.setAttribute('src',D);C.preview.setAttribute('src',s.$.src);l(C);}else if(C.preview){C.preview.removeAttribute('src');C.preview.setStyle('display','none');}},setup:function(C,D){if(C==d){var E=D.data('cke-saved-src')||D.getAttribute('src'),F=this;this.getDialog().dontResetSize=true;F.setValue(E);F.setInitValue();}},commit:function(C,D){var E=this;if(C==d&&(E.getValue()||E.isChanged())){D.data('cke-saved-src',E.getValue());
D.setAttribute('src',E.getValue());}else if(C==g){D.setAttribute('src','');D.removeAttribute('src');}},validate:CKEDITOR.dialog.validate.notEmpty(b.lang.image.urlMissing)},{type:'button',id:'browse',style:'display:inline-block;margin-top:10px;',align:'center',label:b.lang.common.browseServer,hidden:true,filebrowser:'info:txtUrl'}]}]},{id:'txtAlt',type:'text',label:b.lang.image.alt,accessKey:'T','default':'',onChange:function(){l(this.getDialog());},setup:function(C,D){if(C==d)this.setValue(D.getAttribute('alt'));},commit:function(C,D){var E=this;if(C==d){if(E.getValue()||E.isChanged())D.setAttribute('alt',E.getValue());}else if(C==f)D.setAttribute('alt',E.getValue());else if(C==g)D.removeAttribute('alt');}},{type:'hbox',children:[{id:'basic',type:'vbox',children:[{type:'hbox',widths:['50%','50%'],children:[{type:'vbox',padding:1,children:[{type:'text',width:'40px',id:'txtWidth',label:b.lang.common.width,onKeyUp:k,onChange:function(){o.call(this,'advanced:txtdlgGenStyle');},validate:function(){var C=this.getValue().match(i),D=!!(C&&parseInt(C[1],10)!==0);if(!D)alert(b.lang.common.invalidWidth);return D;},setup:r,commit:function(C,D,E){var F=this.getValue();if(C==d){if(F)D.setStyle('width',CKEDITOR.tools.cssLength(F));else D.removeStyle('width');!E&&D.removeAttribute('width');}else if(C==f){var G=F.match(h);if(!G){var H=this.getDialog().originalElement;if(H.getCustomData('isReady')=='true')D.setStyle('width',H.$.width+'px');}else D.setStyle('width',CKEDITOR.tools.cssLength(F));}else if(C==g){D.removeAttribute('width');D.removeStyle('width');}}},{type:'text',id:'txtHeight',width:'40px',label:b.lang.common.height,onKeyUp:k,onChange:function(){o.call(this,'advanced:txtdlgGenStyle');},validate:function(){var C=this.getValue().match(i),D=!!(C&&parseInt(C[1],10)!==0);if(!D)alert(b.lang.common.invalidHeight);return D;},setup:r,commit:function(C,D,E){var F=this.getValue();if(C==d){if(F)D.setStyle('height',CKEDITOR.tools.cssLength(F));else D.removeStyle('height');!E&&D.removeAttribute('height');}else if(C==f){var G=F.match(h);if(!G){var H=this.getDialog().originalElement;if(H.getCustomData('isReady')=='true')D.setStyle('height',H.$.height+'px');}else D.setStyle('height',CKEDITOR.tools.cssLength(F));}else if(C==g){D.removeAttribute('height');D.removeStyle('height');}}}]},{id:'ratioLock',type:'html',style:'margin-top:30px;width:40px;height:40px;',onLoad:function(){var C=CKEDITOR.document.getById(x),D=CKEDITOR.document.getById(w);if(C){C.on('click',function(E){q(this);E.data&&E.data.preventDefault();
},this.getDialog());C.on('mouseover',function(){this.addClass('cke_btn_over');},C);C.on('mouseout',function(){this.removeClass('cke_btn_over');},C);}if(D){D.on('click',function(E){var J=this;var F=p(J),G=J.originalElement,H=J.getValueOf('info','txtWidth');if(G.getCustomData('isReady')=='true'&&H){var I=G.$.height/G.$.width*H;if(!isNaN(I)){J.setValueOf('info','txtHeight',Math.round(I));l(J);}}E.data&&E.data.preventDefault();},this.getDialog());D.on('mouseover',function(){this.addClass('cke_btn_over');},D);D.on('mouseout',function(){this.removeClass('cke_btn_over');},D);}},html:'<div><a href="javascript:void(0)" tabindex="-1" title="'+b.lang.image.lockRatio+'" class="cke_btn_locked" id="'+w+'" role="checkbox"><span class="cke_icon"></span><span class="cke_label">'+b.lang.image.lockRatio+'</span></a>'+'<a href="javascript:void(0)" tabindex="-1" title="'+b.lang.image.resetSize+'" class="cke_btn_reset" id="'+x+'" role="button"><span class="cke_label">'+b.lang.image.resetSize+'</span></a>'+'</div>'}]},{type:'vbox',padding:1,children:[{type:'text',id:'txtBorder',width:'60px',label:b.lang.image.border,'default':'',onKeyUp:function(){l(this.getDialog());},onChange:function(){o.call(this,'advanced:txtdlgGenStyle');},validate:CKEDITOR.dialog.validate.integer(b.lang.image.validateBorder),setup:function(C,D){if(C==d){var E,F=D.getStyle('border-width');F=F&&F.match(/^(\d+px)(?: \1 \1 \1)?$/);E=F&&parseInt(F[1],10);isNaN(parseInt(E,10))&&(E=D.getAttribute('border'));this.setValue(E);}},commit:function(C,D,E){var F=parseInt(this.getValue(),10);if(C==d||C==f){if(!isNaN(F)){D.setStyle('border-width',CKEDITOR.tools.cssLength(F));D.setStyle('border-style','solid');}else if(!F&&this.isChanged()){D.removeStyle('border-width');D.removeStyle('border-style');D.removeStyle('border-color');}if(!E&&C==d)D.removeAttribute('border');}else if(C==g){D.removeAttribute('border');D.removeStyle('border-width');D.removeStyle('border-style');D.removeStyle('border-color');}}},{type:'text',id:'txtHSpace',width:'60px',label:b.lang.image.hSpace,'default':'',onKeyUp:function(){l(this.getDialog());},onChange:function(){o.call(this,'advanced:txtdlgGenStyle');},validate:CKEDITOR.dialog.validate.integer(b.lang.image.validateHSpace),setup:function(C,D){if(C==d){var E,F,G,H=D.getStyle('margin-left'),I=D.getStyle('margin-right');H=H&&H.match(j);I=I&&I.match(j);F=parseInt(H,10);G=parseInt(I,10);E=F==G&&F;isNaN(parseInt(E,10))&&(E=D.getAttribute('hspace'));this.setValue(E);}},commit:function(C,D,E){var F=parseInt(this.getValue(),10);
if(C==d||C==f){if(!isNaN(F)){D.setStyle('margin-left',CKEDITOR.tools.cssLength(F));D.setStyle('margin-right',CKEDITOR.tools.cssLength(F));}else if(!F&&this.isChanged()){D.removeStyle('margin-left');D.removeStyle('margin-right');}if(!E&&C==d)D.removeAttribute('hspace');}else if(C==g){D.removeAttribute('hspace');D.removeStyle('margin-left');D.removeStyle('margin-right');}}},{type:'text',id:'txtVSpace',width:'60px',label:b.lang.image.vSpace,'default':'',onKeyUp:function(){l(this.getDialog());},onChange:function(){o.call(this,'advanced:txtdlgGenStyle');},validate:CKEDITOR.dialog.validate.integer(b.lang.image.validateVSpace),setup:function(C,D){if(C==d){var E,F,G,H=D.getStyle('margin-top'),I=D.getStyle('margin-bottom');H=H&&H.match(j);I=I&&I.match(j);F=parseInt(H,10);G=parseInt(I,10);E=F==G&&F;isNaN(parseInt(E,10))&&(E=D.getAttribute('vspace'));this.setValue(E);}},commit:function(C,D,E){var F=parseInt(this.getValue(),10);if(C==d||C==f){if(!isNaN(F)){D.setStyle('margin-top',CKEDITOR.tools.cssLength(F));D.setStyle('margin-bottom',CKEDITOR.tools.cssLength(F));}else if(!F&&this.isChanged()){D.removeStyle('margin-top');D.removeStyle('margin-bottom');}if(!E&&C==d)D.removeAttribute('vspace');}else if(C==g){D.removeAttribute('vspace');D.removeStyle('margin-top');D.removeStyle('margin-bottom');}}},{id:'cmbAlign',type:'select',widths:['35%','65%'],style:'width:90px',label:b.lang.common.align,'default':'',items:[[b.lang.common.notSet,''],[b.lang.common.alignLeft,'left'],[b.lang.common.alignRight,'right']],onChange:function(){l(this.getDialog());o.call(this,'advanced:txtdlgGenStyle');},setup:function(C,D){if(C==d){var E=D.getStyle('float');switch(E){case 'inherit':case 'none':E='';}!E&&(E=(D.getAttribute('align')||'').toLowerCase());this.setValue(E);}},commit:function(C,D,E){var F=this.getValue();if(C==d||C==f){if(F)D.setStyle('float',F);else D.removeStyle('float');if(!E&&C==d){F=(D.getAttribute('align')||'').toLowerCase();switch(F){case 'left':case 'right':D.removeAttribute('align');}}}else if(C==g)D.removeStyle('float');}}]}]},{type:'vbox',height:'250px',children:[{type:'html',id:'htmlPreview',style:'width:95%;',html:'<div>'+CKEDITOR.tools.htmlEncode(b.lang.common.preview)+'<br>'+'<div id="'+y+'" class="ImagePreviewLoader" style="display:none"><div class="loading"> </div></div>'+'<div id="'+z+'" class="ImagePreviewBox"><table><tr><td>'+'<a href="javascript:void(0)" target="_blank" onclick="return false;" id="'+A+'">'+'<img id="'+B+'" alt="" /></a>'+(b.config.image_previewText||'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas feugiat consequat diam. Maecenas metus. Vivamus diam purus, cursus a, commodo non, facilisis vitae, nulla. Aenean dictum lacinia tortor. Nunc iaculis, nibh non iaculis aliquam, orci felis euismod neque, sed ornare massa mauris sed velit. Nulla pretium mi et risus. Fusce mi pede, tempor id, cursus ac, ullamcorper nec, enim. Sed tortor. Curabitur molestie. Duis velit augue, condimentum at, ultrices a, luctus ut, orci. Donec pellentesque egestas eros. Integer cursus, augue in cursus faucibus, eros pede bibendum sem, in tempus tellus justo quis ligula. Etiam eget tortor. Vestibulum rutrum, est ut placerat elementum, lectus nisl aliquam velit, tempor aliquam eros nunc nonummy metus. In eros metus, gravida a, gravida sed, lobortis id, turpis. Ut ultrices, ipsum at venenatis fringilla, sem nulla lacinia tellus, eget aliquet turpis mauris non enim. Nam turpis. Suspendisse lacinia. Curabitur ac tortor ut ipsum egestas elementum. Nunc imperdiet gravida mauris.')+'</td></tr></table></div></div>'}]}]}]},{id:'Link',label:b.lang.link.title,padding:0,elements:[{id:'txtUrl',type:'text',label:b.lang.common.url,style:'width: 100%','default':'',setup:function(C,D){if(C==e){var E=D.data('cke-saved-href');
if(!E)E=D.getAttribute('href');this.setValue(E);}},commit:function(C,D){var F=this;if(C==e)if(F.getValue()||F.isChanged()){var E=decodeURI(F.getValue());D.data('cke-saved-href',E);D.setAttribute('href',E);if(F.getValue()||!b.config.image_removeLinkByEmptyURL)F.getDialog().addLink=true;}}},{type:'button',id:'browse',filebrowser:{action:'Browse',target:'Link:txtUrl',url:b.config.filebrowserImageBrowseLinkUrl},style:'float:right',hidden:true,label:b.lang.common.browseServer},{id:'cmbTarget',type:'select',label:b.lang.common.target,'default':'',items:[[b.lang.common.notSet,''],[b.lang.common.targetNew,'_blank'],[b.lang.common.targetTop,'_top'],[b.lang.common.targetSelf,'_self'],[b.lang.common.targetParent,'_parent']],setup:function(C,D){if(C==e)this.setValue(D.getAttribute('target')||'');},commit:function(C,D){if(C==e)if(this.getValue()||this.isChanged())D.setAttribute('target',this.getValue());}}]},{id:'Upload',hidden:true,filebrowser:'uploadButton',label:b.lang.image.upload,elements:[{type:'file',id:'upload',label:b.lang.image.btnUpload,style:'height:40px',size:38},{type:'fileButton',id:'uploadButton',filebrowser:'info:txtUrl',label:b.lang.image.btnUpload,'for':['Upload','upload']}]},{id:'advanced',label:b.lang.common.advancedTab,elements:[{type:'hbox',widths:['50%','25%','25%'],children:[{type:'text',id:'linkId',label:b.lang.common.id,setup:function(C,D){if(C==d)this.setValue(D.getAttribute('id'));},commit:function(C,D){if(C==d)if(this.getValue()||this.isChanged())D.setAttribute('id',this.getValue());}},{id:'cmbLangDir',type:'select',style:'width : 100px;',label:b.lang.common.langDir,'default':'',items:[[b.lang.common.notSet,''],[b.lang.common.langDirLtr,'ltr'],[b.lang.common.langDirRtl,'rtl']],setup:function(C,D){if(C==d)this.setValue(D.getAttribute('dir'));},commit:function(C,D){if(C==d)if(this.getValue()||this.isChanged())D.setAttribute('dir',this.getValue());}},{type:'text',id:'txtLangCode',label:b.lang.common.langCode,'default':'',setup:function(C,D){if(C==d)this.setValue(D.getAttribute('lang'));},commit:function(C,D){if(C==d)if(this.getValue()||this.isChanged())D.setAttribute('lang',this.getValue());}}]},{type:'text',id:'txtGenLongDescr',label:b.lang.common.longDescr,setup:function(C,D){if(C==d)this.setValue(D.getAttribute('longDesc'));},commit:function(C,D){if(C==d)if(this.getValue()||this.isChanged())D.setAttribute('longDesc',this.getValue());}},{type:'hbox',widths:['50%','50%'],children:[{type:'text',id:'txtGenClass',label:b.lang.common.cssClass,'default':'',setup:function(C,D){if(C==d)this.setValue(D.getAttribute('class'));
},commit:function(C,D){if(C==d)if(this.getValue()||this.isChanged())D.setAttribute('class',this.getValue());}},{type:'text',id:'txtGenTitle',label:b.lang.common.advisoryTitle,'default':'',onChange:function(){l(this.getDialog());},setup:function(C,D){if(C==d)this.setValue(D.getAttribute('title'));},commit:function(C,D){var E=this;if(C==d){if(E.getValue()||E.isChanged())D.setAttribute('title',E.getValue());}else if(C==f)D.setAttribute('title',E.getValue());else if(C==g)D.removeAttribute('title');}}]},{type:'text',id:'txtdlgGenStyle',label:b.lang.common.cssStyle,validate:CKEDITOR.dialog.validate.inlineStyle(b.lang.common.invalidInlineStyle),'default':'',setup:function(C,D){if(C==d){var E=D.getAttribute('style');if(!E&&D.$.style.cssText)E=D.$.style.cssText;this.setValue(E);var F=D.$.style.height,G=D.$.style.width,H=(F?F:'').match(h),I=(G?G:'').match(h);this.attributesInStyle={height:!!H,width:!!I};}},onChange:function(){o.call(this,['info:cmbFloat','info:cmbAlign','info:txtVSpace','info:txtHSpace','info:txtBorder','info:txtWidth','info:txtHeight']);l(this);},commit:function(C,D){if(C==d&&(this.getValue()||this.isChanged()))D.setAttribute('style',this.getValue());}}]}]};};CKEDITOR.dialog.add('image',function(b){return a(b,'image');});CKEDITOR.dialog.add('imagebutton',function(b){return a(b,'imagebutton');});})(); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/plugins/image/dialogs/image.js | image.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function(){var a=1,b=2,c=4,d={id:[{type:a,name:'id'}],classid:[{type:a,name:'classid'}],codebase:[{type:a,name:'codebase'}],pluginspage:[{type:c,name:'pluginspage'}],src:[{type:b,name:'movie'},{type:c,name:'src'},{type:a,name:'data'}],name:[{type:c,name:'name'}],align:[{type:a,name:'align'}],title:[{type:a,name:'title'},{type:c,name:'title'}],'class':[{type:a,name:'class'},{type:c,name:'class'}],width:[{type:a,name:'width'},{type:c,name:'width'}],height:[{type:a,name:'height'},{type:c,name:'height'}],hSpace:[{type:a,name:'hSpace'},{type:c,name:'hSpace'}],vSpace:[{type:a,name:'vSpace'},{type:c,name:'vSpace'}],style:[{type:a,name:'style'},{type:c,name:'style'}],type:[{type:c,name:'type'}]},e=['play','loop','menu','quality','scale','salign','wmode','bgcolor','base','flashvars','allowScriptAccess','allowFullScreen'];for(var f=0;f<e.length;f++)d[e[f]]=[{type:c,name:e[f]},{type:b,name:e[f]}];e=['allowFullScreen','play','loop','menu'];for(f=0;f<e.length;f++)d[e[f]][0]['default']=d[e[f]][1]['default']=true;var g=CKEDITOR.tools.cssLength;function h(j,k,l){var r=this;var m=d[r.id];if(!m)return;var n=r instanceof CKEDITOR.ui.dialog.checkbox;for(var o=0;o<m.length;o++){var p=m[o];switch(p.type){case a:if(!j)continue;if(j.getAttribute(p.name)!==null){var q=j.getAttribute(p.name);if(n)r.setValue(q.toLowerCase()=='true');else r.setValue(q);return;}else if(n)r.setValue(!!p['default']);break;case b:if(!j)continue;if(p.name in l){q=l[p.name];if(n)r.setValue(q.toLowerCase()=='true');else r.setValue(q);return;}else if(n)r.setValue(!!p['default']);break;case c:if(!k)continue;if(k.getAttribute(p.name)){q=k.getAttribute(p.name);if(n)r.setValue(q.toLowerCase()=='true');else r.setValue(q);return;}else if(n)r.setValue(!!p['default']);}}};function i(j,k,l){var t=this;var m=d[t.id];if(!m)return;var n=t.getValue()==='',o=t instanceof CKEDITOR.ui.dialog.checkbox;for(var p=0;p<m.length;p++){var q=m[p];switch(q.type){case a:if(!j||q.name=='data'&&k&&!j.hasAttribute('data'))continue;var r=t.getValue();if(n||o&&r===q['default'])j.removeAttribute(q.name);else j.setAttribute(q.name,r);break;case b:if(!j)continue;r=t.getValue();if(n||o&&r===q['default']){if(q.name in l)l[q.name].remove();}else if(q.name in l)l[q.name].setAttribute('value',r);else{var s=CKEDITOR.dom.element.createFromHtml('<cke:param></cke:param>',j.getDocument());s.setAttributes({name:q.name,value:r});if(j.getChildCount()<1)s.appendTo(j);else s.insertBefore(j.getFirst());}break;case c:if(!k)continue;r=t.getValue();if(n||o&&r===q['default'])k.removeAttribute(q.name);
else k.setAttribute(q.name,r);}}};CKEDITOR.dialog.add('flash',function(j){var k=!j.config.flashEmbedTagOnly,l=j.config.flashAddEmbedTag||j.config.flashEmbedTagOnly,m,n='<div>'+CKEDITOR.tools.htmlEncode(j.lang.common.preview)+'<br>'+'<div id="cke_FlashPreviewLoader'+CKEDITOR.tools.getNextNumber()+'" style="display:none"><div class="loading"> </div></div>'+'<div id="cke_FlashPreviewBox'+CKEDITOR.tools.getNextNumber()+'" class="FlashPreviewBox"></div></div>';return{title:j.lang.flash.title,minWidth:420,minHeight:310,onShow:function(){var A=this;A.fakeImage=A.objectNode=A.embedNode=null;m=new CKEDITOR.dom.element('embed',j.document);var o=A.getSelectedElement();if(o&&o.data('cke-real-element-type')&&o.data('cke-real-element-type')=='flash'){A.fakeImage=o;var p=j.restoreRealElement(o),q=null,r=null,s={};if(p.getName()=='cke:object'){q=p;var t=q.getElementsByTag('embed','cke');if(t.count()>0)r=t.getItem(0);var u=q.getElementsByTag('param','cke');for(var v=0,w=u.count();v<w;v++){var x=u.getItem(v),y=x.getAttribute('name'),z=x.getAttribute('value');s[y]=z;}}else if(p.getName()=='cke:embed')r=p;A.objectNode=q;A.embedNode=r;A.setupContent(q,r,s,o);}},onOk:function(){var y=this;var o=null,p=null,q=null;if(!y.fakeImage){if(k){o=CKEDITOR.dom.element.createFromHtml('<cke:object></cke:object>',j.document);var r={classid:'clsid:d27cdb6e-ae6d-11cf-96b8-444553540000',codebase:'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0'};o.setAttributes(r);}if(l){p=CKEDITOR.dom.element.createFromHtml('<cke:embed></cke:embed>',j.document);p.setAttributes({type:'application/x-shockwave-flash',pluginspage:'http://www.macromedia.com/go/getflashplayer'});if(o)p.appendTo(o);}}else{o=y.objectNode;p=y.embedNode;}if(o){q={};var s=o.getElementsByTag('param','cke');for(var t=0,u=s.count();t<u;t++)q[s.getItem(t).getAttribute('name')]=s.getItem(t);}var v={},w={};y.commitContent(o,p,q,v,w);var x=j.createFakeElement(o||p,'cke_flash','flash',true);x.setAttributes(w);x.setStyles(v);if(y.fakeImage){x.replace(y.fakeImage);j.getSelection().selectElement(x);}else j.insertElement(x);},onHide:function(){if(this.preview)this.preview.setHtml('');},contents:[{id:'info',label:j.lang.common.generalTab,accessKey:'I',elements:[{type:'vbox',padding:0,children:[{type:'hbox',widths:['280px','110px'],align:'right',children:[{id:'src',type:'text',label:j.lang.common.url,required:true,validate:CKEDITOR.dialog.validate.notEmpty(j.lang.flash.validateSrc),setup:h,commit:i,onLoad:function(){var o=this.getDialog(),p=function(q){m.setAttribute('src',q);
o.preview.setHtml('<embed height="100%" width="100%" src="'+CKEDITOR.tools.htmlEncode(m.getAttribute('src'))+'" type="application/x-shockwave-flash"></embed>');};o.preview=o.getContentElement('info','preview').getElement().getChild(3);this.on('change',function(q){if(q.data&&q.data.value)p(q.data.value);});this.getInputElement().on('change',function(q){p(this.getValue());},this);}},{type:'button',id:'browse',filebrowser:'info:src',hidden:true,style:'display:inline-block;margin-top:10px;',label:j.lang.common.browseServer}]}]},{type:'hbox',widths:['25%','25%','25%','25%','25%'],children:[{type:'text',id:'width',style:'width:95px',label:j.lang.common.width,validate:CKEDITOR.dialog.validate.htmlLength(j.lang.common.invalidHtmlLength.replace('%1',j.lang.common.width)),setup:h,commit:i},{type:'text',id:'height',style:'width:95px',label:j.lang.common.height,validate:CKEDITOR.dialog.validate.htmlLength(j.lang.common.invalidHtmlLength.replace('%1',j.lang.common.height)),setup:h,commit:i},{type:'text',id:'hSpace',style:'width:95px',label:j.lang.flash.hSpace,validate:CKEDITOR.dialog.validate.integer(j.lang.flash.validateHSpace),setup:h,commit:i},{type:'text',id:'vSpace',style:'width:95px',label:j.lang.flash.vSpace,validate:CKEDITOR.dialog.validate.integer(j.lang.flash.validateVSpace),setup:h,commit:i}]},{type:'vbox',children:[{type:'html',id:'preview',style:'width:95%;',html:n}]}]},{id:'Upload',hidden:true,filebrowser:'uploadButton',label:j.lang.common.upload,elements:[{type:'file',id:'upload',label:j.lang.common.upload,size:38},{type:'fileButton',id:'uploadButton',label:j.lang.common.uploadSubmit,filebrowser:'info:src','for':['Upload','upload']}]},{id:'properties',label:j.lang.flash.propertiesTab,elements:[{type:'hbox',widths:['50%','50%'],children:[{id:'scale',type:'select',label:j.lang.flash.scale,'default':'',style:'width : 100%;',items:[[j.lang.common.notSet,''],[j.lang.flash.scaleAll,'showall'],[j.lang.flash.scaleNoBorder,'noborder'],[j.lang.flash.scaleFit,'exactfit']],setup:h,commit:i},{id:'allowScriptAccess',type:'select',label:j.lang.flash.access,'default':'',style:'width : 100%;',items:[[j.lang.common.notSet,''],[j.lang.flash.accessAlways,'always'],[j.lang.flash.accessSameDomain,'samedomain'],[j.lang.flash.accessNever,'never']],setup:h,commit:i}]},{type:'hbox',widths:['50%','50%'],children:[{id:'wmode',type:'select',label:j.lang.flash.windowMode,'default':'',style:'width : 100%;',items:[[j.lang.common.notSet,''],[j.lang.flash.windowModeWindow,'window'],[j.lang.flash.windowModeOpaque,'opaque'],[j.lang.flash.windowModeTransparent,'transparent']],setup:h,commit:i},{id:'quality',type:'select',label:j.lang.flash.quality,'default':'high',style:'width : 100%;',items:[[j.lang.common.notSet,''],[j.lang.flash.qualityBest,'best'],[j.lang.flash.qualityHigh,'high'],[j.lang.flash.qualityAutoHigh,'autohigh'],[j.lang.flash.qualityMedium,'medium'],[j.lang.flash.qualityAutoLow,'autolow'],[j.lang.flash.qualityLow,'low']],setup:h,commit:i}]},{type:'hbox',widths:['50%','50%'],children:[{id:'align',type:'select',label:j.lang.common.align,'default':'',style:'width : 100%;',items:[[j.lang.common.notSet,''],[j.lang.common.alignLeft,'left'],[j.lang.flash.alignAbsBottom,'absBottom'],[j.lang.flash.alignAbsMiddle,'absMiddle'],[j.lang.flash.alignBaseline,'baseline'],[j.lang.common.alignBottom,'bottom'],[j.lang.common.alignMiddle,'middle'],[j.lang.common.alignRight,'right'],[j.lang.flash.alignTextTop,'textTop'],[j.lang.common.alignTop,'top']],setup:h,commit:function(o,p,q,r,s){var t=this.getValue();
i.apply(this,arguments);t&&(s.align=t);}},{type:'html',html:'<div></div>'}]},{type:'fieldset',label:CKEDITOR.tools.htmlEncode(j.lang.flash.flashvars),children:[{type:'vbox',padding:0,children:[{type:'checkbox',id:'menu',label:j.lang.flash.chkMenu,'default':true,setup:h,commit:i},{type:'checkbox',id:'play',label:j.lang.flash.chkPlay,'default':true,setup:h,commit:i},{type:'checkbox',id:'loop',label:j.lang.flash.chkLoop,'default':true,setup:h,commit:i},{type:'checkbox',id:'allowFullScreen',label:j.lang.flash.chkFull,'default':true,setup:h,commit:i}]}]}]},{id:'advanced',label:j.lang.common.advancedTab,elements:[{type:'hbox',widths:['45%','55%'],children:[{type:'text',id:'id',label:j.lang.common.id,setup:h,commit:i},{type:'text',id:'title',label:j.lang.common.advisoryTitle,setup:h,commit:i}]},{type:'hbox',widths:['45%','55%'],children:[{type:'text',id:'bgcolor',label:j.lang.flash.bgcolor,setup:h,commit:i},{type:'text',id:'class',label:j.lang.common.cssClass,setup:h,commit:i}]},{type:'text',id:'style',validate:CKEDITOR.dialog.validate.inlineStyle(j.lang.common.invalidInlineStyle),label:j.lang.common.cssStyle,setup:h,commit:i}]}]};});})(); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/plugins/flash/dialogs/flash.js | flash.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function(){var a=CKEDITOR.tools.cssLength,b=function(e){var f=this.id;if(!e.info)e.info={};e.info[f]=this.getValue();};function c(e){var f=0,g=0;for(var h=0,i,j=e.$.rows.length;h<j;h++){i=e.$.rows[h],f=0;for(var k=0,l,m=i.cells.length;k<m;k++){l=i.cells[k];f+=l.colSpan;}f>g&&(g=f);}return g;};function d(e,f){var g=function(i){return new CKEDITOR.dom.element(i,e.document);},h=e.plugins.dialogadvtab;return{title:e.lang.table.title,minWidth:310,minHeight:CKEDITOR.env.ie?310:280,onLoad:function(){var i=this,j=i.getContentElement('advanced','advStyles');if(j)j.on('change',function(k){var l=this.getStyle('width',''),m=i.getContentElement('info','txtWidth');m&&m.setValue(l,true);var n=this.getStyle('height',''),o=i.getContentElement('info','txtHeight');o&&o.setValue(n,true);});},onShow:function(){var q=this;var i=e.getSelection(),j=i.getRanges(),k=null,l=q.getContentElement('info','txtRows'),m=q.getContentElement('info','txtCols'),n=q.getContentElement('info','txtWidth'),o=q.getContentElement('info','txtHeight');if(f=='tableProperties'){if(k=i.getSelectedElement())k=k.getAscendant('table',true);else if(j.length>0){if(CKEDITOR.env.webkit)j[0].shrink(CKEDITOR.NODE_ELEMENT);var p=j[0].getCommonAncestor(true);k=p.getAscendant('table',true);}q._.selectedElement=k;}if(k){q.setupContent(k);l&&l.disable();m&&m.disable();}else{l&&l.enable();m&&m.enable();}n&&n.onChange();o&&o.onChange();},onOk:function(){var i=e.getSelection(),j=this._.selectedElement&&i.createBookmarks(),k=this._.selectedElement||g('table'),l=this,m={};this.commitContent(m,k);if(m.info){var n=m.info;if(!this._.selectedElement){var o=k.append(g('tbody')),p=parseInt(n.txtRows,10)||0,q=parseInt(n.txtCols,10)||0;for(var r=0;r<p;r++){var s=o.append(g('tr'));for(var t=0;t<q;t++){var u=s.append(g('td'));if(!CKEDITOR.env.ie)u.append(g('br'));}}}var v=n.selHeaders;if(!k.$.tHead&&(v=='row'||v=='both')){var w=new CKEDITOR.dom.element(k.$.createTHead());o=k.getElementsByTag('tbody').getItem(0);var x=o.getElementsByTag('tr').getItem(0);for(r=0;r<x.getChildCount();r++){var y=x.getChild(r);if(y.type==CKEDITOR.NODE_ELEMENT&&!y.data('cke-bookmark')){y.renameNode('th');y.setAttribute('scope','col');}}w.append(x.remove());}if(k.$.tHead!==null&&!(v=='row'||v=='both')){w=new CKEDITOR.dom.element(k.$.tHead);o=k.getElementsByTag('tbody').getItem(0);var z=o.getFirst();while(w.getChildCount()>0){x=w.getFirst();for(r=0;r<x.getChildCount();r++){var A=x.getChild(r);if(A.type==CKEDITOR.NODE_ELEMENT){A.renameNode('td');A.removeAttribute('scope');
}}x.insertBefore(z);}w.remove();}if(!this.hasColumnHeaders&&(v=='col'||v=='both'))for(s=0;s<k.$.rows.length;s++){A=new CKEDITOR.dom.element(k.$.rows[s].cells[0]);A.renameNode('th');A.setAttribute('scope','row');}if(this.hasColumnHeaders&&!(v=='col'||v=='both'))for(r=0;r<k.$.rows.length;r++){s=new CKEDITOR.dom.element(k.$.rows[r]);if(s.getParent().getName()=='tbody'){A=new CKEDITOR.dom.element(s.$.cells[0]);A.renameNode('td');A.removeAttribute('scope');}}n.txtHeight?k.setStyle('height',n.txtHeight):k.removeStyle('height');n.txtWidth?k.setStyle('width',n.txtWidth):k.removeStyle('width');if(!k.getAttribute('style'))k.removeAttribute('style');}if(!this._.selectedElement){e.insertElement(k);setTimeout(function(){var B=new CKEDITOR.dom.element(k.$.rows[0].cells[0]),C=new CKEDITOR.dom.range(e.document);C.moveToPosition(B,CKEDITOR.POSITION_AFTER_START);C.select(1);},0);}else try{i.selectBookmarks(j);}catch(B){}},contents:[{id:'info',label:e.lang.table.title,elements:[{type:'hbox',widths:[null,null],styles:['vertical-align:top'],children:[{type:'vbox',padding:0,children:[{type:'text',id:'txtRows','default':3,label:e.lang.table.rows,required:true,controlStyle:'width:5em',validate:function(){var i=true,j=this.getValue();i=i&&CKEDITOR.dialog.validate.integer()(j)&&j>0;if(!i){alert(e.lang.table.invalidRows);this.select();}return i;},setup:function(i){this.setValue(i.$.rows.length);},commit:b},{type:'text',id:'txtCols','default':2,label:e.lang.table.columns,required:true,controlStyle:'width:5em',validate:function(){var i=true,j=this.getValue();i=i&&CKEDITOR.dialog.validate.integer()(j)&&j>0;if(!i){alert(e.lang.table.invalidCols);this.select();}return i;},setup:function(i){this.setValue(c(i));},commit:b},{type:'html',html:' '},{type:'select',id:'selHeaders','default':'',label:e.lang.table.headers,items:[[e.lang.table.headersNone,''],[e.lang.table.headersRow,'row'],[e.lang.table.headersColumn,'col'],[e.lang.table.headersBoth,'both']],setup:function(i){var j=this.getDialog();j.hasColumnHeaders=true;for(var k=0;k<i.$.rows.length;k++){var l=i.$.rows[k].cells[0];if(l&&l.nodeName.toLowerCase()!='th'){j.hasColumnHeaders=false;break;}}if(i.$.tHead!==null)this.setValue(j.hasColumnHeaders?'both':'row');else this.setValue(j.hasColumnHeaders?'col':'');},commit:b},{type:'text',id:'txtBorder','default':1,label:e.lang.table.border,controlStyle:'width:3em',validate:CKEDITOR.dialog.validate.number(e.lang.table.invalidBorder),setup:function(i){this.setValue(i.getAttribute('border')||'');
},commit:function(i,j){if(this.getValue())j.setAttribute('border',this.getValue());else j.removeAttribute('border');}},{id:'cmbAlign',type:'select','default':'',label:e.lang.common.align,items:[[e.lang.common.notSet,''],[e.lang.common.alignLeft,'left'],[e.lang.common.alignCenter,'center'],[e.lang.common.alignRight,'right']],setup:function(i){this.setValue(i.getAttribute('align')||'');},commit:function(i,j){if(this.getValue())j.setAttribute('align',this.getValue());else j.removeAttribute('align');}}]},{type:'vbox',padding:0,children:[{type:'hbox',widths:['5em'],children:[{type:'text',id:'txtWidth',controlStyle:'width:5em',label:e.lang.common.width,title:e.lang.common.cssLengthTooltip,'default':500,getValue:a,validate:CKEDITOR.dialog.validate.cssLength(e.lang.common.invalidCssLength.replace('%1',e.lang.common.width)),onChange:function(){var i=this.getDialog().getContentElement('advanced','advStyles');i&&i.updateStyle('width',this.getValue());},setup:function(i){var j=i.getStyle('width');j&&this.setValue(j);},commit:b}]},{type:'hbox',widths:['5em'],children:[{type:'text',id:'txtHeight',controlStyle:'width:5em',label:e.lang.common.height,title:e.lang.common.cssLengthTooltip,'default':'',getValue:a,validate:CKEDITOR.dialog.validate.cssLength(e.lang.common.invalidCssLength.replace('%1',e.lang.common.height)),onChange:function(){var i=this.getDialog().getContentElement('advanced','advStyles');i&&i.updateStyle('height',this.getValue());},setup:function(i){var j=i.getStyle('width');j&&this.setValue(j);},commit:b}]},{type:'html',html:' '},{type:'text',id:'txtCellSpace',controlStyle:'width:3em',label:e.lang.table.cellSpace,'default':1,validate:CKEDITOR.dialog.validate.number(e.lang.table.invalidCellSpacing),setup:function(i){this.setValue(i.getAttribute('cellSpacing')||'');},commit:function(i,j){if(this.getValue())j.setAttribute('cellSpacing',this.getValue());else j.removeAttribute('cellSpacing');}},{type:'text',id:'txtCellPad',controlStyle:'width:3em',label:e.lang.table.cellPad,'default':1,validate:CKEDITOR.dialog.validate.number(e.lang.table.invalidCellPadding),setup:function(i){this.setValue(i.getAttribute('cellPadding')||'');},commit:function(i,j){if(this.getValue())j.setAttribute('cellPadding',this.getValue());else j.removeAttribute('cellPadding');}}]}]},{type:'html',align:'right',html:''},{type:'vbox',padding:0,children:[{type:'text',id:'txtCaption',label:e.lang.table.caption,setup:function(i){var m=this;m.enable();var j=i.getElementsByTag('caption');if(j.count()>0){var k=j.getItem(0),l=k.getFirst(CKEDITOR.dom.walker.nodeType(CKEDITOR.NODE_ELEMENT));
if(l&&!l.equals(k.getBogus())){m.disable();m.setValue(k.getText());return;}k=CKEDITOR.tools.trim(k.getText());m.setValue(k);}},commit:function(i,j){if(!this.isEnabled())return;var k=this.getValue(),l=j.getElementsByTag('caption');if(k){if(l.count()>0){l=l.getItem(0);l.setHtml('');}else{l=new CKEDITOR.dom.element('caption',e.document);if(j.getChildCount())l.insertBefore(j.getFirst());else l.appendTo(j);}l.append(new CKEDITOR.dom.text(k,e.document));}else if(l.count()>0)for(var m=l.count()-1;m>=0;m--)l.getItem(m).remove();}},{type:'text',id:'txtSummary',label:e.lang.table.summary,setup:function(i){this.setValue(i.getAttribute('summary')||'');},commit:function(i,j){if(this.getValue())j.setAttribute('summary',this.getValue());else j.removeAttribute('summary');}}]}]},h&&h.createAdvancedTab(e)]};};CKEDITOR.dialog.add('table',function(e){return d(e,'table');});CKEDITOR.dialog.add('tableProperties',function(e){return d(e,'tableProperties');});})(); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/plugins/table/dialogs/table.js | table.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add('scaytcheck',function(a){var b=true,c,d=CKEDITOR.document,e=a.name,f=CKEDITOR.plugins.scayt.getUiTabs(a),g,h=[],i=0,j=['dic_create_'+e+',dic_restore_'+e,'dic_rename_'+e+',dic_delete_'+e],k=['mixedCase','mixedWithDigits','allCaps','ignoreDomainNames'];function l(){if(typeof document.forms['optionsbar_'+e]!='undefined')return document.forms['optionsbar_'+e].options;return[];};function m(){if(typeof document.forms['languagesbar_'+e]!='undefined')return document.forms['languagesbar_'+e].scayt_lang;return[];};function n(z,A){if(!z)return;var B=z.length;if(B==undefined){z.checked=z.value==A.toString();return;}for(var C=0;C<B;C++){z[C].checked=false;if(z[C].value==A.toString())z[C].checked=true;}};var o=a.lang.scayt,p=[{id:'options',label:o.optionsTab,elements:[{type:'html',id:'options',html:'<form name="optionsbar_'+e+'"><div class="inner_options">'+'\t<div class="messagebox"></div>'+'\t<div style="display:none;">'+'\t\t<input type="checkbox" name="options" id="allCaps_'+e+'" />'+'\t\t<label for="allCaps" id="label_allCaps_'+e+'"></label>'+'\t</div>'+'\t<div style="display:none;">'+'\t\t<input name="options" type="checkbox" id="ignoreDomainNames_'+e+'" />'+'\t\t<label for="ignoreDomainNames" id="label_ignoreDomainNames_'+e+'"></label>'+'\t</div>'+'\t<div style="display:none;">'+'\t<input name="options" type="checkbox" id="mixedCase_'+e+'" />'+'\t\t<label for="mixedCase" id="label_mixedCase_'+e+'"></label>'+'\t</div>'+'\t<div style="display:none;">'+'\t\t<input name="options" type="checkbox" id="mixedWithDigits_'+e+'" />'+'\t\t<label for="mixedWithDigits" id="label_mixedWithDigits_'+e+'"></label>'+'\t</div>'+'</div></form>'}]},{id:'langs',label:o.languagesTab,elements:[{type:'html',id:'langs',html:'<form name="languagesbar_'+e+'"><div class="inner_langs">'+'\t<div class="messagebox"></div>\t'+' <div style="float:left;width:45%;margin-left:5px;" id="scayt_lcol_'+e+'" ></div>'+' <div style="float:left;width:45%;margin-left:15px;" id="scayt_rcol_'+e+'"></div>'+'</div></form>'}]},{id:'dictionaries',label:o.dictionariesTab,elements:[{type:'html',style:'',id:'dictionaries',html:'<form name="dictionarybar_'+e+'"><div class="inner_dictionary" style="text-align:left; white-space:normal; width:320px; overflow: hidden;">'+'\t<div style="margin:5px auto; width:80%;white-space:normal; overflow:hidden;" id="dic_message_'+e+'"> </div>'+'\t<div style="margin:5px auto; width:80%;white-space:normal;"> '+' <span class="cke_dialog_ui_labeled_label" >Dictionary name</span><br>'+'\t\t<span class="cke_dialog_ui_labeled_content" >'+'\t\t\t<div class="cke_dialog_ui_input_text">'+'\t\t\t\t<input id="dic_name_'+e+'" type="text" class="cke_dialog_ui_input_text"/>'+'\t\t</div></span></div>'+'\t\t<div style="margin:5px auto; width:80%;white-space:normal;">'+'\t\t\t<a style="display:none;" class="cke_dialog_ui_button" href="javascript:void(0)" id="dic_create_'+e+'">'+'\t\t\t\t</a>'+'\t\t\t<a style="display:none;" class="cke_dialog_ui_button" href="javascript:void(0)" id="dic_delete_'+e+'">'+'\t\t\t\t</a>'+'\t\t\t<a style="display:none;" class="cke_dialog_ui_button" href="javascript:void(0)" id="dic_rename_'+e+'">'+'\t\t\t\t</a>'+'\t\t\t<a style="display:none;" class="cke_dialog_ui_button" href="javascript:void(0)" id="dic_restore_'+e+'">'+'\t\t\t\t</a>'+'\t\t</div>'+'\t<div style="margin:5px auto; width:95%;white-space:normal;" id="dic_info_'+e+'"></div>'+'</div></form>'}]},{id:'about',label:o.aboutTab,elements:[{type:'html',id:'about',style:'margin: 5px 5px;',html:'<div id="scayt_about_'+e+'"></div>'}]}],q={title:o.title,minWidth:360,minHeight:220,onShow:function(){var z=this;
z.data=a.fire('scaytDialog',{});z.options=z.data.scayt_control.option();z.chosed_lang=z.sLang=z.data.scayt_control.sLang;if(!z.data||!z.data.scayt||!z.data.scayt_control){alert('Error loading application service');z.hide();return;}var A=0;if(b)z.data.scayt.getCaption(a.langCode||'en',function(B){if(A++>0)return;c=B;s.apply(z);t.apply(z);b=false;});else t.apply(z);z.selectPage(z.data.tab);},onOk:function(){var z=this.data.scayt_control;z.option(this.options);var A=this.chosed_lang;z.setLang(A);z.refresh();},onCancel:function(){var z=l();for(var A in z)z[A].checked=false;n(m(),'');},contents:h},r=CKEDITOR.plugins.scayt.getScayt(a);for(g=0;g<f.length;g++){if(f[g]==1)h[h.length]=p[g];}if(f[2]==1)i=1;var s=function(){var z=this,A=z.data.scayt.getLangList(),B=['dic_create','dic_delete','dic_rename','dic_restore'],C=[],D=[],E=k,F;if(i){for(F=0;F<B.length;F++){C[F]=B[F]+'_'+e;d.getById(C[F]).setHtml('<span class="cke_dialog_ui_button">'+c['button_'+B[F]]+'</span>');}d.getById('dic_info_'+e).setHtml(c.dic_info);}if(f[0]==1)for(F in E){var G='label_'+E[F],H=G+'_'+e,I=d.getById(H);if('undefined'!=typeof I&&'undefined'!=typeof c[G]&&'undefined'!=typeof z.options[E[F]]){I.setHtml(c[G]);var J=I.getParent();J.$.style.display='block';}}var K='<p><img src="'+window.scayt.getAboutInfo().logoURL+'" /></p>'+'<p>'+c.version+window.scayt.getAboutInfo().version.toString()+'</p>'+'<p>'+c.about_throwt_copy+'</p>';d.getById('scayt_about_'+e).setHtml(K);var L=function(U,V){var W=d.createElement('label');W.setAttribute('for','cke_option'+U);W.setHtml(V[U]);if(z.sLang==U)z.chosed_lang=U;var X=d.createElement('div'),Y=CKEDITOR.dom.element.createFromHtml('<input id="cke_option'+U+'" type="radio" '+(z.sLang==U?'checked="checked"':'')+' value="'+U+'" name="scayt_lang" />');Y.on('click',function(){this.$.checked=true;z.chosed_lang=U;});X.append(Y);X.append(W);return{lang:V[U],code:U,radio:X};};if(f[1]==1){for(F in A.rtl)D[D.length]=L(F,A.ltr);for(F in A.ltr)D[D.length]=L(F,A.ltr);D.sort(function(U,V){return V.lang>U.lang?-1:1;});var M=d.getById('scayt_lcol_'+e),N=d.getById('scayt_rcol_'+e);for(F=0;F<D.length;F++){var O=F<D.length/2?M:N;O.append(D[F].radio);}}var P={};P.dic_create=function(U,V,W){var X=W[0]+','+W[1],Y=c.err_dic_create,Z=c.succ_dic_create;window.scayt.createUserDictionary(V,function(aa){x(X);w(W[1]);Z=Z.replace('%s',aa.dname);v(Z);},function(aa){Y=Y.replace('%s',aa.dname);u(Y+'( '+(aa.message||'')+')');});};P.dic_rename=function(U,V){var W=c.err_dic_rename||'',X=c.succ_dic_rename||'';
window.scayt.renameUserDictionary(V,function(Y){X=X.replace('%s',Y.dname);y(V);v(X);},function(Y){W=W.replace('%s',Y.dname);y(V);u(W+'( '+(Y.message||'')+' )');});};P.dic_delete=function(U,V,W){var X=W[0]+','+W[1],Y=c.err_dic_delete,Z=c.succ_dic_delete;window.scayt.deleteUserDictionary(function(aa){Z=Z.replace('%s',aa.dname);x(X);w(W[0]);y('');v(Z);},function(aa){Y=Y.replace('%s',aa.dname);u(Y);});};P.dic_restore=z.dic_restore||(function(U,V,W){var X=W[0]+','+W[1],Y=c.err_dic_restore,Z=c.succ_dic_restore;window.scayt.restoreUserDictionary(V,function(aa){Z=Z.replace('%s',aa.dname);x(X);w(W[1]);v(Z);},function(aa){Y=Y.replace('%s',aa.dname);u(Y);});});function Q(U){var V=d.getById('dic_name_'+e).getValue();if(!V){u(' Dictionary name should not be empty. ');return false;}try{var W=U.data.getTarget().getParent(),X=/(dic_\w+)_[\w\d]+/.exec(W.getId())[1];P[X].apply(null,[W,V,j]);}catch(Y){u(' Dictionary error. ');}return true;};var R=(j[0]+','+j[1]).split(','),S;for(F=0,S=R.length;F<S;F+=1){var T=d.getById(R[F]);if(T)T.on('click',Q,this);}},t=function(){var z=this;if(f[0]==1){var A=l();for(var B=0,C=A.length;B<C;B++){var D=A[B].id,E=d.getById(D);if(E){A[B].checked=false;if(z.options[D.split('_')[0]]==1)A[B].checked=true;if(b)E.on('click',function(){z.options[this.getId().split('_')[0]]=this.$.checked?1:0;});}}}if(f[1]==1){var F=d.getById('cke_option'+z.sLang);n(F.$,z.sLang);}if(i){window.scayt.getNameUserDictionary(function(G){var H=G.dname;x(j[0]+','+j[1]);if(H){d.getById('dic_name_'+e).setValue(H);w(j[1]);}else w(j[0]);},function(){d.getById('dic_name_'+e).setValue('');});v('');}};function u(z){d.getById('dic_message_'+e).setHtml('<span style="color:red;">'+z+'</span>');};function v(z){d.getById('dic_message_'+e).setHtml('<span style="color:blue;">'+z+'</span>');};function w(z){z=String(z);var A=z.split(',');for(var B=0,C=A.length;B<C;B+=1)d.getById(A[B]).$.style.display='inline';};function x(z){z=String(z);var A=z.split(',');for(var B=0,C=A.length;B<C;B+=1)d.getById(A[B]).$.style.display='none';};function y(z){d.getById('dic_name_'+e).$.value=z;};return q;}); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/plugins/scayt/dialogs/options.js | options.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function(){var a=/\[\[[^\]]+\]\]/g;CKEDITOR.plugins.add('placeholder',{requires:['dialog'],lang:['en','he'],init:function(b){var c=b.lang.placeholder;b.addCommand('createplaceholder',new CKEDITOR.dialogCommand('createplaceholder'));b.addCommand('editplaceholder',new CKEDITOR.dialogCommand('editplaceholder'));b.ui.addButton('CreatePlaceholder',{label:c.toolbar,command:'createplaceholder',icon:this.path+'placeholder.gif'});if(b.addMenuItems){b.addMenuGroup('placeholder',20);b.addMenuItems({editplaceholder:{label:c.edit,command:'editplaceholder',group:'placeholder',order:1,icon:this.path+'placeholder.gif'}});if(b.contextMenu)b.contextMenu.addListener(function(d,e){if(!d||!d.data('cke-placeholder'))return null;return{editplaceholder:CKEDITOR.TRISTATE_OFF};});}b.on('doubleclick',function(d){if(CKEDITOR.plugins.placeholder.getSelectedPlaceHoder(b))d.data.dialog='editplaceholder';});b.addCss('.cke_placeholder{background-color: #ffff00;'+(CKEDITOR.env.gecko?'cursor: default;':'')+'}');b.on('contentDom',function(){b.document.getBody().on('resizestart',function(d){if(b.getSelection().getSelectedElement().data('cke-placeholder'))d.data.preventDefault();});});CKEDITOR.dialog.add('createplaceholder',this.path+'dialogs/placeholder.js');CKEDITOR.dialog.add('editplaceholder',this.path+'dialogs/placeholder.js');},afterInit:function(b){var c=b.dataProcessor,d=c&&c.dataFilter,e=c&&c.htmlFilter;if(d)d.addRules({text:function(f){return f.replace(a,function(g){return CKEDITOR.plugins.placeholder.createPlaceholder(b,null,g,1);});}});if(e)e.addRules({elements:{span:function(f){if(f.attributes&&f.attributes['data-cke-placeholder'])delete f.name;}}});}});})();CKEDITOR.plugins.placeholder={createPlaceholder:function(a,b,c,d){var e=new CKEDITOR.dom.element('span',a.document);e.setAttributes({contentEditable:'false','data-cke-placeholder':1,'class':'cke_placeholder'});c&&e.setText(c);if(d)return e.getOuterHtml();if(b){if(CKEDITOR.env.ie){e.insertAfter(b);setTimeout(function(){b.remove();e.focus();},10);}else e.replace(b);}else a.insertElement(e);return null;},getSelectedPlaceHoder:function(a){var b=a.getSelection().getRanges()[0];b.shrink(CKEDITOR.SHRINK_TEXT);var c=b.startContainer;while(c&&!(c.type==CKEDITOR.NODE_ELEMENT&&c.data('cke-placeholder')))c=c.getParent();return c;}}; | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/plugins/placeholder/plugin.js | plugin.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add('cellProperties',function(a){var b=a.lang.table,c=b.cell,d=a.lang.common,e=CKEDITOR.dialog.validate,f=/^(\d+(?:\.\d+)?)(px|%)$/,g=/^(\d+(?:\.\d+)?)px$/,h=CKEDITOR.tools.bind,i={type:'html',html:' '},j=a.lang.dir=='rtl';function k(l,m){var n=function(){var r=this;p(r);m(r,r._.parentDialog);r._.parentDialog.changeFocus(true);},o=function(){p(this);this._.parentDialog.changeFocus();},p=function(r){r.removeListener('ok',n);r.removeListener('cancel',o);},q=function(r){r.on('ok',n);r.on('cancel',o);};a.execCommand(l);if(a._.storedDialogs.colordialog)q(a._.storedDialogs.colordialog);else CKEDITOR.on('dialogDefinition',function(r){if(r.data.name!=l)return;var s=r.data.definition;r.removeListener();s.onLoad=CKEDITOR.tools.override(s.onLoad,function(t){return function(){q(this);s.onLoad=t;if(typeof t=='function')t.call(this);};});});};return{title:c.title,minWidth:CKEDITOR.env.ie&&CKEDITOR.env.quirks?450:410,minHeight:CKEDITOR.env.ie&&(CKEDITOR.env.ie7Compat||CKEDITOR.env.quirks)?230:200,contents:[{id:'info',label:c.title,accessKey:'I',elements:[{type:'hbox',widths:['40%','5%','40%'],children:[{type:'vbox',padding:0,children:[{type:'hbox',widths:['70%','30%'],children:[{type:'text',id:'width',width:'100px',label:d.width,validate:e.number(c.invalidWidth),onLoad:function(){var l=this.getDialog().getContentElement('info','widthType'),m=l.getElement(),n=this.getInputElement(),o=n.getAttribute('aria-labelledby');n.setAttribute('aria-labelledby',[o,m.$.id].join(' '));},setup:function(l){var m=parseInt(l.getAttribute('width'),10),n=parseInt(l.getStyle('width'),10);!isNaN(m)&&this.setValue(m);!isNaN(n)&&this.setValue(n);},commit:function(l){var m=parseInt(this.getValue(),10),n=this.getDialog().getValueOf('info','widthType');if(!isNaN(m))l.setStyle('width',m+n);else l.removeStyle('width');l.removeAttribute('width');},'default':''},{type:'select',id:'widthType',label:a.lang.table.widthUnit,labelStyle:'visibility:hidden','default':'px',items:[[b.widthPx,'px'],[b.widthPc,'%']],setup:function(l){var m=f.exec(l.getStyle('width')||l.getAttribute('width'));if(m)this.setValue(m[2]);}}]},{type:'hbox',widths:['70%','30%'],children:[{type:'text',id:'height',label:d.height,width:'100px','default':'',validate:e.number(c.invalidHeight),onLoad:function(){var l=this.getDialog().getContentElement('info','htmlHeightType'),m=l.getElement(),n=this.getInputElement(),o=n.getAttribute('aria-labelledby');n.setAttribute('aria-labelledby',[o,m.$.id].join(' '));},setup:function(l){var m=parseInt(l.getAttribute('height'),10),n=parseInt(l.getStyle('height'),10);
!isNaN(m)&&this.setValue(m);!isNaN(n)&&this.setValue(n);},commit:function(l){var m=parseInt(this.getValue(),10);if(!isNaN(m))l.setStyle('height',CKEDITOR.tools.cssLength(m));else l.removeStyle('height');l.removeAttribute('height');}},{id:'htmlHeightType',type:'html',html:'<br />'+b.widthPx}]},i,{type:'select',id:'wordWrap',label:c.wordWrap,'default':'yes',items:[[c.yes,'yes'],[c.no,'no']],setup:function(l){var m=l.getAttribute('noWrap'),n=l.getStyle('white-space');if(n=='nowrap'||m)this.setValue('no');},commit:function(l){if(this.getValue()=='no')l.setStyle('white-space','nowrap');else l.removeStyle('white-space');l.removeAttribute('noWrap');}},i,{type:'select',id:'hAlign',label:c.hAlign,'default':'',items:[[d.notSet,''],[d.alignLeft,'left'],[d.alignCenter,'center'],[d.alignRight,'right']],setup:function(l){var m=l.getAttribute('align'),n=l.getStyle('text-align');this.setValue(n||m||'');},commit:function(l){var m=this.getValue();if(m)l.setStyle('text-align',m);else l.removeStyle('text-align');l.removeAttribute('align');}},{type:'select',id:'vAlign',label:c.vAlign,'default':'',items:[[d.notSet,''],[d.alignTop,'top'],[d.alignMiddle,'middle'],[d.alignBottom,'bottom'],[c.alignBaseline,'baseline']],setup:function(l){var m=l.getAttribute('vAlign'),n=l.getStyle('vertical-align');switch(n){case 'top':case 'middle':case 'bottom':case 'baseline':break;default:n='';}this.setValue(n||m||'');},commit:function(l){var m=this.getValue();if(m)l.setStyle('vertical-align',m);else l.removeStyle('vertical-align');l.removeAttribute('vAlign');}}]},i,{type:'vbox',padding:0,children:[{type:'select',id:'cellType',label:c.cellType,'default':'td',items:[[c.data,'td'],[c.header,'th']],setup:function(l){this.setValue(l.getName());},commit:function(l){l.renameNode(this.getValue());}},i,{type:'text',id:'rowSpan',label:c.rowSpan,'default':'',validate:e.integer(c.invalidRowSpan),setup:function(l){var m=parseInt(l.getAttribute('rowSpan'),10);if(m&&m!=1)this.setValue(m);},commit:function(l){var m=parseInt(this.getValue(),10);if(m&&m!=1)l.setAttribute('rowSpan',this.getValue());else l.removeAttribute('rowSpan');}},{type:'text',id:'colSpan',label:c.colSpan,'default':'',validate:e.integer(c.invalidColSpan),setup:function(l){var m=parseInt(l.getAttribute('colSpan'),10);if(m&&m!=1)this.setValue(m);},commit:function(l){var m=parseInt(this.getValue(),10);if(m&&m!=1)l.setAttribute('colSpan',this.getValue());else l.removeAttribute('colSpan');}},i,{type:'hbox',padding:0,widths:['60%','40%'],children:[{type:'text',id:'bgColor',label:c.bgColor,'default':'',setup:function(l){var m=l.getAttribute('bgColor'),n=l.getStyle('background-color');
this.setValue(n||m);},commit:function(l){var m=this.getValue();if(m)l.setStyle('background-color',this.getValue());else l.removeStyle('background-color');l.removeAttribute('bgColor');}},{type:'button',id:'bgColorChoose','class':'colorChooser',label:c.chooseColor,onLoad:function(){this.getElement().getParent().setStyle('vertical-align','bottom');},onClick:function(){var l=this;k('colordialog',function(m){l.getDialog().getContentElement('info','bgColor').setValue(m.getContentElement('picker','selectedColor').getValue());});}}]},i,{type:'hbox',padding:0,widths:['60%','40%'],children:[{type:'text',id:'borderColor',label:c.borderColor,'default':'',setup:function(l){var m=l.getAttribute('borderColor'),n=l.getStyle('border-color');this.setValue(n||m);},commit:function(l){var m=this.getValue();if(m)l.setStyle('border-color',this.getValue());else l.removeStyle('border-color');l.removeAttribute('borderColor');}},{type:'button',id:'borderColorChoose','class':'colorChooser',label:c.chooseColor,style:(j?'margin-right':'margin-left')+': 10px',onLoad:function(){this.getElement().getParent().setStyle('vertical-align','bottom');},onClick:function(){var l=this;k('colordialog',function(m){l.getDialog().getContentElement('info','borderColor').setValue(m.getContentElement('picker','selectedColor').getValue());});}}]}]}]}]}],onShow:function(){var l=this;l.cells=CKEDITOR.plugins.tabletools.getSelectedCells(l._.editor.getSelection());l.setupContent(l.cells[0]);},onOk:function(){var r=this;var l=r._.editor.getSelection(),m=l.createBookmarks(),n=r.cells;for(var o=0;o<n.length;o++)r.commitContent(n[o]);l.selectBookmarks(m);var p=l.getStartElement(),q=new CKEDITOR.dom.elementPath(p);r._.editor._.selectionPreviousPath=q;r._.editor.fire('selectionChange',{selection:l,path:q,element:p});}};}); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/plugins/tabletools/dialogs/tableCell.js | tableCell.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function(){function a(e,f){var g;try{g=e.getSelection().getRanges()[0];}catch(h){return null;}g.shrink(CKEDITOR.SHRINK_TEXT);return g.getCommonAncestor().getAscendant(f,1);};var b=function(e){return e.type==CKEDITOR.NODE_ELEMENT&&e.is('li');},c={a:'lower-alpha',A:'upper-alpha',i:'lower-roman',I:'upper-roman',1:'decimal',disc:'disc',circle:'circle',square:'square'};function d(e,f){var g=e.lang.list;if(f=='bulletedListStyle')return{title:g.bulletedTitle,minWidth:300,minHeight:50,contents:[{id:'info',accessKey:'I',elements:[{type:'select',label:g.type,id:'type',align:'center',style:'width:150px',items:[[g.notset,''],[g.circle,'circle'],[g.disc,'disc'],[g.square,'square']],setup:function(i){var j=i.getStyle('list-style-type')||c[i.getAttribute('type')]||i.getAttribute('type')||'';this.setValue(j);},commit:function(i){var j=this.getValue();if(j)i.setStyle('list-style-type',j);else i.removeStyle('list-style-type');}}]}],onShow:function(){var i=this.getParentEditor(),j=a(i,'ul');j&&this.setupContent(j);},onOk:function(){var i=this.getParentEditor(),j=a(i,'ul');j&&this.commitContent(j);}};else if(f=='numberedListStyle'){var h=[[g.notset,''],[g.lowerRoman,'lower-roman'],[g.upperRoman,'upper-roman'],[g.lowerAlpha,'lower-alpha'],[g.upperAlpha,'upper-alpha'],[g.decimal,'decimal']];if(!CKEDITOR.env.ie||CKEDITOR.env.version>7)h.concat([[g.armenian,'armenian'],[g.decimalLeadingZero,'decimal-leading-zero'],[g.georgian,'georgian'],[g.lowerGreek,'lower-greek']]);return{title:g.numberedTitle,minWidth:300,minHeight:50,contents:[{id:'info',accessKey:'I',elements:[{type:'hbox',widths:['25%','75%'],children:[{label:g.start,type:'text',id:'start',validate:CKEDITOR.dialog.validate.integer(g.validateStartNumber),setup:function(i){var j=i.getFirst(b).getAttribute('value')||i.getAttribute('start')||1;j&&this.setValue(j);},commit:function(i){var j=i.getFirst(b),k=j.getAttribute('value')||i.getAttribute('start')||1;i.getFirst(b).removeAttribute('value');var l=parseInt(this.getValue(),10);if(isNaN(l))i.removeAttribute('start');else i.setAttribute('start',l);var m=j,n=k,o=isNaN(l)?1:l;while((m=m.getNext(b))&&n++){if(m.getAttribute('value')==n)m.setAttribute('value',o+n-k);}}},{type:'select',label:g.type,id:'type',style:'width: 100%;',items:h,setup:function(i){var j=i.getStyle('list-style-type')||c[i.getAttribute('type')]||i.getAttribute('type')||'';this.setValue(j);},commit:function(i){var j=this.getValue();if(j)i.setStyle('list-style-type',j);else i.removeStyle('list-style-type');}}]}]}],onShow:function(){var i=this.getParentEditor(),j=a(i,'ol');
j&&this.setupContent(j);},onOk:function(){var i=this.getParentEditor(),j=a(i,'ol');j&&this.commitContent(j);}};}};CKEDITOR.dialog.add('numberedListStyle',function(e){return d(e,'numberedListStyle');});CKEDITOR.dialog.add('bulletedListStyle',function(e){return d(e,'bulletedListStyle');});})(); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/plugins/liststyle/dialogs/liststyle.js | liststyle.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add('checkspell',function(a){var b=CKEDITOR.tools.getNextNumber(),c='cke_frame_'+b,d='cke_data_'+b,e='cke_error_'+b,f,g=document.location.protocol||'http:',h=a.lang.spellCheck.notAvailable,i='<textarea style="display: none" id="'+d+'"'+' rows="10"'+' cols="40">'+' </textarea><div'+' id="'+e+'"'+' style="display:none;color:red;font-size:16px;font-weight:bold;padding-top:160px;text-align:center;z-index:11;">'+'</div><iframe'+' src=""'+' style="width:100%;background-color:#f1f1e3;"'+' frameborder="0"'+' name="'+c+'"'+' id="'+c+'"'+' allowtransparency="1">'+'</iframe>',j=a.config.wsc_customLoaderScript||g+'//loader.webspellchecker.net/sproxy_fck/sproxy.php'+'?plugin=fck2'+'&customerid='+a.config.wsc_customerId+'&cmd=script&doc=wsc&schema=22';if(a.config.wsc_customLoaderScript)h+='<p style="color:#000;font-size:11px;font-weight: normal;text-align:center;padding-top:10px">'+a.lang.spellCheck.errorLoading.replace(/%s/g,a.config.wsc_customLoaderScript)+'</p>';function k(m,n){var o=0;return function(){if(typeof window.doSpell=='function'){if(typeof f!='undefined')window.clearInterval(f);l(m);}else if(o++==180)window._cancelOnError(n);};};window._cancelOnError=function(m){if(typeof window.WSC_Error=='undefined'){CKEDITOR.document.getById(c).setStyle('display','none');var n=CKEDITOR.document.getById(e);n.setStyle('display','block');n.setHtml(m||a.lang.spellCheck.notAvailable);}};function l(m){var n=new window._SP_FCK_LangCompare(),o=CKEDITOR.getUrl(a.plugins.wsc.path+'dialogs/'),p=o+'tmpFrameset.html';window.gFCKPluginName='wsc';n.setDefaulLangCode(a.config.defaultLanguage);window.doSpell({ctrl:d,lang:a.config.wsc_lang||n.getSPLangCode(a.langCode),intLang:a.config.wsc_uiLang||n.getSPLangCode(a.langCode),winType:c,onCancel:function(){m.hide();},onFinish:function(q){a.focus();m.getParentEditor().setData(q.value);m.hide();},staticFrame:p,framesetPath:p,iframePath:o+'ciframe.html',schemaURI:o+'wsc.css',userDictionaryName:a.config.wsc_userDictionaryName,customDictionaryName:a.config.wsc_customDictionaryIds&&a.config.wsc_customDictionaryIds.split(','),domainName:a.config.wsc_domainName});CKEDITOR.document.getById(e).setStyle('display','none');CKEDITOR.document.getById(c).setStyle('display','block');};return{title:a.config.wsc_dialogTitle||a.lang.spellCheck.title,minWidth:485,minHeight:380,buttons:[CKEDITOR.dialog.cancelButton],onShow:function(){var m=this.getContentElement('general','content').getElement();m.setHtml(i);m.getChild(2).setStyle('height',this._.contentSize.height+'px');
if(typeof window.doSpell!='function')CKEDITOR.document.getHead().append(CKEDITOR.document.createElement('script',{attributes:{type:'text/javascript',src:j}}));var n=a.getData();CKEDITOR.document.getById(d).setValue(n);f=window.setInterval(k(this,h),250);},onHide:function(){window.ooo=undefined;window.int_framsetLoaded=undefined;window.framesetLoaded=undefined;window.is_window_opened=false;},contents:[{id:'general',label:a.config.wsc_dialogTitle||a.lang.spellCheck.title,padding:0,elements:[{type:'html',id:'content',html:''}]}]};});CKEDITOR.dialog.on('resize',function(a){var b=a.data,c=b.dialog;if(c._.name=='checkspell'){var d=c.getContentElement('general','content').getElement(),e=d&&d.getChild(2);e&&e.setSize('height',b.height);e&&e.setSize('width',b.width);}}); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/plugins/wsc/dialogs/wsc.js | wsc.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function(){var a=CKEDITOR.htmlParser.fragment.prototype,b=CKEDITOR.htmlParser.element.prototype;a.onlyChild=b.onlyChild=function(){var u=this.children,v=u.length,w=v==1&&u[0];return w||null;};b.removeAnyChildWithName=function(u){var v=this.children,w=[],x;for(var y=0;y<v.length;y++){x=v[y];if(!x.name)continue;if(x.name==u){w.push(x);v.splice(y--,1);}w=w.concat(x.removeAnyChildWithName(u));}return w;};b.getAncestor=function(u){var v=this.parent;while(v&&!(v.name&&v.name.match(u)))v=v.parent;return v;};a.firstChild=b.firstChild=function(u){var v;for(var w=0;w<this.children.length;w++){v=this.children[w];if(u(v))return v;else if(v.name){v=v.firstChild(u);if(v)return v;}}return null;};b.addStyle=function(u,v,w){var A=this;var x,y='';if(typeof v=='string')y+=u+':'+v+';';else{if(typeof u=='object')for(var z in u){if(u.hasOwnProperty(z))y+=z+':'+u[z]+';';}else y+=u;w=v;}if(!A.attributes)A.attributes={};x=A.attributes.style||'';x=(w?[y,x]:[x,y]).join(';');A.attributes.style=x.replace(/^;|;(?=;)/,'');};CKEDITOR.dtd.parentOf=function(u){var v={};for(var w in this){if(w.indexOf('$')==-1&&this[w][u])v[w]=1;}return v;};function c(u){var v=u.children,w,x,y=u.children.length,z,A,B=/list-style-type:(.*?)(?:;|$)/,C=CKEDITOR.plugins.pastefromword.filters.stylesFilter;x=u.attributes;if(B.exec(x.style))return;for(var D=0;D<y;D++){w=v[D];if(w.attributes.value&&Number(w.attributes.value)==D+1)delete w.attributes.value;z=B.exec(w.attributes.style);if(z)if(z[1]==A||!A)A=z[1];else{A=null;break;}}if(A){for(D=0;D<y;D++){x=v[D].attributes;x.style&&(x.style=C([['list-style-type']])(x.style)||'');}u.addStyle('list-style-type',A);}};var d=/^([.\d]*)+(em|ex|px|gd|rem|vw|vh|vm|ch|mm|cm|in|pt|pc|deg|rad|ms|s|hz|khz){1}?/i,e=/^(?:\b0[^\s]*\s*){1,4}$/,f='^m{0,4}(cm|cd|d?c{0,3})(xc|xl|l?x{0,3})(ix|iv|v?i{0,3})$',g=new RegExp(f),h=new RegExp(f.toUpperCase()),i={decimal:/\d+/,'lower-roman':g,'upper-roman':h,'lower-alpha':/^[a-z]+$/,'upper-alpha':/^[A-Z]+$/},j={disc:/[l\u00B7\u2002]/,circle:/[\u006F\u00D8]/,square:/[\u006E\u25C6]/},k={ol:i,ul:j},l=[[1000,'M'],[900,'CM'],[500,'D'],[400,'CD'],[100,'C'],[90,'XC'],[50,'L'],[40,'XL'],[10,'X'],[9,'IX'],[5,'V'],[4,'IV'],[1,'I']],m='ABCDEFGHIJKLMNOPQRSTUVWXYZ';function n(u){u=u.toUpperCase();var v=l.length,w=0;for(var x=0;x<v;++x)for(var y=l[x],z=y[1].length;u.substr(0,z)==y[1];u=u.substr(z))w+=y[0];return w;};function o(u){u=u.toUpperCase();var v=m.length,w=1;for(var x=1;u.length>0;x*=v){w+=m.indexOf(u.charAt(u.length-1))*x;u=u.substr(0,u.length-1);}return w;
};var p=0,q=null,r,s=CKEDITOR.plugins.pastefromword={utils:{createListBulletMarker:function(u,v){var w=new CKEDITOR.htmlParser.element('cke:listbullet');w.attributes={'cke:listsymbol':u[0]};w.add(new CKEDITOR.htmlParser.text(v));return w;},isListBulletIndicator:function(u){var v=u.attributes&&u.attributes.style;if(/mso-list\s*:\s*Ignore/i.test(v))return true;},isContainingOnlySpaces:function(u){var v;return(v=u.onlyChild())&&/^(:?\s| )+$/.test(v.value);},resolveList:function(u){var v=u.attributes,w;if((w=u.removeAnyChildWithName('cke:listbullet'))&&w.length&&(w=w[0])){u.name='cke:li';if(v.style)v.style=s.filters.stylesFilter([['text-indent'],['line-height'],[/^margin(:?-left)?$/,null,function(x){var y=x.split(' ');x=CKEDITOR.tools.convertToPx(y[3]||y[1]||y[0]);if(!p&&q!==null&&x>q)p=x-q;q=x;v['cke:indent']=p&&Math.ceil(x/p)+1||1;}],[/^mso-list$/,null,function(x){x=x.split(' ');var y=Number(x[0].match(/\d+/)),z=Number(x[1].match(/\d+/));if(z==1){y!==r&&(v['cke:reset']=1);r=y;}v['cke:indent']=z;}]])(v.style,u)||'';if(!v['cke:indent']){q=0;v['cke:indent']=1;}CKEDITOR.tools.extend(v,w.attributes);return true;}else r=q=p=null;return false;},getStyleComponents:(function(){var u=CKEDITOR.dom.element.createFromHtml('<div style="position:absolute;left:-9999px;top:-9999px;"></div>',CKEDITOR.document);CKEDITOR.document.getBody().append(u);return function(v,w,x){u.setStyle(v,w);var y={},z=x.length;for(var A=0;A<z;A++)y[x[A]]=u.getStyle(x[A]);return y;};})(),listDtdParents:CKEDITOR.dtd.parentOf('ol')},filters:{flattenList:function(u,v){v=typeof v=='number'?v:1;var w=u.attributes,x;switch(w.type){case 'a':x='lower-alpha';break;case '1':x='decimal';break;}var y=u.children,z;for(var A=0;A<y.length;A++){z=y[A];if(z.name in CKEDITOR.dtd.$listItem){var B=z.attributes,C=z.children,D=C.length,E=C[D-1];if(E.name in CKEDITOR.dtd.$list){u.add(E,A+1);if(!--C.length)y.splice(A--,1);}z.name='cke:li';w.start&&!A&&(B.value=w.start);s.filters.stylesFilter([['tab-stops',null,function(H){var I=H.split(' ')[1].match(d);I&&(q=CKEDITOR.tools.convertToPx(I[0]));}],v==1?['mso-list',null,function(H){H=H.split(' ');var I=Number(H[0].match(/\d+/));I!==r&&(B['cke:reset']=1);r=I;}]:null])(B.style);B['cke:indent']=v;B['cke:listtype']=u.name;B['cke:list-style-type']=x;}else if(z.name in CKEDITOR.dtd.$list){arguments.callee.apply(this,[z,v+1]);y=y.slice(0,A).concat(z.children).concat(y.slice(A+1));u.children=[];for(var F=0,G=y.length;F<G;F++)u.add(y[F]);}}delete u.name;w['cke:list']=1;},assembleList:function(u){var v=u.children,w,x,y,z,A,B,C,D=[],E,F,G,H,I,J;
for(var K=0;K<v.length;K++){w=v[K];if('cke:li'==w.name){w.name='li';x=w;y=x.attributes;G=y['cke:listsymbol'];G=G&&G.match(/^(?:[(]?)([^\s]+?)([.)]?)$/);H=I=J=null;if(y['cke:ignored']){v.splice(K--,1);continue;}y['cke:reset']&&(C=A=B=null);z=Number(y['cke:indent']);if(z!=A)F=E=null;if(!G){H=y['cke:listtype']||'ol';I=y['cke:list-style-type'];}else{if(F&&k[F][E].test(G[1])){H=F;I=E;}else for(var L in k)for(var M in k[L]){if(k[L][M].test(G[1]))if(L=='ol'&&/alpha|roman/.test(M)){var N=/roman/.test(M)?n(G[1]):o(G[1]);if(!J||N<J){J=N;H=L;I=M;}}else{H=L;I=M;break;}}!H&&(H=G[2]?'ol':'ul');}F=H;E=I||(H=='ol'?'decimal':'disc');if(I&&I!=(H=='ol'?'decimal':'disc'))x.addStyle('list-style-type',I);if(H=='ol'&&G){switch(I){case 'decimal':J=Number(G[1]);break;case 'lower-roman':case 'upper-roman':J=n(G[1]);break;case 'lower-alpha':case 'upper-alpha':J=o(G[1]);break;}x.attributes.value=J;}if(!C){D.push(C=new CKEDITOR.htmlParser.element(H));C.add(x);v[K]=C;}else{if(z>A){D.push(C=new CKEDITOR.htmlParser.element(H));C.add(x);B.add(C);}else if(z<A){var O=A-z,P;while(O--&&(P=C.parent))C=P.parent;C.add(x);}else C.add(x);v.splice(K--,1);}B=x;A=z;}else if(C)C=A=B=null;}for(K=0;K<D.length;K++)c(D[K]);C=A=B=r=q=p=null;},falsyFilter:function(u){return false;},stylesFilter:function(u,v){return function(w,x){var y=[];(w||'').replace(/"/g,'"').replace(/\s*([^ :;]+)\s*:\s*([^;]+)\s*(?=;|$)/g,function(A,B,C){B=B.toLowerCase();B=='font-family'&&(C=C.replace(/["']/g,''));var D,E,F,G;for(var H=0;H<u.length;H++){if(u[H]){D=u[H][0];E=u[H][1];F=u[H][2];G=u[H][3];if(B.match(D)&&(!E||C.match(E))){B=G||B;v&&(F=F||C);if(typeof F=='function')F=F(C,x,B);if(F&&F.push)B=F[0],F=F[1];if(typeof F=='string')y.push([B,F]);return;}}}!v&&y.push([B,C]);});for(var z=0;z<y.length;z++)y[z]=y[z].join(':');return y.length?y.join(';')+';':false;};},elementMigrateFilter:function(u,v){return function(w){var x=v?new CKEDITOR.style(u,v)._.definition:u;w.name=x.element;CKEDITOR.tools.extend(w.attributes,CKEDITOR.tools.clone(x.attributes));w.addStyle(CKEDITOR.style.getStyleText(x));};},styleMigrateFilter:function(u,v){var w=this.elementMigrateFilter;return function(x,y){var z=new CKEDITOR.htmlParser.element(null),A={};A[v]=x;w(u,A)(z);z.children=y.children;y.children=[z];};},bogusAttrFilter:function(u,v){if(v.name.indexOf('cke:')==-1)return false;},applyStyleFilter:null},getRules:function(u){var v=CKEDITOR.dtd,w=CKEDITOR.tools.extend({},v.$block,v.$listItem,v.$tableContent),x=u.config,y=this.filters,z=y.falsyFilter,A=y.stylesFilter,B=y.elementMigrateFilter,C=CKEDITOR.tools.bind(this.filters.styleMigrateFilter,this.filters),D=this.utils.createListBulletMarker,E=y.flattenList,F=y.assembleList,G=this.utils.isListBulletIndicator,H=this.utils.isContainingOnlySpaces,I=this.utils.resolveList,J=function(O){O=CKEDITOR.tools.convertToPx(O);
return isNaN(O)?O:O+'px';},K=this.utils.getStyleComponents,L=this.utils.listDtdParents,M=x.pasteFromWordRemoveFontStyles!==false,N=x.pasteFromWordRemoveStyles!==false;return{elementNames:[[/meta|link|script/,'']],root:function(O){O.filterChildren();F(O);},elements:{'^':function(O){var P;if(CKEDITOR.env.gecko&&(P=y.applyStyleFilter))P(O);},$:function(O){var P=O.name||'',Q=O.attributes;if(P in w&&Q.style)Q.style=A([[/^(:?width|height)$/,null,J]])(Q.style)||'';if(P.match(/h\d/)){O.filterChildren();if(I(O))return;B(x['format_'+P])(O);}else if(P in v.$inline){O.filterChildren();if(H(O))delete O.name;}else if(P.indexOf(':')!=-1&&P.indexOf('cke')==-1){O.filterChildren();if(P=='v:imagedata'){var R=O.attributes['o:href'];if(R)O.attributes.src=R;O.name='img';return;}delete O.name;}if(P in L){O.filterChildren();F(O);}},style:function(O){if(CKEDITOR.env.gecko){var P=O.onlyChild().value.match(/\/\* Style Definitions \*\/([\s\S]*?)\/\*/),Q=P&&P[1],R={};if(Q){Q.replace(/[\n\r]/g,'').replace(/(.+?)\{(.+?)\}/g,function(S,T,U){T=T.split(',');var V=T.length,W;for(var X=0;X<V;X++)CKEDITOR.tools.trim(T[X]).replace(/^(\w+)(\.[\w-]+)?$/g,function(Y,Z,aa){Z=Z||'*';aa=aa.substring(1,aa.length);if(aa.match(/MsoNormal/))return;if(!R[Z])R[Z]={};if(aa)R[Z][aa]=U;else R[Z]=U;});});y.applyStyleFilter=function(S){var T=R['*']?'*':S.name,U=S.attributes&&S.attributes['class'],V;if(T in R){V=R[T];if(typeof V=='object')V=V[U];V&&S.addStyle(V,true);}};}}return false;},p:function(O){if(/MsoListParagraph/.exec(O.attributes['class'])){var P=O.firstChild(function(S){return S.type==CKEDITOR.NODE_TEXT&&!H(S.parent);}),Q=P&&P.parent,R=Q&&Q.attributes;R&&!R.style&&(R.style='mso-list: Ignore;');}O.filterChildren();if(I(O))return;if(x.enterMode==CKEDITOR.ENTER_BR){delete O.name;O.add(new CKEDITOR.htmlParser.element('br'));}else B(x['format_'+(x.enterMode==CKEDITOR.ENTER_P?'p':'div')])(O);},div:function(O){var P=O.onlyChild();if(P&&P.name=='table'){var Q=O.attributes;P.attributes=CKEDITOR.tools.extend(P.attributes,Q);Q.style&&P.addStyle(Q.style);var R=new CKEDITOR.htmlParser.element('div');R.addStyle('clear','both');O.add(R);delete O.name;}},td:function(O){if(O.getAncestor('thead'))O.name='th';},ol:E,ul:E,dl:E,font:function(O){if(G(O.parent)){delete O.name;return;}O.filterChildren();var P=O.attributes,Q=P.style,R=O.parent;if('font'==R.name){CKEDITOR.tools.extend(R.attributes,O.attributes);Q&&R.addStyle(Q);delete O.name;}else{Q=Q||'';if(P.color){P.color!='#000000'&&(Q+='color:'+P.color+';');delete P.color;
}if(P.face){Q+='font-family:'+P.face+';';delete P.face;}if(P.size){Q+='font-size:'+(P.size>3?'large':P.size<3?'small':'medium')+';';delete P.size;}O.name='span';O.addStyle(Q);}},span:function(O){if(G(O.parent))return false;O.filterChildren();if(H(O)){delete O.name;return null;}if(G(O)){var P=O.firstChild(function(Y){return Y.value||Y.name=='img';}),Q=P&&(P.value||'l.'),R=Q&&Q.match(/^(?:[(]?)([^\s]+?)([.)]?)$/);if(R){var S=D(R,Q),T=O.getAncestor('span');if(T&&/ mso-hide:\s*all|display:\s*none /.test(T.attributes.style))S.attributes['cke:ignored']=1;return S;}}var U=O.children,V=O.attributes,W=V&&V.style,X=U&&U[0];if(W)V.style=A([['line-height'],[/^font-family$/,null,!M?C(x.font_style,'family'):null],[/^font-size$/,null,!M?C(x.fontSize_style,'size'):null],[/^color$/,null,!M?C(x.colorButton_foreStyle,'color'):null],[/^background-color$/,null,!M?C(x.colorButton_backStyle,'color'):null]])(W,O)||'';return null;},b:B(x.coreStyles_bold),i:B(x.coreStyles_italic),u:B(x.coreStyles_underline),s:B(x.coreStyles_strike),sup:B(x.coreStyles_superscript),sub:B(x.coreStyles_subscript),a:function(O){var P=O.attributes;if(P&&!P.href&&P.name)delete O.name;else if(CKEDITOR.env.webkit&&P.href&&P.href.match(/file:\/\/\/[\S]+#/i))P.href=P.href.replace(/file:\/\/\/[^#]+/i,'');},'cke:listbullet':function(O){if(O.getAncestor(/h\d/)&&!x.pasteFromWordNumberedHeadingToList)delete O.name;}},attributeNames:[[/^onmouse(:?out|over)/,''],[/^onload$/,''],[/(?:v|o):\w+/,''],[/^lang/,'']],attributes:{style:A(N?[[/^list-style-type$/,null],[/^margin$|^margin-(?!bottom|top)/,null,function(O,P,Q){if(P.name in {p:1,div:1}){var R=x.contentsLangDirection=='ltr'?'margin-left':'margin-right';if(Q=='margin')O=K(Q,O,[R])[R];else if(Q!=R)return null;if(O&&!e.test(O))return[R,O];}return null;}],[/^clear$/],[/^border.*|margin.*|vertical-align|float$/,null,function(O,P){if(P.name=='img')return O;}],[/^width|height$/,null,function(O,P){if(P.name in {table:1,td:1,th:1,img:1})return O;}]]:[[/^mso-/],[/-color$/,null,function(O){if(O=='transparent')return false;if(CKEDITOR.env.gecko)return O.replace(/-moz-use-text-color/g,'transparent');}],[/^margin$/,e],['text-indent','0cm'],['page-break-before'],['tab-stops'],['display','none'],M?[/font-?/]:null],N),width:function(O,P){if(P.name in v.$tableContent)return false;},border:function(O,P){if(P.name in v.$tableContent)return false;},'class':z,bgcolor:z,valign:N?z:function(O,P){P.addStyle('vertical-align',O);return false;}},comment:!CKEDITOR.env.ie?function(O,P){var Q=O.match(/<img.*?>/),R=O.match(/^\[if !supportLists\]([\s\S]*?)\[endif\]$/);
if(R){var S=R[1]||Q&&'l.',T=S&&S.match(/>(?:[(]?)([^\s]+?)([.)]?)</);return D(T,S);}if(CKEDITOR.env.gecko&&Q){var U=CKEDITOR.htmlParser.fragment.fromHtml(Q[0]).children[0],V=P.previous,W=V&&V.value.match(/<v:imagedata[^>]*o:href=['"](.*?)['"]/),X=W&&W[1];X&&(U.attributes.src=X);return U;}return false;}:z};}},t=function(){this.dataFilter=new CKEDITOR.htmlParser.filter();};t.prototype={toHtml:function(u){var v=CKEDITOR.htmlParser.fragment.fromHtml(u,false),w=new CKEDITOR.htmlParser.basicWriter();v.writeHtml(w,this.dataFilter);return w.getHtml(true);}};CKEDITOR.cleanWord=function(u,v){if(CKEDITOR.env.gecko)u=u.replace(/(<!--\[if[^<]*?\])-->([\S\s]*?)<!--(\[endif\]-->)/gi,'$1$2$3');var w=new t(),x=w.dataFilter;x.addRules(CKEDITOR.plugins.pastefromword.getRules(v));v.fire('beforeCleanWord',{filter:x});try{u=w.toHtml(u,false);}catch(y){alert(v.lang.pastefromword.error);}u=u.replace(/cke:.*?".*?"/g,'');u=u.replace(/style=""/g,'');u=u.replace(/<span>/g,'');return u;};})(); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/plugins/pastefromword/filter/default.js | default.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function(){function a(d,e,f){if(!e.is||!e.getCustomData('block_processed')){e.is&&CKEDITOR.dom.element.setMarker(f,e,'block_processed',true);d.push(e);}};function b(d){var e=[],f=d.getChildren();for(var g=0;g<f.count();g++){var h=f.getItem(g);if(!(h.type===CKEDITOR.NODE_TEXT&&/^[ \t\n\r]+$/.test(h.getText())))e.push(h);}return e;};function c(d,e){var f=(function(){var p=CKEDITOR.tools.extend({},CKEDITOR.dtd.$blockLimit);delete p.div;if(d.config.div_wrapTable){delete p.td;delete p.th;}return p;})(),g=CKEDITOR.dtd.div;function h(p){var q=new CKEDITOR.dom.elementPath(p).elements,r;for(var s=0;s<q.length;s++){if(q[s].getName() in f){r=q[s];break;}}return r;};function i(){this.foreach(function(p){if(/^(?!vbox|hbox)/.test(p.type)){if(!p.setup)p.setup=function(q){p.setValue(q.getAttribute(p.id)||'');};if(!p.commit)p.commit=function(q){var r=this.getValue();if('dir'==p.id&&q.getComputedStyle('direction')==r)return;if(r)q.setAttribute(p.id,r);else q.removeAttribute(p.id);};}});};function j(p){var q=[],r={},s=[],t,u=p.document.getSelection(),v=u.getRanges(),w=u.createBookmarks(),x,y,z=p.config.enterMode==CKEDITOR.ENTER_DIV?'div':'p';for(x=0;x<v.length;x++){y=v[x].createIterator();while(t=y.getNextParagraph()){if(t.getName() in f){var A,B=t.getChildren();for(A=0;A<B.count();A++)a(s,B.getItem(A),r);}else{while(!g[t.getName()]&&t.getName()!='body')t=t.getParent();a(s,t,r);}}}CKEDITOR.dom.element.clearAllMarkers(r);var C=l(s),D,E,F;for(x=0;x<C.length;x++){var G=C[x][0];D=G.getParent();for(A=1;A<C[x].length;A++)D=D.getCommonAncestor(C[x][A]);F=new CKEDITOR.dom.element('div',p.document);for(A=0;A<C[x].length;A++){G=C[x][A];while(!G.getParent().equals(D))G=G.getParent();C[x][A]=G;}var H=null;for(A=0;A<C[x].length;A++){G=C[x][A];if(!(G.getCustomData&&G.getCustomData('block_processed'))){G.is&&CKEDITOR.dom.element.setMarker(r,G,'block_processed',true);if(!A)F.insertBefore(G);F.append(G);}}CKEDITOR.dom.element.clearAllMarkers(r);q.push(F);}u.selectBookmarks(w);return q;};function k(p){var q=new CKEDITOR.dom.elementPath(p.getSelection().getStartElement()),r=q.blockLimit,s=r&&r.getAscendant('div',true);return s;};function l(p){var q=[],r=null,s,t;for(var u=0;u<p.length;u++){t=p[u];var v=h(t);if(!v.equals(r)){r=v;q.push([]);}q[q.length-1].push(t);}return q;};function m(p){var q=this.getDialog(),r=q._element&&q._element.clone()||new CKEDITOR.dom.element('div',d.document);this.commit(r,true);p=[].concat(p);var s=p.length,t;for(var u=0;u<s;u++){t=q.getContentElement.apply(q,p[u].split(':'));
t&&t.setup&&t.setup(r,true);}};var n={},o=[];return{title:d.lang.div.title,minWidth:400,minHeight:165,contents:[{id:'info',label:d.lang.common.generalTab,title:d.lang.common.generalTab,elements:[{type:'hbox',widths:['50%','50%'],children:[{id:'elementStyle',type:'select',style:'width: 100%;',label:d.lang.div.styleSelectLabel,'default':'',items:[[d.lang.common.notSet,'']],onChange:function(){m.call(this,['info:class','advanced:dir','advanced:style']);},setup:function(p){for(var q in n)n[q].checkElementRemovable(p,true)&&this.setValue(q);},commit:function(p){var q;if(q=this.getValue()){var r=n[q],s=p.getCustomData('elementStyle')||'';r.applyToObject(p);p.setCustomData('elementStyle',s+r._.definition.attributes.style);}}},{id:'class',type:'text',label:d.lang.common.cssClass,'default':''}]}]},{id:'advanced',label:d.lang.common.advancedTab,title:d.lang.common.advancedTab,elements:[{type:'vbox',padding:1,children:[{type:'hbox',widths:['50%','50%'],children:[{type:'text',id:'id',label:d.lang.common.id,'default':''},{type:'text',id:'lang',label:d.lang.link.langCode,'default':''}]},{type:'hbox',children:[{type:'text',id:'style',style:'width: 100%;',label:d.lang.common.cssStyle,'default':'',commit:function(p){var q=this.getValue()+(p.getCustomData('elementStyle')||'');p.setAttribute('style',q);}}]},{type:'hbox',children:[{type:'text',id:'title',style:'width: 100%;',label:d.lang.common.advisoryTitle,'default':''}]},{type:'select',id:'dir',style:'width: 100%;',label:d.lang.common.langDir,'default':'',items:[[d.lang.common.notSet,''],[d.lang.common.langDirLtr,'ltr'],[d.lang.common.langDirRtl,'rtl']]}]}]}],onLoad:function(){i.call(this);var p=this,q=this.getContentElement('info','elementStyle');d.getStylesSet(function(r){var s;if(r)for(var t=0;t<r.length;t++){var u=r[t];if(u.element&&u.element=='div'){s=u.name;n[s]=new CKEDITOR.style(u);q.items.push([s,s]);q.add(s,s);}}q[q.items.length>1?'enable':'disable']();setTimeout(function(){q.setup(p._element);},0);});},onShow:function(){if(e=='editdiv'){var p=k(d);p&&this.setupContent(this._element=p);}},onOk:function(){if(e=='editdiv')o=[this._element];else o=j(d,true);var p=o.length;for(var q=0;q<p;q++){this.commitContent(o[q]);!o[q].getAttribute('style')&&o[q].removeAttribute('style');}this.hide();},onHide:function(){if(e=='editdiv')this._element.removeCustomData('elementStyle');delete this._element;}};};CKEDITOR.dialog.add('creatediv',function(d){return c(d,'creatediv');});CKEDITOR.dialog.add('editdiv',function(d){return c(d,'editdiv');
});})(); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/plugins/div/dialogs/div.js | div.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function(){var a=['click','keydown','mousedown','keypress','mouseover','mouseout'];function b(c){var d=c.getElementsByTag('*'),e=d.count(),f;for(var g=0;g<e;g++){f=d.getItem(g);(function(h){for(var i=0;i<a.length;i++)(function(j){var k=h.getAttribute('on'+j);if(h.hasAttribute('on'+j)){h.removeAttribute('on'+j);h.on(j,function(l){var m=/(return\s*)?CKEDITOR\.tools\.callFunction\(([^)]+)\)/.exec(k),n=m&&m[1],o=m&&m[2].split(','),p=/return false;/.test(k);if(o){var q=o.length,r;for(var s=0;s<q;s++){o[s]=r=CKEDITOR.tools.trim(o[s]);var t=r.match(/^(["'])([^"']*?)\1$/);if(t){o[s]=t[2];continue;}if(r.match(/\d+/)){o[s]=parseInt(r,10);continue;}switch(r){case 'this':o[s]=h.$;break;case 'event':o[s]=l.data.$;break;case 'null':o[s]=null;break;}}var u=CKEDITOR.tools.callFunction.apply(window,o);if(n&&u===false)p=1;}if(p)l.data.preventDefault();});}})(a[i]);})(f);}};CKEDITOR.plugins.add('adobeair',{init:function(c){if(!CKEDITOR.env.air)return;c.addCss('body { padding: 8px }');c.on('uiReady',function(){b(c.container);if(c.sharedSpaces)for(var d in c.sharedSpaces)b(c.sharedSpaces[d]);c.on('elementsPathUpdate',function(e){b(e.data.space);});});c.on('contentDom',function(){c.document.on('click',function(d){d.data.preventDefault(true);});});}});CKEDITOR.ui.on('ready',function(c){var d=c.data;if(d._.panel){var e=d._.panel._.panel,f;(function(){if(!e.isLoaded){setTimeout(arguments.callee,30);return;}f=e._.holder;b(f);})();}else if(d instanceof CKEDITOR.dialog)b(d._.element);});})();CKEDITOR.dom.document.prototype.write=CKEDITOR.tools.override(CKEDITOR.dom.document.prototype.write,function(a){function b(c,d,e,f){var g=c.append(d),h=CKEDITOR.htmlParser.fragment.fromHtml(e).children[0].attributes;h&&g.setAttributes(h);f&&g.append(c.getDocument().createText(f));};return function(c,d){if(this.getBody()){var e=this,f=this.getHead();c=c.replace(/(<style[^>]*>)([\s\S]*?)<\/style>/gi,function(g,h,i){b(f,'style',h,i);return '';});c=c.replace(/<base\b[^>]*\/>/i,function(g){b(f,'base',g);return '';});c=c.replace(/<title>([\s\S]*)<\/title>/i,function(g,h){e.$.title=h;return '';});c=c.replace(/<head>([\s\S]*)<\/head>/i,function(g){var h=new CKEDITOR.dom.element('div',e);h.setHtml(g);h.moveChildren(f);return '';});c.replace(/(<body[^>]*>)([\s\S]*)(?=$|<\/body>)/i,function(g,h,i){e.getBody().setHtml(i);var j=CKEDITOR.htmlParser.fragment.fromHtml(h).children[0].attributes;j&&e.getBody().setAttributes(j);});}else a.apply(this,arguments);};}); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/plugins/adobeair/plugin.js | plugin.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function(){var a={scrolling:{'true':'yes','false':'no'},frameborder:{'true':'1','false':'0'}};function b(d){var g=this;var e=g instanceof CKEDITOR.ui.dialog.checkbox;if(d.hasAttribute(g.id)){var f=d.getAttribute(g.id);if(e)g.setValue(a[g.id]['true']==f.toLowerCase());else g.setValue(f);}};function c(d){var h=this;var e=h.getValue()==='',f=h instanceof CKEDITOR.ui.dialog.checkbox,g=h.getValue();if(e)d.removeAttribute(h.att||h.id);else if(f)d.setAttribute(h.id,a[h.id][g]);else d.setAttribute(h.att||h.id,g);};CKEDITOR.dialog.add('iframe',function(d){var e=d.lang.iframe,f=d.lang.common,g=d.plugins.dialogadvtab;return{title:e.title,minWidth:350,minHeight:260,onShow:function(){var j=this;j.fakeImage=j.iframeNode=null;var h=j.getSelectedElement();if(h&&h.data('cke-real-element-type')&&h.data('cke-real-element-type')=='iframe'){j.fakeImage=h;var i=d.restoreRealElement(h);j.iframeNode=i;j.setupContent(i);}},onOk:function(){var l=this;var h;if(!l.fakeImage)h=new CKEDITOR.dom.element('iframe');else h=l.iframeNode;var i={},j={};l.commitContent(h,i,j);var k=d.createFakeElement(h,'cke_iframe','iframe',true);k.setAttributes(j);k.setStyles(i);if(l.fakeImage){k.replace(l.fakeImage);d.getSelection().selectElement(k);}else d.insertElement(k);},contents:[{id:'info',label:f.generalTab,accessKey:'I',elements:[{type:'vbox',padding:0,children:[{id:'src',type:'text',label:f.url,required:true,validate:CKEDITOR.dialog.validate.notEmpty(e.noUrl),setup:b,commit:c}]},{type:'hbox',children:[{id:'width',type:'text',style:'width:100%',labelLayout:'vertical',label:f.width,validate:CKEDITOR.dialog.validate.htmlLength(f.invalidHtmlLength.replace('%1',f.width)),setup:b,commit:c},{id:'height',type:'text',style:'width:100%',labelLayout:'vertical',label:f.height,validate:CKEDITOR.dialog.validate.htmlLength(f.invalidHtmlLength.replace('%1',f.height)),setup:b,commit:c},{id:'align',type:'select','default':'',items:[[f.notSet,''],[f.alignLeft,'left'],[f.alignRight,'right'],[f.alignTop,'top'],[f.alignMiddle,'middle'],[f.alignBottom,'bottom']],style:'width:100%',labelLayout:'vertical',label:f.align,setup:function(h,i){b.apply(this,arguments);if(i){var j=i.getAttribute('align');this.setValue(j&&j.toLowerCase()||'');}},commit:function(h,i,j){c.apply(this,arguments);if(this.getValue())j.align=this.getValue();}}]},{type:'hbox',widths:['50%','50%'],children:[{id:'scrolling',type:'checkbox',label:e.scrolling,setup:b,commit:c},{id:'frameborder',type:'checkbox',label:e.border,setup:b,commit:c}]},{type:'hbox',widths:['50%','50%'],children:[{id:'name',type:'text',label:f.name,setup:b,commit:c},{id:'title',type:'text',label:f.advisoryTitle,setup:b,commit:c}]},{id:'longdesc',type:'text',label:f.longDescr,setup:b,commit:c}]},g&&g.createAdvancedTab(d,{id:1,classes:1,styles:1})]};
});})(); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/plugins/iframe/dialogs/iframe.js | iframe.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add('colordialog',function(a){var b=CKEDITOR.dom.element,c=CKEDITOR.document,d=CKEDITOR.tools,e=a.lang.colordialog,f,g={type:'html',html:' '};function h(){c.getById(x).removeStyle('background-color');f.getContentElement('picker','selectedColor').setValue('');};function i(z){if(!(z instanceof CKEDITOR.dom.event))z=new CKEDITOR.dom.event(z);var A=z.getTarget(),B;if(A.getName()=='a'&&(B=A.getChild(0).getHtml()))f.getContentElement('picker','selectedColor').setValue(B);};function j(z){if(!(z instanceof CKEDITOR.dom.event))z=z.data;var A=z.getTarget(),B;if(A.getName()=='a'&&(B=A.getChild(0).getHtml())){c.getById(v).setStyle('background-color',B);c.getById(w).setHtml(B);}};function k(){c.getById(v).removeStyle('background-color');c.getById(w).setHtml(' ');};var l=d.addFunction(k),m=i,n=CKEDITOR.tools.addFunction(m),o=j,p=k,q=CKEDITOR.tools.addFunction(function(z){z=new CKEDITOR.dom.event(z);var A=z.getTarget(),B,C,D=z.getKeystroke(),E=a.lang.dir=='rtl';switch(D){case 38:if(B=A.getParent().getParent().getPrevious()){C=B.getChild([A.getParent().getIndex(),0]);C.focus();p(z,A);o(z,C);}z.preventDefault();break;case 40:if(B=A.getParent().getParent().getNext()){C=B.getChild([A.getParent().getIndex(),0]);if(C&&C.type==1){C.focus();p(z,A);o(z,C);}}z.preventDefault();break;case 32:m(z);z.preventDefault();break;case E?37:39:if(B=A.getParent().getNext()){C=B.getChild(0);if(C.type==1){C.focus();p(z,A);o(z,C);z.preventDefault(true);}else p(null,A);}else if(B=A.getParent().getParent().getNext()){C=B.getChild([0,0]);if(C&&C.type==1){C.focus();p(z,A);o(z,C);z.preventDefault(true);}else p(null,A);}break;case E?39:37:if(B=A.getParent().getPrevious()){C=B.getChild(0);C.focus();p(z,A);o(z,C);z.preventDefault(true);}else if(B=A.getParent().getParent().getPrevious()){C=B.getLast().getChild(0);C.focus();p(z,A);o(z,C);z.preventDefault(true);}else p(null,A);break;default:return;}});function r(){var z=['00','33','66','99','cc','ff'];function A(F,G){for(var H=F;H<F+3;H++){var I=s.$.insertRow(-1);for(var J=G;J<G+3;J++)for(var K=0;K<6;K++)B(I,'#'+z[J]+z[K]+z[H]);}};function B(F,G){var H=new b(F.insertCell(-1));H.setAttribute('class','ColorCell');H.setStyle('background-color',G);H.setStyle('width','15px');H.setStyle('height','15px');var I=H.$.cellIndex+1+18*F.rowIndex;H.append(CKEDITOR.dom.element.createFromHtml('<a href="javascript: void(0);" role="option" aria-posinset="'+I+'"'+' aria-setsize="'+234+'"'+' style="cursor: pointer;display:block;width:100%;height:100% " title="'+CKEDITOR.tools.htmlEncode(G)+'"'+' onkeydown="CKEDITOR.tools.callFunction( '+q+', event, this )"'+' onclick="CKEDITOR.tools.callFunction('+n+', event, this ); return false;"'+' tabindex="-1"><span class="cke_voice_label">'+G+'</span> </a>',CKEDITOR.document));
};A(0,0);A(3,0);A(0,3);A(3,3);var C=s.$.insertRow(-1);for(var D=0;D<6;D++)B(C,'#'+z[D]+z[D]+z[D]);for(var E=0;E<12;E++)B(C,'#000000');};var s=new b('table');r();var t=s.getHtml(),u=function(z){return CKEDITOR.tools.getNextId()+'_'+z;},v=u('hicolor'),w=u('hicolortext'),x=u('selhicolor'),y=u('color_table_label');return{title:e.title,minWidth:360,minHeight:220,onLoad:function(){f=this;},contents:[{id:'picker',label:e.title,accessKey:'I',elements:[{type:'hbox',padding:0,widths:['70%','10%','30%'],children:[{type:'html',html:'<table role="listbox" aria-labelledby="'+y+'" onmouseout="CKEDITOR.tools.callFunction( '+l+' );">'+(!CKEDITOR.env.webkit?t:'')+'</table><span id="'+y+'" class="cke_voice_label">'+e.options+'</span>',onLoad:function(){var z=CKEDITOR.document.getById(this.domId);z.on('mouseover',j);CKEDITOR.env.webkit&&z.setHtml(t);},focus:function(){var z=this.getElement().getElementsByTag('a').getItem(0);z.focus();}},g,{type:'vbox',padding:0,widths:['70%','5%','25%'],children:[{type:'html',html:'<span>'+e.highlight+'</span>\t\t\t\t\t\t\t\t\t\t\t\t<div id="'+v+'" style="border: 1px solid; height: 74px; width: 74px;"></div>\t\t\t\t\t\t\t\t\t\t\t\t<div id="'+w+'"> </div><span>'+e.selected+'</span>\t\t\t\t\t\t\t\t\t\t\t\t<div id="'+x+'" style="border: 1px solid; height: 20px; width: 74px;"></div>'},{type:'text',label:e.selected,labelStyle:'display:none',id:'selectedColor',style:'width: 74px',onChange:function(){try{c.getById(x).setStyle('background-color',this.getValue());}catch(z){h();}}},g,{type:'button',id:'clear',style:'margin-top: 5px',label:e.clear,onClick:h}]}]}]}]};}); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/plugins/colordialog/dialogs/colordialog.js | colordialog.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add('paste',function(a){var b=a.lang.clipboard,c=CKEDITOR.env.isCustomDomain();function d(e){var f=new CKEDITOR.dom.document(e.document),g=f.$,h=f.getById('cke_actscrpt');h&&h.remove();CKEDITOR.env.ie?g.body.contentEditable='true':g.designMode='on';if(CKEDITOR.env.ie&&CKEDITOR.env.version<8)f.getWindow().on('blur',function(){g.selection.empty();});f.on('keydown',function(i){var j=i.data,k=j.getKeystroke(),l;switch(k){case 27:this.hide();l=1;break;case 9:case CKEDITOR.SHIFT+9:this.changeFocus(true);l=1;}l&&j.preventDefault();},this);a.fire('ariaWidget',new CKEDITOR.dom.element(e.frameElement));};return{title:b.title,minWidth:CKEDITOR.env.ie&&CKEDITOR.env.quirks?370:350,minHeight:CKEDITOR.env.quirks?250:245,onShow:function(){this.parts.dialog.$.offsetHeight;this.setupContent();},onHide:function(){if(CKEDITOR.env.ie)this.getParentEditor().document.getBody().$.contentEditable='true';},onLoad:function(){if((CKEDITOR.env.ie7Compat||CKEDITOR.env.ie6Compat)&&a.lang.dir=='rtl')this.parts.contents.setStyle('overflow','hidden');},onOk:function(){this.commitContent();},contents:[{id:'general',label:a.lang.common.generalTab,elements:[{type:'html',id:'securityMsg',html:'<div style="white-space:normal;width:340px;">'+b.securityMsg+'</div>'},{type:'html',id:'pasteMsg',html:'<div style="white-space:normal;width:340px;">'+b.pasteMsg+'</div>'},{type:'html',id:'editing_area',style:'width: 100%; height: 100%;',html:'',focus:function(){var e=this.getInputElement().$.contentWindow;setTimeout(function(){e.focus();},500);},setup:function(){var e=this.getDialog(),f='<html dir="'+a.config.contentsLangDirection+'"'+' lang="'+(a.config.contentsLanguage||a.langCode)+'">'+'<head><style>body { margin: 3px; height: 95%; } </style></head><body>'+'<script id="cke_actscrpt" type="text/javascript">'+'window.parent.CKEDITOR.tools.callFunction( '+CKEDITOR.tools.addFunction(d,e)+', this );'+'</script></body>'+'</html>',g=CKEDITOR.env.air?'javascript:void(0)':c?"javascript:void((function(){document.open();document.domain='"+document.domain+"';"+'document.close();'+'})())"':'',h=CKEDITOR.dom.element.createFromHtml('<iframe class="cke_pasteframe" frameborder="0" allowTransparency="true" src="'+g+'"'+' role="region"'+' aria-label="'+b.pasteArea+'"'+' aria-describedby="'+e.getContentElement('general','pasteMsg').domId+'"'+' aria-multiple="true"'+'></iframe>');h.on('load',function(k){k.removeListener();var l=h.getFrameDocument();l.write(f);if(CKEDITOR.env.air)d.call(this,l.getWindow().$);
},e);h.setCustomData('dialog',e);var i=this.getElement();i.setHtml('');i.append(h);if(CKEDITOR.env.ie){var j=CKEDITOR.dom.element.createFromHtml('<span tabindex="-1" style="position:absolute;" role="presentation"></span>');j.on('focus',function(){h.$.contentWindow.focus();});i.append(j);this.focus=function(){j.focus();this.fire('focus');};}this.getInputElement=function(){return h;};if(CKEDITOR.env.ie){i.setStyle('display','block');i.setStyle('height',h.$.offsetHeight+2+'px');}},commit:function(e){var f=this.getElement(),g=this.getDialog().getParentEditor(),h=this.getInputElement().getFrameDocument().getBody(),i=h.getBogus(),j;i&&i.remove();j=h.getHtml();setTimeout(function(){g.fire('paste',{html:j});},0);}}]}]};}); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/plugins/clipboard/dialogs/paste.js | paste.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add('link',function(a){var b=CKEDITOR.plugins.link,c=function(){var F=this.getDialog(),G=F.getContentElement('target','popupFeatures'),H=F.getContentElement('target','linkTargetName'),I=this.getValue();if(!G||!H)return;G=G.getElement();G.hide();H.setValue('');switch(I){case 'frame':H.setLabel(a.lang.link.targetFrameName);H.getElement().show();break;case 'popup':G.show();H.setLabel(a.lang.link.targetPopupName);H.getElement().show();break;default:H.setValue(I);H.getElement().hide();break;}},d=function(){var F=this.getDialog(),G=['urlOptions','anchorOptions','emailOptions'],H=this.getValue(),I=F.definition.getContents('upload'),J=I&&I.hidden;if(H=='url'){if(a.config.linkShowTargetTab)F.showPage('target');if(!J)F.showPage('upload');}else{F.hidePage('target');if(!J)F.hidePage('upload');}for(var K=0;K<G.length;K++){var L=F.getContentElement('info',G[K]);if(!L)continue;L=L.getElement().getParent().getParent();if(G[K]==H+'Options')L.show();else L.hide();}F.layout();},e=/^javascript:/,f=/^mailto:([^?]+)(?:\?(.+))?$/,g=/subject=([^;?:@&=$,\/]*)/,h=/body=([^;?:@&=$,\/]*)/,i=/^#(.*)$/,j=/^((?:http|https|ftp|news):\/\/)?(.*)$/,k=/^(_(?:self|top|parent|blank))$/,l=/^javascript:void\(location\.href='mailto:'\+String\.fromCharCode\(([^)]+)\)(?:\+'(.*)')?\)$/,m=/^javascript:([^(]+)\(([^)]+)\)$/,n=/\s*window.open\(\s*this\.href\s*,\s*(?:'([^']*)'|null)\s*,\s*'([^']*)'\s*\)\s*;\s*return\s*false;*\s*/,o=/(?:^|,)([^=]+)=(\d+|yes|no)/gi,p=function(F,G){var H=G&&(G.data('cke-saved-href')||G.getAttribute('href'))||'',I,J,K,L,M={};if(I=H.match(e))if(y=='encode')H=H.replace(l,function(ae,af,ag){return 'mailto:'+String.fromCharCode.apply(String,af.split(','))+(ag&&w(ag));});else if(y)H.replace(m,function(ae,af,ag){if(af==z.name){M.type='email';var ah=M.email={},ai=/[^,\s]+/g,aj=/(^')|('$)/g,ak=ag.match(ai),al=ak.length,am,an;for(var ao=0;ao<al;ao++){an=decodeURIComponent(w(ak[ao].replace(aj,'')));am=z.params[ao].toLowerCase();ah[am]=an;}ah.address=[ah.name,ah.domain].join('@');}});if(!M.type)if(K=H.match(i)){M.type='anchor';M.anchor={};M.anchor.name=M.anchor.id=K[1];}else if(J=H.match(f)){var N=H.match(g),O=H.match(h);M.type='email';var P=M.email={};P.address=J[1];N&&(P.subject=decodeURIComponent(N[1]));O&&(P.body=decodeURIComponent(O[1]));}else if(H&&(L=H.match(j))){M.type='url';M.url={};M.url.protocol=L[1];M.url.url=L[2];}else M.type='url';if(G){var Q=G.getAttribute('target');M.target={};M.adv={};if(!Q){var R=G.data('cke-pa-onclick')||G.getAttribute('onclick'),S=R&&R.match(n);
if(S){M.target.type='popup';M.target.name=S[1];var T;while(T=o.exec(S[2])){if((T[2]=='yes'||T[2]=='1')&&!(T[1] in {height:1,width:1,top:1,left:1}))M.target[T[1]]=true;else if(isFinite(T[2]))M.target[T[1]]=T[2];}}}else{var U=Q.match(k);if(U)M.target.type=M.target.name=Q;else{M.target.type='frame';M.target.name=Q;}}var V=this,W=function(ae,af){var ag=G.getAttribute(af);if(ag!==null)M.adv[ae]=ag||'';};W('advId','id');W('advLangDir','dir');W('advAccessKey','accessKey');M.adv.advName=G.data('cke-saved-name')||G.getAttribute('name')||'';W('advLangCode','lang');W('advTabIndex','tabindex');W('advTitle','title');W('advContentType','type');CKEDITOR.plugins.link.synAnchorSelector?M.adv.advCSSClasses=C(G):W('advCSSClasses','class');W('advCharset','charset');W('advStyles','style');W('advRel','rel');}var X=M.anchors=[],Y;if(CKEDITOR.plugins.link.emptyAnchorFix){var Z=F.document.getElementsByTag('a');for(i=0,count=Z.count();i<count;i++){Y=Z.getItem(i);if(Y.data('cke-saved-name')||Y.hasAttribute('name'))X.push({name:Y.data('cke-saved-name')||Y.getAttribute('name'),id:Y.getAttribute('id')});}}else{var aa=new CKEDITOR.dom.nodeList(F.document.$.anchors);for(var ab=0,ac=aa.count();ab<ac;ab++){Y=aa.getItem(ab);X[ab]={name:Y.getAttribute('name'),id:Y.getAttribute('id')};}}if(CKEDITOR.plugins.link.fakeAnchor){var ad=F.document.getElementsByTag('img');for(ab=0,ac=ad.count();ab<ac;ab++){if(Y=CKEDITOR.plugins.link.tryRestoreFakeAnchor(F,ad.getItem(ab)))X.push({name:Y.getAttribute('name'),id:Y.getAttribute('id')});}}this._.selectedElement=G;return M;},q=function(F,G){if(G[F])this.setValue(G[F][this.id]||'');},r=function(F){return q.call(this,'target',F);},s=function(F){return q.call(this,'adv',F);},t=function(F,G){if(!G[F])G[F]={};G[F][this.id]=this.getValue()||'';},u=function(F){return t.call(this,'target',F);},v=function(F){return t.call(this,'adv',F);};function w(F){return F.replace(/\\'/g,"'");};function x(F){return F.replace(/'/g,'\\$&');};var y=a.config.emailProtection||'';if(y&&y!='encode'){var z={};y.replace(/^([^(]+)\(([^)]+)\)$/,function(F,G,H){z.name=G;z.params=[];H.replace(/[^,\s]+/g,function(I){z.params.push(I);});});}function A(F){var G,H=z.name,I=z.params,J,K;G=[H,'('];for(var L=0;L<I.length;L++){J=I[L].toLowerCase();K=F[J];L>0&&G.push(',');G.push("'",K?x(encodeURIComponent(F[J])):'',"'");}G.push(')');return G.join('');};function B(F){var G,H=F.length,I=[];for(var J=0;J<H;J++){G=F.charCodeAt(J);I.push(G);}return 'String.fromCharCode('+I.join(',')+')';};function C(F){var G=F.getAttribute('class');
return G?G.replace(/\s*(?:cke_anchor_empty|cke_anchor)(?:\s*$)?/g,''):'';};var D=a.lang.common,E=a.lang.link;return{title:E.title,minWidth:350,minHeight:230,contents:[{id:'info',label:E.info,title:E.info,elements:[{id:'linkType',type:'select',label:E.type,'default':'url',items:[[E.toUrl,'url'],[E.toAnchor,'anchor'],[E.toEmail,'email']],onChange:d,setup:function(F){if(F.type)this.setValue(F.type);},commit:function(F){F.type=this.getValue();}},{type:'vbox',id:'urlOptions',children:[{type:'hbox',widths:['25%','75%'],children:[{id:'protocol',type:'select',label:D.protocol,'default':'http://',items:[['http://','http://'],['https://','https://'],['ftp://','ftp://'],['news://','news://'],[E.other,'']],setup:function(F){if(F.url)this.setValue(F.url.protocol||'');},commit:function(F){if(!F.url)F.url={};F.url.protocol=this.getValue();}},{type:'text',id:'url',label:D.url,required:true,onLoad:function(){this.allowOnChange=true;},onKeyUp:function(){var K=this;K.allowOnChange=false;var F=K.getDialog().getContentElement('info','protocol'),G=K.getValue(),H=/^(http|https|ftp|news):\/\/(?=.)/i,I=/^((javascript:)|[#\/\.\?])/i,J=H.exec(G);if(J){K.setValue(G.substr(J[0].length));F.setValue(J[0].toLowerCase());}else if(I.test(G))F.setValue('');K.allowOnChange=true;},onChange:function(){if(this.allowOnChange)this.onKeyUp();},validate:function(){var F=this.getDialog();if(F.getContentElement('info','linkType')&&F.getValueOf('info','linkType')!='url')return true;if(this.getDialog().fakeObj)return true;var G=CKEDITOR.dialog.validate.notEmpty(E.noUrl);return G.apply(this);},setup:function(F){this.allowOnChange=false;if(F.url)this.setValue(F.url.url);this.allowOnChange=true;},commit:function(F){this.onChange();if(!F.url)F.url={};F.url.url=this.getValue();this.allowOnChange=false;}}],setup:function(F){if(!this.getDialog().getContentElement('info','linkType'))this.getElement().show();}},{type:'button',id:'browse',hidden:'true',filebrowser:'info:url',label:D.browseServer}]},{type:'vbox',id:'anchorOptions',width:260,align:'center',padding:0,children:[{type:'fieldset',id:'selectAnchorText',label:E.selectAnchor,setup:function(F){if(F.anchors.length>0)this.getElement().show();else this.getElement().hide();},children:[{type:'hbox',id:'selectAnchor',children:[{type:'select',id:'anchorName','default':'',label:E.anchorName,style:'width: 100%;',items:[['']],setup:function(F){var I=this;I.clear();I.add('');for(var G=0;G<F.anchors.length;G++){if(F.anchors[G].name)I.add(F.anchors[G].name);}if(F.anchor)I.setValue(F.anchor.name);
var H=I.getDialog().getContentElement('info','linkType');if(H&&H.getValue()=='email')I.focus();},commit:function(F){if(!F.anchor)F.anchor={};F.anchor.name=this.getValue();}},{type:'select',id:'anchorId','default':'',label:E.anchorId,style:'width: 100%;',items:[['']],setup:function(F){var H=this;H.clear();H.add('');for(var G=0;G<F.anchors.length;G++){if(F.anchors[G].id)H.add(F.anchors[G].id);}if(F.anchor)H.setValue(F.anchor.id);},commit:function(F){if(!F.anchor)F.anchor={};F.anchor.id=this.getValue();}}],setup:function(F){if(F.anchors.length>0)this.getElement().show();else this.getElement().hide();}}]},{type:'html',id:'noAnchors',style:'text-align: center;',html:'<div role="label" tabIndex="-1">'+CKEDITOR.tools.htmlEncode(E.noAnchors)+'</div>',focus:true,setup:function(F){if(F.anchors.length<1)this.getElement().show();else this.getElement().hide();}}],setup:function(F){if(!this.getDialog().getContentElement('info','linkType'))this.getElement().hide();}},{type:'vbox',id:'emailOptions',padding:1,children:[{type:'text',id:'emailAddress',label:E.emailAddress,required:true,validate:function(){var F=this.getDialog();if(!F.getContentElement('info','linkType')||F.getValueOf('info','linkType')!='email')return true;var G=CKEDITOR.dialog.validate.notEmpty(E.noEmail);return G.apply(this);},setup:function(F){if(F.email)this.setValue(F.email.address);var G=this.getDialog().getContentElement('info','linkType');if(G&&G.getValue()=='email')this.select();},commit:function(F){if(!F.email)F.email={};F.email.address=this.getValue();}},{type:'text',id:'emailSubject',label:E.emailSubject,setup:function(F){if(F.email)this.setValue(F.email.subject);},commit:function(F){if(!F.email)F.email={};F.email.subject=this.getValue();}},{type:'textarea',id:'emailBody',label:E.emailBody,rows:3,'default':'',setup:function(F){if(F.email)this.setValue(F.email.body);},commit:function(F){if(!F.email)F.email={};F.email.body=this.getValue();}}],setup:function(F){if(!this.getDialog().getContentElement('info','linkType'))this.getElement().hide();}}]},{id:'target',label:E.target,title:E.target,elements:[{type:'hbox',widths:['50%','50%'],children:[{type:'select',id:'linkTargetType',label:D.target,'default':'notSet',style:'width : 100%;',items:[[D.notSet,'notSet'],[E.targetFrame,'frame'],[E.targetPopup,'popup'],[D.targetNew,'_blank'],[D.targetTop,'_top'],[D.targetSelf,'_self'],[D.targetParent,'_parent']],onChange:c,setup:function(F){if(F.target)this.setValue(F.target.type||'notSet');c.call(this);},commit:function(F){if(!F.target)F.target={};
F.target.type=this.getValue();}},{type:'text',id:'linkTargetName',label:E.targetFrameName,'default':'',setup:function(F){if(F.target)this.setValue(F.target.name);},commit:function(F){if(!F.target)F.target={};F.target.name=this.getValue().replace(/\W/gi,'');}}]},{type:'vbox',width:'100%',align:'center',padding:2,id:'popupFeatures',children:[{type:'fieldset',label:E.popupFeatures,children:[{type:'hbox',children:[{type:'checkbox',id:'resizable',label:E.popupResizable,setup:r,commit:u},{type:'checkbox',id:'status',label:E.popupStatusBar,setup:r,commit:u}]},{type:'hbox',children:[{type:'checkbox',id:'location',label:E.popupLocationBar,setup:r,commit:u},{type:'checkbox',id:'toolbar',label:E.popupToolbar,setup:r,commit:u}]},{type:'hbox',children:[{type:'checkbox',id:'menubar',label:E.popupMenuBar,setup:r,commit:u},{type:'checkbox',id:'fullscreen',label:E.popupFullScreen,setup:r,commit:u}]},{type:'hbox',children:[{type:'checkbox',id:'scrollbars',label:E.popupScrollBars,setup:r,commit:u},{type:'checkbox',id:'dependent',label:E.popupDependent,setup:r,commit:u}]},{type:'hbox',children:[{type:'text',widths:['50%','50%'],labelLayout:'horizontal',label:D.width,id:'width',setup:r,commit:u},{type:'text',labelLayout:'horizontal',widths:['50%','50%'],label:E.popupLeft,id:'left',setup:r,commit:u}]},{type:'hbox',children:[{type:'text',labelLayout:'horizontal',widths:['50%','50%'],label:D.height,id:'height',setup:r,commit:u},{type:'text',labelLayout:'horizontal',label:E.popupTop,widths:['50%','50%'],id:'top',setup:r,commit:u}]}]}]}]},{id:'upload',label:E.upload,title:E.upload,hidden:true,filebrowser:'uploadButton',elements:[{type:'file',id:'upload',label:D.upload,style:'height:40px',size:29},{type:'fileButton',id:'uploadButton',label:D.uploadSubmit,filebrowser:'info:url','for':['upload','upload']}]},{id:'advanced',label:E.advanced,title:E.advanced,elements:[{type:'vbox',padding:1,children:[{type:'hbox',widths:['45%','35%','20%'],children:[{type:'text',id:'advId',label:E.id,setup:s,commit:v},{type:'select',id:'advLangDir',label:E.langDir,'default':'',style:'width:110px',items:[[D.notSet,''],[E.langDirLTR,'ltr'],[E.langDirRTL,'rtl']],setup:s,commit:v},{type:'text',id:'advAccessKey',width:'80px',label:E.acccessKey,maxLength:1,setup:s,commit:v}]},{type:'hbox',widths:['45%','35%','20%'],children:[{type:'text',label:E.name,id:'advName',setup:s,commit:v},{type:'text',label:E.langCode,id:'advLangCode',width:'110px','default':'',setup:s,commit:v},{type:'text',label:E.tabIndex,id:'advTabIndex',width:'80px',maxLength:5,setup:s,commit:v}]}]},{type:'vbox',padding:1,children:[{type:'hbox',widths:['45%','55%'],children:[{type:'text',label:E.advisoryTitle,'default':'',id:'advTitle',setup:s,commit:v},{type:'text',label:E.advisoryContentType,'default':'',id:'advContentType',setup:s,commit:v}]},{type:'hbox',widths:['45%','55%'],children:[{type:'text',label:E.cssClasses,'default':'',id:'advCSSClasses',setup:s,commit:v},{type:'text',label:E.charset,'default':'',id:'advCharset',setup:s,commit:v}]},{type:'hbox',widths:['45%','55%'],children:[{type:'text',label:E.rel,'default':'',id:'advRel',setup:s,commit:v},{type:'text',label:E.styles,'default':'',id:'advStyles',validate:CKEDITOR.dialog.validate.inlineStyle(a.lang.common.invalidInlineStyle),setup:s,commit:v}]}]}]}],onShow:function(){var F=this.getParentEditor(),G=F.getSelection(),H=null;
if((H=b.getSelectedLink(F))&&H.hasAttribute('href'))G.selectElement(H);else H=null;this.setupContent(p.apply(this,[F,H]));},onOk:function(){var F={},G=[],H={},I=this,J=this.getParentEditor();this.commitContent(H);switch(H.type||'url'){case 'url':var K=H.url&&H.url.protocol!=undefined?H.url.protocol:'http://',L=H.url&&CKEDITOR.tools.trim(H.url.url)||'';F['data-cke-saved-href']=L.indexOf('/')===0?L:K+L;break;case 'anchor':var M=H.anchor&&H.anchor.name,N=H.anchor&&H.anchor.id;F['data-cke-saved-href']='#'+(M||N||'');break;case 'email':var O,P=H.email,Q=P.address;switch(y){case '':case 'encode':var R=encodeURIComponent(P.subject||''),S=encodeURIComponent(P.body||''),T=[];R&&T.push('subject='+R);S&&T.push('body='+S);T=T.length?'?'+T.join('&'):'';if(y=='encode'){O=["javascript:void(location.href='mailto:'+",B(Q)];T&&O.push("+'",x(T),"'");O.push(')');}else O=['mailto:',Q,T];break;default:var U=Q.split('@',2);P.name=U[0];P.domain=U[1];O=['javascript:',A(P)];}F['data-cke-saved-href']=O.join('');break;}if(H.target)if(H.target.type=='popup'){var V=["window.open(this.href, '",H.target.name||'',"', '"],W=['resizable','status','location','toolbar','menubar','fullscreen','scrollbars','dependent'],X=W.length,Y=function(ai){if(H.target[ai])W.push(ai+'='+H.target[ai]);};for(var Z=0;Z<X;Z++)W[Z]=W[Z]+(H.target[W[Z]]?'=yes':'=no');Y('width');Y('left');Y('height');Y('top');V.push(W.join(','),"'); return false;");F['data-cke-pa-onclick']=V.join('');G.push('target');}else{if(H.target.type!='notSet'&&H.target.name)F.target=H.target.name;else G.push('target');G.push('data-cke-pa-onclick','onclick');}if(H.adv){var aa=function(ai,aj){var ak=H.adv[ai];if(ak)F[aj]=ak;else G.push(aj);};aa('advId','id');aa('advLangDir','dir');aa('advAccessKey','accessKey');if(H.adv.advName)F.name=F['data-cke-saved-name']=H.adv.advName;else G=G.concat(['data-cke-saved-name','name']);aa('advLangCode','lang');aa('advTabIndex','tabindex');aa('advTitle','title');aa('advContentType','type');aa('advCSSClasses','class');aa('advCharset','charset');aa('advStyles','style');aa('advRel','rel');}F.href=F['data-cke-saved-href'];if(!this._.selectedElement){var ab=J.getSelection(),ac=ab.getRanges(true);if(ac.length==1&&ac[0].collapsed){var ad=new CKEDITOR.dom.text(H.type=='email'?H.email.address:F['data-cke-saved-href'],J.document);ac[0].insertNode(ad);ac[0].selectNodeContents(ad);ab.selectRanges(ac);}var ae=new CKEDITOR.style({element:'a',attributes:F});ae.type=CKEDITOR.STYLE_INLINE;ae.apply(J.document);}else{var af=this._.selectedElement,ag=af.data('cke-saved-href'),ah=af.getHtml();
af.setAttributes(F);af.removeAttributes(G);if(H.adv&&H.adv.advName&&CKEDITOR.plugins.link.synAnchorSelector)af.addClass(af.getChildCount()?'cke_anchor':'cke_anchor_empty');if(ag==ah||H.type=='email'&&ah.indexOf('@')!=-1)af.setHtml(H.type=='email'?H.email.address:F['data-cke-saved-href']);delete this._.selectedElement;}},onLoad:function(){if(!a.config.linkShowAdvancedTab)this.hidePage('advanced');if(!a.config.linkShowTargetTab)this.hidePage('target');},onFocus:function(){var F=this.getContentElement('info','linkType'),G;if(F&&F.getValue()=='url'){G=this.getContentElement('info','url');G.select();}}};}); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/plugins/link/dialogs/link.js | link.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add('textfield',function(a){var b={value:1,size:1,maxLength:1},c={text:1,password:1};return{title:a.lang.textfield.title,minWidth:350,minHeight:150,onShow:function(){var e=this;delete e.textField;var d=e.getParentEditor().getSelection().getSelectedElement();if(d&&d.getName()=='input'&&(c[d.getAttribute('type')]||!d.getAttribute('type'))){e.textField=d;e.setupContent(d);}},onOk:function(){var d,e=this.textField,f=!e;if(f){d=this.getParentEditor();e=d.document.createElement('input');e.setAttribute('type','text');}if(f)d.insertElement(e);this.commitContent({element:e});},onLoad:function(){var d=function(f){var g=f.hasAttribute(this.id)&&f.getAttribute(this.id);this.setValue(g||'');},e=function(f){var g=f.element,h=this.getValue();if(h)g.setAttribute(this.id,h);else g.removeAttribute(this.id);};this.foreach(function(f){if(b[f.id]){f.setup=d;f.commit=e;}});},contents:[{id:'info',label:a.lang.textfield.title,title:a.lang.textfield.title,elements:[{type:'hbox',widths:['50%','50%'],children:[{id:'_cke_saved_name',type:'text',label:a.lang.textfield.name,'default':'',accessKey:'N',setup:function(d){this.setValue(d.data('cke-saved-name')||d.getAttribute('name')||'');},commit:function(d){var e=d.element;if(this.getValue())e.data('cke-saved-name',this.getValue());else{e.data('cke-saved-name',false);e.removeAttribute('name');}}},{id:'value',type:'text',label:a.lang.textfield.value,'default':'',accessKey:'V'}]},{type:'hbox',widths:['50%','50%'],children:[{id:'size',type:'text',label:a.lang.textfield.charWidth,'default':'',accessKey:'C',style:'width:50px',validate:CKEDITOR.dialog.validate.integer(a.lang.common.validateNumberFailed)},{id:'maxLength',type:'text',label:a.lang.textfield.maxChars,'default':'',accessKey:'M',style:'width:50px',validate:CKEDITOR.dialog.validate.integer(a.lang.common.validateNumberFailed)}],onLoad:function(){if(CKEDITOR.env.ie7Compat)this.getElement().setStyle('zoom','100%');}},{id:'type',type:'select',label:a.lang.textfield.type,'default':'text',accessKey:'M',items:[[a.lang.textfield.typeText,'text'],[a.lang.textfield.typePass,'password']],setup:function(d){this.setValue(d.getAttribute('type'));},commit:function(d){var e=d.element;if(CKEDITOR.env.ie){var f=e.getAttribute('type'),g=this.getValue();if(f!=g){var h=CKEDITOR.dom.element.createFromHtml('<input type="'+g+'"></input>',a.document);e.copyAttributes(h,{type:1});h.replace(e);a.getSelection().selectElement(h);d.element=h;}}else e.setAttribute('type',this.getValue());}}]}]};}); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/plugins/forms/dialogs/textfield.js | textfield.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add('checkbox',function(a){return{title:a.lang.checkboxAndRadio.checkboxTitle,minWidth:350,minHeight:140,onShow:function(){var c=this;delete c.checkbox;var b=c.getParentEditor().getSelection().getSelectedElement();if(b&&b.getAttribute('type')=='checkbox'){c.checkbox=b;c.setupContent(b);}},onOk:function(){var b,c=this.checkbox,d=!c;if(d){b=this.getParentEditor();c=b.document.createElement('input');c.setAttribute('type','checkbox');b.insertElement(c);}this.commitContent({element:c});},contents:[{id:'info',label:a.lang.checkboxAndRadio.checkboxTitle,title:a.lang.checkboxAndRadio.checkboxTitle,startupFocus:'txtName',elements:[{id:'txtName',type:'text',label:a.lang.common.name,'default':'',accessKey:'N',setup:function(b){this.setValue(b.data('cke-saved-name')||b.getAttribute('name')||'');},commit:function(b){var c=b.element;if(this.getValue())c.data('cke-saved-name',this.getValue());else{c.data('cke-saved-name',false);c.removeAttribute('name');}}},{id:'txtValue',type:'text',label:a.lang.checkboxAndRadio.value,'default':'',accessKey:'V',setup:function(b){var c=b.getAttribute('value');this.setValue(CKEDITOR.env.ie&&c=='on'?'':c);},commit:function(b){var c=b.element,d=this.getValue();if(d&&!(CKEDITOR.env.ie&&d=='on'))c.setAttribute('value',d);else if(CKEDITOR.env.ie){var e=new CKEDITOR.dom.element('input',c.getDocument());c.copyAttributes(e,{value:1});e.replace(c);a.getSelection().selectElement(e);b.element=e;}else c.removeAttribute('value');}},{id:'cmbSelected',type:'checkbox',label:a.lang.checkboxAndRadio.selected,'default':'',accessKey:'S',value:'checked',setup:function(b){this.setValue(b.getAttribute('checked'));},commit:function(b){var c=b.element;if(CKEDITOR.env.ie){var d=!!c.getAttribute('checked'),e=!!this.getValue();if(d!=e){var f=CKEDITOR.dom.element.createFromHtml('<input type="checkbox"'+(e?' checked="checked"':'')+'/>',a.document);c.copyAttributes(f,{type:1,checked:1});f.replace(c);a.getSelection().selectElement(f);b.element=f;}}else{var g=this.getValue();if(g)c.setAttribute('checked','checked');else c.removeAttribute('checked');}}}]}]};}); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/plugins/forms/dialogs/checkbox.js | checkbox.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add('form',function(a){var b={action:1,id:1,method:1,enctype:1,target:1};return{title:a.lang.form.title,minWidth:350,minHeight:200,onShow:function(){var e=this;delete e.form;var c=e.getParentEditor().getSelection().getStartElement(),d=c&&c.getAscendant('form',true);if(d){e.form=d;e.setupContent(d);}},onOk:function(){var c,d=this.form,e=!d;if(e){c=this.getParentEditor();d=c.document.createElement('form');!CKEDITOR.env.ie&&d.append(c.document.createElement('br'));}if(e)c.insertElement(d);this.commitContent(d);},onLoad:function(){function c(e){this.setValue(e.getAttribute(this.id)||'');};function d(e){var f=this;if(f.getValue())e.setAttribute(f.id,f.getValue());else e.removeAttribute(f.id);};this.foreach(function(e){if(b[e.id]){e.setup=c;e.commit=d;}});},contents:[{id:'info',label:a.lang.form.title,title:a.lang.form.title,elements:[{id:'txtName',type:'text',label:a.lang.common.name,'default':'',accessKey:'N',setup:function(c){this.setValue(c.data('cke-saved-name')||c.getAttribute('name')||'');},commit:function(c){if(this.getValue())c.data('cke-saved-name',this.getValue());else{c.data('cke-saved-name',false);c.removeAttribute('name');}}},{id:'action',type:'text',label:a.lang.form.action,'default':'',accessKey:'T'},{type:'hbox',widths:['45%','55%'],children:[{id:'id',type:'text',label:a.lang.common.id,'default':'',accessKey:'I'},{id:'enctype',type:'select',label:a.lang.form.encoding,style:'width:100%',accessKey:'E','default':'',items:[[''],['text/plain'],['multipart/form-data'],['application/x-www-form-urlencoded']]}]},{type:'hbox',widths:['45%','55%'],children:[{id:'target',type:'select',label:a.lang.common.target,style:'width:100%',accessKey:'M','default':'',items:[[a.lang.common.notSet,''],[a.lang.common.targetNew,'_blank'],[a.lang.common.targetTop,'_top'],[a.lang.common.targetSelf,'_self'],[a.lang.common.targetParent,'_parent']]},{id:'method',type:'select',label:a.lang.form.method,accessKey:'M','default':'GET',items:[['GET','get'],['POST','post']]}]}]}]};}); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/plugins/forms/dialogs/form.js | form.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add('select',function(a){function b(k,l,m,n,o){k=j(k);var p;if(n)p=n.createElement('OPTION');else p=document.createElement('OPTION');if(k&&p&&p.getName()=='option'){if(CKEDITOR.env.ie){if(!isNaN(parseInt(o,10)))k.$.options.add(p.$,o);else k.$.options.add(p.$);p.$.innerHTML=l.length>0?l:'';p.$.value=m;}else{if(o!==null&&o<k.getChildCount())k.getChild(o<0?0:o).insertBeforeMe(p);else k.append(p);p.setText(l.length>0?l:'');p.setValue(m);}}else return false;return p;};function c(k){k=j(k);var l=g(k);for(var m=k.getChildren().count()-1;m>=0;m--){if(k.getChild(m).$.selected)k.getChild(m).remove();}h(k,l);};function d(k,l,m,n){k=j(k);if(l<0)return false;var o=k.getChild(l);o.setText(m);o.setValue(n);return o;};function e(k){k=j(k);while(k.getChild(0)&&k.getChild(0).remove()){}};function f(k,l,m){k=j(k);var n=g(k);if(n<0)return false;var o=n+l;o=o<0?0:o;o=o>=k.getChildCount()?k.getChildCount()-1:o;if(n==o)return false;var p=k.getChild(n),q=p.getText(),r=p.getValue();p.remove();p=b(k,q,r,!m?null:m,o);h(k,o);return p;};function g(k){k=j(k);return k?k.$.selectedIndex:-1;};function h(k,l){k=j(k);if(l<0)return null;var m=k.getChildren().count();k.$.selectedIndex=l>=m?m-1:l;return k;};function i(k){k=j(k);return k?k.getChildren():false;};function j(k){if(k&&k.domId&&k.getInputElement().$)return k.getInputElement();else if(k&&k.$)return k;return false;};return{title:a.lang.select.title,minWidth:CKEDITOR.env.ie?460:395,minHeight:CKEDITOR.env.ie?320:300,onShow:function(){var n=this;delete n.selectBox;n.setupContent('clear');var k=n.getParentEditor().getSelection().getSelectedElement();if(k&&k.getName()=='select'){n.selectBox=k;n.setupContent(k.getName(),k);var l=i(k);for(var m=0;m<l.count();m++)n.setupContent('option',l.getItem(m));}},onOk:function(){var k=this.getParentEditor(),l=this.selectBox,m=!l;if(m)l=k.document.createElement('select');this.commitContent(l);if(m){k.insertElement(l);if(CKEDITOR.env.ie){var n=k.getSelection(),o=n.createBookmarks();setTimeout(function(){n.selectBookmarks(o);},0);}}},contents:[{id:'info',label:a.lang.select.selectInfo,title:a.lang.select.selectInfo,accessKey:'',elements:[{id:'txtName',type:'text',widths:['25%','75%'],labelLayout:'horizontal',label:a.lang.common.name,'default':'',accessKey:'N',style:'width:350px',setup:function(k,l){if(k=='clear')this.setValue(this['default']||'');else if(k=='select')this.setValue(l.data('cke-saved-name')||l.getAttribute('name')||'');},commit:function(k){if(this.getValue())k.data('cke-saved-name',this.getValue());
else{k.data('cke-saved-name',false);k.removeAttribute('name');}}},{id:'txtValue',type:'text',widths:['25%','75%'],labelLayout:'horizontal',label:a.lang.select.value,style:'width:350px','default':'',className:'cke_disabled',onLoad:function(){this.getInputElement().setAttribute('readOnly',true);},setup:function(k,l){if(k=='clear')this.setValue('');else if(k=='option'&&l.getAttribute('selected'))this.setValue(l.$.value);}},{type:'hbox',widths:['175px','170px'],children:[{id:'txtSize',type:'text',labelLayout:'horizontal',label:a.lang.select.size,'default':'',accessKey:'S',style:'width:175px',validate:function(){var k=CKEDITOR.dialog.validate.integer(a.lang.common.validateNumberFailed);return this.getValue()===''||k.apply(this);},setup:function(k,l){if(k=='select')this.setValue(l.getAttribute('size')||'');if(CKEDITOR.env.webkit)this.getInputElement().setStyle('width','86px');},commit:function(k){if(this.getValue())k.setAttribute('size',this.getValue());else k.removeAttribute('size');}},{type:'html',html:'<span>'+CKEDITOR.tools.htmlEncode(a.lang.select.lines)+'</span>'}]},{type:'html',html:'<span>'+CKEDITOR.tools.htmlEncode(a.lang.select.opAvail)+'</span>'},{type:'hbox',widths:['115px','115px','100px'],children:[{type:'vbox',children:[{id:'txtOptName',type:'text',label:a.lang.select.opText,style:'width:115px',setup:function(k,l){if(k=='clear')this.setValue('');}},{type:'select',id:'cmbName',label:'',title:'',size:5,style:'width:115px;height:75px',items:[],onChange:function(){var k=this.getDialog(),l=k.getContentElement('info','cmbValue'),m=k.getContentElement('info','txtOptName'),n=k.getContentElement('info','txtOptValue'),o=g(this);h(l,o);m.setValue(this.getValue());n.setValue(l.getValue());},setup:function(k,l){if(k=='clear')e(this);else if(k=='option')b(this,l.getText(),l.getText(),this.getDialog().getParentEditor().document);},commit:function(k){var l=this.getDialog(),m=i(this),n=i(l.getContentElement('info','cmbValue')),o=l.getContentElement('info','txtValue').getValue();e(k);for(var p=0;p<m.count();p++){var q=b(k,m.getItem(p).getValue(),n.getItem(p).getValue(),l.getParentEditor().document);if(n.getItem(p).getValue()==o){q.setAttribute('selected','selected');q.selected=true;}}}}]},{type:'vbox',children:[{id:'txtOptValue',type:'text',label:a.lang.select.opValue,style:'width:115px',setup:function(k,l){if(k=='clear')this.setValue('');}},{type:'select',id:'cmbValue',label:'',size:5,style:'width:115px;height:75px',items:[],onChange:function(){var k=this.getDialog(),l=k.getContentElement('info','cmbName'),m=k.getContentElement('info','txtOptName'),n=k.getContentElement('info','txtOptValue'),o=g(this);
h(l,o);m.setValue(l.getValue());n.setValue(this.getValue());},setup:function(k,l){var n=this;if(k=='clear')e(n);else if(k=='option'){var m=l.getValue();b(n,m,m,n.getDialog().getParentEditor().document);if(l.getAttribute('selected')=='selected')n.getDialog().getContentElement('info','txtValue').setValue(m);}}}]},{type:'vbox',padding:5,children:[{type:'button',id:'btnAdd',style:'',label:a.lang.select.btnAdd,title:a.lang.select.btnAdd,style:'width:100%;',onClick:function(){var k=this.getDialog(),l=k.getParentEditor(),m=k.getContentElement('info','txtOptName'),n=k.getContentElement('info','txtOptValue'),o=k.getContentElement('info','cmbName'),p=k.getContentElement('info','cmbValue');b(o,m.getValue(),m.getValue(),k.getParentEditor().document);b(p,n.getValue(),n.getValue(),k.getParentEditor().document);m.setValue('');n.setValue('');}},{type:'button',id:'btnModify',label:a.lang.select.btnModify,title:a.lang.select.btnModify,style:'width:100%;',onClick:function(){var k=this.getDialog(),l=k.getContentElement('info','txtOptName'),m=k.getContentElement('info','txtOptValue'),n=k.getContentElement('info','cmbName'),o=k.getContentElement('info','cmbValue'),p=g(n);if(p>=0){d(n,p,l.getValue(),l.getValue());d(o,p,m.getValue(),m.getValue());}}},{type:'button',id:'btnUp',style:'width:100%;',label:a.lang.select.btnUp,title:a.lang.select.btnUp,onClick:function(){var k=this.getDialog(),l=k.getContentElement('info','cmbName'),m=k.getContentElement('info','cmbValue');f(l,-1,k.getParentEditor().document);f(m,-1,k.getParentEditor().document);}},{type:'button',id:'btnDown',style:'width:100%;',label:a.lang.select.btnDown,title:a.lang.select.btnDown,onClick:function(){var k=this.getDialog(),l=k.getContentElement('info','cmbName'),m=k.getContentElement('info','cmbValue');f(l,1,k.getParentEditor().document);f(m,1,k.getParentEditor().document);}}]}]},{type:'hbox',widths:['40%','20%','40%'],children:[{type:'button',id:'btnSetValue',label:a.lang.select.btnSetValue,title:a.lang.select.btnSetValue,onClick:function(){var k=this.getDialog(),l=k.getContentElement('info','cmbValue'),m=k.getContentElement('info','txtValue');m.setValue(l.getValue());}},{type:'button',id:'btnDelete',label:a.lang.select.btnDelete,title:a.lang.select.btnDelete,onClick:function(){var k=this.getDialog(),l=k.getContentElement('info','cmbName'),m=k.getContentElement('info','cmbValue'),n=k.getContentElement('info','txtOptName'),o=k.getContentElement('info','txtOptValue');c(l);c(m);n.setValue('');o.setValue('');}},{id:'chkMulti',type:'checkbox',label:a.lang.select.chkMulti,'default':'',accessKey:'M',value:'checked',setup:function(k,l){if(k=='select')this.setValue(l.getAttribute('multiple'));
if(CKEDITOR.env.webkit)this.getElement().getParent().setStyle('vertical-align','middle');},commit:function(k){if(this.getValue())k.setAttribute('multiple',this.getValue());else k.removeAttribute('multiple');}}]}]}]};}); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/plugins/forms/dialogs/select.js | select.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add('radio',function(a){return{title:a.lang.checkboxAndRadio.radioTitle,minWidth:350,minHeight:140,onShow:function(){var c=this;delete c.radioButton;var b=c.getParentEditor().getSelection().getSelectedElement();if(b&&b.getName()=='input'&&b.getAttribute('type')=='radio'){c.radioButton=b;c.setupContent(b);}},onOk:function(){var b,c=this.radioButton,d=!c;if(d){b=this.getParentEditor();c=b.document.createElement('input');c.setAttribute('type','radio');}if(d)b.insertElement(c);this.commitContent({element:c});},contents:[{id:'info',label:a.lang.checkboxAndRadio.radioTitle,title:a.lang.checkboxAndRadio.radioTitle,elements:[{id:'name',type:'text',label:a.lang.common.name,'default':'',accessKey:'N',setup:function(b){this.setValue(b.data('cke-saved-name')||b.getAttribute('name')||'');},commit:function(b){var c=b.element;if(this.getValue())c.data('cke-saved-name',this.getValue());else{c.data('cke-saved-name',false);c.removeAttribute('name');}}},{id:'value',type:'text',label:a.lang.checkboxAndRadio.value,'default':'',accessKey:'V',setup:function(b){this.setValue(b.getAttribute('value')||'');},commit:function(b){var c=b.element;if(this.getValue())c.setAttribute('value',this.getValue());else c.removeAttribute('value');}},{id:'checked',type:'checkbox',label:a.lang.checkboxAndRadio.selected,'default':'',accessKey:'S',value:'checked',setup:function(b){this.setValue(b.getAttribute('checked'));},commit:function(b){var c=b.element;if(!(CKEDITOR.env.ie||CKEDITOR.env.opera)){if(this.getValue())c.setAttribute('checked','checked');else c.removeAttribute('checked');}else{var d=c.getAttribute('checked'),e=!!this.getValue();if(d!=e){var f=CKEDITOR.dom.element.createFromHtml('<input type="radio"'+(e?' checked="checked"':'')+'></input>',a.document);c.copyAttributes(f,{type:1,checked:1});f.replace(c);a.getSelection().selectElement(f);b.element=f;}}}}]}]};}); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/plugins/forms/dialogs/radio.js | radio.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function(){var a=CKEDITOR.document;CKEDITOR.dialog.add('templates',function(b){function c(k,l){k.setHtml('');for(var m=0,n=l.length;m<n;m++){var o=CKEDITOR.getTemplates(l[m]),p=o.imagesPath,q=o.templates,r=q.length;for(var s=0;s<r;s++){var t=q[s],u=d(t,p);u.setAttribute('aria-posinset',s+1);u.setAttribute('aria-setsize',r);k.append(u);}}};function d(k,l){var m=CKEDITOR.dom.element.createFromHtml('<a href="javascript:void(0)" tabIndex="-1" role="option" ><div class="cke_tpl_item"></div></a>'),n='<table style="width:350px;" class="cke_tpl_preview" role="presentation"><tr>';if(k.image&&l)n+='<td class="cke_tpl_preview_img"><img src="'+CKEDITOR.getUrl(l+k.image)+'"'+(CKEDITOR.env.ie6Compat?' onload="this.width=this.width"':'')+' alt="" title=""></td>';n+='<td style="white-space:normal;"><span class="cke_tpl_title">'+k.title+'</span><br/>';if(k.description)n+='<span>'+k.description+'</span>';n+='</td></tr></table>';m.getFirst().setHtml(n);m.on('click',function(){e(k.html);});return m;};function e(k){var l=CKEDITOR.dialog.getCurrent(),m=l.getValueOf('selectTpl','chkInsertOpt');if(m){b.on('contentDom',function(n){n.removeListener();l.hide();var o=new CKEDITOR.dom.range(b.document);o.moveToElementEditStart(b.document.getBody());o.select(1);setTimeout(function(){b.fire('saveSnapshot');},0);});b.fire('saveSnapshot');b.setData(k);}else{b.insertHtml(k);l.hide();}};function f(k){var l=k.data.getTarget(),m=g.equals(l);if(m||g.contains(l)){var n=k.data.getKeystroke(),o=g.getElementsByTag('a'),p;if(o){if(m)p=o.getItem(0);else switch(n){case 40:p=l.getNext();break;case 38:p=l.getPrevious();break;case 13:case 32:l.fire('click');}if(p){p.focus();k.data.preventDefault();}}}};CKEDITOR.skins.load(b,'templates');var g,h='cke_tpl_list_label_'+CKEDITOR.tools.getNextNumber(),i=b.lang.templates,j=b.config;return{title:b.lang.templates.title,minWidth:CKEDITOR.env.ie?440:400,minHeight:340,contents:[{id:'selectTpl',label:i.title,elements:[{type:'vbox',padding:5,children:[{id:'selectTplText',type:'html',html:'<span>'+i.selectPromptMsg+'</span>'},{id:'templatesList',type:'html',focus:true,html:'<div class="cke_tpl_list" tabIndex="-1" role="listbox" aria-labelledby="'+h+'">'+'<div class="cke_tpl_loading"><span></span></div>'+'</div>'+'<span class="cke_voice_label" id="'+h+'">'+i.options+'</span>'},{id:'chkInsertOpt',type:'checkbox',label:i.insertOption,'default':j.templates_replaceContent}]}]}],buttons:[CKEDITOR.dialog.cancelButton],onShow:function(){var k=this.getContentElement('selectTpl','templatesList');
g=k.getElement();CKEDITOR.loadTemplates(j.templates_files,function(){var l=(j.templates||'default').split(',');if(l.length){c(g,l);k.focus();}else g.setHtml('<div class="cke_tpl_empty"><span>'+i.emptyListMsg+'</span>'+'</div>');});this._.element.on('keydown',f);},onHide:function(){this._.element.removeListener('keydown',f);}};});})(); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/plugins/templates/dialogs/templates.js | templates.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function(){CKEDITOR.on('dialogDefinition',function(r){var s,t=r.data.name,u=r.data.definition;if(t=='link'){u.removeContents('target');u.removeContents('upload');u.removeContents('advanced');s=u.getContents('info');s.remove('emailSubject');s.remove('emailBody');}else if(t=='image'){u.removeContents('advanced');s=u.getContents('Link');s.remove('cmbTarget');s=u.getContents('info');s.remove('txtAlt');s.remove('basic');}});var a={b:'strong',u:'u',i:'em',color:'span',size:'span',quote:'blockquote',code:'code',url:'a',email:'span',img:'span','*':'li',list:'ol'},b={strong:'b',b:'b',u:'u',em:'i',i:'i',code:'code',li:'*'},c={strong:'b',em:'i',u:'u',li:'*',ul:'list',ol:'list',code:'code',a:'link',img:'img',blockquote:'quote'},d={color:'color',size:'font-size'},e={url:'href',email:'mailhref',quote:'cite',list:'listType'},f=CKEDITOR.dtd,g=CKEDITOR.tools.extend({table:1},f.$block,f.$listItem,f.$tableContent,f.$list),h=/\s*(?:;\s*|$)/;function i(r){var s='';for(var t in r){var u=r[t],v=(t+':'+u).replace(h,';');s+=v;}return s;};function j(r){var s={};(r||'').replace(/"/g,'"').replace(/\s*([^ :;]+)\s*:\s*([^;]+)\s*(?=;|$)/g,function(t,u,v){s[u.toLowerCase()]=v;});return s;};function k(r){return r.replace(/(?:rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\))/gi,function(s,t,u,v){t=parseInt(t,10).toString(16);u=parseInt(u,10).toString(16);v=parseInt(v,10).toString(16);var w=[t,u,v];for(var x=0;x<w.length;x++)w[x]=String('0'+w[x]).slice(-2);return '#'+w.join('');});};var l={smiley:':)',sad:':(',wink:';)',laugh:':D',cheeky:':P',blush:':*)',surprise:':-o',indecision:':|',angry:'>:(',angel:'o:)',cool:'8-)',devil:'>:-)',crying:';(',kiss:':-*'},m={},n=[];for(var o in l){m[l[o]]=o;n.push(l[o].replace(/\(|\)|\:|\/|\*|\-|\|/g,function(r){return '\\'+r;}));}n=new RegExp(n.join('|'),'g');var p=(function(){var r=[],s={nbsp:'\xa0',shy:'',gt:'>',lt:'<'};for(var t in s)r.push(t);r=new RegExp('&('+r.join('|')+');','g');return function(u){return u.replace(r,function(v,w){return s[w];});};})();CKEDITOR.BBCodeParser=function(){this._={bbcPartsRegex:/(?:\[([^\/\]=]*?)(?:=([^\]]*?))?\])|(?:\[\/([a-z]{1,16})\])/ig};};CKEDITOR.BBCodeParser.prototype={parse:function(r){var B=this;var s,t,u=0;while(s=B._.bbcPartsRegex.exec(r)){var v=s.index;if(v>u){var w=r.substring(u,v);B.onText(w,1);}u=B._.bbcPartsRegex.lastIndex;t=(s[1]||s[3]||'').toLowerCase();if(t&&!a[t]){B.onText(s[0]);continue;}if(s[1]){var x=a[t],y={},z={},A=s[2];if(A){if(t=='list')if(!isNaN(A))A='decimal';else if(/^[a-z]+$/.test(A))A='lower-alpha';
else if(/^[A-Z]+$/.test(A))A='upper-alpha';if(d[t]){if(t=='size')A+='%';z[d[t]]=A;y.style=i(z);}else if(e[t])y[e[t]]=A;}if(t=='email'||t=='img')y.bbcode=t;B.onTagOpen(x,y,CKEDITOR.dtd.$empty[x]);}else if(s[3])B.onTagClose(a[t]);}if(r.length>u)B.onText(r.substring(u,r.length),1);}};CKEDITOR.htmlParser.fragment.fromBBCode=function(r){var s=new CKEDITOR.BBCodeParser(),t=new CKEDITOR.htmlParser.fragment(),u=[],v=0,w=t,x;function y(D){if(u.length>0)for(var E=0;E<u.length;E++){var F=u[E],G=F.name,H=CKEDITOR.dtd[G],I=w.name&&CKEDITOR.dtd[w.name];if((!I||I[G])&&(!D||!H||H[D]||!CKEDITOR.dtd[D])){F=F.clone();F.parent=w;w=F;u.splice(E,1);E--;}}};function z(D,E){var F=w.children.length,G=F>0&&w.children[F-1],H=!G&&q.getRule(c[w.name],'breakAfterOpen'),I=G&&G.type==CKEDITOR.NODE_ELEMENT&&q.getRule(c[G.name],'breakAfterClose'),J=D&&q.getRule(c[D],E?'breakBeforeClose':'breakBeforeOpen');if(v&&(H||I||J))v--;if(v&&D in g)v++;while(v&&v--)w.children.push(G=new CKEDITOR.htmlParser.element('br'));};function A(D,E){z(D.name,1);E=E||w||t;var F=E.children.length,G=F>0&&E.children[F-1]||null;D.previous=G;D.parent=E;E.children.push(D);if(D.returnPoint){w=D.returnPoint;delete D.returnPoint;}};s.onTagOpen=function(D,E,F){var G=new CKEDITOR.htmlParser.element(D,E);if(CKEDITOR.dtd.$removeEmpty[D]){u.push(G);return;}var H=w.name,I=H&&(CKEDITOR.dtd[H]||(w._.isBlockLike?CKEDITOR.dtd.div:CKEDITOR.dtd.span));if(I&&!I[D]){var J=false,K;if(D==H)A(w,w.parent);else if(D in CKEDITOR.dtd.$listItem){s.onTagOpen('ul',{});K=w;J=true;}else{A(w,w.parent);u.unshift(w);J=true;}if(K)w=K;else w=w.returnPoint||w.parent;if(J){s.onTagOpen.apply(this,arguments);return;}}y(D);z(D);G.parent=w;G.returnPoint=x;x=0;if(G.isEmpty)A(G);else w=G;};s.onTagClose=function(D){for(var E=u.length-1;E>=0;E--){if(D==u[E].name){u.splice(E,1);return;}}var F=[],G=[],H=w;while(H.type&&H.name!=D){if(!H._.isBlockLike)G.unshift(H);F.push(H);H=H.parent;}if(H.type){for(E=0;E<F.length;E++){var I=F[E];A(I,I.parent);}w=H;A(H,H.parent);if(H==w)w=w.parent;u=u.concat(G);}};s.onText=function(D){var E=CKEDITOR.dtd[w.name];if(!E||E['#']){z();y();D.replace(/([\r\n])|[^\r\n]*/g,function(F,G){if(G!==undefined&&G.length)v++;else if(F.length){var H=0;F.replace(n,function(I,J){A(new CKEDITOR.htmlParser.text(F.substring(H,J)),w);A(new CKEDITOR.htmlParser.element('smiley',{desc:m[I]}),w);H=J+I.length;});if(H!=F.length)A(new CKEDITOR.htmlParser.text(F.substring(H,F.length)),w);}});}};s.parse(CKEDITOR.tools.htmlEncode(r));while(w.type){var B=w.parent,C=w;
A(C,B);w=B;}return t;};CKEDITOR.htmlParser.BBCodeWriter=CKEDITOR.tools.createClass({$:function(){var r=this;r._={output:[],rules:[]};r.setRules('list',{breakBeforeOpen:1,breakAfterOpen:1,breakBeforeClose:1,breakAfterClose:1});r.setRules('*',{breakBeforeOpen:1,breakAfterOpen:0,breakBeforeClose:1,breakAfterClose:0});r.setRules('quote',{breakBeforeOpen:1,breakAfterOpen:0,breakBeforeClose:0,breakAfterClose:1});},proto:{setRules:function(r,s){var t=this._.rules[r];if(t)CKEDITOR.tools.extend(t,s,true);else this._.rules[r]=s;},getRule:function(r,s){return this._.rules[r]&&this._.rules[r][s];},openTag:function(r,s){var u=this;if(r in a){if(u.getRule(r,'breakBeforeOpen'))u.lineBreak(1);u.write('[',r);var t=s.option;t&&u.write('=',t);u.write(']');if(u.getRule(r,'breakAfterOpen'))u.lineBreak(1);}else if(r=='br')u._.output.push('\n');},openTagClose:function(){},attribute:function(){},closeTag:function(r){var s=this;if(r in a){if(s.getRule(r,'breakBeforeClose'))s.lineBreak(1);r!='*'&&s.write('[/',r,']');if(s.getRule(r,'breakAfterClose'))s.lineBreak(1);}},text:function(r){this.write(r);},comment:function(){},lineBreak:function(){var r=this;if(!r._.hasLineBreak&&r._.output.length){r.write('\n');r._.hasLineBreak=1;}},write:function(){this._.hasLineBreak=0;var r=Array.prototype.join.call(arguments,'');this._.output.push(r);},reset:function(){this._.output=[];this._.hasLineBreak=0;},getHtml:function(r){var s=this._.output.join('');if(r)this.reset();return p(s);}}});var q=new CKEDITOR.htmlParser.BBCodeWriter();CKEDITOR.plugins.add('bbcode',{requires:['htmldataprocessor','entities'],beforeInit:function(r){var s=r.config;CKEDITOR.tools.extend(s,{enterMode:CKEDITOR.ENTER_BR,basicEntities:false,entities:false,fillEmptyBlocks:false},true);},init:function(r){var s=r.config;function t(v){var w=CKEDITOR.htmlParser.fragment.fromBBCode(v),x=new CKEDITOR.htmlParser.basicWriter();w.writeHtml(x,u);return x.getHtml(true);};var u=new CKEDITOR.htmlParser.filter();u.addRules({elements:{blockquote:function(v){var w=new CKEDITOR.htmlParser.element('div');w.children=v.children;v.children=[w];var x=v.attributes.cite;if(x){var y=new CKEDITOR.htmlParser.element('cite');y.add(new CKEDITOR.htmlParser.text(x.replace(/^"|"$/g,'')));delete v.attributes.cite;v.children.unshift(y);}},span:function(v){var w;if(w=v.attributes.bbcode){if(w=='img'){v.name='img';v.attributes.src=v.children[0].value;v.children=[];}else if(w=='email'){v.name='a';v.attributes.href='mailto:'+v.children[0].value;}delete v.attributes.bbcode;
}},ol:function(v){if(v.attributes.listType){if(v.attributes.listType!='decimal')v.attributes.style='list-style-type:'+v.attributes.listType;}else v.name='ul';delete v.attributes.listType;},a:function(v){if(!v.attributes.href)v.attributes.href=v.children[0].value;},smiley:function(v){v.name='img';var w=v.attributes.desc,x=s.smiley_images[CKEDITOR.tools.indexOf(s.smiley_descriptions,w)],y=CKEDITOR.tools.htmlEncode(s.smiley_path+x);v.attributes={src:y,'data-cke-saved-src':y,title:w,alt:w};}}});r.dataProcessor.htmlFilter.addRules({elements:{$:function(v){var w=v.attributes,x=j(w.style),y,z=v.name;if(z in b)z=b[z];else if(z=='span'){if(y=x.color){z='color';y=k(y);}else if(y=x['font-size']){var A=y.match(/(\d+)%$/);if(A){y=A[1];z='size';}}}else if(z=='ol'||z=='ul'){if(y=x['list-style-type']){switch(y){case 'lower-alpha':y='a';break;case 'upper-alpha':y='A';break;}}else if(z=='ol')y=1;z='list';}else if(z=='blockquote'){try{var B=v.children[0],C=v.children[1],D=B.name=='cite'&&B.children[0].value;if(D){y='"'+D+'"';v.children=C.children;}}catch(G){}z='quote';}else if(z=='a'){if(y=w.href)if(y.indexOf('mailto:')!==-1){z='email';v.children=[new CKEDITOR.htmlParser.text(y.replace('mailto:',''))];y='';}else{var E=v.children.length==1&&v.children[0];if(E&&E.type==CKEDITOR.NODE_TEXT&&E.value==y)y='';z='url';}}else if(z=='img'){v.isEmpty=0;var F=w['data-cke-saved-src'];if(F&&F.indexOf(r.config.smiley_path)!=-1)return new CKEDITOR.htmlParser.text(l[w.alt]);else v.children=[new CKEDITOR.htmlParser.text(F)];}v.name=z;y&&(v.attributes.option=y);return null;},br:function(v){var w=v.next;if(w&&w.name in g)return false;}}},1);r.dataProcessor.writer=q;r.on('beforeSetMode',function(v){v.removeListener();var w=r._.modes.wysiwyg;w.loadData=CKEDITOR.tools.override(w.loadData,function(x){return function(y){return x.call(this,t(y));};});});},afterInit:function(r){var s;if(r._.elementsPath)if(s=r._.elementsPath.filters)s.push(function(t){var u=t.getName(),v=c[u]||false;if(v=='link'&&t.getAttribute('href').indexOf('mailto:')===0)v='email';else if(u=='span'){if(t.getStyle('font-size'))v='size';else if(t.getStyle('color'))v='color';}else if(v=='img'){var w=t.data('cke-saved-src');if(w&&w.indexOf(r.config.smiley_path)===0)v='smiley';}return v;});}});})(); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/plugins/bbcode/plugin.js | plugin.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function(){var a=CKEDITOR.tools.cssLength,b=CKEDITOR.env.ie&&(CKEDITOR.env.ie7Compat||CKEDITOR.env.quirks||CKEDITOR.env.version<7);function c(k){return CKEDITOR.env.ie?k.$.clientWidth:parseInt(k.getComputedStyle('width'),10);};function d(k,l){var m=k.getComputedStyle('border-'+l+'-width'),n={thin:'0px',medium:'1px',thick:'2px'};if(m.indexOf('px')<0)if(m in n&&k.getComputedStyle('border-style')!='none')m=n[m];else m=0;return parseInt(m,10);};function e(k){var l=k.$.rows,m=0,n,o,p;for(var q=0,r=l.length;q<r;q++){p=l[q];n=p.cells.length;if(n>m){m=n;o=p;}}return o;};function f(k){var l=[],m=-1,n=k.getComputedStyle('direction')=='rtl',o=e(k),p=new CKEDITOR.dom.element(k.$.tBodies[0]),q=p.getDocumentPosition();for(var r=0,s=o.cells.length;r<s;r++){var t=new CKEDITOR.dom.element(o.cells[r]),u=o.cells[r+1]&&new CKEDITOR.dom.element(o.cells[r+1]);m+=t.$.colSpan||1;var v,w,x,y=t.getDocumentPosition().x;n?w=y+d(t,'left'):v=y+t.$.offsetWidth-d(t,'right');if(u){y=u.getDocumentPosition().x;n?v=y+u.$.offsetWidth-d(u,'right'):w=y+d(u,'left');}else{y=k.getDocumentPosition().x;n?v=y:w=y+k.$.offsetWidth;}x=Math.max(w-v,3);l.push({table:k,index:m,x:v,y:q.y,width:x,height:p.$.offsetHeight,rtl:n});}return l;};function g(k,l){for(var m=0,n=k.length;m<n;m++){var o=k[m];if(l>=o.x&&l<=o.x+o.width)return o;}return null;};function h(k){(k.data||k).preventDefault();};function i(k){var l,m,n,o,p,q,r,s,t,u;function v(){l=null;q=0;o=0;m.removeListener('mouseup',A);n.removeListener('mousedown',z);n.removeListener('mousemove',B);m.getBody().setStyle('cursor','auto');b?n.remove():n.hide();};function w(){var D=l.index,E=CKEDITOR.tools.buildTableMap(l.table),F=[],G=[],H=Number.MAX_VALUE,I=H,J=l.rtl;for(var K=0,L=E.length;K<L;K++){var M=E[K],N=M[D+(J?1:0)],O=M[D+(J?0:1)];N=N&&new CKEDITOR.dom.element(N);O=O&&new CKEDITOR.dom.element(O);if(!N||!O||!N.equals(O)){N&&(H=Math.min(H,c(N)));O&&(I=Math.min(I,c(O)));F.push(N);G.push(O);}}r=F;s=G;t=l.x-H;u=l.x+I;n.setOpacity(0.5);p=parseInt(n.getStyle('left'),10);q=0;o=1;n.on('mousemove',B);m.on('dragstart',h);};function x(){o=0;n.setOpacity(0);q&&y();var D=l.table;setTimeout(function(){D.removeCustomData('_cke_table_pillars');},0);m.removeListener('dragstart',h);};function y(){var D=l.rtl,E=D?s.length:r.length;for(var F=0;F<E;F++){var G=r[F],H=s[F],I=l.table;CKEDITOR.tools.setTimeout(function(J,K,L,M,N,O){J&&J.setStyle('width',a(Math.max(K+O,0)));L&&L.setStyle('width',a(Math.max(M-O,0)));if(N)I.setStyle('width',a(N+O*(D?-1:1)));},0,this,[G,G&&c(G),H,H&&c(H),(!G||!H)&&c(I)+d(I,'left')+d(I,'right'),q]);
}};function z(D){h(D);w();m.on('mouseup',A,this);};function A(D){D.removeListener();x();};function B(D){C(D.data.$.clientX);};m=k.document;n=CKEDITOR.dom.element.createFromHtml('<div data-cke-temp=1 contenteditable=false unselectable=on style="position:absolute;cursor:col-resize;filter:alpha(opacity=0);opacity:0;padding:0;background-color:#004;background-image:none;border:0px none;z-index:10"></div>',m);if(!b)m.getDocumentElement().append(n);this.attachTo=function(D){if(o)return;if(b){m.getBody().append(n);q=0;}l=D;n.setStyles({width:a(D.width),height:a(D.height),left:a(D.x),top:a(D.y)});b&&n.setOpacity(0.25);n.on('mousedown',z,this);m.getBody().setStyle('cursor','col-resize');n.show();};var C=this.move=function(D){if(!l)return 0;if(!o&&(D<l.x||D>l.x+l.width)){v();return 0;}var E=D-Math.round(n.$.offsetWidth/2);if(o){if(E==t||E==u)return 1;E=Math.max(E,t);E=Math.min(E,u);q=E-p;}n.setStyle('left',a(E));return 1;};};function j(k){var l=k.data.getTarget();if(k.name=='mouseout'){if(!l.is('table'))return;var m=new CKEDITOR.dom.element(k.data.$.relatedTarget||k.data.$.toElement);while(m&&m.$&&!m.equals(l)&&!m.is('body'))m=m.getParent();if(!m||m.equals(l))return;}l.getAscendant('table',1).removeCustomData('_cke_table_pillars');k.removeListener();};CKEDITOR.plugins.add('tableresize',{requires:['tabletools'],init:function(k){k.on('contentDom',function(){var l;k.document.getBody().on('mousemove',function(m){m=m.data;if(l&&l.move(m.$.clientX)){h(m);return;}var n=m.getTarget(),o,p;if(!n.is('table')&&!n.getAscendant('tbody',1))return;o=n.getAscendant('table',1);if(!(p=o.getCustomData('_cke_table_pillars'))){o.setCustomData('_cke_table_pillars',p=f(o));o.on('mouseout',j);o.on('mousedown',j);}var q=g(p,m.$.clientX);if(q){!l&&(l=new i(k));l.attachTo(q);}});});}});})(); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/plugins/tableresize/plugin.js | plugin.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function(){var a;function b(i){return i.type==CKEDITOR.NODE_TEXT&&i.getLength()>0&&(!a||!i.isReadOnly());};function c(i){return!(i.type==CKEDITOR.NODE_ELEMENT&&i.isBlockBoundary(CKEDITOR.tools.extend({},CKEDITOR.dtd.$empty,CKEDITOR.dtd.$nonEditable)));};var d=function(){var i=this;return{textNode:i.textNode,offset:i.offset,character:i.textNode?i.textNode.getText().charAt(i.offset):null,hitMatchBoundary:i._.matchBoundary};},e=['find','replace'],f=[['txtFindFind','txtFindReplace'],['txtFindCaseChk','txtReplaceCaseChk'],['txtFindWordChk','txtReplaceWordChk'],['txtFindCyclic','txtReplaceCyclic']];function g(i){var j,k,l,m;j=i==='find'?1:0;k=1-j;var n,o=f.length;for(n=0;n<o;n++){l=this.getContentElement(e[j],f[n][j]);m=this.getContentElement(e[k],f[n][k]);m.setValue(l.getValue());}};var h=function(i,j){var k=new CKEDITOR.style(CKEDITOR.tools.extend({attributes:{'data-cke-highlight':1},fullMatch:1,ignoreReadonly:1,childRule:function(){return 0;}},i.config.find_highlight,true)),l=function(y,z){var A=this,B=new CKEDITOR.dom.walker(y);B.guard=z?c:function(C){!c(C)&&(A._.matchBoundary=true);};B.evaluator=b;B.breakOnFalse=1;if(y.startContainer.type==CKEDITOR.NODE_TEXT){this.textNode=y.startContainer;this.offset=y.startOffset-1;}this._={matchWord:z,walker:B,matchBoundary:false};};l.prototype={next:function(){return this.move();},back:function(){return this.move(true);},move:function(y){var A=this;var z=A.textNode;if(z===null)return d.call(A);A._.matchBoundary=false;if(z&&y&&A.offset>0){A.offset--;return d.call(A);}else if(z&&A.offset<z.getLength()-1){A.offset++;return d.call(A);}else{z=null;while(!z){z=A._.walker[y?'previous':'next'].call(A._.walker);if(A._.matchWord&&!z||A._.walker._.end)break;}A.textNode=z;if(z)A.offset=y?z.getLength()-1:0;else A.offset=0;}return d.call(A);}};var m=function(y,z){this._={walker:y,cursors:[],rangeLength:z,highlightRange:null,isMatched:0};};m.prototype={toDomRange:function(){var y=new CKEDITOR.dom.range(i.document),z=this._.cursors;if(z.length<1){var A=this._.walker.textNode;if(A)y.setStartAfter(A);else return null;}else{var B=z[0],C=z[z.length-1];y.setStart(B.textNode,B.offset);y.setEnd(C.textNode,C.offset+1);}return y;},updateFromDomRange:function(y){var B=this;var z,A=new l(y);B._.cursors=[];do{z=A.next();if(z.character)B._.cursors.push(z);}while(z.character);B._.rangeLength=B._.cursors.length;},setMatched:function(){this._.isMatched=true;},clearMatched:function(){this._.isMatched=false;},isMatched:function(){return this._.isMatched;
},highlight:function(){var B=this;if(B._.cursors.length<1)return;if(B._.highlightRange)B.removeHighlight();var y=B.toDomRange(),z=y.createBookmark();k.applyToRange(y);y.moveToBookmark(z);B._.highlightRange=y;var A=y.startContainer;if(A.type!=CKEDITOR.NODE_ELEMENT)A=A.getParent();A.scrollIntoView();B.updateFromDomRange(y);},removeHighlight:function(){var z=this;if(!z._.highlightRange)return;var y=z._.highlightRange.createBookmark();k.removeFromRange(z._.highlightRange);z._.highlightRange.moveToBookmark(y);z.updateFromDomRange(z._.highlightRange);z._.highlightRange=null;},isReadOnly:function(){if(!this._.highlightRange)return 0;return this._.highlightRange.startContainer.isReadOnly();},moveBack:function(){var A=this;var y=A._.walker.back(),z=A._.cursors;if(y.hitMatchBoundary)A._.cursors=z=[];z.unshift(y);if(z.length>A._.rangeLength)z.pop();return y;},moveNext:function(){var A=this;var y=A._.walker.next(),z=A._.cursors;if(y.hitMatchBoundary)A._.cursors=z=[];z.push(y);if(z.length>A._.rangeLength)z.shift();return y;},getEndCharacter:function(){var y=this._.cursors;if(y.length<1)return null;return y[y.length-1].character;},getNextCharacterRange:function(y){var z,A,B=this._.cursors;if((z=B[B.length-1])&&z.textNode)A=new l(n(z));else A=this._.walker;return new m(A,y);},getCursors:function(){return this._.cursors;}};function n(y,z){var A=new CKEDITOR.dom.range();A.setStart(y.textNode,z?y.offset:y.offset+1);A.setEndAt(i.document.getBody(),CKEDITOR.POSITION_BEFORE_END);return A;};function o(y){var z=new CKEDITOR.dom.range();z.setStartAt(i.document.getBody(),CKEDITOR.POSITION_AFTER_START);z.setEnd(y.textNode,y.offset);return z;};var p=0,q=1,r=2,s=function(y,z){var A=[-1];if(z)y=y.toLowerCase();for(var B=0;B<y.length;B++){A.push(A[B]+1);while(A[B+1]>0&&y.charAt(B)!=y.charAt(A[B+1]-1))A[B+1]=A[A[B+1]-1]+1;}this._={overlap:A,state:0,ignoreCase:!!z,pattern:y};};s.prototype={feedCharacter:function(y){var z=this;if(z._.ignoreCase)y=y.toLowerCase();for(;;){if(y==z._.pattern.charAt(z._.state)){z._.state++;if(z._.state==z._.pattern.length){z._.state=0;return r;}return q;}else if(!z._.state)return p;else z._.state=z._.overlap[z._.state];}return null;},reset:function(){this._.state=0;}};var t=/[.,"'?!;: \u0085\u00a0\u1680\u280e\u2028\u2029\u202f\u205f\u3000]/,u=function(y){if(!y)return true;var z=y.charCodeAt(0);return z>=9&&z<=13||z>=8192&&z<=8202||t.test(y);},v={searchRange:null,matchRange:null,find:function(y,z,A,B,C,D){var M=this;if(!M.matchRange)M.matchRange=new m(new l(M.searchRange),y.length);
else{M.matchRange.removeHighlight();M.matchRange=M.matchRange.getNextCharacterRange(y.length);}var E=new s(y,!z),F=p,G='%';while(G!==null){M.matchRange.moveNext();while(G=M.matchRange.getEndCharacter()){F=E.feedCharacter(G);if(F==r)break;if(M.matchRange.moveNext().hitMatchBoundary)E.reset();}if(F==r){if(A){var H=M.matchRange.getCursors(),I=H[H.length-1],J=H[0],K=new l(o(J),true),L=new l(n(I),true);if(!(u(K.back().character)&&u(L.next().character)))continue;}M.matchRange.setMatched();if(C!==false)M.matchRange.highlight();return true;}}M.matchRange.clearMatched();M.matchRange.removeHighlight();if(B&&!D){M.searchRange=w(1);M.matchRange=null;return arguments.callee.apply(M,Array.prototype.slice.call(arguments).concat([true]));}return false;},replaceCounter:0,replace:function(y,z,A,B,C,D,E){var J=this;a=1;var F=0;if(J.matchRange&&J.matchRange.isMatched()&&!J.matchRange._.isReplaced&&!J.matchRange.isReadOnly()){J.matchRange.removeHighlight();var G=J.matchRange.toDomRange(),H=i.document.createText(A);if(!E){var I=i.getSelection();I.selectRanges([G]);i.fire('saveSnapshot');}G.deleteContents();G.insertNode(H);if(!E){I.selectRanges([G]);i.fire('saveSnapshot');}J.matchRange.updateFromDomRange(G);if(!E)J.matchRange.highlight();J.matchRange._.isReplaced=true;J.replaceCounter++;F=1;}else F=J.find(z,B,C,D,!E);a=0;return F;}};function w(y){var z,A=i.getSelection(),B=i.document.getBody();if(A&&!y){z=A.getRanges()[0].clone();z.collapse(true);}else{z=new CKEDITOR.dom.range();z.setStartAt(B,CKEDITOR.POSITION_AFTER_START);}z.setEndAt(B,CKEDITOR.POSITION_BEFORE_END);return z;};var x=i.lang.findAndReplace;return{title:x.title,resizable:CKEDITOR.DIALOG_RESIZE_NONE,minWidth:350,minHeight:170,buttons:[CKEDITOR.dialog.cancelButton],contents:[{id:'find',label:x.find,title:x.find,accessKey:'',elements:[{type:'hbox',widths:['230px','90px'],children:[{type:'text',id:'txtFindFind',label:x.findWhat,isChanged:false,labelLayout:'horizontal',accessKey:'F'},{type:'button',id:'btnFind',align:'left',style:'width:100%',label:x.find,onClick:function(){var y=this.getDialog();if(!v.find(y.getValueOf('find','txtFindFind'),y.getValueOf('find','txtFindCaseChk'),y.getValueOf('find','txtFindWordChk'),y.getValueOf('find','txtFindCyclic')))alert(x.notFoundMsg);}}]},{type:'fieldset',label:CKEDITOR.tools.htmlEncode(x.findOptions),style:'margin-top:29px',children:[{type:'vbox',padding:0,children:[{type:'checkbox',id:'txtFindCaseChk',isChanged:false,label:x.matchCase},{type:'checkbox',id:'txtFindWordChk',isChanged:false,label:x.matchWord},{type:'checkbox',id:'txtFindCyclic',isChanged:false,'default':true,label:x.matchCyclic}]}]}]},{id:'replace',label:x.replace,accessKey:'M',elements:[{type:'hbox',widths:['230px','90px'],children:[{type:'text',id:'txtFindReplace',label:x.findWhat,isChanged:false,labelLayout:'horizontal',accessKey:'F'},{type:'button',id:'btnFindReplace',align:'left',style:'width:100%',label:x.replace,onClick:function(){var y=this.getDialog();
if(!v.replace(y,y.getValueOf('replace','txtFindReplace'),y.getValueOf('replace','txtReplace'),y.getValueOf('replace','txtReplaceCaseChk'),y.getValueOf('replace','txtReplaceWordChk'),y.getValueOf('replace','txtReplaceCyclic')))alert(x.notFoundMsg);}}]},{type:'hbox',widths:['230px','90px'],children:[{type:'text',id:'txtReplace',label:x.replaceWith,isChanged:false,labelLayout:'horizontal',accessKey:'R'},{type:'button',id:'btnReplaceAll',align:'left',style:'width:100%',label:x.replaceAll,isChanged:false,onClick:function(){var y=this.getDialog(),z;v.replaceCounter=0;v.searchRange=w(1);if(v.matchRange){v.matchRange.removeHighlight();v.matchRange=null;}i.fire('saveSnapshot');while(v.replace(y,y.getValueOf('replace','txtFindReplace'),y.getValueOf('replace','txtReplace'),y.getValueOf('replace','txtReplaceCaseChk'),y.getValueOf('replace','txtReplaceWordChk'),false,true)){}if(v.replaceCounter){alert(x.replaceSuccessMsg.replace(/%1/,v.replaceCounter));i.fire('saveSnapshot');}else alert(x.notFoundMsg);}}]},{type:'fieldset',label:CKEDITOR.tools.htmlEncode(x.findOptions),children:[{type:'vbox',padding:0,children:[{type:'checkbox',id:'txtReplaceCaseChk',isChanged:false,label:x.matchCase},{type:'checkbox',id:'txtReplaceWordChk',isChanged:false,label:x.matchWord},{type:'checkbox',id:'txtReplaceCyclic',isChanged:false,'default':true,label:x.matchCyclic}]}]}]}],onLoad:function(){var y=this,z,A,B=0;this.on('hide',function(){B=0;});this.on('show',function(){B=1;});this.selectPage=CKEDITOR.tools.override(this.selectPage,function(C){return function(D){C.call(y,D);var E=y._.tabs[D],F,G,H;G=D==='find'?'txtFindFind':'txtFindReplace';H=D==='find'?'txtFindWordChk':'txtReplaceWordChk';z=y.getContentElement(D,G);A=y.getContentElement(D,H);if(!E.initialized){F=CKEDITOR.document.getById(z._.inputId);E.initialized=true;}if(B)g.call(this,D);};});},onShow:function(){var B=this;v.searchRange=w();var y=B.getParentEditor().getSelection().getSelectedText(),z=j=='find'?'txtFindFind':'txtFindReplace',A=B.getContentElement(j,z);A.setValue(y);A.select();B.selectPage(j);B[(j=='find'&&B._.editor.readOnly?'hide':'show')+'Page']('replace');},onHide:function(){var y;if(v.matchRange&&v.matchRange.isMatched()){v.matchRange.removeHighlight();i.focus();y=v.matchRange.toDomRange();if(y)i.getSelection().selectRanges([y]);}delete v.matchRange;},onFocus:function(){if(j=='replace')return this.getContentElement('replace','txtFindReplace');else return this.getContentElement('find','txtFindFind');}};};CKEDITOR.dialog.add('find',function(i){return h(i,'find');
});CKEDITOR.dialog.add('replace',function(i){return h(i,'replace');});})(); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/plugins/find/dialogs/find.js | find.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.add( 'resize',
{
init : function( editor )
{
var config = editor.config;
// Resize in the same direction of chrome,
// which is identical to dir of editor element. (#6614)
var resizeDir = editor.element.getDirection( 1 );
!config.resize_dir && ( config.resize_dir = 'both' );
( config.resize_maxWidth == undefined ) && ( config.resize_maxWidth = 3000 );
( config.resize_maxHeight == undefined ) && ( config.resize_maxHeight = 3000 );
( config.resize_minWidth == undefined ) && ( config.resize_minWidth = 750 );
( config.resize_minHeight == undefined ) && ( config.resize_minHeight = 250 );
if ( config.resize_enabled !== false )
{
var container = null,
origin,
startSize,
resizeHorizontal = ( config.resize_dir == 'both' || config.resize_dir == 'horizontal' ) &&
( config.resize_minWidth != config.resize_maxWidth ),
resizeVertical = ( config.resize_dir == 'both' || config.resize_dir == 'vertical' ) &&
( config.resize_minHeight != config.resize_maxHeight );
function dragHandler( evt )
{
var dx = evt.data.$.screenX - origin.x,
dy = evt.data.$.screenY - origin.y,
width = startSize.width,
height = startSize.height,
internalWidth = width + dx * ( resizeDir == 'rtl' ? -1 : 1 ),
internalHeight = height + dy;
if ( resizeHorizontal )
width = Math.max( config.resize_minWidth, Math.min( internalWidth, config.resize_maxWidth ) );
if ( resizeVertical )
height = Math.max( config.resize_minHeight, Math.min( internalHeight, config.resize_maxHeight ) );
editor.resize( width, height );
}
function dragEndHandler ( evt )
{
CKEDITOR.document.removeListener( 'mousemove', dragHandler );
CKEDITOR.document.removeListener( 'mouseup', dragEndHandler );
if ( editor.document )
{
editor.document.removeListener( 'mousemove', dragHandler );
editor.document.removeListener( 'mouseup', dragEndHandler );
}
}
var mouseDownFn = CKEDITOR.tools.addFunction( function( $event )
{
if ( !container )
container = editor.getResizable();
startSize = { width : container.$.offsetWidth || 0, height : container.$.offsetHeight || 0 };
origin = { x : $event.screenX, y : $event.screenY };
config.resize_minWidth > startSize.width && ( config.resize_minWidth = startSize.width );
config.resize_minHeight > startSize.height && ( config.resize_minHeight = startSize.height );
CKEDITOR.document.on( 'mousemove', dragHandler );
CKEDITOR.document.on( 'mouseup', dragEndHandler );
if ( editor.document )
{
editor.document.on( 'mousemove', dragHandler );
editor.document.on( 'mouseup', dragEndHandler );
}
});
editor.on( 'destroy', function() { CKEDITOR.tools.removeFunction( mouseDownFn ); } );
editor.on( 'themeSpace', function( event )
{
if ( event.data.space == 'bottom' )
{
var direction = '';
if ( resizeHorizontal && !resizeVertical )
direction = ' cke_resizer_horizontal';
if ( !resizeHorizontal && resizeVertical )
direction = ' cke_resizer_vertical';
var resizerHtml =
'<div' +
' class="cke_resizer' + direction + ' cke_resizer_' + resizeDir + '"' +
' title="' + CKEDITOR.tools.htmlEncode( editor.lang.resize ) + '"' +
' onmousedown="CKEDITOR.tools.callFunction(' + mouseDownFn + ', event)"' +
'></div>';
// Always sticks the corner of botttom space.
resizeDir == 'ltr' && direction == 'ltr' ?
event.data.html += resizerHtml :
event.data.html = resizerHtml + event.data.html;
}
}, editor, null, 100 );
}
}
} );
/**
* The minimum editor width, in pixels, when resizing the editor interface by using the resize handle.
* Note: It falls back to editor's actual width if it is smaller than the default value.
* @name CKEDITOR.config.resize_minWidth
* @type Number
* @default 750
* @example
* config.resize_minWidth = 500;
*/
/**
* The minimum editor height, in pixels, when resizing the editor interface by using the resize handle.
* Note: It falls back to editor's actual height if it is smaller than the default value.
* @name CKEDITOR.config.resize_minHeight
* @type Number
* @default 250
* @example
* config.resize_minHeight = 600;
*/
/**
* The maximum editor width, in pixels, when resizing the editor interface by using the resize handle.
* @name CKEDITOR.config.resize_maxWidth
* @type Number
* @default 3000
* @example
* config.resize_maxWidth = 750;
*/
/**
* The maximum editor height, in pixels, when resizing the editor interface by using the resize handle.
* @name CKEDITOR.config.resize_maxHeight
* @type Number
* @default 3000
* @example
* config.resize_maxHeight = 600;
*/
/**
* Whether to enable the resizing feature. If this feature is disabled, the resize handle will not be visible.
* @name CKEDITOR.config.resize_enabled
* @type Boolean
* @default true
* @example
* config.resize_enabled = false;
*/
/**
* The dimensions for which the editor resizing is enabled. Possible values
* are <code>both</code>, <code>vertical</code>, and <code>horizontal</code>.
* @name CKEDITOR.config.resize_dir
* @type String
* @default 'both'
* @since 3.3
* @example
* config.resize_dir = 'vertical';
*/ | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/_source/plugins/resize/plugin.js | plugin.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
function addCombo( editor, comboName, styleType, lang, entries, defaultLabel, styleDefinition )
{
var config = editor.config;
// Gets the list of fonts from the settings.
var names = entries.split( ';' ),
values = [];
// Create style objects for all fonts.
var styles = {};
for ( var i = 0 ; i < names.length ; i++ )
{
var parts = names[ i ];
if ( parts )
{
parts = parts.split( '/' );
var vars = {},
name = names[ i ] = parts[ 0 ];
vars[ styleType ] = values[ i ] = parts[ 1 ] || name;
styles[ name ] = new CKEDITOR.style( styleDefinition, vars );
styles[ name ]._.definition.name = name;
}
else
names.splice( i--, 1 );
}
editor.ui.addRichCombo( comboName,
{
label : lang.label,
title : lang.panelTitle,
className : 'cke_' + ( styleType == 'size' ? 'fontSize' : 'font' ),
panel :
{
css : editor.skin.editor.css.concat( config.contentsCss ),
multiSelect : false,
attributes : { 'aria-label' : lang.panelTitle }
},
init : function()
{
this.startGroup( lang.panelTitle );
for ( var i = 0 ; i < names.length ; i++ )
{
var name = names[ i ];
// Add the tag entry to the panel list.
this.add( name, styles[ name ].buildPreview(), name );
}
},
onClick : function( value )
{
editor.focus();
editor.fire( 'saveSnapshot' );
var style = styles[ value ];
if ( this.getValue() == value )
style.remove( editor.document );
else
style.apply( editor.document );
editor.fire( 'saveSnapshot' );
},
onRender : function()
{
editor.on( 'selectionChange', function( ev )
{
var currentValue = this.getValue();
var elementPath = ev.data.path,
elements = elementPath.elements;
// For each element into the elements path.
for ( var i = 0, element ; i < elements.length ; i++ )
{
element = elements[i];
// Check if the element is removable by any of
// the styles.
for ( var value in styles )
{
if ( styles[ value ].checkElementRemovable( element, true ) )
{
if ( value != currentValue )
this.setValue( value );
return;
}
}
}
// If no styles match, just empty it.
this.setValue( '', defaultLabel );
},
this);
}
});
}
CKEDITOR.plugins.add( 'font',
{
requires : [ 'richcombo', 'styles' ],
init : function( editor )
{
var config = editor.config;
addCombo( editor, 'Font', 'family', editor.lang.font, config.font_names, config.font_defaultLabel, config.font_style );
addCombo( editor, 'FontSize', 'size', editor.lang.fontSize, config.fontSize_sizes, config.fontSize_defaultLabel, config.fontSize_style );
}
});
})();
/**
* The list of fonts names to be displayed in the Font combo in the toolbar.
* Entries are separated by semi-colons (;), while it's possible to have more
* than one font for each entry, in the HTML way (separated by comma).
*
* A display name may be optionally defined by prefixing the entries with the
* name and the slash character. For example, "Arial/Arial, Helvetica, sans-serif"
* will be displayed as "Arial" in the list, but will be outputted as
* "Arial, Helvetica, sans-serif".
* @type String
* @example
* config.font_names =
* 'Arial/Arial, Helvetica, sans-serif;' +
* 'Times New Roman/Times New Roman, Times, serif;' +
* 'Verdana';
* @example
* config.font_names = 'Arial;Times New Roman;Verdana';
*/
CKEDITOR.config.font_names =
'Arial/Arial, Helvetica, sans-serif;' +
'Comic Sans MS/Comic Sans MS, cursive;' +
'Courier New/Courier New, Courier, monospace;' +
'Georgia/Georgia, serif;' +
'Lucida Sans Unicode/Lucida Sans Unicode, Lucida Grande, sans-serif;' +
'Tahoma/Tahoma, Geneva, sans-serif;' +
'Times New Roman/Times New Roman, Times, serif;' +
'Trebuchet MS/Trebuchet MS, Helvetica, sans-serif;' +
'Verdana/Verdana, Geneva, sans-serif';
/**
* The text to be displayed in the Font combo is none of the available values
* matches the current cursor position or text selection.
* @type String
* @example
* // If the default site font is Arial, we may making it more explicit to the end user.
* config.font_defaultLabel = 'Arial';
*/
CKEDITOR.config.font_defaultLabel = '';
/**
* The style definition to be used to apply the font in the text.
* @type Object
* @example
* // This is actually the default value for it.
* config.font_style =
* {
* element : 'span',
* styles : { 'font-family' : '#(family)' },
* overrides : [ { element : 'font', attributes : { 'face' : null } } ]
* };
*/
CKEDITOR.config.font_style =
{
element : 'span',
styles : { 'font-family' : '#(family)' },
overrides : [ { element : 'font', attributes : { 'face' : null } } ]
};
/**
* The list of fonts size to be displayed in the Font Size combo in the
* toolbar. Entries are separated by semi-colons (;).
*
* Any kind of "CSS like" size can be used, like "12px", "2.3em", "130%",
* "larger" or "x-small".
*
* A display name may be optionally defined by prefixing the entries with the
* name and the slash character. For example, "Bigger Font/14px" will be
* displayed as "Bigger Font" in the list, but will be outputted as "14px".
* @type String
* @default '8/8px;9/9px;10/10px;11/11px;12/12px;14/14px;16/16px;18/18px;20/20px;22/22px;24/24px;26/26px;28/28px;36/36px;48/48px;72/72px'
* @example
* config.fontSize_sizes = '16/16px;24/24px;48/48px;';
* @example
* config.fontSize_sizes = '12px;2.3em;130%;larger;x-small';
* @example
* config.fontSize_sizes = '12 Pixels/12px;Big/2.3em;30 Percent More/130%;Bigger/larger;Very Small/x-small';
*/
CKEDITOR.config.fontSize_sizes =
'8/8px;9/9px;10/10px;11/11px;12/12px;14/14px;16/16px;18/18px;20/20px;22/22px;24/24px;26/26px;28/28px;36/36px;48/48px;72/72px';
/**
* The text to be displayed in the Font Size combo is none of the available
* values matches the current cursor position or text selection.
* @type String
* @example
* // If the default site font size is 12px, we may making it more explicit to the end user.
* config.fontSize_defaultLabel = '12px';
*/
CKEDITOR.config.fontSize_defaultLabel = '';
/**
* The style definition to be used to apply the font size in the text.
* @type Object
* @example
* // This is actually the default value for it.
* config.fontSize_style =
* {
* element : 'span',
* styles : { 'font-size' : '#(size)' },
* overrides : [ { element : 'font', attributes : { 'size' : null } } ]
* };
*/
CKEDITOR.config.fontSize_style =
{
element : 'span',
styles : { 'font-size' : '#(size)' },
overrides : [ { element : 'font', attributes : { 'size' : null } } ]
}; | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/_source/plugins/font/plugin.js | plugin.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.add( 'basicstyles',
{
requires : [ 'styles', 'button' ],
init : function( editor )
{
// All buttons use the same code to register. So, to avoid
// duplications, let's use this tool function.
var addButtonCommand = function( buttonName, buttonLabel, commandName, styleDefiniton )
{
var style = new CKEDITOR.style( styleDefiniton );
editor.attachStyleStateChange( style, function( state )
{
!editor.readOnly && editor.getCommand( commandName ).setState( state );
});
editor.addCommand( commandName, new CKEDITOR.styleCommand( style ) );
editor.ui.addButton( buttonName,
{
label : buttonLabel,
command : commandName
});
};
var config = editor.config,
lang = editor.lang;
addButtonCommand( 'Bold' , lang.bold , 'bold' , config.coreStyles_bold );
addButtonCommand( 'Italic' , lang.italic , 'italic' , config.coreStyles_italic );
addButtonCommand( 'Underline' , lang.underline , 'underline' , config.coreStyles_underline );
addButtonCommand( 'Strike' , lang.strike , 'strike' , config.coreStyles_strike );
addButtonCommand( 'Subscript' , lang.subscript , 'subscript' , config.coreStyles_subscript );
addButtonCommand( 'Superscript' , lang.superscript , 'superscript' , config.coreStyles_superscript );
}
});
// Basic Inline Styles.
/**
* The style definition that applies the <strong>bold</strong> style to the text.
* @type Object
* @default <code>{ element : 'strong', overrides : 'b' }</code>
* @example
* config.coreStyles_bold = { element : 'b', overrides : 'strong' };
* @example
* config.coreStyles_bold =
* {
* element : 'span',
* attributes : { 'class' : 'Bold' }
* };
*/
CKEDITOR.config.coreStyles_bold = { element : 'strong', overrides : 'b' };
/**
* The style definition that applies the <em>italics</em> style to the text.
* @type Object
* @default <code>{ element : 'em', overrides : 'i' }</code>
* @example
* config.coreStyles_italic = { element : 'i', overrides : 'em' };
* @example
* CKEDITOR.config.coreStyles_italic =
* {
* element : 'span',
* attributes : { 'class' : 'Italic' }
* };
*/
CKEDITOR.config.coreStyles_italic = { element : 'em', overrides : 'i' };
/**
* The style definition that applies the <u>underline</u> style to the text.
* @type Object
* @default <code>{ element : 'u' }</code>
* @example
* CKEDITOR.config.coreStyles_underline =
* {
* element : 'span',
* attributes : { 'class' : 'Underline' }
* };
*/
CKEDITOR.config.coreStyles_underline = { element : 'u' };
/**
* The style definition that applies the <strike>strike-through</strike> style to the text.
* @type Object
* @default <code>{ element : 'strike' }</code>
* @example
* CKEDITOR.config.coreStyles_strike =
* {
* element : 'span',
* attributes : { 'class' : 'StrikeThrough' },
* overrides : 'strike'
* };
*/
CKEDITOR.config.coreStyles_strike = { element : 'strike' };
/**
* The style definition that applies the subscript style to the text.
* @type Object
* @default <code>{ element : 'sub' }</code>
* @example
* CKEDITOR.config.coreStyles_subscript =
* {
* element : 'span',
* attributes : { 'class' : 'Subscript' },
* overrides : 'sub'
* };
*/
CKEDITOR.config.coreStyles_subscript = { element : 'sub' };
/**
* The style definition that applies the superscript style to the text.
* @type Object
* @default <code>{ element : 'sup' }</code>
* @example
* CKEDITOR.config.coreStyles_superscript =
* {
* element : 'span',
* attributes : { 'class' : 'Superscript' },
* overrides : 'sup'
* };
*/
CKEDITOR.config.coreStyles_superscript = { element : 'sup' }; | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/_source/plugins/basicstyles/plugin.js | plugin.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @file Insert and remove numbered and bulleted lists.
*/
(function()
{
var listNodeNames = { ol : 1, ul : 1 },
emptyTextRegex = /^[\n\r\t ]*$/;
var whitespaces = CKEDITOR.dom.walker.whitespaces(),
bookmarks = CKEDITOR.dom.walker.bookmark(),
nonEmpty = function( node ){ return !( whitespaces( node ) || bookmarks( node ) ); };
function cleanUpDirection( element )
{
var dir, parent, parentDir;
if ( ( dir = element.getDirection() ) )
{
parent = element.getParent();
while ( parent && !( parentDir = parent.getDirection() ) )
parent = parent.getParent();
if ( dir == parentDir )
element.removeAttribute( 'dir' );
}
}
CKEDITOR.plugins.list = {
/*
* Convert a DOM list tree into a data structure that is easier to
* manipulate. This operation should be non-intrusive in the sense that it
* does not change the DOM tree, with the exception that it may add some
* markers to the list item nodes when database is specified.
*/
listToArray : function( listNode, database, baseArray, baseIndentLevel, grandparentNode )
{
if ( !listNodeNames[ listNode.getName() ] )
return [];
if ( !baseIndentLevel )
baseIndentLevel = 0;
if ( !baseArray )
baseArray = [];
// Iterate over all list items to and look for inner lists.
for ( var i = 0, count = listNode.getChildCount() ; i < count ; i++ )
{
var listItem = listNode.getChild( i );
// Fixing malformed nested lists by moving it into a previous list item. (#6236)
if( listItem.type == CKEDITOR.NODE_ELEMENT && listItem.getName() in CKEDITOR.dtd.$list )
CKEDITOR.plugins.list.listToArray( listItem, database, baseArray, baseIndentLevel + 1 );
// It may be a text node or some funny stuff.
if ( listItem.$.nodeName.toLowerCase() != 'li' )
continue;
var itemObj = { 'parent' : listNode, indent : baseIndentLevel, element : listItem, contents : [] };
if ( !grandparentNode )
{
itemObj.grandparent = listNode.getParent();
if ( itemObj.grandparent && itemObj.grandparent.$.nodeName.toLowerCase() == 'li' )
itemObj.grandparent = itemObj.grandparent.getParent();
}
else
itemObj.grandparent = grandparentNode;
if ( database )
CKEDITOR.dom.element.setMarker( database, listItem, 'listarray_index', baseArray.length );
baseArray.push( itemObj );
for ( var j = 0, itemChildCount = listItem.getChildCount(), child; j < itemChildCount ; j++ )
{
child = listItem.getChild( j );
if ( child.type == CKEDITOR.NODE_ELEMENT && listNodeNames[ child.getName() ] )
// Note the recursion here, it pushes inner list items with
// +1 indentation in the correct order.
CKEDITOR.plugins.list.listToArray( child, database, baseArray, baseIndentLevel + 1, itemObj.grandparent );
else
itemObj.contents.push( child );
}
}
return baseArray;
},
// Convert our internal representation of a list back to a DOM forest.
arrayToList : function( listArray, database, baseIndex, paragraphMode, dir )
{
if ( !baseIndex )
baseIndex = 0;
if ( !listArray || listArray.length < baseIndex + 1 )
return null;
var doc = listArray[ baseIndex ].parent.getDocument(),
retval = new CKEDITOR.dom.documentFragment( doc ),
rootNode = null,
currentIndex = baseIndex,
indentLevel = Math.max( listArray[ baseIndex ].indent, 0 ),
currentListItem = null,
orgDir,
paragraphName = ( paragraphMode == CKEDITOR.ENTER_P ? 'p' : 'div' );
while ( 1 )
{
var item = listArray[ currentIndex ];
orgDir = item.element.getDirection( 1 );
if ( item.indent == indentLevel )
{
if ( !rootNode || listArray[ currentIndex ].parent.getName() != rootNode.getName() )
{
rootNode = listArray[ currentIndex ].parent.clone( false, 1 );
dir && rootNode.setAttribute( 'dir', dir );
retval.append( rootNode );
}
currentListItem = rootNode.append( item.element.clone( 0, 1 ) );
if ( orgDir != rootNode.getDirection( 1 ) )
currentListItem.setAttribute( 'dir', orgDir );
for ( var i = 0 ; i < item.contents.length ; i++ )
currentListItem.append( item.contents[i].clone( 1, 1 ) );
currentIndex++;
}
else if ( item.indent == Math.max( indentLevel, 0 ) + 1 )
{
// Maintain original direction (#6861).
var currDir = listArray[ currentIndex - 1 ].element.getDirection( 1 ),
listData = CKEDITOR.plugins.list.arrayToList( listArray, null, currentIndex, paragraphMode,
currDir != orgDir ? orgDir: null );
// If the next block is an <li> with another list tree as the first
// child, we'll need to append a filler (<br>/NBSP) or the list item
// wouldn't be editable. (#6724)
if ( !currentListItem.getChildCount() && CKEDITOR.env.ie && !( doc.$.documentMode > 7 ))
currentListItem.append( doc.createText( '\xa0' ) );
currentListItem.append( listData.listNode );
currentIndex = listData.nextIndex;
}
else if ( item.indent == -1 && !baseIndex && item.grandparent )
{
if ( listNodeNames[ item.grandparent.getName() ] )
currentListItem = item.element.clone( false, true );
else
{
// Create completely new blocks here.
if ( dir || item.element.hasAttributes() || paragraphMode != CKEDITOR.ENTER_BR )
{
currentListItem = doc.createElement( paragraphName );
item.element.copyAttributes( currentListItem, { type:1, value:1 } );
// There might be a case where there are no attributes in the element after all
// (i.e. when "type" or "value" are the only attributes set). In this case, if enterMode = BR,
// the current item should be a fragment.
if ( !dir && paragraphMode == CKEDITOR.ENTER_BR && !currentListItem.hasAttributes() )
currentListItem = new CKEDITOR.dom.documentFragment( doc );
}
else
currentListItem = new CKEDITOR.dom.documentFragment( doc );
}
if ( currentListItem.type == CKEDITOR.NODE_ELEMENT )
{
if ( item.grandparent.getDirection( 1 ) != orgDir )
currentListItem.setAttribute( 'dir', orgDir );
}
for ( i = 0 ; i < item.contents.length ; i++ )
currentListItem.append( item.contents[i].clone( 1, 1 ) );
if ( currentListItem.type == CKEDITOR.NODE_DOCUMENT_FRAGMENT
&& currentIndex != listArray.length - 1 )
{
var last = currentListItem.getLast();
if ( last && last.type == CKEDITOR.NODE_ELEMENT
&& last.getAttribute( 'type' ) == '_moz' )
{
last.remove();
}
if ( !( last = currentListItem.getLast( nonEmpty )
&& last.type == CKEDITOR.NODE_ELEMENT
&& last.getName() in CKEDITOR.dtd.$block ) )
{
currentListItem.append( doc.createElement( 'br' ) );
}
}
if ( currentListItem.type == CKEDITOR.NODE_ELEMENT &&
currentListItem.getName() == paragraphName &&
currentListItem.$.firstChild )
{
currentListItem.trim();
var firstChild = currentListItem.getFirst();
if ( firstChild.type == CKEDITOR.NODE_ELEMENT && firstChild.isBlockBoundary() )
{
var tmp = new CKEDITOR.dom.documentFragment( doc );
currentListItem.moveChildren( tmp );
currentListItem = tmp;
}
}
var currentListItemName = currentListItem.$.nodeName.toLowerCase();
if ( !CKEDITOR.env.ie && ( currentListItemName == 'div' || currentListItemName == 'p' ) )
currentListItem.appendBogus();
retval.append( currentListItem );
rootNode = null;
currentIndex++;
}
else
return null;
if ( listArray.length <= currentIndex || Math.max( listArray[ currentIndex ].indent, 0 ) < indentLevel )
break;
}
if ( database )
{
var currentNode = retval.getFirst(),
listRoot = listArray[ 0 ].parent;
while ( currentNode )
{
if ( currentNode.type == CKEDITOR.NODE_ELEMENT )
{
// Clear marker attributes for the new list tree made of cloned nodes, if any.
CKEDITOR.dom.element.clearMarkers( database, currentNode );
// Clear redundant direction attribute specified on list items.
if ( currentNode.getName() in CKEDITOR.dtd.$listItem )
cleanUpDirection( currentNode );
}
currentNode = currentNode.getNextSourceNode();
}
}
return { listNode : retval, nextIndex : currentIndex };
}
};
function onSelectionChange( evt )
{
if ( evt.editor.readOnly )
return null;
var path = evt.data.path,
blockLimit = path.blockLimit,
elements = path.elements,
element,
i;
// Grouping should only happen under blockLimit.(#3940).
for ( i = 0 ; i < elements.length && ( element = elements[ i ] )
&& !element.equals( blockLimit ); i++ )
{
if ( listNodeNames[ elements[ i ].getName() ] )
return this.setState( this.type == elements[ i ].getName() ? CKEDITOR.TRISTATE_ON : CKEDITOR.TRISTATE_OFF );
}
return this.setState( CKEDITOR.TRISTATE_OFF );
}
function changeListType( editor, groupObj, database, listsCreated )
{
// This case is easy...
// 1. Convert the whole list into a one-dimensional array.
// 2. Change the list type by modifying the array.
// 3. Recreate the whole list by converting the array to a list.
// 4. Replace the original list with the recreated list.
var listArray = CKEDITOR.plugins.list.listToArray( groupObj.root, database ),
selectedListItems = [];
for ( var i = 0 ; i < groupObj.contents.length ; i++ )
{
var itemNode = groupObj.contents[i];
itemNode = itemNode.getAscendant( 'li', true );
if ( !itemNode || itemNode.getCustomData( 'list_item_processed' ) )
continue;
selectedListItems.push( itemNode );
CKEDITOR.dom.element.setMarker( database, itemNode, 'list_item_processed', true );
}
var root = groupObj.root,
fakeParent = root.getDocument().createElement( this.type );
// Copy all attributes, except from 'start' and 'type'.
root.copyAttributes( fakeParent, { start : 1, type : 1 } );
// The list-style-type property should be ignored.
fakeParent.removeStyle( 'list-style-type' );
for ( i = 0 ; i < selectedListItems.length ; i++ )
{
var listIndex = selectedListItems[i].getCustomData( 'listarray_index' );
listArray[listIndex].parent = fakeParent;
}
var newList = CKEDITOR.plugins.list.arrayToList( listArray, database, null, editor.config.enterMode );
var child, length = newList.listNode.getChildCount();
for ( i = 0 ; i < length && ( child = newList.listNode.getChild( i ) ) ; i++ )
{
if ( child.getName() == this.type )
listsCreated.push( child );
}
newList.listNode.replace( groupObj.root );
}
var headerTagRegex = /^h[1-6]$/;
function createList( editor, groupObj, listsCreated )
{
var contents = groupObj.contents,
doc = groupObj.root.getDocument(),
listContents = [];
// It is possible to have the contents returned by DomRangeIterator to be the same as the root.
// e.g. when we're running into table cells.
// In such a case, enclose the childNodes of contents[0] into a <div>.
if ( contents.length == 1 && contents[0].equals( groupObj.root ) )
{
var divBlock = doc.createElement( 'div' );
contents[0].moveChildren && contents[0].moveChildren( divBlock );
contents[0].append( divBlock );
contents[0] = divBlock;
}
// Calculate the common parent node of all content blocks.
var commonParent = groupObj.contents[0].getParent();
for ( var i = 0 ; i < contents.length ; i++ )
commonParent = commonParent.getCommonAncestor( contents[i].getParent() );
var useComputedState = editor.config.useComputedState,
listDir, explicitDirection;
useComputedState = useComputedState === undefined || useComputedState;
// We want to insert things that are in the same tree level only, so calculate the contents again
// by expanding the selected blocks to the same tree level.
for ( i = 0 ; i < contents.length ; i++ )
{
var contentNode = contents[i],
parentNode;
while ( ( parentNode = contentNode.getParent() ) )
{
if ( parentNode.equals( commonParent ) )
{
listContents.push( contentNode );
// Determine the lists's direction.
if ( !explicitDirection && contentNode.getDirection() )
explicitDirection = 1;
var itemDir = contentNode.getDirection( useComputedState );
if ( listDir !== null )
{
// If at least one LI have a different direction than current listDir, we can't have listDir.
if ( listDir && listDir != itemDir )
listDir = null;
else
listDir = itemDir;
}
break;
}
contentNode = parentNode;
}
}
if ( listContents.length < 1 )
return;
// Insert the list to the DOM tree.
var insertAnchor = listContents[ listContents.length - 1 ].getNext(),
listNode = doc.createElement( this.type );
listsCreated.push( listNode );
var contentBlock, listItem;
while ( listContents.length )
{
contentBlock = listContents.shift();
listItem = doc.createElement( 'li' );
// Preserve preformat block and heading structure when converting to list item. (#5335) (#5271)
if ( contentBlock.is( 'pre' ) || headerTagRegex.test( contentBlock.getName() ) )
contentBlock.appendTo( listItem );
else
{
contentBlock.copyAttributes( listItem );
// Remove direction attribute after it was merged into list root. (#7657)
if ( listDir && contentBlock.getDirection() )
{
listItem.removeStyle( 'direction' );
listItem.removeAttribute( 'dir' );
}
contentBlock.moveChildren( listItem );
contentBlock.remove();
}
listItem.appendTo( listNode );
}
// Apply list root dir only if it has been explicitly declared.
if ( listDir && explicitDirection )
listNode.setAttribute( 'dir', listDir );
if ( insertAnchor )
listNode.insertBefore( insertAnchor );
else
listNode.appendTo( commonParent );
}
function removeList( editor, groupObj, database )
{
// This is very much like the change list type operation.
// Except that we're changing the selected items' indent to -1 in the list array.
var listArray = CKEDITOR.plugins.list.listToArray( groupObj.root, database ),
selectedListItems = [];
for ( var i = 0 ; i < groupObj.contents.length ; i++ )
{
var itemNode = groupObj.contents[i];
itemNode = itemNode.getAscendant( 'li', true );
if ( !itemNode || itemNode.getCustomData( 'list_item_processed' ) )
continue;
selectedListItems.push( itemNode );
CKEDITOR.dom.element.setMarker( database, itemNode, 'list_item_processed', true );
}
var lastListIndex = null;
for ( i = 0 ; i < selectedListItems.length ; i++ )
{
var listIndex = selectedListItems[i].getCustomData( 'listarray_index' );
listArray[listIndex].indent = -1;
lastListIndex = listIndex;
}
// After cutting parts of the list out with indent=-1, we still have to maintain the array list
// model's nextItem.indent <= currentItem.indent + 1 invariant. Otherwise the array model of the
// list cannot be converted back to a real DOM list.
for ( i = lastListIndex + 1 ; i < listArray.length ; i++ )
{
if ( listArray[i].indent > listArray[i-1].indent + 1 )
{
var indentOffset = listArray[i-1].indent + 1 - listArray[i].indent;
var oldIndent = listArray[i].indent;
while ( listArray[i] && listArray[i].indent >= oldIndent )
{
listArray[i].indent += indentOffset;
i++;
}
i--;
}
}
var newList = CKEDITOR.plugins.list.arrayToList( listArray, database, null, editor.config.enterMode,
groupObj.root.getAttribute( 'dir' ) );
// Compensate <br> before/after the list node if the surrounds are non-blocks.(#3836)
var docFragment = newList.listNode, boundaryNode, siblingNode;
function compensateBrs( isStart )
{
if ( ( boundaryNode = docFragment[ isStart ? 'getFirst' : 'getLast' ]() )
&& !( boundaryNode.is && boundaryNode.isBlockBoundary() )
&& ( siblingNode = groupObj.root[ isStart ? 'getPrevious' : 'getNext' ]
( CKEDITOR.dom.walker.whitespaces( true ) ) )
&& !( siblingNode.is && siblingNode.isBlockBoundary( { br : 1 } ) ) )
editor.document.createElement( 'br' )[ isStart ? 'insertBefore' : 'insertAfter' ]( boundaryNode );
}
compensateBrs( true );
compensateBrs();
docFragment.replace( groupObj.root );
}
function listCommand( name, type )
{
this.name = name;
this.type = type;
}
// Move direction attribute from root to list items.
function dirToListItems( list )
{
var dir = list.getDirection();
if ( dir )
{
for ( var i = 0, children = list.getChildren(), child; child = children.getItem( i ), i < children.count(); i++ )
{
if ( child.type == CKEDITOR.NODE_ELEMENT && child.is( 'li' ) && !child.getDirection() )
child.setAttribute( 'dir', dir );
}
list.removeAttribute( 'dir' );
}
}
listCommand.prototype = {
exec : function( editor )
{
var doc = editor.document,
config = editor.config,
selection = editor.getSelection(),
ranges = selection && selection.getRanges( true );
// There should be at least one selected range.
if ( !ranges || ranges.length < 1 )
return;
// Midas lists rule #1 says we can create a list even in an empty document.
// But DOM iterator wouldn't run if the document is really empty.
// So create a paragraph if the document is empty and we're going to create a list.
if ( this.state == CKEDITOR.TRISTATE_OFF )
{
var body = doc.getBody();
if ( !body.getFirst( nonEmpty ) )
{
config.enterMode == CKEDITOR.ENTER_BR ?
body.appendBogus() :
ranges[ 0 ].fixBlock( 1, config.enterMode == CKEDITOR.ENTER_P ? 'p' : 'div' );
selection.selectRanges( ranges );
}
// Maybe a single range there enclosing the whole list,
// turn on the list state manually(#4129).
else
{
var range = ranges.length == 1 && ranges[ 0 ],
enclosedNode = range && range.getEnclosedNode();
if ( enclosedNode && enclosedNode.is
&& this.type == enclosedNode.getName() )
this.setState( CKEDITOR.TRISTATE_ON );
}
}
var bookmarks = selection.createBookmarks( true );
// Group the blocks up because there are many cases where multiple lists have to be created,
// or multiple lists have to be cancelled.
var listGroups = [],
database = {},
rangeIterator = ranges.createIterator(),
index = 0;
while ( ( range = rangeIterator.getNextRange() ) && ++index )
{
var boundaryNodes = range.getBoundaryNodes(),
startNode = boundaryNodes.startNode,
endNode = boundaryNodes.endNode;
if ( startNode.type == CKEDITOR.NODE_ELEMENT && startNode.getName() == 'td' )
range.setStartAt( boundaryNodes.startNode, CKEDITOR.POSITION_AFTER_START );
if ( endNode.type == CKEDITOR.NODE_ELEMENT && endNode.getName() == 'td' )
range.setEndAt( boundaryNodes.endNode, CKEDITOR.POSITION_BEFORE_END );
var iterator = range.createIterator(),
block;
iterator.forceBrBreak = ( this.state == CKEDITOR.TRISTATE_OFF );
while ( ( block = iterator.getNextParagraph() ) )
{
// Avoid duplicate blocks get processed across ranges.
if( block.getCustomData( 'list_block' ) )
continue;
else
CKEDITOR.dom.element.setMarker( database, block, 'list_block', 1 );
var path = new CKEDITOR.dom.elementPath( block ),
pathElements = path.elements,
pathElementsCount = pathElements.length,
listNode = null,
processedFlag = 0,
blockLimit = path.blockLimit,
element;
// First, try to group by a list ancestor.
for ( var i = pathElementsCount - 1; i >= 0 && ( element = pathElements[ i ] ); i-- )
{
if ( listNodeNames[ element.getName() ]
&& blockLimit.contains( element ) ) // Don't leak outside block limit (#3940).
{
// If we've encountered a list inside a block limit
// The last group object of the block limit element should
// no longer be valid. Since paragraphs after the list
// should belong to a different group of paragraphs before
// the list. (Bug #1309)
blockLimit.removeCustomData( 'list_group_object_' + index );
var groupObj = element.getCustomData( 'list_group_object' );
if ( groupObj )
groupObj.contents.push( block );
else
{
groupObj = { root : element, contents : [ block ] };
listGroups.push( groupObj );
CKEDITOR.dom.element.setMarker( database, element, 'list_group_object', groupObj );
}
processedFlag = 1;
break;
}
}
if ( processedFlag )
continue;
// No list ancestor? Group by block limit, but don't mix contents from different ranges.
var root = blockLimit;
if ( root.getCustomData( 'list_group_object_' + index ) )
root.getCustomData( 'list_group_object_' + index ).contents.push( block );
else
{
groupObj = { root : root, contents : [ block ] };
CKEDITOR.dom.element.setMarker( database, root, 'list_group_object_' + index, groupObj );
listGroups.push( groupObj );
}
}
}
// Now we have two kinds of list groups, groups rooted at a list, and groups rooted at a block limit element.
// We either have to build lists or remove lists, for removing a list does not makes sense when we are looking
// at the group that's not rooted at lists. So we have three cases to handle.
var listsCreated = [];
while ( listGroups.length > 0 )
{
groupObj = listGroups.shift();
if ( this.state == CKEDITOR.TRISTATE_OFF )
{
if ( listNodeNames[ groupObj.root.getName() ] )
changeListType.call( this, editor, groupObj, database, listsCreated );
else
createList.call( this, editor, groupObj, listsCreated );
}
else if ( this.state == CKEDITOR.TRISTATE_ON && listNodeNames[ groupObj.root.getName() ] )
removeList.call( this, editor, groupObj, database );
}
// For all new lists created, merge adjacent, same type lists.
for ( i = 0 ; i < listsCreated.length ; i++ )
{
listNode = listsCreated[i];
var mergeSibling, listCommand = this;
( mergeSibling = function( rtl ){
var sibling = listNode[ rtl ?
'getPrevious' : 'getNext' ]( CKEDITOR.dom.walker.whitespaces( true ) );
if ( sibling && sibling.getName &&
sibling.getName() == listCommand.type )
{
// In case to be merged lists have difference directions. (#7448)
if ( sibling.getDirection( 1 ) != listNode.getDirection( 1 ) )
dirToListItems( listNode.getDirection() ? listNode : sibling );
sibling.remove();
// Move children order by merge direction.(#3820)
sibling.moveChildren( listNode, rtl );
}
} )();
mergeSibling( 1 );
}
// Clean up, restore selection and update toolbar button states.
CKEDITOR.dom.element.clearAllMarkers( database );
selection.selectBookmarks( bookmarks );
editor.focus();
}
};
var dtd = CKEDITOR.dtd;
var tailNbspRegex = /[\t\r\n ]*(?: |\xa0)$/;
function indexOfFirstChildElement( element, tagNameList )
{
var child,
children = element.children,
length = children.length;
for ( var i = 0 ; i < length ; i++ )
{
child = children[ i ];
if ( child.name && ( child.name in tagNameList ) )
return i;
}
return length;
}
function getExtendNestedListFilter( isHtmlFilter )
{
// An element filter function that corrects nested list start in an empty
// list item for better displaying/outputting. (#3165)
return function( listItem )
{
var children = listItem.children,
firstNestedListIndex = indexOfFirstChildElement( listItem, dtd.$list ),
firstNestedList = children[ firstNestedListIndex ],
nodeBefore = firstNestedList && firstNestedList.previous,
tailNbspmatch;
if ( nodeBefore
&& ( nodeBefore.name && nodeBefore.name == 'br'
|| nodeBefore.value && ( tailNbspmatch = nodeBefore.value.match( tailNbspRegex ) ) ) )
{
var fillerNode = nodeBefore;
// Always use 'nbsp' as filler node if we found a nested list appear
// in front of a list item.
if ( !( tailNbspmatch && tailNbspmatch.index ) && fillerNode == children[ 0 ] )
children[ 0 ] = ( isHtmlFilter || CKEDITOR.env.ie ) ?
new CKEDITOR.htmlParser.text( '\xa0' ) :
new CKEDITOR.htmlParser.element( 'br', {} );
// Otherwise the filler is not needed anymore.
else if ( fillerNode.name == 'br' )
children.splice( firstNestedListIndex - 1, 1 );
else
fillerNode.value = fillerNode.value.replace( tailNbspRegex, '' );
}
};
}
var defaultListDataFilterRules = { elements : {} };
for ( var i in dtd.$listItem )
defaultListDataFilterRules.elements[ i ] = getExtendNestedListFilter();
var defaultListHtmlFilterRules = { elements : {} };
for ( i in dtd.$listItem )
defaultListHtmlFilterRules.elements[ i ] = getExtendNestedListFilter( true );
CKEDITOR.plugins.add( 'list',
{
init : function( editor )
{
// Register commands.
var numberedListCommand = editor.addCommand( 'numberedlist', new listCommand( 'numberedlist', 'ol' ) ),
bulletedListCommand = editor.addCommand( 'bulletedlist', new listCommand( 'bulletedlist', 'ul' ) );
// Register the toolbar button.
editor.ui.addButton( 'NumberedList',
{
label : editor.lang.numberedlist,
command : 'numberedlist'
} );
editor.ui.addButton( 'BulletedList',
{
label : editor.lang.bulletedlist,
command : 'bulletedlist'
} );
// Register the state changing handlers.
editor.on( 'selectionChange', CKEDITOR.tools.bind( onSelectionChange, numberedListCommand ) );
editor.on( 'selectionChange', CKEDITOR.tools.bind( onSelectionChange, bulletedListCommand ) );
},
afterInit : function ( editor )
{
var dataProcessor = editor.dataProcessor;
if ( dataProcessor )
{
dataProcessor.dataFilter.addRules( defaultListDataFilterRules );
dataProcessor.htmlFilter.addRules( defaultListHtmlFilterRules );
}
},
requires : [ 'domiterator' ]
} );
})(); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/_source/plugins/list/plugin.js | plugin.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
CKEDITOR.plugins.add( 'stylescombo',
{
requires : [ 'richcombo', 'styles' ],
init : function( editor )
{
var config = editor.config,
lang = editor.lang.stylesCombo,
styles = {},
stylesList = [],
combo;
function loadStylesSet( callback )
{
editor.getStylesSet( function( stylesDefinitions )
{
if ( !stylesList.length )
{
var style,
styleName;
// Put all styles into an Array.
for ( var i = 0, count = stylesDefinitions.length ; i < count ; i++ )
{
var styleDefinition = stylesDefinitions[ i ];
styleName = styleDefinition.name;
style = styles[ styleName ] = new CKEDITOR.style( styleDefinition );
style._name = styleName;
style._.enterMode = config.enterMode;
stylesList.push( style );
}
// Sorts the Array, so the styles get grouped by type.
stylesList.sort( sortStyles );
}
callback && callback();
});
}
editor.ui.addRichCombo( 'Styles',
{
label : lang.label,
title : lang.panelTitle,
className : 'cke_styles',
panel :
{
css : editor.skin.editor.css.concat( config.contentsCss ),
multiSelect : true,
attributes : { 'aria-label' : lang.panelTitle }
},
init : function()
{
combo = this;
loadStylesSet( function()
{
var style,
styleName,
lastType,
type,
i,
count;
// Loop over the Array, adding all items to the
// combo.
for ( i = 0, count = stylesList.length ; i < count ; i++ )
{
style = stylesList[ i ];
styleName = style._name;
type = style.type;
if ( type != lastType )
{
combo.startGroup( lang[ 'panelTitle' + String( type ) ] );
lastType = type;
}
combo.add(
styleName,
style.type == CKEDITOR.STYLE_OBJECT ? styleName : style.buildPreview(),
styleName );
}
combo.commit();
});
},
onClick : function( value )
{
editor.focus();
editor.fire( 'saveSnapshot' );
var style = styles[ value ],
selection = editor.getSelection(),
elementPath = new CKEDITOR.dom.elementPath( selection.getStartElement() );
style[ style.checkActive( elementPath ) ? 'remove' : 'apply' ]( editor.document );
editor.fire( 'saveSnapshot' );
},
onRender : function()
{
editor.on( 'selectionChange', function( ev )
{
var currentValue = this.getValue(),
elementPath = ev.data.path,
elements = elementPath.elements;
// For each element into the elements path.
for ( var i = 0, count = elements.length, element ; i < count ; i++ )
{
element = elements[i];
// Check if the element is removable by any of
// the styles.
for ( var value in styles )
{
if ( styles[ value ].checkElementRemovable( element, true ) )
{
if ( value != currentValue )
this.setValue( value );
return;
}
}
}
// If no styles match, just empty it.
this.setValue( '' );
},
this);
},
onOpen : function()
{
if ( CKEDITOR.env.ie || CKEDITOR.env.webkit )
editor.focus();
var selection = editor.getSelection(),
element = selection.getSelectedElement(),
elementPath = new CKEDITOR.dom.elementPath( element || selection.getStartElement() ),
counter = [ 0, 0, 0, 0 ];
this.showAll();
this.unmarkAll();
for ( var name in styles )
{
var style = styles[ name ],
type = style.type;
if ( style.checkActive( elementPath ) )
this.mark( name );
else if ( type == CKEDITOR.STYLE_OBJECT && !style.checkApplicable( elementPath ) )
{
this.hideItem( name );
counter[ type ]--;
}
counter[ type ]++;
}
if ( !counter[ CKEDITOR.STYLE_BLOCK ] )
this.hideGroup( lang[ 'panelTitle' + String( CKEDITOR.STYLE_BLOCK ) ] );
if ( !counter[ CKEDITOR.STYLE_INLINE ] )
this.hideGroup( lang[ 'panelTitle' + String( CKEDITOR.STYLE_INLINE ) ] );
if ( !counter[ CKEDITOR.STYLE_OBJECT ] )
this.hideGroup( lang[ 'panelTitle' + String( CKEDITOR.STYLE_OBJECT ) ] );
},
// Force a reload of the data
reset: function()
{
if ( combo )
{
delete combo._.panel;
delete combo._.list;
combo._.committed = 0;
combo._.items = {};
combo._.state = CKEDITOR.TRISTATE_OFF;
}
styles = {};
stylesList = [];
loadStylesSet();
}
});
editor.on( 'instanceReady', function() { loadStylesSet(); } );
}
});
function sortStyles( styleA, styleB )
{
var typeA = styleA.type,
typeB = styleB.type;
return typeA == typeB ? 0 :
typeA == CKEDITOR.STYLE_OBJECT ? -1 :
typeB == CKEDITOR.STYLE_OBJECT ? 1 :
typeB == CKEDITOR.STYLE_BLOCK ? 1 :
-1;
}
})(); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/_source/plugins/stylescombo/plugin.js | plugin.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @file Horizontal Page Break
*/
// Register a plugin named "pagebreak".
CKEDITOR.plugins.add( 'pagebreak',
{
init : function( editor )
{
// Register the command.
editor.addCommand( 'pagebreak', CKEDITOR.plugins.pagebreakCmd );
// Register the toolbar button.
editor.ui.addButton( 'PageBreak',
{
label : editor.lang.pagebreak,
command : 'pagebreak'
});
var cssStyles = [
'{' ,
'background: url(' + CKEDITOR.getUrl( this.path + 'images/pagebreak.gif' ) + ') no-repeat center center;' ,
'clear: both;' ,
'width:100%; _width:99.9%;' ,
'border-top: #999999 1px dotted;' ,
'border-bottom: #999999 1px dotted;' ,
'padding:0;' ,
'height: 5px;' ,
'cursor: default;' ,
'}'
].join( '' ).replace(/;/g, ' !important;' ); // Increase specificity to override other styles, e.g. block outline.
// Add the style that renders our placeholder.
editor.addCss( 'div.cke_pagebreak' + cssStyles );
// Opera needs help to select the page-break.
CKEDITOR.env.opera && editor.on( 'contentDom', function()
{
editor.document.on( 'click', function( evt )
{
var target = evt.data.getTarget();
if ( target.is( 'div' ) && target.hasClass( 'cke_pagebreak') )
editor.getSelection().selectElement( target );
});
});
},
afterInit : function( editor )
{
var label = editor.lang.pagebreakAlt;
// Register a filter to displaying placeholders after mode change.
var dataProcessor = editor.dataProcessor,
dataFilter = dataProcessor && dataProcessor.dataFilter,
htmlFilter = dataProcessor && dataProcessor.htmlFilter;
if ( htmlFilter )
{
htmlFilter.addRules(
{
attributes : {
'class' : function( value, element )
{
var className = value.replace( 'cke_pagebreak', '' );
if ( className != value )
{
var span = CKEDITOR.htmlParser.fragment.fromHtml( '<span style="display: none;"> </span>' );
element.children.length = 0;
element.add( span );
var attrs = element.attributes;
delete attrs[ 'aria-label' ];
delete attrs.contenteditable;
delete attrs.title;
}
return className;
}
}
}, 5 );
}
if ( dataFilter )
{
dataFilter.addRules(
{
elements :
{
div : function( element )
{
var attributes = element.attributes,
style = attributes && attributes.style,
child = style && element.children.length == 1 && element.children[ 0 ],
childStyle = child && ( child.name == 'span' ) && child.attributes.style;
if ( childStyle && ( /page-break-after\s*:\s*always/i ).test( style ) && ( /display\s*:\s*none/i ).test( childStyle ) )
{
attributes.contenteditable = "false";
attributes[ 'class' ] = "cke_pagebreak";
attributes[ 'data-cke-display-name' ] = "pagebreak";
attributes[ 'aria-label' ] = label;
attributes[ 'title' ] = label;
element.children.length = 0;
}
}
}
});
}
},
requires : [ 'fakeobjects' ]
});
CKEDITOR.plugins.pagebreakCmd =
{
exec : function( editor )
{
var label = editor.lang.pagebreakAlt;
// Create read-only element that represents a print break.
var pagebreak = CKEDITOR.dom.element.createFromHtml(
'<div style="' +
'page-break-after: always;"' +
'contenteditable="false" ' +
'title="'+ label + '" ' +
'aria-label="'+ label + '" ' +
'data-cke-display-name="pagebreak" ' +
'class="cke_pagebreak">' +
'</div>', editor.document );
var ranges = editor.getSelection().getRanges( true );
editor.fire( 'saveSnapshot' );
for ( var range, i = ranges.length - 1 ; i >= 0; i-- )
{
range = ranges[ i ];
if ( i < ranges.length -1 )
pagebreak = pagebreak.clone( true );
range.splitBlock( 'p' );
range.insertNode( pagebreak );
if ( i == ranges.length - 1 )
{
var next = pagebreak.getNext();
range.moveToPosition( pagebreak, CKEDITOR.POSITION_AFTER_END );
// If there's nothing or a non-editable block followed by, establish a new paragraph
// to make sure cursor is not trapped.
if ( !next || next.type == CKEDITOR.NODE_ELEMENT && !next.isEditable() )
range.fixBlock( true, editor.config.enterMode == CKEDITOR.ENTER_DIV ? 'div' : 'p' );
range.select();
}
}
editor.fire( 'saveSnapshot' );
}
}; | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/_source/plugins/pagebreak/plugin.js | plugin.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.add( 'devtools',
{
lang : [ 'en' ],
init : function( editor )
{
editor._.showDialogDefinitionTooltips = 1;
},
onLoad : function()
{
CKEDITOR.document.appendStyleText( CKEDITOR.config.devtools_styles ||
'#cke_tooltip { padding: 5px; border: 2px solid #333; background: #ffffff }' +
'#cke_tooltip h2 { font-size: 1.1em; border-bottom: 1px solid; margin: 0; padding: 1px; }' +
'#cke_tooltip ul { padding: 0pt; list-style-type: none; }' );
}
});
(function()
{
function defaultCallback( editor, dialog, element, tabName )
{
var lang = editor.lang.devTools,
link = '<a href="http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.dialog.definition.' +
( element ? ( element.type == 'text' ? 'textInput' : element.type ) : 'content' ) +
'.html" target="_blank">' + ( element ? element.type : 'content' ) + '</a>',
str =
'<h2>' + lang.title + '</h2>' +
'<ul>' +
'<li><strong>' + lang.dialogName + '</strong> : ' + dialog.getName() + '</li>' +
'<li><strong>' + lang.tabName + '</strong> : ' + tabName + '</li>';
if ( element )
str += '<li><strong>' + lang.elementId + '</strong> : ' + element.id + '</li>';
str += '<li><strong>' + lang.elementType + '</strong> : ' + link + '</li>';
return str + '</ul>';
}
function showTooltip( callback, el, editor, dialog, obj, tabName )
{
var pos = el.getDocumentPosition(),
styles = { 'z-index' : CKEDITOR.dialog._.currentZIndex + 10, top : ( pos.y + el.getSize( 'height' ) ) + 'px' };
tooltip.setHtml( callback( editor, dialog, obj, tabName ) );
tooltip.show();
// Translate coordinate for RTL.
if ( editor.lang.dir == 'rtl' )
{
var viewPaneSize = CKEDITOR.document.getWindow().getViewPaneSize();
styles.right = ( viewPaneSize.width - pos.x - el.getSize( 'width' ) ) + 'px';
}
else
styles.left = pos.x + 'px';
tooltip.setStyles( styles );
}
var tooltip;
CKEDITOR.on( 'reset', function()
{
tooltip && tooltip.remove();
tooltip = null;
});
CKEDITOR.on( 'dialogDefinition', function( evt )
{
var editor = evt.editor;
if ( editor._.showDialogDefinitionTooltips )
{
if ( !tooltip )
{
tooltip = CKEDITOR.dom.element.createFromHtml( '<div id="cke_tooltip" tabindex="-1" style="position: absolute"></div>', CKEDITOR.document );
tooltip.hide();
tooltip.on( 'mouseover', function(){ this.show(); } );
tooltip.on( 'mouseout', function(){ this.hide(); } );
tooltip.appendTo( CKEDITOR.document.getBody() );
}
var dialog = evt.data.definition.dialog,
callback = editor.config.devtools_textCallback || defaultCallback;
dialog.on( 'load', function()
{
var tabs = dialog.parts.tabs.getChildren(), tab;
for ( var i = 0, len = tabs.count(); i < len; i++ )
{
tab = tabs.getItem( i );
tab.on( 'mouseover', function()
{
var id = this.$.id;
showTooltip( callback, this, editor, dialog, null, id.substring( 4, id.lastIndexOf( '_' ) ) );
});
tab.on( 'mouseout', function()
{
tooltip.hide();
});
}
dialog.foreach( function( obj )
{
if ( obj.type in { hbox : 1, vbox : 1 } )
return;
var el = obj.getElement();
if ( el )
{
el.on( 'mouseover', function()
{
showTooltip( callback, this, editor, dialog, obj, dialog._.currentTabId );
});
el.on( 'mouseout', function()
{
tooltip.hide();
});
}
});
});
}
});
})();
/**
* A function that returns the text to be displayed inside the Developer Tools tooltip when hovering over a dialog UI element.
* There are 4 parameters that are being passed into the function: editor, dialog window, element, tab name.
* @name editor.config.devtools_textCallback
* @since 3.6
* @type Function
* @default (see example)
* @example
* // This is actually the default value.
* // Show dialog window name, tab ID, and element ID.
* config.devtools_textCallback = function( editor, dialog, element, tabName )
* {
* var lang = editor.lang.devTools,
* link = '<a href="http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.dialog.definition.' +
* ( element ? ( element.type == 'text' ? 'textInput' : element.type ) : 'content' ) +
* '.html" target="_blank">' + ( element ? element.type : 'content' ) + '</a>',
* str =
* '<h2>' + lang.title + '</h2>' +
* '<ul>' +
* '<li><strong>' + lang.dialogName + '</strong> : ' + dialog.getName() + '</li>' +
* '<li><strong>' + lang.tabName + '</strong> : ' + tabName + '</li>';
*
* if ( element )
* str += '<li><strong>' + lang.elementId + '</strong> : ' + element.id + '</li>';
*
* str += '<li><strong>' + lang.elementType + '</strong> : ' + link + '</li>';
*
* return str + '</ul>';
* }
*/
/**
* A setting that stores CSS rules to be injected into the page with styles to be applied to the tooltip element.
* @name CKEDITOR.config.devtools_styles
* @since 3.6
* @type String
* @default (see example)
* @example
* // This is actually the default value.
* CKEDITOR.config.devtools_styles = "
* #cke_tooltip { padding: 5px; border: 2px solid #333; background: #ffffff }
* #cke_tooltip h2 { font-size: 1.1em; border-bottom: 1px solid; margin: 0; padding: 1px; }
* #cke_tooltip ul { padding: 0pt; list-style-type: none; }
* ";
*/ | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/_source/plugins/devtools/plugin.js | plugin.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.add( 'listblock',
{
requires : [ 'panel' ],
onLoad : function()
{
CKEDITOR.ui.panel.prototype.addListBlock = function( name, definition )
{
return this.addBlock( name, new CKEDITOR.ui.listBlock( this.getHolderElement(), definition ) );
};
CKEDITOR.ui.listBlock = CKEDITOR.tools.createClass(
{
base : CKEDITOR.ui.panel.block,
$ : function( blockHolder, blockDefinition )
{
blockDefinition = blockDefinition || {};
var attribs = blockDefinition.attributes || ( blockDefinition.attributes = {} );
( this.multiSelect = !!blockDefinition.multiSelect ) &&
( attribs[ 'aria-multiselectable' ] = true );
// Provide default role of 'listbox'.
!attribs.role && ( attribs.role = 'listbox' );
// Call the base contructor.
this.base.apply( this, arguments );
var keys = this.keys;
keys[ 40 ] = 'next'; // ARROW-DOWN
keys[ 9 ] = 'next'; // TAB
keys[ 38 ] = 'prev'; // ARROW-UP
keys[ CKEDITOR.SHIFT + 9 ] = 'prev'; // SHIFT + TAB
keys[ 32 ] = CKEDITOR.env.ie ? 'mouseup' : 'click'; // SPACE
CKEDITOR.env.ie && ( keys[ 13 ] = 'mouseup' ); // Manage ENTER, since onclick is blocked in IE (#8041).
this._.pendingHtml = [];
this._.items = {};
this._.groups = {};
},
_ :
{
close : function()
{
if ( this._.started )
{
this._.pendingHtml.push( '</ul>' );
delete this._.started;
}
},
getClick : function()
{
if ( !this._.click )
{
this._.click = CKEDITOR.tools.addFunction( function( value )
{
var marked = true;
if ( this.multiSelect )
marked = this.toggle( value );
else
this.mark( value );
if ( this.onClick )
this.onClick( value, marked );
},
this );
}
return this._.click;
}
},
proto :
{
add : function( value, html, title )
{
var pendingHtml = this._.pendingHtml,
id = CKEDITOR.tools.getNextId();
if ( !this._.started )
{
pendingHtml.push( '<ul role="presentation" class=cke_panel_list>' );
this._.started = 1;
this._.size = this._.size || 0;
}
this._.items[ value ] = id;
pendingHtml.push(
'<li id=', id, ' class=cke_panel_listItem role=presentation>' +
'<a id="', id, '_option" _cke_focus=1 hidefocus=true' +
' title="', title || value, '"' +
' href="javascript:void(\'', value, '\')" ' +
( CKEDITOR.env.ie ? 'onclick="return false;" onmouseup' : 'onclick' ) + // #188
'="CKEDITOR.tools.callFunction(', this._.getClick(), ',\'', value, '\'); return false;"',
' role="option"' +
' aria-posinset="' + ++this._.size + '">',
html || value,
'</a>' +
'</li>' );
},
startGroup : function( title )
{
this._.close();
var id = CKEDITOR.tools.getNextId();
this._.groups[ title ] = id;
this._.pendingHtml.push( '<h1 role="presentation" id=', id, ' class=cke_panel_grouptitle>', title, '</h1>' );
},
commit : function()
{
this._.close();
this.element.appendHtml( this._.pendingHtml.join( '' ) );
var items = this._.items,
doc = this.element.getDocument();
for ( var value in items )
doc.getById( items[ value ] + '_option' ).setAttribute( 'aria-setsize', this._.size );
delete this._.size;
this._.pendingHtml = [];
},
toggle : function( value )
{
var isMarked = this.isMarked( value );
if ( isMarked )
this.unmark( value );
else
this.mark( value );
return !isMarked;
},
hideGroup : function( groupTitle )
{
var group = this.element.getDocument().getById( this._.groups[ groupTitle ] ),
list = group && group.getNext();
if ( group )
{
group.setStyle( 'display', 'none' );
if ( list && list.getName() == 'ul' )
list.setStyle( 'display', 'none' );
}
},
hideItem : function( value )
{
this.element.getDocument().getById( this._.items[ value ] ).setStyle( 'display', 'none' );
},
showAll : function()
{
var items = this._.items,
groups = this._.groups,
doc = this.element.getDocument();
for ( var value in items )
{
doc.getById( items[ value ] ).setStyle( 'display', '' );
}
for ( var title in groups )
{
var group = doc.getById( groups[ title ] ),
list = group.getNext();
group.setStyle( 'display', '' );
if ( list && list.getName() == 'ul' )
list.setStyle( 'display', '' );
}
},
mark : function( value )
{
if ( !this.multiSelect )
this.unmarkAll();
var itemId = this._.items[ value ],
item = this.element.getDocument().getById( itemId );
item.addClass( 'cke_selected' );
this.element.getDocument().getById( itemId + '_option' ).setAttribute( 'aria-selected', true );
this.onMark && this.onMark( item );
},
unmark : function( value )
{
var doc = this.element.getDocument(),
itemId = this._.items[ value ],
item = doc.getById( itemId );
item.removeClass( 'cke_selected' );
doc.getById( itemId + '_option' ).removeAttribute( 'aria-selected' );
this.onUnmark && this.onUnmark( item );
},
unmarkAll : function()
{
var items = this._.items,
doc = this.element.getDocument();
for ( var value in items )
{
var itemId = items[ value ];
doc.getById( itemId ).removeClass( 'cke_selected' );
doc.getById( itemId + '_option' ).removeAttribute( 'aria-selected' );
}
this.onUnmark && this.onUnmark();
},
isMarked : function( value )
{
return this.element.getDocument().getById( this._.items[ value ] ).hasClass( 'cke_selected' );
},
focus : function( value )
{
this._.focusIndex = -1;
if ( value )
{
var selected = this.element.getDocument().getById( this._.items[ value ] ).getFirst();
var links = this.element.getElementsByTag( 'a' ),
link,
i = -1;
while ( ( link = links.getItem( ++i ) ) )
{
if ( link.equals( selected ) )
{
this._.focusIndex = i;
break;
}
}
setTimeout( function()
{
selected.focus();
},
0 );
}
}
}
});
}
}); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/_source/plugins/listblock/plugin.js | plugin.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add( 'uicolor', function( editor )
{
var dialog, picker, pickerContents,
// Actual UI color value.
uiColor = editor.getUiColor(),
pickerId = 'cke_uicolor_picker' + CKEDITOR.tools.getNextNumber();
function setNewPickerColor( color )
{
// Convert HEX representation to RGB, stripping # char.
if ( /^#/.test( color ) )
color = window.YAHOO.util.Color.hex2rgb( color.substr( 1 ) );
picker.setValue( color, true );
// Refresh picker UI.
picker.refresh( pickerId );
}
function setNewUiColor( color, force )
{
if ( force || dialog._.contents.tab1.livePeview.getValue() )
editor.setUiColor( color );
// Write new config string into textbox.
dialog._.contents.tab1.configBox.setValue(
'config.uiColor = "#' + picker.get( "hex" ) + '"'
);
}
pickerContents =
{
id : 'yuiColorPicker',
type : 'html',
html : "<div id='" + pickerId + "' class='cke_uicolor_picker' style='width: 360px; height: 200px; position: relative;'></div>",
onLoad : function( event )
{
var url = CKEDITOR.getUrl(
'_source/' + // @Packager.RemoveLine
'plugins/uicolor/yui/'
);
// Create new color picker widget.
picker = new window.YAHOO.widget.ColorPicker( pickerId,
{
showhsvcontrols : true,
showhexcontrols : true,
images :
{
PICKER_THUMB : url + "assets/picker_thumb.png",
HUE_THUMB : url + "assets/hue_thumb.png"
}
});
// Set actual UI color to the picker.
if ( uiColor )
setNewPickerColor( uiColor );
// Subscribe to the rgbChange event.
picker.on( "rgbChange", function()
{
// Reset predefined box.
dialog._.contents.tab1.predefined.setValue( '' );
setNewUiColor( '#' + picker.get( 'hex' ) );
});
// Fix input class names.
var inputs = new CKEDITOR.dom.nodeList( picker.getElementsByTagName( 'input' ) );
for ( var i = 0; i < inputs.count() ; i++ )
inputs.getItem( i ).addClass( 'cke_dialog_ui_input_text' );
}
};
var skipPreviewChange = true;
return {
title : editor.lang.uicolor.title,
minWidth : 360,
minHeight : 320,
onLoad : function()
{
dialog = this;
this.setupContent();
// #3808
if ( CKEDITOR.env.ie7Compat )
dialog.parts.contents.setStyle( 'overflow', 'hidden' );
},
contents : [
{
id : 'tab1',
label : '',
title : '',
expand : true,
padding : 0,
elements : [
pickerContents,
{
id : 'tab1',
type : 'vbox',
children :
[
{
id : 'livePeview',
type : 'checkbox',
label : editor.lang.uicolor.preview,
'default' : 1,
onLoad : function()
{
skipPreviewChange = true;
},
onChange : function()
{
if ( skipPreviewChange )
return;
var on = this.getValue(),
color = on ? '#' + picker.get( 'hex' ) : uiColor;
setNewUiColor( color, true );
}
},
{
type : 'hbox',
children :
[
{
id : 'predefined',
type : 'select',
'default' : '',
label : editor.lang.uicolor.predefined,
items :
[
[ '' ],
[ 'Light blue', '#9AB8F3' ],
[ 'Sand', '#D2B48C' ],
[ 'Metallic', '#949AAA' ],
[ 'Purple', '#C2A3C7' ],
[ 'Olive', '#A2C980' ],
[ 'Happy green', '#9BD446' ],
[ 'Jezebel Blue', '#14B8C4' ],
[ 'Burn', '#FF893A' ],
[ 'Easy red', '#FF6969' ],
[ 'Pisces 3', '#48B4F2' ],
[ 'Aquarius 5', '#487ED4' ],
[ 'Absinthe', '#A8CF76' ],
[ 'Scrambled Egg', '#C7A622' ],
[ 'Hello monday', '#8E8D80' ],
[ 'Lovely sunshine', '#F1E8B1' ],
[ 'Recycled air', '#B3C593' ],
[ 'Down', '#BCBCA4' ],
[ 'Mark Twain', '#CFE91D' ],
[ 'Specks of dust', '#D1B596' ],
[ 'Lollipop', '#F6CE23' ]
],
onChange : function()
{
var color = this.getValue();
if ( color )
{
setNewPickerColor( color );
setNewUiColor( color );
// Refresh predefined preview box.
CKEDITOR.document.getById( 'predefinedPreview' ).setStyle( 'background', color );
}
else
CKEDITOR.document.getById( 'predefinedPreview' ).setStyle( 'background', '' );
},
onShow : function()
{
var color = editor.getUiColor();
if ( color )
this.setValue( color );
}
},
{
id : 'predefinedPreview',
type : 'html',
html : '<div id="cke_uicolor_preview" style="border: 1px solid black; padding: 3px; width: 30px;">' +
'<div id="predefinedPreview" style="width: 30px; height: 30px;"> </div>' +
'</div>'
}
]
},
{
id : 'configBox',
type : 'text',
label : editor.lang.uicolor.config,
onShow : function()
{
var color = editor.getUiColor();
if ( color )
this.setValue(
'config.uiColor = "' + color + '"'
);
}
}
]
}
]
}
],
buttons : [ CKEDITOR.dialog.okButton ]
};
} ); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/_source/plugins/uicolor/dialogs/uicolor.js | uicolor.js |
/*jsl:ignoreall*/
/*
Copyright (c) 2009, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.7.0
*/
if(typeof YAHOO=="undefined"||!YAHOO){var YAHOO={};}YAHOO.namespace=function(){var A=arguments,E=null,C,B,D;for(C=0;C<A.length;C=C+1){D=(""+A[C]).split(".");E=YAHOO;for(B=(D[0]=="YAHOO")?1:0;B<D.length;B=B+1){E[D[B]]=E[D[B]]||{};E=E[D[B]];}}return E;};YAHOO.log=function(D,A,C){var B=YAHOO.widget.Logger;if(B&&B.log){return B.log(D,A,C);}else{return false;}};YAHOO.register=function(A,E,D){var I=YAHOO.env.modules,B,H,G,F,C;if(!I[A]){I[A]={versions:[],builds:[]};}B=I[A];H=D.version;G=D.build;F=YAHOO.env.listeners;B.name=A;B.version=H;B.build=G;B.versions.push(H);B.builds.push(G);B.mainClass=E;for(C=0;C<F.length;C=C+1){F[C](B);}if(E){E.VERSION=H;E.BUILD=G;}else{YAHOO.log("mainClass is undefined for module "+A,"warn");}};YAHOO.env=YAHOO.env||{modules:[],listeners:[]};YAHOO.env.getVersion=function(A){return YAHOO.env.modules[A]||null;};YAHOO.env.ua=function(){var C={ie:0,opera:0,gecko:0,webkit:0,mobile:null,air:0,caja:0},B=navigator.userAgent,A;if((/KHTML/).test(B)){C.webkit=1;}A=B.match(/AppleWebKit\/([^\s]*)/);if(A&&A[1]){C.webkit=parseFloat(A[1]);if(/ Mobile\//.test(B)){C.mobile="Apple";}else{A=B.match(/NokiaN[^\/]*/);if(A){C.mobile=A[0];}}A=B.match(/AdobeAIR\/([^\s]*)/);if(A){C.air=A[0];}}if(!C.webkit){A=B.match(/Opera[\s\/]([^\s]*)/);if(A&&A[1]){C.opera=parseFloat(A[1]);A=B.match(/Opera Mini[^;]*/);if(A){C.mobile=A[0];}}else{A=B.match(/MSIE\s([^;]*)/);if(A&&A[1]){C.ie=parseFloat(A[1]);}else{A=B.match(/Gecko\/([^\s]*)/);if(A){C.gecko=1;A=B.match(/rv:([^\s\)]*)/);if(A&&A[1]){C.gecko=parseFloat(A[1]);}}}}}A=B.match(/Caja\/([^\s]*)/);if(A&&A[1]){C.caja=parseFloat(A[1]);}return C;}();(function(){YAHOO.namespace("util","widget","example");if("undefined"!==typeof YAHOO_config){var B=YAHOO_config.listener,A=YAHOO.env.listeners,D=true,C;if(B){for(C=0;C<A.length;C=C+1){if(A[C]==B){D=false;break;}}if(D){A.push(B);}}}})();YAHOO.lang=YAHOO.lang||{};(function(){var B=YAHOO.lang,F="[object Array]",C="[object Function]",A=Object.prototype,E=["toString","valueOf"],D={isArray:function(G){return A.toString.apply(G)===F;},isBoolean:function(G){return typeof G==="boolean";},isFunction:function(G){return A.toString.apply(G)===C;},isNull:function(G){return G===null;},isNumber:function(G){return typeof G==="number"&&isFinite(G);},isObject:function(G){return(G&&(typeof G==="object"||B.isFunction(G)))||false;},isString:function(G){return typeof G==="string";},isUndefined:function(G){return typeof G==="undefined";},_IEEnumFix:(YAHOO.env.ua.ie)?function(I,H){var G,K,J;for(G=0;G<E.length;G=G+1){K=E[G];J=H[K];if(B.isFunction(J)&&J!=A[K]){I[K]=J;}}}:function(){},extend:function(J,K,I){if(!K||!J){throw new Error("extend failed, please check that "+"all dependencies are included.");}var H=function(){},G;H.prototype=K.prototype;J.prototype=new H();J.prototype.constructor=J;J.superclass=K.prototype;if(K.prototype.constructor==A.constructor){K.prototype.constructor=K;}if(I){for(G in I){if(B.hasOwnProperty(I,G)){J.prototype[G]=I[G];}}B._IEEnumFix(J.prototype,I);}},augmentObject:function(K,J){if(!J||!K){throw new Error("Absorb failed, verify dependencies.");}var G=arguments,I,L,H=G[2];if(H&&H!==true){for(I=2;I<G.length;I=I+1){K[G[I]]=J[G[I]];}}else{for(L in J){if(H||!(L in K)){K[L]=J[L];}}B._IEEnumFix(K,J);}},augmentProto:function(J,I){if(!I||!J){throw new Error("Augment failed, verify dependencies.");}var G=[J.prototype,I.prototype],H;for(H=2;H<arguments.length;H=H+1){G.push(arguments[H]);}B.augmentObject.apply(this,G);},dump:function(G,L){var I,K,N=[],O="{...}",H="f(){...}",M=", ",J=" => ";if(!B.isObject(G)){return G+"";}else{if(G instanceof Date||("nodeType" in G&&"tagName" in G)){return G;}else{if(B.isFunction(G)){return H;}}}L=(B.isNumber(L))?L:3;if(B.isArray(G)){N.push("[");for(I=0,K=G.length;I<K;I=I+1){if(B.isObject(G[I])){N.push((L>0)?B.dump(G[I],L-1):O);}else{N.push(G[I]);}N.push(M);}if(N.length>1){N.pop();}N.push("]");}else{N.push("{");for(I in G){if(B.hasOwnProperty(G,I)){N.push(I+J);if(B.isObject(G[I])){N.push((L>0)?B.dump(G[I],L-1):O);}else{N.push(G[I]);}N.push(M);}}if(N.length>1){N.pop();}N.push("}");}return N.join("");},substitute:function(V,H,O){var L,K,J,R,S,U,Q=[],I,M="dump",P=" ",G="{",T="}",N;for(;;){L=V.lastIndexOf(G);if(L<0){break;}K=V.indexOf(T,L);if(L+1>=K){break;}I=V.substring(L+1,K);R=I;U=null;J=R.indexOf(P);if(J>-1){U=R.substring(J+1);R=R.substring(0,J);}S=H[R];if(O){S=O(R,S,U);}if(B.isObject(S)){if(B.isArray(S)){S=B.dump(S,parseInt(U,10));}else{U=U||"";N=U.indexOf(M);if(N>-1){U=U.substring(4);}if(S.toString===A.toString||N>-1){S=B.dump(S,parseInt(U,10));}else{S=S.toString();}}}else{if(!B.isString(S)&&!B.isNumber(S)){S="~-"+Q.length+"-~";Q[Q.length]=I;}}V=V.substring(0,L)+S+V.substring(K+1);}for(L=Q.length-1;L>=0;L=L-1){V=V.replace(new RegExp("~-"+L+"-~"),"{"+Q[L]+"}","g");}return V;},trim:function(G){try{return G.replace(/^\s+|\s+$/g,"");}catch(H){return G;}},merge:function(){var J={},H=arguments,G=H.length,I;for(I=0;I<G;I=I+1){B.augmentObject(J,H[I],true);}return J;},later:function(N,H,O,J,K){N=N||0;H=H||{};var I=O,M=J,L,G;if(B.isString(O)){I=H[O];}if(!I){throw new TypeError("method undefined");}if(!B.isArray(M)){M=[J];}L=function(){I.apply(H,M);};G=(K)?setInterval(L,N):setTimeout(L,N);return{interval:K,cancel:function(){if(this.interval){clearInterval(G);}else{clearTimeout(G);}}};},isValue:function(G){return(B.isObject(G)||B.isString(G)||B.isNumber(G)||B.isBoolean(G));}};B.hasOwnProperty=(A.hasOwnProperty)?function(G,H){return G&&G.hasOwnProperty(H);}:function(G,H){return !B.isUndefined(G[H])&&G.constructor.prototype[H]!==G[H];};D.augmentObject(B,D,true);YAHOO.util.Lang=B;B.augment=B.augmentProto;YAHOO.augment=B.augmentProto;YAHOO.extend=B.extend;})();YAHOO.register("yahoo",YAHOO,{version:"2.7.0",build:"1796"});(function(){YAHOO.env._id_counter=YAHOO.env._id_counter||0;var E=YAHOO.util,L=YAHOO.lang,m=YAHOO.env.ua,A=YAHOO.lang.trim,d={},h={},N=/^t(?:able|d|h)$/i,X=/color$/i,K=window.document,W=K.documentElement,e="ownerDocument",n="defaultView",v="documentElement",t="compatMode",b="offsetLeft",P="offsetTop",u="offsetParent",Z="parentNode",l="nodeType",C="tagName",O="scrollLeft",i="scrollTop",Q="getBoundingClientRect",w="getComputedStyle",a="currentStyle",M="CSS1Compat",c="BackCompat",g="class",F="className",J="",B=" ",s="(?:^|\\s)",k="(?= |$)",U="g",p="position",f="fixed",V="relative",j="left",o="top",r="medium",q="borderLeftWidth",R="borderTopWidth",D=m.opera,I=m.webkit,H=m.gecko,T=m.ie;E.Dom={CUSTOM_ATTRIBUTES:(!W.hasAttribute)?{"for":"htmlFor","class":F}:{"htmlFor":"for","className":g},get:function(y){var AA,Y,z,x,G;if(y){if(y[l]||y.item){return y;}if(typeof y==="string"){AA=y;y=K.getElementById(y);if(y&&y.id===AA){return y;}else{if(y&&K.all){y=null;Y=K.all[AA];for(x=0,G=Y.length;x<G;++x){if(Y[x].id===AA){return Y[x];}}}}return y;}if(y.DOM_EVENTS){y=y.get("element");}if("length" in y){z=[];for(x=0,G=y.length;x<G;++x){z[z.length]=E.Dom.get(y[x]);}return z;}return y;}return null;},getComputedStyle:function(G,Y){if(window[w]){return G[e][n][w](G,null)[Y];}else{if(G[a]){return E.Dom.IE_ComputedStyle.get(G,Y);}}},getStyle:function(G,Y){return E.Dom.batch(G,E.Dom._getStyle,Y);},_getStyle:function(){if(window[w]){return function(G,y){y=(y==="float")?y="cssFloat":E.Dom._toCamel(y);var x=G.style[y],Y;if(!x){Y=G[e][n][w](G,null);if(Y){x=Y[y];}}return x;};}else{if(W[a]){return function(G,y){var x;switch(y){case"opacity":x=100;try{x=G.filters["DXImageTransform.Microsoft.Alpha"].opacity;}catch(z){try{x=G.filters("alpha").opacity;}catch(Y){}}return x/100;case"float":y="styleFloat";default:y=E.Dom._toCamel(y);x=G[a]?G[a][y]:null;return(G.style[y]||x);}};}}}(),setStyle:function(G,Y,x){E.Dom.batch(G,E.Dom._setStyle,{prop:Y,val:x});},_setStyle:function(){if(T){return function(Y,G){var x=E.Dom._toCamel(G.prop),y=G.val;if(Y){switch(x){case"opacity":if(L.isString(Y.style.filter)){Y.style.filter="alpha(opacity="+y*100+")";if(!Y[a]||!Y[a].hasLayout){Y.style.zoom=1;}}break;case"float":x="styleFloat";default:Y.style[x]=y;}}else{}};}else{return function(Y,G){var x=E.Dom._toCamel(G.prop),y=G.val;if(Y){if(x=="float"){x="cssFloat";}Y.style[x]=y;}else{}};}}(),getXY:function(G){return E.Dom.batch(G,E.Dom._getXY);},_canPosition:function(G){return(E.Dom._getStyle(G,"display")!=="none"&&E.Dom._inDoc(G));},_getXY:function(){if(K[v][Q]){return function(y){var z,Y,AA,AF,AE,AD,AC,G,x,AB=Math.floor,AG=false;if(E.Dom._canPosition(y)){AA=y[Q]();AF=y[e];z=E.Dom.getDocumentScrollLeft(AF);Y=E.Dom.getDocumentScrollTop(AF);AG=[AB(AA[j]),AB(AA[o])];if(T&&m.ie<8){AE=2;AD=2;AC=AF[t];G=S(AF[v],q);x=S(AF[v],R);if(m.ie===6){if(AC!==c){AE=0;AD=0;}}if((AC==c)){if(G!==r){AE=parseInt(G,10);}if(x!==r){AD=parseInt(x,10);}}AG[0]-=AE;AG[1]-=AD;}if((Y||z)){AG[0]+=z;AG[1]+=Y;}AG[0]=AB(AG[0]);AG[1]=AB(AG[1]);}else{}return AG;};}else{return function(y){var x,Y,AA,AB,AC,z=false,G=y;if(E.Dom._canPosition(y)){z=[y[b],y[P]];x=E.Dom.getDocumentScrollLeft(y[e]);Y=E.Dom.getDocumentScrollTop(y[e]);AC=((H||m.webkit>519)?true:false);while((G=G[u])){z[0]+=G[b];z[1]+=G[P];if(AC){z=E.Dom._calcBorders(G,z);}}if(E.Dom._getStyle(y,p)!==f){G=y;while((G=G[Z])&&G[C]){AA=G[i];AB=G[O];if(H&&(E.Dom._getStyle(G,"overflow")!=="visible")){z=E.Dom._calcBorders(G,z);}if(AA||AB){z[0]-=AB;z[1]-=AA;}}z[0]+=x;z[1]+=Y;}else{if(D){z[0]-=x;z[1]-=Y;}else{if(I||H){z[0]+=x;z[1]+=Y;}}}z[0]=Math.floor(z[0]);z[1]=Math.floor(z[1]);}else{}return z;};}}(),getX:function(G){var Y=function(x){return E.Dom.getXY(x)[0];};return E.Dom.batch(G,Y,E.Dom,true);},getY:function(G){var Y=function(x){return E.Dom.getXY(x)[1];};return E.Dom.batch(G,Y,E.Dom,true);},setXY:function(G,x,Y){E.Dom.batch(G,E.Dom._setXY,{pos:x,noRetry:Y});},_setXY:function(G,z){var AA=E.Dom._getStyle(G,p),y=E.Dom.setStyle,AD=z.pos,Y=z.noRetry,AB=[parseInt(E.Dom.getComputedStyle(G,j),10),parseInt(E.Dom.getComputedStyle(G,o),10)],AC,x;if(AA=="static"){AA=V;y(G,p,AA);}AC=E.Dom._getXY(G);if(!AD||AC===false){return false;}if(isNaN(AB[0])){AB[0]=(AA==V)?0:G[b];}if(isNaN(AB[1])){AB[1]=(AA==V)?0:G[P];}if(AD[0]!==null){y(G,j,AD[0]-AC[0]+AB[0]+"px");}if(AD[1]!==null){y(G,o,AD[1]-AC[1]+AB[1]+"px");}if(!Y){x=E.Dom._getXY(G);if((AD[0]!==null&&x[0]!=AD[0])||(AD[1]!==null&&x[1]!=AD[1])){E.Dom._setXY(G,{pos:AD,noRetry:true});}}},setX:function(Y,G){E.Dom.setXY(Y,[G,null]);},setY:function(G,Y){E.Dom.setXY(G,[null,Y]);},getRegion:function(G){var Y=function(x){var y=false;if(E.Dom._canPosition(x)){y=E.Region.getRegion(x);}else{}return y;};return E.Dom.batch(G,Y,E.Dom,true);},getClientWidth:function(){return E.Dom.getViewportWidth();},getClientHeight:function(){return E.Dom.getViewportHeight();},getElementsByClassName:function(AB,AF,AC,AE,x,AD){AB=L.trim(AB);AF=AF||"*";AC=(AC)?E.Dom.get(AC):null||K;if(!AC){return[];}var Y=[],G=AC.getElementsByTagName(AF),z=E.Dom.hasClass;for(var y=0,AA=G.length;y<AA;++y){if(z(G[y],AB)){Y[Y.length]=G[y];}}if(AE){E.Dom.batch(Y,AE,x,AD);}return Y;},hasClass:function(Y,G){return E.Dom.batch(Y,E.Dom._hasClass,G);},_hasClass:function(x,Y){var G=false,y;if(x&&Y){y=E.Dom.getAttribute(x,F)||J;if(Y.exec){G=Y.test(y);}else{G=Y&&(B+y+B).indexOf(B+Y+B)>-1;}}else{}return G;},addClass:function(Y,G){return E.Dom.batch(Y,E.Dom._addClass,G);},_addClass:function(x,Y){var G=false,y;if(x&&Y){y=E.Dom.getAttribute(x,F)||J;if(!E.Dom._hasClass(x,Y)){E.Dom.setAttribute(x,F,A(y+B+Y));G=true;}}else{}return G;},removeClass:function(Y,G){return E.Dom.batch(Y,E.Dom._removeClass,G);},_removeClass:function(y,x){var Y=false,AA,z,G;if(y&&x){AA=E.Dom.getAttribute(y,F)||J;E.Dom.setAttribute(y,F,AA.replace(E.Dom._getClassRegex(x),J));z=E.Dom.getAttribute(y,F);if(AA!==z){E.Dom.setAttribute(y,F,A(z));Y=true;if(E.Dom.getAttribute(y,F)===""){G=(y.hasAttribute&&y.hasAttribute(g))?g:F;y.removeAttribute(G);}}}else{}return Y;},replaceClass:function(x,Y,G){return E.Dom.batch(x,E.Dom._replaceClass,{from:Y,to:G});
},_replaceClass:function(y,x){var Y,AB,AA,G=false,z;if(y&&x){AB=x.from;AA=x.to;if(!AA){G=false;}else{if(!AB){G=E.Dom._addClass(y,x.to);}else{if(AB!==AA){z=E.Dom.getAttribute(y,F)||J;Y=(B+z.replace(E.Dom._getClassRegex(AB),B+AA)).split(E.Dom._getClassRegex(AA));Y.splice(1,0,B+AA);E.Dom.setAttribute(y,F,A(Y.join(J)));G=true;}}}}else{}return G;},generateId:function(G,x){x=x||"yui-gen";var Y=function(y){if(y&&y.id){return y.id;}var z=x+YAHOO.env._id_counter++;if(y){if(y[e].getElementById(z)){return E.Dom.generateId(y,z+x);}y.id=z;}return z;};return E.Dom.batch(G,Y,E.Dom,true)||Y.apply(E.Dom,arguments);},isAncestor:function(Y,x){Y=E.Dom.get(Y);x=E.Dom.get(x);var G=false;if((Y&&x)&&(Y[l]&&x[l])){if(Y.contains&&Y!==x){G=Y.contains(x);}else{if(Y.compareDocumentPosition){G=!!(Y.compareDocumentPosition(x)&16);}}}else{}return G;},inDocument:function(G,Y){return E.Dom._inDoc(E.Dom.get(G),Y);},_inDoc:function(Y,x){var G=false;if(Y&&Y[C]){x=x||Y[e];G=E.Dom.isAncestor(x[v],Y);}else{}return G;},getElementsBy:function(Y,AF,AB,AD,y,AC,AE){AF=AF||"*";AB=(AB)?E.Dom.get(AB):null||K;if(!AB){return[];}var x=[],G=AB.getElementsByTagName(AF);for(var z=0,AA=G.length;z<AA;++z){if(Y(G[z])){if(AE){x=G[z];break;}else{x[x.length]=G[z];}}}if(AD){E.Dom.batch(x,AD,y,AC);}return x;},getElementBy:function(x,G,Y){return E.Dom.getElementsBy(x,G,Y,null,null,null,true);},batch:function(x,AB,AA,z){var y=[],Y=(z)?AA:window;x=(x&&(x[C]||x.item))?x:E.Dom.get(x);if(x&&AB){if(x[C]||x.length===undefined){return AB.call(Y,x,AA);}for(var G=0;G<x.length;++G){y[y.length]=AB.call(Y,x[G],AA);}}else{return false;}return y;},getDocumentHeight:function(){var Y=(K[t]!=M||I)?K.body.scrollHeight:W.scrollHeight,G=Math.max(Y,E.Dom.getViewportHeight());return G;},getDocumentWidth:function(){var Y=(K[t]!=M||I)?K.body.scrollWidth:W.scrollWidth,G=Math.max(Y,E.Dom.getViewportWidth());return G;},getViewportHeight:function(){var G=self.innerHeight,Y=K[t];if((Y||T)&&!D){G=(Y==M)?W.clientHeight:K.body.clientHeight;}return G;},getViewportWidth:function(){var G=self.innerWidth,Y=K[t];if(Y||T){G=(Y==M)?W.clientWidth:K.body.clientWidth;}return G;},getAncestorBy:function(G,Y){while((G=G[Z])){if(E.Dom._testElement(G,Y)){return G;}}return null;},getAncestorByClassName:function(Y,G){Y=E.Dom.get(Y);if(!Y){return null;}var x=function(y){return E.Dom.hasClass(y,G);};return E.Dom.getAncestorBy(Y,x);},getAncestorByTagName:function(Y,G){Y=E.Dom.get(Y);if(!Y){return null;}var x=function(y){return y[C]&&y[C].toUpperCase()==G.toUpperCase();};return E.Dom.getAncestorBy(Y,x);},getPreviousSiblingBy:function(G,Y){while(G){G=G.previousSibling;if(E.Dom._testElement(G,Y)){return G;}}return null;},getPreviousSibling:function(G){G=E.Dom.get(G);if(!G){return null;}return E.Dom.getPreviousSiblingBy(G);},getNextSiblingBy:function(G,Y){while(G){G=G.nextSibling;if(E.Dom._testElement(G,Y)){return G;}}return null;},getNextSibling:function(G){G=E.Dom.get(G);if(!G){return null;}return E.Dom.getNextSiblingBy(G);},getFirstChildBy:function(G,x){var Y=(E.Dom._testElement(G.firstChild,x))?G.firstChild:null;return Y||E.Dom.getNextSiblingBy(G.firstChild,x);},getFirstChild:function(G,Y){G=E.Dom.get(G);if(!G){return null;}return E.Dom.getFirstChildBy(G);},getLastChildBy:function(G,x){if(!G){return null;}var Y=(E.Dom._testElement(G.lastChild,x))?G.lastChild:null;return Y||E.Dom.getPreviousSiblingBy(G.lastChild,x);},getLastChild:function(G){G=E.Dom.get(G);return E.Dom.getLastChildBy(G);},getChildrenBy:function(Y,y){var x=E.Dom.getFirstChildBy(Y,y),G=x?[x]:[];E.Dom.getNextSiblingBy(x,function(z){if(!y||y(z)){G[G.length]=z;}return false;});return G;},getChildren:function(G){G=E.Dom.get(G);if(!G){}return E.Dom.getChildrenBy(G);},getDocumentScrollLeft:function(G){G=G||K;return Math.max(G[v].scrollLeft,G.body.scrollLeft);},getDocumentScrollTop:function(G){G=G||K;return Math.max(G[v].scrollTop,G.body.scrollTop);},insertBefore:function(Y,G){Y=E.Dom.get(Y);G=E.Dom.get(G);if(!Y||!G||!G[Z]){return null;}return G[Z].insertBefore(Y,G);},insertAfter:function(Y,G){Y=E.Dom.get(Y);G=E.Dom.get(G);if(!Y||!G||!G[Z]){return null;}if(G.nextSibling){return G[Z].insertBefore(Y,G.nextSibling);}else{return G[Z].appendChild(Y);}},getClientRegion:function(){var x=E.Dom.getDocumentScrollTop(),Y=E.Dom.getDocumentScrollLeft(),y=E.Dom.getViewportWidth()+Y,G=E.Dom.getViewportHeight()+x;return new E.Region(x,y,G,Y);},setAttribute:function(Y,G,x){G=E.Dom.CUSTOM_ATTRIBUTES[G]||G;Y.setAttribute(G,x);},getAttribute:function(Y,G){G=E.Dom.CUSTOM_ATTRIBUTES[G]||G;return Y.getAttribute(G);},_toCamel:function(Y){var x=d;function G(y,z){return z.toUpperCase();}return x[Y]||(x[Y]=Y.indexOf("-")===-1?Y:Y.replace(/-([a-z])/gi,G));},_getClassRegex:function(Y){var G;if(Y!==undefined){if(Y.exec){G=Y;}else{G=h[Y];if(!G){Y=Y.replace(E.Dom._patterns.CLASS_RE_TOKENS,"\\$1");G=h[Y]=new RegExp(s+Y+k,U);}}}return G;},_patterns:{ROOT_TAG:/^body|html$/i,CLASS_RE_TOKENS:/([\.\(\)\^\$\*\+\?\|\[\]\{\}])/g},_testElement:function(G,Y){return G&&G[l]==1&&(!Y||Y(G));},_calcBorders:function(x,y){var Y=parseInt(E.Dom[w](x,R),10)||0,G=parseInt(E.Dom[w](x,q),10)||0;if(H){if(N.test(x[C])){Y=0;G=0;}}y[0]+=G;y[1]+=Y;return y;}};var S=E.Dom[w];if(m.opera){E.Dom[w]=function(Y,G){var x=S(Y,G);if(X.test(G)){x=E.Dom.Color.toRGB(x);}return x;};}if(m.webkit){E.Dom[w]=function(Y,G){var x=S(Y,G);if(x==="rgba(0, 0, 0, 0)"){x="transparent";}return x;};}})();YAHOO.util.Region=function(C,D,A,B){this.top=C;this.y=C;this[1]=C;this.right=D;this.bottom=A;this.left=B;this.x=B;this[0]=B;this.width=this.right-this.left;this.height=this.bottom-this.top;};YAHOO.util.Region.prototype.contains=function(A){return(A.left>=this.left&&A.right<=this.right&&A.top>=this.top&&A.bottom<=this.bottom);};YAHOO.util.Region.prototype.getArea=function(){return((this.bottom-this.top)*(this.right-this.left));};YAHOO.util.Region.prototype.intersect=function(E){var C=Math.max(this.top,E.top),D=Math.min(this.right,E.right),A=Math.min(this.bottom,E.bottom),B=Math.max(this.left,E.left);if(A>=C&&D>=B){return new YAHOO.util.Region(C,D,A,B);
}else{return null;}};YAHOO.util.Region.prototype.union=function(E){var C=Math.min(this.top,E.top),D=Math.max(this.right,E.right),A=Math.max(this.bottom,E.bottom),B=Math.min(this.left,E.left);return new YAHOO.util.Region(C,D,A,B);};YAHOO.util.Region.prototype.toString=function(){return("Region {"+"top: "+this.top+", right: "+this.right+", bottom: "+this.bottom+", left: "+this.left+", height: "+this.height+", width: "+this.width+"}");};YAHOO.util.Region.getRegion=function(D){var F=YAHOO.util.Dom.getXY(D),C=F[1],E=F[0]+D.offsetWidth,A=F[1]+D.offsetHeight,B=F[0];return new YAHOO.util.Region(C,E,A,B);};YAHOO.util.Point=function(A,B){if(YAHOO.lang.isArray(A)){B=A[1];A=A[0];}YAHOO.util.Point.superclass.constructor.call(this,B,A,B,A);};YAHOO.extend(YAHOO.util.Point,YAHOO.util.Region);(function(){var B=YAHOO.util,A="clientTop",F="clientLeft",J="parentNode",K="right",W="hasLayout",I="px",U="opacity",L="auto",D="borderLeftWidth",G="borderTopWidth",P="borderRightWidth",V="borderBottomWidth",S="visible",Q="transparent",N="height",E="width",H="style",T="currentStyle",R=/^width|height$/,O=/^(\d[.\d]*)+(em|ex|px|gd|rem|vw|vh|vm|ch|mm|cm|in|pt|pc|deg|rad|ms|s|hz|khz|%){1}?/i,M={get:function(X,Z){var Y="",a=X[T][Z];if(Z===U){Y=B.Dom.getStyle(X,U);}else{if(!a||(a.indexOf&&a.indexOf(I)>-1)){Y=a;}else{if(B.Dom.IE_COMPUTED[Z]){Y=B.Dom.IE_COMPUTED[Z](X,Z);}else{if(O.test(a)){Y=B.Dom.IE.ComputedStyle.getPixel(X,Z);}else{Y=a;}}}}return Y;},getOffset:function(Z,e){var b=Z[T][e],X=e.charAt(0).toUpperCase()+e.substr(1),c="offset"+X,Y="pixel"+X,a="",d;if(b==L){d=Z[c];if(d===undefined){a=0;}a=d;if(R.test(e)){Z[H][e]=d;if(Z[c]>d){a=d-(Z[c]-d);}Z[H][e]=L;}}else{if(!Z[H][Y]&&!Z[H][e]){Z[H][e]=b;}a=Z[H][Y];}return a+I;},getBorderWidth:function(X,Z){var Y=null;if(!X[T][W]){X[H].zoom=1;}switch(Z){case G:Y=X[A];break;case V:Y=X.offsetHeight-X.clientHeight-X[A];break;case D:Y=X[F];break;case P:Y=X.offsetWidth-X.clientWidth-X[F];break;}return Y+I;},getPixel:function(Y,X){var a=null,b=Y[T][K],Z=Y[T][X];Y[H][K]=Z;a=Y[H].pixelRight;Y[H][K]=b;return a+I;},getMargin:function(Y,X){var Z;if(Y[T][X]==L){Z=0+I;}else{Z=B.Dom.IE.ComputedStyle.getPixel(Y,X);}return Z;},getVisibility:function(Y,X){var Z;while((Z=Y[T])&&Z[X]=="inherit"){Y=Y[J];}return(Z)?Z[X]:S;},getColor:function(Y,X){return B.Dom.Color.toRGB(Y[T][X])||Q;},getBorderColor:function(Y,X){var Z=Y[T],a=Z[X]||Z.color;return B.Dom.Color.toRGB(B.Dom.Color.toHex(a));}},C={};C.top=C.right=C.bottom=C.left=C[E]=C[N]=M.getOffset;C.color=M.getColor;C[G]=C[P]=C[V]=C[D]=M.getBorderWidth;C.marginTop=C.marginRight=C.marginBottom=C.marginLeft=M.getMargin;C.visibility=M.getVisibility;C.borderColor=C.borderTopColor=C.borderRightColor=C.borderBottomColor=C.borderLeftColor=M.getBorderColor;B.Dom.IE_COMPUTED=C;B.Dom.IE_ComputedStyle=M;})();(function(){var C="toString",A=parseInt,B=RegExp,D=YAHOO.util;D.Dom.Color={KEYWORDS:{black:"000",silver:"c0c0c0",gray:"808080",white:"fff",maroon:"800000",red:"f00",purple:"800080",fuchsia:"f0f",green:"008000",lime:"0f0",olive:"808000",yellow:"ff0",navy:"000080",blue:"00f",teal:"008080",aqua:"0ff"},re_RGB:/^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i,re_hex:/^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i,re_hex3:/([0-9A-F])/gi,toRGB:function(E){if(!D.Dom.Color.re_RGB.test(E)){E=D.Dom.Color.toHex(E);}if(D.Dom.Color.re_hex.exec(E)){E="rgb("+[A(B.$1,16),A(B.$2,16),A(B.$3,16)].join(", ")+")";}return E;},toHex:function(H){H=D.Dom.Color.KEYWORDS[H]||H;if(D.Dom.Color.re_RGB.exec(H)){var G=(B.$1.length===1)?"0"+B.$1:Number(B.$1),F=(B.$2.length===1)?"0"+B.$2:Number(B.$2),E=(B.$3.length===1)?"0"+B.$3:Number(B.$3);H=[G[C](16),F[C](16),E[C](16)].join("");}if(H.length<6){H=H.replace(D.Dom.Color.re_hex3,"$1$1");}if(H!=="transparent"&&H.indexOf("#")<0){H="#"+H;}return H.toLowerCase();}};}());YAHOO.register("dom",YAHOO.util.Dom,{version:"2.7.0",build:"1796"});YAHOO.util.CustomEvent=function(D,C,B,A){this.type=D;this.scope=C||window;this.silent=B;this.signature=A||YAHOO.util.CustomEvent.LIST;this.subscribers=[];if(!this.silent){}var E="_YUICEOnSubscribe";if(D!==E){this.subscribeEvent=new YAHOO.util.CustomEvent(E,this,true);}this.lastError=null;};YAHOO.util.CustomEvent.LIST=0;YAHOO.util.CustomEvent.FLAT=1;YAHOO.util.CustomEvent.prototype={subscribe:function(A,B,C){if(!A){throw new Error("Invalid callback for subscriber to '"+this.type+"'");}if(this.subscribeEvent){this.subscribeEvent.fire(A,B,C);}this.subscribers.push(new YAHOO.util.Subscriber(A,B,C));},unsubscribe:function(D,F){if(!D){return this.unsubscribeAll();}var E=false;for(var B=0,A=this.subscribers.length;B<A;++B){var C=this.subscribers[B];if(C&&C.contains(D,F)){this._delete(B);E=true;}}return E;},fire:function(){this.lastError=null;var K=[],E=this.subscribers.length;if(!E&&this.silent){return true;}var I=[].slice.call(arguments,0),G=true,D,J=false;if(!this.silent){}var C=this.subscribers.slice(),A=YAHOO.util.Event.throwErrors;for(D=0;D<E;++D){var M=C[D];if(!M){J=true;}else{if(!this.silent){}var L=M.getScope(this.scope);if(this.signature==YAHOO.util.CustomEvent.FLAT){var B=null;if(I.length>0){B=I[0];}try{G=M.fn.call(L,B,M.obj);}catch(F){this.lastError=F;if(A){throw F;}}}else{try{G=M.fn.call(L,this.type,I,M.obj);}catch(H){this.lastError=H;if(A){throw H;}}}if(false===G){if(!this.silent){}break;}}}return(G!==false);},unsubscribeAll:function(){var A=this.subscribers.length,B;for(B=A-1;B>-1;B--){this._delete(B);}this.subscribers=[];return A;},_delete:function(A){var B=this.subscribers[A];if(B){delete B.fn;delete B.obj;}this.subscribers.splice(A,1);},toString:function(){return"CustomEvent: "+"'"+this.type+"', "+"context: "+this.scope;}};YAHOO.util.Subscriber=function(A,B,C){this.fn=A;this.obj=YAHOO.lang.isUndefined(B)?null:B;this.overrideContext=C;};YAHOO.util.Subscriber.prototype.getScope=function(A){if(this.overrideContext){if(this.overrideContext===true){return this.obj;}else{return this.overrideContext;}}return A;};YAHOO.util.Subscriber.prototype.contains=function(A,B){if(B){return(this.fn==A&&this.obj==B);}else{return(this.fn==A);}};YAHOO.util.Subscriber.prototype.toString=function(){return"Subscriber { obj: "+this.obj+", overrideContext: "+(this.overrideContext||"no")+" }";};if(!YAHOO.util.Event){YAHOO.util.Event=function(){var H=false;var I=[];var J=[];var G=[];var E=[];var C=0;var F=[];var B=[];var A=0;var D={63232:38,63233:40,63234:37,63235:39,63276:33,63277:34,25:9};var K=YAHOO.env.ua.ie?"focusin":"focus";var L=YAHOO.env.ua.ie?"focusout":"blur";return{POLL_RETRYS:2000,POLL_INTERVAL:20,EL:0,TYPE:1,FN:2,WFN:3,UNLOAD_OBJ:3,ADJ_SCOPE:4,OBJ:5,OVERRIDE:6,lastError:null,isSafari:YAHOO.env.ua.webkit,webkit:YAHOO.env.ua.webkit,isIE:YAHOO.env.ua.ie,_interval:null,_dri:null,DOMReady:false,throwErrors:false,startInterval:function(){if(!this._interval){var M=this;var N=function(){M._tryPreloadAttach();};this._interval=setInterval(N,this.POLL_INTERVAL);}},onAvailable:function(S,O,Q,R,P){var M=(YAHOO.lang.isString(S))?[S]:S;for(var N=0;N<M.length;N=N+1){F.push({id:M[N],fn:O,obj:Q,overrideContext:R,checkReady:P});}C=this.POLL_RETRYS;this.startInterval();},onContentReady:function(P,M,N,O){this.onAvailable(P,M,N,O,true);},onDOMReady:function(M,N,O){if(this.DOMReady){setTimeout(function(){var P=window;if(O){if(O===true){P=N;}else{P=O;}}M.call(P,"DOMReady",[],N);},0);}else{this.DOMReadyEvent.subscribe(M,N,O);}},_addListener:function(O,M,Y,S,W,b){if(!Y||!Y.call){return false;}if(this._isValidCollection(O)){var Z=true;for(var T=0,V=O.length;T<V;++T){Z=this.on(O[T],M,Y,S,W)&&Z;}return Z;}else{if(YAHOO.lang.isString(O)){var R=this.getEl(O);if(R){O=R;}else{this.onAvailable(O,function(){YAHOO.util.Event.on(O,M,Y,S,W);});return true;}}}if(!O){return false;}if("unload"==M&&S!==this){J[J.length]=[O,M,Y,S,W];return true;}var N=O;if(W){if(W===true){N=S;}else{N=W;}}var P=function(c){return Y.call(N,YAHOO.util.Event.getEvent(c,O),S);};var a=[O,M,Y,P,N,S,W];var U=I.length;I[U]=a;if(this.useLegacyEvent(O,M)){var Q=this.getLegacyIndex(O,M);if(Q==-1||O!=G[Q][0]){Q=G.length;B[O.id+M]=Q;G[Q]=[O,M,O["on"+M]];E[Q]=[];O["on"+M]=function(c){YAHOO.util.Event.fireLegacyEvent(YAHOO.util.Event.getEvent(c),Q);};}E[Q].push(a);}else{try{this._simpleAdd(O,M,P,b);}catch(X){this.lastError=X;this.removeListener(O,M,Y);return false;}}return true;},addListener:function(N,Q,M,O,P){return this._addListener(N,Q,M,O,P,false);},addFocusListener:function(N,M,O,P){return this._addListener(N,K,M,O,P,true);},removeFocusListener:function(N,M){return this.removeListener(N,K,M);},addBlurListener:function(N,M,O,P){return this._addListener(N,L,M,O,P,true);},removeBlurListener:function(N,M){return this.removeListener(N,L,M);},fireLegacyEvent:function(R,P){var T=true,M,V,U,N,S;V=E[P].slice();for(var O=0,Q=V.length;O<Q;++O){U=V[O];if(U&&U[this.WFN]){N=U[this.ADJ_SCOPE];S=U[this.WFN].call(N,R);T=(T&&S);}}M=G[P];if(M&&M[2]){M[2](R);}return T;},getLegacyIndex:function(N,O){var M=this.generateId(N)+O;if(typeof B[M]=="undefined"){return -1;}else{return B[M];}},useLegacyEvent:function(M,N){return(this.webkit&&this.webkit<419&&("click"==N||"dblclick"==N));},removeListener:function(N,M,V){var Q,T,X;if(typeof N=="string"){N=this.getEl(N);}else{if(this._isValidCollection(N)){var W=true;for(Q=N.length-1;Q>-1;Q--){W=(this.removeListener(N[Q],M,V)&&W);}return W;}}if(!V||!V.call){return this.purgeElement(N,false,M);}if("unload"==M){for(Q=J.length-1;Q>-1;Q--){X=J[Q];if(X&&X[0]==N&&X[1]==M&&X[2]==V){J.splice(Q,1);return true;}}return false;}var R=null;var S=arguments[3];if("undefined"===typeof S){S=this._getCacheIndex(N,M,V);}if(S>=0){R=I[S];}if(!N||!R){return false;}if(this.useLegacyEvent(N,M)){var P=this.getLegacyIndex(N,M);var O=E[P];if(O){for(Q=0,T=O.length;Q<T;++Q){X=O[Q];if(X&&X[this.EL]==N&&X[this.TYPE]==M&&X[this.FN]==V){O.splice(Q,1);break;}}}}else{try{this._simpleRemove(N,M,R[this.WFN],false);}catch(U){this.lastError=U;return false;}}delete I[S][this.WFN];delete I[S][this.FN];
I.splice(S,1);return true;},getTarget:function(O,N){var M=O.target||O.srcElement;return this.resolveTextNode(M);},resolveTextNode:function(N){try{if(N&&3==N.nodeType){return N.parentNode;}}catch(M){}return N;},getPageX:function(N){var M=N.pageX;if(!M&&0!==M){M=N.clientX||0;if(this.isIE){M+=this._getScrollLeft();}}return M;},getPageY:function(M){var N=M.pageY;if(!N&&0!==N){N=M.clientY||0;if(this.isIE){N+=this._getScrollTop();}}return N;},getXY:function(M){return[this.getPageX(M),this.getPageY(M)];},getRelatedTarget:function(N){var M=N.relatedTarget;if(!M){if(N.type=="mouseout"){M=N.toElement;}else{if(N.type=="mouseover"){M=N.fromElement;}}}return this.resolveTextNode(M);},getTime:function(O){if(!O.time){var N=new Date().getTime();try{O.time=N;}catch(M){this.lastError=M;return N;}}return O.time;},stopEvent:function(M){this.stopPropagation(M);this.preventDefault(M);},stopPropagation:function(M){if(M.stopPropagation){M.stopPropagation();}else{M.cancelBubble=true;}},preventDefault:function(M){if(M.preventDefault){M.preventDefault();}else{M.returnValue=false;}},getEvent:function(O,M){var N=O||window.event;if(!N){var P=this.getEvent.caller;while(P){N=P.arguments[0];if(N&&Event==N.constructor){break;}P=P.caller;}}return N;},getCharCode:function(N){var M=N.keyCode||N.charCode||0;if(YAHOO.env.ua.webkit&&(M in D)){M=D[M];}return M;},_getCacheIndex:function(Q,R,P){for(var O=0,N=I.length;O<N;O=O+1){var M=I[O];if(M&&M[this.FN]==P&&M[this.EL]==Q&&M[this.TYPE]==R){return O;}}return -1;},generateId:function(M){var N=M.id;if(!N){N="yuievtautoid-"+A;++A;M.id=N;}return N;},_isValidCollection:function(N){try{return(N&&typeof N!=="string"&&N.length&&!N.tagName&&!N.alert&&typeof N[0]!=="undefined");}catch(M){return false;}},elCache:{},getEl:function(M){return(typeof M==="string")?document.getElementById(M):M;},clearCache:function(){},DOMReadyEvent:new YAHOO.util.CustomEvent("DOMReady",this),_load:function(N){if(!H){H=true;var M=YAHOO.util.Event;M._ready();M._tryPreloadAttach();}},_ready:function(N){var M=YAHOO.util.Event;if(!M.DOMReady){M.DOMReady=true;M.DOMReadyEvent.fire();M._simpleRemove(document,"DOMContentLoaded",M._ready);}},_tryPreloadAttach:function(){if(F.length===0){C=0;if(this._interval){clearInterval(this._interval);this._interval=null;}return;}if(this.locked){return;}if(this.isIE){if(!this.DOMReady){this.startInterval();return;}}this.locked=true;var S=!H;if(!S){S=(C>0&&F.length>0);}var R=[];var T=function(V,W){var U=V;if(W.overrideContext){if(W.overrideContext===true){U=W.obj;}else{U=W.overrideContext;}}W.fn.call(U,W.obj);};var N,M,Q,P,O=[];for(N=0,M=F.length;N<M;N=N+1){Q=F[N];if(Q){P=this.getEl(Q.id);if(P){if(Q.checkReady){if(H||P.nextSibling||!S){O.push(Q);F[N]=null;}}else{T(P,Q);F[N]=null;}}else{R.push(Q);}}}for(N=0,M=O.length;N<M;N=N+1){Q=O[N];T(this.getEl(Q.id),Q);}C--;if(S){for(N=F.length-1;N>-1;N--){Q=F[N];if(!Q||!Q.id){F.splice(N,1);}}this.startInterval();}else{if(this._interval){clearInterval(this._interval);this._interval=null;}}this.locked=false;},purgeElement:function(Q,R,T){var O=(YAHOO.lang.isString(Q))?this.getEl(Q):Q;var S=this.getListeners(O,T),P,M;if(S){for(P=S.length-1;P>-1;P--){var N=S[P];this.removeListener(O,N.type,N.fn);}}if(R&&O&&O.childNodes){for(P=0,M=O.childNodes.length;P<M;++P){this.purgeElement(O.childNodes[P],R,T);}}},getListeners:function(O,M){var R=[],N;if(!M){N=[I,J];}else{if(M==="unload"){N=[J];}else{N=[I];}}var T=(YAHOO.lang.isString(O))?this.getEl(O):O;for(var Q=0;Q<N.length;Q=Q+1){var V=N[Q];if(V){for(var S=0,U=V.length;S<U;++S){var P=V[S];if(P&&P[this.EL]===T&&(!M||M===P[this.TYPE])){R.push({type:P[this.TYPE],fn:P[this.FN],obj:P[this.OBJ],adjust:P[this.OVERRIDE],scope:P[this.ADJ_SCOPE],index:S});}}}}return(R.length)?R:null;},_unload:function(T){var N=YAHOO.util.Event,Q,P,O,S,R,U=J.slice(),M;for(Q=0,S=J.length;Q<S;++Q){O=U[Q];if(O){M=window;if(O[N.ADJ_SCOPE]){if(O[N.ADJ_SCOPE]===true){M=O[N.UNLOAD_OBJ];}else{M=O[N.ADJ_SCOPE];}}O[N.FN].call(M,N.getEvent(T,O[N.EL]),O[N.UNLOAD_OBJ]);U[Q]=null;}}O=null;M=null;J=null;if(I){for(P=I.length-1;P>-1;P--){O=I[P];if(O){N.removeListener(O[N.EL],O[N.TYPE],O[N.FN],P);}}O=null;}G=null;N._simpleRemove(window,"unload",N._unload);},_getScrollLeft:function(){return this._getScroll()[1];},_getScrollTop:function(){return this._getScroll()[0];},_getScroll:function(){var M=document.documentElement,N=document.body;if(M&&(M.scrollTop||M.scrollLeft)){return[M.scrollTop,M.scrollLeft];}else{if(N){return[N.scrollTop,N.scrollLeft];}else{return[0,0];}}},regCE:function(){},_simpleAdd:function(){if(window.addEventListener){return function(O,P,N,M){O.addEventListener(P,N,(M));};}else{if(window.attachEvent){return function(O,P,N,M){O.attachEvent("on"+P,N);};}else{return function(){};}}}(),_simpleRemove:function(){if(window.removeEventListener){return function(O,P,N,M){O.removeEventListener(P,N,(M));};}else{if(window.detachEvent){return function(N,O,M){N.detachEvent("on"+O,M);};}else{return function(){};}}}()};}();(function(){var EU=YAHOO.util.Event;EU.on=EU.addListener;EU.onFocus=EU.addFocusListener;EU.onBlur=EU.addBlurListener;
/* DOMReady: based on work by: Dean Edwards/John Resig/Matthias Miller */
if(EU.isIE){YAHOO.util.Event.onDOMReady(YAHOO.util.Event._tryPreloadAttach,YAHOO.util.Event,true);var n=document.createElement("p");EU._dri=setInterval(function(){try{n.doScroll("left");clearInterval(EU._dri);EU._dri=null;EU._ready();n=null;}catch(ex){}},EU.POLL_INTERVAL);}else{if(EU.webkit&&EU.webkit<525){EU._dri=setInterval(function(){var rs=document.readyState;if("loaded"==rs||"complete"==rs){clearInterval(EU._dri);EU._dri=null;EU._ready();}},EU.POLL_INTERVAL);}else{EU._simpleAdd(document,"DOMContentLoaded",EU._ready);}}EU._simpleAdd(window,"load",EU._load);EU._simpleAdd(window,"unload",EU._unload);EU._tryPreloadAttach();})();}YAHOO.util.EventProvider=function(){};YAHOO.util.EventProvider.prototype={__yui_events:null,__yui_subscribers:null,subscribe:function(A,C,F,E){this.__yui_events=this.__yui_events||{};var D=this.__yui_events[A];if(D){D.subscribe(C,F,E);
}else{this.__yui_subscribers=this.__yui_subscribers||{};var B=this.__yui_subscribers;if(!B[A]){B[A]=[];}B[A].push({fn:C,obj:F,overrideContext:E});}},unsubscribe:function(C,E,G){this.__yui_events=this.__yui_events||{};var A=this.__yui_events;if(C){var F=A[C];if(F){return F.unsubscribe(E,G);}}else{var B=true;for(var D in A){if(YAHOO.lang.hasOwnProperty(A,D)){B=B&&A[D].unsubscribe(E,G);}}return B;}return false;},unsubscribeAll:function(A){return this.unsubscribe(A);},createEvent:function(G,D){this.__yui_events=this.__yui_events||{};var A=D||{};var I=this.__yui_events;if(I[G]){}else{var H=A.scope||this;var E=(A.silent);var B=new YAHOO.util.CustomEvent(G,H,E,YAHOO.util.CustomEvent.FLAT);I[G]=B;if(A.onSubscribeCallback){B.subscribeEvent.subscribe(A.onSubscribeCallback);}this.__yui_subscribers=this.__yui_subscribers||{};var F=this.__yui_subscribers[G];if(F){for(var C=0;C<F.length;++C){B.subscribe(F[C].fn,F[C].obj,F[C].overrideContext);}}}return I[G];},fireEvent:function(E,D,A,C){this.__yui_events=this.__yui_events||{};var G=this.__yui_events[E];if(!G){return null;}var B=[];for(var F=1;F<arguments.length;++F){B.push(arguments[F]);}return G.fire.apply(G,B);},hasEvent:function(A){if(this.__yui_events){if(this.__yui_events[A]){return true;}}return false;}};(function(){var A=YAHOO.util.Event,C=YAHOO.lang;YAHOO.util.KeyListener=function(D,I,E,F){if(!D){}else{if(!I){}else{if(!E){}}}if(!F){F=YAHOO.util.KeyListener.KEYDOWN;}var G=new YAHOO.util.CustomEvent("keyPressed");this.enabledEvent=new YAHOO.util.CustomEvent("enabled");this.disabledEvent=new YAHOO.util.CustomEvent("disabled");if(C.isString(D)){D=document.getElementById(D);}if(C.isFunction(E)){G.subscribe(E);}else{G.subscribe(E.fn,E.scope,E.correctScope);}function H(O,N){if(!I.shift){I.shift=false;}if(!I.alt){I.alt=false;}if(!I.ctrl){I.ctrl=false;}if(O.shiftKey==I.shift&&O.altKey==I.alt&&O.ctrlKey==I.ctrl){var J,M=I.keys,L;if(YAHOO.lang.isArray(M)){for(var K=0;K<M.length;K++){J=M[K];L=A.getCharCode(O);if(J==L){G.fire(L,O);break;}}}else{L=A.getCharCode(O);if(M==L){G.fire(L,O);}}}}this.enable=function(){if(!this.enabled){A.on(D,F,H);this.enabledEvent.fire(I);}this.enabled=true;};this.disable=function(){if(this.enabled){A.removeListener(D,F,H);this.disabledEvent.fire(I);}this.enabled=false;};this.toString=function(){return"KeyListener ["+I.keys+"] "+D.tagName+(D.id?"["+D.id+"]":"");};};var B=YAHOO.util.KeyListener;B.KEYDOWN="keydown";B.KEYUP="keyup";B.KEY={ALT:18,BACK_SPACE:8,CAPS_LOCK:20,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,META:224,NUM_LOCK:144,PAGE_DOWN:34,PAGE_UP:33,PAUSE:19,PRINTSCREEN:44,RIGHT:39,SCROLL_LOCK:145,SHIFT:16,SPACE:32,TAB:9,UP:38};})();YAHOO.register("event",YAHOO.util.Event,{version:"2.7.0",build:"1796"});YAHOO.register("yahoo-dom-event", YAHOO, {version: "2.7.0", build: "1796"});
/*
Copyright (c) 2009, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.7.0
*/
if(!YAHOO.util.DragDropMgr){YAHOO.util.DragDropMgr=function(){var A=YAHOO.util.Event,B=YAHOO.util.Dom;return{useShim:false,_shimActive:false,_shimState:false,_debugShim:false,_createShim:function(){var C=document.createElement("div");C.id="yui-ddm-shim";if(document.body.firstChild){document.body.insertBefore(C,document.body.firstChild);}else{document.body.appendChild(C);}C.style.display="none";C.style.backgroundColor="red";C.style.position="absolute";C.style.zIndex="99999";B.setStyle(C,"opacity","0");this._shim=C;A.on(C,"mouseup",this.handleMouseUp,this,true);A.on(C,"mousemove",this.handleMouseMove,this,true);A.on(window,"scroll",this._sizeShim,this,true);},_sizeShim:function(){if(this._shimActive){var C=this._shim;C.style.height=B.getDocumentHeight()+"px";C.style.width=B.getDocumentWidth()+"px";C.style.top="0";C.style.left="0";}},_activateShim:function(){if(this.useShim){if(!this._shim){this._createShim();}this._shimActive=true;var C=this._shim,D="0";if(this._debugShim){D=".5";}B.setStyle(C,"opacity",D);this._sizeShim();C.style.display="block";}},_deactivateShim:function(){this._shim.style.display="none";this._shimActive=false;},_shim:null,ids:{},handleIds:{},dragCurrent:null,dragOvers:{},deltaX:0,deltaY:0,preventDefault:true,stopPropagation:true,initialized:false,locked:false,interactionInfo:null,init:function(){this.initialized=true;},POINT:0,INTERSECT:1,STRICT_INTERSECT:2,mode:0,_execOnAll:function(E,D){for(var F in this.ids){for(var C in this.ids[F]){var G=this.ids[F][C];if(!this.isTypeOfDD(G)){continue;}G[E].apply(G,D);}}},_onLoad:function(){this.init();A.on(document,"mouseup",this.handleMouseUp,this,true);A.on(document,"mousemove",this.handleMouseMove,this,true);A.on(window,"unload",this._onUnload,this,true);A.on(window,"resize",this._onResize,this,true);},_onResize:function(C){this._execOnAll("resetConstraints",[]);},lock:function(){this.locked=true;},unlock:function(){this.locked=false;},isLocked:function(){return this.locked;},locationCache:{},useCache:true,clickPixelThresh:3,clickTimeThresh:1000,dragThreshMet:false,clickTimeout:null,startX:0,startY:0,fromTimeout:false,regDragDrop:function(D,C){if(!this.initialized){this.init();}if(!this.ids[C]){this.ids[C]={};}this.ids[C][D.id]=D;},removeDDFromGroup:function(E,C){if(!this.ids[C]){this.ids[C]={};}var D=this.ids[C];if(D&&D[E.id]){delete D[E.id];}},_remove:function(E){for(var D in E.groups){if(D){var C=this.ids[D];if(C&&C[E.id]){delete C[E.id];}}}delete this.handleIds[E.id];},regHandle:function(D,C){if(!this.handleIds[D]){this.handleIds[D]={};}this.handleIds[D][C]=C;},isDragDrop:function(C){return(this.getDDById(C))?true:false;},getRelated:function(H,D){var G=[];for(var F in H.groups){for(var E in this.ids[F]){var C=this.ids[F][E];if(!this.isTypeOfDD(C)){continue;}if(!D||C.isTarget){G[G.length]=C;}}}return G;},isLegalTarget:function(G,F){var D=this.getRelated(G,true);for(var E=0,C=D.length;E<C;++E){if(D[E].id==F.id){return true;}}return false;},isTypeOfDD:function(C){return(C&&C.__ygDragDrop);},isHandle:function(D,C){return(this.handleIds[D]&&this.handleIds[D][C]);},getDDById:function(D){for(var C in this.ids){if(this.ids[C][D]){return this.ids[C][D];}}return null;},handleMouseDown:function(E,D){this.currentTarget=YAHOO.util.Event.getTarget(E);this.dragCurrent=D;var C=D.getEl();this.startX=YAHOO.util.Event.getPageX(E);this.startY=YAHOO.util.Event.getPageY(E);this.deltaX=this.startX-C.offsetLeft;this.deltaY=this.startY-C.offsetTop;this.dragThreshMet=false;this.clickTimeout=setTimeout(function(){var F=YAHOO.util.DDM;F.startDrag(F.startX,F.startY);F.fromTimeout=true;},this.clickTimeThresh);},startDrag:function(C,E){if(this.dragCurrent&&this.dragCurrent.useShim){this._shimState=this.useShim;this.useShim=true;}this._activateShim();clearTimeout(this.clickTimeout);var D=this.dragCurrent;if(D&&D.events.b4StartDrag){D.b4StartDrag(C,E);D.fireEvent("b4StartDragEvent",{x:C,y:E});}if(D&&D.events.startDrag){D.startDrag(C,E);D.fireEvent("startDragEvent",{x:C,y:E});}this.dragThreshMet=true;},handleMouseUp:function(C){if(this.dragCurrent){clearTimeout(this.clickTimeout);if(this.dragThreshMet){if(this.fromTimeout){this.fromTimeout=false;this.handleMouseMove(C);}this.fromTimeout=false;this.fireEvents(C,true);}else{}this.stopDrag(C);this.stopEvent(C);}},stopEvent:function(C){if(this.stopPropagation){YAHOO.util.Event.stopPropagation(C);}if(this.preventDefault){YAHOO.util.Event.preventDefault(C);}},stopDrag:function(E,D){var C=this.dragCurrent;if(C&&!D){if(this.dragThreshMet){if(C.events.b4EndDrag){C.b4EndDrag(E);C.fireEvent("b4EndDragEvent",{e:E});}if(C.events.endDrag){C.endDrag(E);C.fireEvent("endDragEvent",{e:E});}}if(C.events.mouseUp){C.onMouseUp(E);C.fireEvent("mouseUpEvent",{e:E});}}if(this._shimActive){this._deactivateShim();if(this.dragCurrent&&this.dragCurrent.useShim){this.useShim=this._shimState;this._shimState=false;}}this.dragCurrent=null;this.dragOvers={};},handleMouseMove:function(F){var C=this.dragCurrent;if(C){if(YAHOO.util.Event.isIE&&!F.button){this.stopEvent(F);return this.handleMouseUp(F);}else{if(F.clientX<0||F.clientY<0){}}if(!this.dragThreshMet){var E=Math.abs(this.startX-YAHOO.util.Event.getPageX(F));var D=Math.abs(this.startY-YAHOO.util.Event.getPageY(F));if(E>this.clickPixelThresh||D>this.clickPixelThresh){this.startDrag(this.startX,this.startY);}}if(this.dragThreshMet){if(C&&C.events.b4Drag){C.b4Drag(F);C.fireEvent("b4DragEvent",{e:F});}if(C&&C.events.drag){C.onDrag(F);C.fireEvent("dragEvent",{e:F});}if(C){this.fireEvents(F,false);}}this.stopEvent(F);}},fireEvents:function(V,L){var a=this.dragCurrent;if(!a||a.isLocked()||a.dragOnly){return;}var N=YAHOO.util.Event.getPageX(V),M=YAHOO.util.Event.getPageY(V),P=new YAHOO.util.Point(N,M),K=a.getTargetCoord(P.x,P.y),F=a.getDragEl(),E=["out","over","drop","enter"],U=new YAHOO.util.Region(K.y,K.x+F.offsetWidth,K.y+F.offsetHeight,K.x),I=[],D={},Q=[],c={outEvts:[],overEvts:[],dropEvts:[],enterEvts:[]};for(var S in this.dragOvers){var d=this.dragOvers[S];if(!this.isTypeOfDD(d)){continue;
}if(!this.isOverTarget(P,d,this.mode,U)){c.outEvts.push(d);}I[S]=true;delete this.dragOvers[S];}for(var R in a.groups){if("string"!=typeof R){continue;}for(S in this.ids[R]){var G=this.ids[R][S];if(!this.isTypeOfDD(G)){continue;}if(G.isTarget&&!G.isLocked()&&G!=a){if(this.isOverTarget(P,G,this.mode,U)){D[R]=true;if(L){c.dropEvts.push(G);}else{if(!I[G.id]){c.enterEvts.push(G);}else{c.overEvts.push(G);}this.dragOvers[G.id]=G;}}}}}this.interactionInfo={out:c.outEvts,enter:c.enterEvts,over:c.overEvts,drop:c.dropEvts,point:P,draggedRegion:U,sourceRegion:this.locationCache[a.id],validDrop:L};for(var C in D){Q.push(C);}if(L&&!c.dropEvts.length){this.interactionInfo.validDrop=false;if(a.events.invalidDrop){a.onInvalidDrop(V);a.fireEvent("invalidDropEvent",{e:V});}}for(S=0;S<E.length;S++){var Y=null;if(c[E[S]+"Evts"]){Y=c[E[S]+"Evts"];}if(Y&&Y.length){var H=E[S].charAt(0).toUpperCase()+E[S].substr(1),X="onDrag"+H,J="b4Drag"+H,O="drag"+H+"Event",W="drag"+H;if(this.mode){if(a.events[J]){a[J](V,Y,Q);a.fireEvent(J+"Event",{event:V,info:Y,group:Q});}if(a.events[W]){a[X](V,Y,Q);a.fireEvent(O,{event:V,info:Y,group:Q});}}else{for(var Z=0,T=Y.length;Z<T;++Z){if(a.events[J]){a[J](V,Y[Z].id,Q[0]);a.fireEvent(J+"Event",{event:V,info:Y[Z].id,group:Q[0]});}if(a.events[W]){a[X](V,Y[Z].id,Q[0]);a.fireEvent(O,{event:V,info:Y[Z].id,group:Q[0]});}}}}}},getBestMatch:function(E){var G=null;var D=E.length;if(D==1){G=E[0];}else{for(var F=0;F<D;++F){var C=E[F];if(this.mode==this.INTERSECT&&C.cursorIsOver){G=C;break;}else{if(!G||!G.overlap||(C.overlap&&G.overlap.getArea()<C.overlap.getArea())){G=C;}}}}return G;},refreshCache:function(D){var F=D||this.ids;for(var C in F){if("string"!=typeof C){continue;}for(var E in this.ids[C]){var G=this.ids[C][E];if(this.isTypeOfDD(G)){var H=this.getLocation(G);if(H){this.locationCache[G.id]=H;}else{delete this.locationCache[G.id];}}}}},verifyEl:function(D){try{if(D){var C=D.offsetParent;if(C){return true;}}}catch(E){}return false;},getLocation:function(H){if(!this.isTypeOfDD(H)){return null;}var F=H.getEl(),K,E,D,M,L,N,C,J,G;try{K=YAHOO.util.Dom.getXY(F);}catch(I){}if(!K){return null;}E=K[0];D=E+F.offsetWidth;M=K[1];L=M+F.offsetHeight;N=M-H.padding[0];C=D+H.padding[1];J=L+H.padding[2];G=E-H.padding[3];return new YAHOO.util.Region(N,C,J,G);},isOverTarget:function(K,C,E,F){var G=this.locationCache[C.id];if(!G||!this.useCache){G=this.getLocation(C);this.locationCache[C.id]=G;}if(!G){return false;}C.cursorIsOver=G.contains(K);var J=this.dragCurrent;if(!J||(!E&&!J.constrainX&&!J.constrainY)){return C.cursorIsOver;}C.overlap=null;if(!F){var H=J.getTargetCoord(K.x,K.y);var D=J.getDragEl();F=new YAHOO.util.Region(H.y,H.x+D.offsetWidth,H.y+D.offsetHeight,H.x);}var I=F.intersect(G);if(I){C.overlap=I;return(E)?true:C.cursorIsOver;}else{return false;}},_onUnload:function(D,C){this.unregAll();},unregAll:function(){if(this.dragCurrent){this.stopDrag();this.dragCurrent=null;}this._execOnAll("unreg",[]);this.ids={};},elementCache:{},getElWrapper:function(D){var C=this.elementCache[D];if(!C||!C.el){C=this.elementCache[D]=new this.ElementWrapper(YAHOO.util.Dom.get(D));}return C;},getElement:function(C){return YAHOO.util.Dom.get(C);},getCss:function(D){var C=YAHOO.util.Dom.get(D);return(C)?C.style:null;},ElementWrapper:function(C){this.el=C||null;this.id=this.el&&C.id;this.css=this.el&&C.style;},getPosX:function(C){return YAHOO.util.Dom.getX(C);},getPosY:function(C){return YAHOO.util.Dom.getY(C);},swapNode:function(E,C){if(E.swapNode){E.swapNode(C);}else{var F=C.parentNode;var D=C.nextSibling;if(D==E){F.insertBefore(E,C);}else{if(C==E.nextSibling){F.insertBefore(C,E);}else{E.parentNode.replaceChild(C,E);F.insertBefore(E,D);}}}},getScroll:function(){var E,C,F=document.documentElement,D=document.body;if(F&&(F.scrollTop||F.scrollLeft)){E=F.scrollTop;C=F.scrollLeft;}else{if(D){E=D.scrollTop;C=D.scrollLeft;}else{}}return{top:E,left:C};},getStyle:function(D,C){return YAHOO.util.Dom.getStyle(D,C);},getScrollTop:function(){return this.getScroll().top;},getScrollLeft:function(){return this.getScroll().left;},moveToEl:function(C,E){var D=YAHOO.util.Dom.getXY(E);YAHOO.util.Dom.setXY(C,D);},getClientHeight:function(){return YAHOO.util.Dom.getViewportHeight();},getClientWidth:function(){return YAHOO.util.Dom.getViewportWidth();},numericSort:function(D,C){return(D-C);},_timeoutCount:0,_addListeners:function(){var C=YAHOO.util.DDM;if(YAHOO.util.Event&&document){C._onLoad();}else{if(C._timeoutCount>2000){}else{setTimeout(C._addListeners,10);if(document&&document.body){C._timeoutCount+=1;}}}},handleWasClicked:function(C,E){if(this.isHandle(E,C.id)){return true;}else{var D=C.parentNode;while(D){if(this.isHandle(E,D.id)){return true;}else{D=D.parentNode;}}}return false;}};}();YAHOO.util.DDM=YAHOO.util.DragDropMgr;YAHOO.util.DDM._addListeners();}(function(){var A=YAHOO.util.Event;var B=YAHOO.util.Dom;YAHOO.util.DragDrop=function(E,C,D){if(E){this.init(E,C,D);}};YAHOO.util.DragDrop.prototype={events:null,on:function(){this.subscribe.apply(this,arguments);},id:null,config:null,dragElId:null,handleElId:null,invalidHandleTypes:null,invalidHandleIds:null,invalidHandleClasses:null,startPageX:0,startPageY:0,groups:null,locked:false,lock:function(){this.locked=true;},unlock:function(){this.locked=false;},isTarget:true,padding:null,dragOnly:false,useShim:false,_domRef:null,__ygDragDrop:true,constrainX:false,constrainY:false,minX:0,maxX:0,minY:0,maxY:0,deltaX:0,deltaY:0,maintainOffset:false,xTicks:null,yTicks:null,primaryButtonOnly:true,available:false,hasOuterHandles:false,cursorIsOver:false,overlap:null,b4StartDrag:function(C,D){},startDrag:function(C,D){},b4Drag:function(C){},onDrag:function(C){},onDragEnter:function(C,D){},b4DragOver:function(C){},onDragOver:function(C,D){},b4DragOut:function(C){},onDragOut:function(C,D){},b4DragDrop:function(C){},onDragDrop:function(C,D){},onInvalidDrop:function(C){},b4EndDrag:function(C){},endDrag:function(C){},b4MouseDown:function(C){},onMouseDown:function(C){},onMouseUp:function(C){},onAvailable:function(){},getEl:function(){if(!this._domRef){this._domRef=B.get(this.id);
}return this._domRef;},getDragEl:function(){return B.get(this.dragElId);},init:function(F,C,D){this.initTarget(F,C,D);A.on(this._domRef||this.id,"mousedown",this.handleMouseDown,this,true);for(var E in this.events){this.createEvent(E+"Event");}},initTarget:function(E,C,D){this.config=D||{};this.events={};this.DDM=YAHOO.util.DDM;this.groups={};if(typeof E!=="string"){this._domRef=E;E=B.generateId(E);}this.id=E;this.addToGroup((C)?C:"default");this.handleElId=E;A.onAvailable(E,this.handleOnAvailable,this,true);this.setDragElId(E);this.invalidHandleTypes={A:"A"};this.invalidHandleIds={};this.invalidHandleClasses=[];this.applyConfig();},applyConfig:function(){this.events={mouseDown:true,b4MouseDown:true,mouseUp:true,b4StartDrag:true,startDrag:true,b4EndDrag:true,endDrag:true,drag:true,b4Drag:true,invalidDrop:true,b4DragOut:true,dragOut:true,dragEnter:true,b4DragOver:true,dragOver:true,b4DragDrop:true,dragDrop:true};if(this.config.events){for(var C in this.config.events){if(this.config.events[C]===false){this.events[C]=false;}}}this.padding=this.config.padding||[0,0,0,0];this.isTarget=(this.config.isTarget!==false);this.maintainOffset=(this.config.maintainOffset);this.primaryButtonOnly=(this.config.primaryButtonOnly!==false);this.dragOnly=((this.config.dragOnly===true)?true:false);this.useShim=((this.config.useShim===true)?true:false);},handleOnAvailable:function(){this.available=true;this.resetConstraints();this.onAvailable();},setPadding:function(E,C,F,D){if(!C&&0!==C){this.padding=[E,E,E,E];}else{if(!F&&0!==F){this.padding=[E,C,E,C];}else{this.padding=[E,C,F,D];}}},setInitPosition:function(F,E){var G=this.getEl();if(!this.DDM.verifyEl(G)){if(G&&G.style&&(G.style.display=="none")){}else{}return;}var D=F||0;var C=E||0;var H=B.getXY(G);this.initPageX=H[0]-D;this.initPageY=H[1]-C;this.lastPageX=H[0];this.lastPageY=H[1];this.setStartPosition(H);},setStartPosition:function(D){var C=D||B.getXY(this.getEl());this.deltaSetXY=null;this.startPageX=C[0];this.startPageY=C[1];},addToGroup:function(C){this.groups[C]=true;this.DDM.regDragDrop(this,C);},removeFromGroup:function(C){if(this.groups[C]){delete this.groups[C];}this.DDM.removeDDFromGroup(this,C);},setDragElId:function(C){this.dragElId=C;},setHandleElId:function(C){if(typeof C!=="string"){C=B.generateId(C);}this.handleElId=C;this.DDM.regHandle(this.id,C);},setOuterHandleElId:function(C){if(typeof C!=="string"){C=B.generateId(C);}A.on(C,"mousedown",this.handleMouseDown,this,true);this.setHandleElId(C);this.hasOuterHandles=true;},unreg:function(){A.removeListener(this.id,"mousedown",this.handleMouseDown);this._domRef=null;this.DDM._remove(this);},isLocked:function(){return(this.DDM.isLocked()||this.locked);},handleMouseDown:function(J,I){var D=J.which||J.button;if(this.primaryButtonOnly&&D>1){return;}if(this.isLocked()){return;}var C=this.b4MouseDown(J),F=true;if(this.events.b4MouseDown){F=this.fireEvent("b4MouseDownEvent",J);}var E=this.onMouseDown(J),H=true;if(this.events.mouseDown){H=this.fireEvent("mouseDownEvent",J);}if((C===false)||(E===false)||(F===false)||(H===false)){return;}this.DDM.refreshCache(this.groups);var G=new YAHOO.util.Point(A.getPageX(J),A.getPageY(J));if(!this.hasOuterHandles&&!this.DDM.isOverTarget(G,this)){}else{if(this.clickValidator(J)){this.setStartPosition();this.DDM.handleMouseDown(J,this);this.DDM.stopEvent(J);}else{}}},clickValidator:function(D){var C=YAHOO.util.Event.getTarget(D);return(this.isValidHandleChild(C)&&(this.id==this.handleElId||this.DDM.handleWasClicked(C,this.id)));},getTargetCoord:function(E,D){var C=E-this.deltaX;var F=D-this.deltaY;if(this.constrainX){if(C<this.minX){C=this.minX;}if(C>this.maxX){C=this.maxX;}}if(this.constrainY){if(F<this.minY){F=this.minY;}if(F>this.maxY){F=this.maxY;}}C=this.getTick(C,this.xTicks);F=this.getTick(F,this.yTicks);return{x:C,y:F};},addInvalidHandleType:function(C){var D=C.toUpperCase();this.invalidHandleTypes[D]=D;},addInvalidHandleId:function(C){if(typeof C!=="string"){C=B.generateId(C);}this.invalidHandleIds[C]=C;},addInvalidHandleClass:function(C){this.invalidHandleClasses.push(C);},removeInvalidHandleType:function(C){var D=C.toUpperCase();delete this.invalidHandleTypes[D];},removeInvalidHandleId:function(C){if(typeof C!=="string"){C=B.generateId(C);}delete this.invalidHandleIds[C];},removeInvalidHandleClass:function(D){for(var E=0,C=this.invalidHandleClasses.length;E<C;++E){if(this.invalidHandleClasses[E]==D){delete this.invalidHandleClasses[E];}}},isValidHandleChild:function(F){var E=true;var H;try{H=F.nodeName.toUpperCase();}catch(G){H=F.nodeName;}E=E&&!this.invalidHandleTypes[H];E=E&&!this.invalidHandleIds[F.id];for(var D=0,C=this.invalidHandleClasses.length;E&&D<C;++D){E=!B.hasClass(F,this.invalidHandleClasses[D]);}return E;},setXTicks:function(F,C){this.xTicks=[];this.xTickSize=C;var E={};for(var D=this.initPageX;D>=this.minX;D=D-C){if(!E[D]){this.xTicks[this.xTicks.length]=D;E[D]=true;}}for(D=this.initPageX;D<=this.maxX;D=D+C){if(!E[D]){this.xTicks[this.xTicks.length]=D;E[D]=true;}}this.xTicks.sort(this.DDM.numericSort);},setYTicks:function(F,C){this.yTicks=[];this.yTickSize=C;var E={};for(var D=this.initPageY;D>=this.minY;D=D-C){if(!E[D]){this.yTicks[this.yTicks.length]=D;E[D]=true;}}for(D=this.initPageY;D<=this.maxY;D=D+C){if(!E[D]){this.yTicks[this.yTicks.length]=D;E[D]=true;}}this.yTicks.sort(this.DDM.numericSort);},setXConstraint:function(E,D,C){this.leftConstraint=parseInt(E,10);this.rightConstraint=parseInt(D,10);this.minX=this.initPageX-this.leftConstraint;this.maxX=this.initPageX+this.rightConstraint;if(C){this.setXTicks(this.initPageX,C);}this.constrainX=true;},clearConstraints:function(){this.constrainX=false;this.constrainY=false;this.clearTicks();},clearTicks:function(){this.xTicks=null;this.yTicks=null;this.xTickSize=0;this.yTickSize=0;},setYConstraint:function(C,E,D){this.topConstraint=parseInt(C,10);this.bottomConstraint=parseInt(E,10);this.minY=this.initPageY-this.topConstraint;this.maxY=this.initPageY+this.bottomConstraint;if(D){this.setYTicks(this.initPageY,D);
}this.constrainY=true;},resetConstraints:function(){if(this.initPageX||this.initPageX===0){var D=(this.maintainOffset)?this.lastPageX-this.initPageX:0;var C=(this.maintainOffset)?this.lastPageY-this.initPageY:0;this.setInitPosition(D,C);}else{this.setInitPosition();}if(this.constrainX){this.setXConstraint(this.leftConstraint,this.rightConstraint,this.xTickSize);}if(this.constrainY){this.setYConstraint(this.topConstraint,this.bottomConstraint,this.yTickSize);}},getTick:function(I,F){if(!F){return I;}else{if(F[0]>=I){return F[0];}else{for(var D=0,C=F.length;D<C;++D){var E=D+1;if(F[E]&&F[E]>=I){var H=I-F[D];var G=F[E]-I;return(G>H)?F[D]:F[E];}}return F[F.length-1];}}},toString:function(){return("DragDrop "+this.id);}};YAHOO.augment(YAHOO.util.DragDrop,YAHOO.util.EventProvider);})();YAHOO.util.DD=function(C,A,B){if(C){this.init(C,A,B);}};YAHOO.extend(YAHOO.util.DD,YAHOO.util.DragDrop,{scroll:true,autoOffset:function(C,B){var A=C-this.startPageX;var D=B-this.startPageY;this.setDelta(A,D);},setDelta:function(B,A){this.deltaX=B;this.deltaY=A;},setDragElPos:function(C,B){var A=this.getDragEl();this.alignElWithMouse(A,C,B);},alignElWithMouse:function(C,G,F){var E=this.getTargetCoord(G,F);if(!this.deltaSetXY){var H=[E.x,E.y];YAHOO.util.Dom.setXY(C,H);var D=parseInt(YAHOO.util.Dom.getStyle(C,"left"),10);var B=parseInt(YAHOO.util.Dom.getStyle(C,"top"),10);this.deltaSetXY=[D-E.x,B-E.y];}else{YAHOO.util.Dom.setStyle(C,"left",(E.x+this.deltaSetXY[0])+"px");YAHOO.util.Dom.setStyle(C,"top",(E.y+this.deltaSetXY[1])+"px");}this.cachePosition(E.x,E.y);var A=this;setTimeout(function(){A.autoScroll.call(A,E.x,E.y,C.offsetHeight,C.offsetWidth);},0);},cachePosition:function(B,A){if(B){this.lastPageX=B;this.lastPageY=A;}else{var C=YAHOO.util.Dom.getXY(this.getEl());this.lastPageX=C[0];this.lastPageY=C[1];}},autoScroll:function(J,I,E,K){if(this.scroll){var L=this.DDM.getClientHeight();var B=this.DDM.getClientWidth();var N=this.DDM.getScrollTop();var D=this.DDM.getScrollLeft();var H=E+I;var M=K+J;var G=(L+N-I-this.deltaY);var F=(B+D-J-this.deltaX);var C=40;var A=(document.all)?80:30;if(H>L&&G<C){window.scrollTo(D,N+A);}if(I<N&&N>0&&I-N<C){window.scrollTo(D,N-A);}if(M>B&&F<C){window.scrollTo(D+A,N);}if(J<D&&D>0&&J-D<C){window.scrollTo(D-A,N);}}},applyConfig:function(){YAHOO.util.DD.superclass.applyConfig.call(this);this.scroll=(this.config.scroll!==false);},b4MouseDown:function(A){this.setStartPosition();this.autoOffset(YAHOO.util.Event.getPageX(A),YAHOO.util.Event.getPageY(A));},b4Drag:function(A){this.setDragElPos(YAHOO.util.Event.getPageX(A),YAHOO.util.Event.getPageY(A));},toString:function(){return("DD "+this.id);}});YAHOO.util.DDProxy=function(C,A,B){if(C){this.init(C,A,B);this.initFrame();}};YAHOO.util.DDProxy.dragElId="ygddfdiv";YAHOO.extend(YAHOO.util.DDProxy,YAHOO.util.DD,{resizeFrame:true,centerFrame:false,createFrame:function(){var B=this,A=document.body;if(!A||!A.firstChild){setTimeout(function(){B.createFrame();},50);return;}var F=this.getDragEl(),E=YAHOO.util.Dom;if(!F){F=document.createElement("div");F.id=this.dragElId;var D=F.style;D.position="absolute";D.visibility="hidden";D.cursor="move";D.border="2px solid #aaa";D.zIndex=999;D.height="25px";D.width="25px";var C=document.createElement("div");E.setStyle(C,"height","100%");E.setStyle(C,"width","100%");E.setStyle(C,"background-color","#ccc");E.setStyle(C,"opacity","0");F.appendChild(C);A.insertBefore(F,A.firstChild);}},initFrame:function(){this.createFrame();},applyConfig:function(){YAHOO.util.DDProxy.superclass.applyConfig.call(this);this.resizeFrame=(this.config.resizeFrame!==false);this.centerFrame=(this.config.centerFrame);this.setDragElId(this.config.dragElId||YAHOO.util.DDProxy.dragElId);},showFrame:function(E,D){var C=this.getEl();var A=this.getDragEl();var B=A.style;this._resizeProxy();if(this.centerFrame){this.setDelta(Math.round(parseInt(B.width,10)/2),Math.round(parseInt(B.height,10)/2));}this.setDragElPos(E,D);YAHOO.util.Dom.setStyle(A,"visibility","visible");},_resizeProxy:function(){if(this.resizeFrame){var H=YAHOO.util.Dom;var B=this.getEl();var C=this.getDragEl();var G=parseInt(H.getStyle(C,"borderTopWidth"),10);var I=parseInt(H.getStyle(C,"borderRightWidth"),10);var F=parseInt(H.getStyle(C,"borderBottomWidth"),10);var D=parseInt(H.getStyle(C,"borderLeftWidth"),10);if(isNaN(G)){G=0;}if(isNaN(I)){I=0;}if(isNaN(F)){F=0;}if(isNaN(D)){D=0;}var E=Math.max(0,B.offsetWidth-I-D);var A=Math.max(0,B.offsetHeight-G-F);H.setStyle(C,"width",E+"px");H.setStyle(C,"height",A+"px");}},b4MouseDown:function(B){this.setStartPosition();var A=YAHOO.util.Event.getPageX(B);var C=YAHOO.util.Event.getPageY(B);this.autoOffset(A,C);},b4StartDrag:function(A,B){this.showFrame(A,B);},b4EndDrag:function(A){YAHOO.util.Dom.setStyle(this.getDragEl(),"visibility","hidden");},endDrag:function(D){var C=YAHOO.util.Dom;var B=this.getEl();var A=this.getDragEl();C.setStyle(A,"visibility","");C.setStyle(B,"visibility","hidden");YAHOO.util.DDM.moveToEl(B,A);C.setStyle(A,"visibility","hidden");C.setStyle(B,"visibility","");},toString:function(){return("DDProxy "+this.id);}});YAHOO.util.DDTarget=function(C,A,B){if(C){this.initTarget(C,A,B);}};YAHOO.extend(YAHOO.util.DDTarget,YAHOO.util.DragDrop,{toString:function(){return("DDTarget "+this.id);}});YAHOO.register("dragdrop",YAHOO.util.DragDropMgr,{version:"2.7.0",build:"1796"});/*
Copyright (c) 2009, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.7.0
*/
(function(){var B=YAHOO.util.Dom.getXY,A=YAHOO.util.Event,D=Array.prototype.slice;function C(G,E,F,H){C.ANIM_AVAIL=(!YAHOO.lang.isUndefined(YAHOO.util.Anim));if(G){this.init(G,E,true);this.initSlider(H);this.initThumb(F);}}YAHOO.lang.augmentObject(C,{getHorizSlider:function(F,G,I,H,E){return new C(F,F,new YAHOO.widget.SliderThumb(G,F,I,H,0,0,E),"horiz");},getVertSlider:function(G,H,E,I,F){return new C(G,G,new YAHOO.widget.SliderThumb(H,G,0,0,E,I,F),"vert");},getSliderRegion:function(G,H,J,I,E,K,F){return new C(G,G,new YAHOO.widget.SliderThumb(H,G,J,I,E,K,F),"region");},SOURCE_UI_EVENT:1,SOURCE_SET_VALUE:2,SOURCE_KEY_EVENT:3,ANIM_AVAIL:false},true);YAHOO.extend(C,YAHOO.util.DragDrop,{_mouseDown:false,dragOnly:true,initSlider:function(E){this.type=E;this.createEvent("change",this);this.createEvent("slideStart",this);this.createEvent("slideEnd",this);this.isTarget=false;this.animate=C.ANIM_AVAIL;this.backgroundEnabled=true;this.tickPause=40;this.enableKeys=true;this.keyIncrement=20;this.moveComplete=true;this.animationDuration=0.2;this.SOURCE_UI_EVENT=1;this.SOURCE_SET_VALUE=2;this.valueChangeSource=0;this._silent=false;this.lastOffset=[0,0];},initThumb:function(F){var E=this;this.thumb=F;F.cacheBetweenDrags=true;if(F._isHoriz&&F.xTicks&&F.xTicks.length){this.tickPause=Math.round(360/F.xTicks.length);}else{if(F.yTicks&&F.yTicks.length){this.tickPause=Math.round(360/F.yTicks.length);}}F.onAvailable=function(){return E.setStartSliderState();};F.onMouseDown=function(){E._mouseDown=true;return E.focus();};F.startDrag=function(){E._slideStart();};F.onDrag=function(){E.fireEvents(true);};F.onMouseUp=function(){E.thumbMouseUp();};},onAvailable:function(){this._bindKeyEvents();},_bindKeyEvents:function(){A.on(this.id,"keydown",this.handleKeyDown,this,true);A.on(this.id,"keypress",this.handleKeyPress,this,true);},handleKeyPress:function(F){if(this.enableKeys){var E=A.getCharCode(F);switch(E){case 37:case 38:case 39:case 40:case 36:case 35:A.preventDefault(F);break;default:}}},handleKeyDown:function(J){if(this.enableKeys){var G=A.getCharCode(J),F=this.thumb,H=this.getXValue(),E=this.getYValue(),I=true;switch(G){case 37:H-=this.keyIncrement;break;case 38:E-=this.keyIncrement;break;case 39:H+=this.keyIncrement;break;case 40:E+=this.keyIncrement;break;case 36:H=F.leftConstraint;E=F.topConstraint;break;case 35:H=F.rightConstraint;E=F.bottomConstraint;break;default:I=false;}if(I){if(F._isRegion){this._setRegionValue(C.SOURCE_KEY_EVENT,H,E,true);}else{this._setValue(C.SOURCE_KEY_EVENT,(F._isHoriz?H:E),true);}A.stopEvent(J);}}},setStartSliderState:function(){this.setThumbCenterPoint();this.baselinePos=B(this.getEl());this.thumb.startOffset=this.thumb.getOffsetFromParent(this.baselinePos);if(this.thumb._isRegion){if(this.deferredSetRegionValue){this._setRegionValue.apply(this,this.deferredSetRegionValue);this.deferredSetRegionValue=null;}else{this.setRegionValue(0,0,true,true,true);}}else{if(this.deferredSetValue){this._setValue.apply(this,this.deferredSetValue);this.deferredSetValue=null;}else{this.setValue(0,true,true,true);}}},setThumbCenterPoint:function(){var E=this.thumb.getEl();if(E){this.thumbCenterPoint={x:parseInt(E.offsetWidth/2,10),y:parseInt(E.offsetHeight/2,10)};}},lock:function(){this.thumb.lock();this.locked=true;},unlock:function(){this.thumb.unlock();this.locked=false;},thumbMouseUp:function(){this._mouseDown=false;if(!this.isLocked()&&!this.moveComplete){this.endMove();}},onMouseUp:function(){this._mouseDown=false;if(this.backgroundEnabled&&!this.isLocked()&&!this.moveComplete){this.endMove();}},getThumb:function(){return this.thumb;},focus:function(){this.valueChangeSource=C.SOURCE_UI_EVENT;var E=this.getEl();if(E.focus){try{E.focus();}catch(F){}}this.verifyOffset();return !this.isLocked();},onChange:function(E,F){},onSlideStart:function(){},onSlideEnd:function(){},getValue:function(){return this.thumb.getValue();},getXValue:function(){return this.thumb.getXValue();},getYValue:function(){return this.thumb.getYValue();},setValue:function(){var E=D.call(arguments);E.unshift(C.SOURCE_SET_VALUE);return this._setValue.apply(this,E);},_setValue:function(I,L,G,H,E){var F=this.thumb,K,J;if(!F.available){this.deferredSetValue=arguments;return false;}if(this.isLocked()&&!H){return false;}if(isNaN(L)){return false;}if(F._isRegion){return false;}this._silent=E;this.valueChangeSource=I||C.SOURCE_SET_VALUE;F.lastOffset=[L,L];this.verifyOffset(true);this._slideStart();if(F._isHoriz){K=F.initPageX+L+this.thumbCenterPoint.x;this.moveThumb(K,F.initPageY,G);}else{J=F.initPageY+L+this.thumbCenterPoint.y;this.moveThumb(F.initPageX,J,G);}return true;},setRegionValue:function(){var E=D.call(arguments);E.unshift(C.SOURCE_SET_VALUE);return this._setRegionValue.apply(this,E);},_setRegionValue:function(F,J,H,I,G,K){var L=this.thumb,E,M;if(!L.available){this.deferredSetRegionValue=arguments;return false;}if(this.isLocked()&&!G){return false;}if(isNaN(J)){return false;}if(!L._isRegion){return false;}this._silent=K;this.valueChangeSource=F||C.SOURCE_SET_VALUE;L.lastOffset=[J,H];this.verifyOffset(true);this._slideStart();E=L.initPageX+J+this.thumbCenterPoint.x;M=L.initPageY+H+this.thumbCenterPoint.y;this.moveThumb(E,M,I);return true;},verifyOffset:function(F){var G=B(this.getEl()),E=this.thumb;if(!this.thumbCenterPoint||!this.thumbCenterPoint.x){this.setThumbCenterPoint();}if(G){if(G[0]!=this.baselinePos[0]||G[1]!=this.baselinePos[1]){this.setInitPosition();this.baselinePos=G;E.initPageX=this.initPageX+E.startOffset[0];E.initPageY=this.initPageY+E.startOffset[1];E.deltaSetXY=null;this.resetThumbConstraints();return false;}}return true;},moveThumb:function(K,J,I,G){var L=this.thumb,M=this,F,E,H;if(!L.available){return;}L.setDelta(this.thumbCenterPoint.x,this.thumbCenterPoint.y);E=L.getTargetCoord(K,J);F=[Math.round(E.x),Math.round(E.y)];if(this.animate&&L._graduated&&!I){this.lock();this.curCoord=B(this.thumb.getEl());this.curCoord=[Math.round(this.curCoord[0]),Math.round(this.curCoord[1])];setTimeout(function(){M.moveOneTick(F);
},this.tickPause);}else{if(this.animate&&C.ANIM_AVAIL&&!I){this.lock();H=new YAHOO.util.Motion(L.id,{points:{to:F}},this.animationDuration,YAHOO.util.Easing.easeOut);H.onComplete.subscribe(function(){M.unlock();if(!M._mouseDown){M.endMove();}});H.animate();}else{L.setDragElPos(K,J);if(!G&&!this._mouseDown){this.endMove();}}}},_slideStart:function(){if(!this._sliding){if(!this._silent){this.onSlideStart();this.fireEvent("slideStart");}this._sliding=true;}},_slideEnd:function(){if(this._sliding&&this.moveComplete){var E=this._silent;this._sliding=false;this._silent=false;this.moveComplete=false;if(!E){this.onSlideEnd();this.fireEvent("slideEnd");}}},moveOneTick:function(F){var H=this.thumb,G=this,I=null,E,J;if(H._isRegion){I=this._getNextX(this.curCoord,F);E=(I!==null)?I[0]:this.curCoord[0];I=this._getNextY(this.curCoord,F);J=(I!==null)?I[1]:this.curCoord[1];I=E!==this.curCoord[0]||J!==this.curCoord[1]?[E,J]:null;}else{if(H._isHoriz){I=this._getNextX(this.curCoord,F);}else{I=this._getNextY(this.curCoord,F);}}if(I){this.curCoord=I;this.thumb.alignElWithMouse(H.getEl(),I[0]+this.thumbCenterPoint.x,I[1]+this.thumbCenterPoint.y);if(!(I[0]==F[0]&&I[1]==F[1])){setTimeout(function(){G.moveOneTick(F);},this.tickPause);}else{this.unlock();if(!this._mouseDown){this.endMove();}}}else{this.unlock();if(!this._mouseDown){this.endMove();}}},_getNextX:function(E,F){var H=this.thumb,J,G=[],I=null;if(E[0]>F[0]){J=H.tickSize-this.thumbCenterPoint.x;G=H.getTargetCoord(E[0]-J,E[1]);I=[G.x,G.y];}else{if(E[0]<F[0]){J=H.tickSize+this.thumbCenterPoint.x;G=H.getTargetCoord(E[0]+J,E[1]);I=[G.x,G.y];}else{}}return I;},_getNextY:function(E,F){var H=this.thumb,J,G=[],I=null;if(E[1]>F[1]){J=H.tickSize-this.thumbCenterPoint.y;G=H.getTargetCoord(E[0],E[1]-J);I=[G.x,G.y];}else{if(E[1]<F[1]){J=H.tickSize+this.thumbCenterPoint.y;G=H.getTargetCoord(E[0],E[1]+J);I=[G.x,G.y];}else{}}return I;},b4MouseDown:function(E){if(!this.backgroundEnabled){return false;}this.thumb.autoOffset();this.resetThumbConstraints();},onMouseDown:function(F){if(!this.backgroundEnabled||this.isLocked()){return false;}this._mouseDown=true;var E=A.getPageX(F),G=A.getPageY(F);this.focus();this._slideStart();this.moveThumb(E,G);},onDrag:function(F){if(this.backgroundEnabled&&!this.isLocked()){var E=A.getPageX(F),G=A.getPageY(F);this.moveThumb(E,G,true,true);this.fireEvents();}},endMove:function(){this.unlock();this.fireEvents();this.moveComplete=true;this._slideEnd();},resetThumbConstraints:function(){var E=this.thumb;E.setXConstraint(E.leftConstraint,E.rightConstraint,E.xTickSize);E.setYConstraint(E.topConstraint,E.bottomConstraint,E.xTickSize);},fireEvents:function(G){var F=this.thumb,I,H,E;if(!G){F.cachePosition();}if(!this.isLocked()){if(F._isRegion){I=F.getXValue();H=F.getYValue();if(I!=this.previousX||H!=this.previousY){if(!this._silent){this.onChange(I,H);this.fireEvent("change",{x:I,y:H});}}this.previousX=I;this.previousY=H;}else{E=F.getValue();if(E!=this.previousVal){if(!this._silent){this.onChange(E);this.fireEvent("change",E);}}this.previousVal=E;}}},toString:function(){return("Slider ("+this.type+") "+this.id);}});YAHOO.lang.augmentProto(C,YAHOO.util.EventProvider);YAHOO.widget.Slider=C;})();YAHOO.widget.SliderThumb=function(G,B,E,D,A,F,C){if(G){YAHOO.widget.SliderThumb.superclass.constructor.call(this,G,B);this.parentElId=B;}this.isTarget=false;this.tickSize=C;this.maintainOffset=true;this.initSlider(E,D,A,F,C);this.scroll=false;};YAHOO.extend(YAHOO.widget.SliderThumb,YAHOO.util.DD,{startOffset:null,dragOnly:true,_isHoriz:false,_prevVal:0,_graduated:false,getOffsetFromParent0:function(C){var A=YAHOO.util.Dom.getXY(this.getEl()),B=C||YAHOO.util.Dom.getXY(this.parentElId);return[(A[0]-B[0]),(A[1]-B[1])];},getOffsetFromParent:function(H){var A=this.getEl(),E,I,F,B,K,D,C,J,G;if(!this.deltaOffset){I=YAHOO.util.Dom.getXY(A);F=H||YAHOO.util.Dom.getXY(this.parentElId);E=[(I[0]-F[0]),(I[1]-F[1])];B=parseInt(YAHOO.util.Dom.getStyle(A,"left"),10);K=parseInt(YAHOO.util.Dom.getStyle(A,"top"),10);D=B-E[0];C=K-E[1];if(isNaN(D)||isNaN(C)){}else{this.deltaOffset=[D,C];}}else{J=parseInt(YAHOO.util.Dom.getStyle(A,"left"),10);G=parseInt(YAHOO.util.Dom.getStyle(A,"top"),10);E=[J+this.deltaOffset[0],G+this.deltaOffset[1]];}return E;},initSlider:function(D,C,A,E,B){this.initLeft=D;this.initRight=C;this.initUp=A;this.initDown=E;this.setXConstraint(D,C,B);this.setYConstraint(A,E,B);if(B&&B>1){this._graduated=true;}this._isHoriz=(D||C);this._isVert=(A||E);this._isRegion=(this._isHoriz&&this._isVert);},clearTicks:function(){YAHOO.widget.SliderThumb.superclass.clearTicks.call(this);this.tickSize=0;this._graduated=false;},getValue:function(){return(this._isHoriz)?this.getXValue():this.getYValue();},getXValue:function(){if(!this.available){return 0;}var A=this.getOffsetFromParent();if(YAHOO.lang.isNumber(A[0])){this.lastOffset=A;return(A[0]-this.startOffset[0]);}else{return(this.lastOffset[0]-this.startOffset[0]);}},getYValue:function(){if(!this.available){return 0;}var A=this.getOffsetFromParent();if(YAHOO.lang.isNumber(A[1])){this.lastOffset=A;return(A[1]-this.startOffset[1]);}else{return(this.lastOffset[1]-this.startOffset[1]);}},toString:function(){return"SliderThumb "+this.id;},onChange:function(A,B){}});(function(){var A=YAHOO.util.Event,B=YAHOO.widget;function C(I,F,H,D){var G=this,J={min:false,max:false},E,K;this.minSlider=I;this.maxSlider=F;this.activeSlider=I;this.isHoriz=I.thumb._isHoriz;E=this.minSlider.thumb.onMouseDown;K=this.maxSlider.thumb.onMouseDown;this.minSlider.thumb.onMouseDown=function(){G.activeSlider=G.minSlider;E.apply(this,arguments);};this.maxSlider.thumb.onMouseDown=function(){G.activeSlider=G.maxSlider;K.apply(this,arguments);};this.minSlider.thumb.onAvailable=function(){I.setStartSliderState();J.min=true;if(J.max){G.fireEvent("ready",G);}};this.maxSlider.thumb.onAvailable=function(){F.setStartSliderState();J.max=true;if(J.min){G.fireEvent("ready",G);}};I.onMouseDown=F.onMouseDown=function(L){return this.backgroundEnabled&&G._handleMouseDown(L);
};I.onDrag=F.onDrag=function(L){G._handleDrag(L);};I.onMouseUp=F.onMouseUp=function(L){G._handleMouseUp(L);};I._bindKeyEvents=function(){G._bindKeyEvents(this);};F._bindKeyEvents=function(){};I.subscribe("change",this._handleMinChange,I,this);I.subscribe("slideStart",this._handleSlideStart,I,this);I.subscribe("slideEnd",this._handleSlideEnd,I,this);F.subscribe("change",this._handleMaxChange,F,this);F.subscribe("slideStart",this._handleSlideStart,F,this);F.subscribe("slideEnd",this._handleSlideEnd,F,this);this.createEvent("ready",this);this.createEvent("change",this);this.createEvent("slideStart",this);this.createEvent("slideEnd",this);D=YAHOO.lang.isArray(D)?D:[0,H];D[0]=Math.min(Math.max(parseInt(D[0],10)|0,0),H);D[1]=Math.max(Math.min(parseInt(D[1],10)|0,H),0);if(D[0]>D[1]){D.splice(0,2,D[1],D[0]);}this.minVal=D[0];this.maxVal=D[1];this.minSlider.setValue(this.minVal,true,true,true);this.maxSlider.setValue(this.maxVal,true,true,true);}C.prototype={minVal:-1,maxVal:-1,minRange:0,_handleSlideStart:function(E,D){this.fireEvent("slideStart",D);},_handleSlideEnd:function(E,D){this.fireEvent("slideEnd",D);},_handleDrag:function(D){B.Slider.prototype.onDrag.call(this.activeSlider,D);},_handleMinChange:function(){this.activeSlider=this.minSlider;this.updateValue();},_handleMaxChange:function(){this.activeSlider=this.maxSlider;this.updateValue();},_bindKeyEvents:function(D){A.on(D.id,"keydown",this._handleKeyDown,this,true);A.on(D.id,"keypress",this._handleKeyPress,this,true);},_handleKeyDown:function(D){this.activeSlider.handleKeyDown.apply(this.activeSlider,arguments);},_handleKeyPress:function(D){this.activeSlider.handleKeyPress.apply(this.activeSlider,arguments);},setValues:function(H,K,I,E,J){var F=this.minSlider,M=this.maxSlider,D=F.thumb,L=M.thumb,N=this,G={min:false,max:false};if(D._isHoriz){D.setXConstraint(D.leftConstraint,L.rightConstraint,D.tickSize);L.setXConstraint(D.leftConstraint,L.rightConstraint,L.tickSize);}else{D.setYConstraint(D.topConstraint,L.bottomConstraint,D.tickSize);L.setYConstraint(D.topConstraint,L.bottomConstraint,L.tickSize);}this._oneTimeCallback(F,"slideEnd",function(){G.min=true;if(G.max){N.updateValue(J);setTimeout(function(){N._cleanEvent(F,"slideEnd");N._cleanEvent(M,"slideEnd");},0);}});this._oneTimeCallback(M,"slideEnd",function(){G.max=true;if(G.min){N.updateValue(J);setTimeout(function(){N._cleanEvent(F,"slideEnd");N._cleanEvent(M,"slideEnd");},0);}});F.setValue(H,I,E,false);M.setValue(K,I,E,false);},setMinValue:function(F,H,I,E){var G=this.minSlider,D=this;this.activeSlider=G;D=this;this._oneTimeCallback(G,"slideEnd",function(){D.updateValue(E);setTimeout(function(){D._cleanEvent(G,"slideEnd");},0);});G.setValue(F,H,I);},setMaxValue:function(D,H,I,F){var G=this.maxSlider,E=this;this.activeSlider=G;this._oneTimeCallback(G,"slideEnd",function(){E.updateValue(F);setTimeout(function(){E._cleanEvent(G,"slideEnd");},0);});G.setValue(D,H,I);},updateValue:function(J){var E=this.minSlider.getValue(),K=this.maxSlider.getValue(),F=false,D,M,H,I,L,G;if(E!=this.minVal||K!=this.maxVal){F=true;D=this.minSlider.thumb;M=this.maxSlider.thumb;H=this.isHoriz?"x":"y";G=this.minSlider.thumbCenterPoint[H]+this.maxSlider.thumbCenterPoint[H];I=Math.max(K-G-this.minRange,0);L=Math.min(-E-G-this.minRange,0);if(this.isHoriz){I=Math.min(I,M.rightConstraint);D.setXConstraint(D.leftConstraint,I,D.tickSize);M.setXConstraint(L,M.rightConstraint,M.tickSize);}else{I=Math.min(I,M.bottomConstraint);D.setYConstraint(D.leftConstraint,I,D.tickSize);M.setYConstraint(L,M.bottomConstraint,M.tickSize);}}this.minVal=E;this.maxVal=K;if(F&&!J){this.fireEvent("change",this);}},selectActiveSlider:function(H){var E=this.minSlider,D=this.maxSlider,J=E.isLocked()||!E.backgroundEnabled,G=D.isLocked()||!E.backgroundEnabled,F=YAHOO.util.Event,I;if(J||G){this.activeSlider=J?D:E;}else{if(this.isHoriz){I=F.getPageX(H)-E.thumb.initPageX-E.thumbCenterPoint.x;}else{I=F.getPageY(H)-E.thumb.initPageY-E.thumbCenterPoint.y;}this.activeSlider=I*2>D.getValue()+E.getValue()?D:E;}},_handleMouseDown:function(D){if(!D._handled){D._handled=true;this.selectActiveSlider(D);return B.Slider.prototype.onMouseDown.call(this.activeSlider,D);}else{return false;}},_handleMouseUp:function(D){B.Slider.prototype.onMouseUp.apply(this.activeSlider,arguments);},_oneTimeCallback:function(F,D,E){F.subscribe(D,function(){F.unsubscribe(D,arguments.callee);E.apply({},[].slice.apply(arguments));});},_cleanEvent:function(K,E){var J,I,D,G,H,F;if(K.__yui_events&&K.events[E]){for(I=K.__yui_events.length;I>=0;--I){if(K.__yui_events[I].type===E){J=K.__yui_events[I];break;}}if(J){H=J.subscribers;F=[];G=0;for(I=0,D=H.length;I<D;++I){if(H[I]){F[G++]=H[I];}}J.subscribers=F;}}}};YAHOO.lang.augmentProto(C,YAHOO.util.EventProvider);B.Slider.getHorizDualSlider=function(H,J,K,G,F,D){var I=new B.SliderThumb(J,H,0,G,0,0,F),E=new B.SliderThumb(K,H,0,G,0,0,F);return new C(new B.Slider(H,H,I,"horiz"),new B.Slider(H,H,E,"horiz"),G,D);};B.Slider.getVertDualSlider=function(H,J,K,G,F,D){var I=new B.SliderThumb(J,H,0,0,0,G,F),E=new B.SliderThumb(K,H,0,0,0,G,F);return new B.DualSlider(new B.Slider(H,H,I,"vert"),new B.Slider(H,H,E,"vert"),G,D);};YAHOO.widget.DualSlider=C;})();YAHOO.register("slider",YAHOO.widget.Slider,{version:"2.7.0",build:"1796"});/*
Copyright (c) 2009, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.7.0
*/
YAHOO.util.Attribute=function(B,A){if(A){this.owner=A;this.configure(B,true);}};YAHOO.util.Attribute.prototype={name:undefined,value:null,owner:null,readOnly:false,writeOnce:false,_initialConfig:null,_written:false,method:null,setter:null,getter:null,validator:null,getValue:function(){var A=this.value;if(this.getter){A=this.getter.call(this.owner,this.name);}return A;},setValue:function(F,B){var E,A=this.owner,C=this.name;var D={type:C,prevValue:this.getValue(),newValue:F};if(this.readOnly||(this.writeOnce&&this._written)){return false;}if(this.validator&&!this.validator.call(A,F)){return false;}if(!B){E=A.fireBeforeChangeEvent(D);if(E===false){return false;}}if(this.setter){F=this.setter.call(A,F,this.name);if(F===undefined){}}if(this.method){this.method.call(A,F,this.name);}this.value=F;this._written=true;D.type=C;if(!B){this.owner.fireChangeEvent(D);}return true;},configure:function(B,C){B=B||{};if(C){this._written=false;}this._initialConfig=this._initialConfig||{};for(var A in B){if(B.hasOwnProperty(A)){this[A]=B[A];if(C){this._initialConfig[A]=B[A];}}}},resetValue:function(){return this.setValue(this._initialConfig.value);},resetConfig:function(){this.configure(this._initialConfig,true);},refresh:function(A){this.setValue(this.value,A);}};(function(){var A=YAHOO.util.Lang;YAHOO.util.AttributeProvider=function(){};YAHOO.util.AttributeProvider.prototype={_configs:null,get:function(C){this._configs=this._configs||{};var B=this._configs[C];if(!B||!this._configs.hasOwnProperty(C)){return null;}return B.getValue();},set:function(D,E,B){this._configs=this._configs||{};var C=this._configs[D];if(!C){return false;}return C.setValue(E,B);},getAttributeKeys:function(){this._configs=this._configs;var C=[],B;for(B in this._configs){if(A.hasOwnProperty(this._configs,B)&&!A.isUndefined(this._configs[B])){C[C.length]=B;}}return C;},setAttributes:function(D,B){for(var C in D){if(A.hasOwnProperty(D,C)){this.set(C,D[C],B);}}},resetValue:function(C,B){this._configs=this._configs||{};if(this._configs[C]){this.set(C,this._configs[C]._initialConfig.value,B);return true;}return false;},refresh:function(E,C){this._configs=this._configs||{};var F=this._configs;E=((A.isString(E))?[E]:E)||this.getAttributeKeys();for(var D=0,B=E.length;D<B;++D){if(F.hasOwnProperty(E[D])){this._configs[E[D]].refresh(C);}}},register:function(B,C){this.setAttributeConfig(B,C);},getAttributeConfig:function(C){this._configs=this._configs||{};var B=this._configs[C]||{};var D={};for(C in B){if(A.hasOwnProperty(B,C)){D[C]=B[C];}}return D;},setAttributeConfig:function(B,C,D){this._configs=this._configs||{};C=C||{};if(!this._configs[B]){C.name=B;this._configs[B]=this.createAttribute(C);}else{this._configs[B].configure(C,D);}},configureAttribute:function(B,C,D){this.setAttributeConfig(B,C,D);},resetAttributeConfig:function(B){this._configs=this._configs||{};this._configs[B].resetConfig();},subscribe:function(B,C){this._events=this._events||{};if(!(B in this._events)){this._events[B]=this.createEvent(B);}YAHOO.util.EventProvider.prototype.subscribe.apply(this,arguments);},on:function(){this.subscribe.apply(this,arguments);},addListener:function(){this.subscribe.apply(this,arguments);},fireBeforeChangeEvent:function(C){var B="before";B+=C.type.charAt(0).toUpperCase()+C.type.substr(1)+"Change";C.type=B;return this.fireEvent(C.type,C);},fireChangeEvent:function(B){B.type+="Change";return this.fireEvent(B.type,B);},createAttribute:function(B){return new YAHOO.util.Attribute(B,this);}};YAHOO.augment(YAHOO.util.AttributeProvider,YAHOO.util.EventProvider);})();(function(){var B=YAHOO.util.Dom,C=YAHOO.util.AttributeProvider;var A=function(D,E){this.init.apply(this,arguments);};A.DOM_EVENTS={"click":true,"dblclick":true,"keydown":true,"keypress":true,"keyup":true,"mousedown":true,"mousemove":true,"mouseout":true,"mouseover":true,"mouseup":true,"focus":true,"blur":true,"submit":true,"change":true};A.prototype={DOM_EVENTS:null,DEFAULT_HTML_SETTER:function(F,D){var E=this.get("element");if(E){E[D]=F;}},DEFAULT_HTML_GETTER:function(D){var E=this.get("element"),F;if(E){F=E[D];}return F;},appendChild:function(D){D=D.get?D.get("element"):D;return this.get("element").appendChild(D);},getElementsByTagName:function(D){return this.get("element").getElementsByTagName(D);},hasChildNodes:function(){return this.get("element").hasChildNodes();},insertBefore:function(D,E){D=D.get?D.get("element"):D;E=(E&&E.get)?E.get("element"):E;return this.get("element").insertBefore(D,E);},removeChild:function(D){D=D.get?D.get("element"):D;return this.get("element").removeChild(D);},replaceChild:function(D,E){D=D.get?D.get("element"):D;E=E.get?E.get("element"):E;return this.get("element").replaceChild(D,E);},initAttributes:function(D){},addListener:function(H,G,I,F){var E=this.get("element")||this.get("id");F=F||this;var D=this;if(!this._events[H]){if(E&&this.DOM_EVENTS[H]){YAHOO.util.Event.addListener(E,H,function(J){if(J.srcElement&&!J.target){J.target=J.srcElement;}D.fireEvent(H,J);},I,F);}this.createEvent(H,this);}return YAHOO.util.EventProvider.prototype.subscribe.apply(this,arguments);},on:function(){return this.addListener.apply(this,arguments);},subscribe:function(){return this.addListener.apply(this,arguments);},removeListener:function(E,D){return this.unsubscribe.apply(this,arguments);},addClass:function(D){B.addClass(this.get("element"),D);},getElementsByClassName:function(E,D){return B.getElementsByClassName(E,D,this.get("element"));},hasClass:function(D){return B.hasClass(this.get("element"),D);},removeClass:function(D){return B.removeClass(this.get("element"),D);},replaceClass:function(E,D){return B.replaceClass(this.get("element"),E,D);},setStyle:function(E,D){return B.setStyle(this.get("element"),E,D);},getStyle:function(D){return B.getStyle(this.get("element"),D);},fireQueue:function(){var E=this._queue;for(var F=0,D=E.length;F<D;++F){this[E[F][0]].apply(this,E[F][1]);}},appendTo:function(E,F){E=(E.get)?E.get("element"):B.get(E);this.fireEvent("beforeAppendTo",{type:"beforeAppendTo",target:E});
F=(F&&F.get)?F.get("element"):B.get(F);var D=this.get("element");if(!D){return false;}if(!E){return false;}if(D.parent!=E){if(F){E.insertBefore(D,F);}else{E.appendChild(D);}}this.fireEvent("appendTo",{type:"appendTo",target:E});return D;},get:function(D){var F=this._configs||{},E=F.element;if(E&&!F[D]&&!YAHOO.lang.isUndefined(E.value[D])){this._setHTMLAttrConfig(D);}return C.prototype.get.call(this,D);},setAttributes:function(J,G){var E={},H=this._configOrder;for(var I=0,D=H.length;I<D;++I){if(J[H[I]]!==undefined){E[H[I]]=true;this.set(H[I],J[H[I]],G);}}for(var F in J){if(J.hasOwnProperty(F)&&!E[F]){this.set(F,J[F],G);}}},set:function(E,G,D){var F=this.get("element");if(!F){this._queue[this._queue.length]=["set",arguments];if(this._configs[E]){this._configs[E].value=G;}return;}if(!this._configs[E]&&!YAHOO.lang.isUndefined(F[E])){this._setHTMLAttrConfig(E);}return C.prototype.set.apply(this,arguments);},setAttributeConfig:function(D,E,F){this._configOrder.push(D);C.prototype.setAttributeConfig.apply(this,arguments);},createEvent:function(E,D){this._events[E]=true;return C.prototype.createEvent.apply(this,arguments);},init:function(E,D){this._initElement(E,D);},destroy:function(){var D=this.get("element");YAHOO.util.Event.purgeElement(D,true);this.unsubscribeAll();if(D&&D.parentNode){D.parentNode.removeChild(D);}this._queue=[];this._events={};this._configs={};this._configOrder=[];},_initElement:function(F,E){this._queue=this._queue||[];this._events=this._events||{};this._configs=this._configs||{};this._configOrder=[];E=E||{};E.element=E.element||F||null;var H=false;var D=A.DOM_EVENTS;this.DOM_EVENTS=this.DOM_EVENTS||{};for(var G in D){if(D.hasOwnProperty(G)){this.DOM_EVENTS[G]=D[G];}}if(typeof E.element==="string"){this._setHTMLAttrConfig("id",{value:E.element});}if(B.get(E.element)){H=true;this._initHTMLElement(E);this._initContent(E);}YAHOO.util.Event.onAvailable(E.element,function(){if(!H){this._initHTMLElement(E);}this.fireEvent("available",{type:"available",target:B.get(E.element)});},this,true);YAHOO.util.Event.onContentReady(E.element,function(){if(!H){this._initContent(E);}this.fireEvent("contentReady",{type:"contentReady",target:B.get(E.element)});},this,true);},_initHTMLElement:function(D){this.setAttributeConfig("element",{value:B.get(D.element),readOnly:true});},_initContent:function(D){this.initAttributes(D);this.setAttributes(D,true);this.fireQueue();},_setHTMLAttrConfig:function(D,F){var E=this.get("element");F=F||{};F.name=D;F.setter=F.setter||this.DEFAULT_HTML_SETTER;F.getter=F.getter||this.DEFAULT_HTML_GETTER;F.value=F.value||E[D];this._configs[D]=new YAHOO.util.Attribute(F,this);}};YAHOO.augment(A,C);YAHOO.util.Element=A;})();YAHOO.register("element",YAHOO.util.Element,{version:"2.7.0",build:"1796"});/*
Copyright (c) 2009, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.7.0
*/
YAHOO.util.Color=function(){var A="0",B=YAHOO.lang.isArray,C=YAHOO.lang.isNumber;return{real2dec:function(D){return Math.min(255,Math.round(D*256));},hsv2rgb:function(H,O,M){if(B(H)){return this.hsv2rgb.call(this,H[0],H[1],H[2]);}var D,I,L,G=Math.floor((H/60)%6),J=(H/60)-G,F=M*(1-O),E=M*(1-J*O),N=M*(1-(1-J)*O),K;switch(G){case 0:D=M;I=N;L=F;break;case 1:D=E;I=M;L=F;break;case 2:D=F;I=M;L=N;break;case 3:D=F;I=E;L=M;break;case 4:D=N;I=F;L=M;break;case 5:D=M;I=F;L=E;break;}K=this.real2dec;return[K(D),K(I),K(L)];},rgb2hsv:function(D,H,I){if(B(D)){return this.rgb2hsv.apply(this,D);}D/=255;H/=255;I/=255;var G,L,E=Math.min(Math.min(D,H),I),J=Math.max(Math.max(D,H),I),K=J-E,F;switch(J){case E:G=0;break;case D:G=60*(H-I)/K;if(H<I){G+=360;}break;case H:G=(60*(I-D)/K)+120;break;case I:G=(60*(D-H)/K)+240;break;}L=(J===0)?0:1-(E/J);F=[Math.round(G),L,J];return F;},rgb2hex:function(F,E,D){if(B(F)){return this.rgb2hex.apply(this,F);}var G=this.dec2hex;return G(F)+G(E)+G(D);},dec2hex:function(D){D=parseInt(D,10)|0;D=(D>255||D<0)?0:D;return(A+D.toString(16)).slice(-2).toUpperCase();},hex2dec:function(D){return parseInt(D,16);},hex2rgb:function(D){var E=this.hex2dec;return[E(D.slice(0,2)),E(D.slice(2,4)),E(D.slice(4,6))];},websafe:function(F,E,D){if(B(F)){return this.websafe.apply(this,F);}var G=function(H){if(C(H)){H=Math.min(Math.max(0,H),255);var I,J;for(I=0;I<256;I=I+51){J=I+51;if(H>=I&&H<=J){return(H-I>25)?J:I;}}}return H;};return[G(F),G(E),G(D)];}};}();(function(){var J=0,F=YAHOO.util,C=YAHOO.lang,D=YAHOO.widget.Slider,B=F.Color,E=F.Dom,I=F.Event,A=C.substitute,H="yui-picker";function G(L,K){J=J+1;K=K||{};if(arguments.length===1&&!YAHOO.lang.isString(L)&&!L.nodeName){K=L;L=K.element||null;}if(!L&&!K.element){L=this._createHostElement(K);}G.superclass.constructor.call(this,L,K);this.initPicker();}YAHOO.extend(G,YAHOO.util.Element,{ID:{R:H+"-r",R_HEX:H+"-rhex",G:H+"-g",G_HEX:H+"-ghex",B:H+"-b",B_HEX:H+"-bhex",H:H+"-h",S:H+"-s",V:H+"-v",PICKER_BG:H+"-bg",PICKER_THUMB:H+"-thumb",HUE_BG:H+"-hue-bg",HUE_THUMB:H+"-hue-thumb",HEX:H+"-hex",SWATCH:H+"-swatch",WEBSAFE_SWATCH:H+"-websafe-swatch",CONTROLS:H+"-controls",RGB_CONTROLS:H+"-rgb-controls",HSV_CONTROLS:H+"-hsv-controls",HEX_CONTROLS:H+"-hex-controls",HEX_SUMMARY:H+"-hex-summary",CONTROLS_LABEL:H+"-controls-label"},TXT:{ILLEGAL_HEX:"Illegal hex value entered",SHOW_CONTROLS:"Show color details",HIDE_CONTROLS:"Hide color details",CURRENT_COLOR:"Currently selected color: {rgb}",CLOSEST_WEBSAFE:"Closest websafe color: {rgb}. Click to select.",R:"R",G:"G",B:"B",H:"H",S:"S",V:"V",HEX:"#",DEG:"\u00B0",PERCENT:"%"},IMAGE:{PICKER_THUMB:"../../build/colorpicker/assets/picker_thumb.png",HUE_THUMB:"../../build/colorpicker/assets/hue_thumb.png"},DEFAULT:{PICKER_SIZE:180},OPT:{HUE:"hue",SATURATION:"saturation",VALUE:"value",RED:"red",GREEN:"green",BLUE:"blue",HSV:"hsv",RGB:"rgb",WEBSAFE:"websafe",HEX:"hex",PICKER_SIZE:"pickersize",SHOW_CONTROLS:"showcontrols",SHOW_RGB_CONTROLS:"showrgbcontrols",SHOW_HSV_CONTROLS:"showhsvcontrols",SHOW_HEX_CONTROLS:"showhexcontrols",SHOW_HEX_SUMMARY:"showhexsummary",SHOW_WEBSAFE:"showwebsafe",CONTAINER:"container",IDS:"ids",ELEMENTS:"elements",TXT:"txt",IMAGES:"images",ANIMATE:"animate"},skipAnim:true,_createHostElement:function(){var K=document.createElement("div");if(this.CSS.BASE){K.className=this.CSS.BASE;}return K;},_updateHueSlider:function(){var K=this.get(this.OPT.PICKER_SIZE),L=this.get(this.OPT.HUE);L=K-Math.round(L/360*K);if(L===K){L=0;}this.hueSlider.setValue(L,this.skipAnim);},_updatePickerSlider:function(){var L=this.get(this.OPT.PICKER_SIZE),M=this.get(this.OPT.SATURATION),K=this.get(this.OPT.VALUE);M=Math.round(M*L/100);K=Math.round(L-(K*L/100));this.pickerSlider.setRegionValue(M,K,this.skipAnim);},_updateSliders:function(){this._updateHueSlider();this._updatePickerSlider();},setValue:function(L,K){K=(K)||false;this.set(this.OPT.RGB,L,K);this._updateSliders();},hueSlider:null,pickerSlider:null,_getH:function(){var K=this.get(this.OPT.PICKER_SIZE),L=(K-this.hueSlider.getValue())/K;L=Math.round(L*360);return(L===360)?0:L;},_getS:function(){return this.pickerSlider.getXValue()/this.get(this.OPT.PICKER_SIZE);},_getV:function(){var K=this.get(this.OPT.PICKER_SIZE);return(K-this.pickerSlider.getYValue())/K;},_updateSwatch:function(){var M=this.get(this.OPT.RGB),O=this.get(this.OPT.WEBSAFE),N=this.getElement(this.ID.SWATCH),L=M.join(","),K=this.get(this.OPT.TXT);E.setStyle(N,"background-color","rgb("+L+")");N.title=A(K.CURRENT_COLOR,{"rgb":"#"+this.get(this.OPT.HEX)});N=this.getElement(this.ID.WEBSAFE_SWATCH);L=O.join(",");E.setStyle(N,"background-color","rgb("+L+")");N.title=A(K.CLOSEST_WEBSAFE,{"rgb":"#"+B.rgb2hex(O)});},_getValuesFromSliders:function(){this.set(this.OPT.RGB,B.hsv2rgb(this._getH(),this._getS(),this._getV()));},_updateFormFields:function(){this.getElement(this.ID.H).value=this.get(this.OPT.HUE);this.getElement(this.ID.S).value=this.get(this.OPT.SATURATION);this.getElement(this.ID.V).value=this.get(this.OPT.VALUE);this.getElement(this.ID.R).value=this.get(this.OPT.RED);this.getElement(this.ID.R_HEX).innerHTML=B.dec2hex(this.get(this.OPT.RED));this.getElement(this.ID.G).value=this.get(this.OPT.GREEN);this.getElement(this.ID.G_HEX).innerHTML=B.dec2hex(this.get(this.OPT.GREEN));this.getElement(this.ID.B).value=this.get(this.OPT.BLUE);this.getElement(this.ID.B_HEX).innerHTML=B.dec2hex(this.get(this.OPT.BLUE));this.getElement(this.ID.HEX).value=this.get(this.OPT.HEX);},_onHueSliderChange:function(N){var L=this._getH(),K=B.hsv2rgb(L,1,1),M="rgb("+K.join(",")+")";this.set(this.OPT.HUE,L,true);E.setStyle(this.getElement(this.ID.PICKER_BG),"background-color",M);if(this.hueSlider.valueChangeSource!==D.SOURCE_SET_VALUE){this._getValuesFromSliders();}this._updateFormFields();this._updateSwatch();},_onPickerSliderChange:function(M){var L=this._getS(),K=this._getV();this.set(this.OPT.SATURATION,Math.round(L*100),true);this.set(this.OPT.VALUE,Math.round(K*100),true);if(this.pickerSlider.valueChangeSource!==D.SOURCE_SET_VALUE){this._getValuesFromSliders();
}this._updateFormFields();this._updateSwatch();},_getCommand:function(K){var L=I.getCharCode(K);if(L===38){return 3;}else{if(L===13){return 6;}else{if(L===40){return 4;}else{if(L>=48&&L<=57){return 1;}else{if(L>=97&&L<=102){return 2;}else{if(L>=65&&L<=70){return 2;}else{if("8, 9, 13, 27, 37, 39".indexOf(L)>-1||K.ctrlKey||K.metaKey){return 5;}else{return 0;}}}}}}}},_useFieldValue:function(L,K,N){var M=K.value;if(N!==this.OPT.HEX){M=parseInt(M,10);}if(M!==this.get(N)){this.set(N,M);}},_rgbFieldKeypress:function(M,K,O){var N=this._getCommand(M),L=(M.shiftKey)?10:1;switch(N){case 6:this._useFieldValue.apply(this,arguments);break;case 3:this.set(O,Math.min(this.get(O)+L,255));this._updateFormFields();break;case 4:this.set(O,Math.max(this.get(O)-L,0));this._updateFormFields();break;default:}},_hexFieldKeypress:function(L,K,N){var M=this._getCommand(L);if(M===6){this._useFieldValue.apply(this,arguments);}},_hexOnly:function(L,K){var M=this._getCommand(L);switch(M){case 6:case 5:case 1:break;case 2:if(K!==true){break;}default:I.stopEvent(L);return false;}},_numbersOnly:function(K){return this._hexOnly(K,true);},getElement:function(K){return this.get(this.OPT.ELEMENTS)[this.get(this.OPT.IDS)[K]];},_createElements:function(){var N,M,P,O,L,K=this.get(this.OPT.IDS),Q=this.get(this.OPT.TXT),S=this.get(this.OPT.IMAGES),R=function(U,V){var W=document.createElement(U);if(V){C.augmentObject(W,V,true);}return W;},T=function(U,V){var W=C.merge({autocomplete:"off",value:"0",size:3,maxlength:3},V);W.name=W.id;return new R(U,W);};L=this.get("element");N=new R("div",{id:K[this.ID.PICKER_BG],className:"yui-picker-bg",tabIndex:-1,hideFocus:true});M=new R("div",{id:K[this.ID.PICKER_THUMB],className:"yui-picker-thumb"});P=new R("img",{src:S.PICKER_THUMB});M.appendChild(P);N.appendChild(M);L.appendChild(N);N=new R("div",{id:K[this.ID.HUE_BG],className:"yui-picker-hue-bg",tabIndex:-1,hideFocus:true});M=new R("div",{id:K[this.ID.HUE_THUMB],className:"yui-picker-hue-thumb"});P=new R("img",{src:S.HUE_THUMB});M.appendChild(P);N.appendChild(M);L.appendChild(N);N=new R("div",{id:K[this.ID.CONTROLS],className:"yui-picker-controls"});L.appendChild(N);L=N;N=new R("div",{className:"hd"});M=new R("a",{id:K[this.ID.CONTROLS_LABEL],href:"#"});N.appendChild(M);L.appendChild(N);N=new R("div",{className:"bd"});L.appendChild(N);L=N;N=new R("ul",{id:K[this.ID.RGB_CONTROLS],className:"yui-picker-rgb-controls"});M=new R("li");M.appendChild(document.createTextNode(Q.R+" "));O=new T("input",{id:K[this.ID.R],className:"yui-picker-r"});M.appendChild(O);N.appendChild(M);M=new R("li");M.appendChild(document.createTextNode(Q.G+" "));O=new T("input",{id:K[this.ID.G],className:"yui-picker-g"});M.appendChild(O);N.appendChild(M);M=new R("li");M.appendChild(document.createTextNode(Q.B+" "));O=new T("input",{id:K[this.ID.B],className:"yui-picker-b"});M.appendChild(O);N.appendChild(M);L.appendChild(N);N=new R("ul",{id:K[this.ID.HSV_CONTROLS],className:"yui-picker-hsv-controls"});M=new R("li");M.appendChild(document.createTextNode(Q.H+" "));O=new T("input",{id:K[this.ID.H],className:"yui-picker-h"});M.appendChild(O);M.appendChild(document.createTextNode(" "+Q.DEG));N.appendChild(M);M=new R("li");M.appendChild(document.createTextNode(Q.S+" "));O=new T("input",{id:K[this.ID.S],className:"yui-picker-s"});M.appendChild(O);M.appendChild(document.createTextNode(" "+Q.PERCENT));N.appendChild(M);M=new R("li");M.appendChild(document.createTextNode(Q.V+" "));O=new T("input",{id:K[this.ID.V],className:"yui-picker-v"});M.appendChild(O);M.appendChild(document.createTextNode(" "+Q.PERCENT));N.appendChild(M);L.appendChild(N);N=new R("ul",{id:K[this.ID.HEX_SUMMARY],className:"yui-picker-hex_summary"});M=new R("li",{id:K[this.ID.R_HEX]});N.appendChild(M);M=new R("li",{id:K[this.ID.G_HEX]});N.appendChild(M);M=new R("li",{id:K[this.ID.B_HEX]});N.appendChild(M);L.appendChild(N);N=new R("div",{id:K[this.ID.HEX_CONTROLS],className:"yui-picker-hex-controls"});N.appendChild(document.createTextNode(Q.HEX+" "));M=new T("input",{id:K[this.ID.HEX],className:"yui-picker-hex",size:6,maxlength:6});N.appendChild(M);L.appendChild(N);L=this.get("element");N=new R("div",{id:K[this.ID.SWATCH],className:"yui-picker-swatch"});L.appendChild(N);N=new R("div",{id:K[this.ID.WEBSAFE_SWATCH],className:"yui-picker-websafe-swatch"});L.appendChild(N);},_attachRGBHSV:function(L,K){I.on(this.getElement(L),"keydown",function(N,M){M._rgbFieldKeypress(N,this,K);},this);I.on(this.getElement(L),"keypress",this._numbersOnly,this,true);I.on(this.getElement(L),"blur",function(N,M){M._useFieldValue(N,this,K);},this);},_updateRGB:function(){var K=[this.get(this.OPT.RED),this.get(this.OPT.GREEN),this.get(this.OPT.BLUE)];this.set(this.OPT.RGB,K);this._updateSliders();},_initElements:function(){var O=this.OPT,N=this.get(O.IDS),L=this.get(O.ELEMENTS),K,M,P;for(K in this.ID){if(C.hasOwnProperty(this.ID,K)){N[this.ID[K]]=N[K];}}M=E.get(N[this.ID.PICKER_BG]);if(!M){this._createElements();}else{}for(K in N){if(C.hasOwnProperty(N,K)){M=E.get(N[K]);P=E.generateId(M);N[K]=P;N[N[K]]=P;L[P]=M;}}},initPicker:function(){this._initSliders();this._bindUI();this.syncUI(true);},_initSliders:function(){var K=this.ID,L=this.get(this.OPT.PICKER_SIZE);this.hueSlider=D.getVertSlider(this.getElement(K.HUE_BG),this.getElement(K.HUE_THUMB),0,L);this.pickerSlider=D.getSliderRegion(this.getElement(K.PICKER_BG),this.getElement(K.PICKER_THUMB),0,L,0,L);this.set(this.OPT.ANIMATE,this.get(this.OPT.ANIMATE));},_bindUI:function(){var K=this.ID,L=this.OPT;this.hueSlider.subscribe("change",this._onHueSliderChange,this,true);this.pickerSlider.subscribe("change",this._onPickerSliderChange,this,true);I.on(this.getElement(K.WEBSAFE_SWATCH),"click",function(M){this.setValue(this.get(L.WEBSAFE));},this,true);I.on(this.getElement(K.CONTROLS_LABEL),"click",function(M){this.set(L.SHOW_CONTROLS,!this.get(L.SHOW_CONTROLS));I.preventDefault(M);},this,true);this._attachRGBHSV(K.R,L.RED);this._attachRGBHSV(K.G,L.GREEN);this._attachRGBHSV(K.B,L.BLUE);this._attachRGBHSV(K.H,L.HUE);
this._attachRGBHSV(K.S,L.SATURATION);this._attachRGBHSV(K.V,L.VALUE);I.on(this.getElement(K.HEX),"keydown",function(N,M){M._hexFieldKeypress(N,this,L.HEX);},this);I.on(this.getElement(this.ID.HEX),"keypress",this._hexOnly,this,true);I.on(this.getElement(this.ID.HEX),"blur",function(N,M){M._useFieldValue(N,this,L.HEX);},this);},syncUI:function(K){this.skipAnim=K;this._updateRGB();this.skipAnim=false;},_updateRGBFromHSV:function(){var L=[this.get(this.OPT.HUE),this.get(this.OPT.SATURATION)/100,this.get(this.OPT.VALUE)/100],K=B.hsv2rgb(L);this.set(this.OPT.RGB,K);this._updateSliders();},_updateHex:function(){var N=this.get(this.OPT.HEX),K=N.length,O,M,L;if(K===3){O=N.split("");for(M=0;M<K;M=M+1){O[M]=O[M]+O[M];}N=O.join("");}if(N.length!==6){return false;}L=B.hex2rgb(N);this.setValue(L);},_hideShowEl:function(M,K){var L=(C.isString(M)?this.getElement(M):M);E.setStyle(L,"display",(K)?"":"none");},initAttributes:function(K){K=K||{};G.superclass.initAttributes.call(this,K);this.setAttributeConfig(this.OPT.PICKER_SIZE,{value:K.size||this.DEFAULT.PICKER_SIZE});this.setAttributeConfig(this.OPT.HUE,{value:K.hue||0,validator:C.isNumber});this.setAttributeConfig(this.OPT.SATURATION,{value:K.saturation||0,validator:C.isNumber});this.setAttributeConfig(this.OPT.VALUE,{value:C.isNumber(K.value)?K.value:100,validator:C.isNumber});this.setAttributeConfig(this.OPT.RED,{value:C.isNumber(K.red)?K.red:255,validator:C.isNumber});this.setAttributeConfig(this.OPT.GREEN,{value:C.isNumber(K.green)?K.green:255,validator:C.isNumber});this.setAttributeConfig(this.OPT.BLUE,{value:C.isNumber(K.blue)?K.blue:255,validator:C.isNumber});this.setAttributeConfig(this.OPT.HEX,{value:K.hex||"FFFFFF",validator:C.isString});this.setAttributeConfig(this.OPT.RGB,{value:K.rgb||[255,255,255],method:function(O){this.set(this.OPT.RED,O[0],true);this.set(this.OPT.GREEN,O[1],true);this.set(this.OPT.BLUE,O[2],true);var Q=B.websafe(O),P=B.rgb2hex(O),N=B.rgb2hsv(O);this.set(this.OPT.WEBSAFE,Q,true);this.set(this.OPT.HEX,P,true);if(N[1]){this.set(this.OPT.HUE,N[0],true);}this.set(this.OPT.SATURATION,Math.round(N[1]*100),true);this.set(this.OPT.VALUE,Math.round(N[2]*100),true);},readonly:true});this.setAttributeConfig(this.OPT.CONTAINER,{value:null,method:function(N){if(N){N.showEvent.subscribe(function(){this.pickerSlider.focus();},this,true);}}});this.setAttributeConfig(this.OPT.WEBSAFE,{value:K.websafe||[255,255,255]});var M=K.ids||C.merge({},this.ID),L;if(!K.ids&&J>1){for(L in M){if(C.hasOwnProperty(M,L)){M[L]=M[L]+J;}}}this.setAttributeConfig(this.OPT.IDS,{value:M,writeonce:true});this.setAttributeConfig(this.OPT.TXT,{value:K.txt||this.TXT,writeonce:true});this.setAttributeConfig(this.OPT.IMAGES,{value:K.images||this.IMAGE,writeonce:true});this.setAttributeConfig(this.OPT.ELEMENTS,{value:{},readonly:true});this.setAttributeConfig(this.OPT.SHOW_CONTROLS,{value:C.isBoolean(K.showcontrols)?K.showcontrols:true,method:function(N){var O=E.getElementsByClassName("bd","div",this.getElement(this.ID.CONTROLS))[0];this._hideShowEl(O,N);this.getElement(this.ID.CONTROLS_LABEL).innerHTML=(N)?this.get(this.OPT.TXT).HIDE_CONTROLS:this.get(this.OPT.TXT).SHOW_CONTROLS;}});this.setAttributeConfig(this.OPT.SHOW_RGB_CONTROLS,{value:C.isBoolean(K.showrgbcontrols)?K.showrgbcontrols:true,method:function(N){this._hideShowEl(this.ID.RGB_CONTROLS,N);}});this.setAttributeConfig(this.OPT.SHOW_HSV_CONTROLS,{value:C.isBoolean(K.showhsvcontrols)?K.showhsvcontrols:false,method:function(N){this._hideShowEl(this.ID.HSV_CONTROLS,N);if(N&&this.get(this.OPT.SHOW_HEX_SUMMARY)){this.set(this.OPT.SHOW_HEX_SUMMARY,false);}}});this.setAttributeConfig(this.OPT.SHOW_HEX_CONTROLS,{value:C.isBoolean(K.showhexcontrols)?K.showhexcontrols:false,method:function(N){this._hideShowEl(this.ID.HEX_CONTROLS,N);}});this.setAttributeConfig(this.OPT.SHOW_WEBSAFE,{value:C.isBoolean(K.showwebsafe)?K.showwebsafe:true,method:function(N){this._hideShowEl(this.ID.WEBSAFE_SWATCH,N);}});this.setAttributeConfig(this.OPT.SHOW_HEX_SUMMARY,{value:C.isBoolean(K.showhexsummary)?K.showhexsummary:true,method:function(N){this._hideShowEl(this.ID.HEX_SUMMARY,N);if(N&&this.get(this.OPT.SHOW_HSV_CONTROLS)){this.set(this.OPT.SHOW_HSV_CONTROLS,false);}}});this.setAttributeConfig(this.OPT.ANIMATE,{value:C.isBoolean(K.animate)?K.animate:true,method:function(N){if(this.pickerSlider){this.pickerSlider.animate=N;this.hueSlider.animate=N;}}});this.on(this.OPT.HUE+"Change",this._updateRGBFromHSV,this,true);this.on(this.OPT.SATURATION+"Change",this._updateRGBFromHSV,this,true);this.on(this.OPT.VALUE+"Change",this._updateRGBFromHSV,this,true);this.on(this.OPT.RED+"Change",this._updateRGB,this,true);this.on(this.OPT.GREEN+"Change",this._updateRGB,this,true);this.on(this.OPT.BLUE+"Change",this._updateRGB,this,true);this.on(this.OPT.HEX+"Change",this._updateHex,this,true);this._initElements();}});YAHOO.widget.ColorPicker=G;})();YAHOO.register("colorpicker",YAHOO.widget.ColorPicker,{version:"2.7.0",build:"1796"});
/*
Copyright (c) 2009, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.7.0
*/
(function(){var B=YAHOO.util;var A=function(D,C,E,F){if(!D){}this.init(D,C,E,F);};A.NAME="Anim";A.prototype={toString:function(){var C=this.getEl()||{};var D=C.id||C.tagName;return(this.constructor.NAME+": "+D);},patterns:{noNegatives:/width|height|opacity|padding/i,offsetAttribute:/^((width|height)|(top|left))$/,defaultUnit:/width|height|top$|bottom$|left$|right$/i,offsetUnit:/\d+(em|%|en|ex|pt|in|cm|mm|pc)$/i},doMethod:function(C,E,D){return this.method(this.currentFrame,E,D-E,this.totalFrames);},setAttribute:function(C,F,E){var D=this.getEl();if(this.patterns.noNegatives.test(C)){F=(F>0)?F:0;}if("style" in D){B.Dom.setStyle(D,C,F+E);}else{if(C in D){D[C]=F;}}},getAttribute:function(C){var E=this.getEl();var G=B.Dom.getStyle(E,C);if(G!=="auto"&&!this.patterns.offsetUnit.test(G)){return parseFloat(G);}var D=this.patterns.offsetAttribute.exec(C)||[];var H=!!(D[3]);var F=!!(D[2]);if("style" in E){if(F||(B.Dom.getStyle(E,"position")=="absolute"&&H)){G=E["offset"+D[0].charAt(0).toUpperCase()+D[0].substr(1)];}else{G=0;}}else{if(C in E){G=E[C];}}return G;},getDefaultUnit:function(C){if(this.patterns.defaultUnit.test(C)){return"px";}return"";},setRuntimeAttribute:function(D){var I;var E;var F=this.attributes;this.runtimeAttributes[D]={};var H=function(J){return(typeof J!=="undefined");};if(!H(F[D]["to"])&&!H(F[D]["by"])){return false;}I=(H(F[D]["from"]))?F[D]["from"]:this.getAttribute(D);if(H(F[D]["to"])){E=F[D]["to"];}else{if(H(F[D]["by"])){if(I.constructor==Array){E=[];for(var G=0,C=I.length;G<C;++G){E[G]=I[G]+F[D]["by"][G]*1;}}else{E=I+F[D]["by"]*1;}}}this.runtimeAttributes[D].start=I;this.runtimeAttributes[D].end=E;this.runtimeAttributes[D].unit=(H(F[D].unit))?F[D]["unit"]:this.getDefaultUnit(D);return true;},init:function(E,J,I,C){var D=false;var F=null;var H=0;E=B.Dom.get(E);this.attributes=J||{};this.duration=!YAHOO.lang.isUndefined(I)?I:1;this.method=C||B.Easing.easeNone;this.useSeconds=true;this.currentFrame=0;this.totalFrames=B.AnimMgr.fps;this.setEl=function(M){E=B.Dom.get(M);};this.getEl=function(){return E;};this.isAnimated=function(){return D;};this.getStartTime=function(){return F;};this.runtimeAttributes={};this.animate=function(){if(this.isAnimated()){return false;}this.currentFrame=0;this.totalFrames=(this.useSeconds)?Math.ceil(B.AnimMgr.fps*this.duration):this.duration;if(this.duration===0&&this.useSeconds){this.totalFrames=1;}B.AnimMgr.registerElement(this);return true;};this.stop=function(M){if(!this.isAnimated()){return false;}if(M){this.currentFrame=this.totalFrames;this._onTween.fire();}B.AnimMgr.stop(this);};var L=function(){this.onStart.fire();this.runtimeAttributes={};for(var M in this.attributes){this.setRuntimeAttribute(M);}D=true;H=0;F=new Date();};var K=function(){var O={duration:new Date()-this.getStartTime(),currentFrame:this.currentFrame};O.toString=function(){return("duration: "+O.duration+", currentFrame: "+O.currentFrame);};this.onTween.fire(O);var N=this.runtimeAttributes;for(var M in N){this.setAttribute(M,this.doMethod(M,N[M].start,N[M].end),N[M].unit);}H+=1;};var G=function(){var M=(new Date()-F)/1000;var N={duration:M,frames:H,fps:H/M};N.toString=function(){return("duration: "+N.duration+", frames: "+N.frames+", fps: "+N.fps);};D=false;H=0;this.onComplete.fire(N);};this._onStart=new B.CustomEvent("_start",this,true);this.onStart=new B.CustomEvent("start",this);this.onTween=new B.CustomEvent("tween",this);this._onTween=new B.CustomEvent("_tween",this,true);this.onComplete=new B.CustomEvent("complete",this);this._onComplete=new B.CustomEvent("_complete",this,true);this._onStart.subscribe(L);this._onTween.subscribe(K);this._onComplete.subscribe(G);}};B.Anim=A;})();YAHOO.util.AnimMgr=new function(){var C=null;var B=[];var A=0;this.fps=1000;this.delay=1;this.registerElement=function(F){B[B.length]=F;A+=1;F._onStart.fire();this.start();};this.unRegister=function(G,F){F=F||E(G);if(!G.isAnimated()||F==-1){return false;}G._onComplete.fire();B.splice(F,1);A-=1;if(A<=0){this.stop();}return true;};this.start=function(){if(C===null){C=setInterval(this.run,this.delay);}};this.stop=function(H){if(!H){clearInterval(C);for(var G=0,F=B.length;G<F;++G){this.unRegister(B[0],0);}B=[];C=null;A=0;}else{this.unRegister(H);}};this.run=function(){for(var H=0,F=B.length;H<F;++H){var G=B[H];if(!G||!G.isAnimated()){continue;}if(G.currentFrame<G.totalFrames||G.totalFrames===null){G.currentFrame+=1;if(G.useSeconds){D(G);}G._onTween.fire();}else{YAHOO.util.AnimMgr.stop(G,H);}}};var E=function(H){for(var G=0,F=B.length;G<F;++G){if(B[G]==H){return G;}}return -1;};var D=function(G){var J=G.totalFrames;var I=G.currentFrame;var H=(G.currentFrame*G.duration*1000/G.totalFrames);var F=(new Date()-G.getStartTime());var K=0;if(F<G.duration*1000){K=Math.round((F/H-1)*G.currentFrame);}else{K=J-(I+1);}if(K>0&&isFinite(K)){if(G.currentFrame+K>=J){K=J-(I+1);}G.currentFrame+=K;}};};YAHOO.util.Bezier=new function(){this.getPosition=function(E,D){var F=E.length;var C=[];for(var B=0;B<F;++B){C[B]=[E[B][0],E[B][1]];}for(var A=1;A<F;++A){for(B=0;B<F-A;++B){C[B][0]=(1-D)*C[B][0]+D*C[parseInt(B+1,10)][0];C[B][1]=(1-D)*C[B][1]+D*C[parseInt(B+1,10)][1];}}return[C[0][0],C[0][1]];};};(function(){var A=function(F,E,G,H){A.superclass.constructor.call(this,F,E,G,H);};A.NAME="ColorAnim";A.DEFAULT_BGCOLOR="#fff";var C=YAHOO.util;YAHOO.extend(A,C.Anim);var D=A.superclass;var B=A.prototype;B.patterns.color=/color$/i;B.patterns.rgb=/^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i;B.patterns.hex=/^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i;B.patterns.hex3=/^#?([0-9A-F]{1})([0-9A-F]{1})([0-9A-F]{1})$/i;B.patterns.transparent=/^transparent|rgba\(0, 0, 0, 0\)$/;B.parseColor=function(E){if(E.length==3){return E;}var F=this.patterns.hex.exec(E);if(F&&F.length==4){return[parseInt(F[1],16),parseInt(F[2],16),parseInt(F[3],16)];}F=this.patterns.rgb.exec(E);if(F&&F.length==4){return[parseInt(F[1],10),parseInt(F[2],10),parseInt(F[3],10)];}F=this.patterns.hex3.exec(E);if(F&&F.length==4){return[parseInt(F[1]+F[1],16),parseInt(F[2]+F[2],16),parseInt(F[3]+F[3],16)];
}return null;};B.getAttribute=function(E){var G=this.getEl();if(this.patterns.color.test(E)){var I=YAHOO.util.Dom.getStyle(G,E);var H=this;if(this.patterns.transparent.test(I)){var F=YAHOO.util.Dom.getAncestorBy(G,function(J){return !H.patterns.transparent.test(I);});if(F){I=C.Dom.getStyle(F,E);}else{I=A.DEFAULT_BGCOLOR;}}}else{I=D.getAttribute.call(this,E);}return I;};B.doMethod=function(F,J,G){var I;if(this.patterns.color.test(F)){I=[];for(var H=0,E=J.length;H<E;++H){I[H]=D.doMethod.call(this,F,J[H],G[H]);}I="rgb("+Math.floor(I[0])+","+Math.floor(I[1])+","+Math.floor(I[2])+")";}else{I=D.doMethod.call(this,F,J,G);}return I;};B.setRuntimeAttribute=function(F){D.setRuntimeAttribute.call(this,F);if(this.patterns.color.test(F)){var H=this.attributes;var J=this.parseColor(this.runtimeAttributes[F].start);var G=this.parseColor(this.runtimeAttributes[F].end);if(typeof H[F]["to"]==="undefined"&&typeof H[F]["by"]!=="undefined"){G=this.parseColor(H[F].by);for(var I=0,E=J.length;I<E;++I){G[I]=J[I]+G[I];}}this.runtimeAttributes[F].start=J;this.runtimeAttributes[F].end=G;}};C.ColorAnim=A;})();
/*
TERMS OF USE - EASING EQUATIONS
Open source under the BSD License.
Copyright 2001 Robert Penner All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
YAHOO.util.Easing={easeNone:function(B,A,D,C){return D*B/C+A;},easeIn:function(B,A,D,C){return D*(B/=C)*B+A;},easeOut:function(B,A,D,C){return -D*(B/=C)*(B-2)+A;},easeBoth:function(B,A,D,C){if((B/=C/2)<1){return D/2*B*B+A;}return -D/2*((--B)*(B-2)-1)+A;},easeInStrong:function(B,A,D,C){return D*(B/=C)*B*B*B+A;},easeOutStrong:function(B,A,D,C){return -D*((B=B/C-1)*B*B*B-1)+A;},easeBothStrong:function(B,A,D,C){if((B/=C/2)<1){return D/2*B*B*B*B+A;}return -D/2*((B-=2)*B*B*B-2)+A;},elasticIn:function(C,A,G,F,B,E){if(C==0){return A;}if((C/=F)==1){return A+G;}if(!E){E=F*0.3;}if(!B||B<Math.abs(G)){B=G;var D=E/4;}else{var D=E/(2*Math.PI)*Math.asin(G/B);}return -(B*Math.pow(2,10*(C-=1))*Math.sin((C*F-D)*(2*Math.PI)/E))+A;},elasticOut:function(C,A,G,F,B,E){if(C==0){return A;}if((C/=F)==1){return A+G;}if(!E){E=F*0.3;}if(!B||B<Math.abs(G)){B=G;var D=E/4;}else{var D=E/(2*Math.PI)*Math.asin(G/B);}return B*Math.pow(2,-10*C)*Math.sin((C*F-D)*(2*Math.PI)/E)+G+A;},elasticBoth:function(C,A,G,F,B,E){if(C==0){return A;}if((C/=F/2)==2){return A+G;}if(!E){E=F*(0.3*1.5);}if(!B||B<Math.abs(G)){B=G;var D=E/4;}else{var D=E/(2*Math.PI)*Math.asin(G/B);}if(C<1){return -0.5*(B*Math.pow(2,10*(C-=1))*Math.sin((C*F-D)*(2*Math.PI)/E))+A;}return B*Math.pow(2,-10*(C-=1))*Math.sin((C*F-D)*(2*Math.PI)/E)*0.5+G+A;},backIn:function(B,A,E,D,C){if(typeof C=="undefined"){C=1.70158;}return E*(B/=D)*B*((C+1)*B-C)+A;},backOut:function(B,A,E,D,C){if(typeof C=="undefined"){C=1.70158;}return E*((B=B/D-1)*B*((C+1)*B+C)+1)+A;},backBoth:function(B,A,E,D,C){if(typeof C=="undefined"){C=1.70158;}if((B/=D/2)<1){return E/2*(B*B*(((C*=(1.525))+1)*B-C))+A;}return E/2*((B-=2)*B*(((C*=(1.525))+1)*B+C)+2)+A;},bounceIn:function(B,A,D,C){return D-YAHOO.util.Easing.bounceOut(C-B,0,D,C)+A;},bounceOut:function(B,A,D,C){if((B/=C)<(1/2.75)){return D*(7.5625*B*B)+A;}else{if(B<(2/2.75)){return D*(7.5625*(B-=(1.5/2.75))*B+0.75)+A;}else{if(B<(2.5/2.75)){return D*(7.5625*(B-=(2.25/2.75))*B+0.9375)+A;}}}return D*(7.5625*(B-=(2.625/2.75))*B+0.984375)+A;},bounceBoth:function(B,A,D,C){if(B<C/2){return YAHOO.util.Easing.bounceIn(B*2,0,D,C)*0.5+A;}return YAHOO.util.Easing.bounceOut(B*2-C,0,D,C)*0.5+D*0.5+A;}};(function(){var A=function(H,G,I,J){if(H){A.superclass.constructor.call(this,H,G,I,J);}};A.NAME="Motion";var E=YAHOO.util;YAHOO.extend(A,E.ColorAnim);var F=A.superclass;var C=A.prototype;C.patterns.points=/^points$/i;C.setAttribute=function(G,I,H){if(this.patterns.points.test(G)){H=H||"px";F.setAttribute.call(this,"left",I[0],H);F.setAttribute.call(this,"top",I[1],H);}else{F.setAttribute.call(this,G,I,H);}};C.getAttribute=function(G){if(this.patterns.points.test(G)){var H=[F.getAttribute.call(this,"left"),F.getAttribute.call(this,"top")];}else{H=F.getAttribute.call(this,G);}return H;};C.doMethod=function(G,K,H){var J=null;if(this.patterns.points.test(G)){var I=this.method(this.currentFrame,0,100,this.totalFrames)/100;J=E.Bezier.getPosition(this.runtimeAttributes[G],I);}else{J=F.doMethod.call(this,G,K,H);}return J;};C.setRuntimeAttribute=function(P){if(this.patterns.points.test(P)){var H=this.getEl();var J=this.attributes;var G;var L=J["points"]["control"]||[];var I;var M,O;if(L.length>0&&!(L[0] instanceof Array)){L=[L];}else{var K=[];for(M=0,O=L.length;M<O;++M){K[M]=L[M];}L=K;}if(E.Dom.getStyle(H,"position")=="static"){E.Dom.setStyle(H,"position","relative");}if(D(J["points"]["from"])){E.Dom.setXY(H,J["points"]["from"]);
}else{E.Dom.setXY(H,E.Dom.getXY(H));}G=this.getAttribute("points");if(D(J["points"]["to"])){I=B.call(this,J["points"]["to"],G);var N=E.Dom.getXY(this.getEl());for(M=0,O=L.length;M<O;++M){L[M]=B.call(this,L[M],G);}}else{if(D(J["points"]["by"])){I=[G[0]+J["points"]["by"][0],G[1]+J["points"]["by"][1]];for(M=0,O=L.length;M<O;++M){L[M]=[G[0]+L[M][0],G[1]+L[M][1]];}}}this.runtimeAttributes[P]=[G];if(L.length>0){this.runtimeAttributes[P]=this.runtimeAttributes[P].concat(L);}this.runtimeAttributes[P][this.runtimeAttributes[P].length]=I;}else{F.setRuntimeAttribute.call(this,P);}};var B=function(G,I){var H=E.Dom.getXY(this.getEl());G=[G[0]-H[0]+I[0],G[1]-H[1]+I[1]];return G;};var D=function(G){return(typeof G!=="undefined");};E.Motion=A;})();(function(){var D=function(F,E,G,H){if(F){D.superclass.constructor.call(this,F,E,G,H);}};D.NAME="Scroll";var B=YAHOO.util;YAHOO.extend(D,B.ColorAnim);var C=D.superclass;var A=D.prototype;A.doMethod=function(E,H,F){var G=null;if(E=="scroll"){G=[this.method(this.currentFrame,H[0],F[0]-H[0],this.totalFrames),this.method(this.currentFrame,H[1],F[1]-H[1],this.totalFrames)];}else{G=C.doMethod.call(this,E,H,F);}return G;};A.getAttribute=function(E){var G=null;var F=this.getEl();if(E=="scroll"){G=[F.scrollLeft,F.scrollTop];}else{G=C.getAttribute.call(this,E);}return G;};A.setAttribute=function(E,H,G){var F=this.getEl();if(E=="scroll"){F.scrollLeft=H[0];F.scrollTop=H[1];}else{C.setAttribute.call(this,E,H,G);}};B.Scroll=D;})();YAHOO.register("animation",YAHOO.util.Anim,{version:"2.7.0",build:"1799"}); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/_source/plugins/uicolor/yui/yui.js | yui.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.add( 'styles',
{
requires : [ 'selection' ],
init : function( editor )
{
// This doesn't look like correct, but it's the safest way to proper
// pass the disableReadonlyStyling configuration to the style system
// without having to change any method signature in the API. (#6103)
editor.on( 'contentDom', function()
{
editor.document.setCustomData( 'cke_includeReadonly', !editor.config.disableReadonlyStyling );
});
}
});
/**
* Registers a function to be called whenever the selection position changes in the
* editing area. The current state is passed to the function. The possible
* states are {@link CKEDITOR.TRISTATE_ON} and {@link CKEDITOR.TRISTATE_OFF}.
* @param {CKEDITOR.style} style The style to be watched.
* @param {Function} callback The function to be called.
* @example
* // Create a style object for the <b> element.
* var style = new CKEDITOR.style( { element : 'b' } );
* var editor = CKEDITOR.instances.editor1;
* editor.attachStyleStateChange( style, function( state )
* {
* if ( state == CKEDITOR.TRISTATE_ON )
* alert( 'The current state for the B element is ON' );
* else
* alert( 'The current state for the B element is OFF' );
* });
*/
CKEDITOR.editor.prototype.attachStyleStateChange = function( style, callback )
{
// Try to get the list of attached callbacks.
var styleStateChangeCallbacks = this._.styleStateChangeCallbacks;
// If it doesn't exist, it means this is the first call. So, let's create
// all the structure to manage the style checks and the callback calls.
if ( !styleStateChangeCallbacks )
{
// Create the callbacks array.
styleStateChangeCallbacks = this._.styleStateChangeCallbacks = [];
// Attach to the selectionChange event, so we can check the styles at
// that point.
this.on( 'selectionChange', function( ev )
{
// Loop throw all registered callbacks.
for ( var i = 0 ; i < styleStateChangeCallbacks.length ; i++ )
{
var callback = styleStateChangeCallbacks[ i ];
// Check the current state for the style defined for that
// callback.
var currentState = callback.style.checkActive( ev.data.path ) ? CKEDITOR.TRISTATE_ON : CKEDITOR.TRISTATE_OFF;
// Call the callback function, passing the current
// state to it.
callback.fn.call( this, currentState );
}
});
}
// Save the callback info, so it can be checked on the next occurrence of
// selectionChange.
styleStateChangeCallbacks.push( { style : style, fn : callback } );
};
CKEDITOR.STYLE_BLOCK = 1;
CKEDITOR.STYLE_INLINE = 2;
CKEDITOR.STYLE_OBJECT = 3;
(function()
{
var blockElements = { address:1,div:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,p:1,pre:1,section:1,header:1,footer:1,nav:1,article:1,aside:1,figure:1,dialog:1,hgroup:1,time:1,meter:1,menu:1,command:1,keygen:1,output:1,progress:1,details:1,datagrid:1,datalist:1 },
objectElements = { a:1,embed:1,hr:1,img:1,li:1,object:1,ol:1,table:1,td:1,tr:1,th:1,ul:1,dl:1,dt:1,dd:1,form:1,audio:1,video:1 };
var semicolonFixRegex = /\s*(?:;\s*|$)/,
varRegex = /#\((.+?)\)/g;
var notBookmark = CKEDITOR.dom.walker.bookmark( 0, 1 ),
nonWhitespaces = CKEDITOR.dom.walker.whitespaces( 1 );
CKEDITOR.style = function( styleDefinition, variablesValues )
{
if ( variablesValues )
{
styleDefinition = CKEDITOR.tools.clone( styleDefinition );
replaceVariables( styleDefinition.attributes, variablesValues );
replaceVariables( styleDefinition.styles, variablesValues );
}
var element = this.element = styleDefinition.element ?
( typeof styleDefinition.element == 'string' ? styleDefinition.element.toLowerCase() : styleDefinition.element )
: '*';
this.type =
blockElements[ element ] ?
CKEDITOR.STYLE_BLOCK
: objectElements[ element ] ?
CKEDITOR.STYLE_OBJECT
:
CKEDITOR.STYLE_INLINE;
// If the 'element' property is an object with a set of possible element, it will be applied like an object style: only to existing elements
if ( typeof this.element == 'object' )
this.type = CKEDITOR.STYLE_OBJECT;
this._ =
{
definition : styleDefinition
};
};
CKEDITOR.style.prototype =
{
apply : function( document )
{
applyStyle.call( this, document, false );
},
remove : function( document )
{
applyStyle.call( this, document, true );
},
applyToRange : function( range )
{
return ( this.applyToRange =
this.type == CKEDITOR.STYLE_INLINE ?
applyInlineStyle
: this.type == CKEDITOR.STYLE_BLOCK ?
applyBlockStyle
: this.type == CKEDITOR.STYLE_OBJECT ?
applyObjectStyle
: null ).call( this, range );
},
removeFromRange : function( range )
{
return ( this.removeFromRange =
this.type == CKEDITOR.STYLE_INLINE ?
removeInlineStyle
: this.type == CKEDITOR.STYLE_BLOCK ?
removeBlockStyle
: this.type == CKEDITOR.STYLE_OBJECT ?
removeObjectStyle
: null ).call( this, range );
},
applyToObject : function( element )
{
setupElement( element, this );
},
/**
* Get the style state inside an element path. Returns "true" if the
* element is active in the path.
*/
checkActive : function( elementPath )
{
switch ( this.type )
{
case CKEDITOR.STYLE_BLOCK :
return this.checkElementRemovable( elementPath.block || elementPath.blockLimit, true );
case CKEDITOR.STYLE_OBJECT :
case CKEDITOR.STYLE_INLINE :
var elements = elementPath.elements;
for ( var i = 0, element ; i < elements.length ; i++ )
{
element = elements[ i ];
if ( this.type == CKEDITOR.STYLE_INLINE
&& ( element == elementPath.block || element == elementPath.blockLimit ) )
continue;
if( this.type == CKEDITOR.STYLE_OBJECT )
{
var name = element.getName();
if ( !( typeof this.element == 'string' ? name == this.element : name in this.element ) )
continue;
}
if ( this.checkElementRemovable( element, true ) )
return true;
}
}
return false;
},
/**
* Whether this style can be applied at the element path.
* @param elementPath
*/
checkApplicable : function( elementPath )
{
switch ( this.type )
{
case CKEDITOR.STYLE_INLINE :
case CKEDITOR.STYLE_BLOCK :
break;
case CKEDITOR.STYLE_OBJECT :
return elementPath.lastElement.getAscendant( this.element, true );
}
return true;
},
// Checks if an element, or any of its attributes, is removable by the
// current style definition.
checkElementRemovable : function( element, fullMatch )
{
var def = this._.definition;
if ( !element || !def.ignoreReadonly && element.isReadOnly() )
return false;
var attribs,
name = element.getName();
// If the element name is the same as the style name.
if ( typeof this.element == 'string' ? name == this.element : name in this.element )
{
// If no attributes are defined in the element.
if ( !fullMatch && !element.hasAttributes() )
return true;
attribs = getAttributesForComparison( def );
if ( attribs._length )
{
for ( var attName in attribs )
{
if ( attName == '_length' )
continue;
var elementAttr = element.getAttribute( attName ) || '';
// Special treatment for 'style' attribute is required.
if ( attName == 'style' ?
compareCssText( attribs[ attName ], normalizeCssText( elementAttr, false ) )
: attribs[ attName ] == elementAttr )
{
if ( !fullMatch )
return true;
}
else if ( fullMatch )
return false;
}
if ( fullMatch )
return true;
}
else
return true;
}
// Check if the element can be somehow overriden.
var override = getOverrides( this )[ element.getName() ] ;
if ( override )
{
// If no attributes have been defined, remove the element.
if ( !( attribs = override.attributes ) )
return true;
for ( var i = 0 ; i < attribs.length ; i++ )
{
attName = attribs[i][0];
var actualAttrValue = element.getAttribute( attName );
if ( actualAttrValue )
{
var attValue = attribs[i][1];
// Remove the attribute if:
// - The override definition value is null;
// - The override definition value is a string that
// matches the attribute value exactly.
// - The override definition value is a regex that
// has matches in the attribute value.
if ( attValue === null ||
( typeof attValue == 'string' && actualAttrValue == attValue ) ||
attValue.test( actualAttrValue ) )
return true;
}
}
}
return false;
},
// Builds the preview HTML based on the styles definition.
buildPreview : function( label )
{
var styleDefinition = this._.definition,
html = [],
elementName = styleDefinition.element;
// Avoid <bdo> in the preview.
if ( elementName == 'bdo' )
elementName = 'span';
html = [ '<', elementName ];
// Assign all defined attributes.
var attribs = styleDefinition.attributes;
if ( attribs )
{
for ( var att in attribs )
{
html.push( ' ', att, '="', attribs[ att ], '"' );
}
}
// Assign the style attribute.
var cssStyle = CKEDITOR.style.getStyleText( styleDefinition );
if ( cssStyle )
html.push( ' style="', cssStyle, '"' );
html.push( '>', ( label || styleDefinition.name ), '</', elementName, '>' );
return html.join( '' );
}
};
// Build the cssText based on the styles definition.
CKEDITOR.style.getStyleText = function( styleDefinition )
{
// If we have already computed it, just return it.
var stylesDef = styleDefinition._ST;
if ( stylesDef )
return stylesDef;
stylesDef = styleDefinition.styles;
// Builds the StyleText.
var stylesText = ( styleDefinition.attributes && styleDefinition.attributes[ 'style' ] ) || '',
specialStylesText = '';
if ( stylesText.length )
stylesText = stylesText.replace( semicolonFixRegex, ';' );
for ( var style in stylesDef )
{
var styleVal = stylesDef[ style ],
text = ( style + ':' + styleVal ).replace( semicolonFixRegex, ';' );
// Some browsers don't support 'inherit' property value, leave them intact. (#5242)
if ( styleVal == 'inherit' )
specialStylesText += text;
else
stylesText += text;
}
// Browsers make some changes to the style when applying them. So, here
// we normalize it to the browser format.
if ( stylesText.length )
stylesText = normalizeCssText( stylesText );
stylesText += specialStylesText;
// Return it, saving it to the next request.
return ( styleDefinition._ST = stylesText );
};
// Gets the parent element which blocks the styling for an element. This
// can be done through read-only elements (contenteditable=false) or
// elements with the "data-nostyle" attribute.
function getUnstylableParent( element )
{
var unstylable,
editable;
while ( ( element = element.getParent() ) )
{
if ( element.getName() == 'body' )
break;
if ( element.getAttribute( 'data-nostyle' ) )
unstylable = element;
else if ( !editable )
{
var contentEditable = element.getAttribute( 'contentEditable' );
if ( contentEditable == 'false' )
unstylable = element;
else if ( contentEditable == 'true' )
editable = 1;
}
}
return unstylable;
}
function applyInlineStyle( range )
{
var document = range.document;
if ( range.collapsed )
{
// Create the element to be inserted in the DOM.
var collapsedElement = getElement( this, document );
// Insert the empty element into the DOM at the range position.
range.insertNode( collapsedElement );
// Place the selection right inside the empty element.
range.moveToPosition( collapsedElement, CKEDITOR.POSITION_BEFORE_END );
return;
}
var elementName = this.element;
var def = this._.definition;
var isUnknownElement;
// Indicates that fully selected read-only elements are to be included in the styling range.
var ignoreReadonly = def.ignoreReadonly,
includeReadonly = ignoreReadonly || def.includeReadonly;
// If the read-only inclusion is not available in the definition, try
// to get it from the document data.
if ( includeReadonly == undefined )
includeReadonly = document.getCustomData( 'cke_includeReadonly' );
// Get the DTD definition for the element. Defaults to "span".
var dtd = CKEDITOR.dtd[ elementName ] || ( isUnknownElement = true, CKEDITOR.dtd.span );
// Expand the range.
range.enlarge( CKEDITOR.ENLARGE_ELEMENT, 1 );
range.trim();
// Get the first node to be processed and the last, which concludes the
// processing.
var boundaryNodes = range.createBookmark(),
firstNode = boundaryNodes.startNode,
lastNode = boundaryNodes.endNode;
var currentNode = firstNode;
var styleRange;
if ( !ignoreReadonly )
{
// Check if the boundaries are inside non stylable elements.
var firstUnstylable = getUnstylableParent( firstNode ),
lastUnstylable = getUnstylableParent( lastNode );
// If the first element can't be styled, we'll start processing right
// after its unstylable root.
if ( firstUnstylable )
currentNode = firstUnstylable.getNextSourceNode( true );
// If the last element can't be styled, we'll stop processing on its
// unstylable root.
if ( lastUnstylable )
lastNode = lastUnstylable;
}
// Do nothing if the current node now follows the last node to be processed.
if ( currentNode.getPosition( lastNode ) == CKEDITOR.POSITION_FOLLOWING )
currentNode = 0;
while ( currentNode )
{
var applyStyle = false;
if ( currentNode.equals( lastNode ) )
{
currentNode = null;
applyStyle = true;
}
else
{
var nodeType = currentNode.type;
var nodeName = nodeType == CKEDITOR.NODE_ELEMENT ? currentNode.getName() : null;
var nodeIsReadonly = nodeName && ( currentNode.getAttribute( 'contentEditable' ) == 'false' );
var nodeIsNoStyle = nodeName && currentNode.getAttribute( 'data-nostyle' );
if ( nodeName && currentNode.data( 'cke-bookmark' ) )
{
currentNode = currentNode.getNextSourceNode( true );
continue;
}
// Check if the current node can be a child of the style element.
if ( !nodeName || ( dtd[ nodeName ]
&& !nodeIsNoStyle
&& ( !nodeIsReadonly || includeReadonly )
&& ( currentNode.getPosition( lastNode ) | CKEDITOR.POSITION_PRECEDING | CKEDITOR.POSITION_IDENTICAL | CKEDITOR.POSITION_IS_CONTAINED ) == ( CKEDITOR.POSITION_PRECEDING + CKEDITOR.POSITION_IDENTICAL + CKEDITOR.POSITION_IS_CONTAINED )
&& ( !def.childRule || def.childRule( currentNode ) ) ) )
{
var currentParent = currentNode.getParent();
// Check if the style element can be a child of the current
// node parent or if the element is not defined in the DTD.
if ( currentParent
&& ( ( currentParent.getDtd() || CKEDITOR.dtd.span )[ elementName ] || isUnknownElement )
&& ( !def.parentRule || def.parentRule( currentParent ) ) )
{
// This node will be part of our range, so if it has not
// been started, place its start right before the node.
// In the case of an element node, it will be included
// only if it is entirely inside the range.
if ( !styleRange && ( !nodeName || !CKEDITOR.dtd.$removeEmpty[ nodeName ] || ( currentNode.getPosition( lastNode ) | CKEDITOR.POSITION_PRECEDING | CKEDITOR.POSITION_IDENTICAL | CKEDITOR.POSITION_IS_CONTAINED ) == ( CKEDITOR.POSITION_PRECEDING + CKEDITOR.POSITION_IDENTICAL + CKEDITOR.POSITION_IS_CONTAINED ) ) )
{
styleRange = new CKEDITOR.dom.range( document );
styleRange.setStartBefore( currentNode );
}
// Non element nodes, readonly elements, or empty
// elements can be added completely to the range.
if ( nodeType == CKEDITOR.NODE_TEXT || nodeIsReadonly || ( nodeType == CKEDITOR.NODE_ELEMENT && !currentNode.getChildCount() ) )
{
var includedNode = currentNode;
var parentNode;
// This node is about to be included completelly, but,
// if this is the last node in its parent, we must also
// check if the parent itself can be added completelly
// to the range, otherwise apply the style immediately.
while ( ( applyStyle = !includedNode.getNext( notBookmark ) )
&& ( parentNode = includedNode.getParent(), dtd[ parentNode.getName() ] )
&& ( parentNode.getPosition( firstNode ) | CKEDITOR.POSITION_FOLLOWING | CKEDITOR.POSITION_IDENTICAL | CKEDITOR.POSITION_IS_CONTAINED ) == ( CKEDITOR.POSITION_FOLLOWING + CKEDITOR.POSITION_IDENTICAL + CKEDITOR.POSITION_IS_CONTAINED )
&& ( !def.childRule || def.childRule( parentNode ) ) )
{
includedNode = parentNode;
}
styleRange.setEndAfter( includedNode );
}
}
else
applyStyle = true;
}
else
applyStyle = true;
// Get the next node to be processed.
currentNode = currentNode.getNextSourceNode( nodeIsNoStyle || nodeIsReadonly );
}
// Apply the style if we have something to which apply it.
if ( applyStyle && styleRange && !styleRange.collapsed )
{
// Build the style element, based on the style object definition.
var styleNode = getElement( this, document ),
styleHasAttrs = styleNode.hasAttributes();
// Get the element that holds the entire range.
var parent = styleRange.getCommonAncestor();
var removeList = {
styles : {},
attrs : {},
// Styles cannot be removed.
blockedStyles : {},
// Attrs cannot be removed.
blockedAttrs : {}
};
var attName, styleName, value;
// Loop through the parents, removing the redundant attributes
// from the element to be applied.
while ( styleNode && parent )
{
if ( parent.getName() == elementName )
{
for ( attName in def.attributes )
{
if ( removeList.blockedAttrs[ attName ] || !( value = parent.getAttribute( styleName ) ) )
continue;
if ( styleNode.getAttribute( attName ) == value )
removeList.attrs[ attName ] = 1;
else
removeList.blockedAttrs[ attName ] = 1;
}
for ( styleName in def.styles )
{
if ( removeList.blockedStyles[ styleName ] || !( value = parent.getStyle( styleName ) ) )
continue;
if ( styleNode.getStyle( styleName ) == value )
removeList.styles[ styleName ] = 1;
else
removeList.blockedStyles[ styleName ] = 1;
}
}
parent = parent.getParent();
}
for ( attName in removeList.attrs )
styleNode.removeAttribute( attName );
for ( styleName in removeList.styles )
styleNode.removeStyle( styleName );
if ( styleHasAttrs && !styleNode.hasAttributes() )
styleNode = null;
if ( styleNode )
{
// Move the contents of the range to the style element.
styleRange.extractContents().appendTo( styleNode );
// Here we do some cleanup, removing all duplicated
// elements from the style element.
removeFromInsideElement( this, styleNode );
// Insert it into the range position (it is collapsed after
// extractContents.
styleRange.insertNode( styleNode );
// Let's merge our new style with its neighbors, if possible.
styleNode.mergeSiblings();
// As the style system breaks text nodes constantly, let's normalize
// things for performance.
// With IE, some paragraphs get broken when calling normalize()
// repeatedly. Also, for IE, we must normalize body, not documentElement.
// IE is also known for having a "crash effect" with normalize().
// We should try to normalize with IE too in some way, somewhere.
if ( !CKEDITOR.env.ie )
styleNode.$.normalize();
}
// Style already inherit from parents, left just to clear up any internal overrides. (#5931)
else
{
styleNode = new CKEDITOR.dom.element( 'span' );
styleRange.extractContents().appendTo( styleNode );
styleRange.insertNode( styleNode );
removeFromInsideElement( this, styleNode );
styleNode.remove( true );
}
// Style applied, let's release the range, so it gets
// re-initialization in the next loop.
styleRange = null;
}
}
// Remove the bookmark nodes.
range.moveToBookmark( boundaryNodes );
// Minimize the result range to exclude empty text nodes. (#5374)
range.shrink( CKEDITOR.SHRINK_TEXT );
}
function removeInlineStyle( range )
{
/*
* Make sure our range has included all "collpased" parent inline nodes so
* that our operation logic can be simpler.
*/
range.enlarge( CKEDITOR.ENLARGE_ELEMENT, 1 );
var bookmark = range.createBookmark(),
startNode = bookmark.startNode;
if ( range.collapsed )
{
var startPath = new CKEDITOR.dom.elementPath( startNode.getParent() ),
// The topmost element in elementspatch which we should jump out of.
boundaryElement;
for ( var i = 0, element ; i < startPath.elements.length
&& ( element = startPath.elements[i] ) ; i++ )
{
/*
* 1. If it's collaped inside text nodes, try to remove the style from the whole element.
*
* 2. Otherwise if it's collapsed on element boundaries, moving the selection
* outside the styles instead of removing the whole tag,
* also make sure other inner styles were well preserverd.(#3309)
*/
if ( element == startPath.block || element == startPath.blockLimit )
break;
if ( this.checkElementRemovable( element ) )
{
var isStart;
if ( range.collapsed && (
range.checkBoundaryOfElement( element, CKEDITOR.END ) ||
( isStart = range.checkBoundaryOfElement( element, CKEDITOR.START ) ) ) )
{
boundaryElement = element;
boundaryElement.match = isStart ? 'start' : 'end';
}
else
{
/*
* Before removing the style node, there may be a sibling to the style node
* that's exactly the same to the one to be removed. To the user, it makes
* no difference that they're separate entities in the DOM tree. So, merge
* them before removal.
*/
element.mergeSiblings();
if ( element.getName() == this.element )
removeFromElement( this, element );
else
removeOverrides( element, getOverrides( this )[ element.getName() ] );
}
}
}
// Re-create the style tree after/before the boundary element,
// the replication start from bookmark start node to define the
// new range.
if ( boundaryElement )
{
var clonedElement = startNode;
for ( i = 0 ;; i++ )
{
var newElement = startPath.elements[ i ];
if ( newElement.equals( boundaryElement ) )
break;
// Avoid copying any matched element.
else if ( newElement.match )
continue;
else
newElement = newElement.clone();
newElement.append( clonedElement );
clonedElement = newElement;
}
clonedElement[ boundaryElement.match == 'start' ?
'insertBefore' : 'insertAfter' ]( boundaryElement );
}
}
else
{
/*
* Now our range isn't collapsed. Lets walk from the start node to the end
* node via DFS and remove the styles one-by-one.
*/
var endNode = bookmark.endNode,
me = this;
/*
* Find out the style ancestor that needs to be broken down at startNode
* and endNode.
*/
function breakNodes()
{
var startPath = new CKEDITOR.dom.elementPath( startNode.getParent() ),
endPath = new CKEDITOR.dom.elementPath( endNode.getParent() ),
breakStart = null,
breakEnd = null;
for ( var i = 0 ; i < startPath.elements.length ; i++ )
{
var element = startPath.elements[ i ];
if ( element == startPath.block || element == startPath.blockLimit )
break;
if ( me.checkElementRemovable( element ) )
breakStart = element;
}
for ( i = 0 ; i < endPath.elements.length ; i++ )
{
element = endPath.elements[ i ];
if ( element == endPath.block || element == endPath.blockLimit )
break;
if ( me.checkElementRemovable( element ) )
breakEnd = element;
}
if ( breakEnd )
endNode.breakParent( breakEnd );
if ( breakStart )
startNode.breakParent( breakStart );
}
breakNodes();
// Now, do the DFS walk.
var currentNode = startNode;
while ( !currentNode.equals( endNode ) )
{
/*
* Need to get the next node first because removeFromElement() can remove
* the current node from DOM tree.
*/
var nextNode = currentNode.getNextSourceNode();
if ( currentNode.type == CKEDITOR.NODE_ELEMENT && this.checkElementRemovable( currentNode ) )
{
// Remove style from element or overriding element.
if ( currentNode.getName() == this.element )
removeFromElement( this, currentNode );
else
removeOverrides( currentNode, getOverrides( this )[ currentNode.getName() ] );
/*
* removeFromElement() may have merged the next node with something before
* the startNode via mergeSiblings(). In that case, the nextNode would
* contain startNode and we'll have to call breakNodes() again and also
* reassign the nextNode to something after startNode.
*/
if ( nextNode.type == CKEDITOR.NODE_ELEMENT && nextNode.contains( startNode ) )
{
breakNodes();
nextNode = startNode.getNext();
}
}
currentNode = nextNode;
}
}
range.moveToBookmark( bookmark );
}
function applyObjectStyle( range )
{
var root = range.getCommonAncestor( true, true ),
element = root.getAscendant( this.element, true );
element && !element.isReadOnly() && setupElement( element, this );
}
function removeObjectStyle( range )
{
var root = range.getCommonAncestor( true, true ),
element = root.getAscendant( this.element, true );
if ( !element )
return;
var style = this,
def = style._.definition,
attributes = def.attributes;
// Remove all defined attributes.
if ( attributes )
{
for ( var att in attributes )
{
element.removeAttribute( att, attributes[ att ] );
}
}
// Assign all defined styles.
if ( def.styles )
{
for ( var i in def.styles )
{
if ( !def.styles.hasOwnProperty( i ) )
continue;
element.removeStyle( i );
}
}
}
function applyBlockStyle( range )
{
// Serializible bookmarks is needed here since
// elements may be merged.
var bookmark = range.createBookmark( true );
var iterator = range.createIterator();
iterator.enforceRealBlocks = true;
// make recognize <br /> tag as a separator in ENTER_BR mode (#5121)
if ( this._.enterMode )
iterator.enlargeBr = ( this._.enterMode != CKEDITOR.ENTER_BR );
var block;
var doc = range.document;
var previousPreBlock;
while ( ( block = iterator.getNextParagraph() ) ) // Only one =
{
if ( !block.isReadOnly() )
{
var newBlock = getElement( this, doc, block );
replaceBlock( block, newBlock );
}
}
range.moveToBookmark( bookmark );
}
function removeBlockStyle( range )
{
// Serializible bookmarks is needed here since
// elements may be merged.
var bookmark = range.createBookmark( 1 );
var iterator = range.createIterator();
iterator.enforceRealBlocks = true;
iterator.enlargeBr = this._.enterMode != CKEDITOR.ENTER_BR;
var block;
while ( ( block = iterator.getNextParagraph() ) )
{
if ( this.checkElementRemovable( block ) )
{
// <pre> get special treatment.
if ( block.is( 'pre' ) )
{
var newBlock = this._.enterMode == CKEDITOR.ENTER_BR ?
null : range.document.createElement(
this._.enterMode == CKEDITOR.ENTER_P ? 'p' : 'div' );
newBlock && block.copyAttributes( newBlock );
replaceBlock( block, newBlock );
}
else
removeFromElement( this, block, 1 );
}
}
range.moveToBookmark( bookmark );
}
// Replace the original block with new one, with special treatment
// for <pre> blocks to make sure content format is well preserved, and merging/splitting adjacent
// when necessary.(#3188)
function replaceBlock( block, newBlock )
{
// Block is to be removed, create a temp element to
// save contents.
var removeBlock = !newBlock;
if ( removeBlock )
{
newBlock = block.getDocument().createElement( 'div' );
block.copyAttributes( newBlock );
}
var newBlockIsPre = newBlock && newBlock.is( 'pre' );
var blockIsPre = block.is( 'pre' );
var isToPre = newBlockIsPre && !blockIsPre;
var isFromPre = !newBlockIsPre && blockIsPre;
if ( isToPre )
newBlock = toPre( block, newBlock );
else if ( isFromPre )
// Split big <pre> into pieces before start to convert.
newBlock = fromPres( removeBlock ?
[ block.getHtml() ] : splitIntoPres( block ), newBlock );
else
block.moveChildren( newBlock );
newBlock.replace( block );
if ( newBlockIsPre )
{
// Merge previous <pre> blocks.
mergePre( newBlock );
}
else if ( removeBlock )
removeNoAttribsElement( newBlock );
}
/**
* Merge a <pre> block with a previous sibling if available.
*/
function mergePre( preBlock )
{
var previousBlock;
if ( !( ( previousBlock = preBlock.getPrevious( nonWhitespaces ) )
&& previousBlock.is
&& previousBlock.is( 'pre') ) )
return;
// Merge the previous <pre> block contents into the current <pre>
// block.
//
// Another thing to be careful here is that currentBlock might contain
// a '\n' at the beginning, and previousBlock might contain a '\n'
// towards the end. These new lines are not normally displayed but they
// become visible after merging.
var mergedHtml = replace( previousBlock.getHtml(), /\n$/, '' ) + '\n\n' +
replace( preBlock.getHtml(), /^\n/, '' ) ;
// Krugle: IE normalizes innerHTML from <pre>, breaking whitespaces.
if ( CKEDITOR.env.ie )
preBlock.$.outerHTML = '<pre>' + mergedHtml + '</pre>';
else
preBlock.setHtml( mergedHtml );
previousBlock.remove();
}
/**
* Split into multiple <pre> blocks separated by double line-break.
* @param preBlock
*/
function splitIntoPres( preBlock )
{
// Exclude the ones at header OR at tail,
// and ignore bookmark content between them.
var duoBrRegex = /(\S\s*)\n(?:\s|(<span[^>]+data-cke-bookmark.*?\/span>))*\n(?!$)/gi,
blockName = preBlock.getName(),
splitedHtml = replace( preBlock.getOuterHtml(),
duoBrRegex,
function( match, charBefore, bookmark )
{
return charBefore + '</pre>' + bookmark + '<pre>';
} );
var pres = [];
splitedHtml.replace( /<pre\b.*?>([\s\S]*?)<\/pre>/gi, function( match, preContent ){
pres.push( preContent );
} );
return pres;
}
// Wrapper function of String::replace without considering of head/tail bookmarks nodes.
function replace( str, regexp, replacement )
{
var headBookmark = '',
tailBookmark = '';
str = str.replace( /(^<span[^>]+data-cke-bookmark.*?\/span>)|(<span[^>]+data-cke-bookmark.*?\/span>$)/gi,
function( str, m1, m2 ){
m1 && ( headBookmark = m1 );
m2 && ( tailBookmark = m2 );
return '';
} );
return headBookmark + str.replace( regexp, replacement ) + tailBookmark;
}
/**
* Converting a list of <pre> into blocks with format well preserved.
*/
function fromPres( preHtmls, newBlock )
{
var docFrag;
if ( preHtmls.length > 1 )
docFrag = new CKEDITOR.dom.documentFragment( newBlock.getDocument() );
for ( var i = 0 ; i < preHtmls.length ; i++ )
{
var blockHtml = preHtmls[ i ];
// 1. Trim the first and last line-breaks immediately after and before <pre>,
// they're not visible.
blockHtml = blockHtml.replace( /(\r\n|\r)/g, '\n' ) ;
blockHtml = replace( blockHtml, /^[ \t]*\n/, '' ) ;
blockHtml = replace( blockHtml, /\n$/, '' ) ;
// 2. Convert spaces or tabs at the beginning or at the end to
blockHtml = replace( blockHtml, /^[ \t]+|[ \t]+$/g, function( match, offset, s )
{
if ( match.length == 1 ) // one space, preserve it
return ' ' ;
else if ( !offset ) // beginning of block
return CKEDITOR.tools.repeat( ' ', match.length - 1 ) + ' ';
else // end of block
return ' ' + CKEDITOR.tools.repeat( ' ', match.length - 1 );
} ) ;
// 3. Convert \n to <BR>.
// 4. Convert contiguous (i.e. non-singular) spaces or tabs to
blockHtml = blockHtml.replace( /\n/g, '<br>' ) ;
blockHtml = blockHtml.replace( /[ \t]{2,}/g,
function ( match )
{
return CKEDITOR.tools.repeat( ' ', match.length - 1 ) + ' ' ;
} ) ;
if ( docFrag )
{
var newBlockClone = newBlock.clone();
newBlockClone.setHtml( blockHtml );
docFrag.append( newBlockClone );
}
else
newBlock.setHtml( blockHtml );
}
return docFrag || newBlock;
}
/**
* Converting from a non-PRE block to a PRE block in formatting operations.
*/
function toPre( block, newBlock )
{
var bogus = block.getBogus();
bogus && bogus.remove();
// First trim the block content.
var preHtml = block.getHtml();
// 1. Trim head/tail spaces, they're not visible.
preHtml = replace( preHtml, /(?:^[ \t\n\r]+)|(?:[ \t\n\r]+$)/g, '' );
// 2. Delete ANSI whitespaces immediately before and after <BR> because
// they are not visible.
preHtml = preHtml.replace( /[ \t\r\n]*(<br[^>]*>)[ \t\r\n]*/gi, '$1' );
// 3. Compress other ANSI whitespaces since they're only visible as one
// single space previously.
// 4. Convert to spaces since is no longer needed in <PRE>.
preHtml = preHtml.replace( /([ \t\n\r]+| )/g, ' ' );
// 5. Convert any <BR /> to \n. This must not be done earlier because
// the \n would then get compressed.
preHtml = preHtml.replace( /<br\b[^>]*>/gi, '\n' );
// Krugle: IE normalizes innerHTML to <pre>, breaking whitespaces.
if ( CKEDITOR.env.ie )
{
var temp = block.getDocument().createElement( 'div' );
temp.append( newBlock );
newBlock.$.outerHTML = '<pre>' + preHtml + '</pre>';
newBlock.copyAttributes( temp.getFirst() );
newBlock = temp.getFirst().remove();
}
else
newBlock.setHtml( preHtml );
return newBlock;
}
// Removes a style from an element itself, don't care about its subtree.
function removeFromElement( style, element )
{
var def = style._.definition,
attributes = CKEDITOR.tools.extend( {}, def.attributes, getOverrides( style )[ element.getName() ] ),
styles = def.styles,
// If the style is only about the element itself, we have to remove the element.
removeEmpty = CKEDITOR.tools.isEmpty( attributes ) && CKEDITOR.tools.isEmpty( styles );
// Remove definition attributes/style from the elemnt.
for ( var attName in attributes )
{
// The 'class' element value must match (#1318).
if ( ( attName == 'class' || style._.definition.fullMatch )
&& element.getAttribute( attName ) != normalizeProperty( attName, attributes[ attName ] ) )
continue;
removeEmpty = element.hasAttribute( attName );
element.removeAttribute( attName );
}
for ( var styleName in styles )
{
// Full match style insist on having fully equivalence. (#5018)
if ( style._.definition.fullMatch
&& element.getStyle( styleName ) != normalizeProperty( styleName, styles[ styleName ], true ) )
continue;
removeEmpty = removeEmpty || !!element.getStyle( styleName );
element.removeStyle( styleName );
}
if ( removeEmpty )
{
!CKEDITOR.dtd.$block[ element.getName() ] || style._.enterMode == CKEDITOR.ENTER_BR && !element.hasAttributes() ?
removeNoAttribsElement( element ) :
element.renameNode( style._.enterMode == CKEDITOR.ENTER_P ? 'p' : 'div' );
}
}
// Removes a style from inside an element.
function removeFromInsideElement( style, element )
{
var def = style._.definition,
attribs = def.attributes,
styles = def.styles,
overrides = getOverrides( style ),
innerElements = element.getElementsByTag( style.element );
for ( var i = innerElements.count(); --i >= 0 ; )
removeFromElement( style, innerElements.getItem( i ) );
// Now remove any other element with different name that is
// defined to be overriden.
for ( var overrideElement in overrides )
{
if ( overrideElement != style.element )
{
innerElements = element.getElementsByTag( overrideElement ) ;
for ( i = innerElements.count() - 1 ; i >= 0 ; i-- )
{
var innerElement = innerElements.getItem( i );
removeOverrides( innerElement, overrides[ overrideElement ] ) ;
}
}
}
}
/**
* Remove overriding styles/attributes from the specific element.
* Note: Remove the element if no attributes remain.
* @param {Object} element
* @param {Object} overrides
*/
function removeOverrides( element, overrides )
{
var attributes = overrides && overrides.attributes ;
if ( attributes )
{
for ( var i = 0 ; i < attributes.length ; i++ )
{
var attName = attributes[i][0], actualAttrValue ;
if ( ( actualAttrValue = element.getAttribute( attName ) ) )
{
var attValue = attributes[i][1] ;
// Remove the attribute if:
// - The override definition value is null ;
// - The override definition valie is a string that
// matches the attribute value exactly.
// - The override definition value is a regex that
// has matches in the attribute value.
if ( attValue === null ||
( attValue.test && attValue.test( actualAttrValue ) ) ||
( typeof attValue == 'string' && actualAttrValue == attValue ) )
element.removeAttribute( attName ) ;
}
}
}
removeNoAttribsElement( element );
}
// If the element has no more attributes, remove it.
function removeNoAttribsElement( element )
{
// If no more attributes remained in the element, remove it,
// leaving its children.
if ( !element.hasAttributes() )
{
if ( CKEDITOR.dtd.$block[ element.getName() ] )
{
var previous = element.getPrevious( nonWhitespaces ),
next = element.getNext( nonWhitespaces );
if ( previous && ( previous.type == CKEDITOR.NODE_TEXT || !previous.isBlockBoundary( { br : 1 } ) ) )
element.append( 'br', 1 );
if ( next && ( next.type == CKEDITOR.NODE_TEXT || !next.isBlockBoundary( { br : 1 } ) ) )
element.append( 'br' );
element.remove( true );
}
else
{
// Removing elements may open points where merging is possible,
// so let's cache the first and last nodes for later checking.
var firstChild = element.getFirst();
var lastChild = element.getLast();
element.remove( true );
if ( firstChild )
{
// Check the cached nodes for merging.
firstChild.type == CKEDITOR.NODE_ELEMENT && firstChild.mergeSiblings();
if ( lastChild && !firstChild.equals( lastChild )
&& lastChild.type == CKEDITOR.NODE_ELEMENT )
lastChild.mergeSiblings();
}
}
}
}
function getElement( style, targetDocument, element )
{
var el,
def = style._.definition,
elementName = style.element;
// The "*" element name will always be a span for this function.
if ( elementName == '*' )
elementName = 'span';
// Create the element.
el = new CKEDITOR.dom.element( elementName, targetDocument );
// #6226: attributes should be copied before the new ones are applied
if ( element )
element.copyAttributes( el );
el = setupElement( el, style );
// Avoid ID duplication.
if ( targetDocument.getCustomData( 'doc_processing_style' ) && el.hasAttribute( 'id' ) )
el.removeAttribute( 'id' );
else
targetDocument.setCustomData( 'doc_processing_style', 1 );
return el;
}
function setupElement( el, style )
{
var def = style._.definition,
attributes = def.attributes,
styles = CKEDITOR.style.getStyleText( def );
// Assign all defined attributes.
if ( attributes )
{
for ( var att in attributes )
{
el.setAttribute( att, attributes[ att ] );
}
}
// Assign all defined styles.
if( styles )
el.setAttribute( 'style', styles );
return el;
}
function replaceVariables( list, variablesValues )
{
for ( var item in list )
{
list[ item ] = list[ item ].replace( varRegex, function( match, varName )
{
return variablesValues[ varName ];
});
}
}
// Returns an object that can be used for style matching comparison.
// Attributes names and values are all lowercased, and the styles get
// merged with the style attribute.
function getAttributesForComparison( styleDefinition )
{
// If we have already computed it, just return it.
var attribs = styleDefinition._AC;
if ( attribs )
return attribs;
attribs = {};
var length = 0;
// Loop through all defined attributes.
var styleAttribs = styleDefinition.attributes;
if ( styleAttribs )
{
for ( var styleAtt in styleAttribs )
{
length++;
attribs[ styleAtt ] = styleAttribs[ styleAtt ];
}
}
// Includes the style definitions.
var styleText = CKEDITOR.style.getStyleText( styleDefinition );
if ( styleText )
{
if ( !attribs[ 'style' ] )
length++;
attribs[ 'style' ] = styleText;
}
// Appends the "length" information to the object.
attribs._length = length;
// Return it, saving it to the next request.
return ( styleDefinition._AC = attribs );
}
/**
* Get the the collection used to compare the elements and attributes,
* defined in this style overrides, with other element. All information in
* it is lowercased.
* @param {CKEDITOR.style} style
*/
function getOverrides( style )
{
if ( style._.overrides )
return style._.overrides;
var overrides = ( style._.overrides = {} ),
definition = style._.definition.overrides;
if ( definition )
{
// The override description can be a string, object or array.
// Internally, well handle arrays only, so transform it if needed.
if ( !CKEDITOR.tools.isArray( definition ) )
definition = [ definition ];
// Loop through all override definitions.
for ( var i = 0 ; i < definition.length ; i++ )
{
var override = definition[i];
var elementName;
var overrideEl;
var attrs;
// If can be a string with the element name.
if ( typeof override == 'string' )
elementName = override.toLowerCase();
// Or an object.
else
{
elementName = override.element ? override.element.toLowerCase() : style.element;
attrs = override.attributes;
}
// We can have more than one override definition for the same
// element name, so we attempt to simply append information to
// it if it already exists.
overrideEl = overrides[ elementName ] || ( overrides[ elementName ] = {} );
if ( attrs )
{
// The returning attributes list is an array, because we
// could have different override definitions for the same
// attribute name.
var overrideAttrs = ( overrideEl.attributes = overrideEl.attributes || new Array() );
for ( var attName in attrs )
{
// Each item in the attributes array is also an array,
// where [0] is the attribute name and [1] is the
// override value.
overrideAttrs.push( [ attName.toLowerCase(), attrs[ attName ] ] );
}
}
}
}
return overrides;
}
// Make the comparison of attribute value easier by standardizing it.
function normalizeProperty( name, value, isStyle )
{
var temp = new CKEDITOR.dom.element( 'span' );
temp [ isStyle ? 'setStyle' : 'setAttribute' ]( name, value );
return temp[ isStyle ? 'getStyle' : 'getAttribute' ]( name );
}
// Make the comparison of style text easier by standardizing it.
function normalizeCssText( unparsedCssText, nativeNormalize )
{
var styleText;
if ( nativeNormalize !== false )
{
// Injects the style in a temporary span object, so the browser parses it,
// retrieving its final format.
var temp = new CKEDITOR.dom.element( 'span' );
temp.setAttribute( 'style', unparsedCssText );
styleText = temp.getAttribute( 'style' ) || '';
}
else
styleText = unparsedCssText;
// Normalize font-family property, ignore quotes and being case insensitive. (#7322)
// http://www.w3.org/TR/css3-fonts/#font-family-the-font-family-property
styleText = styleText.replace( /(font-family:)(.*?)(?=;|$)/, function ( match, prop, val )
{
var names = val.split( ',' );
for ( var i = 0; i < names.length; i++ )
names[ i ] = CKEDITOR.tools.trim( names[ i ].replace( /["']/g, '' ) );
return prop + names.join( ',' );
});
// Shrinking white-spaces around colon and semi-colon (#4147).
// Compensate tail semi-colon.
return styleText.replace( /\s*([;:])\s*/, '$1' )
.replace( /([^\s;])$/, '$1;')
// Trimming spaces after comma(#4107),
// remove quotations(#6403),
// mostly for differences on "font-family".
.replace( /,\s+/g, ',' )
.replace( /\"/g,'' )
.toLowerCase();
}
// Turn inline style text properties into one hash.
function parseStyleText( styleText )
{
var retval = {};
styleText
.replace( /"/g, '"' )
.replace( /\s*([^ :;]+)\s*:\s*([^;]+)\s*(?=;|$)/g, function( match, name, value )
{
retval[ name ] = value;
} );
return retval;
}
/**
* Compare two bunch of styles, with the speciality that value 'inherit'
* is treated as a wildcard which will match any value.
* @param {Object|String} source
* @param {Object|String} target
*/
function compareCssText( source, target )
{
typeof source == 'string' && ( source = parseStyleText( source ) );
typeof target == 'string' && ( target = parseStyleText( target ) );
for( var name in source )
{
if ( !( name in target &&
( target[ name ] == source[ name ]
|| source[ name ] == 'inherit'
|| target[ name ] == 'inherit' ) ) )
{
return false;
}
}
return true;
}
function applyStyle( document, remove )
{
var selection = document.getSelection(),
// Bookmark the range so we can re-select it after processing.
bookmarks = selection.createBookmarks( 1 ),
ranges = selection.getRanges(),
func = remove ? this.removeFromRange : this.applyToRange,
range;
var iterator = ranges.createIterator();
while ( ( range = iterator.getNextRange() ) )
func.call( this, range );
if ( bookmarks.length == 1 && bookmarks[ 0 ].collapsed )
{
selection.selectRanges( ranges );
document.getById( bookmarks[ 0 ].startNode ).remove();
}
else
selection.selectBookmarks( bookmarks );
document.removeCustomData( 'doc_processing_style' );
}
})();
CKEDITOR.styleCommand = function( style )
{
this.style = style;
};
CKEDITOR.styleCommand.prototype.exec = function( editor )
{
editor.focus();
var doc = editor.document;
if ( doc )
{
if ( this.state == CKEDITOR.TRISTATE_OFF )
this.style.apply( doc );
else if ( this.state == CKEDITOR.TRISTATE_ON )
this.style.remove( doc );
}
return !!doc;
};
/**
* Manages styles registration and loading. See also {@link CKEDITOR.config.stylesSet}.
* @namespace
* @augments CKEDITOR.resourceManager
* @constructor
* @since 3.2
* @example
* // The set of styles for the <b>Styles</b> combo
* CKEDITOR.stylesSet.add( 'default',
* [
* // Block Styles
* { name : 'Blue Title' , element : 'h3', styles : { 'color' : 'Blue' } },
* { name : 'Red Title' , element : 'h3', styles : { 'color' : 'Red' } },
*
* // Inline Styles
* { name : 'Marker: Yellow' , element : 'span', styles : { 'background-color' : 'Yellow' } },
* { name : 'Marker: Green' , element : 'span', styles : { 'background-color' : 'Lime' } },
*
* // Object Styles
* {
* name : 'Image on Left',
* element : 'img',
* attributes :
* {
* 'style' : 'padding: 5px; margin-right: 5px',
* 'border' : '2',
* 'align' : 'left'
* }
* }
* ]);
*/
CKEDITOR.stylesSet = new CKEDITOR.resourceManager( '', 'stylesSet' );
// Backward compatibility (#5025).
CKEDITOR.addStylesSet = CKEDITOR.tools.bind( CKEDITOR.stylesSet.add, CKEDITOR.stylesSet );
CKEDITOR.loadStylesSet = function( name, url, callback )
{
CKEDITOR.stylesSet.addExternal( name, url, '' );
CKEDITOR.stylesSet.load( name, callback );
};
/**
* Gets the current styleSet for this instance
* @param {Function} callback The function to be called with the styles data.
* @example
* editor.getStylesSet( function( stylesDefinitions ) {} );
*/
CKEDITOR.editor.prototype.getStylesSet = function( callback )
{
if ( !this._.stylesDefinitions )
{
var editor = this,
// Respect the backwards compatible definition entry
configStyleSet = editor.config.stylesCombo_stylesSet || editor.config.stylesSet || 'default';
// #5352 Allow to define the styles directly in the config object
if ( configStyleSet instanceof Array )
{
editor._.stylesDefinitions = configStyleSet;
callback( configStyleSet );
return;
}
var partsStylesSet = configStyleSet.split( ':' ),
styleSetName = partsStylesSet[ 0 ],
externalPath = partsStylesSet[ 1 ],
pluginPath = CKEDITOR.plugins.registered.styles.path;
CKEDITOR.stylesSet.addExternal( styleSetName,
externalPath ?
partsStylesSet.slice( 1 ).join( ':' ) :
pluginPath + 'styles/' + styleSetName + '.js', '' );
CKEDITOR.stylesSet.load( styleSetName, function( stylesSet )
{
editor._.stylesDefinitions = stylesSet[ styleSetName ];
callback( editor._.stylesDefinitions );
} ) ;
}
else
callback( this._.stylesDefinitions );
};
/**
* Indicates that fully selected read-only elements will be included when
* applying the style (for inline styles only).
* @name CKEDITOR.style.includeReadonly
* @type Boolean
* @default false
* @since 3.5
*/
/**
* Disables inline styling on read-only elements.
* @name CKEDITOR.config.disableReadonlyStyling
* @type Boolean
* @default false
* @since 3.5
*/
/**
* The "styles definition set" to use in the editor. They will be used in the
* styles combo and the Style selector of the div container. <br>
* The styles may be defined in the page containing the editor, or can be
* loaded on demand from an external file. In the second case, if this setting
* contains only a name, the styles definition file will be loaded from the
* "styles" folder inside the styles plugin folder.
* Otherwise, this setting has the "name:url" syntax, making it
* possible to set the URL from which loading the styles file.<br>
* Previously this setting was available as config.stylesCombo_stylesSet<br>
* @name CKEDITOR.config.stylesSet
* @type String|Array
* @default 'default'
* @since 3.3
* @example
* // Load from the styles' styles folder (mystyles.js file).
* config.stylesSet = 'mystyles';
* @example
* // Load from a relative URL.
* config.stylesSet = 'mystyles:/editorstyles/styles.js';
* @example
* // Load from a full URL.
* config.stylesSet = 'mystyles:http://www.example.com/editorstyles/styles.js';
* @example
* // Load from a list of definitions.
* config.stylesSet = [
* { name : 'Strong Emphasis', element : 'strong' },
* { name : 'Emphasis', element : 'em' }, ... ];
*/ | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/_source/plugins/styles/plugin.js | plugin.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.stylesSet.add( 'default',
[
/* Block Styles */
// These styles are already available in the "Format" combo, so they are
// not needed here by default. You may enable them to avoid placing the
// "Format" combo in the toolbar, maintaining the same features.
/*
{ name : 'Paragraph' , element : 'p' },
{ name : 'Heading 1' , element : 'h1' },
{ name : 'Heading 2' , element : 'h2' },
{ name : 'Heading 3' , element : 'h3' },
{ name : 'Heading 4' , element : 'h4' },
{ name : 'Heading 5' , element : 'h5' },
{ name : 'Heading 6' , element : 'h6' },
{ name : 'Preformatted Text', element : 'pre' },
{ name : 'Address' , element : 'address' },
*/
{ name : 'Blue Title' , element : 'h3', styles : { 'color' : 'Blue' } },
{ name : 'Red Title' , element : 'h3', styles : { 'color' : 'Red' } },
/* Inline Styles */
// These are core styles available as toolbar buttons. You may opt enabling
// some of them in the Styles combo, removing them from the toolbar.
/*
{ name : 'Strong' , element : 'strong', overrides : 'b' },
{ name : 'Emphasis' , element : 'em' , overrides : 'i' },
{ name : 'Underline' , element : 'u' },
{ name : 'Strikethrough' , element : 'strike' },
{ name : 'Subscript' , element : 'sub' },
{ name : 'Superscript' , element : 'sup' },
*/
{ name : 'Marker: Yellow' , element : 'span', styles : { 'background-color' : 'Yellow' } },
{ name : 'Marker: Green' , element : 'span', styles : { 'background-color' : 'Lime' } },
{ name : 'Big' , element : 'big' },
{ name : 'Small' , element : 'small' },
{ name : 'Typewriter' , element : 'tt' },
{ name : 'Computer Code' , element : 'code' },
{ name : 'Keyboard Phrase' , element : 'kbd' },
{ name : 'Sample Text' , element : 'samp' },
{ name : 'Variable' , element : 'var' },
{ name : 'Deleted Text' , element : 'del' },
{ name : 'Inserted Text' , element : 'ins' },
{ name : 'Cited Work' , element : 'cite' },
{ name : 'Inline Quotation' , element : 'q' },
{ name : 'Language: RTL' , element : 'span', attributes : { 'dir' : 'rtl' } },
{ name : 'Language: LTR' , element : 'span', attributes : { 'dir' : 'ltr' } },
/* Object Styles */
{
name : 'Image on Left',
element : 'img',
attributes :
{
'style' : 'padding: 5px; margin-right: 5px',
'border' : '2',
'align' : 'left'
}
},
{
name : 'Image on Right',
element : 'img',
attributes :
{
'style' : 'padding: 5px; margin-left: 5px',
'border' : '2',
'align' : 'right'
}
},
{ name : 'Borderless Table', element : 'table', styles: { 'border-style': 'hidden', 'background-color' : '#E6E6FA' } },
{ name : 'Square Bulleted List', element : 'ul', styles : { 'list-style-type' : 'square' } }
]); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/_source/plugins/styles/styles/default.js | default.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add( 'a11yHelp', function( editor )
{
var lang = editor.lang.accessibilityHelp,
id = CKEDITOR.tools.getNextId();
// CharCode <-> KeyChar.
var keyMap =
{
8 : "BACKSPACE",
9 : "TAB" ,
13 : "ENTER" ,
16 : "SHIFT" ,
17 : "CTRL" ,
18 : "ALT" ,
19 : "PAUSE" ,
20 : "CAPSLOCK" ,
27 : "ESCAPE" ,
33 : "PAGE UP" ,
34 : "PAGE DOWN" ,
35 : "END" ,
36 : "HOME" ,
37 : "LEFT ARROW" ,
38 : "UP ARROW" ,
39 : "RIGHT ARROW" ,
40 : "DOWN ARROW" ,
45 : "INSERT" ,
46 : "DELETE" ,
91 : "LEFT WINDOW KEY" ,
92 : "RIGHT WINDOW KEY" ,
93 : "SELECT KEY" ,
96 : "NUMPAD 0" ,
97 : "NUMPAD 1" ,
98 : "NUMPAD 2" ,
99 : "NUMPAD 3" ,
100 : "NUMPAD 4" ,
101 : "NUMPAD 5" ,
102 : "NUMPAD 6" ,
103 : "NUMPAD 7" ,
104 : "NUMPAD 8" ,
105 : "NUMPAD 9" ,
106 : "MULTIPLY" ,
107 : "ADD" ,
109 : "SUBTRACT" ,
110 : "DECIMAL POINT" ,
111 : "DIVIDE" ,
112 : "F1" ,
113 : "F2" ,
114 : "F3" ,
115 : "F4" ,
116 : "F5" ,
117 : "F6" ,
118 : "F7" ,
119 : "F8" ,
120 : "F9" ,
121 : "F10" ,
122 : "F11" ,
123 : "F12" ,
144 : "NUM LOCK" ,
145 : "SCROLL LOCK" ,
186 : "SEMI-COLON" ,
187 : "EQUAL SIGN" ,
188 : "COMMA" ,
189 : "DASH" ,
190 : "PERIOD" ,
191 : "FORWARD SLASH" ,
192 : "GRAVE ACCENT" ,
219 : "OPEN BRACKET" ,
220 : "BACK SLASH" ,
221 : "CLOSE BRAKET" ,
222 : "SINGLE QUOTE"
};
// Modifier keys override.
keyMap[ CKEDITOR.ALT ] = 'ALT';
keyMap[ CKEDITOR.SHIFT ] = 'SHIFT';
keyMap[ CKEDITOR.CTRL ] = 'CTRL';
// Sort in desc.
var modifiers = [ CKEDITOR.ALT, CKEDITOR.SHIFT, CKEDITOR.CTRL ];
function representKeyStroke( keystroke )
{
var quotient,
modifier,
presentation = [];
for ( var i = 0; i < modifiers.length; i++ )
{
modifier = modifiers[ i ];
quotient = keystroke / modifiers[ i ];
if ( quotient > 1 && quotient <= 2 )
{
keystroke -= modifier;
presentation.push( keyMap[ modifier ] );
}
}
presentation.push( keyMap[ keystroke ]
|| String.fromCharCode( keystroke ) );
return presentation.join( '+' );
}
var variablesPattern = /\$\{(.*?)\}/g;
function replaceVariables( match, name )
{
var keystrokes = editor.config.keystrokes,
definition,
length = keystrokes.length;
for ( var i = 0; i < length; i++ )
{
definition = keystrokes[ i ];
if ( definition[ 1 ] == name )
break;
}
return representKeyStroke( definition[ 0 ] );
}
// Create the help list directly from lang file entries.
function buildHelpContents()
{
var pageTpl = '<div class="cke_accessibility_legend" role="document" aria-labelledby="' + id + '_arialbl" tabIndex="-1">%1</div>' +
'<span id="' + id + '_arialbl" class="cke_voice_label">' + lang.contents + ' </span>',
sectionTpl = '<h1>%1</h1><dl>%2</dl>',
itemTpl = '<dt>%1</dt><dd>%2</dd>';
var pageHtml = [],
sections = lang.legend,
sectionLength = sections.length;
for ( var i = 0; i < sectionLength; i++ )
{
var section = sections[ i ],
sectionHtml = [],
items = section.items,
itemsLength = items.length;
for ( var j = 0; j < itemsLength; j++ )
{
var item = items[ j ],
itemHtml;
itemHtml = itemTpl.replace( '%1', item.name ).
replace( '%2', item.legend.replace( variablesPattern, replaceVariables ) );
sectionHtml.push( itemHtml );
}
pageHtml.push( sectionTpl.replace( '%1', section.name ).replace( '%2', sectionHtml.join( '' ) ) );
}
return pageTpl.replace( '%1', pageHtml.join( '' ) );
}
return {
title : lang.title,
minWidth : 600,
minHeight : 400,
contents : [
{
id : 'info',
label : editor.lang.common.generalTab,
expand : true,
elements :
[
{
type : 'html',
id : 'legends',
style : 'white-space:normal;',
focus : function() {},
html : buildHelpContents() +
'<style type="text/css">' +
'.cke_accessibility_legend' +
'{' +
'width:600px;' +
'height:400px;' +
'padding-right:5px;' +
'overflow-y:auto;' +
'overflow-x:hidden;' +
'}' +
// Some adjustments are to be done for IE6 and Quirks to work "properly" (#5757)
'.cke_browser_quirks .cke_accessibility_legend,' +
'.cke_browser_ie6 .cke_accessibility_legend' +
'{' +
'height:390px' +
'}' +
// Override non-wrapping white-space rule in reset css.
'.cke_accessibility_legend *' +
'{' +
'white-space:normal;' +
'}' +
'.cke_accessibility_legend h1' +
'{' +
'font-size: 20px;' +
'border-bottom: 1px solid #AAA;' +
'margin: 5px 0px 15px;' +
'}' +
'.cke_accessibility_legend dl' +
'{' +
'margin-left: 5px;' +
'}' +
'.cke_accessibility_legend dt' +
'{' +
'font-size: 13px;' +
'font-weight: bold;' +
'}' +
'.cke_accessibility_legend dd' +
'{' +
'margin:10px' +
'}' +
'</style>'
}
]
}
],
buttons : [ CKEDITOR.dialog.cancelButton ]
};
}); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/_source/plugins/a11yhelp/dialogs/a11yhelp.js | a11yhelp.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'a11yhelp', 'en',
{
accessibilityHelp :
{
title : 'Accessibility Instructions',
contents : 'Help Contents. To close this dialog press ESC.',
legend :
[
{
name : 'General',
items :
[
{
name : 'Editor Toolbar',
legend:
'Press ${toolbarFocus} to navigate to the toolbar. ' +
'Move to the next and previous toolbar group with TAB and SHIFT-TAB. ' +
'Move to the next and previous toolbar button with RIGHT ARROW or LEFT ARROW. ' +
'Press SPACE or ENTER to activate the toolbar button.'
},
{
name : 'Editor Dialog',
legend :
'Inside a dialog, press TAB to navigate to next dialog field, press SHIFT + TAB to move to previous field, press ENTER to submit dialog, press ESC to cancel dialog. ' +
'For dialogs that have multiple tab pages, press ALT + F10 to navigate to tab-list. ' +
'Then move to next tab with TAB OR RIGTH ARROW. ' +
'Move to previous tab with SHIFT + TAB or LEFT ARROW. ' +
'Press SPACE or ENTER to select the tab page.'
},
{
name : 'Editor Context Menu',
legend :
'Press ${contextMenu} or APPLICATION KEY to open context-menu. ' +
'Then move to next menu option with TAB or DOWN ARROW. ' +
'Move to previous option with SHIFT+TAB or UP ARROW. ' +
'Press SPACE or ENTER to select the menu option. ' +
'Open sub-menu of current option wtih SPACE or ENTER or RIGHT ARROW. ' +
'Go back to parent menu item with ESC or LEFT ARROW. ' +
'Close context menu with ESC.'
},
{
name : 'Editor List Box',
legend :
'Inside a list-box, move to next list item with TAB OR DOWN ARROW. ' +
'Move to previous list item with SHIFT + TAB or UP ARROW. ' +
'Press SPACE or ENTER to select the list option. ' +
'Press ESC to close the list-box.'
},
{
name : 'Editor Element Path Bar',
legend :
'Press ${elementsPathFocus} to navigate to the elements path bar. ' +
'Move to next element button with TAB or RIGHT ARROW. ' +
'Move to previous button with SHIFT+TAB or LEFT ARROW. ' +
'Press SPACE or ENTER to select the element in editor.'
}
]
},
{
name : 'Commands',
items :
[
{
name : ' Undo command',
legend : 'Press ${undo}'
},
{
name : ' Redo command',
legend : 'Press ${redo}'
},
{
name : ' Bold command',
legend : 'Press ${bold}'
},
{
name : ' Italic command',
legend : 'Press ${italic}'
},
{
name : ' Underline command',
legend : 'Press ${underline}'
},
{
name : ' Link command',
legend : 'Press ${link}'
},
{
name : ' Toolbar Collapse command',
legend : 'Press ${toolbarCollapse}'
},
{
name : ' Accessibility Help',
legend : 'Press ${a11yHelp}'
}
]
}
]
}
}); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/_source/plugins/a11yhelp/lang/en.js | en.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'a11yhelp', 'he',
{
accessibilityHelp :
{
title : 'הוראות נגישות',
contents : 'הוראות נגישות. לסגירה לחץ אסקייפ (ESC).',
legend :
[
{
name : 'כללי',
items :
[
{
name : 'סרגל הכלים',
legend:
'לחץ על ${toolbarFocus} כדי לנווט לסרגל הכלים. ' +
'עבור לכפתור הבא עם מקש הטאב (TAB) או חץ שמאלי. ' +
'עבור לכפתור הקודם עם מקש השיפט (SHIFT) + טאב (TAB) או חץ ימני. ' +
'לחץ רווח או אנטר (ENTER) כדי להפעיל את הכפתור הנבחר.'
},
{
name : 'דיאלוגים (חלונות תשאול)',
legend :
'בתוך דיאלוג, לחץ טאב (TAB) כדי לנווט לשדה הבא, לחץ שיפט (SHIFT) + טאב (TAB) כדי לנווט לשדה הקודם, לחץ אנטר (ENTER) כדי לשלוח את הדיאלוג, לחץ אסקייפ (ESC) כדי לבטל. ' +
'בתוך דיאלוגים בעלי מספר טאבים (לשוניות), לחץ אלט (ALT) + F10 כדי לנווט לשורת הטאבים. ' +
'נווט לטאב הבא עם טאב (TAB) או חץ שמאלי. ' +
'עבור לטאב הקודם עם שיפט (SHIFT) + טאב (TAB) או חץ שמאלי. ' +
'לחץ רווח או אנטר (ENTER) כדי להיכנס לטאב.'
},
{
name : 'תפריט ההקשר (Context Menu)',
legend :
'לחץ ${contextMenu} או APPLICATION KEYכדי לפתוח את תפריט ההקשר. ' +
'עבור לאפשרות הבאה עם טאב (TAB) או חץ למטה. ' +
'עבור לאפשרות הקודמת עם שיפט (SHIFT) + טאב (TAB) או חץ למעלה. ' +
'לחץ רווח או אנטר (ENTER) כדי לבחור את האפשרות. ' +
'פתח את תת התפריט (Sub-menu) של האפשרות הנוכחית עם רווח או אנטר (ENTER) או חץ שמאלי. ' +
'חזור לתפריט האב עם אסקייפ (ESC) או חץ שמאלי. ' +
'סגור את תפריט ההקשר עם אסקייפ (ESC).'
},
{
name : 'תפריטים צפים (List boxes)',
legend :
'בתוך תפריט צף, עבור לפריט הבא עם טאב (TAB) או חץ למטה. ' +
'עבור לתפריט הקודם עם שיפט (SHIFT) + טאב (TAB) or חץ עליון. ' +
'Press SPACE or ENTER to select the list option. ' +
'Press ESC to close the list-box.'
},
{
name : 'עץ אלמנטים (Elements Path)',
legend :
'לחץ ${elementsPathFocus} כדי לנווט לעץ האלמנטים. ' +
'עבור לפריט הבא עם טאב (TAB) או חץ ימני. ' +
'עבור לפריט הקודם עם שיפט (SHIFT) + טאב (TAB) או חץ שמאלי. ' +
'לחץ רווח או אנטר (ENTER) כדי לבחור את האלמנט בעורך.'
}
]
},
{
name : 'פקודות',
items :
[
{
name : ' ביטול צעד אחרון',
legend : 'לחץ ${undo}'
},
{
name : ' חזרה על צעד אחרון',
legend : 'לחץ ${redo}'
},
{
name : ' הדגשה',
legend : 'לחץ ${bold}'
},
{
name : ' הטייה',
legend : 'לחץ ${italic}'
},
{
name : ' הוספת קו תחתון',
legend : 'לחץ ${underline}'
},
{
name : ' הוספת לינק',
legend : 'לחץ ${link}'
},
{
name : ' כיווץ סרגל הכלים',
legend : 'לחץ ${toolbarCollapse}'
},
{
name : ' הוראות נגישות',
legend : 'לחץ ${a11yHelp}'
}
]
}
]
}
});
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'a11yhelp', 'he',
{
accessibilityHelp :
{
title : 'הוראות נגישות',
contents : 'הוראות נגישות. לסגירה לחץ אסקייפ (ESC).',
legend :
[
{
name : 'כללי',
items :
[
{
name : 'סרגל הכלים',
legend:
'לחץ על ${toolbarFocus} כדי לנווט לסרגל הכלים. ' +
'עבור לכפתור הבא עם מקש הטאב (TAB) או חץ שמאלי. ' +
'עבור לכפתור הקודם עם מקש השיפט (SHIFT) + טאב (TAB) או חץ ימני. ' +
'לחץ רווח או אנטר (ENTER) כדי להפעיל את הכפתור הנבחר.'
},
{
name : 'דיאלוגים (חלונות תשאול)',
legend :
'בתוך דיאלוג, לחץ טאב (TAB) כדי לנווט לשדה הבא, לחץ שיפט (SHIFT) + טאב (TAB) כדי לנווט לשדה הקודם, לחץ אנטר (ENTER) כדי לשלוח את הדיאלוג, לחץ אסקייפ (ESC) כדי לבטל. ' +
'בתוך דיאלוגים בעלי מספר טאבים (לשוניות), לחץ אלט (ALT) + F10 כדי לנווט לשורת הטאבים. ' +
'נווט לטאב הבא עם טאב (TAB) או חץ שמאלי. ' +
'עבור לטאב הקודם עם שיפט (SHIFT) + טאב (TAB) או חץ שמאלי. ' +
'לחץ רווח או אנטר (ENTER) כדי להיכנס לטאב.'
},
{
name : 'תפריט ההקשר (Context Menu)',
legend :
'לחץ ${contextMenu} או APPLICATION KEYכדי לפתוח את תפריט ההקשר. ' +
'עבור לאפשרות הבאה עם טאב (TAB) או חץ למטה. ' +
'עבור לאפשרות הקודמת עם שיפט (SHIFT) + טאב (TAB) או חץ למעלה. ' +
'לחץ רווח או אנטר (ENTER) כדי לבחור את האפשרות. ' +
'פתח את תת התפריט (Sub-menu) של האפשרות הנוכחית עם רווח או אנטר (ENTER) או חץ שמאלי. ' +
'חזור לתפריט האב עם אסקייפ (ESC) או חץ שמאלי. ' +
'סגור את תפריט ההקשר עם אסקייפ (ESC).'
},
{
name : 'תפריטים צפים (List boxes)',
legend :
'בתוך תפריט צף, עבור לפריט הבא עם טאב (TAB) או חץ למטה. ' +
'עבור לתפריט הקודם עם שיפט (SHIFT) + טאב (TAB) or חץ עליון. ' +
'Press SPACE or ENTER to select the list option. ' +
'Press ESC to close the list-box.'
},
{
name : 'עץ אלמנטים (Elements Path)',
legend :
'לחץ ${elementsPathFocus} כדי לנווט לעץ האלמנטים. ' +
'עבור לפריט הבא עם טאב (TAB) או חץ ימני. ' +
'עבור לפריט הקודם עם שיפט (SHIFT) + טאב (TAB) או חץ שמאלי. ' +
'לחץ רווח או אנטר (ENTER) כדי לבחור את האלמנט בעורך.'
}
]
},
{
name : 'פקודות',
items :
[
{
name : ' ביטול צעד אחרון',
legend : 'לחץ ${undo}'
},
{
name : ' חזרה על צעד אחרון',
legend : 'לחץ ${redo}'
},
{
name : ' הדגשה',
legend : 'לחץ ${bold}'
},
{
name : ' הטייה',
legend : 'לחץ ${italic}'
},
{
name : ' הוספת קו תחתון',
legend : 'לחץ ${underline}'
},
{
name : ' הוספת לינק',
legend : 'לחץ ${link}'
},
{
name : ' כיווץ סרגל הכלים',
legend : 'לחץ ${toolbarCollapse}'
},
{
name : ' הוראות נגישות',
legend : 'לחץ ${a11yHelp}'
}
]
}
]
}
}); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/_source/plugins/a11yhelp/lang/he.js | he.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
function protectFormStyles( formElement )
{
if ( !formElement || formElement.type != CKEDITOR.NODE_ELEMENT || formElement.getName() != 'form' )
return [];
var hijackRecord = [],
hijackNames = [ 'style', 'className' ];
for ( var i = 0 ; i < hijackNames.length ; i++ )
{
var name = hijackNames[i];
var $node = formElement.$.elements.namedItem( name );
if ( $node )
{
var hijackNode = new CKEDITOR.dom.element( $node );
hijackRecord.push( [ hijackNode, hijackNode.nextSibling ] );
hijackNode.remove();
}
}
return hijackRecord;
}
function restoreFormStyles( formElement, hijackRecord )
{
if ( !formElement || formElement.type != CKEDITOR.NODE_ELEMENT || formElement.getName() != 'form' )
return;
if ( hijackRecord.length > 0 )
{
for ( var i = hijackRecord.length - 1 ; i >= 0 ; i-- )
{
var node = hijackRecord[i][0];
var sibling = hijackRecord[i][1];
if ( sibling )
node.insertBefore( sibling );
else
node.appendTo( formElement );
}
}
}
function saveStyles( element, isInsideEditor )
{
var data = protectFormStyles( element );
var retval = {};
var $element = element.$;
if ( !isInsideEditor )
{
retval[ 'class' ] = $element.className || '';
$element.className = '';
}
retval.inline = $element.style.cssText || '';
if ( !isInsideEditor ) // Reset any external styles that might interfere. (#2474)
$element.style.cssText = 'position: static; overflow: visible';
restoreFormStyles( data );
return retval;
}
function restoreStyles( element, savedStyles )
{
var data = protectFormStyles( element );
var $element = element.$;
if ( 'class' in savedStyles )
$element.className = savedStyles[ 'class' ];
if ( 'inline' in savedStyles )
$element.style.cssText = savedStyles.inline;
restoreFormStyles( data );
}
function refreshCursor( editor )
{
// Refresh all editor instances on the page (#5724).
var all = CKEDITOR.instances;
for ( var i in all )
{
var one = all[ i ];
if ( one.mode == 'wysiwyg' && !one.readOnly )
{
var body = one.document.getBody();
// Refresh 'contentEditable' otherwise
// DOM lifting breaks design mode. (#5560)
body.setAttribute( 'contentEditable', false );
body.setAttribute( 'contentEditable', true );
}
}
if ( editor.focusManager.hasFocus )
{
editor.toolbox.focus();
editor.focus();
}
}
/**
* Adding an iframe shim to this element, OR removing the existing one if already applied.
* Note: This will only affect IE version below 7.
*/
function createIframeShim( element )
{
if ( !CKEDITOR.env.ie || CKEDITOR.env.version > 6 )
return null;
var shim = CKEDITOR.dom.element.createFromHtml( '<iframe frameborder="0" tabindex="-1"' +
' src="javascript:' +
'void((function(){' +
'document.open();' +
( CKEDITOR.env.isCustomDomain() ? 'document.domain=\'' + this.getDocument().$.domain + '\';' : '' ) +
'document.close();' +
'})())"' +
' style="display:block;position:absolute;z-index:-1;' +
'progid:DXImageTransform.Microsoft.Alpha(opacity=0);' +
'"></iframe>' );
return element.append( shim, true );
}
CKEDITOR.plugins.add( 'maximize',
{
init : function( editor )
{
var lang = editor.lang;
var mainDocument = CKEDITOR.document,
mainWindow = mainDocument.getWindow();
// Saved selection and scroll position for the editing area.
var savedSelection,
savedScroll;
// Saved scroll position for the outer window.
var outerScroll;
var shim;
// Saved resize handler function.
function resizeHandler()
{
var viewPaneSize = mainWindow.getViewPaneSize();
shim && shim.setStyles( { width : viewPaneSize.width + 'px', height : viewPaneSize.height + 'px' } );
editor.resize( viewPaneSize.width, viewPaneSize.height, null, true );
}
// Retain state after mode switches.
var savedState = CKEDITOR.TRISTATE_OFF;
editor.addCommand( 'maximize',
{
// Disabled on iOS (#8307).
modes : { wysiwyg : !CKEDITOR.env.iOS, source : !CKEDITOR.env.iOS },
readOnly : 1,
editorFocus : false,
exec : function()
{
var container = editor.container.getChild( 1 );
var contents = editor.getThemeSpace( 'contents' );
// Save current selection and scroll position in editing area.
if ( editor.mode == 'wysiwyg' )
{
var selection = editor.getSelection();
savedSelection = selection && selection.getRanges();
savedScroll = mainWindow.getScrollPosition();
}
else
{
var $textarea = editor.textarea.$;
savedSelection = !CKEDITOR.env.ie && [ $textarea.selectionStart, $textarea.selectionEnd ];
savedScroll = [ $textarea.scrollLeft, $textarea.scrollTop ];
}
if ( this.state == CKEDITOR.TRISTATE_OFF ) // Go fullscreen if the state is off.
{
// Add event handler for resizing.
mainWindow.on( 'resize', resizeHandler );
// Save the scroll bar position.
outerScroll = mainWindow.getScrollPosition();
// Save and reset the styles for the entire node tree.
var currentNode = editor.container;
while ( ( currentNode = currentNode.getParent() ) )
{
currentNode.setCustomData( 'maximize_saved_styles', saveStyles( currentNode ) );
currentNode.setStyle( 'z-index', editor.config.baseFloatZIndex - 1 );
}
contents.setCustomData( 'maximize_saved_styles', saveStyles( contents, true ) );
container.setCustomData( 'maximize_saved_styles', saveStyles( container, true ) );
// Hide scroll bars.
var styles =
{
overflow : CKEDITOR.env.webkit ? '' : 'hidden', // #6896
width : 0,
height : 0
};
mainDocument.getDocumentElement().setStyles( styles );
!CKEDITOR.env.gecko && mainDocument.getDocumentElement().setStyle( 'position', 'fixed' );
!( CKEDITOR.env.gecko && CKEDITOR.env.quirks ) && mainDocument.getBody().setStyles( styles );
// Scroll to the top left (IE needs some time for it - #4923).
CKEDITOR.env.ie ?
setTimeout( function() { mainWindow.$.scrollTo( 0, 0 ); }, 0 ) :
mainWindow.$.scrollTo( 0, 0 );
// Resize and move to top left.
// Special treatment for FF Quirks (#7284)
container.setStyle( 'position', CKEDITOR.env.gecko && CKEDITOR.env.quirks ? 'fixed' : 'absolute' );
container.$.offsetLeft; // SAFARI BUG: See #2066.
container.setStyles(
{
'z-index' : editor.config.baseFloatZIndex - 1,
left : '0px',
top : '0px'
} );
shim = createIframeShim( container ); // IE6 select element penetration when maximized. (#4459)
// Add cke_maximized class before resize handle since that will change things sizes (#5580)
container.addClass( 'cke_maximized' );
resizeHandler();
// Still not top left? Fix it. (Bug #174)
var offset = container.getDocumentPosition();
container.setStyles(
{
left : ( -1 * offset.x ) + 'px',
top : ( -1 * offset.y ) + 'px'
} );
// Fixing positioning editor chrome in Firefox break design mode. (#5149)
CKEDITOR.env.gecko && refreshCursor( editor );
}
else if ( this.state == CKEDITOR.TRISTATE_ON ) // Restore from fullscreen if the state is on.
{
// Remove event handler for resizing.
mainWindow.removeListener( 'resize', resizeHandler );
// Restore CSS styles for the entire node tree.
var editorElements = [ contents, container ];
for ( var i = 0 ; i < editorElements.length ; i++ )
{
restoreStyles( editorElements[i], editorElements[i].getCustomData( 'maximize_saved_styles' ) );
editorElements[i].removeCustomData( 'maximize_saved_styles' );
}
currentNode = editor.container;
while ( ( currentNode = currentNode.getParent() ) )
{
restoreStyles( currentNode, currentNode.getCustomData( 'maximize_saved_styles' ) );
currentNode.removeCustomData( 'maximize_saved_styles' );
}
// Restore the window scroll position.
CKEDITOR.env.ie ?
setTimeout( function() { mainWindow.$.scrollTo( outerScroll.x, outerScroll.y ); }, 0 ) :
mainWindow.$.scrollTo( outerScroll.x, outerScroll.y );
// Remove cke_maximized class.
container.removeClass( 'cke_maximized' );
// Webkit requires a re-layout on editor chrome. (#6695)
if ( CKEDITOR.env.webkit )
{
container.setStyle( 'display', 'inline' );
setTimeout( function(){ container.setStyle( 'display', 'block' ); }, 0 );
}
if ( shim )
{
shim.remove();
shim = null;
}
// Emit a resize event, because this time the size is modified in
// restoreStyles.
editor.fire( 'resize' );
}
this.toggleState();
// Toggle button label.
var button = this.uiItems[ 0 ];
// Only try to change the button if it exists (#6166)
if( button )
{
var label = ( this.state == CKEDITOR.TRISTATE_OFF )
? lang.maximize : lang.minimize;
var buttonNode = editor.element.getDocument().getById( button._.id );
buttonNode.getChild( 1 ).setHtml( label );
buttonNode.setAttribute( 'title', label );
buttonNode.setAttribute( 'href', 'javascript:void("' + label + '");' );
}
// Restore selection and scroll position in editing area.
if ( editor.mode == 'wysiwyg' )
{
if ( savedSelection )
{
// Fixing positioning editor chrome in Firefox break design mode. (#5149)
CKEDITOR.env.gecko && refreshCursor( editor );
editor.getSelection().selectRanges(savedSelection);
var element = editor.getSelection().getStartElement();
element && element.scrollIntoView( true );
}
else
mainWindow.$.scrollTo( savedScroll.x, savedScroll.y );
}
else
{
if ( savedSelection )
{
$textarea.selectionStart = savedSelection[0];
$textarea.selectionEnd = savedSelection[1];
}
$textarea.scrollLeft = savedScroll[0];
$textarea.scrollTop = savedScroll[1];
}
savedSelection = savedScroll = null;
savedState = this.state;
},
canUndo : false
} );
editor.ui.addButton( 'Maximize',
{
label : lang.maximize,
command : 'maximize'
} );
// Restore the command state after mode change, unless it has been changed to disabled (#6467)
editor.on( 'mode', function()
{
var command = editor.getCommand( 'maximize' );
command.setState( command.state == CKEDITOR.TRISTATE_DISABLED ? CKEDITOR.TRISTATE_DISABLED : savedState );
}, null, null, 100 );
}
} );
})(); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/_source/plugins/maximize/plugin.js | plugin.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add( 'about', function( editor )
{
var lang = editor.lang.about;
return {
title : CKEDITOR.env.ie ? lang.dlgTitle : lang.title,
minWidth : 390,
minHeight : 230,
contents : [
{
id : 'tab1',
label : '',
title : '',
expand : true,
padding : 0,
elements :
[
{
type : 'html',
html :
'<style type="text/css">' +
'.cke_about_container' +
'{' +
'color:#000 !important;' +
'padding:10px 10px 0;' +
'margin-top:5px' +
'}' +
'.cke_about_container p' +
'{' +
'margin: 0 0 10px;' +
'}' +
'.cke_about_container .cke_about_logo' +
'{' +
'height:81px;' +
'background-color:#fff;' +
'background-image:url(' + CKEDITOR.plugins.get( 'about' ).path + 'dialogs/logo_ckeditor.png);' +
'background-position:center; ' +
'background-repeat:no-repeat;' +
'margin-bottom:10px;' +
'}' +
'.cke_about_container a' +
'{' +
'cursor:pointer !important;' +
'color:blue !important;' +
'text-decoration:underline !important;' +
'}' +
'</style>' +
'<div class="cke_about_container">' +
'<div class="cke_about_logo"></div>' +
'<p>' +
'CKEditor ' + CKEDITOR.version + ' (revision ' + CKEDITOR.revision + ')<br>' +
'<a href="http://ckeditor.com/">http://ckeditor.com</a>' +
'</p>' +
'<p>' +
lang.help.replace( '$1', '<a href="http://docs.cksource.com/CKEditor_3.x/Users_Guide/Quick_Reference">' + lang.userGuide + '</a>' ) +
'</p>' +
'<p>' +
lang.moreInfo + '<br>' +
'<a href="http://ckeditor.com/license">http://ckeditor.com/license</a>' +
'</p>' +
'<p>' +
lang.copy.replace( '$1', '<a href="http://cksource.com/">CKSource</a> - Frederico Knabben' ) +
'</p>' +
'</div>'
}
]
}
],
buttons : [ CKEDITOR.dialog.cancelButton ]
};
} ); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/_source/plugins/about/dialogs/about.js | about.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
var guardElements = { table:1, ul:1, ol:1, blockquote:1, div:1 },
directSelectionGuardElements = {},
// All guard elements which can have a direction applied on them.
allGuardElements = {};
CKEDITOR.tools.extend( directSelectionGuardElements, guardElements, { tr:1, p:1, div:1, li:1 } );
CKEDITOR.tools.extend( allGuardElements, directSelectionGuardElements, { td:1 } );
function onSelectionChange( e )
{
setToolbarStates( e );
handleMixedDirContent( e );
}
function setToolbarStates( evt )
{
var editor = evt.editor,
path = evt.data.path;
if ( editor.readOnly )
return;
var useComputedState = editor.config.useComputedState,
selectedElement;
useComputedState = useComputedState === undefined || useComputedState;
// We can use computedState provided by the browser or traverse parents manually.
if ( !useComputedState )
selectedElement = getElementForDirection( path.lastElement );
selectedElement = selectedElement || path.block || path.blockLimit;
// If we're having BODY here, user probably done CTRL+A, let's try to get the enclosed node, if any.
if ( selectedElement.is( 'body' ) )
{
var enclosedNode = editor.getSelection().getRanges()[ 0 ].getEnclosedNode();
enclosedNode && enclosedNode.type == CKEDITOR.NODE_ELEMENT && ( selectedElement = enclosedNode );
}
if ( !selectedElement )
return;
var selectionDir = useComputedState ?
selectedElement.getComputedStyle( 'direction' ) :
selectedElement.getStyle( 'direction' ) || selectedElement.getAttribute( 'dir' );
editor.getCommand( 'bidirtl' ).setState( selectionDir == 'rtl' ? CKEDITOR.TRISTATE_ON : CKEDITOR.TRISTATE_OFF );
editor.getCommand( 'bidiltr' ).setState( selectionDir == 'ltr' ? CKEDITOR.TRISTATE_ON : CKEDITOR.TRISTATE_OFF );
}
function handleMixedDirContent( evt )
{
var editor = evt.editor,
directionNode = evt.data.path.block || evt.data.path.blockLimit;
editor.fire( 'contentDirChanged', directionNode ? directionNode.getComputedStyle( 'direction' ) : editor.lang.dir );
}
/**
* Returns element with possibility of applying the direction.
* @param node
*/
function getElementForDirection( node )
{
while ( node && !( node.getName() in allGuardElements || node.is( 'body' ) ) )
{
var parent = node.getParent();
if ( !parent )
break;
node = parent;
}
return node;
}
function switchDir( element, dir, editor, database )
{
if ( element.isReadOnly() )
return;
// Mark this element as processed by switchDir.
CKEDITOR.dom.element.setMarker( database, element, 'bidi_processed', 1 );
// Check whether one of the ancestors has already been styled.
var parent = element;
while ( ( parent = parent.getParent() ) && !parent.is( 'body' ) )
{
if ( parent.getCustomData( 'bidi_processed' ) )
{
// Ancestor style must dominate.
element.removeStyle( 'direction' );
element.removeAttribute( 'dir' );
return;
}
}
var useComputedState = ( 'useComputedState' in editor.config ) ? editor.config.useComputedState : 1;
var elementDir = useComputedState ? element.getComputedStyle( 'direction' )
: element.getStyle( 'direction' ) || element.hasAttribute( 'dir' );
// Stop if direction is same as present.
if ( elementDir == dir )
return;
// Clear direction on this element.
element.removeStyle( 'direction' );
// Do the second check when computed state is ON, to check
// if we need to apply explicit direction on this element.
if ( useComputedState )
{
element.removeAttribute( 'dir' );
if ( dir != element.getComputedStyle( 'direction' ) )
element.setAttribute( 'dir', dir );
}
else
// Set new direction for this element.
element.setAttribute( 'dir', dir );
editor.forceNextSelectionCheck();
return;
}
function getFullySelected( range, elements, enterMode )
{
var ancestor = range.getCommonAncestor( false, true );
range = range.clone();
range.enlarge( enterMode == CKEDITOR.ENTER_BR ?
CKEDITOR.ENLARGE_LIST_ITEM_CONTENTS
: CKEDITOR.ENLARGE_BLOCK_CONTENTS );
if ( range.checkBoundaryOfElement( ancestor, CKEDITOR.START )
&& range.checkBoundaryOfElement( ancestor, CKEDITOR.END ) )
{
var parent;
while ( ancestor && ancestor.type == CKEDITOR.NODE_ELEMENT
&& ( parent = ancestor.getParent() )
&& parent.getChildCount() == 1
&& !( ancestor.getName() in elements ) )
ancestor = parent;
return ancestor.type == CKEDITOR.NODE_ELEMENT
&& ( ancestor.getName() in elements )
&& ancestor;
}
}
function bidiCommand( dir )
{
return function( editor )
{
var selection = editor.getSelection(),
enterMode = editor.config.enterMode,
ranges = selection.getRanges();
if ( ranges && ranges.length )
{
var database = {};
// Creates bookmarks for selection, as we may split some blocks.
var bookmarks = selection.createBookmarks();
var rangeIterator = ranges.createIterator(),
range,
i = 0;
while ( ( range = rangeIterator.getNextRange( 1 ) ) )
{
// Apply do directly selected elements from guardElements.
var selectedElement = range.getEnclosedNode();
// If this is not our element of interest, apply to fully selected elements from guardElements.
if ( !selectedElement || selectedElement
&& !( selectedElement.type == CKEDITOR.NODE_ELEMENT && selectedElement.getName() in directSelectionGuardElements )
)
selectedElement = getFullySelected( range, guardElements, enterMode );
selectedElement && switchDir( selectedElement, dir, editor, database );
var iterator,
block;
// Walker searching for guardElements.
var walker = new CKEDITOR.dom.walker( range );
var start = bookmarks[ i ].startNode,
end = bookmarks[ i++ ].endNode;
walker.evaluator = function( node )
{
return !! ( node.type == CKEDITOR.NODE_ELEMENT
&& node.getName() in guardElements
&& !( node.getName() == ( enterMode == CKEDITOR.ENTER_P ? 'p' : 'div' )
&& node.getParent().type == CKEDITOR.NODE_ELEMENT
&& node.getParent().getName() == 'blockquote' )
// Element must be fully included in the range as well. (#6485).
&& node.getPosition( start ) & CKEDITOR.POSITION_FOLLOWING
&& ( ( node.getPosition( end ) & CKEDITOR.POSITION_PRECEDING + CKEDITOR.POSITION_CONTAINS ) == CKEDITOR.POSITION_PRECEDING ) );
};
while ( ( block = walker.next() ) )
switchDir( block, dir, editor, database );
iterator = range.createIterator();
iterator.enlargeBr = enterMode != CKEDITOR.ENTER_BR;
while ( ( block = iterator.getNextParagraph( enterMode == CKEDITOR.ENTER_P ? 'p' : 'div' ) ) )
switchDir( block, dir, editor, database );
}
CKEDITOR.dom.element.clearAllMarkers( database );
editor.forceNextSelectionCheck();
// Restore selection position.
selection.selectBookmarks( bookmarks );
editor.focus();
}
};
}
CKEDITOR.plugins.add( 'bidi',
{
requires : [ 'styles', 'button' ],
init : function( editor )
{
// All buttons use the same code to register. So, to avoid
// duplications, let's use this tool function.
var addButtonCommand = function( buttonName, buttonLabel, commandName, commandExec )
{
editor.addCommand( commandName, new CKEDITOR.command( editor, { exec : commandExec }) );
editor.ui.addButton( buttonName,
{
label : buttonLabel,
command : commandName
});
};
var lang = editor.lang.bidi;
addButtonCommand( 'BidiLtr', lang.ltr, 'bidiltr', bidiCommand( 'ltr' ) );
addButtonCommand( 'BidiRtl', lang.rtl, 'bidirtl', bidiCommand( 'rtl' ) );
editor.on( 'selectionChange', onSelectionChange );
editor.on( 'contentDom', function()
{
editor.document.on( 'dirChanged', function( evt )
{
editor.fire( 'dirChanged',
{
node : evt.data,
dir : evt.data.getDirection( 1 )
} );
});
});
}
});
// If the element direction changed, we need to switch the margins of
// the element and all its children, so it will get really reflected
// like a mirror. (#5910)
function isOffline( el )
{
var html = el.getDocument().getBody().getParent();
while ( el )
{
if ( el.equals( html ) )
return false;
el = el.getParent();
}
return true;
}
function dirChangeNotifier( org )
{
var isAttribute = org == elementProto.setAttribute,
isRemoveAttribute = org == elementProto.removeAttribute,
dirStyleRegexp = /\bdirection\s*:\s*(.*?)\s*(:?$|;)/;
return function( name, val )
{
if ( !this.getDocument().equals( CKEDITOR.document ) )
{
var orgDir;
if ( ( name == ( isAttribute || isRemoveAttribute ? 'dir' : 'direction' ) ||
name == 'style' && ( isRemoveAttribute || dirStyleRegexp.test( val ) ) ) && !isOffline( this ) )
{
orgDir = this.getDirection( 1 );
var retval = org.apply( this, arguments );
if ( orgDir != this.getDirection( 1 ) )
{
this.getDocument().fire( 'dirChanged', this );
return retval;
}
}
}
return org.apply( this, arguments );
};
}
var elementProto = CKEDITOR.dom.element.prototype,
methods = [ 'setStyle', 'removeStyle', 'setAttribute', 'removeAttribute' ];
for ( var i = 0; i < methods.length; i++ )
elementProto[ methods[ i ] ] = CKEDITOR.tools.override( elementProto[ methods [ i ] ], dirChangeNotifier );
})();
/**
* Fired when the language direction of an element is changed
* @name CKEDITOR.editor#dirChanged
* @event
* @param {CKEDITOR.editor} editor This editor instance.
* @param {Object} eventData.node The element that is being changed.
* @param {String} eventData.dir The new direction.
*/
/**
* Fired when the language direction in the specific cursor position is changed
* @name CKEDITOR.editor#contentDirChanged
* @event
* @param {String} eventData The direction in the current position.
*/ | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/_source/plugins/bidi/plugin.js | plugin.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add( 'docProps', function( editor )
{
var lang = editor.lang.docprops,
langCommon = editor.lang.common,
metaHash = {};
function getDialogValue( dialogName, callback )
{
var onOk = function()
{
releaseHandlers( this );
callback( this, this._.parentDialog );
};
var releaseHandlers = function( dialog )
{
dialog.removeListener( 'ok', onOk );
dialog.removeListener( 'cancel', releaseHandlers );
};
var bindToDialog = function( dialog )
{
dialog.on( 'ok', onOk );
dialog.on( 'cancel', releaseHandlers );
};
editor.execCommand( dialogName );
if ( editor._.storedDialogs.colordialog )
bindToDialog( editor._.storedDialogs.colordialog );
else
{
CKEDITOR.on( 'dialogDefinition', function( e )
{
if ( e.data.name != dialogName )
return;
var definition = e.data.definition;
e.removeListener();
definition.onLoad = CKEDITOR.tools.override( definition.onLoad, function( orginal )
{
return function()
{
bindToDialog( this );
definition.onLoad = orginal;
if ( typeof orginal == 'function' )
orginal.call( this );
};
});
});
}
}
function handleOther()
{
var dialog = this.getDialog(),
other = dialog.getContentElement( 'general', this.id + 'Other' );
if ( !other )
return;
if ( this.getValue() == 'other' )
{
other.getInputElement().removeAttribute( 'readOnly' );
other.focus();
other.getElement().removeClass( 'cke_disabled' );
}
else
{
other.getInputElement().setAttribute( 'readOnly', true );
other.getElement().addClass( 'cke_disabled' );
}
}
function commitMeta( name, isHttp, value )
{
return function( doc, html, head )
{
var hash = metaHash,
val = typeof value != 'undefined' ? value : this.getValue();
if ( !val && ( name in hash ) )
hash[ name ].remove();
else if ( val && ( name in hash ) )
hash[ name ].setAttribute( 'content', val );
else if ( val )
{
var meta = new CKEDITOR.dom.element( 'meta', editor.document );
meta.setAttribute( isHttp ? 'http-equiv' : 'name', name );
meta.setAttribute( 'content', val );
head.append( meta );
}
};
}
function setupMeta( name, ret )
{
return function()
{
var hash = metaHash,
result = ( name in hash ) ? hash[ name ].getAttribute( 'content' ) || '' : '';
if ( ret )
return result;
this.setValue( result );
return null;
};
}
function commitMargin( name )
{
return function( doc, html, head, body )
{
body.removeAttribute( 'margin' + name );
var val = this.getValue();
if ( val !== '' )
body.setStyle( 'margin-' + name, CKEDITOR.tools.cssLength( val ) );
else
body.removeStyle( 'margin-' + name );
};
}
function createMetaHash( doc )
{
var hash = {},
metas = doc.getElementsByTag( 'meta' ),
count = metas.count();
for ( var i = 0; i < count; i++ )
{
var meta = metas.getItem( i );
hash[ meta.getAttribute( meta.hasAttribute( 'http-equiv' ) ? 'http-equiv' : 'name' ).toLowerCase() ] = meta;
}
return hash;
}
// We cannot just remove the style from the element, as it might be affected from non-inline stylesheets.
// To get the proper result, we should manually set the inline style to its default value.
function resetStyle( element, prop, resetVal )
{
element.removeStyle( prop );
if ( element.getComputedStyle( prop ) != resetVal )
element.setStyle( prop, resetVal );
}
// Utilty to shorten the creation of color fields in the dialog.
var colorField = function( id, label, fieldProps )
{
return {
type : 'hbox',
padding : 0,
widths : [ '60%', '40%' ],
children : [
CKEDITOR.tools.extend( {
type : 'text',
id : id,
label : lang[ label ]
}, fieldProps || {}, 1 ),
{
type : 'button',
id : id + 'Choose',
label : lang.chooseColor,
className : 'colorChooser',
onClick : function()
{
var self = this;
getDialogValue( 'colordialog', function( colorDialog )
{
var dialog = self.getDialog();
dialog.getContentElement( dialog._.currentTabId, id ).setValue( colorDialog.getContentElement( 'picker', 'selectedColor' ).getValue() );
});
}
}
]
};
};
var previewSrc = 'javascript:' +
'void((function(){' +
encodeURIComponent(
'document.open();' +
( CKEDITOR.env.isCustomDomain() ? 'document.domain=\'' + document.domain + '\';' : '' ) +
'document.write( \'<html style="background-color: #ffffff; height: 100%"><head></head><body style="width: 100%; height: 100%; margin: 0px">' + lang.previewHtml + '</body></html>\' );' +
'document.close();'
) +
'})())';
return {
title : lang.title,
minHeight: 330,
minWidth: 500,
onShow : function()
{
var doc = editor.document,
html = doc.getElementsByTag( 'html' ).getItem( 0 ),
head = doc.getHead(),
body = doc.getBody();
metaHash = createMetaHash( doc );
this.setupContent( doc, html, head, body );
},
onHide : function()
{
metaHash = {};
},
onOk : function()
{
var doc = editor.document,
html = doc.getElementsByTag( 'html' ).getItem( 0 ),
head = doc.getHead(),
body = doc.getBody();
this.commitContent( doc, html, head, body );
},
contents : [
{
id : 'general',
label : langCommon.generalTab,
elements : [
{
type : 'text',
id : 'title',
label : lang.docTitle,
setup : function( doc )
{
this.setValue( doc.getElementsByTag( 'title' ).getItem( 0 ).data( 'cke-title' ) );
},
commit : function( doc, html, head, body, isPreview )
{
if ( isPreview )
return;
doc.getElementsByTag( 'title' ).getItem( 0 ).data( 'cke-title', this.getValue() );
}
},
{
type : 'hbox',
children : [
{
type : 'select',
id : 'dir',
label : langCommon.langDir,
style : 'width: 100%',
items : [
[ langCommon.notSet , '' ],
[ langCommon.langDirLtr, 'ltr' ],
[ langCommon.langDirRtl, 'rtl' ]
],
setup : function( doc, html, head, body )
{
this.setValue( body.getDirection() || '' );
},
commit : function( doc, html, head, body )
{
var val = this.getValue();
if ( val )
body.setAttribute( 'dir', val );
else
body.removeAttribute( 'dir' );
body.removeStyle( 'direction' );
}
},
{
type : 'text',
id : 'langCode',
label : langCommon.langCode,
setup : function( doc, html )
{
this.setValue( html.getAttribute( 'xml:lang' ) || html.getAttribute( 'lang' ) || '' );
},
commit : function( doc, html, head, body, isPreview )
{
if ( isPreview )
return;
var val = this.getValue();
if ( val )
html.setAttributes( { 'xml:lang' : val, lang : val } );
else
html.removeAttributes( { 'xml:lang' : 1, lang : 1 } );
}
}
]
},
{
type : 'hbox',
children : [
{
type : 'select',
id : 'charset',
label : lang.charset,
style : 'width: 100%',
items : [
[ langCommon.notSet, '' ],
[ lang.charsetASCII, 'us-ascii' ],
[ lang.charsetCE, 'iso-8859-2' ],
[ lang.charsetCT, 'big5' ],
[ lang.charsetCR, 'iso-8859-5' ],
[ lang.charsetGR, 'iso-8859-7' ],
[ lang.charsetJP, 'iso-2022-jp' ],
[ lang.charsetKR, 'iso-2022-kr' ],
[ lang.charsetTR, 'iso-8859-9' ],
[ lang.charsetUN, 'utf-8' ],
[ lang.charsetWE, 'iso-8859-1' ],
[ lang.other, 'other' ]
],
'default' : '',
onChange : function()
{
this.getDialog().selectedCharset = this.getValue() != 'other' ? this.getValue() : '';
handleOther.call( this );
},
setup : function()
{
this.metaCharset = ( 'charset' in metaHash );
var func = setupMeta( this.metaCharset ? 'charset' : 'content-type', 1, 1 ),
val = func.call( this );
!this.metaCharset && val.match( /charset=[^=]+$/ ) && ( val = val.substring( val.indexOf( '=' ) + 1 ) );
if ( val )
{
this.setValue( val.toLowerCase() );
if ( !this.getValue() )
{
this.setValue( 'other' );
var other = this.getDialog().getContentElement( 'general', 'charsetOther' );
other && other.setValue( val );
}
this.getDialog().selectedCharset = val;
}
handleOther.call( this );
},
commit : function( doc, html, head, body, isPreview )
{
if ( isPreview )
return;
var value = this.getValue(),
other = this.getDialog().getContentElement( 'general', 'charsetOther' );
value == 'other' && ( value = other ? other.getValue() : '' );
value && !this.metaCharset && ( value = ( metaHash[ 'content-type' ] ? metaHash[ 'content-type' ].getAttribute( 'content' ).split( ';' )[0] : 'text/html' ) + '; charset=' + value );
var func = commitMeta( this.metaCharset ? 'charset' : 'content-type', 1, value );
func.call( this, doc, html, head );
}
},
{
type : 'text',
id : 'charsetOther',
label : lang.charsetOther,
onChange : function(){ this.getDialog().selectedCharset = this.getValue(); }
}
]
},
{
type : 'hbox',
children : [
{
type : 'select',
id : 'docType',
label : lang.docType,
style : 'width: 100%',
items : [
[ langCommon.notSet , '' ],
[ 'XHTML 1.1', '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">' ],
[ 'XHTML 1.0 Transitional', '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' ],
[ 'XHTML 1.0 Strict', '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' ],
[ 'XHTML 1.0 Frameset', '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">' ],
[ 'HTML 5', '<!DOCTYPE html>' ],
[ 'HTML 4.01 Transitional', '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">' ],
[ 'HTML 4.01 Strict', '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">' ],
[ 'HTML 4.01 Frameset', '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">' ],
[ 'HTML 3.2', '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">' ],
[ 'HTML 2.0', '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">' ],
[ lang.other, 'other' ]
],
onChange : handleOther,
setup : function()
{
if ( editor.docType )
{
this.setValue( editor.docType );
if ( !this.getValue() )
{
this.setValue( 'other' );
var other = this.getDialog().getContentElement( 'general', 'docTypeOther' );
other && other.setValue( editor.docType );
}
}
handleOther.call( this );
},
commit : function( doc, html, head, body, isPreview )
{
if ( isPreview )
return;
var value = this.getValue(),
other = this.getDialog().getContentElement( 'general', 'docTypeOther' );
editor.docType = value == 'other' ? ( other ? other.getValue() : '' ) : value;
}
},
{
type : 'text',
id : 'docTypeOther',
label : lang.docTypeOther
}
]
},
{
type : 'checkbox',
id : 'xhtmlDec',
label : lang.xhtmlDec,
setup : function()
{
this.setValue( !!editor.xmlDeclaration );
},
commit : function( doc, html, head, body, isPreview )
{
if ( isPreview )
return;
if ( this.getValue() )
{
editor.xmlDeclaration = '<?xml version="1.0" encoding="' + ( this.getDialog().selectedCharset || 'utf-8' )+ '"?>' ;
html.setAttribute( 'xmlns', 'http://www.w3.org/1999/xhtml' );
}
else
{
editor.xmlDeclaration = '';
html.removeAttribute( 'xmlns' );
}
}
}
]
},
{
id : 'design',
label : lang.design,
elements : [
{
type : 'hbox',
widths : [ '60%', '40%' ],
children : [
{
type : 'vbox',
children : [
colorField( 'txtColor', 'txtColor',
{
setup : function( doc, html, head, body )
{
this.setValue( body.getComputedStyle( 'color' ) );
},
commit : function( doc, html, head, body, isPreview )
{
if ( this.isChanged() || isPreview )
{
body.removeAttribute( 'text' );
var val = this.getValue();
if ( val )
body.setStyle( 'color', val );
else
body.removeStyle( 'color' );
}
}
}),
colorField( 'bgColor', 'bgColor', {
setup : function( doc, html, head, body )
{
var val = body.getComputedStyle( 'background-color' ) || '';
this.setValue( val == 'transparent' ? '' : val );
},
commit : function( doc, html, head, body, isPreview )
{
if ( this.isChanged() || isPreview )
{
body.removeAttribute( 'bgcolor' );
var val = this.getValue();
if ( val )
body.setStyle( 'background-color', val );
else
resetStyle( body, 'background-color', 'transparent' );
}
}
}),
{
type : 'hbox',
widths : [ '60%', '40%' ],
padding : 1,
children : [
{
type : 'text',
id : 'bgImage',
label : lang.bgImage,
setup : function( doc, html, head, body )
{
var val = body.getComputedStyle( 'background-image' ) || '';
if ( val == 'none' )
val = '';
else
{
val = val.replace( /url\(\s*(["']?)\s*([^\)]*)\s*\1\s*\)/i, function( match, quote, url )
{
return url;
});
}
this.setValue( val );
},
commit : function( doc, html, head, body )
{
body.removeAttribute( 'background' );
var val = this.getValue();
if ( val )
body.setStyle( 'background-image', 'url(' + val + ')' );
else
resetStyle( body, 'background-image', 'none' );
}
},
{
type : 'button',
id : 'bgImageChoose',
label : langCommon.browseServer,
style : 'display:inline-block;margin-top:10px;',
hidden : true,
filebrowser : 'design:bgImage'
}
]
},
{
type : 'checkbox',
id : 'bgFixed',
label : lang.bgFixed,
setup : function( doc, html, head, body )
{
this.setValue( body.getComputedStyle( 'background-attachment' ) == 'fixed' );
},
commit : function( doc, html, head, body )
{
if ( this.getValue() )
body.setStyle( 'background-attachment', 'fixed' );
else
resetStyle( body, 'background-attachment', 'scroll' );
}
}
]
},
{
type : 'vbox',
children : [
{
type : 'html',
id : 'marginTitle',
html : '<div style="text-align: center; margin: 0px auto; font-weight: bold">' + lang.margin + '</div>'
},
{
type : 'text',
id : 'marginTop',
label : lang.marginTop,
style : 'width: 80px; text-align: center',
align : 'center',
inputStyle : 'text-align: center',
setup : function( doc, html, head, body )
{
this.setValue( body.getStyle( 'margin-top' ) || body.getAttribute( 'margintop' ) || '' );
},
commit : commitMargin( 'top' )
},
{
type : 'hbox',
children : [
{
type : 'text',
id : 'marginLeft',
label : lang.marginLeft,
style : 'width: 80px; text-align: center',
align : 'center',
inputStyle : 'text-align: center',
setup : function( doc, html, head, body )
{
this.setValue( body.getStyle( 'margin-left' ) || body.getAttribute( 'marginleft' ) || '' );
},
commit : commitMargin( 'left' )
},
{
type : 'text',
id : 'marginRight',
label : lang.marginRight,
style : 'width: 80px; text-align: center',
align : 'center',
inputStyle : 'text-align: center',
setup : function( doc, html, head, body )
{
this.setValue( body.getStyle( 'margin-right' ) || body.getAttribute( 'marginright' ) || '' );
},
commit : commitMargin( 'right' )
}
]
},
{
type : 'text',
id : 'marginBottom',
label : lang.marginBottom,
style : 'width: 80px; text-align: center',
align : 'center',
inputStyle : 'text-align: center',
setup : function( doc, html, head, body )
{
this.setValue( body.getStyle( 'margin-bottom' ) || body.getAttribute( 'marginbottom' ) || '' );
},
commit : commitMargin( 'bottom' )
}
]
}
]
}
]
},
{
id : 'meta',
label : lang.meta,
elements : [
{
type : 'textarea',
id : 'metaKeywords',
label : lang.metaKeywords,
setup : setupMeta( 'keywords' ),
commit : commitMeta( 'keywords' )
},
{
type : 'textarea',
id : 'metaDescription',
label : lang.metaDescription,
setup : setupMeta( 'description' ),
commit : commitMeta( 'description' )
},
{
type : 'text',
id : 'metaAuthor',
label : lang.metaAuthor,
setup : setupMeta( 'author' ),
commit : commitMeta( 'author' )
},
{
type : 'text',
id : 'metaCopyright',
label : lang.metaCopyright,
setup : setupMeta( 'copyright' ),
commit : commitMeta( 'copyright' )
}
]
},
{
id : 'preview',
label : langCommon.preview,
elements : [
{
type : 'html',
id : 'previewHtml',
html : '<iframe src="' + previewSrc + '" style="width: 100%; height: 310px" hidefocus="true" frameborder="0" ' +
'id="cke_docProps_preview_iframe"></iframe>',
onLoad : function()
{
this.getDialog().on( 'selectPage', function( ev )
{
if ( ev.data.page == 'preview' )
{
var self = this;
setTimeout( function()
{
var doc = CKEDITOR.document.getById( 'cke_docProps_preview_iframe' ).getFrameDocument(),
html = doc.getElementsByTag( 'html' ).getItem( 0 ),
head = doc.getHead(),
body = doc.getBody();
self.commitContent( doc, html, head, body, 1 );
}, 50 );
}
});
CKEDITOR.document.getById( 'cke_docProps_preview_iframe' ).getAscendant( 'table' ).setStyle( 'height', '100%' );
}
}
]
}
]
};
}); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/_source/plugins/docprops/dialogs/docprops.js | docprops.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.add( 'smiley',
{
requires : [ 'dialog' ],
init : function( editor )
{
editor.config.smiley_path = editor.config.smiley_path || ( this.path + 'images/' );
editor.addCommand( 'smiley', new CKEDITOR.dialogCommand( 'smiley' ) );
editor.ui.addButton( 'Smiley',
{
label : editor.lang.smiley.toolbar,
command : 'smiley'
});
CKEDITOR.dialog.add( 'smiley', this.path + 'dialogs/smiley.js' );
}
} );
/**
* The base path used to build the URL for the smiley images. It must end with
* a slash.
* @name CKEDITOR.config.smiley_path
* @type String
* @default <code><em>CKEDITOR.basePath</em> + 'plugins/smiley/images/'</code>
* @example
* config.smiley_path = 'http://www.example.com/images/smileys/';
* @example
* config.smiley_path = '/images/smileys/';
*/
/**
* The file names for the smileys to be displayed. These files must be
* contained inside the URL path defined with the
* {@link CKEDITOR.config.smiley_path} setting.
* @type Array
* @default (see example)
* @example
* // This is actually the default value.
* config.smiley_images = [
* 'regular_smile.gif','sad_smile.gif','wink_smile.gif','teeth_smile.gif','confused_smile.gif','tounge_smile.gif',
* 'embaressed_smile.gif','omg_smile.gif','whatchutalkingabout_smile.gif','angry_smile.gif','angel_smile.gif','shades_smile.gif',
* 'devil_smile.gif','cry_smile.gif','lightbulb.gif','thumbs_down.gif','thumbs_up.gif','heart.gif',
* 'broken_heart.gif','kiss.gif','envelope.gif'];
*/
CKEDITOR.config.smiley_images = [
'regular_smile.gif','sad_smile.gif','wink_smile.gif','teeth_smile.gif','confused_smile.gif','tounge_smile.gif',
'embaressed_smile.gif','omg_smile.gif','whatchutalkingabout_smile.gif','angry_smile.gif','angel_smile.gif','shades_smile.gif',
'devil_smile.gif','cry_smile.gif','lightbulb.gif','thumbs_down.gif','thumbs_up.gif','heart.gif',
'broken_heart.gif','kiss.gif','envelope.gif'];
/**
* The description to be used for each of the smileys defined in the
* {@link CKEDITOR.config.smiley_images} setting. Each entry in this array list
* must match its relative pair in the {@link CKEDITOR.config.smiley_images}
* setting.
* @type Array
* @default The textual descriptions of smiley.
* @example
* // Default settings.
* config.smiley_descriptions =
* [
* 'smiley', 'sad', 'wink', 'laugh', 'frown', 'cheeky', 'blush', 'surprise',
* 'indecision', 'angry', 'angel', 'cool', 'devil', 'crying', 'enlightened', 'no',
* 'yes', 'heart', 'broken heart', 'kiss', 'mail'
* ];
* @example
* // Use textual emoticons as description.
* config.smiley_descriptions =
* [
* ':)', ':(', ';)', ':D', ':/', ':P', ':*)', ':-o',
* ':|', '>:(', 'o:)', '8-)', '>:-)', ';(', '', '', '',
* '', '', ':-*', ''
* ];
*/
CKEDITOR.config.smiley_descriptions =
[
'smiley', 'sad', 'wink', 'laugh', 'frown', 'cheeky', 'blush', 'surprise',
'indecision', 'angry', 'angel', 'cool', 'devil', 'crying', 'enlightened', 'no',
'yes', 'heart', 'broken heart', 'kiss', 'mail'
];
/**
* The number of columns to be generated by the smilies matrix.
* @name CKEDITOR.config.smiley_columns
* @type Number
* @default 8
* @since 3.3.2
* @example
* config.smiley_columns = 6;
*/ | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/_source/plugins/smiley/plugin.js | plugin.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add( 'smiley', function( editor )
{
var config = editor.config,
lang = editor.lang.smiley,
images = config.smiley_images,
columns = config.smiley_columns || 8,
i;
/**
* Simulate "this" of a dialog for non-dialog events.
* @type {CKEDITOR.dialog}
*/
var dialog;
var onClick = function( evt )
{
var target = evt.data.getTarget(),
targetName = target.getName();
if ( targetName == 'a' )
target = target.getChild( 0 );
else if ( targetName != 'img' )
return;
var src = target.getAttribute( 'cke_src' ),
title = target.getAttribute( 'title' );
var img = editor.document.createElement( 'img',
{
attributes :
{
src : src,
'data-cke-saved-src' : src,
title : title,
alt : title,
width : target.$.width,
height : target.$.height
}
});
editor.insertElement( img );
dialog.hide();
evt.data.preventDefault();
};
var onKeydown = CKEDITOR.tools.addFunction( function( ev, element )
{
ev = new CKEDITOR.dom.event( ev );
element = new CKEDITOR.dom.element( element );
var relative, nodeToMove;
var keystroke = ev.getKeystroke(),
rtl = editor.lang.dir == 'rtl';
switch ( keystroke )
{
// UP-ARROW
case 38 :
// relative is TR
if ( ( relative = element.getParent().getParent().getPrevious() ) )
{
nodeToMove = relative.getChild( [element.getParent().getIndex(), 0] );
nodeToMove.focus();
}
ev.preventDefault();
break;
// DOWN-ARROW
case 40 :
// relative is TR
if ( ( relative = element.getParent().getParent().getNext() ) )
{
nodeToMove = relative.getChild( [element.getParent().getIndex(), 0] );
if ( nodeToMove )
nodeToMove.focus();
}
ev.preventDefault();
break;
// ENTER
// SPACE
case 32 :
onClick( { data: ev } );
ev.preventDefault();
break;
// RIGHT-ARROW
case rtl ? 37 : 39 :
// TAB
case 9 :
// relative is TD
if ( ( relative = element.getParent().getNext() ) )
{
nodeToMove = relative.getChild( 0 );
nodeToMove.focus();
ev.preventDefault(true);
}
// relative is TR
else if ( ( relative = element.getParent().getParent().getNext() ) )
{
nodeToMove = relative.getChild( [0, 0] );
if ( nodeToMove )
nodeToMove.focus();
ev.preventDefault(true);
}
break;
// LEFT-ARROW
case rtl ? 39 : 37 :
// SHIFT + TAB
case CKEDITOR.SHIFT + 9 :
// relative is TD
if ( ( relative = element.getParent().getPrevious() ) )
{
nodeToMove = relative.getChild( 0 );
nodeToMove.focus();
ev.preventDefault(true);
}
// relative is TR
else if ( ( relative = element.getParent().getParent().getPrevious() ) )
{
nodeToMove = relative.getLast().getChild( 0 );
nodeToMove.focus();
ev.preventDefault(true);
}
break;
default :
// Do not stop not handled events.
return;
}
});
// Build the HTML for the smiley images table.
var labelId = CKEDITOR.tools.getNextId() + '_smiley_emtions_label';
var html =
[
'<div>' +
'<span id="' + labelId + '" class="cke_voice_label">' + lang.options +'</span>',
'<table role="listbox" aria-labelledby="' + labelId + '" style="width:100%;height:100%" cellspacing="2" cellpadding="2"',
CKEDITOR.env.ie && CKEDITOR.env.quirks ? ' style="position:absolute;"' : '',
'><tbody>'
];
var size = images.length;
for ( i = 0 ; i < size ; i++ )
{
if ( i % columns === 0 )
html.push( '<tr>' );
var smileyLabelId = 'cke_smile_label_' + i + '_' + CKEDITOR.tools.getNextNumber();
html.push(
'<td class="cke_dark_background cke_centered" style="vertical-align: middle;">' +
'<a href="javascript:void(0)" role="option"',
' aria-posinset="' + ( i +1 ) + '"',
' aria-setsize="' + size + '"',
' aria-labelledby="' + smileyLabelId + '"',
' class="cke_smile cke_hand" tabindex="-1" onkeydown="CKEDITOR.tools.callFunction( ', onKeydown, ', event, this );">',
'<img class="cke_hand" title="', config.smiley_descriptions[i], '"' +
' cke_src="', CKEDITOR.tools.htmlEncode( config.smiley_path + images[ i ] ), '" alt="', config.smiley_descriptions[i], '"',
' src="', CKEDITOR.tools.htmlEncode( config.smiley_path + images[ i ] ), '"',
// IE BUG: Below is a workaround to an IE image loading bug to ensure the image sizes are correct.
( CKEDITOR.env.ie ? ' onload="this.setAttribute(\'width\', 2); this.removeAttribute(\'width\');" ' : '' ),
'>' +
'<span id="' + smileyLabelId + '" class="cke_voice_label">' +config.smiley_descriptions[ i ] + '</span>' +
'</a>',
'</td>' );
if ( i % columns == columns - 1 )
html.push( '</tr>' );
}
if ( i < columns - 1 )
{
for ( ; i < columns - 1 ; i++ )
html.push( '<td></td>' );
html.push( '</tr>' );
}
html.push( '</tbody></table></div>' );
var smileySelector =
{
type : 'html',
id : 'smileySelector',
html : html.join( '' ),
onLoad : function( event )
{
dialog = event.sender;
},
focus : function()
{
var self = this;
// IE need a while to move the focus (#6539).
setTimeout( function ()
{
var firstSmile = self.getElement().getElementsByTag( 'a' ).getItem( 0 );
firstSmile.focus();
}, 0 );
},
onClick : onClick,
style : 'width: 100%; border-collapse: separate;'
};
return {
title : editor.lang.smiley.title,
minWidth : 270,
minHeight : 120,
contents : [
{
id : 'tab1',
label : '',
title : '',
expand : true,
padding : 0,
elements : [
smileySelector
]
}
],
buttons : [ CKEDITOR.dialog.cancelButton ]
};
} ); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/_source/plugins/smiley/dialogs/smiley.js | smiley.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.add( 'button',
{
beforeInit : function( editor )
{
editor.ui.addHandler( CKEDITOR.UI_BUTTON, CKEDITOR.ui.button.handler );
}
});
/**
* Button UI element.
* @constant
* @example
*/
CKEDITOR.UI_BUTTON = 'button';
/**
* Represents a button UI element. This class should not be called directly. To
* create new buttons use {@link CKEDITOR.ui.prototype.addButton} instead.
* @constructor
* @param {Object} definition The button definition.
* @example
*/
CKEDITOR.ui.button = function( definition )
{
// Copy all definition properties to this object.
CKEDITOR.tools.extend( this, definition,
// Set defaults.
{
title : definition.label,
className : definition.className || ( definition.command && 'cke_button_' + definition.command ) || '',
click : definition.click || function( editor )
{
editor.execCommand( definition.command );
}
});
this._ = {};
};
/**
* Transforms a button definition in a {@link CKEDITOR.ui.button} instance.
* @type Object
* @example
*/
CKEDITOR.ui.button.handler =
{
create : function( definition )
{
return new CKEDITOR.ui.button( definition );
}
};
( function()
{
CKEDITOR.ui.button.prototype =
{
/**
* Renders the button.
* @param {CKEDITOR.editor} editor The editor instance which this button is
* to be used by.
* @param {Array} output The output array to which append the HTML relative
* to this button.
* @example
*/
render : function( editor, output )
{
var env = CKEDITOR.env,
id = this._.id = CKEDITOR.tools.getNextId(),
classes = '',
command = this.command, // Get the command name.
clickFn;
this._.editor = editor;
var instance =
{
id : id,
button : this,
editor : editor,
focus : function()
{
var element = CKEDITOR.document.getById( id );
element.focus();
},
execute : function()
{
// IE 6 needs some time before execution (#7922)
if ( CKEDITOR.env.ie && CKEDITOR.env.version < 7 )
CKEDITOR.tools.setTimeout( function(){ this.button.click( editor ); }, 0, this );
else
this.button.click( editor );
}
};
var keydownFn = CKEDITOR.tools.addFunction( function( ev )
{
if ( instance.onkey )
{
ev = new CKEDITOR.dom.event( ev );
return ( instance.onkey( instance, ev.getKeystroke() ) !== false );
}
});
var focusFn = CKEDITOR.tools.addFunction( function( ev )
{
var retVal;
if ( instance.onfocus )
retVal = ( instance.onfocus( instance, new CKEDITOR.dom.event( ev ) ) !== false );
// FF2: prevent focus event been bubbled up to editor container, which caused unexpected editor focus.
if ( CKEDITOR.env.gecko && CKEDITOR.env.version < 10900 )
ev.preventBubble();
return retVal;
});
instance.clickFn = clickFn = CKEDITOR.tools.addFunction( instance.execute, instance );
// Indicate a mode sensitive button.
if ( this.modes )
{
var modeStates = {};
function updateState()
{
// "this" is a CKEDITOR.ui.button instance.
var mode = editor.mode;
if ( mode )
{
// Restore saved button state.
var state = this.modes[ mode ] ? modeStates[ mode ] != undefined ? modeStates[ mode ] :
CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED;
this.setState( editor.readOnly && !this.readOnly ? CKEDITOR.TRISTATE_DISABLED : state );
}
}
editor.on( 'beforeModeUnload', function()
{
if ( editor.mode && this._.state != CKEDITOR.TRISTATE_DISABLED )
modeStates[ editor.mode ] = this._.state;
}, this );
editor.on( 'mode', updateState, this);
// If this button is sensitive to readOnly state, update it accordingly.
!this.readOnly && editor.on( 'readOnly', updateState, this);
}
else if ( command )
{
// Get the command instance.
command = editor.getCommand( command );
if ( command )
{
command.on( 'state', function()
{
this.setState( command.state );
}, this);
classes += 'cke_' + (
command.state == CKEDITOR.TRISTATE_ON ? 'on' :
command.state == CKEDITOR.TRISTATE_DISABLED ? 'disabled' :
'off' );
}
}
if ( !command )
classes += 'cke_off';
if ( this.className )
classes += ' ' + this.className;
output.push(
'<span class="cke_button' + ( this.icon && this.icon.indexOf( '.png' ) == -1 ? ' cke_noalphafix' : '' ) + '">',
'<a id="', id, '"' +
' class="', classes, '"',
env.gecko && env.version >= 10900 && !env.hc ? '' : '" href="javascript:void(\''+ ( this.title || '' ).replace( "'", '' )+ '\')"',
' title="', this.title, '"' +
' tabindex="-1"' +
' hidefocus="true"' +
' role="button"' +
' aria-labelledby="' + id + '_label"' +
( this.hasArrow ? ' aria-haspopup="true"' : '' ) );
// Some browsers don't cancel key events in the keydown but in the
// keypress.
// TODO: Check if really needed for Gecko+Mac.
if ( env.opera || ( env.gecko && env.mac ) )
{
output.push(
' onkeypress="return false;"' );
}
// With Firefox, we need to force the button to redraw, otherwise it
// will remain in the focus state.
if ( env.gecko )
{
output.push(
' onblur="this.style.cssText = this.style.cssText;"' );
}
output.push(
' onkeydown="return CKEDITOR.tools.callFunction(', keydownFn, ', event);"' +
' onfocus="return CKEDITOR.tools.callFunction(', focusFn,', event);" ' +
( CKEDITOR.env.ie ? 'onclick="return false;" onmouseup' : 'onclick' ) + // #188
'="CKEDITOR.tools.callFunction(', clickFn, ', this); return false;">' +
'<span class="cke_icon"' );
if ( this.icon )
{
var offset = ( this.iconOffset || 0 ) * -16;
output.push( ' style="background-image:url(', CKEDITOR.getUrl( this.icon ), ');background-position:0 ' + offset + 'px;"' );
}
output.push(
'> </span>' +
'<span id="', id, '_label" class="cke_label">', this.label, '</span>' );
if ( this.hasArrow )
{
output.push(
'<span class="cke_buttonarrow">'
// BLACK DOWN-POINTING TRIANGLE
+ ( CKEDITOR.env.hc ? '▼' : ' ' )
+ '</span>' );
}
output.push(
'</a>',
'</span>' );
if ( this.onRender )
this.onRender();
return instance;
},
setState : function( state )
{
if ( this._.state == state )
return false;
this._.state = state;
var element = CKEDITOR.document.getById( this._.id );
if ( element )
{
element.setState( state );
state == CKEDITOR.TRISTATE_DISABLED ?
element.setAttribute( 'aria-disabled', true ) :
element.removeAttribute( 'aria-disabled' );
state == CKEDITOR.TRISTATE_ON ?
element.setAttribute( 'aria-pressed', true ) :
element.removeAttribute( 'aria-pressed' );
return true;
}
else
return false;
}
};
})();
/**
* Adds a button definition to the UI elements list.
* @param {String} name The button name.
* @param {Object} definition The button definition.
* @example
* editorInstance.ui.addButton( 'MyBold',
* {
* label : 'My Bold',
* command : 'bold'
* });
*/
CKEDITOR.ui.prototype.addButton = function( name, definition )
{
this.add( name, CKEDITOR.UI_BUTTON, definition );
}; | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/_source/plugins/button/plugin.js | plugin.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
// #### checkSelectionChange : START
// The selection change check basically saves the element parent tree of
// the current node and check it on successive requests. If there is any
// change on the tree, then the selectionChange event gets fired.
function checkSelectionChange()
{
try
{
// In IE, the "selectionchange" event may still get thrown when
// releasing the WYSIWYG mode, so we need to check it first.
var sel = this.getSelection();
if ( !sel || !sel.document.getWindow().$ )
return;
var firstElement = sel.getStartElement();
var currentPath = new CKEDITOR.dom.elementPath( firstElement );
if ( !currentPath.compare( this._.selectionPreviousPath ) )
{
this._.selectionPreviousPath = currentPath;
this.fire( 'selectionChange', { selection : sel, path : currentPath, element : firstElement } );
}
}
catch (e)
{}
}
var checkSelectionChangeTimer,
checkSelectionChangeTimeoutPending;
function checkSelectionChangeTimeout()
{
// Firing the "OnSelectionChange" event on every key press started to
// be too slow. This function guarantees that there will be at least
// 200ms delay between selection checks.
checkSelectionChangeTimeoutPending = true;
if ( checkSelectionChangeTimer )
return;
checkSelectionChangeTimeoutExec.call( this );
checkSelectionChangeTimer = CKEDITOR.tools.setTimeout( checkSelectionChangeTimeoutExec, 200, this );
}
function checkSelectionChangeTimeoutExec()
{
checkSelectionChangeTimer = null;
if ( checkSelectionChangeTimeoutPending )
{
// Call this with a timeout so the browser properly moves the
// selection after the mouseup. It happened that the selection was
// being moved after the mouseup when clicking inside selected text
// with Firefox.
CKEDITOR.tools.setTimeout( checkSelectionChange, 0, this );
checkSelectionChangeTimeoutPending = false;
}
}
// #### checkSelectionChange : END
function rangeRequiresFix( range )
{
function isInlineCt( node )
{
return node && node.type == CKEDITOR.NODE_ELEMENT
&& node.getName() in CKEDITOR.dtd.$removeEmpty;
}
function singletonBlock( node )
{
var body = range.document.getBody();
return !node.is( 'body' ) && body.getChildCount() == 1;
}
var start = range.startContainer,
offset = range.startOffset;
if ( start.type == CKEDITOR.NODE_TEXT )
return false;
// 1. Empty inline element. <span>^</span>
// 2. Adjoin to inline element. <p><strong>text</strong>^</p>
// 3. The only empty block in document. <body><p>^</p></body> (#7222)
return !CKEDITOR.tools.trim( start.getHtml() ) ? isInlineCt( start ) || singletonBlock( start )
: isInlineCt( start.getChild( offset - 1 ) ) || isInlineCt( start.getChild( offset ) );
}
var selectAllCmd =
{
modes : { wysiwyg : 1, source : 1 },
readOnly : CKEDITOR.env.ie || CKEDITOR.env.webkit,
exec : function( editor )
{
switch ( editor.mode )
{
case 'wysiwyg' :
editor.document.$.execCommand( 'SelectAll', false, null );
// Force triggering selectionChange (#7008)
editor.forceNextSelectionCheck();
editor.selectionChange();
break;
case 'source' :
// Select the contents of the textarea
var textarea = editor.textarea.$;
if ( CKEDITOR.env.ie )
textarea.createTextRange().execCommand( 'SelectAll' );
else
{
textarea.selectionStart = 0;
textarea.selectionEnd = textarea.value.length;
}
textarea.focus();
}
},
canUndo : false
};
function createFillingChar( doc )
{
removeFillingChar( doc );
var fillingChar = doc.createText( '\u200B' );
doc.setCustomData( 'cke-fillingChar', fillingChar );
return fillingChar;
}
function getFillingChar( doc )
{
return doc && doc.getCustomData( 'cke-fillingChar' );
}
// Checks if a filling char has been used, eventualy removing it (#1272).
function checkFillingChar( doc )
{
var fillingChar = doc && getFillingChar( doc );
if ( fillingChar )
{
// Use this flag to avoid removing the filling char right after
// creating it.
if ( fillingChar.getCustomData( 'ready' ) )
removeFillingChar( doc );
else
fillingChar.setCustomData( 'ready', 1 );
}
}
function removeFillingChar( doc )
{
var fillingChar = doc && doc.removeCustomData( 'cke-fillingChar' );
if ( fillingChar )
{
// We can't simply remove the filling node because the user
// will actually enlarge it when typing, so we just remove the
// invisible char from it.
fillingChar.setText( fillingChar.getText().replace( /\u200B/g, '' ) );
fillingChar = 0;
}
}
CKEDITOR.plugins.add( 'selection',
{
init : function( editor )
{
// On WebKit only, we need a special "filling" char on some situations
// (#1272). Here we set the events that should invalidate that char.
if ( CKEDITOR.env.webkit )
{
editor.on( 'selectionChange', function() { checkFillingChar( editor.document ); } );
editor.on( 'beforeSetMode', function() { removeFillingChar( editor.document ); } );
editor.on( 'key', function( e )
{
// Remove the filling char before some keys get
// executed, so they'll not get blocked by it.
switch ( e.data.keyCode )
{
case 13 : // ENTER
case CKEDITOR.SHIFT + 13 : // SHIFT-ENTER
case 37 : // LEFT-ARROW
case 39 : // RIGHT-ARROW
case 8 : // BACKSPACE
removeFillingChar( editor.document );
}
}, null, null, 10 );
var fillingCharBefore,
resetSelection;
function beforeData()
{
var doc = editor.document,
fillingChar = getFillingChar( doc );
if ( fillingChar )
{
// If cursor is right blinking by side of the filler node, save it for restoring,
// as the following text substitution will blind it. (#7437)
var sel = doc.$.defaultView.getSelection();
if ( sel.type == 'Caret' && sel.anchorNode == fillingChar.$ )
resetSelection = 1;
fillingCharBefore = fillingChar.getText();
fillingChar.setText( fillingCharBefore.replace( /\u200B/g, '' ) );
}
}
function afterData()
{
var doc = editor.document,
fillingChar = getFillingChar( doc );
if ( fillingChar )
{
fillingChar.setText( fillingCharBefore );
if ( resetSelection )
{
doc.$.defaultView.getSelection().setPosition( fillingChar.$,fillingChar.getLength() );
resetSelection = 0;
}
}
}
editor.on( 'beforeUndoImage', beforeData );
editor.on( 'afterUndoImage', afterData );
editor.on( 'beforeGetData', beforeData, null, null, 0 );
editor.on( 'getData', afterData );
}
editor.on( 'contentDom', function()
{
var doc = editor.document,
body = doc.getBody(),
html = doc.getDocumentElement();
if ( CKEDITOR.env.ie )
{
// Other browsers don't loose the selection if the
// editor document loose the focus. In IE, we don't
// have support for it, so we reproduce it here, other
// than firing the selection change event.
var savedRange,
saveEnabled,
restoreEnabled = 1;
// "onfocusin" is fired before "onfocus". It makes it
// possible to restore the selection before click
// events get executed.
body.on( 'focusin', function( evt )
{
// If there are elements with layout they fire this event but
// it must be ignored to allow edit its contents #4682
if ( evt.data.$.srcElement.nodeName != 'BODY' )
return;
// If we have saved a range, restore it at this
// point.
if ( savedRange )
{
if ( restoreEnabled )
{
// Well not break because of this.
try
{
savedRange.select();
}
catch (e)
{}
// Update locked selection because of the normalized text nodes. (#6083, #6987)
var lockedSelection = doc.getCustomData( 'cke_locked_selection' );
if ( lockedSelection )
{
lockedSelection.unlock();
lockedSelection.lock();
}
}
savedRange = null;
}
});
body.on( 'focus', function()
{
// Enable selections to be saved.
saveEnabled = 1;
saveSelection();
});
body.on( 'beforedeactivate', function( evt )
{
// Ignore this event if it's caused by focus switch between
// internal editable control type elements, e.g. layouted paragraph. (#4682)
if ( evt.data.$.toElement )
return;
// Disable selections from being saved.
saveEnabled = 0;
restoreEnabled = 1;
});
// IE before version 8 will leave cursor blinking inside the document after
// editor blurred unless we clean up the selection. (#4716)
if ( CKEDITOR.env.ie && CKEDITOR.env.version < 8 )
{
editor.on( 'blur', function( evt )
{
// Try/Catch to avoid errors if the editor is hidden. (#6375)
try
{
editor.document && editor.document.$.selection.empty();
}
catch (e) {}
});
}
// Listening on document element ensures that
// scrollbar is included. (#5280)
html.on( 'mousedown', function()
{
// Lock restore selection now, as we have
// a followed 'click' event which introduce
// new selection. (#5735)
restoreEnabled = 0;
});
html.on( 'mouseup', function()
{
restoreEnabled = 1;
});
// In IE6/7 the blinking cursor appears, but contents are
// not editable. (#5634)
if ( CKEDITOR.env.ie && ( CKEDITOR.env.ie7Compat || CKEDITOR.env.version < 8 || CKEDITOR.env.quirks ) )
{
// The 'click' event is not fired when clicking the
// scrollbars, so we can use it to check whether
// the empty space following <body> has been clicked.
html.on( 'click', function( evt )
{
if ( evt.data.getTarget().getName() == 'html' )
editor.getSelection().getRanges()[ 0 ].select();
});
}
var scroll;
// IE fires the "selectionchange" event when clicking
// inside a selection. We don't want to capture that.
body.on( 'mousedown', function( evt )
{
// IE scrolls document to top on right mousedown
// when editor has no focus, remember this scroll
// position and revert it before context menu opens. (#5778)
if ( evt.data.$.button == 2 )
{
var sel = editor.document.$.selection;
if ( sel.type == 'None' )
scroll = editor.window.getScrollPosition();
}
disableSave();
});
body.on( 'mouseup',
function( evt )
{
// Restore recorded scroll position when needed on right mouseup.
if ( evt.data.$.button == 2 && scroll )
{
editor.document.$.documentElement.scrollLeft = scroll.x;
editor.document.$.documentElement.scrollTop = scroll.y;
}
scroll = null;
saveEnabled = 1;
setTimeout( function()
{
saveSelection( true );
},
0 );
});
body.on( 'keydown', disableSave );
body.on( 'keyup',
function()
{
saveEnabled = 1;
saveSelection();
});
// IE is the only to provide the "selectionchange"
// event.
doc.on( 'selectionchange', saveSelection );
function disableSave()
{
saveEnabled = 0;
}
function saveSelection( testIt )
{
if ( saveEnabled )
{
var doc = editor.document,
sel = editor.getSelection(),
nativeSel = sel && sel.getNative();
// There is a very specific case, when clicking
// inside a text selection. In that case, the
// selection collapses at the clicking point,
// but the selection object remains in an
// unknown state, making createRange return a
// range at the very start of the document. In
// such situation we have to test the range, to
// be sure it's valid.
if ( testIt && nativeSel && nativeSel.type == 'None' )
{
// The "InsertImage" command can be used to
// test whether the selection is good or not.
// If not, it's enough to give some time to
// IE to put things in order for us.
if ( !doc.$.queryCommandEnabled( 'InsertImage' ) )
{
CKEDITOR.tools.setTimeout( saveSelection, 50, this, true );
return;
}
}
// Avoid saving selection from within text input. (#5747)
var parentTag;
if ( nativeSel && nativeSel.type && nativeSel.type != 'Control'
&& ( parentTag = nativeSel.createRange() )
&& ( parentTag = parentTag.parentElement() )
&& ( parentTag = parentTag.nodeName )
&& parentTag.toLowerCase() in { input: 1, textarea : 1 } )
{
return;
}
savedRange = nativeSel && sel.getRanges()[ 0 ];
checkSelectionChangeTimeout.call( editor );
}
}
}
else
{
// In other browsers, we make the selection change
// check based on other events, like clicks or keys
// press.
doc.on( 'mouseup', checkSelectionChangeTimeout, editor );
doc.on( 'keyup', checkSelectionChangeTimeout, editor );
doc.on( 'selectionchange', checkSelectionChangeTimeout, editor );
}
});
// Clear the cached range path before unload. (#7174)
editor.on( 'contentDomUnload', editor.forceNextSelectionCheck, editor );
editor.addCommand( 'selectAll', selectAllCmd );
editor.ui.addButton( 'SelectAll',
{
label : editor.lang.selectAll,
command : 'selectAll'
});
editor.selectionChange = checkSelectionChangeTimeout;
// IE9 might cease to work if there's an object selection inside the iframe (#7639).
CKEDITOR.env.ie9Compat && editor.on( 'destroy', function()
{
var sel = editor.getSelection();
sel && sel.getNative().clear();
}, null, null, 9 );
}
});
/**
* Gets the current selection from the editing area when in WYSIWYG mode.
* @returns {CKEDITOR.dom.selection} A selection object or null if not in
* WYSIWYG mode or no selection is available.
* @example
* var selection = CKEDITOR.instances.editor1.<strong>getSelection()</strong>;
* alert( selection.getType() );
*/
CKEDITOR.editor.prototype.getSelection = function()
{
return this.document && this.document.getSelection();
};
CKEDITOR.editor.prototype.forceNextSelectionCheck = function()
{
delete this._.selectionPreviousPath;
};
/**
* Gets the current selection from the document.
* @returns {CKEDITOR.dom.selection} A selection object.
* @example
* var selection = CKEDITOR.instances.editor1.document.<strong>getSelection()</strong>;
* alert( selection.getType() );
*/
CKEDITOR.dom.document.prototype.getSelection = function()
{
var sel = new CKEDITOR.dom.selection( this );
return ( !sel || sel.isInvalid ) ? null : sel;
};
/**
* No selection.
* @constant
* @example
* if ( editor.getSelection().getType() == CKEDITOR.SELECTION_NONE )
* alert( 'Nothing is selected' );
*/
CKEDITOR.SELECTION_NONE = 1;
/**
* A text or a collapsed selection.
* @constant
* @example
* if ( editor.getSelection().getType() == CKEDITOR.SELECTION_TEXT )
* alert( 'A text is selected' );
*/
CKEDITOR.SELECTION_TEXT = 2;
/**
* Element selection.
* @constant
* @example
* if ( editor.getSelection().getType() == CKEDITOR.SELECTION_ELEMENT )
* alert( 'An element is selected' );
*/
CKEDITOR.SELECTION_ELEMENT = 3;
/**
* Manipulates the selection in a DOM document.
* @constructor
* @param {CKEDITOR.dom.document} document The DOM document that contains the selection.
* @example
* var sel = new <strong>CKEDITOR.dom.selection( CKEDITOR.document )</strong>;
*/
CKEDITOR.dom.selection = function( document )
{
var lockedSelection = document.getCustomData( 'cke_locked_selection' );
if ( lockedSelection )
return lockedSelection;
this.document = document;
this.isLocked = 0;
this._ =
{
cache : {}
};
/**
* IE BUG: The selection's document may be a different document than the
* editor document. Return null if that is the case.
*/
if ( CKEDITOR.env.ie )
{
var range = this.getNative().createRange();
if ( !range
|| ( range.item && range.item(0).ownerDocument != this.document.$ )
|| ( range.parentElement && range.parentElement().ownerDocument != this.document.$ ) )
{
this.isInvalid = true;
}
}
return this;
};
var styleObjectElements =
{
img:1,hr:1,li:1,table:1,tr:1,td:1,th:1,embed:1,object:1,ol:1,ul:1,
a:1,input:1,form:1,select:1,textarea:1,button:1,fieldset:1,thead:1,tfoot:1
};
CKEDITOR.dom.selection.prototype =
{
/**
* Gets the native selection object from the browser.
* @function
* @returns {Object} The native browser selection object.
* @example
* var selection = editor.getSelection().<strong>getNative()</strong>;
*/
getNative :
CKEDITOR.env.ie ?
function()
{
return this._.cache.nativeSel || ( this._.cache.nativeSel = this.document.$.selection );
}
:
function()
{
return this._.cache.nativeSel || ( this._.cache.nativeSel = this.document.getWindow().$.getSelection() );
},
/**
* Gets the type of the current selection. The following values are
* available:
* <ul>
* <li><code>{@link CKEDITOR.SELECTION_NONE}</code> (1): No selection.</li>
* <li><code>{@link CKEDITOR.SELECTION_TEXT}</code> (2): A text or a collapsed
* selection is selected.</li>
* <li><code>{@link CKEDITOR.SELECTION_ELEMENT}</code> (3): An element is
* selected.</li>
* </ul>
* @function
* @returns {Number} One of the following constant values:
* <code>{@link CKEDITOR.SELECTION_NONE}</code>, <code>{@link CKEDITOR.SELECTION_TEXT}</code>, or
* <code>{@link CKEDITOR.SELECTION_ELEMENT}</code>.
* @example
* if ( editor.getSelection().<strong>getType()</strong> == CKEDITOR.SELECTION_TEXT )
* alert( 'A text is selected' );
*/
getType :
CKEDITOR.env.ie ?
function()
{
var cache = this._.cache;
if ( cache.type )
return cache.type;
var type = CKEDITOR.SELECTION_NONE;
try
{
var sel = this.getNative(),
ieType = sel.type;
if ( ieType == 'Text' )
type = CKEDITOR.SELECTION_TEXT;
if ( ieType == 'Control' )
type = CKEDITOR.SELECTION_ELEMENT;
// It is possible that we can still get a text range
// object even when type == 'None' is returned by IE.
// So we'd better check the object returned by
// createRange() rather than by looking at the type.
if ( sel.createRange().parentElement )
type = CKEDITOR.SELECTION_TEXT;
}
catch(e) {}
return ( cache.type = type );
}
:
function()
{
var cache = this._.cache;
if ( cache.type )
return cache.type;
var type = CKEDITOR.SELECTION_TEXT;
var sel = this.getNative();
if ( !sel )
type = CKEDITOR.SELECTION_NONE;
else if ( sel.rangeCount == 1 )
{
// Check if the actual selection is a control (IMG,
// TABLE, HR, etc...).
var range = sel.getRangeAt(0),
startContainer = range.startContainer;
if ( startContainer == range.endContainer
&& startContainer.nodeType == 1
&& ( range.endOffset - range.startOffset ) == 1
&& styleObjectElements[ startContainer.childNodes[ range.startOffset ].nodeName.toLowerCase() ] )
{
type = CKEDITOR.SELECTION_ELEMENT;
}
}
return ( cache.type = type );
},
/**
* Retrieves the <code>{@link CKEDITOR.dom.range}</code> instances that represent the current selection.
* Note: Some browsers return multiple ranges even for a continuous selection. Firefox, for example, returns
* one range for each table cell when one or more table rows are selected.
* @function
* @param {Boolean} [onlyEditables] If set to <code>true</code>, this function retrives editable ranges only.
* @return {Array} Range instances that represent the current selection.
* @example
* var ranges = selection.<strong>getRanges()</strong>;
* alert( ranges.length );
*/
getRanges : (function()
{
var func = CKEDITOR.env.ie ?
( function()
{
function getNodeIndex( node ) { return new CKEDITOR.dom.node( node ).getIndex(); }
// Finds the container and offset for a specific boundary
// of an IE range.
var getBoundaryInformation = function( range, start )
{
// Creates a collapsed range at the requested boundary.
range = range.duplicate();
range.collapse( start );
// Gets the element that encloses the range entirely.
var parent = range.parentElement(),
doc = parent.ownerDocument;
// Empty parent element, e.g. <i>^</i>
if ( !parent.hasChildNodes() )
return { container : parent, offset : 0 };
var siblings = parent.children,
child,
sibling,
testRange = range.duplicate(),
startIndex = 0,
endIndex = siblings.length - 1,
index = -1,
position,
distance;
// Binary search over all element childs to test the range to see whether
// range is right on the boundary of one element.
while ( startIndex <= endIndex )
{
index = Math.floor( ( startIndex + endIndex ) / 2 );
child = siblings[ index ];
testRange.moveToElementText( child );
position = testRange.compareEndPoints( 'StartToStart', range );
if ( position > 0 )
endIndex = index - 1;
else if ( position < 0 )
startIndex = index + 1;
else
{
// IE9 report wrong measurement with compareEndPoints when range anchors between two BRs.
// e.g. <p>text<br />^<br /></p> (#7433)
if ( CKEDITOR.env.ie9Compat && child.tagName == 'BR' )
{
var bmId = 'cke_range_marker';
range.execCommand( 'CreateBookmark', false, bmId );
child = doc.getElementsByName( bmId )[ 0 ];
var offset = getNodeIndex( child );
parent.removeChild( child );
return { container : parent, offset : offset };
}
else
return { container : parent, offset : getNodeIndex( child ) };
}
}
// All childs are text nodes,
// or to the right hand of test range are all text nodes. (#6992)
if ( index == -1 || index == siblings.length - 1 && position < 0 )
{
// Adapt test range to embrace the entire parent contents.
testRange.moveToElementText( parent );
testRange.setEndPoint( 'StartToStart', range );
// IE report line break as CRLF with range.text but
// only LF with textnode.nodeValue, normalize them to avoid
// breaking character counting logic below. (#3949)
distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length;
siblings = parent.childNodes;
// Actual range anchor right beside test range at the boundary of text node.
if ( !distance )
{
child = siblings[ siblings.length - 1 ];
if ( child.nodeType == CKEDITOR.NODE_ELEMENT )
return { container : parent, offset : siblings.length };
else
return { container : child, offset : child.nodeValue.length };
}
// Start the measuring until distance overflows, meanwhile count the text nodes.
var i = siblings.length;
while ( distance > 0 )
distance -= siblings[ --i ].nodeValue.length;
return { container : siblings[ i ], offset : -distance };
}
// Test range was one offset beyond OR behind the anchored text node.
else
{
// Adapt one side of test range to the actual range
// for measuring the offset between them.
testRange.collapse( position > 0 ? true : false );
testRange.setEndPoint( position > 0 ? 'StartToStart' : 'EndToStart', range );
// IE report line break as CRLF with range.text but
// only LF with textnode.nodeValue, normalize them to avoid
// breaking character counting logic below. (#3949)
distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length;
// Actual range anchor right beside test range at the inner boundary of text node.
if ( !distance )
return { container : parent, offset : getNodeIndex( child ) + ( position > 0 ? 0 : 1 ) };
// Start the measuring until distance overflows, meanwhile count the text nodes.
while ( distance > 0 )
{
try
{
sibling = child[ position > 0 ? 'previousSibling' : 'nextSibling' ];
distance -= sibling.nodeValue.length;
child = sibling;
}
// Measurement in IE could be somtimes wrong because of <select> element. (#4611)
catch( e )
{
return { container : parent, offset : getNodeIndex( child ) };
}
}
return { container : child, offset : position > 0 ? -distance : child.nodeValue.length + distance };
}
};
return function()
{
// IE doesn't have range support (in the W3C way), so we
// need to do some magic to transform selections into
// CKEDITOR.dom.range instances.
var sel = this.getNative(),
nativeRange = sel && sel.createRange(),
type = this.getType(),
range;
if ( !sel )
return [];
if ( type == CKEDITOR.SELECTION_TEXT )
{
range = new CKEDITOR.dom.range( this.document );
var boundaryInfo = getBoundaryInformation( nativeRange, true );
range.setStart( new CKEDITOR.dom.node( boundaryInfo.container ), boundaryInfo.offset );
boundaryInfo = getBoundaryInformation( nativeRange );
range.setEnd( new CKEDITOR.dom.node( boundaryInfo.container ), boundaryInfo.offset );
// Correct an invalid IE range case on empty list item. (#5850)
if ( range.endContainer.getPosition( range.startContainer ) & CKEDITOR.POSITION_PRECEDING
&& range.endOffset <= range.startContainer.getIndex() )
{
range.collapse();
}
return [ range ];
}
else if ( type == CKEDITOR.SELECTION_ELEMENT )
{
var retval = [];
for ( var i = 0 ; i < nativeRange.length ; i++ )
{
var element = nativeRange.item( i ),
parentElement = element.parentNode,
j = 0;
range = new CKEDITOR.dom.range( this.document );
for (; j < parentElement.childNodes.length && parentElement.childNodes[j] != element ; j++ )
{ /*jsl:pass*/ }
range.setStart( new CKEDITOR.dom.node( parentElement ), j );
range.setEnd( new CKEDITOR.dom.node( parentElement ), j + 1 );
retval.push( range );
}
return retval;
}
return [];
};
})()
:
function()
{
// On browsers implementing the W3C range, we simply
// tranform the native ranges in CKEDITOR.dom.range
// instances.
var ranges = [],
range,
doc = this.document,
sel = this.getNative();
if ( !sel )
return ranges;
// On WebKit, it may happen that we'll have no selection
// available. We normalize it here by replicating the
// behavior of other browsers.
if ( !sel.rangeCount )
{
range = new CKEDITOR.dom.range( doc );
range.moveToElementEditStart( doc.getBody() );
ranges.push( range );
}
for ( var i = 0 ; i < sel.rangeCount ; i++ )
{
var nativeRange = sel.getRangeAt( i );
range = new CKEDITOR.dom.range( doc );
range.setStart( new CKEDITOR.dom.node( nativeRange.startContainer ), nativeRange.startOffset );
range.setEnd( new CKEDITOR.dom.node( nativeRange.endContainer ), nativeRange.endOffset );
ranges.push( range );
}
return ranges;
};
return function( onlyEditables )
{
var cache = this._.cache;
if ( cache.ranges && !onlyEditables )
return cache.ranges;
else if ( !cache.ranges )
cache.ranges = new CKEDITOR.dom.rangeList( func.call( this ) );
// Split range into multiple by read-only nodes.
if ( onlyEditables )
{
var ranges = cache.ranges;
for ( var i = 0; i < ranges.length; i++ )
{
var range = ranges[ i ];
// Drop range spans inside one ready-only node.
var parent = range.getCommonAncestor();
if ( parent.isReadOnly() )
ranges.splice( i, 1 );
if ( range.collapsed )
continue;
// Range may start inside a non-editable element,
// replace the range start after it.
if ( range.startContainer.isReadOnly() )
{
var current = range.startContainer;
while( current )
{
if ( current.is( 'body' ) || !current.isReadOnly() )
break;
if ( current.type == CKEDITOR.NODE_ELEMENT
&& current.getAttribute( 'contentEditable' ) == 'false' )
range.setStartAfter( current );
current = current.getParent();
}
}
var startContainer = range.startContainer,
endContainer = range.endContainer,
startOffset = range.startOffset,
endOffset = range.endOffset,
walkerRange = range.clone();
// Enlarge range start/end with text node to avoid walker
// being DOM destructive, it doesn't interfere our checking
// of elements below as well.
if ( startContainer && startContainer.type == CKEDITOR.NODE_TEXT )
{
if ( startOffset >= startContainer.getLength() )
walkerRange.setStartAfter( startContainer );
else
walkerRange.setStartBefore( startContainer );
}
if ( endContainer && endContainer.type == CKEDITOR.NODE_TEXT )
{
if ( !endOffset )
walkerRange.setEndBefore( endContainer );
else
walkerRange.setEndAfter( endContainer );
}
// Looking for non-editable element inside the range.
var walker = new CKEDITOR.dom.walker( walkerRange );
walker.evaluator = function( node )
{
if ( node.type == CKEDITOR.NODE_ELEMENT
&& node.isReadOnly() )
{
var newRange = range.clone();
range.setEndBefore( node );
// Drop collapsed range around read-only elements,
// it make sure the range list empty when selecting
// only non-editable elements.
if ( range.collapsed )
ranges.splice( i--, 1 );
// Avoid creating invalid range.
if ( !( node.getPosition( walkerRange.endContainer ) & CKEDITOR.POSITION_CONTAINS ) )
{
newRange.setStartAfter( node );
if ( !newRange.collapsed )
ranges.splice( i + 1, 0, newRange );
}
return true;
}
return false;
};
walker.next();
}
}
return cache.ranges;
};
})(),
/**
* Gets the DOM element in which the selection starts.
* @returns {CKEDITOR.dom.element} The element at the beginning of the
* selection.
* @example
* var element = editor.getSelection().<strong>getStartElement()</strong>;
* alert( element.getName() );
*/
getStartElement : function()
{
var cache = this._.cache;
if ( cache.startElement !== undefined )
return cache.startElement;
var node,
sel = this.getNative();
switch ( this.getType() )
{
case CKEDITOR.SELECTION_ELEMENT :
return this.getSelectedElement();
case CKEDITOR.SELECTION_TEXT :
var range = this.getRanges()[0];
if ( range )
{
if ( !range.collapsed )
{
range.optimize();
// Decrease the range content to exclude particial
// selected node on the start which doesn't have
// visual impact. ( #3231 )
while ( 1 )
{
var startContainer = range.startContainer,
startOffset = range.startOffset;
// Limit the fix only to non-block elements.(#3950)
if ( startOffset == ( startContainer.getChildCount ?
startContainer.getChildCount() : startContainer.getLength() )
&& !startContainer.isBlockBoundary() )
range.setStartAfter( startContainer );
else break;
}
node = range.startContainer;
if ( node.type != CKEDITOR.NODE_ELEMENT )
return node.getParent();
node = node.getChild( range.startOffset );
if ( !node || node.type != CKEDITOR.NODE_ELEMENT )
node = range.startContainer;
else
{
var child = node.getFirst();
while ( child && child.type == CKEDITOR.NODE_ELEMENT )
{
node = child;
child = child.getFirst();
}
}
}
else
{
node = range.startContainer;
if ( node.type != CKEDITOR.NODE_ELEMENT )
node = node.getParent();
}
node = node.$;
}
}
return cache.startElement = ( node ? new CKEDITOR.dom.element( node ) : null );
},
/**
* Gets the currently selected element.
* @returns {CKEDITOR.dom.element} The selected element. Null if no
* selection is available or the selection type is not
* <code>{@link CKEDITOR.SELECTION_ELEMENT}</code>.
* @example
* var element = editor.getSelection().<strong>getSelectedElement()</strong>;
* alert( element.getName() );
*/
getSelectedElement : function()
{
var cache = this._.cache;
if ( cache.selectedElement !== undefined )
return cache.selectedElement;
var self = this;
var node = CKEDITOR.tools.tryThese(
// Is it native IE control type selection?
function()
{
return self.getNative().createRange().item( 0 );
},
// If a table or list is fully selected.
function()
{
var root,
retval,
range = self.getRanges()[ 0 ],
ancestor = range.getCommonAncestor( 1, 1 ),
tags = { table:1,ul:1,ol:1,dl:1 };
for ( var t in tags )
{
if ( root = ancestor.getAscendant( t, 1 ) )
break;
}
if ( root )
{
// Enlarging the start boundary.
var testRange = new CKEDITOR.dom.range( this.document );
testRange.setStartAt( root, CKEDITOR.POSITION_AFTER_START );
testRange.setEnd( range.startContainer, range.startOffset );
var enlargeables = CKEDITOR.tools.extend( tags, CKEDITOR.dtd.$listItem, CKEDITOR.dtd.$tableContent ),
walker = new CKEDITOR.dom.walker( testRange ),
// Check the range is at the inner boundary of the structural element.
guard = function( walker, isEnd )
{
return function( node, isWalkOut )
{
if ( node.type == CKEDITOR.NODE_TEXT && ( !CKEDITOR.tools.trim( node.getText() ) || node.getParent().data( 'cke-bookmark' ) ) )
return true;
var tag;
if ( node.type == CKEDITOR.NODE_ELEMENT )
{
tag = node.getName();
// Bypass bogus br at the end of block.
if ( tag == 'br' && isEnd && node.equals( node.getParent().getBogus() ) )
return true;
if ( isWalkOut && tag in enlargeables || tag in CKEDITOR.dtd.$removeEmpty )
return true;
}
walker.halted = 1;
return false;
};
};
walker.guard = guard( walker );
if ( walker.checkBackward() && !walker.halted )
{
walker = new CKEDITOR.dom.walker( testRange );
testRange.setStart( range.endContainer, range.endOffset );
testRange.setEndAt( root, CKEDITOR.POSITION_BEFORE_END );
walker.guard = guard( walker, 1 );
if ( walker.checkForward() && !walker.halted )
retval = root.$;
}
}
if ( !retval )
throw 0;
return retval;
},
// Figure it out by checking if there's a single enclosed
// node of the range.
function()
{
var range = self.getRanges()[ 0 ],
enclosed,
selected;
// Check first any enclosed element, e.g. <ul>[<li><a href="#">item</a></li>]</ul>
for ( var i = 2; i && !( ( enclosed = range.getEnclosedNode() )
&& ( enclosed.type == CKEDITOR.NODE_ELEMENT )
&& styleObjectElements[ enclosed.getName() ]
&& ( selected = enclosed ) ); i-- )
{
// Then check any deep wrapped element, e.g. [<b><i><img /></i></b>]
range.shrink( CKEDITOR.SHRINK_ELEMENT );
}
return selected.$;
});
return cache.selectedElement = ( node ? new CKEDITOR.dom.element( node ) : null );
},
/**
* Retrieves the text contained within the range. An empty string is returned for non-text selection.
* @returns {String} A string of text within the current selection.
* @since 3.6.1
* @example
* var text = editor.getSelection().<strong>getSelectedText()</strong>;
* alert( text );
*/
getSelectedText : function()
{
var cache = this._.cache;
if ( cache.selectedText !== undefined )
return cache.selectedText;
var text = '',
nativeSel = this.getNative();
if ( this.getType() == CKEDITOR.SELECTION_TEXT )
text = CKEDITOR.env.ie ? nativeSel.createRange().text : nativeSel.toString();
return ( cache.selectedText = text );
},
/**
* Locks the selection made in the editor in order to make it possible to
* manipulate it without browser interference. A locked selection is
* cached and remains unchanged until it is released with the <code>#unlock</code>
* method.
* @example
* editor.getSelection().<strong>lock()</strong>;
*/
lock : function()
{
// Call all cacheable function.
this.getRanges();
this.getStartElement();
this.getSelectedElement();
this.getSelectedText();
// The native selection is not available when locked.
this._.cache.nativeSel = {};
this.isLocked = 1;
// Save this selection inside the DOM document.
this.document.setCustomData( 'cke_locked_selection', this );
},
/**
* Unlocks the selection made in the editor and locked with the <code>#lock</code> method.
* An unlocked selection is no longer cached and can be changed.
* @param {Boolean} [restore] If set to <code>true</code>, the selection is restored back to the selection saved earlier by using the <code>#lock</code> method.
* @example
* editor.getSelection().<strong>unlock()</strong>;
*/
unlock : function( restore )
{
var doc = this.document,
lockedSelection = doc.getCustomData( 'cke_locked_selection' );
if ( lockedSelection )
{
doc.setCustomData( 'cke_locked_selection', null );
if ( restore )
{
var selectedElement = lockedSelection.getSelectedElement(),
ranges = !selectedElement && lockedSelection.getRanges();
this.isLocked = 0;
this.reset();
doc.getBody().focus();
if ( selectedElement )
this.selectElement( selectedElement );
else
this.selectRanges( ranges );
}
}
if ( !lockedSelection || !restore )
{
this.isLocked = 0;
this.reset();
}
},
/**
* Clears the selection cache.
* @example
* editor.getSelection().<strong>reset()</strong>;
*/
reset : function()
{
this._.cache = {};
},
/**
* Makes the current selection of type <code>{@link CKEDITOR.SELECTION_ELEMENT}</code> by enclosing the specified element.
* @param {CKEDITOR.dom.element} element The element to enclose in the selection.
* @example
* var element = editor.document.getById( 'sampleElement' );
* editor.getSelection.<strong>selectElement( element )</strong>;
*/
selectElement : function( element )
{
if ( this.isLocked )
{
var range = new CKEDITOR.dom.range( this.document );
range.setStartBefore( element );
range.setEndAfter( element );
this._.cache.selectedElement = element;
this._.cache.startElement = element;
this._.cache.ranges = new CKEDITOR.dom.rangeList( range );
this._.cache.type = CKEDITOR.SELECTION_ELEMENT;
return;
}
range = new CKEDITOR.dom.range( element.getDocument() );
range.setStartBefore( element );
range.setEndAfter( element );
range.select();
this.document.fire( 'selectionchange' );
this.reset();
},
/**
* Clears the original selection and adds the specified ranges
* to the document selection.
* @param {Array} ranges An array of <code>{@link CKEDITOR.dom.range}</code> instances representing ranges to be added to the document.
* @example
* var ranges = new CKEDITOR.dom.range( editor.document );
* editor.getSelection().<strong>selectRanges( [ ranges ] )</strong>;
*/
selectRanges : function( ranges )
{
if ( this.isLocked )
{
this._.cache.selectedElement = null;
this._.cache.startElement = ranges[ 0 ] && ranges[ 0 ].getTouchedStartNode();
this._.cache.ranges = new CKEDITOR.dom.rangeList( ranges );
this._.cache.type = CKEDITOR.SELECTION_TEXT;
return;
}
if ( CKEDITOR.env.ie )
{
if ( ranges.length > 1 )
{
// IE doesn't accept multiple ranges selection, so we join all into one.
var last = ranges[ ranges.length -1 ] ;
ranges[ 0 ].setEnd( last.endContainer, last.endOffset );
ranges.length = 1;
}
if ( ranges[ 0 ] )
ranges[ 0 ].select();
this.reset();
}
else
{
var sel = this.getNative();
// getNative() returns null if iframe is "display:none" in FF. (#6577)
if ( !sel )
return;
if ( ranges.length )
{
sel.removeAllRanges();
// Remove any existing filling char first.
CKEDITOR.env.webkit && removeFillingChar( this.document );
}
for ( var i = 0 ; i < ranges.length ; i++ )
{
// Joining sequential ranges introduced by
// readonly elements protection.
if ( i < ranges.length -1 )
{
var left = ranges[ i ], right = ranges[ i +1 ],
between = left.clone();
between.setStart( left.endContainer, left.endOffset );
between.setEnd( right.startContainer, right.startOffset );
// Don't confused by Firefox adjancent multi-ranges
// introduced by table cells selection.
if ( !between.collapsed )
{
between.shrink( CKEDITOR.NODE_ELEMENT, true );
var ancestor = between.getCommonAncestor(),
enclosed = between.getEnclosedNode();
// The following cases has to be considered:
// 1. <span contenteditable="false">[placeholder]</span>
// 2. <input contenteditable="false" type="radio"/> (#6621)
if ( ancestor.isReadOnly() || enclosed && enclosed.isReadOnly() )
{
right.setStart( left.startContainer, left.startOffset );
ranges.splice( i--, 1 );
continue;
}
}
}
var range = ranges[ i ];
var nativeRange = this.document.$.createRange();
var startContainer = range.startContainer;
// In FF2, if we have a collapsed range, inside an empty
// element, we must add something to it otherwise the caret
// will not be visible.
// In Opera instead, the selection will be moved out of the
// element. (#4657)
if ( range.collapsed &&
( CKEDITOR.env.opera || ( CKEDITOR.env.gecko && CKEDITOR.env.version < 10900 ) ) &&
startContainer.type == CKEDITOR.NODE_ELEMENT &&
!startContainer.getChildCount() )
{
startContainer.appendText( '' );
}
if ( range.collapsed
&& CKEDITOR.env.webkit
&& rangeRequiresFix( range ) )
{
// Append a zero-width space so WebKit will not try to
// move the selection by itself (#1272).
var fillingChar = createFillingChar( this.document );
range.insertNode( fillingChar ) ;
var next = fillingChar.getNext();
// If the filling char is followed by a <br>, whithout
// having something before it, it'll not blink.
// Let's remove it in this case.
if ( next && !fillingChar.getPrevious() && next.type == CKEDITOR.NODE_ELEMENT && next.getName() == 'br' )
{
removeFillingChar( this.document );
range.moveToPosition( next, CKEDITOR.POSITION_BEFORE_START );
}
else
range.moveToPosition( fillingChar, CKEDITOR.POSITION_AFTER_END );
}
nativeRange.setStart( range.startContainer.$, range.startOffset );
try
{
nativeRange.setEnd( range.endContainer.$, range.endOffset );
}
catch ( e )
{
// There is a bug in Firefox implementation (it would be too easy
// otherwise). The new start can't be after the end (W3C says it can).
// So, let's create a new range and collapse it to the desired point.
if ( e.toString().indexOf( 'NS_ERROR_ILLEGAL_VALUE' ) >= 0 )
{
range.collapse( 1 );
nativeRange.setEnd( range.endContainer.$, range.endOffset );
}
else
throw e;
}
// Select the range.
sel.addRange( nativeRange );
}
// Don't miss selection change event for non-IEs.
this.document.fire( 'selectionchange' );
this.reset();
}
},
/**
* Creates a bookmark for each range of this selection (from <code>#getRanges</code>)
* by calling the <code>{@link CKEDITOR.dom.range.prototype.createBookmark}</code> method,
* with extra care taken to avoid interference among those ranges. The arguments
* received are the same as with the underlying range method.
* @returns {Array} Array of bookmarks for each range.
* @example
* var bookmarks = editor.getSelection().<strong>createBookmarks()</strong>;
*/
createBookmarks : function( serializable )
{
return this.getRanges().createBookmarks( serializable );
},
/**
* Creates a bookmark for each range of this selection (from <code>#getRanges</code>)
* by calling the <code>{@link CKEDITOR.dom.range.prototype.createBookmark2}</code> method,
* with extra care taken to avoid interference among those ranges. The arguments
* received are the same as with the underlying range method.
* @returns {Array} Array of bookmarks for each range.
* @example
* var bookmarks = editor.getSelection().<strong>createBookmarks2()</strong>;
*/
createBookmarks2 : function( normalized )
{
return this.getRanges().createBookmarks2( normalized );
},
/**
* Selects the virtual ranges denoted by the bookmarks by calling <code>#selectRanges</code>.
* @param {Array} bookmarks The bookmarks representing ranges to be selected.
* @returns {CKEDITOR.dom.selection} This selection object, after the ranges were selected.
* @example
* var bookmarks = editor.getSelection().createBookmarks();
* editor.getSelection().<strong>selectBookmarks( bookmarks )</strong>;
*/
selectBookmarks : function( bookmarks )
{
var ranges = [];
for ( var i = 0 ; i < bookmarks.length ; i++ )
{
var range = new CKEDITOR.dom.range( this.document );
range.moveToBookmark( bookmarks[i] );
ranges.push( range );
}
this.selectRanges( ranges );
return this;
},
/**
* Retrieves the common ancestor node of the first range and the last range.
* @returns {CKEDITOR.dom.element} The common ancestor of the selection.
* @example
* var ancestor = editor.getSelection().<strong>getCommonAncestor()</strong>;
*/
getCommonAncestor : function()
{
var ranges = this.getRanges(),
startNode = ranges[ 0 ].startContainer,
endNode = ranges[ ranges.length - 1 ].endContainer;
return startNode.getCommonAncestor( endNode );
},
/**
* Moves the scrollbar to the starting position of the current selection.
* @example
* editor.getSelection().<strong>scrollIntoView()</strong>;
*/
scrollIntoView : function()
{
// If we have split the block, adds a temporary span at the
// range position and scroll relatively to it.
var start = this.getStartElement();
start.scrollIntoView();
}
};
})();
( function()
{
var notWhitespaces = CKEDITOR.dom.walker.whitespaces( true ),
fillerTextRegex = /\ufeff|\u00a0/,
nonCells = { table:1,tbody:1,tr:1 };
CKEDITOR.dom.range.prototype.select =
CKEDITOR.env.ie ?
// V2
function( forceExpand )
{
var collapsed = this.collapsed,
isStartMarkerAlone, dummySpan, ieRange;
// Try to make a object selection.
var selected = this.getEnclosedNode();
if ( selected )
{
try
{
ieRange = this.document.$.body.createControlRange();
ieRange.addElement( selected.$ );
ieRange.select();
return;
}
catch( er ) {}
}
// IE doesn't support selecting the entire table row/cell, move the selection into cells, e.g.
// <table><tbody><tr>[<td>cell</b></td>... => <table><tbody><tr><td>[cell</td>...
if ( this.startContainer.type == CKEDITOR.NODE_ELEMENT && this.startContainer.getName() in nonCells
|| this.endContainer.type == CKEDITOR.NODE_ELEMENT && this.endContainer.getName() in nonCells )
{
this.shrink( CKEDITOR.NODE_ELEMENT, true );
}
var bookmark = this.createBookmark();
// Create marker tags for the start and end boundaries.
var startNode = bookmark.startNode;
var endNode;
if ( !collapsed )
endNode = bookmark.endNode;
// Create the main range which will be used for the selection.
ieRange = this.document.$.body.createTextRange();
// Position the range at the start boundary.
ieRange.moveToElementText( startNode.$ );
ieRange.moveStart( 'character', 1 );
if ( endNode )
{
// Create a tool range for the end.
var ieRangeEnd = this.document.$.body.createTextRange();
// Position the tool range at the end.
ieRangeEnd.moveToElementText( endNode.$ );
// Move the end boundary of the main range to match the tool range.
ieRange.setEndPoint( 'EndToEnd', ieRangeEnd );
ieRange.moveEnd( 'character', -1 );
}
else
{
// The isStartMarkerAlone logic comes from V2. It guarantees that the lines
// will expand and that the cursor will be blinking on the right place.
// Actually, we are using this flag just to avoid using this hack in all
// situations, but just on those needed.
var next = startNode.getNext( notWhitespaces );
isStartMarkerAlone = ( !( next && next.getText && next.getText().match( fillerTextRegex ) ) // already a filler there?
&& ( forceExpand || !startNode.hasPrevious() || ( startNode.getPrevious().is && startNode.getPrevious().is( 'br' ) ) ) );
// Append a temporary <span></span> before the selection.
// This is needed to avoid IE destroying selections inside empty
// inline elements, like <b></b> (#253).
// It is also needed when placing the selection right after an inline
// element to avoid the selection moving inside of it.
dummySpan = this.document.createElement( 'span' );
dummySpan.setHtml( '' ); // Zero Width No-Break Space (U+FEFF). See #1359.
dummySpan.insertBefore( startNode );
if ( isStartMarkerAlone )
{
// To expand empty blocks or line spaces after <br>, we need
// instead to have any char, which will be later deleted using the
// selection.
// \ufeff = Zero Width No-Break Space (U+FEFF). (#1359)
this.document.createText( '\ufeff' ).insertBefore( startNode );
}
}
// Remove the markers (reset the position, because of the changes in the DOM tree).
this.setStartBefore( startNode );
startNode.remove();
if ( collapsed )
{
if ( isStartMarkerAlone )
{
// Move the selection start to include the temporary \ufeff.
ieRange.moveStart( 'character', -1 );
ieRange.select();
// Remove our temporary stuff.
this.document.$.selection.clear();
}
else
ieRange.select();
this.moveToPosition( dummySpan, CKEDITOR.POSITION_BEFORE_START );
dummySpan.remove();
}
else
{
this.setEndBefore( endNode );
endNode.remove();
ieRange.select();
}
this.document.fire( 'selectionchange' );
}
:
function()
{
this.document.getSelection().selectRanges( [ this ] );
};
} )(); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/_source/plugins/selection/plugin.js | plugin.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Undo/Redo system for saving shapshot for document modification
* and other recordable changes.
*/
(function()
{
CKEDITOR.plugins.add( 'undo',
{
requires : [ 'selection', 'wysiwygarea' ],
init : function( editor )
{
var undoManager = new UndoManager( editor );
var undoCommand = editor.addCommand( 'undo',
{
exec : function()
{
if ( undoManager.undo() )
{
editor.selectionChange();
this.fire( 'afterUndo' );
}
},
state : CKEDITOR.TRISTATE_DISABLED,
canUndo : false
});
var redoCommand = editor.addCommand( 'redo',
{
exec : function()
{
if ( undoManager.redo() )
{
editor.selectionChange();
this.fire( 'afterRedo' );
}
},
state : CKEDITOR.TRISTATE_DISABLED,
canUndo : false
});
undoManager.onChange = function()
{
undoCommand.setState( undoManager.undoable() ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED );
redoCommand.setState( undoManager.redoable() ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED );
};
function recordCommand( event )
{
// If the command hasn't been marked to not support undo.
if ( undoManager.enabled && event.data.command.canUndo !== false )
undoManager.save();
}
// We'll save snapshots before and after executing a command.
editor.on( 'beforeCommandExec', recordCommand );
editor.on( 'afterCommandExec', recordCommand );
// Save snapshots before doing custom changes.
editor.on( 'saveSnapshot', function( evt )
{
undoManager.save( evt.data && evt.data.contentOnly );
});
// Registering keydown on every document recreation.(#3844)
editor.on( 'contentDom', function()
{
editor.document.on( 'keydown', function( event )
{
// Do not capture CTRL hotkeys.
if ( !event.data.$.ctrlKey && !event.data.$.metaKey )
undoManager.type( event );
});
});
// Always save an undo snapshot - the previous mode might have
// changed editor contents.
editor.on( 'beforeModeUnload', function()
{
editor.mode == 'wysiwyg' && undoManager.save( true );
});
// Make the undo manager available only in wysiwyg mode.
editor.on( 'mode', function()
{
undoManager.enabled = editor.readOnly ? false : editor.mode == 'wysiwyg';
undoManager.onChange();
});
editor.ui.addButton( 'Undo',
{
label : editor.lang.undo,
command : 'undo'
});
editor.ui.addButton( 'Redo',
{
label : editor.lang.redo,
command : 'redo'
});
editor.resetUndo = function()
{
// Reset the undo stack.
undoManager.reset();
// Create the first image.
editor.fire( 'saveSnapshot' );
};
/**
* Amend the top of undo stack (last undo image) with the current DOM changes.
* @name CKEDITOR.editor#updateUndo
* @example
* function()
* {
* editor.fire( 'saveSnapshot' );
* editor.document.body.append(...);
* // Make new changes following the last undo snapshot part of it.
* editor.fire( 'updateSnapshot' );
* ...
* }
*/
editor.on( 'updateSnapshot', function()
{
if ( undoManager.currentImage )
undoManager.update();
});
}
});
CKEDITOR.plugins.undo = {};
/**
* Undo snapshot which represents the current document status.
* @name CKEDITOR.plugins.undo.Image
* @param editor The editor instance on which the image is created.
*/
var Image = CKEDITOR.plugins.undo.Image = function( editor )
{
this.editor = editor;
editor.fire( 'beforeUndoImage' );
var contents = editor.getSnapshot(),
selection = contents && editor.getSelection();
// In IE, we need to remove the expando attributes.
CKEDITOR.env.ie && contents && ( contents = contents.replace( /\s+data-cke-expando=".*?"/g, '' ) );
this.contents = contents;
this.bookmarks = selection && selection.createBookmarks2( true );
editor.fire( 'afterUndoImage' );
};
// Attributes that browser may changing them when setting via innerHTML.
var protectedAttrs = /\b(?:href|src|name)="[^"]*?"/gi;
Image.prototype =
{
equals : function( otherImage, contentOnly )
{
var thisContents = this.contents,
otherContents = otherImage.contents;
// For IE6/7 : Comparing only the protected attribute values but not the original ones.(#4522)
if ( CKEDITOR.env.ie && ( CKEDITOR.env.ie7Compat || CKEDITOR.env.ie6Compat ) )
{
thisContents = thisContents.replace( protectedAttrs, '' );
otherContents = otherContents.replace( protectedAttrs, '' );
}
if ( thisContents != otherContents )
return false;
if ( contentOnly )
return true;
var bookmarksA = this.bookmarks,
bookmarksB = otherImage.bookmarks;
if ( bookmarksA || bookmarksB )
{
if ( !bookmarksA || !bookmarksB || bookmarksA.length != bookmarksB.length )
return false;
for ( var i = 0 ; i < bookmarksA.length ; i++ )
{
var bookmarkA = bookmarksA[ i ],
bookmarkB = bookmarksB[ i ];
if (
bookmarkA.startOffset != bookmarkB.startOffset ||
bookmarkA.endOffset != bookmarkB.endOffset ||
!CKEDITOR.tools.arrayCompare( bookmarkA.start, bookmarkB.start ) ||
!CKEDITOR.tools.arrayCompare( bookmarkA.end, bookmarkB.end ) )
{
return false;
}
}
}
return true;
}
};
/**
* @constructor Main logic for Redo/Undo feature.
*/
function UndoManager( editor )
{
this.editor = editor;
// Reset the undo stack.
this.reset();
}
var editingKeyCodes = { /*Backspace*/ 8:1, /*Delete*/ 46:1 },
modifierKeyCodes = { /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1 },
navigationKeyCodes = { 37:1, 38:1, 39:1, 40:1 }; // Arrows: L, T, R, B
UndoManager.prototype =
{
/**
* Process undo system regard keystrikes.
* @param {CKEDITOR.dom.event} event
*/
type : function( event )
{
var keystroke = event && event.data.getKey(),
isModifierKey = keystroke in modifierKeyCodes,
isEditingKey = keystroke in editingKeyCodes,
wasEditingKey = this.lastKeystroke in editingKeyCodes,
sameAsLastEditingKey = isEditingKey && keystroke == this.lastKeystroke,
// Keystrokes which navigation through contents.
isReset = keystroke in navigationKeyCodes,
wasReset = this.lastKeystroke in navigationKeyCodes,
// Keystrokes which just introduce new contents.
isContent = ( !isEditingKey && !isReset ),
// Create undo snap for every different modifier key.
modifierSnapshot = ( isEditingKey && !sameAsLastEditingKey ),
// Create undo snap on the following cases:
// 1. Just start to type .
// 2. Typing some content after a modifier.
// 3. Typing some content after make a visible selection.
startedTyping = !( isModifierKey || this.typing )
|| ( isContent && ( wasEditingKey || wasReset ) );
if ( startedTyping || modifierSnapshot )
{
var beforeTypeImage = new Image( this.editor );
// Use setTimeout, so we give the necessary time to the
// browser to insert the character into the DOM.
CKEDITOR.tools.setTimeout( function()
{
var currentSnapshot = this.editor.getSnapshot();
// In IE, we need to remove the expando attributes.
if ( CKEDITOR.env.ie )
currentSnapshot = currentSnapshot.replace( /\s+data-cke-expando=".*?"/g, '' );
if ( beforeTypeImage.contents != currentSnapshot )
{
// It's safe to now indicate typing state.
this.typing = true;
// This's a special save, with specified snapshot
// and without auto 'fireChange'.
if ( !this.save( false, beforeTypeImage, false ) )
// Drop future snapshots.
this.snapshots.splice( this.index + 1, this.snapshots.length - this.index - 1 );
this.hasUndo = true;
this.hasRedo = false;
this.typesCount = 1;
this.modifiersCount = 1;
this.onChange();
}
},
0, this
);
}
this.lastKeystroke = keystroke;
// Create undo snap after typed too much (over 25 times).
if ( isEditingKey )
{
this.typesCount = 0;
this.modifiersCount++;
if ( this.modifiersCount > 25 )
{
this.save( false, null, false );
this.modifiersCount = 1;
}
}
else if ( !isReset )
{
this.modifiersCount = 0;
this.typesCount++;
if ( this.typesCount > 25 )
{
this.save( false, null, false );
this.typesCount = 1;
}
}
},
reset : function() // Reset the undo stack.
{
/**
* Remember last pressed key.
*/
this.lastKeystroke = 0;
/**
* Stack for all the undo and redo snapshots, they're always created/removed
* in consistency.
*/
this.snapshots = [];
/**
* Current snapshot history index.
*/
this.index = -1;
this.limit = this.editor.config.undoStackSize || 20;
this.currentImage = null;
this.hasUndo = false;
this.hasRedo = false;
this.resetType();
},
/**
* Reset all states about typing.
* @see UndoManager.type
*/
resetType : function()
{
this.typing = false;
delete this.lastKeystroke;
this.typesCount = 0;
this.modifiersCount = 0;
},
fireChange : function()
{
this.hasUndo = !!this.getNextImage( true );
this.hasRedo = !!this.getNextImage( false );
// Reset typing
this.resetType();
this.onChange();
},
/**
* Save a snapshot of document image for later retrieve.
*/
save : function( onContentOnly, image, autoFireChange )
{
var snapshots = this.snapshots;
// Get a content image.
if ( !image )
image = new Image( this.editor );
// Do nothing if it was not possible to retrieve an image.
if ( image.contents === false )
return false;
// Check if this is a duplicate. In such case, do nothing.
if ( this.currentImage && image.equals( this.currentImage, onContentOnly ) )
return false;
// Drop future snapshots.
snapshots.splice( this.index + 1, snapshots.length - this.index - 1 );
// If we have reached the limit, remove the oldest one.
if ( snapshots.length == this.limit )
snapshots.shift();
// Add the new image, updating the current index.
this.index = snapshots.push( image ) - 1;
this.currentImage = image;
if ( autoFireChange !== false )
this.fireChange();
return true;
},
restoreImage : function( image )
{
this.editor.loadSnapshot( image.contents );
if ( image.bookmarks )
this.editor.getSelection().selectBookmarks( image.bookmarks );
else if ( CKEDITOR.env.ie )
{
// IE BUG: If I don't set the selection to *somewhere* after setting
// document contents, then IE would create an empty paragraph at the bottom
// the next time the document is modified.
var $range = this.editor.document.getBody().$.createTextRange();
$range.collapse( true );
$range.select();
}
this.index = image.index;
// Update current image with the actual editor
// content, since actualy content may differ from
// the original snapshot due to dom change. (#4622)
this.update();
this.fireChange();
},
// Get the closest available image.
getNextImage : function( isUndo )
{
var snapshots = this.snapshots,
currentImage = this.currentImage,
image, i;
if ( currentImage )
{
if ( isUndo )
{
for ( i = this.index - 1 ; i >= 0 ; i-- )
{
image = snapshots[ i ];
if ( !currentImage.equals( image, true ) )
{
image.index = i;
return image;
}
}
}
else
{
for ( i = this.index + 1 ; i < snapshots.length ; i++ )
{
image = snapshots[ i ];
if ( !currentImage.equals( image, true ) )
{
image.index = i;
return image;
}
}
}
}
return null;
},
/**
* Check the current redo state.
* @return {Boolean} Whether the document has previous state to
* retrieve.
*/
redoable : function()
{
return this.enabled && this.hasRedo;
},
/**
* Check the current undo state.
* @return {Boolean} Whether the document has future state to restore.
*/
undoable : function()
{
return this.enabled && this.hasUndo;
},
/**
* Perform undo on current index.
*/
undo : function()
{
if ( this.undoable() )
{
this.save( true );
var image = this.getNextImage( true );
if ( image )
return this.restoreImage( image ), true;
}
return false;
},
/**
* Perform redo on current index.
*/
redo : function()
{
if ( this.redoable() )
{
// Try to save. If no changes have been made, the redo stack
// will not change, so it will still be redoable.
this.save( true );
// If instead we had changes, we can't redo anymore.
if ( this.redoable() )
{
var image = this.getNextImage( false );
if ( image )
return this.restoreImage( image ), true;
}
}
return false;
},
/**
* Update the last snapshot of the undo stack with the current editor content.
*/
update : function()
{
this.snapshots.splice( this.index, 1, ( this.currentImage = new Image( this.editor ) ) );
}
};
})();
/**
* The number of undo steps to be saved. The higher this setting value the more
* memory is used for it.
* @name CKEDITOR.config.undoStackSize
* @type Number
* @default 20
* @example
* config.undoStackSize = 50;
*/
/**
* Fired when the editor is about to save an undo snapshot. This event can be
* fired by plugins and customizations to make the editor saving undo snapshots.
* @name CKEDITOR.editor#saveSnapshot
* @event
*/
/**
* Fired before an undo image is to be taken. An undo image represents the
* editor state at some point. It's saved into an undo store, so the editor is
* able to recover the editor state on undo and redo operations.
* @name CKEDITOR.editor#beforeUndoImage
* @since 3.5.3
* @see CKEDITOR.editor#afterUndoImage
* @event
*/
/**
* Fired after an undo image is taken. An undo image represents the
* editor state at some point. It's saved into an undo store, so the editor is
* able to recover the editor state on undo and redo operations.
* @name CKEDITOR.editor#afterUndoImage
* @since 3.5.3
* @see CKEDITOR.editor#beforeUndoImage
* @event
*/ | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/_source/plugins/undo/plugin.js | plugin.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @file Special Character plugin
*/
CKEDITOR.plugins.add( 'specialchar',
{
// List of available localizations.
availableLangs : { en:1 },
init : function( editor )
{
var pluginName = 'specialchar',
plugin = this;
// Register the dialog.
CKEDITOR.dialog.add( pluginName, this.path + 'dialogs/specialchar.js' );
editor.addCommand( pluginName,
{
exec : function()
{
var langCode = editor.langCode;
langCode = plugin.availableLangs[ langCode ] ? langCode : 'en';
CKEDITOR.scriptLoader.load(
CKEDITOR.getUrl( plugin.path + 'lang/' + langCode + '.js' ),
function()
{
CKEDITOR.tools.extend( editor.lang.specialChar, plugin.langEntries[ langCode ] );
editor.openDialog( pluginName );
});
},
modes : { wysiwyg:1 },
canUndo : false
});
// Register the toolbar button.
editor.ui.addButton( 'SpecialChar',
{
label : editor.lang.specialChar.toolbar,
command : pluginName
});
}
} );
/**
* The list of special characters visible in the Special Character dialog window.
* @type Array
* @example
* config.specialChars = [ '"', '’', [ '&custom;', 'Custom label' ] ];
* config.specialChars = config.specialChars.concat( [ '"', [ '’', 'Custom label' ] ] );
*/
CKEDITOR.config.specialChars =
[
'!','"','#','$','%','&',"'",'(',')','*','+','-','.','/',
'0','1','2','3','4','5','6','7','8','9',':',';',
'<','=','>','?','@',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O',
'P','Q','R','S','T','U','V','W','X','Y','Z',
'[',']','^','_','`',
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p',
'q','r','s','t','u','v','w','x','y','z',
'{','|','}','~',
"€", "‘", "’", "“", "”", "–", "—", "¡", "¢", "£", "¤", "¥", "¦", "§", "¨", "©", "ª", "«", "¬", "®", "¯", "°", "²", "³", "´", "µ", "¶", "·", "¸", "¹", "º", "»", "¼", "½", "¾", "¿", "À", "Á", "Â", "Ã", "Ä", "Å", "Æ", "Ç", "È", "É", "Ê", "Ë", "Ì", "Í", "Î", "Ï", "Ð", "Ñ", "Ò", "Ó", "Ô", "Õ", "Ö", "×", "Ø", "Ù", "Ú", "Û", "Ü", "Ý", "Þ", "ß", "à", "á", "â", "ã", "ä", "å", "æ", "ç", "è", "é", "ê", "ë", "ì", "í", "î", "ï", "ð", "ñ", "ò", "ó", "ô", "õ", "ö", "÷", "ø", "ù", "ú", "û", "ü", "ý", "þ", "ÿ", "Œ", "œ", "Ŵ", "Ŷ", "ŵ", "ŷ", "‚", "‛", "„", "…", "™", "►", "•", "→", "⇒", "⇔", "♦", "≈"
]; | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/_source/plugins/specialchar/plugin.js | plugin.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add( 'specialchar', function( editor )
{
/**
* Simulate "this" of a dialog for non-dialog events.
* @type {CKEDITOR.dialog}
*/
var dialog,
lang = editor.lang.specialChar;
var onChoice = function( evt )
{
var target, value;
if ( evt.data )
target = evt.data.getTarget();
else
target = new CKEDITOR.dom.element( evt );
if ( target.getName() == 'a' && ( value = target.getChild( 0 ).getHtml() ) )
{
target.removeClass( "cke_light_background" );
dialog.hide();
// We must use "insertText" here to keep text styled.
var span = editor.document.createElement( 'span' );
span.setHtml( value );
editor.insertText( span.getText() );
}
};
var onClick = CKEDITOR.tools.addFunction( onChoice );
var focusedNode;
var onFocus = function( evt, target )
{
var value;
target = target || evt.data.getTarget();
if ( target.getName() == 'span' )
target = target.getParent();
if ( target.getName() == 'a' && ( value = target.getChild( 0 ).getHtml() ) )
{
// Trigger blur manually if there is focused node.
if ( focusedNode )
onBlur( null, focusedNode );
var htmlPreview = dialog.getContentElement( 'info', 'htmlPreview' ).getElement();
dialog.getContentElement( 'info', 'charPreview' ).getElement().setHtml( value );
htmlPreview.setHtml( CKEDITOR.tools.htmlEncode( value ) );
target.getParent().addClass( "cke_light_background" );
// Memorize focused node.
focusedNode = target;
}
};
var onBlur = function( evt, target )
{
target = target || evt.data.getTarget();
if ( target.getName() == 'span' )
target = target.getParent();
if ( target.getName() == 'a' )
{
dialog.getContentElement( 'info', 'charPreview' ).getElement().setHtml( ' ' );
dialog.getContentElement( 'info', 'htmlPreview' ).getElement().setHtml( ' ' );
target.getParent().removeClass( "cke_light_background" );
focusedNode = undefined;
}
};
var onKeydown = CKEDITOR.tools.addFunction( function( ev )
{
ev = new CKEDITOR.dom.event( ev );
// Get an Anchor element.
var element = ev.getTarget();
var relative, nodeToMove;
var keystroke = ev.getKeystroke(),
rtl = editor.lang.dir == 'rtl';
switch ( keystroke )
{
// UP-ARROW
case 38 :
// relative is TR
if ( ( relative = element.getParent().getParent().getPrevious() ) )
{
nodeToMove = relative.getChild( [element.getParent().getIndex(), 0] );
nodeToMove.focus();
onBlur( null, element );
onFocus( null, nodeToMove );
}
ev.preventDefault();
break;
// DOWN-ARROW
case 40 :
// relative is TR
if ( ( relative = element.getParent().getParent().getNext() ) )
{
nodeToMove = relative.getChild( [ element.getParent().getIndex(), 0 ] );
if ( nodeToMove && nodeToMove.type == 1 )
{
nodeToMove.focus();
onBlur( null, element );
onFocus( null, nodeToMove );
}
}
ev.preventDefault();
break;
// SPACE
// ENTER is already handled as onClick
case 32 :
onChoice( { data: ev } );
ev.preventDefault();
break;
// RIGHT-ARROW
case rtl ? 37 : 39 :
// TAB
case 9 :
// relative is TD
if ( ( relative = element.getParent().getNext() ) )
{
nodeToMove = relative.getChild( 0 );
if ( nodeToMove.type == 1 )
{
nodeToMove.focus();
onBlur( null, element );
onFocus( null, nodeToMove );
ev.preventDefault( true );
}
else
onBlur( null, element );
}
// relative is TR
else if ( ( relative = element.getParent().getParent().getNext() ) )
{
nodeToMove = relative.getChild( [ 0, 0 ] );
if ( nodeToMove && nodeToMove.type == 1 )
{
nodeToMove.focus();
onBlur( null, element );
onFocus( null, nodeToMove );
ev.preventDefault( true );
}
else
onBlur( null, element );
}
break;
// LEFT-ARROW
case rtl ? 39 : 37 :
// SHIFT + TAB
case CKEDITOR.SHIFT + 9 :
// relative is TD
if ( ( relative = element.getParent().getPrevious() ) )
{
nodeToMove = relative.getChild( 0 );
nodeToMove.focus();
onBlur( null, element );
onFocus( null, nodeToMove );
ev.preventDefault( true );
}
// relative is TR
else if ( ( relative = element.getParent().getParent().getPrevious() ) )
{
nodeToMove = relative.getLast().getChild( 0 );
nodeToMove.focus();
onBlur( null, element );
onFocus( null, nodeToMove );
ev.preventDefault( true );
}
else
onBlur( null, element );
break;
default :
// Do not stop not handled events.
return;
}
});
return {
title : lang.title,
minWidth : 430,
minHeight : 280,
buttons : [ CKEDITOR.dialog.cancelButton ],
charColumns : 17,
onLoad : function()
{
var columns = this.definition.charColumns,
extraChars = editor.config.extraSpecialChars,
chars = editor.config.specialChars;
var charsTableLabel = CKEDITOR.tools.getNextId() + '_specialchar_table_label';
var html = [ '<table role="listbox" aria-labelledby="' + charsTableLabel + '"' +
' style="width: 320px; height: 100%; border-collapse: separate;"' +
' align="center" cellspacing="2" cellpadding="2" border="0">' ];
var i = 0,
size = chars.length,
character,
charDesc;
while ( i < size )
{
html.push( '<tr>' ) ;
for ( var j = 0 ; j < columns ; j++, i++ )
{
if ( ( character = chars[ i ] ) )
{
charDesc = '';
if ( character instanceof Array )
{
charDesc = character[ 1 ];
character = character[ 0 ];
}
else
{
var _tmpName = character.replace( '&', '' ).replace( ';', '' ).replace( '#', '' );
// Use character in case description unavailable.
charDesc = lang[ _tmpName ] || character;
}
var charLabelId = 'cke_specialchar_label_' + i + '_' + CKEDITOR.tools.getNextNumber();
html.push(
'<td class="cke_dark_background" style="cursor: default" role="presentation">' +
'<a href="javascript: void(0);" role="option"' +
' aria-posinset="' + ( i +1 ) + '"',
' aria-setsize="' + size + '"',
' aria-labelledby="' + charLabelId + '"',
' style="cursor: inherit; display: block; height: 1.25em; margin-top: 0.25em; text-align: center;" title="', CKEDITOR.tools.htmlEncode( charDesc ), '"' +
' onkeydown="CKEDITOR.tools.callFunction( ' + onKeydown + ', event, this )"' +
' onclick="CKEDITOR.tools.callFunction(' + onClick + ', this); return false;"' +
' tabindex="-1">' +
'<span style="margin: 0 auto;cursor: inherit">' +
character +
'</span>' +
'<span class="cke_voice_label" id="' + charLabelId + '">' +
charDesc +
'</span></a>');
}
else
html.push( '<td class="cke_dark_background"> ' );
html.push( '</td>' );
}
html.push( '</tr>' );
}
html.push( '</tbody></table>', '<span id="' + charsTableLabel + '" class="cke_voice_label">' + lang.options +'</span>' );
this.getContentElement( 'info', 'charContainer' ).getElement().setHtml( html.join( '' ) );
},
contents : [
{
id : 'info',
label : editor.lang.common.generalTab,
title : editor.lang.common.generalTab,
padding : 0,
align : 'top',
elements : [
{
type : 'hbox',
align : 'top',
widths : [ '320px', '90px' ],
children :
[
{
type : 'html',
id : 'charContainer',
html : '',
onMouseover : onFocus,
onMouseout : onBlur,
focus : function()
{
var firstChar = this.getElement().getElementsByTag( 'a' ).getItem( 0 );
setTimeout( function()
{
firstChar.focus();
onFocus( null, firstChar );
}, 0 );
},
onShow : function()
{
var firstChar = this.getElement().getChild( [ 0, 0, 0, 0, 0 ] );
setTimeout( function()
{
firstChar.focus();
onFocus( null, firstChar );
}, 0 );
},
onLoad : function( event )
{
dialog = event.sender;
}
},
{
type : 'hbox',
align : 'top',
widths : [ '100%' ],
children :
[
{
type : 'vbox',
align : 'top',
children :
[
{
type : 'html',
html : '<div></div>'
},
{
type : 'html',
id : 'charPreview',
className : 'cke_dark_background',
style : 'border:1px solid #eeeeee;font-size:28px;height:40px;width:70px;padding-top:9px;font-family:\'Microsoft Sans Serif\',Arial,Helvetica,Verdana;text-align:center;',
html : '<div> </div>'
},
{
type : 'html',
id : 'htmlPreview',
className : 'cke_dark_background',
style : 'border:1px solid #eeeeee;font-size:14px;height:20px;width:70px;padding-top:2px;font-family:\'Microsoft Sans Serif\',Arial,Helvetica,Verdana;text-align:center;',
html : '<div> </div>'
}
]
}
]
}
]
}
]
}
]
};
} ); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/_source/plugins/specialchar/dialogs/specialchar.js | specialchar.js |
CKEDITOR.plugins.setLang( 'specialchar', 'en',
{
euro: "Euro sign",
lsquo: "Left single quotation mark",
rsquo: "Right single quotation mark",
ldquo: "Left double quotation mark",
rdquo: "Right double quotation mark",
ndash: "En dash",
mdash: "Em dash",
iexcl: "Inverted exclamation mark",
cent: "Cent sign",
pound: "Pound sign",
curren: "Currency sign",
yen: "Yen sign",
brvbar: "Broken bar",
sect: "Section sign",
uml: "Diaeresis",
copy: "Copyright sign",
ordf: "Feminine ordinal indicator",
laquo: "Left-pointing double angle quotation mark",
not: "Not sign",
reg: "Registered sign",
macr: "Macron",
deg: "Degree sign",
sup2: "Superscript two",
sup3: "Superscript three",
acute: "Acute accent",
micro: "Micro sign",
para: "Pilcrow sign",
middot: "Middle dot",
cedil: "Cedilla",
sup1: "Superscript one",
ordm: "Masculine ordinal indicator",
raquo: "Right-pointing double angle quotation mark",
frac14: "Vulgar fraction one quarter",
frac12: "Vulgar fraction one half",
frac34: "Vulgar fraction three quarters",
iquest: "Inverted question mark",
Agrave: "Latin capital letter A with grave accent",
Aacute: "Latin capital letter A with acute accent",
Acirc: "Latin capital letter A with circumflex",
Atilde: "Latin capital letter A with tilde",
Auml: "Latin capital letter A with diaeresis",
Aring: "Latin capital letter A with ring above",
AElig: "Latin Capital letter Æ",
Ccedil: "Latin capital letter C with cedilla",
Egrave: "Latin capital letter E with grave accent",
Eacute: "Latin capital letter E with acute accent",
Ecirc: "Latin capital letter E with circumflex",
Euml: "Latin capital letter E with diaeresis",
Igrave: "Latin capital letter I with grave accent",
Iacute: "Latin capital letter I with acute accent",
Icirc: "Latin capital letter I with circumflex",
Iuml: "Latin capital letter I with diaeresis",
ETH: "Latin capital letter Eth",
Ntilde: "Latin capital letter N with tilde",
Ograve: "Latin capital letter O with grave accent",
Oacute: "Latin capital letter O with acute accent",
Ocirc: "Latin capital letter O with circumflex",
Otilde: "Latin capital letter O with tilde",
Ouml: "Latin capital letter O with diaeresis",
times: "Multiplication sign",
Oslash: "Latin capital letter O with stroke",
Ugrave: "Latin capital letter U with grave accent",
Uacute: "Latin capital letter U with acute accent",
Ucirc: "Latin capital letter U with circumflex",
Uuml: "Latin capital letter U with diaeresis",
Yacute: "Latin capital letter Y with acute accent",
THORN: "Latin capital letter Thorn",
szlig: "Latin small letter sharp s",
agrave: "Latin small letter a with grave accent",
aacute: "Latin small letter a with acute accent",
acirc: "Latin small letter a with circumflex",
atilde: "Latin small letter a with tilde",
auml: "Latin small letter a with diaeresis",
aring: "Latin small letter a with ring above",
aelig: "Latin small letter æ",
ccedil: "Latin small letter c with cedilla",
egrave: "Latin small letter e with grave accent",
eacute: "Latin small letter e with acute accent",
ecirc: "Latin small letter e with circumflex",
euml: "Latin small letter e with diaeresis",
igrave: "Latin small letter i with grave accent",
iacute: "Latin small letter i with acute accent",
icirc: "Latin small letter i with circumflex",
iuml: "Latin small letter i with diaeresis",
eth: "Latin small letter eth",
ntilde: "Latin small letter n with tilde",
ograve: "Latin small letter o with grave accent",
oacute: "Latin small letter o with acute accent",
ocirc: "Latin small letter o with circumflex",
otilde: "Latin small letter o with tilde",
ouml: "Latin small letter o with diaeresis",
divide: "Division sign",
oslash: "Latin small letter o with stroke",
ugrave: "Latin small letter u with grave accent",
uacute: "Latin small letter u with acute accent",
ucirc: "Latin small letter u with circumflex",
uuml: "Latin small letter u with diaeresis",
yacute: "Latin small letter y with acute accent",
thorn: "Latin small letter thorn",
yuml: "Latin small letter y with diaeresis",
OElig: "Latin capital ligature OE",
oelig: "Latin small ligature oe",
'372': "Latin capital letter W with circumflex",
'374': "Latin capital letter Y with circumflex",
'373': "Latin small letter w with circumflex",
'375': "Latin small letter y with circumflex",
sbquo: "Single low-9 quotation mark",
'8219': "Single high-reversed-9 quotation mark",
bdquo: "Double low-9 quotation mark",
hellip: "Horizontal ellipsis",
trade: "Trade mark sign",
'9658': "Black right-pointing pointer",
bull: "Bullet",
rarr: "Rightwards arrow",
rArr: "Rightwards double arrow",
hArr: "Left right double arrow",
diams: "Black diamond suit",
asymp: "Almost equal to"
}); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/_source/plugins/specialchar/lang/en.js | en.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
var imageDialog = function( editor, dialogType )
{
// Load image preview.
var IMAGE = 1,
LINK = 2,
PREVIEW = 4,
CLEANUP = 8,
regexGetSize = /^\s*(\d+)((px)|\%)?\s*$/i,
regexGetSizeOrEmpty = /(^\s*(\d+)((px)|\%)?\s*$)|^$/i,
pxLengthRegex = /^\d+px$/;
var onSizeChange = function()
{
var value = this.getValue(), // This = input element.
dialog = this.getDialog(),
aMatch = value.match( regexGetSize ); // Check value
if ( aMatch )
{
if ( aMatch[2] == '%' ) // % is allowed - > unlock ratio.
switchLockRatio( dialog, false ); // Unlock.
value = aMatch[1];
}
// Only if ratio is locked
if ( dialog.lockRatio )
{
var oImageOriginal = dialog.originalElement;
if ( oImageOriginal.getCustomData( 'isReady' ) == 'true' )
{
if ( this.id == 'txtHeight' )
{
if ( value && value != '0' )
value = Math.round( oImageOriginal.$.width * ( value / oImageOriginal.$.height ) );
if ( !isNaN( value ) )
dialog.setValueOf( 'info', 'txtWidth', value );
}
else //this.id = txtWidth.
{
if ( value && value != '0' )
value = Math.round( oImageOriginal.$.height * ( value / oImageOriginal.$.width ) );
if ( !isNaN( value ) )
dialog.setValueOf( 'info', 'txtHeight', value );
}
}
}
updatePreview( dialog );
};
var updatePreview = function( dialog )
{
//Don't load before onShow.
if ( !dialog.originalElement || !dialog.preview )
return 1;
// Read attributes and update imagePreview;
dialog.commitContent( PREVIEW, dialog.preview );
return 0;
};
// Custom commit dialog logic, where we're intended to give inline style
// field (txtdlgGenStyle) higher priority to avoid overwriting styles contribute
// by other fields.
function commitContent()
{
var args = arguments;
var inlineStyleField = this.getContentElement( 'advanced', 'txtdlgGenStyle' );
inlineStyleField && inlineStyleField.commit.apply( inlineStyleField, args );
this.foreach( function( widget )
{
if ( widget.commit && widget.id != 'txtdlgGenStyle' )
widget.commit.apply( widget, args );
});
}
// Avoid recursions.
var incommit;
// Synchronous field values to other impacted fields is required, e.g. border
// size change should alter inline-style text as well.
function commitInternally( targetFields )
{
if ( incommit )
return;
incommit = 1;
var dialog = this.getDialog(),
element = dialog.imageElement;
if ( element )
{
// Commit this field and broadcast to target fields.
this.commit( IMAGE, element );
targetFields = [].concat( targetFields );
var length = targetFields.length,
field;
for ( var i = 0; i < length; i++ )
{
field = dialog.getContentElement.apply( dialog, targetFields[ i ].split( ':' ) );
// May cause recursion.
field && field.setup( IMAGE, element );
}
}
incommit = 0;
}
var switchLockRatio = function( dialog, value )
{
if ( !dialog.getContentElement( 'info', 'ratioLock' ) )
return null;
var oImageOriginal = dialog.originalElement;
// Dialog may already closed. (#5505)
if( !oImageOriginal )
return null;
// Check image ratio and original image ratio, but respecting user's preference.
if ( value == 'check' )
{
if ( !dialog.userlockRatio && oImageOriginal.getCustomData( 'isReady' ) == 'true' )
{
var width = dialog.getValueOf( 'info', 'txtWidth' ),
height = dialog.getValueOf( 'info', 'txtHeight' ),
originalRatio = oImageOriginal.$.width * 1000 / oImageOriginal.$.height,
thisRatio = width * 1000 / height;
dialog.lockRatio = false; // Default: unlock ratio
if ( !width && !height )
dialog.lockRatio = true;
else if ( !isNaN( originalRatio ) && !isNaN( thisRatio ) )
{
if ( Math.round( originalRatio ) == Math.round( thisRatio ) )
dialog.lockRatio = true;
}
}
}
else if ( value != undefined )
dialog.lockRatio = value;
else
{
dialog.userlockRatio = 1;
dialog.lockRatio = !dialog.lockRatio;
}
var ratioButton = CKEDITOR.document.getById( btnLockSizesId );
if ( dialog.lockRatio )
ratioButton.removeClass( 'cke_btn_unlocked' );
else
ratioButton.addClass( 'cke_btn_unlocked' );
ratioButton.setAttribute( 'aria-checked', dialog.lockRatio );
// Ratio button hc presentation - WHITE SQUARE / BLACK SQUARE
if ( CKEDITOR.env.hc )
{
var icon = ratioButton.getChild( 0 );
icon.setHtml( dialog.lockRatio ? CKEDITOR.env.ie ? '\u25A0': '\u25A3' : CKEDITOR.env.ie ? '\u25A1' : '\u25A2' );
}
return dialog.lockRatio;
};
var resetSize = function( dialog )
{
var oImageOriginal = dialog.originalElement;
if ( oImageOriginal.getCustomData( 'isReady' ) == 'true' )
{
var widthField = dialog.getContentElement( 'info', 'txtWidth' ),
heightField = dialog.getContentElement( 'info', 'txtHeight' );
widthField && widthField.setValue( oImageOriginal.$.width );
heightField && heightField.setValue( oImageOriginal.$.height );
}
updatePreview( dialog );
};
var setupDimension = function( type, element )
{
if ( type != IMAGE )
return;
function checkDimension( size, defaultValue )
{
var aMatch = size.match( regexGetSize );
if ( aMatch )
{
if ( aMatch[2] == '%' ) // % is allowed.
{
aMatch[1] += '%';
switchLockRatio( dialog, false ); // Unlock ratio
}
return aMatch[1];
}
return defaultValue;
}
var dialog = this.getDialog(),
value = '',
dimension = this.id == 'txtWidth' ? 'width' : 'height',
size = element.getAttribute( dimension );
if ( size )
value = checkDimension( size, value );
value = checkDimension( element.getStyle( dimension ), value );
this.setValue( value );
};
var previewPreloader;
var onImgLoadEvent = function()
{
// Image is ready.
var original = this.originalElement;
original.setCustomData( 'isReady', 'true' );
original.removeListener( 'load', onImgLoadEvent );
original.removeListener( 'error', onImgLoadErrorEvent );
original.removeListener( 'abort', onImgLoadErrorEvent );
// Hide loader
CKEDITOR.document.getById( imagePreviewLoaderId ).setStyle( 'display', 'none' );
// New image -> new domensions
if ( !this.dontResetSize )
resetSize( this );
if ( this.firstLoad )
CKEDITOR.tools.setTimeout( function(){ switchLockRatio( this, 'check' ); }, 0, this );
this.firstLoad = false;
this.dontResetSize = false;
};
var onImgLoadErrorEvent = function()
{
// Error. Image is not loaded.
var original = this.originalElement;
original.removeListener( 'load', onImgLoadEvent );
original.removeListener( 'error', onImgLoadErrorEvent );
original.removeListener( 'abort', onImgLoadErrorEvent );
// Set Error image.
var noimage = CKEDITOR.getUrl( editor.skinPath + 'images/noimage.png' );
if ( this.preview )
this.preview.setAttribute( 'src', noimage );
// Hide loader
CKEDITOR.document.getById( imagePreviewLoaderId ).setStyle( 'display', 'none' );
switchLockRatio( this, false ); // Unlock.
};
var numbering = function( id )
{
return CKEDITOR.tools.getNextId() + '_' + id;
},
btnLockSizesId = numbering( 'btnLockSizes' ),
btnResetSizeId = numbering( 'btnResetSize' ),
imagePreviewLoaderId = numbering( 'ImagePreviewLoader' ),
imagePreviewBoxId = numbering( 'ImagePreviewBox' ),
previewLinkId = numbering( 'previewLink' ),
previewImageId = numbering( 'previewImage' );
return {
title : editor.lang.image[ dialogType == 'image' ? 'title' : 'titleButton' ],
minWidth : 420,
minHeight : 360,
onShow : function()
{
this.imageElement = false;
this.linkElement = false;
// Default: create a new element.
this.imageEditMode = false;
this.linkEditMode = false;
this.lockRatio = true;
this.userlockRatio = 0;
this.dontResetSize = false;
this.firstLoad = true;
this.addLink = false;
var editor = this.getParentEditor(),
sel = this.getParentEditor().getSelection(),
element = sel.getSelectedElement(),
link = element && element.getAscendant( 'a' );
//Hide loader.
CKEDITOR.document.getById( imagePreviewLoaderId ).setStyle( 'display', 'none' );
// Create the preview before setup the dialog contents.
previewPreloader = new CKEDITOR.dom.element( 'img', editor.document );
this.preview = CKEDITOR.document.getById( previewImageId );
// Copy of the image
this.originalElement = editor.document.createElement( 'img' );
this.originalElement.setAttribute( 'alt', '' );
this.originalElement.setCustomData( 'isReady', 'false' );
if ( link )
{
this.linkElement = link;
this.linkEditMode = true;
// Look for Image element.
var linkChildren = link.getChildren();
if ( linkChildren.count() == 1 ) // 1 child.
{
var childTagName = linkChildren.getItem( 0 ).getName();
if ( childTagName == 'img' || childTagName == 'input' )
{
this.imageElement = linkChildren.getItem( 0 );
if ( this.imageElement.getName() == 'img' )
this.imageEditMode = 'img';
else if ( this.imageElement.getName() == 'input' )
this.imageEditMode = 'input';
}
}
// Fill out all fields.
if ( dialogType == 'image' )
this.setupContent( LINK, link );
}
if ( element && element.getName() == 'img' && !element.data( 'cke-realelement' )
|| element && element.getName() == 'input' && element.getAttribute( 'type' ) == 'image' )
{
this.imageEditMode = element.getName();
this.imageElement = element;
}
if ( this.imageEditMode )
{
// Use the original element as a buffer from since we don't want
// temporary changes to be committed, e.g. if the dialog is canceled.
this.cleanImageElement = this.imageElement;
this.imageElement = this.cleanImageElement.clone( true, true );
// Fill out all fields.
this.setupContent( IMAGE, this.imageElement );
}
else
this.imageElement = editor.document.createElement( 'img' );
// Refresh LockRatio button
switchLockRatio ( this, true );
// Dont show preview if no URL given.
if ( !CKEDITOR.tools.trim( this.getValueOf( 'info', 'txtUrl' ) ) )
{
this.preview.removeAttribute( 'src' );
this.preview.setStyle( 'display', 'none' );
}
},
onOk : function()
{
// Edit existing Image.
if ( this.imageEditMode )
{
var imgTagName = this.imageEditMode;
// Image dialog and Input element.
if ( dialogType == 'image' && imgTagName == 'input' && confirm( editor.lang.image.button2Img ) )
{
// Replace INPUT-> IMG
imgTagName = 'img';
this.imageElement = editor.document.createElement( 'img' );
this.imageElement.setAttribute( 'alt', '' );
editor.insertElement( this.imageElement );
}
// ImageButton dialog and Image element.
else if ( dialogType != 'image' && imgTagName == 'img' && confirm( editor.lang.image.img2Button ))
{
// Replace IMG -> INPUT
imgTagName = 'input';
this.imageElement = editor.document.createElement( 'input' );
this.imageElement.setAttributes(
{
type : 'image',
alt : ''
}
);
editor.insertElement( this.imageElement );
}
else
{
// Restore the original element before all commits.
this.imageElement = this.cleanImageElement;
delete this.cleanImageElement;
}
}
else // Create a new image.
{
// Image dialog -> create IMG element.
if ( dialogType == 'image' )
this.imageElement = editor.document.createElement( 'img' );
else
{
this.imageElement = editor.document.createElement( 'input' );
this.imageElement.setAttribute ( 'type' ,'image' );
}
this.imageElement.setAttribute( 'alt', '' );
}
// Create a new link.
if ( !this.linkEditMode )
this.linkElement = editor.document.createElement( 'a' );
// Set attributes.
this.commitContent( IMAGE, this.imageElement );
this.commitContent( LINK, this.linkElement );
// Remove empty style attribute.
if ( !this.imageElement.getAttribute( 'style' ) )
this.imageElement.removeAttribute( 'style' );
// Insert a new Image.
if ( !this.imageEditMode )
{
if ( this.addLink )
{
//Insert a new Link.
if ( !this.linkEditMode )
{
editor.insertElement( this.linkElement );
this.linkElement.append( this.imageElement, false );
}
else //Link already exists, image not.
editor.insertElement( this.imageElement );
}
else
editor.insertElement( this.imageElement );
}
else // Image already exists.
{
//Add a new link element.
if ( !this.linkEditMode && this.addLink )
{
editor.insertElement( this.linkElement );
this.imageElement.appendTo( this.linkElement );
}
//Remove Link, Image exists.
else if ( this.linkEditMode && !this.addLink )
{
editor.getSelection().selectElement( this.linkElement );
editor.insertElement( this.imageElement );
}
}
},
onLoad : function()
{
if ( dialogType != 'image' )
this.hidePage( 'Link' ); //Hide Link tab.
var doc = this._.element.getDocument();
if ( this.getContentElement( 'info', 'ratioLock' ) )
{
this.addFocusable( doc.getById( btnResetSizeId ), 5 );
this.addFocusable( doc.getById( btnLockSizesId ), 5 );
}
this.commitContent = commitContent;
},
onHide : function()
{
if ( this.preview )
this.commitContent( CLEANUP, this.preview );
if ( this.originalElement )
{
this.originalElement.removeListener( 'load', onImgLoadEvent );
this.originalElement.removeListener( 'error', onImgLoadErrorEvent );
this.originalElement.removeListener( 'abort', onImgLoadErrorEvent );
this.originalElement.remove();
this.originalElement = false; // Dialog is closed.
}
delete this.imageElement;
},
contents : [
{
id : 'info',
label : editor.lang.image.infoTab,
accessKey : 'I',
elements :
[
{
type : 'vbox',
padding : 0,
children :
[
{
type : 'hbox',
widths : [ '280px', '110px' ],
align : 'right',
children :
[
{
id : 'txtUrl',
type : 'text',
label : editor.lang.common.url,
required: true,
onChange : function()
{
var dialog = this.getDialog(),
newUrl = this.getValue();
//Update original image
if ( newUrl.length > 0 ) //Prevent from load before onShow
{
dialog = this.getDialog();
var original = dialog.originalElement;
dialog.preview.removeStyle( 'display' );
original.setCustomData( 'isReady', 'false' );
// Show loader
var loader = CKEDITOR.document.getById( imagePreviewLoaderId );
if ( loader )
loader.setStyle( 'display', '' );
original.on( 'load', onImgLoadEvent, dialog );
original.on( 'error', onImgLoadErrorEvent, dialog );
original.on( 'abort', onImgLoadErrorEvent, dialog );
original.setAttribute( 'src', newUrl );
// Query the preloader to figure out the url impacted by based href.
previewPreloader.setAttribute( 'src', newUrl );
dialog.preview.setAttribute( 'src', previewPreloader.$.src );
updatePreview( dialog );
}
// Dont show preview if no URL given.
else if ( dialog.preview )
{
dialog.preview.removeAttribute( 'src' );
dialog.preview.setStyle( 'display', 'none' );
}
},
setup : function( type, element )
{
if ( type == IMAGE )
{
var url = element.data( 'cke-saved-src' ) || element.getAttribute( 'src' );
var field = this;
this.getDialog().dontResetSize = true;
field.setValue( url ); // And call this.onChange()
// Manually set the initial value.(#4191)
field.setInitValue();
}
},
commit : function( type, element )
{
if ( type == IMAGE && ( this.getValue() || this.isChanged() ) )
{
element.data( 'cke-saved-src', this.getValue() );
element.setAttribute( 'src', this.getValue() );
}
else if ( type == CLEANUP )
{
element.setAttribute( 'src', '' ); // If removeAttribute doesn't work.
element.removeAttribute( 'src' );
}
},
validate : CKEDITOR.dialog.validate.notEmpty( editor.lang.image.urlMissing )
},
{
type : 'button',
id : 'browse',
// v-align with the 'txtUrl' field.
// TODO: We need something better than a fixed size here.
style : 'display:inline-block;margin-top:10px;',
align : 'center',
label : editor.lang.common.browseServer,
hidden : true,
filebrowser : 'info:txtUrl'
}
]
}
]
},
{
id : 'txtAlt',
type : 'text',
label : editor.lang.image.alt,
accessKey : 'T',
'default' : '',
onChange : function()
{
updatePreview( this.getDialog() );
},
setup : function( type, element )
{
if ( type == IMAGE )
this.setValue( element.getAttribute( 'alt' ) );
},
commit : function( type, element )
{
if ( type == IMAGE )
{
if ( this.getValue() || this.isChanged() )
element.setAttribute( 'alt', this.getValue() );
}
else if ( type == PREVIEW )
{
element.setAttribute( 'alt', this.getValue() );
}
else if ( type == CLEANUP )
{
element.removeAttribute( 'alt' );
}
}
},
{
type : 'hbox',
children :
[
{
id : 'basic',
type : 'vbox',
children :
[
{
type : 'hbox',
widths : [ '50%', '50%' ],
children :
[
{
type : 'vbox',
padding : 1,
children :
[
{
type : 'text',
width: '40px',
id : 'txtWidth',
label : editor.lang.common.width,
onKeyUp : onSizeChange,
onChange : function()
{
commitInternally.call( this, 'advanced:txtdlgGenStyle' );
},
validate : function()
{
var aMatch = this.getValue().match( regexGetSizeOrEmpty ),
isValid = !!( aMatch && parseInt( aMatch[1], 10 ) !== 0 );
if ( !isValid )
alert( editor.lang.common.invalidWidth );
return isValid;
},
setup : setupDimension,
commit : function( type, element, internalCommit )
{
var value = this.getValue();
if ( type == IMAGE )
{
if ( value )
element.setStyle( 'width', CKEDITOR.tools.cssLength( value ) );
else
element.removeStyle( 'width' );
!internalCommit && element.removeAttribute( 'width' );
}
else if ( type == PREVIEW )
{
var aMatch = value.match( regexGetSize );
if ( !aMatch )
{
var oImageOriginal = this.getDialog().originalElement;
if ( oImageOriginal.getCustomData( 'isReady' ) == 'true' )
element.setStyle( 'width', oImageOriginal.$.width + 'px');
}
else
element.setStyle( 'width', CKEDITOR.tools.cssLength( value ) );
}
else if ( type == CLEANUP )
{
element.removeAttribute( 'width' );
element.removeStyle( 'width' );
}
}
},
{
type : 'text',
id : 'txtHeight',
width: '40px',
label : editor.lang.common.height,
onKeyUp : onSizeChange,
onChange : function()
{
commitInternally.call( this, 'advanced:txtdlgGenStyle' );
},
validate : function()
{
var aMatch = this.getValue().match( regexGetSizeOrEmpty ),
isValid = !!( aMatch && parseInt( aMatch[1], 10 ) !== 0 );
if ( !isValid )
alert( editor.lang.common.invalidHeight );
return isValid;
},
setup : setupDimension,
commit : function( type, element, internalCommit )
{
var value = this.getValue();
if ( type == IMAGE )
{
if ( value )
element.setStyle( 'height', CKEDITOR.tools.cssLength( value ) );
else
element.removeStyle( 'height' );
!internalCommit && element.removeAttribute( 'height' );
}
else if ( type == PREVIEW )
{
var aMatch = value.match( regexGetSize );
if ( !aMatch )
{
var oImageOriginal = this.getDialog().originalElement;
if ( oImageOriginal.getCustomData( 'isReady' ) == 'true' )
element.setStyle( 'height', oImageOriginal.$.height + 'px' );
}
else
element.setStyle( 'height', CKEDITOR.tools.cssLength( value ) );
}
else if ( type == CLEANUP )
{
element.removeAttribute( 'height' );
element.removeStyle( 'height' );
}
}
}
]
},
{
id : 'ratioLock',
type : 'html',
style : 'margin-top:30px;width:40px;height:40px;',
onLoad : function()
{
// Activate Reset button
var resetButton = CKEDITOR.document.getById( btnResetSizeId ),
ratioButton = CKEDITOR.document.getById( btnLockSizesId );
if ( resetButton )
{
resetButton.on( 'click', function( evt )
{
resetSize( this );
evt.data && evt.data.preventDefault();
}, this.getDialog() );
resetButton.on( 'mouseover', function()
{
this.addClass( 'cke_btn_over' );
}, resetButton );
resetButton.on( 'mouseout', function()
{
this.removeClass( 'cke_btn_over' );
}, resetButton );
}
// Activate (Un)LockRatio button
if ( ratioButton )
{
ratioButton.on( 'click', function(evt)
{
var locked = switchLockRatio( this ),
oImageOriginal = this.originalElement,
width = this.getValueOf( 'info', 'txtWidth' );
if ( oImageOriginal.getCustomData( 'isReady' ) == 'true' && width )
{
var height = oImageOriginal.$.height / oImageOriginal.$.width * width;
if ( !isNaN( height ) )
{
this.setValueOf( 'info', 'txtHeight', Math.round( height ) );
updatePreview( this );
}
}
evt.data && evt.data.preventDefault();
}, this.getDialog() );
ratioButton.on( 'mouseover', function()
{
this.addClass( 'cke_btn_over' );
}, ratioButton );
ratioButton.on( 'mouseout', function()
{
this.removeClass( 'cke_btn_over' );
}, ratioButton );
}
},
html : '<div>'+
'<a href="javascript:void(0)" tabindex="-1" title="' + editor.lang.image.lockRatio +
'" class="cke_btn_locked" id="' + btnLockSizesId + '" role="checkbox"><span class="cke_icon"></span><span class="cke_label">' + editor.lang.image.lockRatio + '</span></a>' +
'<a href="javascript:void(0)" tabindex="-1" title="' + editor.lang.image.resetSize +
'" class="cke_btn_reset" id="' + btnResetSizeId + '" role="button"><span class="cke_label">' + editor.lang.image.resetSize + '</span></a>'+
'</div>'
}
]
},
{
type : 'vbox',
padding : 1,
children :
[
{
type : 'text',
id : 'txtBorder',
width: '60px',
label : editor.lang.image.border,
'default' : '',
onKeyUp : function()
{
updatePreview( this.getDialog() );
},
onChange : function()
{
commitInternally.call( this, 'advanced:txtdlgGenStyle' );
},
validate : CKEDITOR.dialog.validate.integer( editor.lang.image.validateBorder ),
setup : function( type, element )
{
if ( type == IMAGE )
{
var value,
borderStyle = element.getStyle( 'border-width' );
borderStyle = borderStyle && borderStyle.match( /^(\d+px)(?: \1 \1 \1)?$/ );
value = borderStyle && parseInt( borderStyle[ 1 ], 10 );
isNaN ( parseInt( value, 10 ) ) && ( value = element.getAttribute( 'border' ) );
this.setValue( value );
}
},
commit : function( type, element, internalCommit )
{
var value = parseInt( this.getValue(), 10 );
if ( type == IMAGE || type == PREVIEW )
{
if ( !isNaN( value ) )
{
element.setStyle( 'border-width', CKEDITOR.tools.cssLength( value ) );
element.setStyle( 'border-style', 'solid' );
}
else if ( !value && this.isChanged() )
{
element.removeStyle( 'border-width' );
element.removeStyle( 'border-style' );
element.removeStyle( 'border-color' );
}
if ( !internalCommit && type == IMAGE )
element.removeAttribute( 'border' );
}
else if ( type == CLEANUP )
{
element.removeAttribute( 'border' );
element.removeStyle( 'border-width' );
element.removeStyle( 'border-style' );
element.removeStyle( 'border-color' );
}
}
},
{
type : 'text',
id : 'txtHSpace',
width: '60px',
label : editor.lang.image.hSpace,
'default' : '',
onKeyUp : function()
{
updatePreview( this.getDialog() );
},
onChange : function()
{
commitInternally.call( this, 'advanced:txtdlgGenStyle' );
},
validate : CKEDITOR.dialog.validate.integer( editor.lang.image.validateHSpace ),
setup : function( type, element )
{
if ( type == IMAGE )
{
var value,
marginLeftPx,
marginRightPx,
marginLeftStyle = element.getStyle( 'margin-left' ),
marginRightStyle = element.getStyle( 'margin-right' );
marginLeftStyle = marginLeftStyle && marginLeftStyle.match( pxLengthRegex );
marginRightStyle = marginRightStyle && marginRightStyle.match( pxLengthRegex );
marginLeftPx = parseInt( marginLeftStyle, 10 );
marginRightPx = parseInt( marginRightStyle, 10 );
value = ( marginLeftPx == marginRightPx ) && marginLeftPx;
isNaN( parseInt( value, 10 ) ) && ( value = element.getAttribute( 'hspace' ) );
this.setValue( value );
}
},
commit : function( type, element, internalCommit )
{
var value = parseInt( this.getValue(), 10 );
if ( type == IMAGE || type == PREVIEW )
{
if ( !isNaN( value ) )
{
element.setStyle( 'margin-left', CKEDITOR.tools.cssLength( value ) );
element.setStyle( 'margin-right', CKEDITOR.tools.cssLength( value ) );
}
else if ( !value && this.isChanged( ) )
{
element.removeStyle( 'margin-left' );
element.removeStyle( 'margin-right' );
}
if ( !internalCommit && type == IMAGE )
element.removeAttribute( 'hspace' );
}
else if ( type == CLEANUP )
{
element.removeAttribute( 'hspace' );
element.removeStyle( 'margin-left' );
element.removeStyle( 'margin-right' );
}
}
},
{
type : 'text',
id : 'txtVSpace',
width : '60px',
label : editor.lang.image.vSpace,
'default' : '',
onKeyUp : function()
{
updatePreview( this.getDialog() );
},
onChange : function()
{
commitInternally.call( this, 'advanced:txtdlgGenStyle' );
},
validate : CKEDITOR.dialog.validate.integer( editor.lang.image.validateVSpace ),
setup : function( type, element )
{
if ( type == IMAGE )
{
var value,
marginTopPx,
marginBottomPx,
marginTopStyle = element.getStyle( 'margin-top' ),
marginBottomStyle = element.getStyle( 'margin-bottom' );
marginTopStyle = marginTopStyle && marginTopStyle.match( pxLengthRegex );
marginBottomStyle = marginBottomStyle && marginBottomStyle.match( pxLengthRegex );
marginTopPx = parseInt( marginTopStyle, 10 );
marginBottomPx = parseInt( marginBottomStyle, 10 );
value = ( marginTopPx == marginBottomPx ) && marginTopPx;
isNaN ( parseInt( value, 10 ) ) && ( value = element.getAttribute( 'vspace' ) );
this.setValue( value );
}
},
commit : function( type, element, internalCommit )
{
var value = parseInt( this.getValue(), 10 );
if ( type == IMAGE || type == PREVIEW )
{
if ( !isNaN( value ) )
{
element.setStyle( 'margin-top', CKEDITOR.tools.cssLength( value ) );
element.setStyle( 'margin-bottom', CKEDITOR.tools.cssLength( value ) );
}
else if ( !value && this.isChanged( ) )
{
element.removeStyle( 'margin-top' );
element.removeStyle( 'margin-bottom' );
}
if ( !internalCommit && type == IMAGE )
element.removeAttribute( 'vspace' );
}
else if ( type == CLEANUP )
{
element.removeAttribute( 'vspace' );
element.removeStyle( 'margin-top' );
element.removeStyle( 'margin-bottom' );
}
}
},
{
id : 'cmbAlign',
type : 'select',
widths : [ '35%','65%' ],
style : 'width:90px',
label : editor.lang.common.align,
'default' : '',
items :
[
[ editor.lang.common.notSet , ''],
[ editor.lang.common.alignLeft , 'left'],
[ editor.lang.common.alignRight , 'right']
// Backward compatible with v2 on setup when specified as attribute value,
// while these values are no more available as select options.
// [ editor.lang.image.alignAbsBottom , 'absBottom'],
// [ editor.lang.image.alignAbsMiddle , 'absMiddle'],
// [ editor.lang.image.alignBaseline , 'baseline'],
// [ editor.lang.image.alignTextTop , 'text-top'],
// [ editor.lang.image.alignBottom , 'bottom'],
// [ editor.lang.image.alignMiddle , 'middle'],
// [ editor.lang.image.alignTop , 'top']
],
onChange : function()
{
updatePreview( this.getDialog() );
commitInternally.call( this, 'advanced:txtdlgGenStyle' );
},
setup : function( type, element )
{
if ( type == IMAGE )
{
var value = element.getStyle( 'float' );
switch( value )
{
// Ignore those unrelated values.
case 'inherit':
case 'none':
value = '';
}
!value && ( value = ( element.getAttribute( 'align' ) || '' ).toLowerCase() );
this.setValue( value );
}
},
commit : function( type, element, internalCommit )
{
var value = this.getValue();
if ( type == IMAGE || type == PREVIEW )
{
if ( value )
element.setStyle( 'float', value );
else
element.removeStyle( 'float' );
if ( !internalCommit && type == IMAGE )
{
value = ( element.getAttribute( 'align' ) || '' ).toLowerCase();
switch( value )
{
// we should remove it only if it matches "left" or "right",
// otherwise leave it intact.
case 'left':
case 'right':
element.removeAttribute( 'align' );
}
}
}
else if ( type == CLEANUP )
element.removeStyle( 'float' );
}
}
]
}
]
},
{
type : 'vbox',
height : '250px',
children :
[
{
type : 'html',
id : 'htmlPreview',
style : 'width:95%;',
html : '<div>' + CKEDITOR.tools.htmlEncode( editor.lang.common.preview ) +'<br>'+
'<div id="' + imagePreviewLoaderId + '" class="ImagePreviewLoader" style="display:none"><div class="loading"> </div></div>'+
'<div id="' + imagePreviewBoxId + '" class="ImagePreviewBox"><table><tr><td>'+
'<a href="javascript:void(0)" target="_blank" onclick="return false;" id="' + previewLinkId + '">'+
'<img id="' + previewImageId + '" alt="" /></a>' +
( editor.config.image_previewText ||
'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. '+
'Maecenas feugiat consequat diam. Maecenas metus. Vivamus diam purus, cursus a, commodo non, facilisis vitae, '+
'nulla. Aenean dictum lacinia tortor. Nunc iaculis, nibh non iaculis aliquam, orci felis euismod neque, sed ornare massa mauris sed velit. Nulla pretium mi et risus. Fusce mi pede, tempor id, cursus ac, ullamcorper nec, enim. Sed tortor. Curabitur molestie. Duis velit augue, condimentum at, ultrices a, luctus ut, orci. Donec pellentesque egestas eros. Integer cursus, augue in cursus faucibus, eros pede bibendum sem, in tempus tellus justo quis ligula. Etiam eget tortor. Vestibulum rutrum, est ut placerat elementum, lectus nisl aliquam velit, tempor aliquam eros nunc nonummy metus. In eros metus, gravida a, gravida sed, lobortis id, turpis. Ut ultrices, ipsum at venenatis fringilla, sem nulla lacinia tellus, eget aliquet turpis mauris non enim. Nam turpis. Suspendisse lacinia. Curabitur ac tortor ut ipsum egestas elementum. Nunc imperdiet gravida mauris.' ) +
'</td></tr></table></div></div>'
}
]
}
]
}
]
},
{
id : 'Link',
label : editor.lang.link.title,
padding : 0,
elements :
[
{
id : 'txtUrl',
type : 'text',
label : editor.lang.common.url,
style : 'width: 100%',
'default' : '',
setup : function( type, element )
{
if ( type == LINK )
{
var href = element.data( 'cke-saved-href' );
if ( !href )
href = element.getAttribute( 'href' );
this.setValue( href );
}
},
commit : function( type, element )
{
if ( type == LINK )
{
if ( this.getValue() || this.isChanged() )
{
var url = decodeURI( this.getValue() );
element.data( 'cke-saved-href', url );
element.setAttribute( 'href', url );
if ( this.getValue() || !editor.config.image_removeLinkByEmptyURL )
this.getDialog().addLink = true;
}
}
}
},
{
type : 'button',
id : 'browse',
filebrowser :
{
action : 'Browse',
target: 'Link:txtUrl',
url: editor.config.filebrowserImageBrowseLinkUrl
},
style : 'float:right',
hidden : true,
label : editor.lang.common.browseServer
},
{
id : 'cmbTarget',
type : 'select',
label : editor.lang.common.target,
'default' : '',
items :
[
[ editor.lang.common.notSet , ''],
[ editor.lang.common.targetNew , '_blank'],
[ editor.lang.common.targetTop , '_top'],
[ editor.lang.common.targetSelf , '_self'],
[ editor.lang.common.targetParent , '_parent']
],
setup : function( type, element )
{
if ( type == LINK )
this.setValue( element.getAttribute( 'target' ) || '' );
},
commit : function( type, element )
{
if ( type == LINK )
{
if ( this.getValue() || this.isChanged() )
element.setAttribute( 'target', this.getValue() );
}
}
}
]
},
{
id : 'Upload',
hidden : true,
filebrowser : 'uploadButton',
label : editor.lang.image.upload,
elements :
[
{
type : 'file',
id : 'upload',
label : editor.lang.image.btnUpload,
style: 'height:40px',
size : 38
},
{
type : 'fileButton',
id : 'uploadButton',
filebrowser : 'info:txtUrl',
label : editor.lang.image.btnUpload,
'for' : [ 'Upload', 'upload' ]
}
]
},
{
id : 'advanced',
label : editor.lang.common.advancedTab,
elements :
[
{
type : 'hbox',
widths : [ '50%', '25%', '25%' ],
children :
[
{
type : 'text',
id : 'linkId',
label : editor.lang.common.id,
setup : function( type, element )
{
if ( type == IMAGE )
this.setValue( element.getAttribute( 'id' ) );
},
commit : function( type, element )
{
if ( type == IMAGE )
{
if ( this.getValue() || this.isChanged() )
element.setAttribute( 'id', this.getValue() );
}
}
},
{
id : 'cmbLangDir',
type : 'select',
style : 'width : 100px;',
label : editor.lang.common.langDir,
'default' : '',
items :
[
[ editor.lang.common.notSet, '' ],
[ editor.lang.common.langDirLtr, 'ltr' ],
[ editor.lang.common.langDirRtl, 'rtl' ]
],
setup : function( type, element )
{
if ( type == IMAGE )
this.setValue( element.getAttribute( 'dir' ) );
},
commit : function( type, element )
{
if ( type == IMAGE )
{
if ( this.getValue() || this.isChanged() )
element.setAttribute( 'dir', this.getValue() );
}
}
},
{
type : 'text',
id : 'txtLangCode',
label : editor.lang.common.langCode,
'default' : '',
setup : function( type, element )
{
if ( type == IMAGE )
this.setValue( element.getAttribute( 'lang' ) );
},
commit : function( type, element )
{
if ( type == IMAGE )
{
if ( this.getValue() || this.isChanged() )
element.setAttribute( 'lang', this.getValue() );
}
}
}
]
},
{
type : 'text',
id : 'txtGenLongDescr',
label : editor.lang.common.longDescr,
setup : function( type, element )
{
if ( type == IMAGE )
this.setValue( element.getAttribute( 'longDesc' ) );
},
commit : function( type, element )
{
if ( type == IMAGE )
{
if ( this.getValue() || this.isChanged() )
element.setAttribute( 'longDesc', this.getValue() );
}
}
},
{
type : 'hbox',
widths : [ '50%', '50%' ],
children :
[
{
type : 'text',
id : 'txtGenClass',
label : editor.lang.common.cssClass,
'default' : '',
setup : function( type, element )
{
if ( type == IMAGE )
this.setValue( element.getAttribute( 'class' ) );
},
commit : function( type, element )
{
if ( type == IMAGE )
{
if ( this.getValue() || this.isChanged() )
element.setAttribute( 'class', this.getValue() );
}
}
},
{
type : 'text',
id : 'txtGenTitle',
label : editor.lang.common.advisoryTitle,
'default' : '',
onChange : function()
{
updatePreview( this.getDialog() );
},
setup : function( type, element )
{
if ( type == IMAGE )
this.setValue( element.getAttribute( 'title' ) );
},
commit : function( type, element )
{
if ( type == IMAGE )
{
if ( this.getValue() || this.isChanged() )
element.setAttribute( 'title', this.getValue() );
}
else if ( type == PREVIEW )
{
element.setAttribute( 'title', this.getValue() );
}
else if ( type == CLEANUP )
{
element.removeAttribute( 'title' );
}
}
}
]
},
{
type : 'text',
id : 'txtdlgGenStyle',
label : editor.lang.common.cssStyle,
validate : CKEDITOR.dialog.validate.inlineStyle( editor.lang.common.invalidInlineStyle ),
'default' : '',
setup : function( type, element )
{
if ( type == IMAGE )
{
var genStyle = element.getAttribute( 'style' );
if ( !genStyle && element.$.style.cssText )
genStyle = element.$.style.cssText;
this.setValue( genStyle );
var height = element.$.style.height,
width = element.$.style.width,
aMatchH = ( height ? height : '' ).match( regexGetSize ),
aMatchW = ( width ? width : '').match( regexGetSize );
this.attributesInStyle =
{
height : !!aMatchH,
width : !!aMatchW
};
}
},
onChange : function ()
{
commitInternally.call( this,
[ 'info:cmbFloat', 'info:cmbAlign',
'info:txtVSpace', 'info:txtHSpace',
'info:txtBorder',
'info:txtWidth', 'info:txtHeight' ] );
updatePreview( this );
},
commit : function( type, element )
{
if ( type == IMAGE && ( this.getValue() || this.isChanged() ) )
{
element.setAttribute( 'style', this.getValue() );
}
}
}
]
}
]
};
};
CKEDITOR.dialog.add( 'image', function( editor )
{
return imageDialog( editor, 'image' );
});
CKEDITOR.dialog.add( 'imagebutton', function( editor )
{
return imageDialog( editor, 'imagebutton' );
});
})(); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/_source/plugins/image/dialogs/image.js | image.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview The "filebrowser" plugin that adds support for file uploads and
* browsing.
*
* When a file is uploaded or selected inside the file browser, its URL is
* inserted automatically into a field defined in the <code>filebrowser</code>
* attribute. In order to specify a field that should be updated, pass the tab ID and
* the element ID, separated with a colon.<br /><br />
*
* <strong>Example 1: (Browse)</strong>
*
* <pre>
* {
* type : 'button',
* id : 'browse',
* filebrowser : 'tabId:elementId',
* label : editor.lang.common.browseServer
* }
* </pre>
*
* If you set the <code>filebrowser</code> attribute for an element other than
* the <code>fileButton</code>, the <code>Browse</code> action will be triggered.<br /><br />
*
* <strong>Example 2: (Quick Upload)</strong>
*
* <pre>
* {
* type : 'fileButton',
* id : 'uploadButton',
* filebrowser : 'tabId:elementId',
* label : editor.lang.common.uploadSubmit,
* 'for' : [ 'upload', 'upload' ]
* }
* </pre>
*
* If you set the <code>filebrowser</code> attribute for a <code>fileButton</code>
* element, the <code>QuickUpload</code> action will be executed.<br /><br />
*
* The filebrowser plugin also supports more advanced configuration performed through
* a JavaScript object.
*
* The following settings are supported:
*
* <ul>
* <li><code>action</code> – <code>Browse</code> or <code>QuickUpload</code>.</li>
* <li><code>target</code> – the field to update in the <code><em>tabId:elementId</em></code> format.</li>
* <li><code>params</code> – additional arguments to be passed to the server connector (optional).</li>
* <li><code>onSelect</code> – a function to execute when the file is selected/uploaded (optional).</li>
* <li><code>url</code> – the URL to be called (optional).</li>
* </ul>
*
* <strong>Example 3: (Quick Upload)</strong>
*
* <pre>
* {
* type : 'fileButton',
* label : editor.lang.common.uploadSubmit,
* id : 'buttonId',
* filebrowser :
* {
* action : 'QuickUpload', // required
* target : 'tab1:elementId', // required
* params : // optional
* {
* type : 'Files',
* currentFolder : '/folder/'
* },
* onSelect : function( fileUrl, errorMessage ) // optional
* {
* // Do not call the built-in selectFuntion.
* // return false;
* }
* },
* 'for' : [ 'tab1', 'myFile' ]
* }
* </pre>
*
* Suppose you have a file element with an ID of <code>myFile</code>, a text
* field with an ID of <code>elementId</code> and a <code>fileButton</code>.
* If the <code>filebowser.url</code> attribute is not specified explicitly,
* the form action will be set to <code>filebrowser[<em>DialogWindowName</em>]UploadUrl</code>
* or, if not specified, to <code>filebrowserUploadUrl</code>. Additional parameters
* from the <code>params</code> object will be added to the query string. It is
* possible to create your own <code>uploadHandler</code> and cancel the built-in
* <code>updateTargetElement</code> command.<br /><br />
*
* <strong>Example 4: (Browse)</strong>
*
* <pre>
* {
* type : 'button',
* id : 'buttonId',
* label : editor.lang.common.browseServer,
* filebrowser :
* {
* action : 'Browse',
* url : '/ckfinder/ckfinder.html&type=Images',
* target : 'tab1:elementId'
* }
* }
* </pre>
*
* In this example, when the button is pressed, the file browser will be opened in a
* popup window. If you do not specify the <code>filebrowser.url</code> attribute,
* <code>filebrowser[<em>DialogName</em>]BrowseUrl</code> or
* <code>filebrowserBrowseUrl</code> will be used. After selecting a file in the file
* browser, an element with an ID of <code>elementId</code> will be updated. Just
* like in the third example, a custom <code>onSelect</code> function may be defined.
*/
( function()
{
/*
* Adds (additional) arguments to given url.
*
* @param {String}
* url The url.
* @param {Object}
* params Additional parameters.
*/
function addQueryString( url, params )
{
var queryString = [];
if ( !params )
return url;
else
{
for ( var i in params )
queryString.push( i + "=" + encodeURIComponent( params[ i ] ) );
}
return url + ( ( url.indexOf( "?" ) != -1 ) ? "&" : "?" ) + queryString.join( "&" );
}
/*
* Make a string's first character uppercase.
*
* @param {String}
* str String.
*/
function ucFirst( str )
{
str += '';
var f = str.charAt( 0 ).toUpperCase();
return f + str.substr( 1 );
}
/*
* The onlick function assigned to the 'Browse Server' button. Opens the
* file browser and updates target field when file is selected.
*
* @param {CKEDITOR.event}
* evt The event object.
*/
function browseServer( evt )
{
var dialog = this.getDialog();
var editor = dialog.getParentEditor();
editor._.filebrowserSe = this;
var width = editor.config[ 'filebrowser' + ucFirst( dialog.getName() ) + 'WindowWidth' ]
|| editor.config.filebrowserWindowWidth || '80%';
var height = editor.config[ 'filebrowser' + ucFirst( dialog.getName() ) + 'WindowHeight' ]
|| editor.config.filebrowserWindowHeight || '70%';
var params = this.filebrowser.params || {};
params.CKEditor = editor.name;
params.CKEditorFuncNum = editor._.filebrowserFn;
if ( !params.langCode )
params.langCode = editor.langCode;
var url = addQueryString( this.filebrowser.url, params );
// TODO: V4: Remove backward compatibility (#8163).
editor.popup( url, width, height, editor.config.filebrowserWindowFeatures || editor.config.fileBrowserWindowFeatures );
}
/*
* The onlick function assigned to the 'Upload' button. Makes the final
* decision whether form is really submitted and updates target field when
* file is uploaded.
*
* @param {CKEDITOR.event}
* evt The event object.
*/
function uploadFile( evt )
{
var dialog = this.getDialog();
var editor = dialog.getParentEditor();
editor._.filebrowserSe = this;
// If user didn't select the file, stop the upload.
if ( !dialog.getContentElement( this[ 'for' ][ 0 ], this[ 'for' ][ 1 ] ).getInputElement().$.value )
return false;
if ( !dialog.getContentElement( this[ 'for' ][ 0 ], this[ 'for' ][ 1 ] ).getAction() )
return false;
return true;
}
/*
* Setups the file element.
*
* @param {CKEDITOR.ui.dialog.file}
* fileInput The file element used during file upload.
* @param {Object}
* filebrowser Object containing filebrowser settings assigned to
* the fileButton associated with this file element.
*/
function setupFileElement( editor, fileInput, filebrowser )
{
var params = filebrowser.params || {};
params.CKEditor = editor.name;
params.CKEditorFuncNum = editor._.filebrowserFn;
if ( !params.langCode )
params.langCode = editor.langCode;
fileInput.action = addQueryString( filebrowser.url, params );
fileInput.filebrowser = filebrowser;
}
/*
* Traverse through the content definition and attach filebrowser to
* elements with 'filebrowser' attribute.
*
* @param String
* dialogName Dialog name.
* @param {CKEDITOR.dialog.definitionObject}
* definition Dialog definition.
* @param {Array}
* elements Array of {@link CKEDITOR.dialog.definition.content}
* objects.
*/
function attachFileBrowser( editor, dialogName, definition, elements )
{
var element, fileInput;
for ( var i in elements )
{
element = elements[ i ];
if ( element.type == 'hbox' || element.type == 'vbox' )
attachFileBrowser( editor, dialogName, definition, element.children );
if ( !element.filebrowser )
continue;
if ( typeof element.filebrowser == 'string' )
{
var fb =
{
action : ( element.type == 'fileButton' ) ? 'QuickUpload' : 'Browse',
target : element.filebrowser
};
element.filebrowser = fb;
}
if ( element.filebrowser.action == 'Browse' )
{
var url = element.filebrowser.url;
if ( url === undefined )
{
url = editor.config[ 'filebrowser' + ucFirst( dialogName ) + 'BrowseUrl' ];
if ( url === undefined )
url = editor.config.filebrowserBrowseUrl;
}
if ( url )
{
element.onClick = browseServer;
element.filebrowser.url = url;
element.hidden = false;
}
}
else if ( element.filebrowser.action == 'QuickUpload' && element[ 'for' ] )
{
url = element.filebrowser.url;
if ( url === undefined )
{
url = editor.config[ 'filebrowser' + ucFirst( dialogName ) + 'UploadUrl' ];
if ( url === undefined )
url = editor.config.filebrowserUploadUrl;
}
if ( url )
{
var onClick = element.onClick;
element.onClick = function( evt )
{
// "element" here means the definition object, so we need to find the correct
// button to scope the event call
var sender = evt.sender;
if ( onClick && onClick.call( sender, evt ) === false )
return false;
return uploadFile.call( sender, evt );
};
element.filebrowser.url = url;
element.hidden = false;
setupFileElement( editor, definition.getContents( element[ 'for' ][ 0 ] ).get( element[ 'for' ][ 1 ] ), element.filebrowser );
}
}
}
}
/*
* Updates the target element with the url of uploaded/selected file.
*
* @param {String}
* url The url of a file.
*/
function updateTargetElement( url, sourceElement )
{
var dialog = sourceElement.getDialog();
var targetElement = sourceElement.filebrowser.target || null;
url = url.replace( /#/g, '%23' );
// If there is a reference to targetElement, update it.
if ( targetElement )
{
var target = targetElement.split( ':' );
var element = dialog.getContentElement( target[ 0 ], target[ 1 ] );
if ( element )
{
element.setValue( url );
dialog.selectPage( target[ 0 ] );
}
}
}
/*
* Returns true if filebrowser is configured in one of the elements.
*
* @param {CKEDITOR.dialog.definitionObject}
* definition Dialog definition.
* @param String
* tabId The tab id where element(s) can be found.
* @param String
* elementId The element id (or ids, separated with a semicolon) to check.
*/
function isConfigured( definition, tabId, elementId )
{
if ( elementId.indexOf( ";" ) !== -1 )
{
var ids = elementId.split( ";" );
for ( var i = 0 ; i < ids.length ; i++ )
{
if ( isConfigured( definition, tabId, ids[i] ) )
return true;
}
return false;
}
var elementFileBrowser = definition.getContents( tabId ).get( elementId ).filebrowser;
return ( elementFileBrowser && elementFileBrowser.url );
}
function setUrl( fileUrl, data )
{
var dialog = this._.filebrowserSe.getDialog(),
targetInput = this._.filebrowserSe[ 'for' ],
onSelect = this._.filebrowserSe.filebrowser.onSelect;
if ( targetInput )
dialog.getContentElement( targetInput[ 0 ], targetInput[ 1 ] ).reset();
if ( typeof data == 'function' && data.call( this._.filebrowserSe ) === false )
return;
if ( onSelect && onSelect.call( this._.filebrowserSe, fileUrl, data ) === false )
return;
// The "data" argument may be used to pass the error message to the editor.
if ( typeof data == 'string' && data )
alert( data );
if ( fileUrl )
updateTargetElement( fileUrl, this._.filebrowserSe );
}
CKEDITOR.plugins.add( 'filebrowser',
{
init : function( editor, pluginPath )
{
editor._.filebrowserFn = CKEDITOR.tools.addFunction( setUrl, editor );
editor.on( 'destroy', function () { CKEDITOR.tools.removeFunction( this._.filebrowserFn ); } );
}
} );
CKEDITOR.on( 'dialogDefinition', function( evt )
{
var definition = evt.data.definition,
element;
// Associate filebrowser to elements with 'filebrowser' attribute.
for ( var i in definition.contents )
{
if ( ( element = definition.contents[ i ] ) )
{
attachFileBrowser( evt.editor, evt.data.name, definition, element.elements );
if ( element.hidden && element.filebrowser )
{
element.hidden = !isConfigured( definition, element[ 'id' ], element.filebrowser );
}
}
}
} );
} )();
/**
* The location of an external file browser that should be launched when the <strong>Browse Server</strong>
* button is pressed. If configured, the <strong>Browse Server</strong> button will appear in the
* <strong>Link</strong>, <strong>Image</strong>, and <strong>Flash</strong> dialog windows.
* @see The <a href="http://docs.cksource.com/CKEditor_3.x/Developers_Guide/File_Browser_(Uploader)">File Browser/Uploader</a> documentation.
* @name CKEDITOR.config.filebrowserBrowseUrl
* @since 3.0
* @type String
* @default <code>''</code> (empty string = disabled)
* @example
* config.filebrowserBrowseUrl = '/browser/browse.php';
*/
/**
* The location of the script that handles file uploads.
* If set, the <strong>Upload</strong> tab will appear in the <strong>Link</strong>, <strong>Image</strong>,
* and <strong>Flash</strong> dialog windows.
* @name CKEDITOR.config.filebrowserUploadUrl
* @see The <a href="http://docs.cksource.com/CKEditor_3.x/Developers_Guide/File_Browser_(Uploader)">File Browser/Uploader</a> documentation.
* @since 3.0
* @type String
* @default <code>''</code> (empty string = disabled)
* @example
* config.filebrowserUploadUrl = '/uploader/upload.php';
*/
/**
* The location of an external file browser that should be launched when the <strong>Browse Server</strong>
* button is pressed in the <strong>Image</strong> dialog window.
* If not set, CKEditor will use <code>{@link CKEDITOR.config.filebrowserBrowseUrl}</code>.
* @name CKEDITOR.config.filebrowserImageBrowseUrl
* @since 3.0
* @type String
* @default <code>''</code> (empty string = disabled)
* @example
* config.filebrowserImageBrowseUrl = '/browser/browse.php?type=Images';
*/
/**
* The location of an external file browser that should be launched when the <strong>Browse Server</strong>
* button is pressed in the <strong>Flash</strong> dialog window.
* If not set, CKEditor will use <code>{@link CKEDITOR.config.filebrowserBrowseUrl}</code>.
* @name CKEDITOR.config.filebrowserFlashBrowseUrl
* @since 3.0
* @type String
* @default <code>''</code> (empty string = disabled)
* @example
* config.filebrowserFlashBrowseUrl = '/browser/browse.php?type=Flash';
*/
/**
* The location of the script that handles file uploads in the <strong>Image</strong> dialog window.
* If not set, CKEditor will use <code>{@link CKEDITOR.config.filebrowserUploadUrl}</code>.
* @name CKEDITOR.config.filebrowserImageUploadUrl
* @since 3.0
* @type String
* @default <code>''</code> (empty string = disabled)
* @example
* config.filebrowserImageUploadUrl = '/uploader/upload.php?type=Images';
*/
/**
* The location of the script that handles file uploads in the <strong>Flash</strong> dialog window.
* If not set, CKEditor will use <code>{@link CKEDITOR.config.filebrowserUploadUrl}</code>.
* @name CKEDITOR.config.filebrowserFlashUploadUrl
* @since 3.0
* @type String
* @default <code>''</code> (empty string = disabled)
* @example
* config.filebrowserFlashUploadUrl = '/uploader/upload.php?type=Flash';
*/
/**
* The location of an external file browser that should be launched when the <strong>Browse Server</strong>
* button is pressed in the <strong>Link</strong> tab of the <strong>Image</strong> dialog window.
* If not set, CKEditor will use <code>{@link CKEDITOR.config.filebrowserBrowseUrl}</code>.
* @name CKEDITOR.config.filebrowserImageBrowseLinkUrl
* @since 3.2
* @type String
* @default <code>''</code> (empty string = disabled)
* @example
* config.filebrowserImageBrowseLinkUrl = '/browser/browse.php';
*/
/**
* The features to use in the file browser popup window.
* @name CKEDITOR.config.filebrowserWindowFeatures
* @since 3.4.1
* @type String
* @default <code>'location=no,menubar=no,toolbar=no,dependent=yes,minimizable=no,modal=yes,alwaysRaised=yes,resizable=yes,scrollbars=yes'</code>
* @example
* config.filebrowserWindowFeatures = 'resizable=yes,scrollbars=no';
*/
/**
* The width of the file browser popup window. It can be a number denoting a value in
* pixels or a percent string.
* @name CKEDITOR.config.filebrowserWindowWidth
* @type Number|String
* @default <code>'80%'</code>
* @example
* config.filebrowserWindowWidth = 750;
* @example
* config.filebrowserWindowWidth = '50%';
*/
/**
* The height of the file browser popup window. It can be a number denoting a value in
* pixels or a percent string.
* @name CKEDITOR.config.filebrowserWindowHeight
* @type Number|String
* @default <code>'70%'</code>
* @example
* config.filebrowserWindowHeight = 580;
* @example
* config.filebrowserWindowHeight = '50%';
*/ | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/_source/plugins/filebrowser/plugin.js | plugin.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.add( 'htmlwriter' );
/**
* Class used to write HTML data.
* @constructor
* @example
* var writer = new CKEDITOR.htmlWriter();
* writer.openTag( 'p' );
* writer.attribute( 'class', 'MyClass' );
* writer.openTagClose( 'p' );
* writer.text( 'Hello' );
* writer.closeTag( 'p' );
* alert( writer.getHtml() ); "<p class="MyClass">Hello</p>"
*/
CKEDITOR.htmlWriter = CKEDITOR.tools.createClass(
{
base : CKEDITOR.htmlParser.basicWriter,
$ : function()
{
// Call the base contructor.
this.base();
/**
* The characters to be used for each identation step.
* @type String
* @default "\t" (tab)
* @example
* // Use two spaces for indentation.
* editorInstance.dataProcessor.writer.indentationChars = ' ';
*/
this.indentationChars = '\t';
/**
* The characters to be used to close "self-closing" elements, like "br" or
* "img".
* @type String
* @default " />"
* @example
* // Use HTML4 notation for self-closing elements.
* editorInstance.dataProcessor.writer.selfClosingEnd = '>';
*/
this.selfClosingEnd = ' />';
/**
* The characters to be used for line breaks.
* @type String
* @default "\n" (LF)
* @example
* // Use CRLF for line breaks.
* editorInstance.dataProcessor.writer.lineBreakChars = '\r\n';
*/
this.lineBreakChars = '\n';
this.forceSimpleAmpersand = 0;
this.sortAttributes = 1;
this._.indent = 0;
this._.indentation = '';
// Indicate preformatted block context status. (#5789)
this._.inPre = 0;
this._.rules = {};
var dtd = CKEDITOR.dtd;
for ( var e in CKEDITOR.tools.extend( {}, dtd.$nonBodyContent, dtd.$block, dtd.$listItem, dtd.$tableContent ) )
{
this.setRules( e,
{
indent : 1,
breakBeforeOpen : 1,
breakAfterOpen : 1,
breakBeforeClose : !dtd[ e ][ '#' ],
breakAfterClose : 1
});
}
this.setRules( 'br',
{
breakAfterOpen : 1
});
this.setRules( 'title',
{
indent : 0,
breakAfterOpen : 0
});
this.setRules( 'style',
{
indent : 0,
breakBeforeClose : 1
});
// Disable indentation on <pre>.
this.setRules( 'pre',
{
indent : 0
});
},
proto :
{
/**
* Writes the tag opening part for a opener tag.
* @param {String} tagName The element name for this tag.
* @param {Object} attributes The attributes defined for this tag. The
* attributes could be used to inspect the tag.
* @example
* // Writes "<p".
* writer.openTag( 'p', { class : 'MyClass', id : 'MyId' } );
*/
openTag : function( tagName, attributes )
{
var rules = this._.rules[ tagName ];
if ( this._.indent )
this.indentation();
// Do not break if indenting.
else if ( rules && rules.breakBeforeOpen )
{
this.lineBreak();
this.indentation();
}
this._.output.push( '<', tagName );
},
/**
* Writes the tag closing part for a opener tag.
* @param {String} tagName The element name for this tag.
* @param {Boolean} isSelfClose Indicates that this is a self-closing tag,
* like "br" or "img".
* @example
* // Writes ">".
* writer.openTagClose( 'p', false );
* @example
* // Writes " />".
* writer.openTagClose( 'br', true );
*/
openTagClose : function( tagName, isSelfClose )
{
var rules = this._.rules[ tagName ];
if ( isSelfClose )
this._.output.push( this.selfClosingEnd );
else
{
this._.output.push( '>' );
if ( rules && rules.indent )
this._.indentation += this.indentationChars;
}
if ( rules && rules.breakAfterOpen )
this.lineBreak();
tagName == 'pre' && ( this._.inPre = 1 );
},
/**
* Writes an attribute. This function should be called after opening the
* tag with {@link #openTagClose}.
* @param {String} attName The attribute name.
* @param {String} attValue The attribute value.
* @example
* // Writes ' class="MyClass"'.
* writer.attribute( 'class', 'MyClass' );
*/
attribute : function( attName, attValue )
{
if ( typeof attValue == 'string' )
{
this.forceSimpleAmpersand && ( attValue = attValue.replace( /&/g, '&' ) );
// Browsers don't always escape special character in attribute values. (#4683, #4719).
attValue = CKEDITOR.tools.htmlEncodeAttr( attValue );
}
this._.output.push( ' ', attName, '="', attValue, '"' );
},
/**
* Writes a closer tag.
* @param {String} tagName The element name for this tag.
* @example
* // Writes "</p>".
* writer.closeTag( 'p' );
*/
closeTag : function( tagName )
{
var rules = this._.rules[ tagName ];
if ( rules && rules.indent )
this._.indentation = this._.indentation.substr( this.indentationChars.length );
if ( this._.indent )
this.indentation();
// Do not break if indenting.
else if ( rules && rules.breakBeforeClose )
{
this.lineBreak();
this.indentation();
}
this._.output.push( '</', tagName, '>' );
tagName == 'pre' && ( this._.inPre = 0 );
if ( rules && rules.breakAfterClose )
this.lineBreak();
},
/**
* Writes text.
* @param {String} text The text value
* @example
* // Writes "Hello Word".
* writer.text( 'Hello Word' );
*/
text : function( text )
{
if ( this._.indent )
{
this.indentation();
!this._.inPre && ( text = CKEDITOR.tools.ltrim( text ) );
}
this._.output.push( text );
},
/**
* Writes a comment.
* @param {String} comment The comment text.
* @example
* // Writes "<!-- My comment -->".
* writer.comment( ' My comment ' );
*/
comment : function( comment )
{
if ( this._.indent )
this.indentation();
this._.output.push( '<!--', comment, '-->' );
},
/**
* Writes a line break. It uses the {@link #lineBreakChars} property for it.
* @example
* // Writes "\n" (e.g.).
* writer.lineBreak();
*/
lineBreak : function()
{
if ( !this._.inPre && this._.output.length > 0 )
this._.output.push( this.lineBreakChars );
this._.indent = 1;
},
/**
* Writes the current indentation chars. It uses the
* {@link #indentationChars} property, repeating it for the current
* indentation steps.
* @example
* // Writes "\t" (e.g.).
* writer.indentation();
*/
indentation : function()
{
if( !this._.inPre )
this._.output.push( this._.indentation );
this._.indent = 0;
},
/**
* Sets formatting rules for a give element. The possible rules are:
* <ul>
* <li><b>indent</b>: indent the element contents.</li>
* <li><b>breakBeforeOpen</b>: break line before the opener tag for this element.</li>
* <li><b>breakAfterOpen</b>: break line after the opener tag for this element.</li>
* <li><b>breakBeforeClose</b>: break line before the closer tag for this element.</li>
* <li><b>breakAfterClose</b>: break line after the closer tag for this element.</li>
* </ul>
*
* All rules default to "false". Each call to the function overrides
* already present rules, leaving the undefined untouched.
*
* By default, all elements available in the {@link CKEDITOR.dtd.$block),
* {@link CKEDITOR.dtd.$listItem} and {@link CKEDITOR.dtd.$tableContent}
* lists have all the above rules set to "true". Additionaly, the "br"
* element has the "breakAfterOpen" set to "true".
* @param {String} tagName The element name to which set the rules.
* @param {Object} rules An object containing the element rules.
* @example
* // Break line before and after "img" tags.
* writer.setRules( 'img',
* {
* breakBeforeOpen : true
* breakAfterOpen : true
* });
* @example
* // Reset the rules for the "h1" tag.
* writer.setRules( 'h1', {} );
*/
setRules : function( tagName, rules )
{
var currentRules = this._.rules[ tagName ];
if ( currentRules )
CKEDITOR.tools.extend( currentRules, rules, true );
else
this._.rules[ tagName ] = rules;
}
}
}); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/_source/plugins/htmlwriter/plugin.js | plugin.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
var flashFilenameRegex = /\.swf(?:$|\?)/i;
function isFlashEmbed( element )
{
var attributes = element.attributes;
return ( attributes.type == 'application/x-shockwave-flash' || flashFilenameRegex.test( attributes.src || '' ) );
}
function createFakeElement( editor, realElement )
{
return editor.createFakeParserElement( realElement, 'cke_flash', 'flash', true );
}
CKEDITOR.plugins.add( 'flash',
{
init : function( editor )
{
editor.addCommand( 'flash', new CKEDITOR.dialogCommand( 'flash' ) );
editor.ui.addButton( 'Flash',
{
label : editor.lang.common.flash,
command : 'flash'
});
CKEDITOR.dialog.add( 'flash', this.path + 'dialogs/flash.js' );
editor.addCss(
'img.cke_flash' +
'{' +
'background-image: url(' + CKEDITOR.getUrl( this.path + 'images/placeholder.png' ) + ');' +
'background-position: center center;' +
'background-repeat: no-repeat;' +
'border: 1px solid #a9a9a9;' +
'width: 80px;' +
'height: 80px;' +
'}'
);
// If the "menu" plugin is loaded, register the menu items.
if ( editor.addMenuItems )
{
editor.addMenuItems(
{
flash :
{
label : editor.lang.flash.properties,
command : 'flash',
group : 'flash'
}
});
}
editor.on( 'doubleclick', function( evt )
{
var element = evt.data.element;
if ( element.is( 'img' ) && element.data( 'cke-real-element-type' ) == 'flash' )
evt.data.dialog = 'flash';
});
// If the "contextmenu" plugin is loaded, register the listeners.
if ( editor.contextMenu )
{
editor.contextMenu.addListener( function( element, selection )
{
if ( element && element.is( 'img' ) && !element.isReadOnly()
&& element.data( 'cke-real-element-type' ) == 'flash' )
return { flash : CKEDITOR.TRISTATE_OFF };
});
}
},
afterInit : function( editor )
{
var dataProcessor = editor.dataProcessor,
dataFilter = dataProcessor && dataProcessor.dataFilter;
if ( dataFilter )
{
dataFilter.addRules(
{
elements :
{
'cke:object' : function( element )
{
var attributes = element.attributes,
classId = attributes.classid && String( attributes.classid ).toLowerCase();
if ( !classId && !isFlashEmbed( element ) )
{
// Look for the inner <embed>
for ( var i = 0 ; i < element.children.length ; i++ )
{
if ( element.children[ i ].name == 'cke:embed' )
{
if ( !isFlashEmbed( element.children[ i ] ) )
return null;
return createFakeElement( editor, element );
}
}
return null;
}
return createFakeElement( editor, element );
},
'cke:embed' : function( element )
{
if ( !isFlashEmbed( element ) )
return null;
return createFakeElement( editor, element );
}
}
},
5);
}
},
requires : [ 'fakeobjects' ]
});
})();
CKEDITOR.tools.extend( CKEDITOR.config,
{
/**
* Save as EMBED tag only. This tag is unrecommended.
* @type Boolean
* @default false
*/
flashEmbedTagOnly : false,
/**
* Add EMBED tag as alternative: <object><embed></embed></object>
* @type Boolean
* @default false
*/
flashAddEmbedTag : true,
/**
* Use embedTagOnly and addEmbedTag values on edit.
* @type Boolean
* @default false
*/
flashConvertOnEdit : false
} ); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/_source/plugins/flash/plugin.js | plugin.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
/*
* It is possible to set things in three different places.
* 1. As attributes in the object tag.
* 2. As param tags under the object tag.
* 3. As attributes in the embed tag.
* It is possible for a single attribute to be present in more than one place.
* So let's define a mapping between a sementic attribute and its syntactic
* equivalents.
* Then we'll set and retrieve attribute values according to the mapping,
* instead of having to check and set each syntactic attribute every time.
*
* Reference: http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_12701
*/
var ATTRTYPE_OBJECT = 1,
ATTRTYPE_PARAM = 2,
ATTRTYPE_EMBED = 4;
var attributesMap =
{
id : [ { type : ATTRTYPE_OBJECT, name : 'id' } ],
classid : [ { type : ATTRTYPE_OBJECT, name : 'classid' } ],
codebase : [ { type : ATTRTYPE_OBJECT, name : 'codebase'} ],
pluginspage : [ { type : ATTRTYPE_EMBED, name : 'pluginspage' } ],
src : [ { type : ATTRTYPE_PARAM, name : 'movie' }, { type : ATTRTYPE_EMBED, name : 'src' }, { type : ATTRTYPE_OBJECT, name : 'data' } ],
name : [ { type : ATTRTYPE_EMBED, name : 'name' } ],
align : [ { type : ATTRTYPE_OBJECT, name : 'align' } ],
title : [ { type : ATTRTYPE_OBJECT, name : 'title' }, { type : ATTRTYPE_EMBED, name : 'title' } ],
'class' : [ { type : ATTRTYPE_OBJECT, name : 'class' }, { type : ATTRTYPE_EMBED, name : 'class'} ],
width : [ { type : ATTRTYPE_OBJECT, name : 'width' }, { type : ATTRTYPE_EMBED, name : 'width' } ],
height : [ { type : ATTRTYPE_OBJECT, name : 'height' }, { type : ATTRTYPE_EMBED, name : 'height' } ],
hSpace : [ { type : ATTRTYPE_OBJECT, name : 'hSpace' }, { type : ATTRTYPE_EMBED, name : 'hSpace' } ],
vSpace : [ { type : ATTRTYPE_OBJECT, name : 'vSpace' }, { type : ATTRTYPE_EMBED, name : 'vSpace' } ],
style : [ { type : ATTRTYPE_OBJECT, name : 'style' }, { type : ATTRTYPE_EMBED, name : 'style' } ],
type : [ { type : ATTRTYPE_EMBED, name : 'type' } ]
};
var names = [ 'play', 'loop', 'menu', 'quality', 'scale', 'salign', 'wmode', 'bgcolor', 'base', 'flashvars', 'allowScriptAccess',
'allowFullScreen' ];
for ( var i = 0 ; i < names.length ; i++ )
attributesMap[ names[i] ] = [ { type : ATTRTYPE_EMBED, name : names[i] }, { type : ATTRTYPE_PARAM, name : names[i] } ];
names = [ 'allowFullScreen', 'play', 'loop', 'menu' ];
for ( i = 0 ; i < names.length ; i++ )
attributesMap[ names[i] ][0]['default'] = attributesMap[ names[i] ][1]['default'] = true;
var defaultToPixel = CKEDITOR.tools.cssLength;
function loadValue( objectNode, embedNode, paramMap )
{
var attributes = attributesMap[ this.id ];
if ( !attributes )
return;
var isCheckbox = ( this instanceof CKEDITOR.ui.dialog.checkbox );
for ( var i = 0 ; i < attributes.length ; i++ )
{
var attrDef = attributes[ i ];
switch ( attrDef.type )
{
case ATTRTYPE_OBJECT:
if ( !objectNode )
continue;
if ( objectNode.getAttribute( attrDef.name ) !== null )
{
var value = objectNode.getAttribute( attrDef.name );
if ( isCheckbox )
this.setValue( value.toLowerCase() == 'true' );
else
this.setValue( value );
return;
}
else if ( isCheckbox )
this.setValue( !!attrDef[ 'default' ] );
break;
case ATTRTYPE_PARAM:
if ( !objectNode )
continue;
if ( attrDef.name in paramMap )
{
value = paramMap[ attrDef.name ];
if ( isCheckbox )
this.setValue( value.toLowerCase() == 'true' );
else
this.setValue( value );
return;
}
else if ( isCheckbox )
this.setValue( !!attrDef[ 'default' ] );
break;
case ATTRTYPE_EMBED:
if ( !embedNode )
continue;
if ( embedNode.getAttribute( attrDef.name ) )
{
value = embedNode.getAttribute( attrDef.name );
if ( isCheckbox )
this.setValue( value.toLowerCase() == 'true' );
else
this.setValue( value );
return;
}
else if ( isCheckbox )
this.setValue( !!attrDef[ 'default' ] );
}
}
}
function commitValue( objectNode, embedNode, paramMap )
{
var attributes = attributesMap[ this.id ];
if ( !attributes )
return;
var isRemove = ( this.getValue() === '' ),
isCheckbox = ( this instanceof CKEDITOR.ui.dialog.checkbox );
for ( var i = 0 ; i < attributes.length ; i++ )
{
var attrDef = attributes[i];
switch ( attrDef.type )
{
case ATTRTYPE_OBJECT:
// Avoid applying the data attribute when not needed (#7733)
if ( !objectNode || ( attrDef.name == 'data' && embedNode && !objectNode.hasAttribute( 'data' ) ) )
continue;
var value = this.getValue();
if ( isRemove || isCheckbox && value === attrDef[ 'default' ] )
objectNode.removeAttribute( attrDef.name );
else
objectNode.setAttribute( attrDef.name, value );
break;
case ATTRTYPE_PARAM:
if ( !objectNode )
continue;
value = this.getValue();
if ( isRemove || isCheckbox && value === attrDef[ 'default' ] )
{
if ( attrDef.name in paramMap )
paramMap[ attrDef.name ].remove();
}
else
{
if ( attrDef.name in paramMap )
paramMap[ attrDef.name ].setAttribute( 'value', value );
else
{
var param = CKEDITOR.dom.element.createFromHtml( '<cke:param></cke:param>', objectNode.getDocument() );
param.setAttributes( { name : attrDef.name, value : value } );
if ( objectNode.getChildCount() < 1 )
param.appendTo( objectNode );
else
param.insertBefore( objectNode.getFirst() );
}
}
break;
case ATTRTYPE_EMBED:
if ( !embedNode )
continue;
value = this.getValue();
if ( isRemove || isCheckbox && value === attrDef[ 'default' ])
embedNode.removeAttribute( attrDef.name );
else
embedNode.setAttribute( attrDef.name, value );
}
}
}
CKEDITOR.dialog.add( 'flash', function( editor )
{
var makeObjectTag = !editor.config.flashEmbedTagOnly,
makeEmbedTag = editor.config.flashAddEmbedTag || editor.config.flashEmbedTagOnly;
var previewPreloader,
previewAreaHtml = '<div>' + CKEDITOR.tools.htmlEncode( editor.lang.common.preview ) +'<br>' +
'<div id="cke_FlashPreviewLoader' + CKEDITOR.tools.getNextNumber() + '" style="display:none"><div class="loading"> </div></div>' +
'<div id="cke_FlashPreviewBox' + CKEDITOR.tools.getNextNumber() + '" class="FlashPreviewBox"></div></div>';
return {
title : editor.lang.flash.title,
minWidth : 420,
minHeight : 310,
onShow : function()
{
// Clear previously saved elements.
this.fakeImage = this.objectNode = this.embedNode = null;
previewPreloader = new CKEDITOR.dom.element( 'embed', editor.document );
// Try to detect any embed or object tag that has Flash parameters.
var fakeImage = this.getSelectedElement();
if ( fakeImage && fakeImage.data( 'cke-real-element-type' ) && fakeImage.data( 'cke-real-element-type' ) == 'flash' )
{
this.fakeImage = fakeImage;
var realElement = editor.restoreRealElement( fakeImage ),
objectNode = null, embedNode = null, paramMap = {};
if ( realElement.getName() == 'cke:object' )
{
objectNode = realElement;
var embedList = objectNode.getElementsByTag( 'embed', 'cke' );
if ( embedList.count() > 0 )
embedNode = embedList.getItem( 0 );
var paramList = objectNode.getElementsByTag( 'param', 'cke' );
for ( var i = 0, length = paramList.count() ; i < length ; i++ )
{
var item = paramList.getItem( i ),
name = item.getAttribute( 'name' ),
value = item.getAttribute( 'value' );
paramMap[ name ] = value;
}
}
else if ( realElement.getName() == 'cke:embed' )
embedNode = realElement;
this.objectNode = objectNode;
this.embedNode = embedNode;
this.setupContent( objectNode, embedNode, paramMap, fakeImage );
}
},
onOk : function()
{
// If there's no selected object or embed, create one. Otherwise, reuse the
// selected object and embed nodes.
var objectNode = null,
embedNode = null,
paramMap = null;
if ( !this.fakeImage )
{
if ( makeObjectTag )
{
objectNode = CKEDITOR.dom.element.createFromHtml( '<cke:object></cke:object>', editor.document );
var attributes = {
classid : 'clsid:d27cdb6e-ae6d-11cf-96b8-444553540000',
codebase : 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0'
};
objectNode.setAttributes( attributes );
}
if ( makeEmbedTag )
{
embedNode = CKEDITOR.dom.element.createFromHtml( '<cke:embed></cke:embed>', editor.document );
embedNode.setAttributes(
{
type : 'application/x-shockwave-flash',
pluginspage : 'http://www.macromedia.com/go/getflashplayer'
} );
if ( objectNode )
embedNode.appendTo( objectNode );
}
}
else
{
objectNode = this.objectNode;
embedNode = this.embedNode;
}
// Produce the paramMap if there's an object tag.
if ( objectNode )
{
paramMap = {};
var paramList = objectNode.getElementsByTag( 'param', 'cke' );
for ( var i = 0, length = paramList.count() ; i < length ; i++ )
paramMap[ paramList.getItem( i ).getAttribute( 'name' ) ] = paramList.getItem( i );
}
// A subset of the specified attributes/styles
// should also be applied on the fake element to
// have better visual effect. (#5240)
var extraStyles = {}, extraAttributes = {};
this.commitContent( objectNode, embedNode, paramMap, extraStyles, extraAttributes );
// Refresh the fake image.
var newFakeImage = editor.createFakeElement( objectNode || embedNode, 'cke_flash', 'flash', true );
newFakeImage.setAttributes( extraAttributes );
newFakeImage.setStyles( extraStyles );
if ( this.fakeImage )
{
newFakeImage.replace( this.fakeImage );
editor.getSelection().selectElement( newFakeImage );
}
else
editor.insertElement( newFakeImage );
},
onHide : function()
{
if ( this.preview )
this.preview.setHtml('');
},
contents : [
{
id : 'info',
label : editor.lang.common.generalTab,
accessKey : 'I',
elements :
[
{
type : 'vbox',
padding : 0,
children :
[
{
type : 'hbox',
widths : [ '280px', '110px' ],
align : 'right',
children :
[
{
id : 'src',
type : 'text',
label : editor.lang.common.url,
required : true,
validate : CKEDITOR.dialog.validate.notEmpty( editor.lang.flash.validateSrc ),
setup : loadValue,
commit : commitValue,
onLoad : function()
{
var dialog = this.getDialog(),
updatePreview = function( src ){
// Query the preloader to figure out the url impacted by based href.
previewPreloader.setAttribute( 'src', src );
dialog.preview.setHtml( '<embed height="100%" width="100%" src="'
+ CKEDITOR.tools.htmlEncode( previewPreloader.getAttribute( 'src' ) )
+ '" type="application/x-shockwave-flash"></embed>' );
};
// Preview element
dialog.preview = dialog.getContentElement( 'info', 'preview' ).getElement().getChild( 3 );
// Sync on inital value loaded.
this.on( 'change', function( evt ){
if ( evt.data && evt.data.value )
updatePreview( evt.data.value );
} );
// Sync when input value changed.
this.getInputElement().on( 'change', function( evt ){
updatePreview( this.getValue() );
}, this );
}
},
{
type : 'button',
id : 'browse',
filebrowser : 'info:src',
hidden : true,
// v-align with the 'src' field.
// TODO: We need something better than a fixed size here.
style : 'display:inline-block;margin-top:10px;',
label : editor.lang.common.browseServer
}
]
}
]
},
{
type : 'hbox',
widths : [ '25%', '25%', '25%', '25%', '25%' ],
children :
[
{
type : 'text',
id : 'width',
style : 'width:95px',
label : editor.lang.common.width,
validate : CKEDITOR.dialog.validate.htmlLength( editor.lang.common.invalidHtmlLength.replace( '%1', editor.lang.common.width ) ),
setup : loadValue,
commit : commitValue
},
{
type : 'text',
id : 'height',
style : 'width:95px',
label : editor.lang.common.height,
validate : CKEDITOR.dialog.validate.htmlLength( editor.lang.common.invalidHtmlLength.replace( '%1', editor.lang.common.height ) ),
setup : loadValue,
commit : commitValue
},
{
type : 'text',
id : 'hSpace',
style : 'width:95px',
label : editor.lang.flash.hSpace,
validate : CKEDITOR.dialog.validate.integer( editor.lang.flash.validateHSpace ),
setup : loadValue,
commit : commitValue
},
{
type : 'text',
id : 'vSpace',
style : 'width:95px',
label : editor.lang.flash.vSpace,
validate : CKEDITOR.dialog.validate.integer( editor.lang.flash.validateVSpace ),
setup : loadValue,
commit : commitValue
}
]
},
{
type : 'vbox',
children :
[
{
type : 'html',
id : 'preview',
style : 'width:95%;',
html : previewAreaHtml
}
]
}
]
},
{
id : 'Upload',
hidden : true,
filebrowser : 'uploadButton',
label : editor.lang.common.upload,
elements :
[
{
type : 'file',
id : 'upload',
label : editor.lang.common.upload,
size : 38
},
{
type : 'fileButton',
id : 'uploadButton',
label : editor.lang.common.uploadSubmit,
filebrowser : 'info:src',
'for' : [ 'Upload', 'upload' ]
}
]
},
{
id : 'properties',
label : editor.lang.flash.propertiesTab,
elements :
[
{
type : 'hbox',
widths : [ '50%', '50%' ],
children :
[
{
id : 'scale',
type : 'select',
label : editor.lang.flash.scale,
'default' : '',
style : 'width : 100%;',
items :
[
[ editor.lang.common.notSet , ''],
[ editor.lang.flash.scaleAll, 'showall' ],
[ editor.lang.flash.scaleNoBorder, 'noborder' ],
[ editor.lang.flash.scaleFit, 'exactfit' ]
],
setup : loadValue,
commit : commitValue
},
{
id : 'allowScriptAccess',
type : 'select',
label : editor.lang.flash.access,
'default' : '',
style : 'width : 100%;',
items :
[
[ editor.lang.common.notSet , ''],
[ editor.lang.flash.accessAlways, 'always' ],
[ editor.lang.flash.accessSameDomain, 'samedomain' ],
[ editor.lang.flash.accessNever, 'never' ]
],
setup : loadValue,
commit : commitValue
}
]
},
{
type : 'hbox',
widths : [ '50%', '50%' ],
children :
[
{
id : 'wmode',
type : 'select',
label : editor.lang.flash.windowMode,
'default' : '',
style : 'width : 100%;',
items :
[
[ editor.lang.common.notSet , '' ],
[ editor.lang.flash.windowModeWindow, 'window' ],
[ editor.lang.flash.windowModeOpaque, 'opaque' ],
[ editor.lang.flash.windowModeTransparent, 'transparent' ]
],
setup : loadValue,
commit : commitValue
},
{
id : 'quality',
type : 'select',
label : editor.lang.flash.quality,
'default' : 'high',
style : 'width : 100%;',
items :
[
[ editor.lang.common.notSet , '' ],
[ editor.lang.flash.qualityBest, 'best' ],
[ editor.lang.flash.qualityHigh, 'high' ],
[ editor.lang.flash.qualityAutoHigh, 'autohigh' ],
[ editor.lang.flash.qualityMedium, 'medium' ],
[ editor.lang.flash.qualityAutoLow, 'autolow' ],
[ editor.lang.flash.qualityLow, 'low' ]
],
setup : loadValue,
commit : commitValue
}
]
},
{
type : 'hbox',
widths : [ '50%', '50%' ],
children :
[
{
id : 'align',
type : 'select',
label : editor.lang.common.align,
'default' : '',
style : 'width : 100%;',
items :
[
[ editor.lang.common.notSet , ''],
[ editor.lang.common.alignLeft , 'left'],
[ editor.lang.flash.alignAbsBottom , 'absBottom'],
[ editor.lang.flash.alignAbsMiddle , 'absMiddle'],
[ editor.lang.flash.alignBaseline , 'baseline'],
[ editor.lang.common.alignBottom , 'bottom'],
[ editor.lang.common.alignMiddle , 'middle'],
[ editor.lang.common.alignRight , 'right'],
[ editor.lang.flash.alignTextTop , 'textTop'],
[ editor.lang.common.alignTop , 'top']
],
setup : loadValue,
commit : function( objectNode, embedNode, paramMap, extraStyles, extraAttributes )
{
var value = this.getValue();
commitValue.apply( this, arguments );
value && ( extraAttributes.align = value );
}
},
{
type : 'html',
html : '<div></div>'
}
]
},
{
type : 'fieldset',
label : CKEDITOR.tools.htmlEncode( editor.lang.flash.flashvars ),
children :
[
{
type : 'vbox',
padding : 0,
children :
[
{
type : 'checkbox',
id : 'menu',
label : editor.lang.flash.chkMenu,
'default' : true,
setup : loadValue,
commit : commitValue
},
{
type : 'checkbox',
id : 'play',
label : editor.lang.flash.chkPlay,
'default' : true,
setup : loadValue,
commit : commitValue
},
{
type : 'checkbox',
id : 'loop',
label : editor.lang.flash.chkLoop,
'default' : true,
setup : loadValue,
commit : commitValue
},
{
type : 'checkbox',
id : 'allowFullScreen',
label : editor.lang.flash.chkFull,
'default' : true,
setup : loadValue,
commit : commitValue
}
]
}
]
}
]
},
{
id : 'advanced',
label : editor.lang.common.advancedTab,
elements :
[
{
type : 'hbox',
widths : [ '45%', '55%' ],
children :
[
{
type : 'text',
id : 'id',
label : editor.lang.common.id,
setup : loadValue,
commit : commitValue
},
{
type : 'text',
id : 'title',
label : editor.lang.common.advisoryTitle,
setup : loadValue,
commit : commitValue
}
]
},
{
type : 'hbox',
widths : [ '45%', '55%' ],
children :
[
{
type : 'text',
id : 'bgcolor',
label : editor.lang.flash.bgcolor,
setup : loadValue,
commit : commitValue
},
{
type : 'text',
id : 'class',
label : editor.lang.common.cssClass,
setup : loadValue,
commit : commitValue
}
]
},
{
type : 'text',
id : 'style',
validate : CKEDITOR.dialog.validate.inlineStyle( editor.lang.common.invalidInlineStyle ),
label : editor.lang.common.cssStyle,
setup : loadValue,
commit : commitValue
}
]
}
]
};
} );
})(); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/_source/plugins/flash/dialogs/flash.js | flash.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
var defaultToPixel = CKEDITOR.tools.cssLength;
var commitValue = function( data )
{
var id = this.id;
if ( !data.info )
data.info = {};
data.info[id] = this.getValue();
};
function tableColumns( table )
{
var cols = 0, maxCols = 0;
for ( var i = 0, row, rows = table.$.rows.length; i < rows; i++ )
{
row = table.$.rows[ i ], cols = 0;
for ( var j = 0, cell, cells = row.cells.length; j < cells; j++ )
{
cell = row.cells[ j ];
cols += cell.colSpan;
}
cols > maxCols && ( maxCols = cols );
}
return maxCols;
}
function tableDialog( editor, command )
{
var makeElement = function( name )
{
return new CKEDITOR.dom.element( name, editor.document );
};
var dialogadvtab = editor.plugins.dialogadvtab;
return {
title : editor.lang.table.title,
minWidth : 310,
minHeight : CKEDITOR.env.ie ? 310 : 280,
onLoad : function()
{
var dialog = this;
var styles = dialog.getContentElement( 'advanced', 'advStyles' );
if ( styles )
{
styles.on( 'change', function( evt )
{
// Synchronize width value.
var width = this.getStyle( 'width', '' ),
txtWidth = dialog.getContentElement( 'info', 'txtWidth' );
txtWidth && txtWidth.setValue( width, true );
// Synchronize height value.
var height = this.getStyle( 'height', '' ),
txtHeight = dialog.getContentElement( 'info', 'txtHeight' );
txtHeight && txtHeight.setValue( height, true );
});
}
},
onShow : function()
{
// Detect if there's a selected table.
var selection = editor.getSelection(),
ranges = selection.getRanges(),
selectedTable = null;
var rowsInput = this.getContentElement( 'info', 'txtRows' ),
colsInput = this.getContentElement( 'info', 'txtCols' ),
widthInput = this.getContentElement( 'info', 'txtWidth' ),
heightInput = this.getContentElement( 'info', 'txtHeight' );
if ( command == 'tableProperties' )
{
if ( ( selectedTable = selection.getSelectedElement() ) )
selectedTable = selectedTable.getAscendant( 'table', true );
else if ( ranges.length > 0 )
{
// Webkit could report the following range on cell selection (#4948):
// <table><tr><td>[ </td></tr></table>]
if ( CKEDITOR.env.webkit )
ranges[ 0 ].shrink( CKEDITOR.NODE_ELEMENT );
var rangeRoot = ranges[0].getCommonAncestor( true );
selectedTable = rangeRoot.getAscendant( 'table', true );
}
// Save a reference to the selected table, and push a new set of default values.
this._.selectedElement = selectedTable;
}
// Enable or disable the row, cols, width fields.
if ( selectedTable )
{
this.setupContent( selectedTable );
rowsInput && rowsInput.disable();
colsInput && colsInput.disable();
}
else
{
rowsInput && rowsInput.enable();
colsInput && colsInput.enable();
}
// Call the onChange method for the widht and height fields so
// they get reflected into the Advanced tab.
widthInput && widthInput.onChange();
heightInput && heightInput.onChange();
},
onOk : function()
{
var selection = editor.getSelection(),
bms = this._.selectedElement && selection.createBookmarks();
var table = this._.selectedElement || makeElement( 'table' ),
me = this,
data = {};
this.commitContent( data, table );
if ( data.info )
{
var info = data.info;
// Generate the rows and cols.
if ( !this._.selectedElement )
{
var tbody = table.append( makeElement( 'tbody' ) ),
rows = parseInt( info.txtRows, 10 ) || 0,
cols = parseInt( info.txtCols, 10 ) || 0;
for ( var i = 0 ; i < rows ; i++ )
{
var row = tbody.append( makeElement( 'tr' ) );
for ( var j = 0 ; j < cols ; j++ )
{
var cell = row.append( makeElement( 'td' ) );
if ( !CKEDITOR.env.ie )
cell.append( makeElement( 'br' ) );
}
}
}
// Modify the table headers. Depends on having rows and cols generated
// correctly so it can't be done in commit functions.
// Should we make a <thead>?
var headers = info.selHeaders;
if ( !table.$.tHead && ( headers == 'row' || headers == 'both' ) )
{
var thead = new CKEDITOR.dom.element( table.$.createTHead() );
tbody = table.getElementsByTag( 'tbody' ).getItem( 0 );
var theRow = tbody.getElementsByTag( 'tr' ).getItem( 0 );
// Change TD to TH:
for ( i = 0 ; i < theRow.getChildCount() ; i++ )
{
var th = theRow.getChild( i );
// Skip bookmark nodes. (#6155)
if ( th.type == CKEDITOR.NODE_ELEMENT && !th.data( 'cke-bookmark' ) )
{
th.renameNode( 'th' );
th.setAttribute( 'scope', 'col' );
}
}
thead.append( theRow.remove() );
}
if ( table.$.tHead !== null && !( headers == 'row' || headers == 'both' ) )
{
// Move the row out of the THead and put it in the TBody:
thead = new CKEDITOR.dom.element( table.$.tHead );
tbody = table.getElementsByTag( 'tbody' ).getItem( 0 );
var previousFirstRow = tbody.getFirst();
while ( thead.getChildCount() > 0 )
{
theRow = thead.getFirst();
for ( i = 0; i < theRow.getChildCount() ; i++ )
{
var newCell = theRow.getChild( i );
if ( newCell.type == CKEDITOR.NODE_ELEMENT )
{
newCell.renameNode( 'td' );
newCell.removeAttribute( 'scope' );
}
}
theRow.insertBefore( previousFirstRow );
}
thead.remove();
}
// Should we make all first cells in a row TH?
if ( !this.hasColumnHeaders && ( headers == 'col' || headers == 'both' ) )
{
for ( row = 0 ; row < table.$.rows.length ; row++ )
{
newCell = new CKEDITOR.dom.element( table.$.rows[ row ].cells[ 0 ] );
newCell.renameNode( 'th' );
newCell.setAttribute( 'scope', 'row' );
}
}
// Should we make all first TH-cells in a row make TD? If 'yes' we do it the other way round :-)
if ( ( this.hasColumnHeaders ) && !( headers == 'col' || headers == 'both' ) )
{
for ( i = 0 ; i < table.$.rows.length ; i++ )
{
row = new CKEDITOR.dom.element( table.$.rows[i] );
if ( row.getParent().getName() == 'tbody' )
{
newCell = new CKEDITOR.dom.element( row.$.cells[0] );
newCell.renameNode( 'td' );
newCell.removeAttribute( 'scope' );
}
}
}
// Set the width and height.
info.txtHeight ? table.setStyle( 'height', info.txtHeight ) : table.removeStyle( 'height' );
info.txtWidth ? table.setStyle( 'width', info.txtWidth ) : table.removeStyle( 'width' );
if ( !table.getAttribute( 'style' ) )
table.removeAttribute( 'style' );
}
// Insert the table element if we're creating one.
if ( !this._.selectedElement )
{
editor.insertElement( table );
// Override the default cursor position after insertElement to place
// cursor inside the first cell (#7959), IE needs a while.
setTimeout( function()
{
var firstCell = new CKEDITOR.dom.element( table.$.rows[ 0 ].cells[ 0 ] );
var range = new CKEDITOR.dom.range( editor.document );
range.moveToPosition( firstCell, CKEDITOR.POSITION_AFTER_START );
range.select( 1 );
}, 0 );
}
// Properly restore the selection, (#4822) but don't break
// because of this, e.g. updated table caption.
else
try { selection.selectBookmarks( bms ); } catch( er ){}
},
contents : [
{
id : 'info',
label : editor.lang.table.title,
elements :
[
{
type : 'hbox',
widths : [ null, null ],
styles : [ 'vertical-align:top' ],
children :
[
{
type : 'vbox',
padding : 0,
children :
[
{
type : 'text',
id : 'txtRows',
'default' : 3,
label : editor.lang.table.rows,
required : true,
controlStyle : 'width:5em',
validate : function()
{
var pass = true,
value = this.getValue();
pass = pass && CKEDITOR.dialog.validate.integer()( value )
&& value > 0;
if ( !pass )
{
alert( editor.lang.table.invalidRows );
this.select();
}
return pass;
},
setup : function( selectedElement )
{
this.setValue( selectedElement.$.rows.length );
},
commit : commitValue
},
{
type : 'text',
id : 'txtCols',
'default' : 2,
label : editor.lang.table.columns,
required : true,
controlStyle : 'width:5em',
validate : function()
{
var pass = true,
value = this.getValue();
pass = pass && CKEDITOR.dialog.validate.integer()( value )
&& value > 0;
if ( !pass )
{
alert( editor.lang.table.invalidCols );
this.select();
}
return pass;
},
setup : function( selectedTable )
{
this.setValue( tableColumns( selectedTable ) );
},
commit : commitValue
},
{
type : 'html',
html : ' '
},
{
type : 'select',
id : 'selHeaders',
'default' : '',
label : editor.lang.table.headers,
items :
[
[ editor.lang.table.headersNone, '' ],
[ editor.lang.table.headersRow, 'row' ],
[ editor.lang.table.headersColumn, 'col' ],
[ editor.lang.table.headersBoth, 'both' ]
],
setup : function( selectedTable )
{
// Fill in the headers field.
var dialog = this.getDialog();
dialog.hasColumnHeaders = true;
// Check if all the first cells in every row are TH
for ( var row = 0 ; row < selectedTable.$.rows.length ; row++ )
{
// If just one cell isn't a TH then it isn't a header column
var headCell = selectedTable.$.rows[row].cells[0];
if ( headCell && headCell.nodeName.toLowerCase() != 'th' )
{
dialog.hasColumnHeaders = false;
break;
}
}
// Check if the table contains <thead>.
if ( ( selectedTable.$.tHead !== null) )
this.setValue( dialog.hasColumnHeaders ? 'both' : 'row' );
else
this.setValue( dialog.hasColumnHeaders ? 'col' : '' );
},
commit : commitValue
},
{
type : 'text',
id : 'txtBorder',
'default' : 1,
label : editor.lang.table.border,
controlStyle : 'width:3em',
validate : CKEDITOR.dialog.validate['number']( editor.lang.table.invalidBorder ),
setup : function( selectedTable )
{
this.setValue( selectedTable.getAttribute( 'border' ) || '' );
},
commit : function( data, selectedTable )
{
if ( this.getValue() )
selectedTable.setAttribute( 'border', this.getValue() );
else
selectedTable.removeAttribute( 'border' );
}
},
{
id : 'cmbAlign',
type : 'select',
'default' : '',
label : editor.lang.common.align,
items :
[
[ editor.lang.common.notSet , ''],
[ editor.lang.common.alignLeft , 'left'],
[ editor.lang.common.alignCenter , 'center'],
[ editor.lang.common.alignRight , 'right']
],
setup : function( selectedTable )
{
this.setValue( selectedTable.getAttribute( 'align' ) || '' );
},
commit : function( data, selectedTable )
{
if ( this.getValue() )
selectedTable.setAttribute( 'align', this.getValue() );
else
selectedTable.removeAttribute( 'align' );
}
}
]
},
{
type : 'vbox',
padding : 0,
children :
[
{
type : 'hbox',
widths : [ '5em' ],
children :
[
{
type : 'text',
id : 'txtWidth',
controlStyle : 'width:5em',
label : editor.lang.common.width,
title : editor.lang.common.cssLengthTooltip,
'default' : 500,
getValue : defaultToPixel,
validate : CKEDITOR.dialog.validate.cssLength( editor.lang.common.invalidCssLength.replace( '%1', editor.lang.common.width ) ),
onChange : function()
{
var styles = this.getDialog().getContentElement( 'advanced', 'advStyles' );
styles && styles.updateStyle( 'width', this.getValue() );
},
setup : function( selectedTable )
{
var val = selectedTable.getStyle( 'width' );
val && this.setValue( val );
},
commit : commitValue
}
]
},
{
type : 'hbox',
widths : [ '5em' ],
children :
[
{
type : 'text',
id : 'txtHeight',
controlStyle : 'width:5em',
label : editor.lang.common.height,
title : editor.lang.common.cssLengthTooltip,
'default' : '',
getValue : defaultToPixel,
validate : CKEDITOR.dialog.validate.cssLength( editor.lang.common.invalidCssLength.replace( '%1', editor.lang.common.height ) ),
onChange : function()
{
var styles = this.getDialog().getContentElement( 'advanced', 'advStyles' );
styles && styles.updateStyle( 'height', this.getValue() );
},
setup : function( selectedTable )
{
var val = selectedTable.getStyle( 'width' );
val && this.setValue( val );
},
commit : commitValue
}
]
},
{
type : 'html',
html : ' '
},
{
type : 'text',
id : 'txtCellSpace',
controlStyle : 'width:3em',
label : editor.lang.table.cellSpace,
'default' : 1,
validate : CKEDITOR.dialog.validate.number( editor.lang.table.invalidCellSpacing ),
setup : function( selectedTable )
{
this.setValue( selectedTable.getAttribute( 'cellSpacing' ) || '' );
},
commit : function( data, selectedTable )
{
if ( this.getValue() )
selectedTable.setAttribute( 'cellSpacing', this.getValue() );
else
selectedTable.removeAttribute( 'cellSpacing' );
}
},
{
type : 'text',
id : 'txtCellPad',
controlStyle : 'width:3em',
label : editor.lang.table.cellPad,
'default' : 1,
validate : CKEDITOR.dialog.validate.number( editor.lang.table.invalidCellPadding ),
setup : function( selectedTable )
{
this.setValue( selectedTable.getAttribute( 'cellPadding' ) || '' );
},
commit : function( data, selectedTable )
{
if ( this.getValue() )
selectedTable.setAttribute( 'cellPadding', this.getValue() );
else
selectedTable.removeAttribute( 'cellPadding' );
}
}
]
}
]
},
{
type : 'html',
align : 'right',
html : ''
},
{
type : 'vbox',
padding : 0,
children :
[
{
type : 'text',
id : 'txtCaption',
label : editor.lang.table.caption,
setup : function( selectedTable )
{
this.enable();
var nodeList = selectedTable.getElementsByTag( 'caption' );
if ( nodeList.count() > 0 )
{
var caption = nodeList.getItem( 0 );
var firstElementChild = caption.getFirst( CKEDITOR.dom.walker.nodeType( CKEDITOR.NODE_ELEMENT ) );
if ( firstElementChild && !firstElementChild.equals( caption.getBogus() ) )
{
this.disable();
this.setValue( caption.getText() );
return;
}
caption = CKEDITOR.tools.trim( caption.getText() );
this.setValue( caption );
}
},
commit : function( data, table )
{
if ( !this.isEnabled() )
return;
var caption = this.getValue(),
captionElement = table.getElementsByTag( 'caption' );
if ( caption )
{
if ( captionElement.count() > 0 )
{
captionElement = captionElement.getItem( 0 );
captionElement.setHtml( '' );
}
else
{
captionElement = new CKEDITOR.dom.element( 'caption', editor.document );
if ( table.getChildCount() )
captionElement.insertBefore( table.getFirst() );
else
captionElement.appendTo( table );
}
captionElement.append( new CKEDITOR.dom.text( caption, editor.document ) );
}
else if ( captionElement.count() > 0 )
{
for ( var i = captionElement.count() - 1 ; i >= 0 ; i-- )
captionElement.getItem( i ).remove();
}
}
},
{
type : 'text',
id : 'txtSummary',
label : editor.lang.table.summary,
setup : function( selectedTable )
{
this.setValue( selectedTable.getAttribute( 'summary' ) || '' );
},
commit : function( data, selectedTable )
{
if ( this.getValue() )
selectedTable.setAttribute( 'summary', this.getValue() );
else
selectedTable.removeAttribute( 'summary' );
}
}
]
}
]
},
dialogadvtab && dialogadvtab.createAdvancedTab( editor )
]
};
}
CKEDITOR.dialog.add( 'table', function( editor )
{
return tableDialog( editor, 'table' );
} );
CKEDITOR.dialog.add( 'tableProperties', function( editor )
{
return tableDialog( editor, 'tableProperties' );
} );
})(); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/_source/plugins/table/dialogs/table.js | table.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Spell Check As You Type (SCAYT).
* Button name : Scayt.
*/
(function()
{
var commandName = 'scaytcheck',
openPage = '';
// Checks if a value exists in an array
function in_array( needle, haystack )
{
var found = 0,
key;
for ( key in haystack )
{
if ( haystack[ key ] == needle )
{
found = 1;
break;
}
}
return found;
}
var onEngineLoad = function()
{
var editor = this;
var createInstance = function() // Create new instance every time Document is created.
{
var config = editor.config;
// Initialise Scayt instance.
var oParams = {};
// Get the iframe.
oParams.srcNodeRef = editor.document.getWindow().$.frameElement;
// syntax : AppName.AppVersion@AppRevision
oParams.assocApp = 'CKEDITOR.' + CKEDITOR.version + '@' + CKEDITOR.revision;
oParams.customerid = config.scayt_customerid || '1:WvF0D4-UtPqN1-43nkD4-NKvUm2-daQqk3-LmNiI-z7Ysb4-mwry24-T8YrS3-Q2tpq2';
oParams.customDictionaryIds = config.scayt_customDictionaryIds || '';
oParams.userDictionaryName = config.scayt_userDictionaryName || '';
oParams.sLang = config.scayt_sLang || 'en_US';
// Introduce SCAYT onLoad callback. (#5632)
oParams.onLoad = function()
{
// Draw down word marker to avoid being covered by background-color style.(#5466)
if ( !( CKEDITOR.env.ie && CKEDITOR.env.version < 8 ) )
this.addStyle( this.selectorCss(), 'padding-bottom: 2px !important;' );
// Call scayt_control.focus when SCAYT loaded
// and only if editor has focus and scayt control creates at first time (#5720)
if ( editor.focusManager.hasFocus && !plugin.isControlRestored( editor ) )
this.focus();
};
oParams.onBeforeChange = function()
{
if ( plugin.getScayt( editor ) && !editor.checkDirty() )
setTimeout( function(){ editor.resetDirty(); }, 0 );
};
var scayt_custom_params = window.scayt_custom_params;
if ( typeof scayt_custom_params == 'object' )
{
for ( var k in scayt_custom_params )
oParams[ k ] = scayt_custom_params[ k ];
}
// needs for restoring a specific scayt control settings
if ( plugin.getControlId( editor ) )
oParams.id = plugin.getControlId( editor );
var scayt_control = new window.scayt( oParams );
scayt_control.afterMarkupRemove.push( function( node )
{
( new CKEDITOR.dom.element( node, scayt_control.document ) ).mergeSiblings();
} );
// Copy config.
var lastInstance = plugin.instances[ editor.name ];
if ( lastInstance )
{
scayt_control.sLang = lastInstance.sLang;
scayt_control.option( lastInstance.option() );
scayt_control.paused = lastInstance.paused;
}
plugin.instances[ editor.name ] = scayt_control;
try {
scayt_control.setDisabled( plugin.isPaused( editor ) === false );
} catch (e) {}
editor.fire( 'showScaytState' );
};
editor.on( 'contentDom', createInstance );
editor.on( 'contentDomUnload', function()
{
// Remove scripts.
var scripts = CKEDITOR.document.getElementsByTag( 'script' ),
scaytIdRegex = /^dojoIoScript(\d+)$/i,
scaytSrcRegex = /^https?:\/\/svc\.webspellchecker\.net\/spellcheck\/script\/ssrv\.cgi/i;
for ( var i=0; i < scripts.count(); i++ )
{
var script = scripts.getItem( i ),
id = script.getId(),
src = script.getAttribute( 'src' );
if ( id && src && id.match( scaytIdRegex ) && src.match( scaytSrcRegex ))
script.remove();
}
});
editor.on( 'beforeCommandExec', function( ev ) // Disable SCAYT before Source command execution.
{
if ( ( ev.data.name == 'source' || ev.data.name == 'newpage' ) && editor.mode == 'wysiwyg' )
{
var scayt_instance = plugin.getScayt( editor );
if ( scayt_instance )
{
plugin.setPaused( editor, !scayt_instance.disabled );
// store a control id for restore a specific scayt control settings
plugin.setControlId( editor, scayt_instance.id );
scayt_instance.destroy( true );
delete plugin.instances[ editor.name ];
}
}
// Catch on source mode switch off (#5720)
else if ( ev.data.name == 'source' && editor.mode == 'source' )
plugin.markControlRestore( editor );
});
editor.on( 'afterCommandExec', function( ev )
{
if ( !plugin.isScaytEnabled( editor ) )
return;
if ( editor.mode == 'wysiwyg' && ( ev.data.name == 'undo' || ev.data.name == 'redo' ) )
window.setTimeout( function() { plugin.getScayt( editor ).refresh(); }, 10 );
});
editor.on( 'destroy', function( ev )
{
var editor = ev.editor,
scayt_instance = plugin.getScayt( editor );
// SCAYT instance might already get destroyed by mode switch (#5744).
if ( !scayt_instance )
return;
delete plugin.instances[ editor.name ];
// store a control id for restore a specific scayt control settings
plugin.setControlId( editor, scayt_instance.id );
scayt_instance.destroy( true );
});
// Listen to data manipulation to reflect scayt markup.
editor.on( 'afterSetData', function()
{
if ( plugin.isScaytEnabled( editor ) ) {
window.setTimeout( function()
{
var instance = plugin.getScayt( editor );
instance && instance.refresh();
}, 10 );
}
});
// Reload spell-checking for current word after insertion completed.
editor.on( 'insertElement', function()
{
var scayt_instance = plugin.getScayt( editor );
if ( plugin.isScaytEnabled( editor ) )
{
// Unlock the selection before reload, SCAYT will take
// care selection update.
if ( CKEDITOR.env.ie )
editor.getSelection().unlock( true );
// Return focus to the editor and refresh SCAYT markup (#5573).
window.setTimeout( function()
{
scayt_instance.focus();
scayt_instance.refresh();
}, 10 );
}
}, this, null, 50 );
editor.on( 'insertHtml', function()
{
var scayt_instance = plugin.getScayt( editor );
if ( plugin.isScaytEnabled( editor ) )
{
// Unlock the selection before reload, SCAYT will take
// care selection update.
if ( CKEDITOR.env.ie )
editor.getSelection().unlock( true );
// Return focus to the editor (#5573)
// Refresh SCAYT markup
window.setTimeout( function()
{
scayt_instance.focus();
scayt_instance.refresh();
}, 10 );
}
}, this, null, 50 );
editor.on( 'scaytDialog', function( ev ) // Communication with dialog.
{
ev.data.djConfig = window.djConfig;
ev.data.scayt_control = plugin.getScayt( editor );
ev.data.tab = openPage;
ev.data.scayt = window.scayt;
});
var dataProcessor = editor.dataProcessor,
htmlFilter = dataProcessor && dataProcessor.htmlFilter;
if ( htmlFilter )
{
htmlFilter.addRules(
{
elements :
{
span : function( element )
{
if ( element.attributes[ 'data-scayt_word' ]
&& element.attributes[ 'data-scaytid' ] )
{
delete element.name; // Write children, but don't write this node.
return element;
}
}
}
}
);
}
// Override Image.equals method avoid CK snapshot module to add SCAYT markup to snapshots. (#5546)
var undoImagePrototype = CKEDITOR.plugins.undo.Image.prototype;
undoImagePrototype.equals = CKEDITOR.tools.override( undoImagePrototype.equals, function( org )
{
return function( otherImage )
{
var thisContents = this.contents,
otherContents = otherImage.contents;
var scayt_instance = plugin.getScayt( this.editor );
// Making the comparison based on content without SCAYT word markers.
if ( scayt_instance && plugin.isScaytReady( this.editor ) )
{
// scayt::reset might return value undefined. (#5742)
this.contents = scayt_instance.reset( thisContents ) || '';
otherImage.contents = scayt_instance.reset( otherContents ) || '';
}
var retval = org.apply( this, arguments );
this.contents = thisContents;
otherImage.contents = otherContents;
return retval;
};
});
if ( editor.document )
createInstance();
};
CKEDITOR.plugins.scayt =
{
engineLoaded : false,
instances : {},
// Data storage for SCAYT control, based on editor instances
controlInfo : {},
setControlInfo : function( editor, o )
{
if ( editor && editor.name && typeof ( this.controlInfo[ editor.name ] ) != 'object' )
this.controlInfo[ editor.name ] = {};
for ( var infoOpt in o )
this.controlInfo[ editor.name ][ infoOpt ] = o[ infoOpt ];
},
isControlRestored : function( editor )
{
if ( editor &&
editor.name &&
this.controlInfo[ editor.name ] )
{
return this.controlInfo[ editor.name ].restored ;
}
return false;
},
markControlRestore : function( editor )
{
this.setControlInfo( editor, { restored:true } );
},
setControlId: function( editor, id )
{
this.setControlInfo( editor, { id:id } );
},
getControlId: function( editor )
{
if ( editor &&
editor.name &&
this.controlInfo[ editor.name ] &&
this.controlInfo[ editor.name ].id )
{
return this.controlInfo[ editor.name ].id;
}
return null;
},
setPaused: function( editor , bool )
{
this.setControlInfo( editor, { paused:bool } );
},
isPaused: function( editor )
{
if ( editor &&
editor.name &&
this.controlInfo[editor.name] )
{
return this.controlInfo[editor.name].paused;
}
return undefined;
},
getScayt : function( editor )
{
return this.instances[ editor.name ];
},
isScaytReady : function( editor )
{
return this.engineLoaded === true &&
'undefined' !== typeof window.scayt && this.getScayt( editor );
},
isScaytEnabled : function( editor )
{
var scayt_instance = this.getScayt( editor );
return ( scayt_instance ) ? scayt_instance.disabled === false : false;
},
getUiTabs : function( editor )
{
var uiTabs = [];
// read UI tabs value from config
var configUiTabs = editor.config.scayt_uiTabs || "1,1,1";
// convert string to array
configUiTabs = configUiTabs.split( ',' );
// "About us" should be always shown for standard config
configUiTabs[3] = "1";
for ( var i = 0; i < 4; i++ ) {
uiTabs[i] = (typeof window.scayt != "undefined" && typeof window.scayt.uiTags != "undefined")
? (parseInt(configUiTabs[i],10) && window.scayt.uiTags[i])
: parseInt(configUiTabs[i],10);
}
return uiTabs;
},
loadEngine : function( editor )
{
// SCAYT doesn't work with Firefox2, Opera and AIR.
if ( CKEDITOR.env.gecko && CKEDITOR.env.version < 10900 || CKEDITOR.env.opera || CKEDITOR.env.air )
return editor.fire( 'showScaytState' );
if ( this.engineLoaded === true )
return onEngineLoad.apply( editor ); // Add new instance.
else if ( this.engineLoaded == -1 ) // We are waiting.
return CKEDITOR.on( 'scaytReady', function(){ onEngineLoad.apply( editor ); } ); // Use function(){} to avoid rejection as duplicate.
CKEDITOR.on( 'scaytReady', onEngineLoad, editor );
CKEDITOR.on( 'scaytReady', function()
{
this.engineLoaded = true;
},
this,
null,
0
); // First to run.
this.engineLoaded = -1; // Loading in progress.
// compose scayt url
var protocol = document.location.protocol;
// Default to 'http' for unknown.
protocol = protocol.search( /https?:/) != -1? protocol : 'http:';
var baseUrl = 'svc.webspellchecker.net/scayt26/loader__base.js';
var scaytUrl = editor.config.scayt_srcUrl || ( protocol + '//' + baseUrl );
var scaytConfigBaseUrl = plugin.parseUrl( scaytUrl ).path + '/';
if( window.scayt == undefined )
{
CKEDITOR._djScaytConfig =
{
baseUrl: scaytConfigBaseUrl,
addOnLoad:
[
function()
{
CKEDITOR.fireOnce( 'scaytReady' );
}
],
isDebug: false
};
// Append javascript code.
CKEDITOR.document.getHead().append(
CKEDITOR.document.createElement( 'script',
{
attributes :
{
type : 'text/javascript',
async : 'true',
src : scaytUrl
}
})
);
}
else
CKEDITOR.fireOnce( 'scaytReady' );
return null;
},
parseUrl : function ( data )
{
var match;
if ( data.match && ( match = data.match(/(.*)[\/\\](.*?\.\w+)$/) ) )
return { path: match[1], file: match[2] };
else
return data;
}
};
var plugin = CKEDITOR.plugins.scayt;
// Context menu constructing.
var addButtonCommand = function( editor, buttonName, buttonLabel, commandName, command, menugroup, menuOrder )
{
editor.addCommand( commandName, command );
// If the "menu" plugin is loaded, register the menu item.
editor.addMenuItem( commandName,
{
label : buttonLabel,
command : commandName,
group : menugroup,
order : menuOrder
});
};
var commandDefinition =
{
preserveState : true,
editorFocus : false,
canUndo : false,
exec: function( editor )
{
if ( plugin.isScaytReady( editor ) )
{
var isEnabled = plugin.isScaytEnabled( editor );
this.setState( isEnabled ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_ON );
var scayt_control = plugin.getScayt( editor );
// the place where the status of editor focus should be restored
// after there will be ability to store its state before SCAYT button click
// if (storedFocusState is focused )
// scayt_control.focus();
//
// now focus is set certainly
scayt_control.focus();
scayt_control.setDisabled( isEnabled );
}
else if ( !editor.config.scayt_autoStartup && plugin.engineLoaded >= 0 ) // Load first time
{
this.setState( CKEDITOR.TRISTATE_DISABLED );
plugin.loadEngine( editor );
}
}
};
// Add scayt plugin.
CKEDITOR.plugins.add( 'scayt',
{
requires : [ 'menubutton' ],
beforeInit : function( editor )
{
var items_order = editor.config.scayt_contextMenuItemsOrder
|| 'suggest|moresuggest|control',
items_order_str = "";
items_order = items_order.split( '|' );
if ( items_order && items_order.length )
{
for ( var pos = 0 ; pos < items_order.length ; pos++ )
items_order_str += 'scayt_' + items_order[ pos ] + ( items_order.length != parseInt( pos, 10 ) + 1 ? ',' : '' );
}
// Put it on top of all context menu items (#5717)
editor.config.menu_groups = items_order_str + ',' + editor.config.menu_groups;
},
init : function( editor )
{
// Delete span[data-scaytid] when text pasting in editor (#6921)
var dataFilter = editor.dataProcessor && editor.dataProcessor.dataFilter;
var dataFilterRules =
{
elements :
{
span : function( element )
{
var attrs = element.attributes;
if ( attrs && attrs[ 'data-scaytid' ] )
delete element.name;
}
}
};
dataFilter && dataFilter.addRules( dataFilterRules );
var moreSuggestions = {},
mainSuggestions = {};
// Scayt command.
var command = editor.addCommand( commandName, commandDefinition );
// Add Options dialog.
CKEDITOR.dialog.add( commandName, CKEDITOR.getUrl( this.path + 'dialogs/options.js' ) );
var uiTabs = plugin.getUiTabs( editor );
var menuGroup = 'scaytButton';
editor.addMenuGroup( menuGroup );
// combine menu items to render
var uiMenuItems = {};
var lang = editor.lang.scayt;
// always added
uiMenuItems.scaytToggle =
{
label : lang.enable,
command : commandName,
group : menuGroup
};
if ( uiTabs[0] == 1 )
uiMenuItems.scaytOptions =
{
label : lang.options,
group : menuGroup,
onClick : function()
{
openPage = 'options';
editor.openDialog( commandName );
}
};
if ( uiTabs[1] == 1 )
uiMenuItems.scaytLangs =
{
label : lang.langs,
group : menuGroup,
onClick : function()
{
openPage = 'langs';
editor.openDialog( commandName );
}
};
if ( uiTabs[2] == 1 )
uiMenuItems.scaytDict =
{
label : lang.dictionariesTab,
group : menuGroup,
onClick : function()
{
openPage = 'dictionaries';
editor.openDialog( commandName );
}
};
// always added
uiMenuItems.scaytAbout =
{
label : editor.lang.scayt.about,
group : menuGroup,
onClick : function()
{
openPage = 'about';
editor.openDialog( commandName );
}
};
editor.addMenuItems( uiMenuItems );
editor.ui.add( 'Scayt', CKEDITOR.UI_MENUBUTTON,
{
label : lang.title,
title : CKEDITOR.env.opera ? lang.opera_title : lang.title,
className : 'cke_button_scayt',
modes : { wysiwyg : 1 },
onRender: function()
{
command.on( 'state', function()
{
this.setState( command.state );
},
this);
},
onMenu : function()
{
var isEnabled = plugin.isScaytEnabled( editor );
editor.getMenuItem( 'scaytToggle' ).label = lang[ isEnabled ? 'disable' : 'enable' ];
var uiTabs = plugin.getUiTabs( editor );
return {
scaytToggle : CKEDITOR.TRISTATE_OFF,
scaytOptions : isEnabled && uiTabs[0] ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED,
scaytLangs : isEnabled && uiTabs[1] ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED,
scaytDict : isEnabled && uiTabs[2] ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED,
scaytAbout : isEnabled && uiTabs[3] ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED
};
}
});
// If the "contextmenu" plugin is loaded, register the listeners.
if ( editor.contextMenu && editor.addMenuItems )
{
editor.contextMenu.addListener( function( element, selection )
{
if ( !plugin.isScaytEnabled( editor )
|| selection.getRanges()[ 0 ].checkReadOnly() )
return null;
var scayt_control = plugin.getScayt( editor ),
node = scayt_control.getScaytNode();
if ( !node )
return null;
var word = scayt_control.getWord( node );
if ( !word )
return null;
var sLang = scayt_control.getLang(),
_r = {},
items_suggestion = window.scayt.getSuggestion( word, sLang );
if ( !items_suggestion || !items_suggestion.length )
return null;
// Remove unused commands and menuitems
for ( var m in moreSuggestions )
{
delete editor._.menuItems[ m ];
delete editor._.commands[ m ];
}
for ( m in mainSuggestions )
{
delete editor._.menuItems[ m ];
delete editor._.commands[ m ];
}
moreSuggestions = {}; // Reset items.
mainSuggestions = {};
var moreSuggestionsUnable = editor.config.scayt_moreSuggestions || 'on';
var moreSuggestionsUnableAdded = false;
var maxSuggestions = editor.config.scayt_maxSuggestions;
( typeof maxSuggestions != 'number' ) && ( maxSuggestions = 5 );
!maxSuggestions && ( maxSuggestions = items_suggestion.length );
var contextCommands = editor.config.scayt_contextCommands || 'all';
contextCommands = contextCommands.split( '|' );
for ( var i = 0, l = items_suggestion.length; i < l; i += 1 )
{
var commandName = 'scayt_suggestion_' + items_suggestion[i].replace( ' ', '_' );
var exec = ( function( el, s )
{
return {
exec: function()
{
scayt_control.replace( el, s );
}
};
})( node, items_suggestion[i] );
if ( i < maxSuggestions )
{
addButtonCommand( editor, 'button_' + commandName, items_suggestion[i],
commandName, exec, 'scayt_suggest', i + 1 );
_r[ commandName ] = CKEDITOR.TRISTATE_OFF;
mainSuggestions[ commandName ] = CKEDITOR.TRISTATE_OFF;
}
else if ( moreSuggestionsUnable == 'on' )
{
addButtonCommand( editor, 'button_' + commandName, items_suggestion[i],
commandName, exec, 'scayt_moresuggest', i + 1 );
moreSuggestions[ commandName ] = CKEDITOR.TRISTATE_OFF;
moreSuggestionsUnableAdded = true;
}
}
if ( moreSuggestionsUnableAdded )
{
// Register the More suggestions group;
editor.addMenuItem( 'scayt_moresuggest',
{
label : lang.moreSuggestions,
group : 'scayt_moresuggest',
order : 10,
getItems : function()
{
return moreSuggestions;
}
});
mainSuggestions[ 'scayt_moresuggest' ] = CKEDITOR.TRISTATE_OFF;
}
if ( in_array( 'all', contextCommands ) || in_array( 'ignore', contextCommands) )
{
var ignore_command = {
exec: function(){
scayt_control.ignore( node );
}
};
addButtonCommand( editor, 'ignore', lang.ignore, 'scayt_ignore', ignore_command, 'scayt_control', 1 );
mainSuggestions[ 'scayt_ignore' ] = CKEDITOR.TRISTATE_OFF;
}
if ( in_array( 'all', contextCommands ) || in_array( 'ignoreall', contextCommands ) )
{
var ignore_all_command = {
exec: function(){
scayt_control.ignoreAll( node );
}
};
addButtonCommand(editor, 'ignore_all', lang.ignoreAll, 'scayt_ignore_all', ignore_all_command, 'scayt_control', 2);
mainSuggestions['scayt_ignore_all'] = CKEDITOR.TRISTATE_OFF;
}
if ( in_array( 'all', contextCommands ) || in_array( 'add', contextCommands ) )
{
var addword_command = {
exec: function(){
window.scayt.addWordToUserDictionary( node );
}
};
addButtonCommand(editor, 'add_word', lang.addWord, 'scayt_add_word', addword_command, 'scayt_control', 3);
mainSuggestions['scayt_add_word'] = CKEDITOR.TRISTATE_OFF;
}
if ( scayt_control.fireOnContextMenu )
scayt_control.fireOnContextMenu( editor );
return mainSuggestions;
});
}
var showInitialState = function()
{
editor.removeListener( 'showScaytState', showInitialState );
if ( !CKEDITOR.env.opera && !CKEDITOR.env.air )
command.setState( plugin.isScaytEnabled( editor ) ? CKEDITOR.TRISTATE_ON : CKEDITOR.TRISTATE_OFF );
else
command.setState( CKEDITOR.TRISTATE_DISABLED );
};
editor.on( 'showScaytState', showInitialState );
if ( CKEDITOR.env.opera || CKEDITOR.env.air )
{
editor.on( 'instanceReady', function()
{
showInitialState();
});
}
// Start plugin
if ( editor.config.scayt_autoStartup )
{
editor.on( 'instanceReady', function()
{
plugin.loadEngine( editor );
});
}
},
afterInit : function( editor )
{
// Prevent word marker line from displaying in elements path and been removed when cleaning format. (#3570) (#4125)
var elementsPathFilters,
scaytFilter = function( element )
{
if ( element.hasAttribute( 'data-scaytid' ) )
return false;
};
if ( editor._.elementsPath && ( elementsPathFilters = editor._.elementsPath.filters ) )
elementsPathFilters.push( scaytFilter );
editor.addRemoveFormatFilter && editor.addRemoveFormatFilter( scaytFilter );
}
});
})();
/**
* If enabled (set to <code>true</code>), turns on SCAYT automatically
* after loading the editor.
* @name CKEDITOR.config.scayt_autoStartup
* @type Boolean
* @default <code>false</code>
* @example
* config.scayt_autoStartup = true;
*/
/**
* Defines the number of SCAYT suggestions to show in the main context menu.
* Possible values are:
* <ul>
* <li><code>0</code> (zero) – All suggestions are displayed in the main context menu.</li>
* <li>Positive number – The maximum number of suggestions to show in the context
* menu. Other entries will be shown in the "More Suggestions" sub-menu.</li>
* <li>Negative number – No suggestions are shown in the main context menu. All
* entries will be listed in the the "Suggestions" sub-menu.</li>
* </ul>
* @name CKEDITOR.config.scayt_maxSuggestions
* @type Number
* @default <code>5</code>
* @example
* // Display only three suggestions in the main context menu.
* config.scayt_maxSuggestions = 3;
* @example
* // Do not show the suggestions directly.
* config.scayt_maxSuggestions = -1;
*/
/**
* Sets the customer ID for SCAYT. Required for migration from free,
* ad-supported version to paid, ad-free version.
* @name CKEDITOR.config.scayt_customerid
* @type String
* @default <code>''</code>
* @example
* // Load SCAYT using my customer ID.
* config.scayt_customerid = 'your-encrypted-customer-id';
*/
/**
* Enables/disables the "More Suggestions" sub-menu in the context menu.
* Possible values are <code>on</code> and <code>off</code>.
* @name CKEDITOR.config.scayt_moreSuggestions
* @type String
* @default <code>'on'</code>
* @example
* // Disables the "More Suggestions" sub-menu.
* config.scayt_moreSuggestions = 'off';
*/
/**
* Customizes the display of SCAYT context menu commands ("Add Word", "Ignore"
* and "Ignore All"). This must be a string with one or more of the following
* words separated by a pipe character ("|"):
* <ul>
* <li><code>off</code> – disables all options.</li>
* <li><code>all</code> – enables all options.</li>
* <li><code>ignore</code> – enables the "Ignore" option.</li>
* <li><code>ignoreall</code> – enables the "Ignore All" option.</li>
* <li><code>add</code> – enables the "Add Word" option.</li>
* </ul>
* @name CKEDITOR.config.scayt_contextCommands
* @type String
* @default <code>'all'</code>
* @example
* // Show only "Add Word" and "Ignore All" in the context menu.
* config.scayt_contextCommands = 'add|ignoreall';
*/
/**
* Sets the default spell checking language for SCAYT. Possible values are:
* <code>en_US</code>, <code>en_GB</code>, <code>pt_BR</code>, <code>da_DK</code>,
* <code>nl_NL</code>, <code>en_CA</code>, <code>fi_FI</code>, <code>fr_FR</code>,
* <code>fr_CA</code>, <code>de_DE</code>, <code>el_GR</code>, <code>it_IT</code>,
* <code>nb_NO</code>, <code>pt_PT</code>, <code>es_ES</code>, <code>sv_SE</code>.
* @name CKEDITOR.config.scayt_sLang
* @type String
* @default <code>'en_US'</code>
* @example
* // Sets SCAYT to German.
* config.scayt_sLang = 'de_DE';
*/
/**
* Sets the visibility of particular tabs in the SCAYT dialog window and toolbar
* button. This setting must contain a <code>1</code> (enabled) or <code>0</code>
* (disabled) value for each of the following entries, in this precise order,
* separated by a comma (","): "Options", "Languages", and "Dictionary".
* @name CKEDITOR.config.scayt_uiTabs
* @type String
* @default <code>'1,1,1'</code>
* @example
* // Hides the "Languages" tab.
* config.scayt_uiTabs = '1,0,1';
*/
/**
* Sets the URL to SCAYT core. Required to switch to the licensed version of SCAYT application.
* Further details available at
* <a href="http://wiki.webspellchecker.net/doku.php?id=migration:hosredfreetolicensedck">
* http://wiki.webspellchecker.net/doku.php?id=migration:hosredfreetolicensedck</a>.
* @name CKEDITOR.config.scayt_srcUrl
* @type String
* @default <code>''</code>
* @example
* config.scayt_srcUrl = "http://my-host/spellcheck/lf/scayt/scayt.js";
*/
/**
* Links SCAYT to custom dictionaries. This is a string containing dictionary IDs
* separared by commas (","). Available only for the licensed version.
* Further details at
* <a href="http://wiki.webspellchecker.net/doku.php?id=installationandconfiguration:customdictionaries:licensed">
* http://wiki.webspellchecker.net/doku.php?id=installationandconfiguration:customdictionaries:licensed</a>.
* @name CKEDITOR.config.scayt_customDictionaryIds
* @type String
* @default <code>''</code>
* @example
* config.scayt_customDictionaryIds = '3021,3456,3478"';
*/
/**
* Makes it possible to activate a custom dictionary in SCAYT. The user
* dictionary name must be used. Available only for the licensed version.
* @name CKEDITOR.config.scayt_userDictionaryName
* @type String
* @default <code>''</code>
* @example
* config.scayt_userDictionaryName = 'MyDictionary';
*/
/**
* Defines the order SCAYT context menu items by groups.
* This must be a string with one or more of the following
* words separated by a pipe character ("|"):
* <ul>
* <li><code>suggest</code> – main suggestion word list,</li>
* <li><code>moresuggest</code> – more suggestions word list,</li>
* <li><code>control</code> – SCAYT commands, such as "Ignore" and "Add Word".</li>
* </ul>
*
* @name CKEDITOR.config.scayt_contextMenuItemsOrder
* @type String
* @default <code>'suggest|moresuggest|control'</code>
* @example
* config.scayt_contextMenuItemsOrder = 'moresuggest|control|suggest';
*/ | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/_source/plugins/scayt/plugin.js | plugin.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add( 'scaytcheck', function( editor )
{
var firstLoad = true,
captions,
doc = CKEDITOR.document,
editorName = editor.name,
tags = CKEDITOR.plugins.scayt.getUiTabs( editor ),
i,
contents = [],
userDicActive = 0,
dic_buttons = [
// [0] contains buttons for creating
"dic_create_" + editorName + ",dic_restore_" + editorName,
// [1] contains buton for manipulation
"dic_rename_" + editorName + ",dic_delete_" + editorName
],
optionsIds = [ 'mixedCase', 'mixedWithDigits', 'allCaps', 'ignoreDomainNames' ];
// common operations
function getBOMAllOptions()
{
if (typeof document.forms["optionsbar_" + editorName] != "undefined")
return document.forms["optionsbar_" + editorName]["options"];
return [];
}
function getBOMAllLangs()
{
if (typeof document.forms["languagesbar_" + editorName] != "undefined")
return document.forms["languagesbar_" + editorName]["scayt_lang"];
return [];
}
function setCheckedValue( radioObj, newValue )
{
if ( !radioObj )
return;
var radioLength = radioObj.length;
if ( radioLength == undefined )
{
radioObj.checked = radioObj.value == newValue.toString();
return;
}
for ( var i = 0; i < radioLength; i++ )
{
radioObj[i].checked = false;
if ( radioObj[i].value == newValue.toString() )
radioObj[i].checked = true;
}
}
var lang = editor.lang.scayt;
var tags_contents = [
{
id : 'options',
label : lang.optionsTab,
elements : [
{
type : 'html',
id : 'options',
html : '<form name="optionsbar_' + editorName + '"><div class="inner_options">' +
' <div class="messagebox"></div>' +
' <div style="display:none;">' +
' <input type="checkbox" name="options" id="allCaps_' + editorName + '" />' +
' <label for="allCaps" id="label_allCaps_' + editorName + '"></label>' +
' </div>' +
' <div style="display:none;">' +
' <input name="options" type="checkbox" id="ignoreDomainNames_' + editorName + '" />' +
' <label for="ignoreDomainNames" id="label_ignoreDomainNames_' + editorName + '"></label>' +
' </div>' +
' <div style="display:none;">' +
' <input name="options" type="checkbox" id="mixedCase_' + editorName + '" />' +
' <label for="mixedCase" id="label_mixedCase_' + editorName + '"></label>' +
' </div>' +
' <div style="display:none;">' +
' <input name="options" type="checkbox" id="mixedWithDigits_' + editorName + '" />' +
' <label for="mixedWithDigits" id="label_mixedWithDigits_' + editorName + '"></label>' +
' </div>' +
'</div></form>'
}
]
},
{
id : 'langs',
label : lang.languagesTab,
elements : [
{
type : 'html',
id : 'langs',
html : '<form name="languagesbar_' + editorName + '"><div class="inner_langs">' +
' <div class="messagebox"></div> ' +
' <div style="float:left;width:45%;margin-left:5px;" id="scayt_lcol_' + editorName + '" ></div>' +
' <div style="float:left;width:45%;margin-left:15px;" id="scayt_rcol_' + editorName + '"></div>' +
'</div></form>'
}
]
},
{
id : 'dictionaries',
label : lang.dictionariesTab,
elements : [
{
type : 'html',
style: '',
id : 'dictionaries',
html : '<form name="dictionarybar_' + editorName + '"><div class="inner_dictionary" style="text-align:left; white-space:normal; width:320px; overflow: hidden;">' +
' <div style="margin:5px auto; width:80%;white-space:normal; overflow:hidden;" id="dic_message_' + editorName + '"> </div>' +
' <div style="margin:5px auto; width:80%;white-space:normal;"> ' +
' <span class="cke_dialog_ui_labeled_label" >Dictionary name</span><br>'+
' <span class="cke_dialog_ui_labeled_content" >'+
' <div class="cke_dialog_ui_input_text">'+
' <input id="dic_name_' + editorName + '" type="text" class="cke_dialog_ui_input_text"/>'+
' </div></span></div>'+
' <div style="margin:5px auto; width:80%;white-space:normal;">'+
' <a style="display:none;" class="cke_dialog_ui_button" href="javascript:void(0)" id="dic_create_' + editorName + '">'+
' </a>' +
' <a style="display:none;" class="cke_dialog_ui_button" href="javascript:void(0)" id="dic_delete_' + editorName + '">'+
' </a>' +
' <a style="display:none;" class="cke_dialog_ui_button" href="javascript:void(0)" id="dic_rename_' + editorName + '">'+
' </a>' +
' <a style="display:none;" class="cke_dialog_ui_button" href="javascript:void(0)" id="dic_restore_' + editorName + '">'+
' </a>' +
' </div>' +
' <div style="margin:5px auto; width:95%;white-space:normal;" id="dic_info_' + editorName + '"></div>' +
'</div></form>'
}
]
},
{
id : 'about',
label : lang.aboutTab,
elements : [
{
type : 'html',
id : 'about',
style : 'margin: 5px 5px;',
html : '<div id="scayt_about_' + editorName + '"></div>'
}
]
}
];
var dialogDefiniton = {
title : lang.title,
minWidth : 360,
minHeight : 220,
onShow : function()
{
var dialog = this;
dialog.data = editor.fire( 'scaytDialog', {} );
dialog.options = dialog.data.scayt_control.option();
dialog.chosed_lang = dialog.sLang = dialog.data.scayt_control.sLang;
if ( !dialog.data || !dialog.data.scayt || !dialog.data.scayt_control )
{
alert( 'Error loading application service' );
dialog.hide();
return;
}
var stop = 0;
if ( firstLoad )
{
dialog.data.scayt.getCaption( editor.langCode || 'en', function( caps )
{
if ( stop++ > 0 ) // Once only
return;
captions = caps;
init_with_captions.apply( dialog );
reload.apply( dialog );
firstLoad = false;
});
}
else
reload.apply( dialog );
dialog.selectPage( dialog.data.tab );
},
onOk : function()
{
var scayt_control = this.data.scayt_control;
scayt_control.option( this.options );
// Setup language if it was changed.
var csLang = this.chosed_lang;
scayt_control.setLang( csLang );
scayt_control.refresh();
},
onCancel: function()
{
var o = getBOMAllOptions();
for ( var i in o )
o[i].checked = false;
setCheckedValue( getBOMAllLangs(), "" );
},
contents : contents
};
var scayt_control = CKEDITOR.plugins.scayt.getScayt( editor );
for ( i = 0; i < tags.length; i++ )
{
if ( tags[ i ] == 1 )
contents[ contents.length ] = tags_contents[ i ];
}
if ( tags[2] == 1 )
userDicActive = 1;
var init_with_captions = function()
{
var dialog = this,
lang_list = dialog.data.scayt.getLangList(),
buttonCaptions = [ 'dic_create', 'dic_delete', 'dic_rename', 'dic_restore' ],
buttonIds = [],
langList = [],
labels = optionsIds,
i;
// Add buttons titles
if ( userDicActive )
{
for ( i = 0; i < buttonCaptions.length; i++ )
{
buttonIds[ i ] = buttonCaptions[ i ] + "_" + editorName;
doc.getById( buttonIds[ i ] ).setHtml( '<span class="cke_dialog_ui_button">' + captions[ 'button_' + buttonCaptions[ i ]] +'</span>' );
}
doc.getById( 'dic_info_' + editorName ).setHtml( captions[ 'dic_info' ] );
}
// Fill options and dictionary labels.
if ( tags[0] == 1 )
{
for ( i in labels )
{
var labelCaption = 'label_' + labels[ i ],
labelId = labelCaption + '_' + editorName,
labelElement = doc.getById( labelId );
if ( 'undefined' != typeof labelElement
&& 'undefined' != typeof captions[ labelCaption ]
&& 'undefined' != typeof dialog.options[labels[ i ]] )
{
labelElement.setHtml( captions[ labelCaption ] );
var labelParent = labelElement.getParent();
labelParent.$.style.display = "block";
}
}
}
var about = '<p><img src="' + window.scayt.getAboutInfo().logoURL + '" /></p>' +
'<p>' + captions[ 'version' ] + window.scayt.getAboutInfo().version.toString() + '</p>' +
'<p>' + captions[ 'about_throwt_copy' ] + '</p>';
doc.getById( 'scayt_about_' + editorName ).setHtml( about );
// Create languages tab.
var createOption = function( option, list )
{
var label = doc.createElement( 'label' );
label.setAttribute( 'for', 'cke_option' + option );
label.setHtml( list[ option ] );
if ( dialog.sLang == option ) // Current.
dialog.chosed_lang = option;
var div = doc.createElement( 'div' );
var radio = CKEDITOR.dom.element.createFromHtml( '<input id="cke_option' +
option + '" type="radio" ' +
( dialog.sLang == option ? 'checked="checked"' : '' ) +
' value="' + option + '" name="scayt_lang" />' );
radio.on( 'click', function()
{
this.$.checked = true;
dialog.chosed_lang = option;
});
div.append( radio );
div.append( label );
return {
lang : list[ option ],
code : option,
radio : div
};
};
if ( tags[1] ==1 )
{
for ( i in lang_list.rtl )
langList[ langList.length ] = createOption( i, lang_list.ltr );
for ( i in lang_list.ltr )
langList[ langList.length ] = createOption( i, lang_list.ltr );
langList.sort( function( lang1, lang2 )
{
return ( lang2.lang > lang1.lang ) ? -1 : 1 ;
});
var fieldL = doc.getById( 'scayt_lcol_' + editorName ),
fieldR = doc.getById( 'scayt_rcol_' + editorName );
for ( i=0; i < langList.length; i++ )
{
var field = ( i < langList.length / 2 ) ? fieldL : fieldR;
field.append( langList[ i ].radio );
}
}
// user dictionary handlers
var dic = {};
dic.dic_create = function( el, dic_name , dic_buttons )
{
// comma separated button's ids include repeats if exists
var all_buttons = dic_buttons[0] + ',' + dic_buttons[1];
var err_massage = captions["err_dic_create"];
var suc_massage = captions["succ_dic_create"];
window.scayt.createUserDictionary( dic_name,
function( arg )
{
hide_dic_buttons ( all_buttons );
display_dic_buttons ( dic_buttons[1] );
suc_massage = suc_massage.replace("%s" , arg.dname );
dic_success_message (suc_massage);
},
function( arg )
{
err_massage = err_massage.replace("%s" ,arg.dname );
dic_error_message ( err_massage + "( "+ (arg.message || "") +")");
});
};
dic.dic_rename = function( el, dic_name )
{
//
// try to rename dictionary
var err_massage = captions["err_dic_rename"] || "";
var suc_massage = captions["succ_dic_rename"] || "";
window.scayt.renameUserDictionary( dic_name,
function( arg )
{
suc_massage = suc_massage.replace("%s" , arg.dname );
set_dic_name( dic_name );
dic_success_message ( suc_massage );
},
function( arg )
{
err_massage = err_massage.replace("%s" , arg.dname );
set_dic_name( dic_name );
dic_error_message( err_massage + "( " + ( arg.message || "" ) + " )" );
});
};
dic.dic_delete = function( el, dic_name , dic_buttons )
{
var all_buttons = dic_buttons[0] + ',' + dic_buttons[1];
var err_massage = captions["err_dic_delete"];
var suc_massage = captions["succ_dic_delete"];
// try to delete dictionary
window.scayt.deleteUserDictionary(
function( arg )
{
suc_massage = suc_massage.replace("%s" , arg.dname );
hide_dic_buttons ( all_buttons );
display_dic_buttons ( dic_buttons[0] );
set_dic_name( "" ); // empty input field
dic_success_message( suc_massage );
},
function( arg )
{
err_massage = err_massage.replace("%s" , arg.dname );
dic_error_message(err_massage);
});
};
dic.dic_restore = dialog.dic_restore || function( el, dic_name , dic_buttons )
{
// try to restore existing dictionary
var all_buttons = dic_buttons[0] + ',' + dic_buttons[1];
var err_massage = captions["err_dic_restore"];
var suc_massage = captions["succ_dic_restore"];
window.scayt.restoreUserDictionary(dic_name,
function( arg )
{
suc_massage = suc_massage.replace("%s" , arg.dname );
hide_dic_buttons ( all_buttons );
display_dic_buttons(dic_buttons[1]);
dic_success_message( suc_massage );
},
function( arg )
{
err_massage = err_massage.replace("%s" , arg.dname );
dic_error_message( err_massage );
});
};
function onDicButtonClick( ev )
{
var dic_name = doc.getById('dic_name_' + editorName).getValue();
if ( !dic_name )
{
dic_error_message(" Dictionary name should not be empty. ");
return false;
}
try{
var el = ev.data.getTarget().getParent();
var id = /(dic_\w+)_[\w\d]+/.exec(el.getId())[1];
dic[ id ].apply( null, [ el, dic_name, dic_buttons ] );
}
catch(err)
{
dic_error_message(" Dictionary error. ");
}
return true;
}
// ** bind event listeners
var arr_buttons = ( dic_buttons[0] + ',' + dic_buttons[1] ).split( ',' ),
l;
for ( i = 0, l = arr_buttons.length ; i < l ; i += 1 )
{
var dic_button = doc.getById(arr_buttons[i]);
if ( dic_button )
dic_button.on( 'click', onDicButtonClick, this );
}
};
var reload = function()
{
var dialog = this;
// for enabled options tab
if ( tags[0] == 1 ){
var opto = getBOMAllOptions();
// Animate options.
for ( var k=0,l = opto.length; k<l;k++ )
{
var i = opto[k].id;
var checkbox = doc.getById( i );
if ( checkbox )
{
opto[k].checked = false;
//alert (opto[k].removeAttribute)
if ( dialog.options[ i.split("_")[0] ] == 1 )
{
opto[k].checked = true;
}
// Bind events. Do it only once.
if ( firstLoad )
{
checkbox.on( 'click', function()
{
dialog.options[ this.getId().split("_")[0] ] = this.$.checked ? 1 : 0 ;
});
}
}
}
}
//for enabled languages tab
if ( tags[1] == 1 )
{
var domLang = doc.getById("cke_option" + dialog.sLang);
setCheckedValue( domLang.$,dialog.sLang );
}
// * user dictionary
if ( userDicActive )
{
window.scayt.getNameUserDictionary(
function( o )
{
var dic_name = o.dname;
hide_dic_buttons( dic_buttons[0] + ',' + dic_buttons[1] );
if ( dic_name )
{
doc.getById( 'dic_name_' + editorName ).setValue(dic_name);
display_dic_buttons( dic_buttons[1] );
}
else
display_dic_buttons( dic_buttons[0] );
},
function()
{
doc.getById( 'dic_name_' + editorName ).setValue("");
});
dic_success_message("");
}
};
function dic_error_message( m )
{
doc.getById('dic_message_' + editorName).setHtml('<span style="color:red;">' + m + '</span>' );
}
function dic_success_message( m )
{
doc.getById('dic_message_' + editorName).setHtml('<span style="color:blue;">' + m + '</span>') ;
}
function display_dic_buttons( sIds )
{
sIds = String( sIds );
var aIds = sIds.split(',');
for ( var i=0, l = aIds.length; i < l ; i+=1)
doc.getById( aIds[i] ).$.style.display = "inline";
}
function hide_dic_buttons( sIds )
{
sIds = String( sIds );
var aIds = sIds.split(',');
for ( var i = 0, l = aIds.length; i < l ; i += 1 )
doc.getById( aIds[i] ).$.style.display = "none";
}
function set_dic_name( dic_name )
{
doc.getById('dic_name_' + editorName).$.value= dic_name;
}
return dialogDefiniton;
}); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/_source/plugins/scayt/dialogs/options.js | options.js |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.add( 'floatpanel',
{
requires : [ 'panel' ]
});
(function()
{
var panels = {};
var isShowing = false;
function getPanel( editor, doc, parentElement, definition, level )
{
// Generates the panel key: docId-eleId-skinName-langDir[-uiColor][-CSSs][-level]
var key = CKEDITOR.tools.genKey( doc.getUniqueId(), parentElement.getUniqueId(), editor.skinName, editor.lang.dir,
editor.uiColor || '', definition.css || '', level || '' );
var panel = panels[ key ];
if ( !panel )
{
panel = panels[ key ] = new CKEDITOR.ui.panel( doc, definition );
panel.element = parentElement.append( CKEDITOR.dom.element.createFromHtml( panel.renderHtml( editor ), doc ) );
panel.element.setStyles(
{
display : 'none',
position : 'absolute'
});
}
return panel;
}
CKEDITOR.ui.floatPanel = CKEDITOR.tools.createClass(
{
$ : function( editor, parentElement, definition, level )
{
definition.forceIFrame = 1;
var doc = parentElement.getDocument(),
panel = getPanel( editor, doc, parentElement, definition, level || 0 ),
element = panel.element,
iframe = element.getFirst().getFirst();
this.element = element;
this._ =
{
editor : editor,
// The panel that will be floating.
panel : panel,
parentElement : parentElement,
definition : definition,
document : doc,
iframe : iframe,
children : [],
dir : editor.lang.dir
};
editor.on( 'mode', function(){ this.hide(); }, this );
},
proto :
{
addBlock : function( name, block )
{
return this._.panel.addBlock( name, block );
},
addListBlock : function( name, multiSelect )
{
return this._.panel.addListBlock( name, multiSelect );
},
getBlock : function( name )
{
return this._.panel.getBlock( name );
},
/*
corner (LTR):
1 = top-left
2 = top-right
3 = bottom-right
4 = bottom-left
corner (RTL):
1 = top-right
2 = top-left
3 = bottom-left
4 = bottom-right
*/
showBlock : function( name, offsetParent, corner, offsetX, offsetY )
{
var panel = this._.panel,
block = panel.showBlock( name );
this.allowBlur( false );
isShowing = 1;
// Record from where the focus is when open panel.
this._.returnFocus = this._.editor.focusManager.hasFocus ? this._.editor : new CKEDITOR.dom.element( CKEDITOR.document.$.activeElement );
var element = this.element,
iframe = this._.iframe,
definition = this._.definition,
position = offsetParent.getDocumentPosition( element.getDocument() ),
rtl = this._.dir == 'rtl';
var left = position.x + ( offsetX || 0 ),
top = position.y + ( offsetY || 0 );
// Floating panels are off by (-1px, 0px) in RTL mode. (#3438)
if ( rtl && ( corner == 1 || corner == 4 ) )
left += offsetParent.$.offsetWidth;
else if ( !rtl && ( corner == 2 || corner == 3 ) )
left += offsetParent.$.offsetWidth - 1;
if ( corner == 3 || corner == 4 )
top += offsetParent.$.offsetHeight - 1;
// Memorize offsetParent by it's ID.
this._.panel._.offsetParentId = offsetParent.getId();
element.setStyles(
{
top : top + 'px',
left: 0,
display : ''
});
// Don't use display or visibility style because we need to
// calculate the rendering layout later and focus the element.
element.setOpacity( 0 );
// To allow the context menu to decrease back their width
element.getFirst().removeStyle( 'width' );
// Configure the IFrame blur event. Do that only once.
if ( !this._.blurSet )
{
// Non IE prefer the event into a window object.
var focused = CKEDITOR.env.ie ? iframe : new CKEDITOR.dom.window( iframe.$.contentWindow );
// With addEventListener compatible browsers, we must
// useCapture when registering the focus/blur events to
// guarantee they will be firing in all situations. (#3068, #3222 )
CKEDITOR.event.useCapture = true;
focused.on( 'blur', function( ev )
{
if ( !this.allowBlur() )
return;
// As we are using capture to register the listener,
// the blur event may get fired even when focusing
// inside the window itself, so we must ensure the
// target is out of it.
var target = ev.data.getTarget() ;
if ( target.getName && target.getName() != 'iframe' )
return;
if ( this.visible && !this._.activeChild && !isShowing )
{
// Panel close is caused by user's navigating away the focus, e.g. click outside the panel.
// DO NOT restore focus in this case.
delete this._.returnFocus;
this.hide();
}
},
this );
focused.on( 'focus', function()
{
this._.focused = true;
this.hideChild();
this.allowBlur( true );
},
this );
CKEDITOR.event.useCapture = false;
this._.blurSet = 1;
}
panel.onEscape = CKEDITOR.tools.bind( function( keystroke )
{
if ( this.onEscape && this.onEscape( keystroke ) === false )
return false;
},
this );
CKEDITOR.tools.setTimeout( function()
{
if ( rtl )
left -= element.$.offsetWidth;
var panelLoad = CKEDITOR.tools.bind( function ()
{
var target = element.getFirst();
if ( block.autoSize )
{
// We must adjust first the width or IE6 could include extra lines in the height computation
var widthNode = block.element.$;
if ( CKEDITOR.env.gecko || CKEDITOR.env.opera )
widthNode = widthNode.parentNode;
if ( CKEDITOR.env.ie )
widthNode = widthNode.document.body;
var width = widthNode.scrollWidth;
// Account for extra height needed due to IE quirks box model bug:
// http://en.wikipedia.org/wiki/Internet_Explorer_box_model_bug
// (#3426)
if ( CKEDITOR.env.ie && CKEDITOR.env.quirks && width > 0 )
width += ( target.$.offsetWidth || 0 ) - ( target.$.clientWidth || 0 ) + 3;
// A little extra at the end.
// If not present, IE6 might break into the next line, but also it looks better this way
width += 4 ;
target.setStyle( 'width', width + 'px' );
// IE doesn't compute the scrollWidth if a filter is applied previously
block.element.addClass( 'cke_frameLoaded' );
var height = block.element.$.scrollHeight;
// Account for extra height needed due to IE quirks box model bug:
// http://en.wikipedia.org/wiki/Internet_Explorer_box_model_bug
// (#3426)
if ( CKEDITOR.env.ie && CKEDITOR.env.quirks && height > 0 )
height += ( target.$.offsetHeight || 0 ) - ( target.$.clientHeight || 0 ) + 3;
target.setStyle( 'height', height + 'px' );
// Fix IE < 8 visibility.
panel._.currentBlock.element.setStyle( 'display', 'none' ).removeStyle( 'display' );
}
else
target.removeStyle( 'height' );
var panelElement = panel.element,
panelWindow = panelElement.getWindow(),
windowScroll = panelWindow.getScrollPosition(),
viewportSize = panelWindow.getViewPaneSize(),
panelSize =
{
'height' : panelElement.$.offsetHeight,
'width' : panelElement.$.offsetWidth
};
// If the menu is horizontal off, shift it toward
// the opposite language direction.
if ( rtl ? left < 0 : left + panelSize.width > viewportSize.width + windowScroll.x )
left += ( panelSize.width * ( rtl ? 1 : -1 ) );
// Vertical off screen is simpler.
if ( top + panelSize.height > viewportSize.height + windowScroll.y )
top -= panelSize.height;
// If IE is in RTL, we have troubles with absolute
// position and horizontal scrolls. Here we have a
// series of hacks to workaround it. (#6146)
if ( CKEDITOR.env.ie )
{
var offsetParent = new CKEDITOR.dom.element( element.$.offsetParent ),
scrollParent = offsetParent;
// Quirks returns <body>, but standards returns <html>.
if ( scrollParent.getName() == 'html' )
scrollParent = scrollParent.getDocument().getBody();
if ( scrollParent.getComputedStyle( 'direction' ) == 'rtl' )
{
// For IE8, there is not much logic on this, but it works.
if ( CKEDITOR.env.ie8Compat )
left -= element.getDocument().getDocumentElement().$.scrollLeft * 2;
else
left -= ( offsetParent.$.scrollWidth - offsetParent.$.clientWidth );
}
}
// Trigger the onHide event of the previously active panel to prevent
// incorrect styles from being applied (#6170)
var innerElement = element.getFirst(),
activePanel;
if ( ( activePanel = innerElement.getCustomData( 'activePanel' ) ) )
activePanel.onHide && activePanel.onHide.call( this, 1 );
innerElement.setCustomData( 'activePanel', this );
element.setStyles(
{
top : top + 'px',
left : left + 'px'
} );
element.setOpacity( 1 );
} , this );
panel.isLoaded ? panelLoad() : panel.onLoad = panelLoad;
// Set the panel frame focus, so the blur event gets fired.
CKEDITOR.tools.setTimeout( function()
{
iframe.$.contentWindow.focus();
// We need this get fired manually because of unfired focus() function.
this.allowBlur( true );
}, 0, this);
}, CKEDITOR.env.air ? 200 : 0, this);
this.visible = 1;
if ( this.onShow )
this.onShow.call( this );
isShowing = 0;
},
hide : function( returnFocus )
{
if ( this.visible && ( !this.onHide || this.onHide.call( this ) !== true ) )
{
this.hideChild();
// Blur previously focused element. (#6671)
CKEDITOR.env.gecko && this._.iframe.getFrameDocument().$.activeElement.blur();
this.element.setStyle( 'display', 'none' );
this.visible = 0;
this.element.getFirst().removeCustomData( 'activePanel' );
// Return focus properly. (#6247)
var focusReturn = returnFocus !== false && this._.returnFocus;
if ( focusReturn )
{
// Webkit requires focus moved out panel iframe first.
if ( CKEDITOR.env.webkit && focusReturn.type )
focusReturn.getWindow().$.focus();
focusReturn.focus();
}
}
},
allowBlur : function( allow ) // Prevent editor from hiding the panel. #3222.
{
var panel = this._.panel;
if ( allow != undefined )
panel.allowBlur = allow;
return panel.allowBlur;
},
showAsChild : function( panel, blockName, offsetParent, corner, offsetX, offsetY )
{
// Skip reshowing of child which is already visible.
if ( this._.activeChild == panel && panel._.panel._.offsetParentId == offsetParent.getId() )
return;
this.hideChild();
panel.onHide = CKEDITOR.tools.bind( function()
{
// Use a timeout, so we give time for this menu to get
// potentially focused.
CKEDITOR.tools.setTimeout( function()
{
if ( !this._.focused )
this.hide();
},
0, this );
},
this );
this._.activeChild = panel;
this._.focused = false;
panel.showBlock( blockName, offsetParent, corner, offsetX, offsetY );
/* #3767 IE: Second level menu may not have borders */
if ( CKEDITOR.env.ie7Compat || ( CKEDITOR.env.ie8 && CKEDITOR.env.ie6Compat ) )
{
setTimeout(function()
{
panel.element.getChild( 0 ).$.style.cssText += '';
}, 100);
}
},
hideChild : function()
{
var activeChild = this._.activeChild;
if ( activeChild )
{
delete activeChild.onHide;
// Sub panels don't manage focus. (#7881)
delete activeChild._.returnFocus;
delete this._.activeChild;
activeChild.hide();
}
}
}
});
CKEDITOR.on( 'instanceDestroyed', function()
{
var isLastInstance = CKEDITOR.tools.isEmpty( CKEDITOR.instances );
for ( var i in panels )
{
var panel = panels[ i ];
// Safe to destroy it since there're no more instances.(#4241)
if ( isLastInstance )
panel.destroy();
// Panel might be used by other instances, just hide them.(#4552)
else
panel.element.hide();
}
// Remove the registration.
isLastInstance && ( panels = {} );
} );
})(); | zope.html | /zope.html-2.4.2.zip/zope.html-2.4.2/src/zope/html/ckeditor/3.6.2/ckeditor/_source/plugins/floatpanel/plugin.js | plugin.js |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.