code
stringlengths
501
5.19M
package
stringlengths
2
81
path
stringlengths
9
304
filename
stringlengths
4
145
__docformat__ = "restructuredtext" # import standard packages # import Zope3 interfaces from zope.intid.interfaces import IIntIds # import local interfaces from ztfy.blog.browser.interfaces import ITopicElementAddFormMenuTarget from ztfy.blog.interfaces.paragraph import IParagraphContainer, IParagraph from ztfy.skin.interfaces.container import IContainerBaseView, IActionsColumn, IContainerTableViewActionsCell from ztfy.skin.layer import IZTFYBrowserLayer, IZTFYBackLayer # import Zope3 packages from z3c.template.template import getLayoutTemplate from zope.component import adapts, getUtility from zope.i18n import translate from zope.interface import implements, Interface from zope.traversing.browser import absoluteURL # import local packages from ztfy.i18n.browser import ztfy_i18n from ztfy.skin.container import OrderedContainerBaseView from ztfy.skin.content import BaseContentDefaultBackViewAdapter from ztfy.skin.form import DialogAddForm, DialogEditForm from ztfy.skin.menu import MenuItem from ztfy.blog import _ class ParagraphContainerContentsViewMenu(MenuItem): """Paragraphs container contents menu""" title = _("Paragraphs") class ParagraphContainerContentsView(OrderedContainerBaseView): implements(ITopicElementAddFormMenuTarget) legend = _("Container's paragraphs") cssClasses = { 'table': 'orderable' } @property def values(self): return IParagraphContainer(self.context).paragraphs def render(self): ztfy_i18n.need() return super(ParagraphContainerContentsView, self).render() class ParagraphContainerTableViewCellActions(object): adapts(IParagraph, IZTFYBrowserLayer, IContainerBaseView, IActionsColumn) implements(IContainerTableViewActionsCell) def __init__(self, context, request, view, column): self.context = context self.request = request self.view = view self.column = column @property def content(self): klass = "workflow icon icon-trash" intids = getUtility(IIntIds) return '''<span class="%s" title="%s" onclick="$.ZTFY.container.remove(%s,this);"></span>''' % (klass, translate(_("Delete paragraph"), context=self.request), intids.register(self.context)) class ParagraphDefaultViewAdapter(BaseContentDefaultBackViewAdapter): adapts(IParagraph, IZTFYBackLayer, Interface) def getAbsoluteURL(self): return '''javascript:$.ZTFY.dialog.open('%s/%s')''' % (absoluteURL(self.context, self.request), self.viewname) class BaseParagraphAddForm(DialogAddForm): """Base paragraph add form""" implements(ITopicElementAddFormMenuTarget) legend = _("Adding new paragraph") layout = getLayoutTemplate() parent_interface = IParagraphContainer parent_view = OrderedContainerBaseView def add(self, paragraph): id = 1 while str(id) in self.context.keys(): id += 1 name = str(id) ids = list(self.context.keys()) + [name, ] self.context[name] = paragraph self.context.updateOrder(ids) class BaseParagraphEditForm(DialogEditForm): """Base paragraph edit form""" legend = _("Edit paragraph properties") layout = getLayoutTemplate() parent_interface = IParagraphContainer parent_view = OrderedContainerBaseView
ztfy.blog
/ztfy.blog-0.6.2.tar.gz/ztfy.blog-0.6.2/src/ztfy/blog/browser/paragraph.py
paragraph.py
__docformat__ = "restructuredtext" # import standard packages # import Zope3 interfaces from hurry.workflow.interfaces import IWorkflowState from z3c.language.switch.interfaces import II18n from zope.intid.interfaces import IIntIds from zope.dublincore.interfaces import IZopeDublinCore from zope.publisher.interfaces import NotFound # import local interfaces from ztfy.blog.browser.interfaces import ITopicAddFormMenuTarget, ISiteManagerTreeView from ztfy.blog.browser.interfaces.skin import ITopicIndexView from ztfy.blog.browser.interfaces.paragraph import IParagraphRenderer from ztfy.blog.interfaces import STATUS_LABELS, STATUS_DRAFT, STATUS_RETIRED, STATUS_ARCHIVED from ztfy.blog.interfaces.topic import ITopic, ITopicInfo, ITopicContainer from ztfy.comment.interfaces import IComments from ztfy.skin.interfaces.container import IContainerBaseView, \ IStatusColumn, IActionsColumn, \ IContainerTableViewStatusCell, IContainerTableViewActionsCell from ztfy.skin.layer import IZTFYBrowserLayer, IZTFYBackLayer from ztfy.workflow.interfaces import IWorkflowTarget, IWorkflowContent # import Zope3 packages from z3c.form import field from zope.component import adapts, getUtility, queryMultiAdapter from zope.i18n import translate from zope.interface import implements from zope.traversing.browser import absoluteURL # import local packages from ztfy.blog.topic import Topic from ztfy.security.search import getPrincipal from ztfy.skin.container import OrderedContainerBaseView from ztfy.skin.content import BaseContentDefaultBackViewAdapter from ztfy.skin.form import AddForm, EditForm from ztfy.skin.menu import MenuItem from ztfy.skin.presentation import BasePresentationEditForm, BaseIndexView from ztfy.skin.viewlets.properties import PropertiesViewlet from ztfy.utils.timezone import tztime from ztfy.blog import _ class TopicContainerContentsViewMenu(MenuItem): """Topics container contents menu""" title = _("Topics") class TopicAddFormMenu(MenuItem): """Topics container add form menu""" title = _(" :: Add topic...") class TopicTreeViewDefaultViewAdapter(BaseContentDefaultBackViewAdapter): adapts(ITopic, IZTFYBackLayer, ISiteManagerTreeView) def getAbsoluteURL(self): intids = getUtility(IIntIds) return '++oid++%d/%s' % (intids.register(self.context), self.viewname) class TopicContainerContentsView(OrderedContainerBaseView): """Topics container contents view""" implements(ITopicAddFormMenuTarget) legend = _("Container's topics") cssClasses = { 'table': 'orderable' } @property def values(self): return ITopicContainer(self.context).topics class TopicContainerTableViewCellStatus(object): adapts(ITopic, IZTFYBrowserLayer, IContainerBaseView, IStatusColumn) implements(IContainerTableViewStatusCell) def __init__(self, context, request, view, table): self.context = context self.request = request self.view = view self.table = table @property def content(self): status = IWorkflowState(self.context).getState() if status == STATUS_DRAFT: klass = "workflow icon icon-edit" elif status == STATUS_RETIRED: klass = "workflow icon icon-eye-close" elif status == STATUS_ARCHIVED: klass = "workflow icon icon-lock" else: klass = "workflow icon icon-globe" if klass: return '<span class="%s"></span> %s' % (klass, translate(STATUS_LABELS[status], context=self.request)) return '' class TopicContainerTableViewCellActions(object): adapts(ITopic, IZTFYBrowserLayer, IContainerBaseView, IActionsColumn) implements(IContainerTableViewActionsCell) def __init__(self, context, request, view, column): self.context = context self.request = request self.view = view self.column = column @property def content(self): status = IWorkflowState(self.context).getState() if status == STATUS_DRAFT: klass = "workflow icon icon-trash" intids = getUtility(IIntIds) return '''<span class="%s" title="%s" onclick="$.ZTFY.container.remove(%s,this);"></span>''' % (klass, translate(_("Delete topic"), context=self.request), intids.register(self.context)) return '' class TopicAddForm(AddForm): implements(ITopicAddFormMenuTarget) @property def title(self): return II18n(self.context).queryAttribute('title', request=self.request) legend = _("Adding new topic") fields = field.Fields(ITopicInfo).omit('publication_year', 'publication_month') + \ field.Fields(IWorkflowTarget) def updateWidgets(self): super(TopicAddForm, self).updateWidgets() self.widgets['heading'].cols = 80 self.widgets['heading'].rows = 10 self.widgets['description'].cols = 80 self.widgets['description'].rows = 3 def create(self, data): topic = Topic() topic.shortname = data.get('shortname', {}) topic.workflow_name = data.get('workflow_name') return topic def add(self, topic): self.context.addTopic(topic) def nextURL(self): return '%s/@@contents.html' % absoluteURL(self.context, self.request) class TopicEditForm(EditForm): legend = _("Topic properties") fields = field.Fields(ITopicInfo).omit('publication_year', 'publication_month') def updateWidgets(self): super(TopicEditForm, self).updateWidgets() self.widgets['heading'].cols = 80 self.widgets['heading'].rows = 10 self.widgets['description'].cols = 80 self.widgets['description'].rows = 3 class TopicPresentationEditForm(BasePresentationEditForm): """Blog presentation edit form""" legend = _("Edit topic presentation properties") parent_interface = ITopic class TopicPropertiesViewlet(PropertiesViewlet): """Topic properties viewlet""" @property def contributors(self): uids = IZopeDublinCore(self.context).creators[1:] return ', '.join((getPrincipal(uid).title for uid in uids)) @property def status_date(self): return tztime(IWorkflowContent(self.context).state_date) @property def status_principal(self): return getPrincipal(IWorkflowContent(self.context).state_principal) @property def first_publication_date(self): return tztime(IWorkflowContent(self.context).first_publication_date) @property def publication_dates(self): content = IWorkflowContent(self.context) return (tztime(content.publication_effective_date), tztime(content.publication_expiration_date)) @property def history(self): comments = IComments(self.context) return comments.getComments('__workflow__') class BaseTopicIndexView(BaseIndexView): """Base topic index view""" implements(ITopicIndexView) def update(self): if not IWorkflowContent(self.context).isVisible(): raise NotFound(self.context, self.__name__, self.request) super(BaseTopicIndexView, self).update() self.renderers = [renderer for renderer in [ queryMultiAdapter((paragraph, self, self.request), IParagraphRenderer) for paragraph in self.context.getVisibleParagraphs(self.request) ] if renderer is not None] [renderer.update() for renderer in self.renderers]
ztfy.blog
/ztfy.blog-0.6.2.tar.gz/ztfy.blog-0.6.2/src/ztfy/blog/browser/topic.py
topic.py
__docformat__ = "restructuredtext" # import standard packages # import Zope3 interfaces from z3c.form.interfaces import IWidgets, ISubForm from z3c.json.interfaces import IJSONWriter # import local interfaces from hurry.workflow.interfaces import IWorkflowInfo from ztfy.blog.interfaces.topic import ITopicContainer from ztfy.comment.interfaces import IComment # import Zope3 packages from z3c.form import field, button from z3c.formjs import ajax, jsaction from zope.component import getUtility, getMultiAdapter from zope.i18n import translate from zope.interface import implements, Interface from zope.traversing.browser import absoluteURL # import local packages from ztfy.blog.browser import ztfy_blog_back from ztfy.skin.form import EditForm from ztfy.utils.traversing import getParent from ztfy.workflow.interfaces import IWorkflowContentInfo from ztfy.blog import _ class IWorkflowFormButtons(Interface): submit = button.Button(title=_("Submit")) class WorkflowCommentAddForm(EditForm): """Workflow comment add form""" implements(ISubForm) legend = _("Workflow comment") fields = field.Fields(IComment).select('body') prefix = 'comment' def updateWidgets(self): self.widgets = getMultiAdapter((self, self.request, self.getContent()), IWidgets) self.widgets.ignoreContext = True self.widgets.update() class WorkflowBaseForm(EditForm): """Workflow base form""" _done = False transition = None buttons = button.Buttons(IWorkflowFormButtons) prefix = 'workflow' @property def legend(self): return self.transition.title @property def help(self): return translate(self.transition.user_data.get('html_help'), context=self.request) def createSubForms(self): self.comment = WorkflowCommentAddForm(None, self.request) return [self.comment, ] def updateWidgets(self): super(WorkflowBaseForm, self).updateWidgets() self.buttons['submit'].title = self.transition.title self.comment.widgets['body'].required = False @button.handler(buttons['submit']) def submit(self, action): self.handleApply(self, action) if self.status != self.formErrorsMessage: self._next = self.nextURL() comments, _errors = self.comment.widgets.extract() info = IWorkflowInfo(self.context) info.fireTransition(self.transition.transition_id, comment=comments.get('body')) self._done = True self.request.response.redirect(self._next) def nextURL(self): return '%s/@@properties.html' % absoluteURL(self.context, self.request) def render(self): if self._done and (self.request.response.getStatus() in (302, 303)): # redirect return '' return super(WorkflowBaseForm, self).render() class WorkflowPublishForm(WorkflowBaseForm): """Workflow publish form""" fields = field.Fields(IWorkflowContentInfo).select('publication_effective_date', 'publication_expiration_date') class IWorkflowDeleteFormButtons(Interface): submit = jsaction.JSButton(title=_("Submit")) class WorkflowDeleteForm(ajax.AJAXRequestHandler, WorkflowBaseForm): """Workflow delete form""" buttons = button.Buttons(IWorkflowDeleteFormButtons) def update(self): super(WorkflowDeleteForm, self).update() ztfy_blog_back.need() @jsaction.handler(buttons['submit']) def submit_handler(self, event, selector): return '$.ZBlog.topic.remove(this.form);' def nextURL(self): return '%s/@@topics.html' % absoluteURL(getParent(self.context, ITopicContainer), self.request) @ajax.handler def ajaxDelete(self): target = self.nextURL() info = IWorkflowInfo(self.context) info.fireTransition(self.transition.transition_id) writer = getUtility(IJSONWriter) return writer.write({ 'url': target })
ztfy.blog
/ztfy.blog-0.6.2.tar.gz/ztfy.blog-0.6.2/src/ztfy/blog/browser/workflow.py
workflow.py
__docformat__ = "restructuredtext" # import standard packages # import Zope3 interfaces from z3c.table.interfaces import INoneCell from zope.intid.interfaces import IIntIds # import local interfaces from ztfy.base.interfaces import IBaseContent from ztfy.blog.browser.interfaces import ISiteManagerTreeView, ISiteManagerTreeViewContent, IBlogAddFormMenuTarget, ISectionAddFormMenuTarget from ztfy.blog.browser.interfaces.skin import ISiteManagerIndexView from ztfy.blog.interfaces import IBaseContentRoles, ISkinnable from ztfy.blog.interfaces.blog import IBlog from ztfy.blog.interfaces.section import ISection from ztfy.blog.interfaces.site import ISiteManager, ISiteManagerInfo, ISiteManagerBackInfo, \ ITreeViewContents from ztfy.blog.interfaces.topic import ITopic from ztfy.skin.interfaces.container import IContainerBaseView, ITitleColumn, IActionsColumn, \ IContainerTableViewTitleCell, IContainerTableViewActionsCell from ztfy.skin.layer import IZTFYBrowserLayer, IZTFYBackLayer # import Zope3 packages from z3c.form import field from z3c.template.template import getLayoutTemplate from zope.component import adapts, getUtility from zope.interface import implements, Interface # import local packages from ztfy.blog.browser.skin import SkinSelectWidgetFactory from ztfy.jqueryui import jquery_treetable, jquery_ui_base from ztfy.security.browser.roles import RolesEditForm from ztfy.skin.container import ContainerBaseView, OrderedContainerBaseView from ztfy.skin.content import BaseContentDefaultBackViewAdapter from ztfy.skin.form import EditForm, DialogEditForm from ztfy.skin.menu import MenuItem, DialogMenuItem from ztfy.skin.presentation import BasePresentationEditForm, BaseIndexView from ztfy.blog import _ class SiteManagerTreeViewMenu(MenuItem): """Site manager tree view menu""" title = _("Tree view") def getValues(parent, context, output): output.append((parent, context)) contents = ITreeViewContents(context, None) if contents is not None: for item in contents.values: getValues(context, item, output) class SiteManagerTreeView(ContainerBaseView): """Site manager tree view""" implements(ISiteManagerTreeView) legend = _("Site's tree view") sortOn = None cssClasses = { 'table': 'orderable treeview' } batchSize = 10000 startBatchingAt = 10000 def __init__(self, context, request): super(SiteManagerTreeView, self).__init__(context, request) self.intids = getUtility(IIntIds) @property def values(self): result = [] getValues(None, self.context, result) return result def renderRow(self, row, cssClass=None): isSelected = self.isSelectedRow(row) if isSelected and self.cssClassSelected and cssClass: cssClass = '%s %s' % (self.cssClassSelected, cssClass) elif isSelected and self.cssClassSelected: cssClass = self.cssClassSelected (parent, context), _col, _colspan = row[0] content = ISiteManagerTreeViewContent(context, None) if (content is not None) and content.resourceLibrary: content.resourceLibrary.need() if (content is not None) and content.cssClass: cssClass += ' %s' % content.cssClass else: if ISiteManager.providedBy(context): cssClass += ' site' elif IBlog.providedBy(context): cssClass += ' blog' elif ISection.providedBy(context): cssClass += ' section' elif ITopic.providedBy(context): cssClass += ' topic' if parent is not None: cssClass += ' child-of-node-%d' % self.intids.register(parent) id = 'id="node-%d"' % self.intids.register(context) cssClass = self.getCSSClass('tr', cssClass) cells = [self.renderCell(context, col, colspan) for (parent, context), col, colspan in row] return u'\n <tr %s%s>%s\n </tr>' % (id, cssClass, u''.join(cells)) def renderCell(self, item, column, colspan=0): if INoneCell.providedBy(column): return u'' cssClass = column.cssClasses.get('td') cssClass = self.getCSSClass('td', cssClass) colspanStr = colspan and ' colspan="%s"' % colspan or '' return u'\n <td%s%s>%s</td>' % (cssClass, colspanStr, column.renderCell(item)) def update(self): super(SiteManagerTreeView, self).update() jquery_treetable.need() jquery_ui_base.need() class SiteManagerTreeViewTitleColumnCellAdapter(object): adapts(IBaseContent, IZTFYBrowserLayer, ISiteManagerTreeView, ITitleColumn) implements(IContainerTableViewTitleCell) prefix = u'' after = u'' suffix = u'' def __init__(self, context, request, table, column): self.context = context self.request = request self.table = table self.column = column @property def before(self): return '<span class="ui-icon"></span>&nbsp;' class SiteManagerContentsViewMenu(MenuItem): """Site manager contents view menu""" title = _("Site contents") class SiteManagerContentsView(OrderedContainerBaseView): """Site manager contents view""" implements(IBlogAddFormMenuTarget, ISectionAddFormMenuTarget) legend = _("Site's content") cssClasses = { 'table': 'orderable' } @property def values(self): return ISiteManager(self.context).values() class SiteManagerContentsViewCellActions(object): adapts(ISiteManager, IZTFYBrowserLayer, IContainerBaseView, IActionsColumn) implements(IContainerTableViewActionsCell) def __init__(self, context, request, view, column): self.context = context self.request = request self.view = view self.column = column @property def content(self): return u'' class SiteManagerEditForm(EditForm): legend = _("Site manager properties") fields = field.Fields(ISiteManagerInfo, ISkinnable) fields['skin'].widgetFactory = SkinSelectWidgetFactory def updateWidgets(self): super(SiteManagerEditForm, self).updateWidgets() self.widgets['heading'].cols = 80 self.widgets['heading'].rows = 10 self.widgets['description'].cols = 80 self.widgets['description'].rows = 3 class SiteManagerRolesEditForm(RolesEditForm): interfaces = (IBaseContentRoles,) layout = getLayoutTemplate() parent_interface = ISiteManager class SiteManagerRolesMenuItem(DialogMenuItem): """Site manager roles menu item""" title = _(":: Roles...") target = SiteManagerRolesEditForm class SiteManagerBackInfoEditForm(DialogEditForm): """Site manager back-office infos edit form""" legend = _("Edit back-office properties") fields = field.Fields(ISiteManagerBackInfo) def getContent(self): return ISiteManagerBackInfo(self.context) def getOutput(self, writer, parent, changes=()): status = changes and u'RELOAD' or u'NONE' return writer.write({ 'output': status }) class SiteManagerBackInfoMenuItem(DialogMenuItem): """Site manager back-office infos menu item""" title = _(":: Back-office...") target = SiteManagerBackInfoEditForm class SiteManagerPresentationEditForm(BasePresentationEditForm): """Site manager presentation edit form""" legend = _("Edit site presentation properties") parent_interface = ISiteManager class SiteManagerDefaultViewAdapter(BaseContentDefaultBackViewAdapter): adapts(ISiteManager, IZTFYBackLayer, Interface) viewname = '@@treeview.html' class SiteManagerTreeViewDefaultViewAdapter(SiteManagerDefaultViewAdapter): adapts(ISiteManager, IZTFYBackLayer, ISiteManagerTreeView) viewname = '@@properties.html' class BaseSiteManagerIndexView(BaseIndexView): """Base site manager index view""" implements(ISiteManagerIndexView)
ztfy.blog
/ztfy.blog-0.6.2.tar.gz/ztfy.blog-0.6.2/src/ztfy/blog/browser/site.py
site.py
__docformat__ = "restructuredtext" # import standard packages # import Zope3 interfaces from z3c.language.switch.interfaces import II18n from zope.intid.interfaces import IIntIds from zope.traversing.interfaces import TraversalError # import local interfaces from ztfy.blog.interfaces.link import ILinkContainer, ILinkContainerTarget from ztfy.blog.interfaces.link import IBaseLinkInfo, IInternalLink, IInternalLinkInfo, IExternalLink, IExternalLinkInfo, ILinkFormatter from ztfy.skin.interfaces import IDefaultView from ztfy.skin.interfaces.container import IContainerBaseView from ztfy.skin.interfaces.container import IStatusColumn, IActionsColumn from ztfy.skin.interfaces.container import IContainerTableViewStatusCell, IContainerTableViewActionsCell from ztfy.skin.layer import IZTFYBrowserLayer, IZTFYBackLayer # import Zope3 packages from z3c.form import field from z3c.formjs import ajax from z3c.template.template import getLayoutTemplate from zope.component import adapts, getUtility, queryMultiAdapter from zope.i18n import translate from zope.interface import implements, Interface from zope.traversing import namespace from zope.traversing.api import getParent as getParentAPI, getName from zope.traversing.browser import absoluteURL # import local packages from ztfy.blog.browser import ztfy_blog_back from ztfy.blog.link import InternalLink, ExternalLink from ztfy.i18n.browser import ztfy_i18n from ztfy.jqueryui import jquery_multiselect from ztfy.skin.container import OrderedContainerBaseView from ztfy.skin.content import BaseContentDefaultBackViewAdapter from ztfy.skin.form import DialogAddForm, DialogEditForm from ztfy.skin.menu import MenuItem, DialogMenuItem from ztfy.utils.container import getContentName from ztfy.utils.text import textToHTML from ztfy.utils.traversing import getParent from ztfy.blog import _ class LinkDefaultViewAdapter(BaseContentDefaultBackViewAdapter): adapts(IBaseLinkInfo, IZTFYBackLayer, Interface) def getAbsoluteURL(self): return '''javascript:$.ZTFY.dialog.open('%s/%s')''' % (absoluteURL(self.context, self.request), self.viewname) class LinkContainerNamespaceTraverser(namespace.view): """++static++ namespace""" def traverse(self, name, ignored): result = getParent(self.context, ILinkContainerTarget) if result is not None: return ILinkContainer(result) raise TraversalError('++links++') class ILinkAddFormMenuTarget(Interface): """Marker interface for link add menu""" class LinkContainerContentsViewMenuItem(MenuItem): """Links container contents menu""" title = _("Links") def render(self): jquery_multiselect.need() ztfy_blog_back.need() return super(LinkContainerContentsViewMenuItem, self).render() class ILinkContainerContentsView(Interface): """Marker interface for links container contents view""" class LinkContainerContentsView(OrderedContainerBaseView): """Links container contents view""" implements(ILinkAddFormMenuTarget, ILinkContainerContentsView) legend = _("Topic links") cssClasses = { 'table': 'orderable' } def __init__(self, *args, **kw): super(LinkContainerContentsView, self).__init__(*args, **kw) @property def values(self): return ILinkContainer(self.context).values() @ajax.handler def ajaxRemove(self): oid = self.request.form.get('id') if oid: intids = getUtility(IIntIds) target = intids.getObject(int(oid)) parent = getParentAPI(target) del parent[getName(target)] return "OK" return "NOK" @ajax.handler def ajaxUpdateOrder(self): self.updateOrder(ILinkContainer(self.context)) class LinkContainerTableViewCellStatus(object): adapts(IBaseLinkInfo, IZTFYBrowserLayer, IContainerBaseView, IStatusColumn) implements(IContainerTableViewStatusCell) def __init__(self, context, request, view, table): self.context = context self.request = request self.view = view self.table = table @property def content(self): info = IInternalLinkInfo(self.context, None) if info is not None: adapter = queryMultiAdapter((info.target, self.request, self.view, self.table), IContainerTableViewStatusCell) if adapter is not None: return adapter.content return '' class LinkContainerContentsViewActionsColumnCellAdapter(object): adapts(IBaseLinkInfo, IZTFYBrowserLayer, ILinkContainerContentsView, IActionsColumn) implements(IContainerTableViewActionsCell) def __init__(self, context, request, view, column): self.context = context self.request = request self.view = view self.column = column self.intids = getUtility(IIntIds) @property def content(self): klass = "workflow icon icon-trash" result = '''<span class="%s" title="%s" onclick="$.ZTFY.form.remove(%d, this);"></span>''' % (klass, translate(_("Delete link"), context=self.request), self.intids.register(self.context)) return result class BaseLinkAddForm(DialogAddForm): """Base link add form""" layout = getLayoutTemplate() parent_interface = ILinkContainerTarget parent_view = LinkContainerContentsView @ajax.handler def ajaxCreate(self): return super(BaseLinkAddForm, self).ajaxCreate(self) def add(self, link): title = II18n(link).queryAttribute('title', request=self.request) if not title: title = translate(_("Untitled link"), context=self.request) name = getContentName(self.context, title) self.context[name] = link class InternalLinkAddForm(BaseLinkAddForm): """Internal link add form""" legend = _("Adding new internal link") fields = field.Fields(IInternalLinkInfo).omit('target') resources = (ztfy_i18n,) def create(self, data): result = InternalLink() result.title = data.get('title', {}) return result class LinkContainerAddInternalLinkMenuItem(DialogMenuItem): """Internal link add menu""" title = _(":: Add internal link...") target = InternalLinkAddForm class ExternalLinkAddForm(BaseLinkAddForm): """External link add form""" legend = _("Adding new external link") fields = field.Fields(IExternalLinkInfo) resources = (ztfy_i18n,) def create(self, data): result = ExternalLink() result.title = data.get('title', {}) return result class LinkContainerAddExternalLinkMenuItem(DialogMenuItem): """External link add menu""" title = _(":: Add external link...") target = ExternalLinkAddForm class BaseLinkEditForm(DialogEditForm): """Base link edit form""" legend = _("Edit link properties") layout = getLayoutTemplate() parent_interface = ILinkContainerTarget parent_view = LinkContainerContentsView @ajax.handler def ajaxEdit(self): return super(BaseLinkEditForm, self).ajaxEdit(self) class InternalLinkEditForm(BaseLinkEditForm): """Internal link edit form""" fields = field.Fields(IInternalLinkInfo).omit('target') class ExternalLinkEditForm(BaseLinkEditForm): """External link edit form""" fields = field.Fields(IExternalLinkInfo) class InternalLinkFormatter(object): """Internal link default view""" adapts(IInternalLink, IZTFYBrowserLayer, Interface) implements(ILinkFormatter) def __init__(self, link, request, view): self.link = link self.request = request self.view = view def render(self): target = self.link.target adapter = queryMultiAdapter((self.link, self.request, self.view), IDefaultView) if adapter is not None: url = adapter.absoluteURL() else: url = absoluteURL(target, self.request) title = II18n(self.link).queryAttribute('title', request=self.request) or \ II18n(target).queryAttribute('title', request=self.request) desc = II18n(self.link).queryAttribute('description', request=self.request) or \ II18n(target).queryAttribute('description', request=self.request) result = '' if self.link.language: result += '''<img src="/--static--/ztfy.i18n/img/flags/%s.png" alt="" />''' % self.link.language.replace('-', '_', 1) result += '''<a href="%s">%s</a>''' % (url, title) if desc: result += '''<div class="desc">%s</div>''' % textToHTML(desc, request=self.request) return '''<div class="link link-internal">%s</link>''' % result class ExternalLinkFormatter(object): """External link default view""" adapts(IExternalLink, IZTFYBrowserLayer, Interface) implements(ILinkFormatter) def __init__(self, link, request, view): self.link = link self.request = request self.view = view def render(self): title = II18n(self.link).queryAttribute('title', request=self.request) desc = II18n(self.link).queryAttribute('description', request=self.request) result = '' if self.link.language: result += '''<img src="/--static--/ztfy.i18n/img/flags/%s.png" alt="" />''' % self.link.language.replace('-', '_', 1) result += '''<a href="%s">%s</a>''' % (self.link.url, title) if desc: result += '''<div class="desc">%s</div>''' % textToHTML(desc, request=self.request) return '''<div class="link link-external">%s</link>''' % result
ztfy.blog
/ztfy.blog-0.6.2.tar.gz/ztfy.blog-0.6.2/src/ztfy/blog/browser/link.py
link.py
__docformat__ = "restructuredtext" # import standard packages # import Zope3 interfaces from z3c.json.interfaces import IJSONWriter from z3c.language.switch.interfaces import II18n from zope.intid.interfaces import IIntIds from zope.traversing.interfaces import TraversalError # import local interfaces from ztfy.blog.interfaces.category import ICategory, ICategoryInfo, ICategoryManager, ICategoryManagerTarget, ICategorizedContent from ztfy.blog.interfaces.site import ISiteManager from ztfy.skin.interfaces import IDialogAddFormButtons from ztfy.skin.interfaces.container import ITitleColumn, IActionsColumn, \ IContainerTableViewTitleCell, IContainerTableViewActionsCell from ztfy.skin.layer import IZTFYBrowserLayer, IZTFYBackLayer # import Zope3 packages from z3c.form import field, button from z3c.formjs import ajax, jsaction from z3c.template.template import getLayoutTemplate from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile from zope.component import adapts, getUtility from zope.event import notify from zope.i18n import translate from zope.interface import implements, Interface from zope.lifecycleevent import ObjectModifiedEvent from zope.traversing import namespace from zope.traversing.api import getParent as getParentAPI, getName from zope.traversing.browser import absoluteURL # import local packages from ztfy.blog.category import Category from ztfy.i18n.browser import ztfy_i18n from ztfy.jqueryui import jquery_treetable from ztfy.skin.container import ContainerBaseView from ztfy.skin.content import BaseContentDefaultBackViewAdapter from ztfy.skin.form import DialogAddForm, DialogEditForm from ztfy.skin.menu import MenuItem, DialogMenuItem from ztfy.utils.traversing import getParent from ztfy.utils.unicode import translateString from ztfy.blog import _ class ICategoryAddFormMenuTarget(Interface): """Marker interface for category add menu""" class CategoryManagerNamespaceTraverser(namespace.view): """++category++ namespace""" def traverse(self, name, ignored): result = ICategoryManager(self.context, None) if result is not None: return result raise TraversalError('++category++') def getValues(parent, context, output): output.append((parent, context)) for item in context.values(): getValues(context, item, output) class ICategoryManagerContentsView(Interface): """Marker interface for category manager contents view""" class CategoryManagerContentsView(ajax.AJAXRequestHandler, ContainerBaseView): """Category manager contents view""" implements(ICategoryAddFormMenuTarget, ICategoryManagerContentsView) legend = _("Topics categories") sortOn = None batchSize = 999 startBatchingAt = 999 cssClasses = { 'table': 'foldertree treeview' } output = ViewPageTemplateFile('templates/categories.pt') def __init__(self, context, request): super(CategoryManagerContentsView, self).__init__(context, request) self.intids = getUtility(IIntIds) @property def values(self): result = [] for item in ICategory(self.context).values(): getValues(None, item, result) return result def renderRow(self, row, cssClass=None): isSelected = self.isSelectedRow(row) if isSelected and self.cssClassSelected and cssClass: cssClass = '%s %s' % (self.cssClassSelected, cssClass) elif isSelected and self.cssClassSelected: cssClass = self.cssClassSelected (parent, context), _col, _colspan = row[0] if parent is not None: cssClass += ' child-of-node-%d' % self.intids.register(parent) id = 'id="node-%d"' % self.intids.register(context) cssClass = self.getCSSClass('tr', cssClass) cells = [self.renderCell(context, col, colspan) for (parent, context), col, colspan in row] return u'\n <tr %s%s>%s\n </tr>' % (id, cssClass, u''.join(cells)) def update(self): super(CategoryManagerContentsView, self).update() jquery_treetable.need() @ajax.handler def ajaxRemove(self): oid = self.request.form.get('id') if oid: target = self.intids.getObject(int(oid)) parent = getParentAPI(target) del parent[getName(target)] return "OK" return "NOK" class CategoryManagerTreeViewTitleColumnCellAdapter(object): adapts(ICategory, IZTFYBrowserLayer, ICategoryManagerContentsView, ITitleColumn) implements(IContainerTableViewTitleCell) prefix = u'' after = u'' suffix = u'' def __init__(self, context, request, table, column): self.context = context self.request = request self.table = table self.column = column @property def before(self): return '<span class="icon icon-folder-open"></span>&nbsp;' class CategoryManagerTreeViewActionsColumnCellAdapter(object): adapts(ICategory, IZTFYBrowserLayer, ICategoryManagerContentsView, IActionsColumn) implements(IContainerTableViewActionsCell) def __init__(self, context, request, view, column): self.context = context self.request = request self.view = view self.column = column self.intids = getUtility(IIntIds) @property def content(self): klass = "workflow icon icon-plus-sign" result = '''<span class="%s" title="%s" onclick="$.ZTFY.dialog.open('++category++/@@addCategory.html?parent=%d');"></span>''' % (klass, translate(_("Add sub-category"), context=self.request), self.intids.register(self.context)) klass = "workflow icon icon-trash" result += '''<span class="%s" title="%s" onclick="$.ZTFY.form.remove(%d, this);"></span>''' % (klass, translate(_("Delete (sub-)category"), context=self.request), self.intids.register(self.context)) return result class CategoryManagerContentsMenuItem(MenuItem): """Category manager contents menu""" title = _("Categories") class CategoryAddForm(DialogAddForm): """Category add form""" legend = _("Adding new category") @property def title(self): return II18n(getParent(self.context, ISiteManager)).queryAttribute('title', request=self.request) fields = field.Fields(ICategoryInfo) buttons = button.Buttons(IDialogAddFormButtons) layout = getLayoutTemplate() resources = (ztfy_i18n,) @jsaction.handler(buttons['add']) def add_handler(self, event, selector): return '$.ZTFY.form.add(this.form, %s);' % self.request.form.get('parent', 'null') @jsaction.handler(buttons['cancel']) def cancel_handler(self, event, selector): return '$.ZTFY.dialog.close();' @ajax.handler def ajaxCreate(self): writer = getUtility(IJSONWriter) self.updateWidgets() data, errors = self.extractData() if errors: self.status = self.formErrorsMessage return writer.write(self.getAjaxErrors()) self.createAndAdd(data) view = CategoryManagerContentsView(getParent(self.context, ICategoryManagerTarget), self.request) view.update() return writer.write({ 'output': 'RELOAD' }) def create(self, data): category = Category() category.shortname = data.get('shortname', {}) return category def add(self, category): parent = self.request.form.get('parent') if parent is None: context = ICategory(self.context) else: intids = getUtility(IIntIds) context = intids.getObject(int(parent)) language = II18n(context).getDefaultLanguage() name = translateString(category.shortname.get(language), forceLower=True, spaces='-') context[name] = category class CategoryManagerAddCategoryMenuItem(DialogMenuItem): """Category add menu""" title = _(":: Add Category...") target = CategoryAddForm class CategoryDefaultViewAdapter(BaseContentDefaultBackViewAdapter): adapts(ICategory, IZTFYBackLayer, Interface) def getAbsoluteURL(self): return '''javascript:$.ZTFY.dialog.open('%s/%s')''' % (absoluteURL(self.context, self.request), self.viewname) class CategoryEditForm(DialogEditForm): """Category edit form""" legend = _("Edit category properties") fields = field.Fields(ICategoryInfo) layout = getLayoutTemplate() parent_interface = ICategoryManagerTarget parent_view = CategoryManagerContentsView class ICategorizedContentEditForm(Interface): """Marker interface for categorized contents edit form""" class CategorizedContentEditForm(ajax.AJAXRequestHandler, ContainerBaseView): implements(ICategorizedContentEditForm) legend = _("Topic categories") sortOn = None batchSize = 999 startBatchingAt = 999 cssClasses = { 'table': 'foldertree treeview' } output = ViewPageTemplateFile('templates/categories.pt') def __init__(self, context, request): super(CategorizedContentEditForm, self).__init__(context, request) self.intids = getUtility(IIntIds) @property def values(self): result = [] target = getParent(self.context, ICategoryManagerTarget) while (target is not None) and (not ICategoryManager(target).values()): target = getParent(target, ICategoryManagerTarget, False) if target is not None: for item in ICategoryManager(target).values(): getValues(None, item, result) return result def renderRow(self, row, cssClass=None): isSelected = self.isSelectedRow(row) if isSelected and self.cssClassSelected and cssClass: cssClass = '%s %s' % (self.cssClassSelected, cssClass) elif isSelected and self.cssClassSelected: cssClass = self.cssClassSelected (parent, context), _col, _colspan = row[0] if parent is not None: cssClass += ' child-of-node-%d' % self.intids.register(parent) id = 'id="node-%d"' % self.intids.register(context) cssClass = self.getCSSClass('tr', cssClass) cells = [self.renderCell(context, col, colspan) for (parent, context), col, colspan in row] return u'\n <tr %s%s>%s\n </tr>' % (id, cssClass, u''.join(cells)) def update(self): super(CategorizedContentEditForm, self).update() jquery_treetable.need() ztfy_i18n.need() @ajax.handler def ajaxUpdate(self): oids = self.request.form.get('category', []) ICategorizedContent(self.context).categories = [self.intids.getObject(int(oid)) for oid in oids] notify(ObjectModifiedEvent(self.context)) return "OK" class CategorizedContentEditFormTitleColumnCellAdapter(object): adapts(ICategory, IZTFYBrowserLayer, ICategorizedContentEditForm, ITitleColumn) implements(IContainerTableViewTitleCell) before = u'' after = u'' suffix = u'' def __init__(self, context, request, table, column): self.context = context self.request = request self.table = table self.column = column self.intids = getUtility(IIntIds) @property def prefix(self): return '<input type="checkbox" %s name="category:list" value="%s" /> ' % (self.context in ICategorizedContent(self.table.context).categories and 'checked="checked"' or '', self.intids.register(self.context)) class CategorizedContentEditFormMenuItem(MenuItem): title = _("Categories")
ztfy.blog
/ztfy.blog-0.6.2.tar.gz/ztfy.blog-0.6.2/src/ztfy/blog/browser/category.py
category.py
__docformat__ = "restructuredtext" # import standard packages # import Zope3 interfaces from z3c.language.switch.interfaces import II18n from zope.intid.interfaces import IIntIds from zope.publisher.browser import NotFound # import local interfaces from ztfy.blog.browser.interfaces import IBlogAddFormMenuTarget from ztfy.blog.browser.interfaces.skin import IBlogIndexView from ztfy.blog.browser.topic import ITopicAddFormMenuTarget from ztfy.blog.interfaces import ISkinnable, IBaseContentRoles from ztfy.blog.interfaces.blog import IBlog, IBlogInfo from ztfy.blog.interfaces.topic import ITopicContainer from ztfy.skin.interfaces.container import IContainerBaseView from ztfy.skin.interfaces.container import IStatusColumn, IActionsColumn from ztfy.skin.interfaces.container import IContainerTableViewActionsCell, IContainerTableViewStatusCell from ztfy.skin.layer import IZTFYBrowserLayer, IZTFYBackLayer # import Zope3 packages from z3c.form import field from z3c.template.template import getLayoutTemplate from zope.component import adapts, getUtility from zope.i18n import translate from zope.interface import implements, Interface from zope.traversing.browser import absoluteURL # import local packages from ztfy.blog.browser.skin import SkinSelectWidgetFactory from ztfy.blog.blog import Blog from ztfy.security.browser.roles import RolesEditForm from ztfy.skin.container import ContainerBaseView from ztfy.skin.content import BaseContentDefaultBackViewAdapter from ztfy.skin.form import AddForm, EditForm from ztfy.skin.menu import MenuItem, DialogMenuItem from ztfy.skin.presentation import BasePresentationEditForm, BaseIndexView from ztfy.utils.unicode import translateString from ztfy.blog import _ class BlogDefaultViewAdapter(BaseContentDefaultBackViewAdapter): adapts(IBlogInfo, IZTFYBackLayer, Interface) viewname = '@@contents.html' class BlogAddFormMenu(MenuItem): """Blogs container add form menu""" title = _(" :: Add blog...") class BlogContainerContentsViewCellActions(object): adapts(IBlog, IZTFYBrowserLayer, IContainerBaseView, IActionsColumn) implements(IContainerTableViewActionsCell) def __init__(self, context, request, view, column): self.context = context self.request = request self.view = view self.column = column @property def content(self): if not IBlog(self.context).topics: klass = "workflow icon icon-trash" intids = getUtility(IIntIds) return '''<span class="%s" title="%s" onclick="$.ZTFY.container.remove(%s,this);"></span>''' % (klass, translate(_("Delete blog"), context=self.request), intids.register(self.context)) return '' class BlogTopicsContentsViewMenu(MenuItem): """Site manager tree view menu""" title = _("Blog topics") class BlogTopicsContentsView(ContainerBaseView): """Blog contents view""" implements(ITopicAddFormMenuTarget) legend = _("Blog's topics") cssClasses = { 'table': 'orderable', 'tr': 'topic' } sortOn = None sortOrder = None @property def values(self): return ITopicContainer(self.context).topics class BlogTableViewCellStatus(object): adapts(IBlogInfo, IZTFYBackLayer, IContainerBaseView, IStatusColumn) implements(IContainerTableViewStatusCell) def __init__(self, context, request, view, table): self.context = context self.request = request self.view = view self.table = table @property def content(self): return translate(_("&raquo; %d topic(s)"), context=self.request) % len(self.context.topics) class BlogAddForm(AddForm): implements(IBlogAddFormMenuTarget) @property def title(self): return II18n(self.context).queryAttribute('title', request=self.request) legend = _("Adding new blog") fields = field.Fields(IBlogInfo, ISkinnable) fields['skin'].widgetFactory = SkinSelectWidgetFactory def updateWidgets(self): super(BlogAddForm, self).updateWidgets() self.widgets['heading'].cols = 80 self.widgets['heading'].rows = 10 self.widgets['description'].cols = 80 self.widgets['description'].rows = 3 def create(self, data): blog = Blog() blog.shortname = data.get('shortname', {}) return blog def add(self, blog): language = II18n(self.context).getDefaultLanguage() name = translateString(blog.shortname.get(language), forceLower=True, spaces='-') ids = list(self.context.keys()) + [name, ] self.context[name] = blog self.context.updateOrder(ids) def nextURL(self): return '%s/@@contents.html' % absoluteURL(self.context, self.request) class BlogEditForm(EditForm): legend = _("Blog properties") fields = field.Fields(IBlogInfo, ISkinnable) fields['skin'].widgetFactory = SkinSelectWidgetFactory def updateWidgets(self): super(BlogEditForm, self).updateWidgets() self.widgets['heading'].cols = 80 self.widgets['heading'].rows = 10 self.widgets['description'].cols = 80 self.widgets['description'].rows = 3 class BlogRolesEditForm(RolesEditForm): interfaces = (IBaseContentRoles,) layout = getLayoutTemplate() parent_interface = IBlog class BlogRolesMenuItem(DialogMenuItem): """Blog roles menu item""" title = _(":: Roles...") target = BlogRolesEditForm class BlogPresentationEditForm(BasePresentationEditForm): """Blog presentation edit form""" legend = _("Edit blog presentation properties") parent_interface = IBlog class BaseBlogIndexView(BaseIndexView): """Base blog index view""" implements(IBlogIndexView) def update(self): if not self.context.visible: raise NotFound(self.context, 'index.html', self.request) super(BaseBlogIndexView, self).update() self.topics = self.context.getVisibleTopics()
ztfy.blog
/ztfy.blog-0.6.2.tar.gz/ztfy.blog-0.6.2/src/ztfy/blog/browser/blog.py
blog.py
__docformat__ = "restructuredtext" # import standard packages import copy # import Zope3 interfaces from zope.publisher.interfaces.browser import IBrowserSkinType from zope.schema.interfaces import IText # import local interfaces from ztfy.blog.interfaces.resource import IResourceContainerTarget from ztfy.file.browser.widget.interfaces import IHTMLWidgetSettings from ztfy.skin.interfaces import ISkinnable, IBaseForm from ztfy.skin.layer import IZTFYBrowserLayer, IZTFYFrontLayer # import Zope3 packages from z3c.form import widget from z3c.form.browser.select import SelectWidget from zope.component import adapter, adapts, queryUtility, queryMultiAdapter from zope.interface import implements, implementer from zope.publisher.browser import applySkin from zope.traversing.browser import absoluteURL # import local packages from ztfy.utils.traversing import getParent from ztfy.blog import _ # # Skin selection widget # class SkinSelectWidget(SelectWidget): noValueMessage = _("(inherit parent skin)") def SkinSelectWidgetFactory(field, request): return widget.FieldWidget(field, SkinSelectWidget(request)) # # HTML widget # @adapter(IText, IBaseForm, IZTFYBrowserLayer) @implementer(IHTMLWidgetSettings) def HTMLWidgetAdapterFactory(field, form, request): """Create widget adapter matching content's applied skin""" settings = None target = getParent(form.context, ISkinnable) if target is not None: skin_name = ISkinnable(target).getSkin() if not skin_name: skin_name = 'ZBlog' skin = queryUtility(IBrowserSkinType, skin_name) if skin is not None: fake = copy.copy(request) applySkin(fake, skin) settings = queryMultiAdapter((field, form, fake), IHTMLWidgetSettings) return settings class HTMLWidgetAdapter(object): """HTML widget settings adapter""" adapts(IText, IBaseForm, IZTFYFrontLayer) implements(IHTMLWidgetSettings) def __init__(self, field, form, request): self.field = field self.form = form self.request = request mce_invalid_elements = 'h1,h2' @property def mce_external_image_list_url(self): target = getParent(self.form.context, IResourceContainerTarget) if target is not None: return '%s/@@getImagesList.js' % absoluteURL(target, self.request) return None @property def mce_external_link_list_url(self): target = getParent(self.form.context, IResourceContainerTarget) if target is not None: return '%s/@@getLinksList.js' % absoluteURL(target, self.request) return None
ztfy.blog
/ztfy.blog-0.6.2.tar.gz/ztfy.blog-0.6.2/src/ztfy/blog/browser/skin.py
skin.py
__docformat__ = "restructuredtext" # import standard packages from persistent import Persistent # import Zope3 interfaces from zope.annotation.interfaces import IAnnotations # import local interfaces from ztfy.blog.browser.interfaces.skin import ISectionIndexView from ztfy.blog.defaultskin.interfaces import ISectionPresentationInfo, IContainerSitemapInfo, SECTION_DISPLAY_FIRST from ztfy.blog.defaultskin.layer import IZBlogDefaultLayer from ztfy.blog.interfaces.section import ISection from ztfy.skin.interfaces import IPresentationTarget # import Zope3 packages from z3c.template.template import getViewTemplate from zope.component import adapter, adapts from zope.container.contained import Contained from zope.interface import implementer, implements from zope.publisher.browser import BrowserView from zope.schema.fieldproperty import FieldProperty from zope.traversing.api import getParents from zope.traversing.browser import absoluteURL # import local packages from ztfy.blog.browser.section import BaseSectionIndexView from ztfy.blog.defaultskin.menu import DefaultSkinDialogMenuItem from ztfy.blog import _ SECTION_PRESENTATION_KEY = 'ztfy.blog.defaultskin.section.presentation' class SectionPresentationViewMenuItem(DefaultSkinDialogMenuItem): """Section presentation menu item""" title = _(" :: Presentation model...") class SectionPresentation(Persistent, Contained): """Section presentation infos""" implements(ISectionPresentationInfo) header_format = FieldProperty(ISectionPresentationInfo['header_format']) header_position = FieldProperty(ISectionPresentationInfo['header_position']) display_googleplus = FieldProperty(ISectionPresentationInfo['display_googleplus']) display_fb_like = FieldProperty(ISectionPresentationInfo['display_fb_like']) presentation_mode = FieldProperty(ISectionPresentationInfo['presentation_mode']) @adapter(ISection) @implementer(ISectionPresentationInfo) def SectionPresentationFactory(context): annotations = IAnnotations(context) presentation = annotations.get(SECTION_PRESENTATION_KEY) if presentation is None: presentation = annotations[SECTION_PRESENTATION_KEY] = SectionPresentation() return presentation class SectionPresentationTargetAdapter(object): adapts(ISection, IZBlogDefaultLayer) implements(IPresentationTarget) target_interface = ISectionPresentationInfo def __init__(self, context, request): self.context, self.request = context, request class SectionIndexView(BaseSectionIndexView): """Section index page""" implements(ISectionIndexView) def render(self): if self.topics and (self.presentation.presentation_mode == SECTION_DISPLAY_FIRST): topic = self.topics[0] self.request.response.redirect(absoluteURL(topic, self.request)) return u'' return super(SectionIndexView, self).render() class SectionSectionsView(BrowserView): """Section sub-sections view""" __call__ = getViewTemplate() @property def sections(self): result = [] context = None parents = getParents(self.context) + [self.context, ] sections = [s for s in getParents(self.context) if ISection.providedBy(s)] if sections: context = sections[-1] elif ISection.providedBy(self.context): context = self.context if context is not None: for section in (s for s in context.sections if s.visible): selected = section in parents subsections = () if selected and ISection.providedBy(section): subsections = [s for s in section.sections if s.visible] result.append({ 'section': section, 'selected': selected, 'subsections': subsections, 'subselected': set(subsections) & set(parents) }) return result class SectionSitemapAdapter(object): """Section sitemap adapter""" adapts(ISection) implements(IContainerSitemapInfo) def __init__(self, context): self.context = context @property def values(self): return self.context.getVisibleSections() + self.context.getVisibleTopics()
ztfy.blog
/ztfy.blog-0.6.2.tar.gz/ztfy.blog-0.6.2/src/ztfy/blog/defaultskin/section.py
section.py
__docformat__ = "restructuredtext" # import standard packages # import Zope3 interfaces # import local interfaces from ztfy.blog.interfaces import IBaseContent from ztfy.i18n.interfaces import II18nAttributesAware from ztfy.skin.interfaces import IBasePresentationInfo # import Zope3 packages from zope.interface import Interface from zope.schema import List, Choice, Bool, Int, TextLine, Object from zope.schema.vocabulary import SimpleTerm, SimpleVocabulary # import local packages from ztfy.i18n.schema import I18nTextLine from ztfy.blog import _ HEADER_POSITION_LEFT = 0 HEADER_POSITION_TOP = 1 HEADER_POSITIONS = (_("Left column"), _("Page top")) HEADER_POSITIONS_VOCABULARY = SimpleVocabulary([SimpleTerm(v, t, t) for v, t in enumerate(HEADER_POSITIONS)]) class IDefaultPresentationInfo(IBasePresentationInfo): """Base interface for presentation infos""" header_format = Choice(title=_("Header format"), description=_("Text format used for content's header"), required=True, default=u'zope.source.plaintext', vocabulary='SourceTypes') header_position = Choice(title=_("Header position"), description=_("Position of content's header"), required=True, default=HEADER_POSITION_LEFT, vocabulary=HEADER_POSITIONS_VOCABULARY) display_googleplus = Bool(title=_("Display Google +1 button"), description=_("Display Google +1 button next to content's title"), required=True, default=True) display_fb_like = Bool(title=_("Display Facebook 'like' button"), description=_("Display Facebook 'like' button next to content's title"), required=True, default=True) class ISiteManagerPresentationInfo(IDefaultPresentationInfo, II18nAttributesAware): """Site manager presentation info""" main_blogs = List(title=_("Main blogs"), description=_("Summary of selected blogs last entries will be listed in front page"), required=False, unique=True, default=[], value_type=Choice(vocabulary="ZTFY site blogs")) nb_entries = Int(title=_("Entries count"), description=_("Number of entries displayed in front page (if a blog is selected)"), required=True, default=10) owner = TextLine(title=_("Site's owner name"), description=_("Site's owner name can be displayed on pages footers"), required=False) owner_mailto = TextLine(title=_("Owner's mail address"), description=_("""Mail address can be displayed on pages footer in a "mailto" link"""), required=False) signature = I18nTextLine(title=_("Site's signature"), description=_("Signature's complement to put on pages footers (can include HTML code)"), required=False) facebook_app_id = TextLine(title=_("Facebook application ID"), description=_("Application ID declared on Facebook"), required=False) disqus_site_id = TextLine(title=_("Disqus site ID"), description=_("Site's ID on Disqus comment platform can be used to allow topics comments"), required=False) class IBlogPresentationInfo(IDefaultPresentationInfo): """Blog presentation info""" page_entries = Int(title=_("Topics per page"), description=_("Number of topics displayed into one page"), required=True, default=10) facebook_app_id = TextLine(title=_("Facebook application ID"), description=_("Application ID declared on Facebook ; this attribute is not used if blog is contained insite a site manager"), required=False) disqus_site_id = TextLine(title=_("Disqus site ID"), description=_("Site's ID on Disqus comment platform can be used to allow topics comments ; this attribute is not used if blog is contained inside a site manager"), required=False) SECTION_DISPLAY_LIST = 0 SECTION_DISPLAY_FIRST = 1 SECTION_DISPLAY_MODES = (_("Display topics list"), _("Display content of first published topic")) SECTION_DISPLAY_VOCABULARY = SimpleVocabulary([SimpleTerm(i, t, t) for i, t in enumerate(SECTION_DISPLAY_MODES)]) class ISectionPresentationInfo(IDefaultPresentationInfo): """Section presentation info""" presentation_mode = Choice(title=_("Presentation mode"), description=_("Select presentation mode for this section"), required=True, default=SECTION_DISPLAY_LIST, vocabulary=SECTION_DISPLAY_VOCABULARY) ILLUSTRATION_DISPLAY_NONE = 0 ILLUSTRATION_DISPLAY_LEFT = 1 ILLUSTRATION_DISPLAY_RIGHT = 2 ILLUSTRATION_DISPLAY_CENTER = 3 ILLUSTRATION_DISPLAY_MODES = (_("Don't display illustration"), _("Display illustration as thumbnail on left side"), _("Display illustration as thumbnail on right side"), _("Display centered illustration")) ILLUSTRATION_DISPLAY_VOCABULARY = SimpleVocabulary([SimpleTerm(i, t, t) for i, t in enumerate(ILLUSTRATION_DISPLAY_MODES)]) class ITopicPresentationInfo(IDefaultPresentationInfo): """Topic presentation info""" illustration_position = Choice(title=_("Illustration's position"), description=_("Select position of topic's illustration"), required=True, default=ILLUSTRATION_DISPLAY_LEFT, vocabulary=ILLUSTRATION_DISPLAY_VOCABULARY) linked_resources = List(title=_("Downloadable resources"), description=_("Select list of resources displayed as download links"), required=False, default=[], value_type=Choice(vocabulary="ZTFY content resources")) class IContainerSitemapInfo(Interface): """Container sitemap info""" values = List(title=_("Container values"), value_type=Object(schema=IBaseContent), readonly=True)
ztfy.blog
/ztfy.blog-0.6.2.tar.gz/ztfy.blog-0.6.2/src/ztfy/blog/defaultskin/interfaces.py
interfaces.py
__docformat__ = "restructuredtext" # import standard packages from pygments import highlight from pygments.formatters import HtmlFormatter from pygments.lexers import get_lexer_by_name # import Zope3 interfaces from z3c.template.interfaces import IContentTemplate # import local interfaces from ztfy.blog.browser.interfaces.paragraph import IParagraphRenderer from ztfy.blog.defaultskin.layer import IZBlogDefaultLayer from ztfy.blog.paragraphs.interfaces import ITextParagraph, ICodeParagraph, IHTMLParagraph, IIllustration, \ POSITION_LEFT, POSITION_RIGHT from ztfy.file.interfaces import IImageDisplay # import Zope3 packages from z3c.language.switch.interfaces import II18n from zope.component import adapts, queryMultiAdapter from zope.interface import implements from zope.traversing.browser import absoluteURL # import local packages from ztfy.blog.browser.interfaces.skin import ITopicIndexView from ztfy.jqueryui import jquery_fancybox class ParagraphRenderer(object): """Text paragraph renderer""" def __init__(self, context, view, request): self.context = context self.view = view self.request = request def update(self): pass def render(self): template = queryMultiAdapter((self, self.request), IContentTemplate) return template(self) class TextParagraphRenderer(ParagraphRenderer): """Text paragraph renderer""" adapts(ITextParagraph, ITopicIndexView, IZBlogDefaultLayer) implements(IParagraphRenderer) class CodeParagraphRenderer(ParagraphRenderer): """Code paragraph renderer""" adapts(ICodeParagraph, ITopicIndexView, IZBlogDefaultLayer) implements(IParagraphRenderer) class CodeParagraphView(object): def __call__(self): lexer = get_lexer_by_name(self.context.body_lexer) formatter = HtmlFormatter(style=self.context.body_style, full=True, linenos='table') return highlight(self.context.body, lexer, formatter).replace('<h2></h2>', '') class HTMLParagraphRenderer(ParagraphRenderer): """HTML paragraph renderer""" adapts(IHTMLParagraph, ITopicIndexView, IZBlogDefaultLayer) implements(IParagraphRenderer) class IllustrationRenderer(ParagraphRenderer): """Illustration renderer""" adapts(IIllustration, ITopicIndexView, IZBlogDefaultLayer) implements(IParagraphRenderer) def update(self): if self.context.zoomable: jquery_fancybox.need() @property def css_class(self): result = 'illustration' position = self.context.position if position == POSITION_LEFT: result += ' toleft' elif position == POSITION_RIGHT: result += ' toright' return result @property def img_src(self): img = II18n(self.context).queryAttribute('body', request=self.request) if self.context.display_width: display = IImageDisplay(img).getDisplay('w%d' % self.context.display_width) url = absoluteURL(display, request=self.request) else: url = absoluteURL(img, request=self.request) return url @property def zoom_target(self): img = II18n(self.context).queryAttribute('body', request=self.request) if self.context.zoom_width: display = IImageDisplay(img).getDisplay('w%d' % self.context.zoom_width) url = absoluteURL(display, request=self.request) else: url = absoluteURL(img, request=self.request) return url
ztfy.blog
/ztfy.blog-0.6.2.tar.gz/ztfy.blog-0.6.2/src/ztfy/blog/defaultskin/paragraph.py
paragraph.py
__docformat__ = "restructuredtext" # import standard packages from persistent import Persistent # import Zope3 interfaces from zope.annotation.interfaces import IAnnotations from zope.dublincore.interfaces import IZopeDublinCore # import local interfaces from ztfy.base.interfaces import IUniqueID from ztfy.blog.defaultskin.interfaces import ISiteManagerPresentationInfo, IBlogPresentationInfo, \ ITopicPresentationInfo from ztfy.blog.defaultskin.layer import IZBlogDefaultLayer from ztfy.blog.interfaces.blog import IBlog from ztfy.blog.interfaces.category import ICategorizedContent from ztfy.blog.interfaces.link import ILinkContainer from ztfy.blog.interfaces.topic import ITopic from ztfy.blog.interfaces.site import ISiteManager from ztfy.skin.interfaces import IPresentationTarget from ztfy.workflow.interfaces import IWorkflowContent # import Zope3 packages from z3c.template.template import getViewTemplate from zope.component import adapter, adapts, queryMultiAdapter from zope.container.contained import Contained from zope.interface import implementer, implements from zope.publisher.browser import BrowserView from zope.schema.fieldproperty import FieldProperty # import local packages from ztfy.blog.browser.topic import BaseTopicIndexView from ztfy.blog.defaultskin.menu import DefaultSkinDialogMenuItem from ztfy.security.search import getPrincipal from ztfy.utils.traversing import getParent from ztfy.blog import _ TOPIC_PRESENTATION_KEY = 'ztfy.blog.defaultskin.topic.presentation' class TopicPresentationViewMenuItem(DefaultSkinDialogMenuItem): """Site manager presentation menu item""" title = _(" :: Presentation model...") class TopicPresentation(Persistent, Contained): """Site manager presentation infos""" implements(ITopicPresentationInfo) header_format = FieldProperty(ITopicPresentationInfo['header_format']) header_position = FieldProperty(ITopicPresentationInfo['header_position']) display_googleplus = FieldProperty(ITopicPresentationInfo['display_googleplus']) display_fb_like = FieldProperty(ITopicPresentationInfo['display_fb_like']) illustration_position = FieldProperty(ITopicPresentationInfo['illustration_position']) linked_resources = FieldProperty(ITopicPresentationInfo['linked_resources']) @adapter(ITopic) @implementer(ITopicPresentationInfo) def TopicPresentationFactory(context): annotations = IAnnotations(context) presentation = annotations.get(TOPIC_PRESENTATION_KEY) if presentation is None: presentation = annotations[TOPIC_PRESENTATION_KEY] = TopicPresentation() return presentation class TopicPresentationTargetAdapter(object): adapts(ITopic, IZBlogDefaultLayer) implements(IPresentationTarget) target_interface = ITopicPresentationInfo def __init__(self, context, request): self.context, self.request = context, request class TopicIndexList(BrowserView): """Topic list item""" __call__ = getViewTemplate() @property def presentation(self): return ITopicPresentationInfo(self.context) class TopicIndexPreview(TopicIndexList): """Topic index preview""" __call__ = getViewTemplate() @property def author(self): return getPrincipal(IZopeDublinCore(self.context).creators[0]) @property def date(self): return IWorkflowContent(self.context).publication_effective_date class TopicIndexView(BaseTopicIndexView): """Topic index page""" @property def author(self): return getPrincipal(IZopeDublinCore(self.context).creators[0]) @property def date(self): return IWorkflowContent(self.context).publication_effective_date class TopicResourcesView(BrowserView): """Topic resources view""" __call__ = getViewTemplate() @property def resources(self): adapter = queryMultiAdapter((self.context, self.request), IPresentationTarget) if adapter is not None: interface = adapter.target_interface else: interface = ITopicPresentationInfo adapter = queryMultiAdapter((self.context, self.request), interface) if adapter is None: adapter = interface(self.context) return adapter.linked_resources class TopicLinksView(BrowserView): """Topic links view""" __call__ = getViewTemplate() @property def links(self): return ILinkContainer(self.context).getVisibleLinks() class TopicTagsView(BrowserView): """Topic tags view""" __call__ = getViewTemplate() @property def tags(self): return ICategorizedContent(self.context).categories class TopicCommentsView(BrowserView): """Topic comments view""" __call__ = getViewTemplate() @property def oid(self): return IUniqueID(self.context).oid @property def presentation(self): if not self.context.commentable: return None site = getParent(self.context, ISiteManager) if site is not None: return ISiteManagerPresentationInfo(site) blog = getParent(self.context, IBlog) if blog is not None: return IBlogPresentationInfo(blog) return None
ztfy.blog
/ztfy.blog-0.6.2.tar.gz/ztfy.blog-0.6.2/src/ztfy/blog/defaultskin/topic.py
topic.py
__docformat__ = "restructuredtext" # import standard packages from persistent import Persistent # import Zope3 interfaces from zope.annotation.interfaces import IAnnotations # import local interfaces from ztfy.blog.defaultskin.interfaces import ISiteManagerPresentationInfo, IContainerSitemapInfo from ztfy.blog.defaultskin.layer import IZBlogDefaultLayer from ztfy.blog.interfaces.site import ISiteManager from ztfy.skin.interfaces import IPresentationTarget from ztfy.skin.interfaces.metas import IContentMetasHeaders from ztfy.workflow.interfaces import IWorkflowContent # import Zope3 packages from zope.component import adapter, adapts, queryMultiAdapter from zope.container.contained import Contained from zope.interface import implementer, implements from zope.location import locate from zope.schema.fieldproperty import FieldProperty from zope.traversing.browser.absoluteurl import absoluteURL # import local packages from ztfy.blog.defaultskin.menu import DefaultSkinDialogMenuItem from ztfy.blog.browser.site import BaseSiteManagerIndexView from ztfy.i18n.property import I18nTextProperty from ztfy.jqueryui import jquery_multiselect, jquery_jsonrpc from ztfy.skin.metas import LinkMeta from ztfy.skin.page import BaseTemplateBasedPage from ztfy.blog import _ SITE_MANAGER_PRESENTATION_KEY = 'ztfy.blog.defaultskin.presentation' class SiteManagerPresentationViewMenuItem(DefaultSkinDialogMenuItem): """Site manager presentation menu item""" title = _(" :: Presentation model...") def render(self): result = super(SiteManagerPresentationViewMenuItem, self).render() if result: jquery_jsonrpc.need() jquery_multiselect.need() return result class SiteManagerPresentation(Persistent, Contained): """Site manager presentation infos""" implements(ISiteManagerPresentationInfo) header_format = FieldProperty(ISiteManagerPresentationInfo['header_format']) header_position = FieldProperty(ISiteManagerPresentationInfo['header_position']) display_googleplus = FieldProperty(ISiteManagerPresentationInfo['display_googleplus']) display_fb_like = FieldProperty(ISiteManagerPresentationInfo['display_fb_like']) main_blogs = FieldProperty(ISiteManagerPresentationInfo['main_blogs']) nb_entries = FieldProperty(ISiteManagerPresentationInfo['nb_entries']) owner = FieldProperty(ISiteManagerPresentationInfo['owner']) owner_mailto = FieldProperty(ISiteManagerPresentationInfo['owner_mailto']) signature = I18nTextProperty(ISiteManagerPresentationInfo['signature']) facebook_app_id = FieldProperty(ISiteManagerPresentationInfo['facebook_app_id']) disqus_site_id = FieldProperty(ISiteManagerPresentationInfo['disqus_site_id']) @adapter(ISiteManager) @implementer(ISiteManagerPresentationInfo) def SiteManagerPresentationFactory(context): annotations = IAnnotations(context) presentation = annotations.get(SITE_MANAGER_PRESENTATION_KEY) if presentation is None: presentation = annotations[SITE_MANAGER_PRESENTATION_KEY] = SiteManagerPresentation() locate(presentation, context, '++presentation++') return presentation class SiteManagerPresentationTargetAdapter(object): adapts(ISiteManager, IZBlogDefaultLayer) implements(IPresentationTarget) target_interface = ISiteManagerPresentationInfo def __init__(self, context, request): self.context, self.request = context, request class SiteManagerIndexView(BaseSiteManagerIndexView): """Site manager index page""" @property def topics(self): blogs = self.presentation.main_blogs if not blogs: return [] topics = [] [topics.extend(blog.getVisibleTopics()) for blog in blogs if blog.visible] topics.sort(key=lambda x: IWorkflowContent(x).publication_effective_date, reverse=True) return topics[:self.presentation.nb_entries] class SiteManagerRssLinkAdapter(object): adapts(ISiteManager, IZBlogDefaultLayer) implements(IContentMetasHeaders) def __init__(self, context, request): self.context = context self.request = request @property def metas(self): return [ LinkMeta('alternate', 'application/rss+xml', '%s/@@rss.xml' % absoluteURL(self.context, self.request)) ] class SiteManagerRssView(BaseTemplateBasedPage): """Site manager RSS view""" def update(self): adapter = queryMultiAdapter((self.context, self.request, self), IPresentationTarget) if adapter is None: adapter = queryMultiAdapter((self.context, self.request), IPresentationTarget) if adapter is not None: interface = adapter.target_interface self.presentation = interface(self.context) @property def topics(self): blogs = self.presentation.main_blogs if not blogs: return [] topics = [] [topics.extend(blog.getVisibleTopics()) for blog in blogs if blog.visible] topics.sort(key=lambda x: IWorkflowContent(x).publication_effective_date, reverse=True) return topics[:self.presentation.nb_entries] class SiteManagerSitemapAdapter(object): """Site manager sitemap adapter""" adapts(ISiteManager) implements(IContainerSitemapInfo) def __init__(self, context): self.context = context @property def values(self): return [v for v in self.context.values() if getattr(v, 'visible', False)]
ztfy.blog
/ztfy.blog-0.6.2.tar.gz/ztfy.blog-0.6.2/src/ztfy/blog/defaultskin/site.py
site.py
__docformat__ = "restructuredtext" # import standard packages # import Zope3 interfaces from z3c.language.switch.interfaces import II18n from zope.schema.interfaces import IVocabularyFactory # import local interfaces # import Zope3 packages from z3c.template.template import getViewTemplate from zope.component import getUtility from zope.i18n import translate from zope.publisher.browser import BrowserView # import local packages from ztfy.blog import _ class InternalLinkView(BrowserView): """Internal link view""" __call__ = getViewTemplate() @property def title(self): return II18n(self.context).queryAttribute('title', request=self.request) or \ II18n(self.context.target).queryAttribute('title', request=self.request) @property def language(self): lang = self.context.language if not lang: return None vocabulary = getUtility(IVocabularyFactory, 'ZTFY languages') return translate(_("Language: %s") % vocabulary(self.context).getTerm(lang).title, context=self.request) @property def flag(self): lang = self.context.language if not lang: return None return lang.replace('-', '_', 1) class ExternalLinkView(BrowserView): """External link view""" __call__ = getViewTemplate() @property def title(self): return II18n(self.context).queryAttribute('title', request=self.request) or \ II18n(self.context).queryAttribute('url', request=self.request) @property def language(self): lang = self.context.language if not lang: return None vocabulary = getUtility(IVocabularyFactory, 'ZTFY languages') return translate(_("Language: %s") % vocabulary(self.context).getTerm(lang).title, context=self.request) @property def flag(self): lang = self.context.language if not lang: return None return lang.replace('-', '_', 1)
ztfy.blog
/ztfy.blog-0.6.2.tar.gz/ztfy.blog-0.6.2/src/ztfy/blog/defaultskin/link.py
link.py
__docformat__ = "restructuredtext" # import standard packages from persistent import Persistent # import Zope3 interfaces from zope.annotation.interfaces import IAnnotations # import local interfaces from ztfy.blog.defaultskin.interfaces import IBlogPresentationInfo, IContainerSitemapInfo from ztfy.blog.defaultskin.layer import IZBlogDefaultLayer from ztfy.blog.interfaces.blog import IBlog from ztfy.skin.interfaces import IPresentationTarget from ztfy.skin.interfaces.metas import IContentMetasHeaders # import Zope3 packages from zope.component import adapter, adapts, queryMultiAdapter from zope.container.contained import Contained from zope.interface import implementer, implements from zope.schema.fieldproperty import FieldProperty from zope.traversing.browser.absoluteurl import absoluteURL # import local packages from ztfy.blog.browser.blog import BaseBlogIndexView from ztfy.blog.defaultskin.menu import DefaultSkinDialogMenuItem from ztfy.skin.metas import LinkMeta from ztfy.skin.page import BaseTemplateBasedPage from ztfy.blog import _ BLOG_PRESENTATION_KEY = 'ztfy.blog.defaultskin.blog.presentation' class BlogPresentationViewMenuItem(DefaultSkinDialogMenuItem): """Blog presentation menu item""" title = _(" :: Presentation model...") class BlogPresentation(Persistent, Contained): """Blog presentation infos""" implements(IBlogPresentationInfo) header_format = FieldProperty(IBlogPresentationInfo['header_format']) header_position = FieldProperty(IBlogPresentationInfo['header_position']) display_googleplus = FieldProperty(IBlogPresentationInfo['display_googleplus']) display_fb_like = FieldProperty(IBlogPresentationInfo['display_fb_like']) page_entries = FieldProperty(IBlogPresentationInfo['page_entries']) facebook_app_id = FieldProperty(IBlogPresentationInfo['facebook_app_id']) disqus_site_id = FieldProperty(IBlogPresentationInfo['disqus_site_id']) @adapter(IBlog) @implementer(IBlogPresentationInfo) def BlogPresentationFactory(context): annotations = IAnnotations(context) presentation = annotations.get(BLOG_PRESENTATION_KEY) if presentation is None: presentation = annotations[BLOG_PRESENTATION_KEY] = BlogPresentation() return presentation class BlogPresentationTargetAdapter(object): adapts(IBlog, IZBlogDefaultLayer) implements(IPresentationTarget) target_interface = IBlogPresentationInfo def __init__(self, context, request): self.context, self.request = context, request class BlogIndexView(BaseBlogIndexView): """Blog index page""" def getTopics(self): page = int(self.request.form.get('page', 0)) page_length = self.presentation.page_entries first = page_length * page last = first + page_length - 1 pages = len(self.topics) / page_length if len(self.topics) % page_length: pages += 1 return { 'topics': self.topics[first:last + 1], 'pages': pages, 'first': first, 'last': last, 'has_prev': page > 0, 'has_next': last < len(self.topics) - 1 } class BlogRssLinkAdapter(object): adapts(IBlog, IZBlogDefaultLayer) implements(IContentMetasHeaders) def __init__(self, context, request): self.context = context self.request = request @property def metas(self): return [ LinkMeta('alternate', 'application/rss+xml', '%s/@@rss.xml' % absoluteURL(self.context, self.request)) ] class BlogRssView(BaseTemplateBasedPage): """Site manager RSS view""" def update(self): adapter = queryMultiAdapter((self.context, self.request, self), IPresentationTarget) if adapter is None: adapter = queryMultiAdapter((self.context, self.request), IPresentationTarget) if adapter is not None: interface = adapter.target_interface self.presentation = interface(self.context) @property def topics(self): topics = self.context.getVisibleTopics() return topics[:20] class BlogSitemapAdapter(object): """Blog sitemap adapter""" adapts(IBlog) implements(IContainerSitemapInfo) def __init__(self, context): self.context = context @property def values(self): return self.context.getVisibleTopics()
ztfy.blog
/ztfy.blog-0.6.2.tar.gz/ztfy.blog-0.6.2/src/ztfy/blog/defaultskin/blog.py
blog.py
__docformat__ = "restructuredtext" # import standard packages # import Zope3 interfaces from z3c.language.switch.interfaces import II18n from zope.dublincore.interfaces import IZopeDublinCore # import local interfaces from hurry.workflow.interfaces import IWorkflowState from ztfy.blog.interfaces import STATUS_DELETED from ztfy.skin.interfaces import IBreadcrumbInfo, IDefaultView # import Zope3 packages from zope.component import queryMultiAdapter from zope.traversing.browser import absoluteURL from zope.traversing.api import getParents # import local packages from ztfy.skin.viewlet import ViewletBase class BreadcrumbsViewlet(ViewletBase): viewname = '' @property def crumbs(self): result = [] state = IWorkflowState(self.context, None) if (state is None) or (state.getState() != STATUS_DELETED): for parent in reversed([self.context, ] + getParents(self.context)): value = None info = queryMultiAdapter((parent, self.request, self.__parent__), IBreadcrumbInfo) if info is not None: if info.visible: value = { 'title': info.title, 'path': info.path } else: visible = getattr(parent, 'visible', True) if visible: i18n = II18n(parent, None) if i18n is not None: name = i18n.queryAttribute('shortname', request=self.request) or i18n.queryAttribute('title', request=self.request) else: name = IZopeDublinCore(parent).title if name: adapter = queryMultiAdapter((parent, self.request, self.__parent__), IDefaultView) if (adapter is not None) and adapter.viewname: self.viewname = '/' + adapter.viewname value = { 'title': name, 'path': '%s%s' % (absoluteURL(parent, request=self.request), self.viewname) } if value: if result and (value['title'] == result[-1]['title']): result[-1] = value else: result.append(value) return result
ztfy.blog
/ztfy.blog-0.6.2.tar.gz/ztfy.blog-0.6.2/src/ztfy/blog/defaultskin/viewlets/header/crumbs.py
crumbs.py
__docformat__ = "restructuredtext" # import standard packages from pygments import lexers, styles # import Zope3 interfaces # import local interfaces from ztfy.blog.interfaces.paragraph import IParagraphInfo, IParagraphWriter, IParagraph # import Zope3 packages from zope.schema import Choice, Bool, Int, Text from zope.schema.vocabulary import SimpleTerm, SimpleVocabulary # import local packages from ztfy.i18n.schema import I18nText, I18nHTML, I18nImage from ztfy.blog import _ # Text paragraphs class ITextParagraphInfo(IParagraphInfo): """Text paragraph base interface""" body = I18nText(title=_("Body"), description=_("Main paragraph's content"), required=False) body_format = Choice(title=_("Body text format"), description=_("Text format of paragraph's body"), required=True, default=u'zope.source.plaintext', vocabulary='SourceTypes') class ITextParagraphWriter(IParagraphWriter): """Text paragraph writer interface""" class ITextParagraph(IParagraph, ITextParagraphInfo, ITextParagraphWriter): """Text paragraph full interface""" # Code paragraphs _lexers_by_name = {} _lexers_by_alias = {} for name, aliases, _i1, _i2 in lexers.get_all_lexers(): alias = aliases[0] if (not _lexers_by_name.get(name)) and (not _lexers_by_alias.get(alias)): _lexers_by_name[name] = alias _lexers_by_alias[alias] = name PYGMENTS_LEXERS_VOCABULARY = SimpleVocabulary([SimpleTerm(i, t, t) for t, i in sorted(_lexers_by_name.items())]) PYGMENTS_STYLES_VOCABULARY = SimpleVocabulary([SimpleTerm(i, i, i) for i in sorted(styles.get_all_styles())]) class ICodeParagraphInfo(IParagraphInfo): """Code paragraph base interface""" body = Text(title=_("Body"), description=_("Main paragraph's content"), required=False) body_lexer = Choice(title=_("Body source language"), description=_("Original language of the body code"), required=True, default=u'python', vocabulary=PYGMENTS_LEXERS_VOCABULARY) body_style = Choice(title=_("Body style"), description=_("Color style of code body"), required=True, default=u'default', vocabulary=PYGMENTS_STYLES_VOCABULARY) class ICodeParagraphWriter(IParagraphWriter): """Code paragraph writer interface""" class ICodeParagraph(IParagraph, ICodeParagraphInfo, ICodeParagraphWriter): """Code paragraph full interface""" # HTML paragraphs class IHTMLParagraphInfo(IParagraphInfo): """HTML paragraph base interface""" body = I18nHTML(title=_("Body"), description=_("Main paragraph's content"), required=False) class IHTMLParagraphWriter(IParagraphWriter): """HTML paragraph writer interface""" class IHTMLParagraph(IParagraph, IHTMLParagraphInfo, IHTMLParagraphWriter): """HTML paragraph full interface""" # Illustrations POSITION_LEFT = 0 POSITION_RIGHT = 1 POSITION_CENTER = 2 POSITION_IDS = [ 'left', 'right', 'center' ] POSITION_LABELS = (_("Floating left to next paragraph"), _("Floating right to next paragraph"), _("Centered before next paragraph")) POSITION_VOCABULARY = SimpleVocabulary([SimpleTerm(i, i, t) for i, t in enumerate(POSITION_LABELS)]) class IIllustrationInfo(IParagraphInfo): """Illustration base interface""" body = I18nImage(title=_("Illustration content"), description=_("Image file containing illustration"), required=True) position = Choice(title=_("Illustration's position"), description=_("Position of the displayed illustration"), required=True, vocabulary=POSITION_VOCABULARY) display_width = Int(title=_("Display width"), description=_("Width of the displayed illustration"), required=False) break_after = Bool(title=_("Linebreak after illustration ?"), description=_("If 'Yes', a linebreak will be inserted after illustration"), required=True, default=False) zoomable = Bool(title=_("Zoomable ?"), description=_("If a display width is applied, can the illustration be zoomed ?"), required=True, default=False) zoom_width = Int(title=_("Zoom width"), description=_("Width of the illustration displayed in zoom mode"), required=False) class IIllustrationWriter(IParagraphWriter): """Illustration writer interface""" class IIllustration(IParagraph, IIllustrationInfo, IIllustrationWriter): """Illustration full interface"""
ztfy.blog
/ztfy.blog-0.6.2.tar.gz/ztfy.blog-0.6.2/src/ztfy/blog/paragraphs/interfaces.py
interfaces.py
================= ztfy.blog package ================= .. contents:: What is ztfy.blog ? =================== ztfy.blog is a set of modules which allows easy management of a simple web site based on Zope3 application server. It's main goal is to be simple to use and manage. So it's far from being a "features full" environment, but available features currently include: - a simple management interface - sites, organized with sections and internal blogs - topics, made of custom elements (text or HTML paragraphs, resources and links) - a default front-office skin. All these elements can be extended by registering a simple set of interfaces and adapters, to create a complete web site matching your own needs. A few list of extensions is available in several packages, like ztfy.gallery which provides basic management of images galleries in a custom skin, or ztfy.hplskin which provides another skin. How to use ztfy.blog ? ====================== ztfy.blog usage is described via doctests in ztfy/blog/doctests/README.txt
ztfy.blog
/ztfy.blog-0.6.2.tar.gz/ztfy.blog-0.6.2/docs/README.txt
README.txt
!function(e){"use strict";e(function(){e.support.transition=function(){var e=function(){var e=document.createElement("bootstrap"),t={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"},n;for(n in t)if(e.style[n]!==undefined)return t[n]}();return e&&{end:e}}()})}(window.jQuery),!function(e){"use strict";var t='[data-dismiss="alert"]',n=function(n){e(n).on("click",t,this.close)};n.prototype.close=function(t){function s(){i.trigger("closed").remove()}var n=e(this),r=n.attr("data-target"),i;r||(r=n.attr("href"),r=r&&r.replace(/.*(?=#[^\s]*$)/,"")),i=e(r),t&&t.preventDefault(),i.length||(i=n.hasClass("alert")?n:n.parent()),i.trigger(t=e.Event("close"));if(t.isDefaultPrevented())return;i.removeClass("in"),e.support.transition&&i.hasClass("fade")?i.on(e.support.transition.end,s):s()};var r=e.fn.alert;e.fn.alert=function(t){return this.each(function(){var r=e(this),i=r.data("alert");i||r.data("alert",i=new n(this)),typeof t=="string"&&i[t].call(r)})},e.fn.alert.Constructor=n,e.fn.alert.noConflict=function(){return e.fn.alert=r,this},e(document).on("click.alert.data-api",t,n.prototype.close)}(window.jQuery),!function(e){"use strict";var t=function(t,n){this.$element=e(t),this.options=e.extend({},e.fn.button.defaults,n)};t.prototype.setState=function(e){var t="disabled",n=this.$element,r=n.data(),i=n.is("input")?"val":"html";e+="Text",r.resetText||n.data("resetText",n[i]()),n[i](r[e]||this.options[e]),setTimeout(function(){e=="loadingText"?n.addClass(t).attr(t,t):n.removeClass(t).removeAttr(t)},0)},t.prototype.toggle=function(){var e=this.$element.closest('[data-toggle="buttons-radio"]');e&&e.find(".active").removeClass("active"),this.$element.toggleClass("active")};var n=e.fn.button;e.fn.button=function(n){return this.each(function(){var r=e(this),i=r.data("button"),s=typeof n=="object"&&n;i||r.data("button",i=new t(this,s)),n=="toggle"?i.toggle():n&&i.setState(n)})},e.fn.button.defaults={loadingText:"loading..."},e.fn.button.Constructor=t,e.fn.button.noConflict=function(){return e.fn.button=n,this},e(document).on("click.button.data-api","[data-toggle^=button]",function(t){var n=e(t.target);n.hasClass("btn")||(n=n.closest(".btn")),n.button("toggle")})}(window.jQuery),!function(e){"use strict";var t=function(t,n){this.$element=e(t),this.$indicators=this.$element.find(".carousel-indicators"),this.options=n,this.options.pause=="hover"&&this.$element.on("mouseenter",e.proxy(this.pause,this)).on("mouseleave",e.proxy(this.cycle,this))};t.prototype={cycle:function(t){return t||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(e.proxy(this.next,this),this.options.interval)),this},getActiveIndex:function(){return this.$active=this.$element.find(".item.active"),this.$items=this.$active.parent().children(),this.$items.index(this.$active)},to:function(t){var n=this.getActiveIndex(),r=this;if(t>this.$items.length-1||t<0)return;return this.sliding?this.$element.one("slid",function(){r.to(t)}):n==t?this.pause().cycle():this.slide(t>n?"next":"prev",e(this.$items[t]))},pause:function(t){return t||(this.paused=!0),this.$element.find(".next, .prev").length&&e.support.transition.end&&(this.$element.trigger(e.support.transition.end),this.cycle(!0)),clearInterval(this.interval),this.interval=null,this},next:function(){if(this.sliding)return;return this.slide("next")},prev:function(){if(this.sliding)return;return this.slide("prev")},slide:function(t,n){var r=this.$element.find(".item.active"),i=n||r[t](),s=this.interval,o=t=="next"?"left":"right",u=t=="next"?"first":"last",a=this,f;this.sliding=!0,s&&this.pause(),i=i.length?i:this.$element.find(".item")[u](),f=e.Event("slide",{relatedTarget:i[0],direction:o});if(i.hasClass("active"))return;this.$indicators.length&&(this.$indicators.find(".active").removeClass("active"),this.$element.one("slid",function(){var t=e(a.$indicators.children()[a.getActiveIndex()]);t&&t.addClass("active")}));if(e.support.transition&&this.$element.hasClass("slide")){this.$element.trigger(f);if(f.isDefaultPrevented())return;i.addClass(t),i[0].offsetWidth,r.addClass(o),i.addClass(o),this.$element.one(e.support.transition.end,function(){i.removeClass([t,o].join(" ")).addClass("active"),r.removeClass(["active",o].join(" ")),a.sliding=!1,setTimeout(function(){a.$element.trigger("slid")},0)})}else{this.$element.trigger(f);if(f.isDefaultPrevented())return;r.removeClass("active"),i.addClass("active"),this.sliding=!1,this.$element.trigger("slid")}return s&&this.cycle(),this}};var n=e.fn.carousel;e.fn.carousel=function(n){return this.each(function(){var r=e(this),i=r.data("carousel"),s=e.extend({},e.fn.carousel.defaults,typeof n=="object"&&n),o=typeof n=="string"?n:s.slide;i||r.data("carousel",i=new t(this,s)),typeof n=="number"?i.to(n):o?i[o]():s.interval&&i.pause().cycle()})},e.fn.carousel.defaults={interval:5e3,pause:"hover"},e.fn.carousel.Constructor=t,e.fn.carousel.noConflict=function(){return e.fn.carousel=n,this},e(document).on("click.carousel.data-api","[data-slide], [data-slide-to]",function(t){var n=e(this),r,i=e(n.attr("data-target")||(r=n.attr("href"))&&r.replace(/.*(?=#[^\s]+$)/,"")),s=e.extend({},i.data(),n.data()),o;i.carousel(s),(o=n.attr("data-slide-to"))&&i.data("carousel").pause().to(o).cycle(),t.preventDefault()})}(window.jQuery),!function(e){"use strict";var t=function(t,n){this.$element=e(t),this.options=e.extend({},e.fn.collapse.defaults,n),this.options.parent&&(this.$parent=e(this.options.parent)),this.options.toggle&&this.toggle()};t.prototype={constructor:t,dimension:function(){var e=this.$element.hasClass("width");return e?"width":"height"},show:function(){var t,n,r,i;if(this.transitioning||this.$element.hasClass("in"))return;t=this.dimension(),n=e.camelCase(["scroll",t].join("-")),r=this.$parent&&this.$parent.find("> .accordion-group > .in");if(r&&r.length){i=r.data("collapse");if(i&&i.transitioning)return;r.collapse("hide"),i||r.data("collapse",null)}this.$element[t](0),this.transition("addClass",e.Event("show"),"shown"),e.support.transition&&this.$element[t](this.$element[0][n])},hide:function(){var t;if(this.transitioning||!this.$element.hasClass("in"))return;t=this.dimension(),this.reset(this.$element[t]()),this.transition("removeClass",e.Event("hide"),"hidden"),this.$element[t](0)},reset:function(e){var t=this.dimension();return this.$element.removeClass("collapse")[t](e||"auto")[0].offsetWidth,this.$element[e!==null?"addClass":"removeClass"]("collapse"),this},transition:function(t,n,r){var i=this,s=function(){n.type=="show"&&i.reset(),i.transitioning=0,i.$element.trigger(r)};this.$element.trigger(n);if(n.isDefaultPrevented())return;this.transitioning=1,this.$element[t]("in"),e.support.transition&&this.$element.hasClass("collapse")?this.$element.one(e.support.transition.end,s):s()},toggle:function(){this[this.$element.hasClass("in")?"hide":"show"]()}};var n=e.fn.collapse;e.fn.collapse=function(n){return this.each(function(){var r=e(this),i=r.data("collapse"),s=e.extend({},e.fn.collapse.defaults,r.data(),typeof n=="object"&&n);i||r.data("collapse",i=new t(this,s)),typeof n=="string"&&i[n]()})},e.fn.collapse.defaults={toggle:!0},e.fn.collapse.Constructor=t,e.fn.collapse.noConflict=function(){return e.fn.collapse=n,this},e(document).on("click.collapse.data-api","[data-toggle=collapse]",function(t){var n=e(this),r,i=n.attr("data-target")||t.preventDefault()||(r=n.attr("href"))&&r.replace(/.*(?=#[^\s]+$)/,""),s=e(i).data("collapse")?"toggle":n.data();n[e(i).hasClass("in")?"addClass":"removeClass"]("collapsed"),e(i).collapse(s)})}(window.jQuery),!function(e){"use strict";function r(){e(t).each(function(){i(e(this)).removeClass("open")})}function i(t){var n=t.attr("data-target"),r;n||(n=t.attr("href"),n=n&&/#/.test(n)&&n.replace(/.*(?=#[^\s]*$)/,"")),r=n&&e(n);if(!r||!r.length)r=t.parent();return r}var t="[data-toggle=dropdown]",n=function(t){var n=e(t).on("click.dropdown.data-api",this.toggle);e("html").on("click.dropdown.data-api",function(){n.parent().removeClass("open")})};n.prototype={constructor:n,toggle:function(t){var n=e(this),s,o;if(n.is(".disabled, :disabled"))return;return s=i(n),o=s.hasClass("open"),r(),o||s.toggleClass("open"),n.focus(),!1},keydown:function(n){var r,s,o,u,a,f;if(!/(38|40|27)/.test(n.keyCode))return;r=e(this),n.preventDefault(),n.stopPropagation();if(r.is(".disabled, :disabled"))return;u=i(r),a=u.hasClass("open");if(!a||a&&n.keyCode==27)return n.which==27&&u.find(t).focus(),r.click();s=e("[role=menu] li:not(.divider):visible a",u);if(!s.length)return;f=s.index(s.filter(":focus")),n.keyCode==38&&f>0&&f--,n.keyCode==40&&f<s.length-1&&f++,~f||(f=0),s.eq(f).focus()}};var s=e.fn.dropdown;e.fn.dropdown=function(t){return this.each(function(){var r=e(this),i=r.data("dropdown");i||r.data("dropdown",i=new n(this)),typeof t=="string"&&i[t].call(r)})},e.fn.dropdown.Constructor=n,e.fn.dropdown.noConflict=function(){return e.fn.dropdown=s,this},e(document).on("click.dropdown.data-api",r).on("click.dropdown.data-api",".dropdown form",function(e){e.stopPropagation()}).on("click.dropdown-menu",function(e){e.stopPropagation()}).on("click.dropdown.data-api",t,n.prototype.toggle).on("keydown.dropdown.data-api",t+", [role=menu]",n.prototype.keydown)}(window.jQuery),!function(e){"use strict";var t=function(t,n){this.options=n,this.$element=e(t).delegate('[data-dismiss="modal"]',"click.dismiss.modal",e.proxy(this.hide,this)),this.options.remote&&this.$element.find(".modal-body").load(this.options.remote)};t.prototype={constructor:t,toggle:function(){return this[this.isShown?"hide":"show"]()},show:function(){var t=this,n=e.Event("show");this.$element.trigger(n);if(this.isShown||n.isDefaultPrevented())return;this.isShown=!0,this.escape(),this.backdrop(function(){var n=e.support.transition&&t.$element.hasClass("fade");t.$element.parent().length||t.$element.appendTo(document.body),t.$element.show(),n&&t.$element[0].offsetWidth,t.$element.addClass("in").attr("aria-hidden",!1),t.enforceFocus(),n?t.$element.one(e.support.transition.end,function(){t.$element.focus().trigger("shown")}):t.$element.focus().trigger("shown")})},hide:function(t){t&&t.preventDefault();var n=this;t=e.Event("hide"),this.$element.trigger(t);if(!this.isShown||t.isDefaultPrevented())return;this.isShown=!1,this.escape(),e(document).off("focusin.modal"),this.$element.removeClass("in").attr("aria-hidden",!0),e.support.transition&&this.$element.hasClass("fade")?this.hideWithTransition():this.hideModal()},enforceFocus:function(){var t=this;e(document).on("focusin.modal",function(e){t.$element[0]!==e.target&&!t.$element.has(e.target).length&&t.$element.focus()})},escape:function(){var e=this;this.isShown&&this.options.keyboard?this.$element.on("keyup.dismiss.modal",function(t){t.which==27&&e.hide()}):this.isShown||this.$element.off("keyup.dismiss.modal")},hideWithTransition:function(){var t=this,n=setTimeout(function(){t.$element.off(e.support.transition.end),t.hideModal()},500);this.$element.one(e.support.transition.end,function(){clearTimeout(n),t.hideModal()})},hideModal:function(){var e=this;this.$element.hide(),this.backdrop(function(){e.removeBackdrop(),e.$element.trigger("hidden")})},removeBackdrop:function(){this.$backdrop&&this.$backdrop.remove(),this.$backdrop=null},backdrop:function(t){var n=this,r=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var i=e.support.transition&&r;this.$backdrop=e('<div class="modal-backdrop '+r+'" />').appendTo(document.body),this.$backdrop.click(this.options.backdrop=="static"?e.proxy(this.$element[0].focus,this.$element[0]):e.proxy(this.hide,this)),i&&this.$backdrop[0].offsetWidth,this.$backdrop.addClass("in");if(!t)return;i?this.$backdrop.one(e.support.transition.end,t):t()}else!this.isShown&&this.$backdrop?(this.$backdrop.removeClass("in"),e.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one(e.support.transition.end,t):t()):t&&t()}};var n=e.fn.modal;e.fn.modal=function(n){return this.each(function(){var r=e(this),i=r.data("modal"),s=e.extend({},e.fn.modal.defaults,r.data(),typeof n=="object"&&n);i||r.data("modal",i=new t(this,s)),typeof n=="string"?i[n]():s.show&&i.show()})},e.fn.modal.defaults={backdrop:!0,keyboard:!0,show:!0},e.fn.modal.Constructor=t,e.fn.modal.noConflict=function(){return e.fn.modal=n,this},e(document).on("click.modal.data-api",'[data-toggle="modal"]',function(t){var n=e(this),r=n.attr("href"),i=e(n.attr("data-target")||r&&r.replace(/.*(?=#[^\s]+$)/,"")),s=i.data("modal")?"toggle":e.extend({remote:!/#/.test(r)&&r},i.data(),n.data());t.preventDefault(),i.modal(s).one("hide",function(){n.focus()})})}(window.jQuery),!function(e){"use strict";var t=function(e,t){this.init("tooltip",e,t)};t.prototype={constructor:t,init:function(t,n,r){var i,s,o,u,a;this.type=t,this.$element=e(n),this.options=this.getOptions(r),this.enabled=!0,o=this.options.trigger.split(" ");for(a=o.length;a--;)u=o[a],u=="click"?this.$element.on("click."+this.type,this.options.selector,e.proxy(this.toggle,this)):u!="manual"&&(i=u=="hover"?"mouseenter":"focus",s=u=="hover"?"mouseleave":"blur",this.$element.on(i+"."+this.type,this.options.selector,e.proxy(this.enter,this)),this.$element.on(s+"."+this.type,this.options.selector,e.proxy(this.leave,this)));this.options.selector?this._options=e.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},getOptions:function(t){return t=e.extend({},e.fn[this.type].defaults,this.$element.data(),t),t.delay&&typeof t.delay=="number"&&(t.delay={show:t.delay,hide:t.delay}),t},enter:function(t){var n=e.fn[this.type].defaults,r={},i;this._options&&e.each(this._options,function(e,t){n[e]!=t&&(r[e]=t)},this),i=e(t.currentTarget)[this.type](r).data(this.type);if(!i.options.delay||!i.options.delay.show)return i.show();clearTimeout(this.timeout),i.hoverState="in",this.timeout=setTimeout(function(){i.hoverState=="in"&&i.show()},i.options.delay.show)},leave:function(t){var n=e(t.currentTarget)[this.type](this._options).data(this.type);this.timeout&&clearTimeout(this.timeout);if(!n.options.delay||!n.options.delay.hide)return n.hide();n.hoverState="out",this.timeout=setTimeout(function(){n.hoverState=="out"&&n.hide()},n.options.delay.hide)},show:function(){var t,n,r,i,s,o,u=e.Event("show");if(this.hasContent()&&this.enabled){this.$element.trigger(u);if(u.isDefaultPrevented())return;t=this.tip(),this.setContent(),this.options.animation&&t.addClass("fade"),s=typeof this.options.placement=="function"?this.options.placement.call(this,t[0],this.$element[0]):this.options.placement,t.detach().css({top:0,left:0,display:"block"}),this.options.container?t.appendTo(this.options.container):t.insertAfter(this.$element),n=this.getPosition(),r=t[0].offsetWidth,i=t[0].offsetHeight;switch(s){case"bottom":o={top:n.top+n.height,left:n.left+n.width/2-r/2};break;case"top":o={top:n.top-i,left:n.left+n.width/2-r/2};break;case"left":o={top:n.top+n.height/2-i/2,left:n.left-r};break;case"right":o={top:n.top+n.height/2-i/2,left:n.left+n.width}}this.applyPlacement(o,s),this.$element.trigger("shown")}},applyPlacement:function(e,t){var n=this.tip(),r=n[0].offsetWidth,i=n[0].offsetHeight,s,o,u,a;n.offset(e).addClass(t).addClass("in"),s=n[0].offsetWidth,o=n[0].offsetHeight,t=="top"&&o!=i&&(e.top=e.top+i-o,a=!0),t=="bottom"||t=="top"?(u=0,e.left<0&&(u=e.left*-2,e.left=0,n.offset(e),s=n[0].offsetWidth,o=n[0].offsetHeight),this.replaceArrow(u-r+s,s,"left")):this.replaceArrow(o-i,o,"top"),a&&n.offset(e)},replaceArrow:function(e,t,n){this.arrow().css(n,e?50*(1-e/t)+"%":"")},setContent:function(){var e=this.tip(),t=this.getTitle();e.find(".tooltip-inner")[this.options.html?"html":"text"](t),e.removeClass("fade in top bottom left right")},hide:function(){function i(){var t=setTimeout(function(){n.off(e.support.transition.end).detach()},500);n.one(e.support.transition.end,function(){clearTimeout(t),n.detach()})}var t=this,n=this.tip(),r=e.Event("hide");this.$element.trigger(r);if(r.isDefaultPrevented())return;return n.removeClass("in"),e.support.transition&&this.$tip.hasClass("fade")?i():n.detach(),this.$element.trigger("hidden"),this},fixTitle:function(){var e=this.$element;(e.attr("title")||typeof e.attr("data-original-title")!="string")&&e.attr("data-original-title",e.attr("title")||"").attr("title","")},hasContent:function(){return this.getTitle()},getPosition:function(){var t=this.$element[0];return e.extend({},typeof t.getBoundingClientRect=="function"?t.getBoundingClientRect():{width:t.offsetWidth,height:t.offsetHeight},this.$element.offset())},getTitle:function(){var e,t=this.$element,n=this.options;return e=t.attr("data-original-title")||(typeof n.title=="function"?n.title.call(t[0]):n.title),e},tip:function(){return this.$tip=this.$tip||e(this.options.template)},arrow:function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},validate:function(){this.$element[0].parentNode||(this.hide(),this.$element=null,this.options=null)},enable:function(){this.enabled=!0},disable:function(){this.enabled=!1},toggleEnabled:function(){this.enabled=!this.enabled},toggle:function(t){var n=t?e(t.currentTarget)[this.type](this._options).data(this.type):this;n.tip().hasClass("in")?n.hide():n.show()},destroy:function(){this.hide().$element.off("."+this.type).removeData(this.type)}};var n=e.fn.tooltip;e.fn.tooltip=function(n){return this.each(function(){var r=e(this),i=r.data("tooltip"),s=typeof n=="object"&&n;i||r.data("tooltip",i=new t(this,s)),typeof n=="string"&&i[n]()})},e.fn.tooltip.Constructor=t,e.fn.tooltip.defaults={animation:!0,placement:"top",selector:!1,template:'<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover focus",title:"",delay:0,html:!1,container:!1},e.fn.tooltip.noConflict=function(){return e.fn.tooltip=n,this}}(window.jQuery),!function(e){"use strict";var t=function(e,t){this.init("popover",e,t)};t.prototype=e.extend({},e.fn.tooltip.Constructor.prototype,{constructor:t,setContent:function(){var e=this.tip(),t=this.getTitle(),n=this.getContent();e.find(".popover-title")[this.options.html?"html":"text"](t),e.find(".popover-content")[this.options.html?"html":"text"](n),e.removeClass("fade top bottom left right in")},hasContent:function(){return this.getTitle()||this.getContent()},getContent:function(){var e,t=this.$element,n=this.options;return e=(typeof n.content=="function"?n.content.call(t[0]):n.content)||t.attr("data-content"),e},tip:function(){return this.$tip||(this.$tip=e(this.options.template)),this.$tip},destroy:function(){this.hide().$element.off("."+this.type).removeData(this.type)}});var n=e.fn.popover;e.fn.popover=function(n){return this.each(function(){var r=e(this),i=r.data("popover"),s=typeof n=="object"&&n;i||r.data("popover",i=new t(this,s)),typeof n=="string"&&i[n]()})},e.fn.popover.Constructor=t,e.fn.popover.defaults=e.extend({},e.fn.tooltip.defaults,{placement:"right",trigger:"click",content:"",template:'<div class="popover"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'}),e.fn.popover.noConflict=function(){return e.fn.popover=n,this}}(window.jQuery),!function(e){"use strict";function t(t,n){var r=e.proxy(this.process,this),i=e(t).is("body")?e(window):e(t),s;this.options=e.extend({},e.fn.scrollspy.defaults,n),this.$scrollElement=i.on("scroll.scroll-spy.data-api",r),this.selector=(this.options.target||(s=e(t).attr("href"))&&s.replace(/.*(?=#[^\s]+$)/,"")||"")+" .nav li > a",this.$body=e("body"),this.refresh(),this.process()}t.prototype={constructor:t,refresh:function(){var t=this,n;this.offsets=e([]),this.targets=e([]),n=this.$body.find(this.selector).map(function(){var n=e(this),r=n.data("target")||n.attr("href"),i=/^#\w/.test(r)&&e(r);return i&&i.length&&[[i.position().top+(!e.isWindow(t.$scrollElement.get(0))&&t.$scrollElement.scrollTop()),r]]||null}).sort(function(e,t){return e[0]-t[0]}).each(function(){t.offsets.push(this[0]),t.targets.push(this[1])})},process:function(){var e=this.$scrollElement.scrollTop()+this.options.offset,t=this.$scrollElement[0].scrollHeight||this.$body[0].scrollHeight,n=t-this.$scrollElement.height(),r=this.offsets,i=this.targets,s=this.activeTarget,o;if(e>=n)return s!=(o=i.last()[0])&&this.activate(o);for(o=r.length;o--;)s!=i[o]&&e>=r[o]&&(!r[o+1]||e<=r[o+1])&&this.activate(i[o])},activate:function(t){var n,r;this.activeTarget=t,e(this.selector).parent(".active").removeClass("active"),r=this.selector+'[data-target="'+t+'"],'+this.selector+'[href="'+t+'"]',n=e(r).parent("li").addClass("active"),n.parent(".dropdown-menu").length&&(n=n.closest("li.dropdown").addClass("active")),n.trigger("activate")}};var n=e.fn.scrollspy;e.fn.scrollspy=function(n){return this.each(function(){var r=e(this),i=r.data("scrollspy"),s=typeof n=="object"&&n;i||r.data("scrollspy",i=new t(this,s)),typeof n=="string"&&i[n]()})},e.fn.scrollspy.Constructor=t,e.fn.scrollspy.defaults={offset:10},e.fn.scrollspy.noConflict=function(){return e.fn.scrollspy=n,this},e(window).on("load",function(){e('[data-spy="scroll"]').each(function(){var t=e(this);t.scrollspy(t.data())})})}(window.jQuery),!function(e){"use strict";var t=function(t){this.element=e(t)};t.prototype={constructor:t,show:function(){var t=this.element,n=t.closest("ul:not(.dropdown-menu)"),r=t.attr("data-target"),i,s,o;r||(r=t.attr("href"),r=r&&r.replace(/.*(?=#[^\s]*$)/,""));if(t.parent("li").hasClass("active"))return;i=n.find(".active:last a")[0],o=e.Event("show",{relatedTarget:i}),t.trigger(o);if(o.isDefaultPrevented())return;s=e(r),this.activate(t.parent("li"),n),this.activate(s,s.parent(),function(){t.trigger({type:"shown",relatedTarget:i})})},activate:function(t,n,r){function o(){i.removeClass("active").find("> .dropdown-menu > .active").removeClass("active"),t.addClass("active"),s?(t[0].offsetWidth,t.addClass("in")):t.removeClass("fade"),t.parent(".dropdown-menu")&&t.closest("li.dropdown").addClass("active"),r&&r()}var i=n.find("> .active"),s=r&&e.support.transition&&i.hasClass("fade");s?i.one(e.support.transition.end,o):o(),i.removeClass("in")}};var n=e.fn.tab;e.fn.tab=function(n){return this.each(function(){var r=e(this),i=r.data("tab");i||r.data("tab",i=new t(this)),typeof n=="string"&&i[n]()})},e.fn.tab.Constructor=t,e.fn.tab.noConflict=function(){return e.fn.tab=n,this},e(document).on("click.tab.data-api",'[data-toggle="tab"], [data-toggle="pill"]',function(t){t.preventDefault(),e(this).tab("show")})}(window.jQuery),!function(e){"use strict";var t=function(t,n){this.$element=e(t),this.options=e.extend({},e.fn.typeahead.defaults,n),this.matcher=this.options.matcher||this.matcher,this.sorter=this.options.sorter||this.sorter,this.highlighter=this.options.highlighter||this.highlighter,this.updater=this.options.updater||this.updater,this.source=this.options.source,this.$menu=e(this.options.menu),this.shown=!1,this.listen()};t.prototype={constructor:t,select:function(){var e=this.$menu.find(".active").attr("data-value");return this.$element.val(this.updater(e)).change(),this.hide()},updater:function(e){return e},show:function(){var t=e.extend({},this.$element.position(),{height:this.$element[0].offsetHeight});return this.$menu.insertAfter(this.$element).css({top:t.top+t.height,left:t.left}).show(),this.shown=!0,this},hide:function(){return this.$menu.hide(),this.shown=!1,this},lookup:function(t){var n;return this.query=this.$element.val(),!this.query||this.query.length<this.options.minLength?this.shown?this.hide():this:(n=e.isFunction(this.source)?this.source(this.query,e.proxy(this.process,this)):this.source,n?this.process(n):this)},process:function(t){var n=this;return t=e.grep(t,function(e){return n.matcher(e)}),t=this.sorter(t),t.length?this.render(t.slice(0,this.options.items)).show():this.shown?this.hide():this},matcher:function(e){return~e.toLowerCase().indexOf(this.query.toLowerCase())},sorter:function(e){var t=[],n=[],r=[],i;while(i=e.shift())i.toLowerCase().indexOf(this.query.toLowerCase())?~i.indexOf(this.query)?n.push(i):r.push(i):t.push(i);return t.concat(n,r)},highlighter:function(e){var t=this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&");return e.replace(new RegExp("("+t+")","ig"),function(e,t){return"<strong>"+t+"</strong>"})},render:function(t){var n=this;return t=e(t).map(function(t,r){return t=e(n.options.item).attr("data-value",r),t.find("a").html(n.highlighter(r)),t[0]}),t.first().addClass("active"),this.$menu.html(t),this},next:function(t){var n=this.$menu.find(".active").removeClass("active"),r=n.next();r.length||(r=e(this.$menu.find("li")[0])),r.addClass("active")},prev:function(e){var t=this.$menu.find(".active").removeClass("active"),n=t.prev();n.length||(n=this.$menu.find("li").last()),n.addClass("active")},listen:function(){this.$element.on("focus",e.proxy(this.focus,this)).on("blur",e.proxy(this.blur,this)).on("keypress",e.proxy(this.keypress,this)).on("keyup",e.proxy(this.keyup,this)),this.eventSupported("keydown")&&this.$element.on("keydown",e.proxy(this.keydown,this)),this.$menu.on("click",e.proxy(this.click,this)).on("mouseenter","li",e.proxy(this.mouseenter,this)).on("mouseleave","li",e.proxy(this.mouseleave,this))},eventSupported:function(e){var t=e in this.$element;return t||(this.$element.setAttribute(e,"return;"),t=typeof this.$element[e]=="function"),t},move:function(e){if(!this.shown)return;switch(e.keyCode){case 9:case 13:case 27:e.preventDefault();break;case 38:e.preventDefault(),this.prev();break;case 40:e.preventDefault(),this.next()}e.stopPropagation()},keydown:function(t){this.suppressKeyPressRepeat=~e.inArray(t.keyCode,[40,38,9,13,27]),this.move(t)},keypress:function(e){if(this.suppressKeyPressRepeat)return;this.move(e)},keyup:function(e){switch(e.keyCode){case 40:case 38:case 16:case 17:case 18:break;case 9:case 13:if(!this.shown)return;this.select();break;case 27:if(!this.shown)return;this.hide();break;default:this.lookup()}e.stopPropagation(),e.preventDefault()},focus:function(e){this.focused=!0},blur:function(e){this.focused=!1,!this.mousedover&&this.shown&&this.hide()},click:function(e){e.stopPropagation(),e.preventDefault(),this.select(),this.$element.focus()},mouseenter:function(t){this.mousedover=!0,this.$menu.find(".active").removeClass("active"),e(t.currentTarget).addClass("active")},mouseleave:function(e){this.mousedover=!1,!this.focused&&this.shown&&this.hide()}};var n=e.fn.typeahead;e.fn.typeahead=function(n){return this.each(function(){var r=e(this),i=r.data("typeahead"),s=typeof n=="object"&&n;i||r.data("typeahead",i=new t(this,s)),typeof n=="string"&&i[n]()})},e.fn.typeahead.defaults={source:[],items:8,menu:'<ul class="typeahead dropdown-menu"></ul>',item:'<li><a href="#"></a></li>',minLength:1},e.fn.typeahead.Constructor=t,e.fn.typeahead.noConflict=function(){return e.fn.typeahead=n,this},e(document).on("focus.typeahead.data-api",'[data-provide="typeahead"]',function(t){var n=e(this);if(n.data("typeahead"))return;n.typeahead(n.data())})}(window.jQuery),!function(e){"use strict";var t=function(t,n){this.options=e.extend({},e.fn.affix.defaults,n),this.$window=e(window).on("scroll.affix.data-api",e.proxy(this.checkPosition,this)).on("click.affix.data-api",e.proxy(function(){setTimeout(e.proxy(this.checkPosition,this),1)},this)),this.$element=e(t),this.checkPosition()};t.prototype.checkPosition=function(){if(!this.$element.is(":visible"))return;var t=e(document).height(),n=this.$window.scrollTop(),r=this.$element.offset(),i=this.options.offset,s=i.bottom,o=i.top,u="affix affix-top affix-bottom",a;typeof i!="object"&&(s=o=i),typeof o=="function"&&(o=i.top()),typeof s=="function"&&(s=i.bottom()),a=this.unpin!=null&&n+this.unpin<=r.top?!1:s!=null&&r.top+this.$element.height()>=t-s?"bottom":o!=null&&n<=o?"top":!1;if(this.affixed===a)return;this.affixed=a,this.unpin=a=="bottom"?r.top-n:null,this.$element.removeClass(u).addClass("affix"+(a?"-"+a:""))};var n=e.fn.affix;e.fn.affix=function(n){return this.each(function(){var r=e(this),i=r.data("affix"),s=typeof n=="object"&&n;i||r.data("affix",i=new t(this,s)),typeof n=="string"&&i[n]()})},e.fn.affix.Constructor=t,e.fn.affix.defaults={offset:0},e.fn.affix.noConflict=function(){return e.fn.affix=n,this},e(window).on("load",function(){e('[data-spy="affix"]').each(function(){var t=e(this),n=t.data();n.offset=n.offset||{},n.offsetBottom&&(n.offset.bottom=n.offsetBottom),n.offsetTop&&(n.offset.top=n.offsetTop),t.affix(n)})})}(window.jQuery);
ztfy.bootstrap
/ztfy.bootstrap-0.1.6.tar.gz/ztfy.bootstrap-0.1.6/src/ztfy/bootstrap/resources/js/bootstrap.min.js
bootstrap.min.js
!function ($) { "use strict"; // jshint ;_; /* CSS TRANSITION SUPPORT (http://www.modernizr.com/) * ======================================================= */ $(function () { $.support.transition = (function () { var transitionEnd = (function () { var el = document.createElement('bootstrap') , transEndEventNames = { 'WebkitTransition' : 'webkitTransitionEnd' , 'MozTransition' : 'transitionend' , 'OTransition' : 'oTransitionEnd otransitionend' , 'transition' : 'transitionend' } , name for (name in transEndEventNames){ if (el.style[name] !== undefined) { return transEndEventNames[name] } } }()) return transitionEnd && { end: transitionEnd } })() }) }(window.jQuery);/* ========================================================== * bootstrap-alert.js v2.3.1 * http://twitter.github.com/bootstrap/javascript.html#alerts * ========================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================== */ !function ($) { "use strict"; // jshint ;_; /* ALERT CLASS DEFINITION * ====================== */ var dismiss = '[data-dismiss="alert"]' , Alert = function (el) { $(el).on('click', dismiss, this.close) } Alert.prototype.close = function (e) { var $this = $(this) , selector = $this.attr('data-target') , $parent if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } $parent = $(selector) e && e.preventDefault() $parent.length || ($parent = $this.hasClass('alert') ? $this : $this.parent()) $parent.trigger(e = $.Event('close')) if (e.isDefaultPrevented()) return $parent.removeClass('in') function removeElement() { $parent .trigger('closed') .remove() } $.support.transition && $parent.hasClass('fade') ? $parent.on($.support.transition.end, removeElement) : removeElement() } /* ALERT PLUGIN DEFINITION * ======================= */ var old = $.fn.alert $.fn.alert = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('alert') if (!data) $this.data('alert', (data = new Alert(this))) if (typeof option == 'string') data[option].call($this) }) } $.fn.alert.Constructor = Alert /* ALERT NO CONFLICT * ================= */ $.fn.alert.noConflict = function () { $.fn.alert = old return this } /* ALERT DATA-API * ============== */ $(document).on('click.alert.data-api', dismiss, Alert.prototype.close) }(window.jQuery);/* ============================================================ * bootstrap-button.js v2.3.1 * http://twitter.github.com/bootstrap/javascript.html#buttons * ============================================================ * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================ */ !function ($) { "use strict"; // jshint ;_; /* BUTTON PUBLIC CLASS DEFINITION * ============================== */ var Button = function (element, options) { this.$element = $(element) this.options = $.extend({}, $.fn.button.defaults, options) } Button.prototype.setState = function (state) { var d = 'disabled' , $el = this.$element , data = $el.data() , val = $el.is('input') ? 'val' : 'html' state = state + 'Text' data.resetText || $el.data('resetText', $el[val]()) $el[val](data[state] || this.options[state]) // push to event loop to allow forms to submit setTimeout(function () { state == 'loadingText' ? $el.addClass(d).attr(d, d) : $el.removeClass(d).removeAttr(d) }, 0) } Button.prototype.toggle = function () { var $parent = this.$element.closest('[data-toggle="buttons-radio"]') $parent && $parent .find('.active') .removeClass('active') this.$element.toggleClass('active') } /* BUTTON PLUGIN DEFINITION * ======================== */ var old = $.fn.button $.fn.button = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('button') , options = typeof option == 'object' && option if (!data) $this.data('button', (data = new Button(this, options))) if (option == 'toggle') data.toggle() else if (option) data.setState(option) }) } $.fn.button.defaults = { loadingText: 'loading...' } $.fn.button.Constructor = Button /* BUTTON NO CONFLICT * ================== */ $.fn.button.noConflict = function () { $.fn.button = old return this } /* BUTTON DATA-API * =============== */ $(document).on('click.button.data-api', '[data-toggle^=button]', function (e) { var $btn = $(e.target) if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn') $btn.button('toggle') }) }(window.jQuery);/* ========================================================== * bootstrap-carousel.js v2.3.1 * http://twitter.github.com/bootstrap/javascript.html#carousel * ========================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================== */ !function ($) { "use strict"; // jshint ;_; /* CAROUSEL CLASS DEFINITION * ========================= */ var Carousel = function (element, options) { this.$element = $(element) this.$indicators = this.$element.find('.carousel-indicators') this.options = options this.options.pause == 'hover' && this.$element .on('mouseenter', $.proxy(this.pause, this)) .on('mouseleave', $.proxy(this.cycle, this)) } Carousel.prototype = { cycle: function (e) { if (!e) this.paused = false if (this.interval) clearInterval(this.interval); this.options.interval && !this.paused && (this.interval = setInterval($.proxy(this.next, this), this.options.interval)) return this } , getActiveIndex: function () { this.$active = this.$element.find('.item.active') this.$items = this.$active.parent().children() return this.$items.index(this.$active) } , to: function (pos) { var activeIndex = this.getActiveIndex() , that = this if (pos > (this.$items.length - 1) || pos < 0) return if (this.sliding) { return this.$element.one('slid', function () { that.to(pos) }) } if (activeIndex == pos) { return this.pause().cycle() } return this.slide(pos > activeIndex ? 'next' : 'prev', $(this.$items[pos])) } , pause: function (e) { if (!e) this.paused = true if (this.$element.find('.next, .prev').length && $.support.transition.end) { this.$element.trigger($.support.transition.end) this.cycle(true) } clearInterval(this.interval) this.interval = null return this } , next: function () { if (this.sliding) return return this.slide('next') } , prev: function () { if (this.sliding) return return this.slide('prev') } , slide: function (type, next) { var $active = this.$element.find('.item.active') , $next = next || $active[type]() , isCycling = this.interval , direction = type == 'next' ? 'left' : 'right' , fallback = type == 'next' ? 'first' : 'last' , that = this , e this.sliding = true isCycling && this.pause() $next = $next.length ? $next : this.$element.find('.item')[fallback]() e = $.Event('slide', { relatedTarget: $next[0] , direction: direction }) if ($next.hasClass('active')) return if (this.$indicators.length) { this.$indicators.find('.active').removeClass('active') this.$element.one('slid', function () { var $nextIndicator = $(that.$indicators.children()[that.getActiveIndex()]) $nextIndicator && $nextIndicator.addClass('active') }) } if ($.support.transition && this.$element.hasClass('slide')) { this.$element.trigger(e) if (e.isDefaultPrevented()) return $next.addClass(type) $next[0].offsetWidth // force reflow $active.addClass(direction) $next.addClass(direction) this.$element.one($.support.transition.end, function () { $next.removeClass([type, direction].join(' ')).addClass('active') $active.removeClass(['active', direction].join(' ')) that.sliding = false setTimeout(function () { that.$element.trigger('slid') }, 0) }) } else { this.$element.trigger(e) if (e.isDefaultPrevented()) return $active.removeClass('active') $next.addClass('active') this.sliding = false this.$element.trigger('slid') } isCycling && this.cycle() return this } } /* CAROUSEL PLUGIN DEFINITION * ========================== */ var old = $.fn.carousel $.fn.carousel = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('carousel') , options = $.extend({}, $.fn.carousel.defaults, typeof option == 'object' && option) , action = typeof option == 'string' ? option : options.slide if (!data) $this.data('carousel', (data = new Carousel(this, options))) if (typeof option == 'number') data.to(option) else if (action) data[action]() else if (options.interval) data.pause().cycle() }) } $.fn.carousel.defaults = { interval: 5000 , pause: 'hover' } $.fn.carousel.Constructor = Carousel /* CAROUSEL NO CONFLICT * ==================== */ $.fn.carousel.noConflict = function () { $.fn.carousel = old return this } /* CAROUSEL DATA-API * ================= */ $(document).on('click.carousel.data-api', '[data-slide], [data-slide-to]', function (e) { var $this = $(this), href , $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 , options = $.extend({}, $target.data(), $this.data()) , slideIndex $target.carousel(options) if (slideIndex = $this.attr('data-slide-to')) { $target.data('carousel').pause().to(slideIndex).cycle() } e.preventDefault() }) }(window.jQuery);/* ============================================================= * bootstrap-collapse.js v2.3.1 * http://twitter.github.com/bootstrap/javascript.html#collapse * ============================================================= * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================ */ !function ($) { "use strict"; // jshint ;_; /* COLLAPSE PUBLIC CLASS DEFINITION * ================================ */ var Collapse = function (element, options) { this.$element = $(element) this.options = $.extend({}, $.fn.collapse.defaults, options) if (this.options.parent) { this.$parent = $(this.options.parent) } this.options.toggle && this.toggle() } Collapse.prototype = { constructor: Collapse , dimension: function () { var hasWidth = this.$element.hasClass('width') return hasWidth ? 'width' : 'height' } , show: function () { var dimension , scroll , actives , hasData if (this.transitioning || this.$element.hasClass('in')) return dimension = this.dimension() scroll = $.camelCase(['scroll', dimension].join('-')) actives = this.$parent && this.$parent.find('> .accordion-group > .in') if (actives && actives.length) { hasData = actives.data('collapse') if (hasData && hasData.transitioning) return actives.collapse('hide') hasData || actives.data('collapse', null) } this.$element[dimension](0) this.transition('addClass', $.Event('show'), 'shown') $.support.transition && this.$element[dimension](this.$element[0][scroll]) } , hide: function () { var dimension if (this.transitioning || !this.$element.hasClass('in')) return dimension = this.dimension() this.reset(this.$element[dimension]()) this.transition('removeClass', $.Event('hide'), 'hidden') this.$element[dimension](0) } , reset: function (size) { var dimension = this.dimension() this.$element .removeClass('collapse') [dimension](size || 'auto') [0].offsetWidth this.$element[size !== null ? 'addClass' : 'removeClass']('collapse') return this } , transition: function (method, startEvent, completeEvent) { var that = this , complete = function () { if (startEvent.type == 'show') that.reset() that.transitioning = 0 that.$element.trigger(completeEvent) } this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return this.transitioning = 1 this.$element[method]('in') $.support.transition && this.$element.hasClass('collapse') ? this.$element.one($.support.transition.end, complete) : complete() } , toggle: function () { this[this.$element.hasClass('in') ? 'hide' : 'show']() } } /* COLLAPSE PLUGIN DEFINITION * ========================== */ var old = $.fn.collapse $.fn.collapse = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('collapse') , options = $.extend({}, $.fn.collapse.defaults, $this.data(), typeof option == 'object' && option) if (!data) $this.data('collapse', (data = new Collapse(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.collapse.defaults = { toggle: true } $.fn.collapse.Constructor = Collapse /* COLLAPSE NO CONFLICT * ==================== */ $.fn.collapse.noConflict = function () { $.fn.collapse = old return this } /* COLLAPSE DATA-API * ================= */ $(document).on('click.collapse.data-api', '[data-toggle=collapse]', function (e) { var $this = $(this), href , target = $this.attr('data-target') || e.preventDefault() || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7 , option = $(target).data('collapse') ? 'toggle' : $this.data() $this[$(target).hasClass('in') ? 'addClass' : 'removeClass']('collapsed') $(target).collapse(option) }) }(window.jQuery);/* ============================================================ * bootstrap-dropdown.js v2.3.1 * http://twitter.github.com/bootstrap/javascript.html#dropdowns * ============================================================ * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================ */ !function ($) { "use strict"; // jshint ;_; /* DROPDOWN CLASS DEFINITION * ========================= */ var toggle = '[data-toggle=dropdown]' , Dropdown = function (element) { var $el = $(element).on('click.dropdown.data-api', this.toggle) $('html').on('click.dropdown.data-api', function () { $el.parent().removeClass('open') }) } Dropdown.prototype = { constructor: Dropdown , toggle: function (e) { var $this = $(this) , $parent , isActive if ($this.is('.disabled, :disabled')) return $parent = getParent($this) isActive = $parent.hasClass('open') clearMenus() if (!isActive) { $parent.toggleClass('open') } $this.focus() return false } , keydown: function (e) { var $this , $items , $active , $parent , isActive , index if (!/(38|40|27)/.test(e.keyCode)) return $this = $(this) e.preventDefault() e.stopPropagation() if ($this.is('.disabled, :disabled')) return $parent = getParent($this) isActive = $parent.hasClass('open') if (!isActive || (isActive && e.keyCode == 27)) { if (e.which == 27) $parent.find(toggle).focus() return $this.click() } $items = $('[role=menu] li:not(.divider):visible a', $parent) if (!$items.length) return index = $items.index($items.filter(':focus')) if (e.keyCode == 38 && index > 0) index-- // up if (e.keyCode == 40 && index < $items.length - 1) index++ // down if (!~index) index = 0 $items .eq(index) .focus() } } function clearMenus() { $(toggle).each(function () { getParent($(this)).removeClass('open') }) } function getParent($this) { var selector = $this.attr('data-target') , $parent if (!selector) { selector = $this.attr('href') selector = selector && /#/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } $parent = selector && $(selector) if (!$parent || !$parent.length) $parent = $this.parent() return $parent } /* DROPDOWN PLUGIN DEFINITION * ========================== */ var old = $.fn.dropdown $.fn.dropdown = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('dropdown') if (!data) $this.data('dropdown', (data = new Dropdown(this))) if (typeof option == 'string') data[option].call($this) }) } $.fn.dropdown.Constructor = Dropdown /* DROPDOWN NO CONFLICT * ==================== */ $.fn.dropdown.noConflict = function () { $.fn.dropdown = old return this } /* APPLY TO STANDARD DROPDOWN ELEMENTS * =================================== */ $(document) .on('click.dropdown.data-api', clearMenus) .on('click.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() }) .on('click.dropdown-menu', function (e) { e.stopPropagation() }) .on('click.dropdown.data-api' , toggle, Dropdown.prototype.toggle) .on('keydown.dropdown.data-api', toggle + ', [role=menu]' , Dropdown.prototype.keydown) }(window.jQuery); /* ========================================================= * bootstrap-modal.js v2.3.1 * http://twitter.github.com/bootstrap/javascript.html#modals * ========================================================= * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================= */ !function ($) { "use strict"; // jshint ;_; /* MODAL CLASS DEFINITION * ====================== */ var Modal = function (element, options) { this.options = options this.$element = $(element) .delegate('[data-dismiss="modal"]', 'click.dismiss.modal', $.proxy(this.hide, this)) this.options.remote && this.$element.find('.modal-body').load(this.options.remote) } Modal.prototype = { constructor: Modal , toggle: function () { return this[!this.isShown ? 'show' : 'hide']() } , show: function () { var that = this , e = $.Event('show') this.$element.trigger(e) if (this.isShown || e.isDefaultPrevented()) return this.isShown = true this.escape() this.backdrop(function () { var transition = $.support.transition && that.$element.hasClass('fade') if (!that.$element.parent().length) { that.$element.appendTo(document.body) //don't move modals dom position } that.$element.show() if (transition) { that.$element[0].offsetWidth // force reflow } that.$element .addClass('in') .attr('aria-hidden', false) that.enforceFocus() transition ? that.$element.one($.support.transition.end, function () { that.$element.focus().trigger('shown') }) : that.$element.focus().trigger('shown') }) } , hide: function (e) { e && e.preventDefault() var that = this e = $.Event('hide') this.$element.trigger(e) if (!this.isShown || e.isDefaultPrevented()) return this.isShown = false this.escape() $(document).off('focusin.modal') this.$element .removeClass('in') .attr('aria-hidden', true) $.support.transition && this.$element.hasClass('fade') ? this.hideWithTransition() : this.hideModal() } , enforceFocus: function () { var that = this $(document).on('focusin.modal', function (e) { if (that.$element[0] !== e.target && !that.$element.has(e.target).length) { that.$element.focus() } }) } , escape: function () { var that = this if (this.isShown && this.options.keyboard) { this.$element.on('keyup.dismiss.modal', function ( e ) { e.which == 27 && that.hide() }) } else if (!this.isShown) { this.$element.off('keyup.dismiss.modal') } } , hideWithTransition: function () { var that = this , timeout = setTimeout(function () { that.$element.off($.support.transition.end) that.hideModal() }, 500) this.$element.one($.support.transition.end, function () { clearTimeout(timeout) that.hideModal() }) } , hideModal: function () { var that = this this.$element.hide() this.backdrop(function () { that.removeBackdrop() that.$element.trigger('hidden') }) } , removeBackdrop: function () { this.$backdrop && this.$backdrop.remove() this.$backdrop = null } , backdrop: function (callback) { var that = this , animate = this.$element.hasClass('fade') ? 'fade' : '' if (this.isShown && this.options.backdrop) { var doAnimate = $.support.transition && animate this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />') .appendTo(document.body) this.$backdrop.click( this.options.backdrop == 'static' ? $.proxy(this.$element[0].focus, this.$element[0]) : $.proxy(this.hide, this) ) if (doAnimate) this.$backdrop[0].offsetWidth // force reflow this.$backdrop.addClass('in') if (!callback) return doAnimate ? this.$backdrop.one($.support.transition.end, callback) : callback() } else if (!this.isShown && this.$backdrop) { this.$backdrop.removeClass('in') $.support.transition && this.$element.hasClass('fade')? this.$backdrop.one($.support.transition.end, callback) : callback() } else if (callback) { callback() } } } /* MODAL PLUGIN DEFINITION * ======================= */ var old = $.fn.modal $.fn.modal = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('modal') , options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option) if (!data) $this.data('modal', (data = new Modal(this, options))) if (typeof option == 'string') data[option]() else if (options.show) data.show() }) } $.fn.modal.defaults = { backdrop: true , keyboard: true , show: true } $.fn.modal.Constructor = Modal /* MODAL NO CONFLICT * ================= */ $.fn.modal.noConflict = function () { $.fn.modal = old return this } /* MODAL DATA-API * ============== */ $(document).on('click.modal.data-api', '[data-toggle="modal"]', function (e) { var $this = $(this) , href = $this.attr('href') , $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7 , option = $target.data('modal') ? 'toggle' : $.extend({ remote:!/#/.test(href) && href }, $target.data(), $this.data()) e.preventDefault() $target .modal(option) .one('hide', function () { $this.focus() }) }) }(window.jQuery); /* =========================================================== * bootstrap-tooltip.js v2.3.1 * http://twitter.github.com/bootstrap/javascript.html#tooltips * Inspired by the original jQuery.tipsy by Jason Frame * =========================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================== */ !function ($) { "use strict"; // jshint ;_; /* TOOLTIP PUBLIC CLASS DEFINITION * =============================== */ var Tooltip = function (element, options) { this.init('tooltip', element, options) } Tooltip.prototype = { constructor: Tooltip , init: function (type, element, options) { var eventIn , eventOut , triggers , trigger , i this.type = type this.$element = $(element) this.options = this.getOptions(options) this.enabled = true triggers = this.options.trigger.split(' ') for (i = triggers.length; i--;) { trigger = triggers[i] if (trigger == 'click') { this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this)) } else if (trigger != 'manual') { eventIn = trigger == 'hover' ? 'mouseenter' : 'focus' eventOut = trigger == 'hover' ? 'mouseleave' : 'blur' this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this)) this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this)) } } this.options.selector ? (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) : this.fixTitle() } , getOptions: function (options) { options = $.extend({}, $.fn[this.type].defaults, this.$element.data(), options) if (options.delay && typeof options.delay == 'number') { options.delay = { show: options.delay , hide: options.delay } } return options } , enter: function (e) { var defaults = $.fn[this.type].defaults , options = {} , self this._options && $.each(this._options, function (key, value) { if (defaults[key] != value) options[key] = value }, this) self = $(e.currentTarget)[this.type](options).data(this.type) if (!self.options.delay || !self.options.delay.show) return self.show() clearTimeout(this.timeout) self.hoverState = 'in' this.timeout = setTimeout(function() { if (self.hoverState == 'in') self.show() }, self.options.delay.show) } , leave: function (e) { var self = $(e.currentTarget)[this.type](this._options).data(this.type) if (this.timeout) clearTimeout(this.timeout) if (!self.options.delay || !self.options.delay.hide) return self.hide() self.hoverState = 'out' this.timeout = setTimeout(function() { if (self.hoverState == 'out') self.hide() }, self.options.delay.hide) } , show: function () { var $tip , pos , actualWidth , actualHeight , placement , tp , e = $.Event('show') if (this.hasContent() && this.enabled) { this.$element.trigger(e) if (e.isDefaultPrevented()) return $tip = this.tip() this.setContent() if (this.options.animation) { $tip.addClass('fade') } placement = typeof this.options.placement == 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement $tip .detach() .css({ top: 0, left: 0, display: 'block' }) this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element) pos = this.getPosition() actualWidth = $tip[0].offsetWidth actualHeight = $tip[0].offsetHeight switch (placement) { case 'bottom': tp = {top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2} break case 'top': tp = {top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2} break case 'left': tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth} break case 'right': tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width} break } this.applyPlacement(tp, placement) this.$element.trigger('shown') } } , applyPlacement: function(offset, placement){ var $tip = this.tip() , width = $tip[0].offsetWidth , height = $tip[0].offsetHeight , actualWidth , actualHeight , delta , replace $tip .offset(offset) .addClass(placement) .addClass('in') actualWidth = $tip[0].offsetWidth actualHeight = $tip[0].offsetHeight if (placement == 'top' && actualHeight != height) { offset.top = offset.top + height - actualHeight replace = true } if (placement == 'bottom' || placement == 'top') { delta = 0 if (offset.left < 0){ delta = offset.left * -2 offset.left = 0 $tip.offset(offset) actualWidth = $tip[0].offsetWidth actualHeight = $tip[0].offsetHeight } this.replaceArrow(delta - width + actualWidth, actualWidth, 'left') } else { this.replaceArrow(actualHeight - height, actualHeight, 'top') } if (replace) $tip.offset(offset) } , replaceArrow: function(delta, dimension, position){ this .arrow() .css(position, delta ? (50 * (1 - delta / dimension) + "%") : '') } , setContent: function () { var $tip = this.tip() , title = this.getTitle() $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title) $tip.removeClass('fade in top bottom left right') } , hide: function () { var that = this , $tip = this.tip() , e = $.Event('hide') this.$element.trigger(e) if (e.isDefaultPrevented()) return $tip.removeClass('in') function removeWithAnimation() { var timeout = setTimeout(function () { $tip.off($.support.transition.end).detach() }, 500) $tip.one($.support.transition.end, function () { clearTimeout(timeout) $tip.detach() }) } $.support.transition && this.$tip.hasClass('fade') ? removeWithAnimation() : $tip.detach() this.$element.trigger('hidden') return this } , fixTitle: function () { var $e = this.$element if ($e.attr('title') || typeof($e.attr('data-original-title')) != 'string') { $e.attr('data-original-title', $e.attr('title') || '').attr('title', '') } } , hasContent: function () { return this.getTitle() } , getPosition: function () { var el = this.$element[0] return $.extend({}, (typeof el.getBoundingClientRect == 'function') ? el.getBoundingClientRect() : { width: el.offsetWidth , height: el.offsetHeight }, this.$element.offset()) } , getTitle: function () { var title , $e = this.$element , o = this.options title = $e.attr('data-original-title') || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title) return title } , tip: function () { return this.$tip = this.$tip || $(this.options.template) } , arrow: function(){ return this.$arrow = this.$arrow || this.tip().find(".tooltip-arrow") } , validate: function () { if (!this.$element[0].parentNode) { this.hide() this.$element = null this.options = null } } , enable: function () { this.enabled = true } , disable: function () { this.enabled = false } , toggleEnabled: function () { this.enabled = !this.enabled } , toggle: function (e) { var self = e ? $(e.currentTarget)[this.type](this._options).data(this.type) : this self.tip().hasClass('in') ? self.hide() : self.show() } , destroy: function () { this.hide().$element.off('.' + this.type).removeData(this.type) } } /* TOOLTIP PLUGIN DEFINITION * ========================= */ var old = $.fn.tooltip $.fn.tooltip = function ( option ) { return this.each(function () { var $this = $(this) , data = $this.data('tooltip') , options = typeof option == 'object' && option if (!data) $this.data('tooltip', (data = new Tooltip(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.tooltip.Constructor = Tooltip $.fn.tooltip.defaults = { animation: true , placement: 'top' , selector: false , template: '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>' , trigger: 'hover focus' , title: '' , delay: 0 , html: false , container: false } /* TOOLTIP NO CONFLICT * =================== */ $.fn.tooltip.noConflict = function () { $.fn.tooltip = old return this } }(window.jQuery); /* =========================================================== * bootstrap-popover.js v2.3.1 * http://twitter.github.com/bootstrap/javascript.html#popovers * =========================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * =========================================================== */ !function ($) { "use strict"; // jshint ;_; /* POPOVER PUBLIC CLASS DEFINITION * =============================== */ var Popover = function (element, options) { this.init('popover', element, options) } /* NOTE: POPOVER EXTENDS BOOTSTRAP-TOOLTIP.js ========================================== */ Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype, { constructor: Popover , setContent: function () { var $tip = this.tip() , title = this.getTitle() , content = this.getContent() $tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title) $tip.find('.popover-content')[this.options.html ? 'html' : 'text'](content) $tip.removeClass('fade top bottom left right in') } , hasContent: function () { return this.getTitle() || this.getContent() } , getContent: function () { var content , $e = this.$element , o = this.options content = (typeof o.content == 'function' ? o.content.call($e[0]) : o.content) || $e.attr('data-content') return content } , tip: function () { if (!this.$tip) { this.$tip = $(this.options.template) } return this.$tip } , destroy: function () { this.hide().$element.off('.' + this.type).removeData(this.type) } }) /* POPOVER PLUGIN DEFINITION * ======================= */ var old = $.fn.popover $.fn.popover = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('popover') , options = typeof option == 'object' && option if (!data) $this.data('popover', (data = new Popover(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.popover.Constructor = Popover $.fn.popover.defaults = $.extend({} , $.fn.tooltip.defaults, { placement: 'right' , trigger: 'click' , content: '' , template: '<div class="popover"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>' }) /* POPOVER NO CONFLICT * =================== */ $.fn.popover.noConflict = function () { $.fn.popover = old return this } }(window.jQuery); /* ============================================================= * bootstrap-scrollspy.js v2.3.1 * http://twitter.github.com/bootstrap/javascript.html#scrollspy * ============================================================= * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================== */ !function ($) { "use strict"; // jshint ;_; /* SCROLLSPY CLASS DEFINITION * ========================== */ function ScrollSpy(element, options) { var process = $.proxy(this.process, this) , $element = $(element).is('body') ? $(window) : $(element) , href this.options = $.extend({}, $.fn.scrollspy.defaults, options) this.$scrollElement = $element.on('scroll.scroll-spy.data-api', process) this.selector = (this.options.target || ((href = $(element).attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 || '') + ' .nav li > a' this.$body = $('body') this.refresh() this.process() } ScrollSpy.prototype = { constructor: ScrollSpy , refresh: function () { var self = this , $targets this.offsets = $([]) this.targets = $([]) $targets = this.$body .find(this.selector) .map(function () { var $el = $(this) , href = $el.data('target') || $el.attr('href') , $href = /^#\w/.test(href) && $(href) return ( $href && $href.length && [[ $href.position().top + (!$.isWindow(self.$scrollElement.get(0)) && self.$scrollElement.scrollTop()), href ]] ) || null }) .sort(function (a, b) { return a[0] - b[0] }) .each(function () { self.offsets.push(this[0]) self.targets.push(this[1]) }) } , process: function () { var scrollTop = this.$scrollElement.scrollTop() + this.options.offset , scrollHeight = this.$scrollElement[0].scrollHeight || this.$body[0].scrollHeight , maxScroll = scrollHeight - this.$scrollElement.height() , offsets = this.offsets , targets = this.targets , activeTarget = this.activeTarget , i if (scrollTop >= maxScroll) { return activeTarget != (i = targets.last()[0]) && this.activate ( i ) } for (i = offsets.length; i--;) { activeTarget != targets[i] && scrollTop >= offsets[i] && (!offsets[i + 1] || scrollTop <= offsets[i + 1]) && this.activate( targets[i] ) } } , activate: function (target) { var active , selector this.activeTarget = target $(this.selector) .parent('.active') .removeClass('active') selector = this.selector + '[data-target="' + target + '"],' + this.selector + '[href="' + target + '"]' active = $(selector) .parent('li') .addClass('active') if (active.parent('.dropdown-menu').length) { active = active.closest('li.dropdown').addClass('active') } active.trigger('activate') } } /* SCROLLSPY PLUGIN DEFINITION * =========================== */ var old = $.fn.scrollspy $.fn.scrollspy = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('scrollspy') , options = typeof option == 'object' && option if (!data) $this.data('scrollspy', (data = new ScrollSpy(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.scrollspy.Constructor = ScrollSpy $.fn.scrollspy.defaults = { offset: 10 } /* SCROLLSPY NO CONFLICT * ===================== */ $.fn.scrollspy.noConflict = function () { $.fn.scrollspy = old return this } /* SCROLLSPY DATA-API * ================== */ $(window).on('load', function () { $('[data-spy="scroll"]').each(function () { var $spy = $(this) $spy.scrollspy($spy.data()) }) }) }(window.jQuery);/* ======================================================== * bootstrap-tab.js v2.3.1 * http://twitter.github.com/bootstrap/javascript.html#tabs * ======================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================== */ !function ($) { "use strict"; // jshint ;_; /* TAB CLASS DEFINITION * ==================== */ var Tab = function (element) { this.element = $(element) } Tab.prototype = { constructor: Tab , show: function () { var $this = this.element , $ul = $this.closest('ul:not(.dropdown-menu)') , selector = $this.attr('data-target') , previous , $target , e if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } if ( $this.parent('li').hasClass('active') ) return previous = $ul.find('.active:last a')[0] e = $.Event('show', { relatedTarget: previous }) $this.trigger(e) if (e.isDefaultPrevented()) return $target = $(selector) this.activate($this.parent('li'), $ul) this.activate($target, $target.parent(), function () { $this.trigger({ type: 'shown' , relatedTarget: previous }) }) } , activate: function ( element, container, callback) { var $active = container.find('> .active') , transition = callback && $.support.transition && $active.hasClass('fade') function next() { $active .removeClass('active') .find('> .dropdown-menu > .active') .removeClass('active') element.addClass('active') if (transition) { element[0].offsetWidth // reflow for transition element.addClass('in') } else { element.removeClass('fade') } if ( element.parent('.dropdown-menu') ) { element.closest('li.dropdown').addClass('active') } callback && callback() } transition ? $active.one($.support.transition.end, next) : next() $active.removeClass('in') } } /* TAB PLUGIN DEFINITION * ===================== */ var old = $.fn.tab $.fn.tab = function ( option ) { return this.each(function () { var $this = $(this) , data = $this.data('tab') if (!data) $this.data('tab', (data = new Tab(this))) if (typeof option == 'string') data[option]() }) } $.fn.tab.Constructor = Tab /* TAB NO CONFLICT * =============== */ $.fn.tab.noConflict = function () { $.fn.tab = old return this } /* TAB DATA-API * ============ */ $(document).on('click.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) { e.preventDefault() $(this).tab('show') }) }(window.jQuery);/* ============================================================= * bootstrap-typeahead.js v2.3.1 * http://twitter.github.com/bootstrap/javascript.html#typeahead * ============================================================= * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================ */ !function($){ "use strict"; // jshint ;_; /* TYPEAHEAD PUBLIC CLASS DEFINITION * ================================= */ var Typeahead = function (element, options) { this.$element = $(element) this.options = $.extend({}, $.fn.typeahead.defaults, options) this.matcher = this.options.matcher || this.matcher this.sorter = this.options.sorter || this.sorter this.highlighter = this.options.highlighter || this.highlighter this.updater = this.options.updater || this.updater this.source = this.options.source this.$menu = $(this.options.menu) this.shown = false this.listen() } Typeahead.prototype = { constructor: Typeahead , select: function () { var val = this.$menu.find('.active').attr('data-value') this.$element .val(this.updater(val)) .change() return this.hide() } , updater: function (item) { return item } , show: function () { var pos = $.extend({}, this.$element.position(), { height: this.$element[0].offsetHeight }) this.$menu .insertAfter(this.$element) .css({ top: pos.top + pos.height , left: pos.left }) .show() this.shown = true return this } , hide: function () { this.$menu.hide() this.shown = false return this } , lookup: function (event) { var items this.query = this.$element.val() if (!this.query || this.query.length < this.options.minLength) { return this.shown ? this.hide() : this } items = $.isFunction(this.source) ? this.source(this.query, $.proxy(this.process, this)) : this.source return items ? this.process(items) : this } , process: function (items) { var that = this items = $.grep(items, function (item) { return that.matcher(item) }) items = this.sorter(items) if (!items.length) { return this.shown ? this.hide() : this } return this.render(items.slice(0, this.options.items)).show() } , matcher: function (item) { return ~item.toLowerCase().indexOf(this.query.toLowerCase()) } , sorter: function (items) { var beginswith = [] , caseSensitive = [] , caseInsensitive = [] , item while (item = items.shift()) { if (!item.toLowerCase().indexOf(this.query.toLowerCase())) beginswith.push(item) else if (~item.indexOf(this.query)) caseSensitive.push(item) else caseInsensitive.push(item) } return beginswith.concat(caseSensitive, caseInsensitive) } , highlighter: function (item) { var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&') return item.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) { return '<strong>' + match + '</strong>' }) } , render: function (items) { var that = this items = $(items).map(function (i, item) { i = $(that.options.item).attr('data-value', item) i.find('a').html(that.highlighter(item)) return i[0] }) items.first().addClass('active') this.$menu.html(items) return this } , next: function (event) { var active = this.$menu.find('.active').removeClass('active') , next = active.next() if (!next.length) { next = $(this.$menu.find('li')[0]) } next.addClass('active') } , prev: function (event) { var active = this.$menu.find('.active').removeClass('active') , prev = active.prev() if (!prev.length) { prev = this.$menu.find('li').last() } prev.addClass('active') } , listen: function () { this.$element .on('focus', $.proxy(this.focus, this)) .on('blur', $.proxy(this.blur, this)) .on('keypress', $.proxy(this.keypress, this)) .on('keyup', $.proxy(this.keyup, this)) if (this.eventSupported('keydown')) { this.$element.on('keydown', $.proxy(this.keydown, this)) } this.$menu .on('click', $.proxy(this.click, this)) .on('mouseenter', 'li', $.proxy(this.mouseenter, this)) .on('mouseleave', 'li', $.proxy(this.mouseleave, this)) } , eventSupported: function(eventName) { var isSupported = eventName in this.$element if (!isSupported) { this.$element.setAttribute(eventName, 'return;') isSupported = typeof this.$element[eventName] === 'function' } return isSupported } , move: function (e) { if (!this.shown) return switch(e.keyCode) { case 9: // tab case 13: // enter case 27: // escape e.preventDefault() break case 38: // up arrow e.preventDefault() this.prev() break case 40: // down arrow e.preventDefault() this.next() break } e.stopPropagation() } , keydown: function (e) { this.suppressKeyPressRepeat = ~$.inArray(e.keyCode, [40,38,9,13,27]) this.move(e) } , keypress: function (e) { if (this.suppressKeyPressRepeat) return this.move(e) } , keyup: function (e) { switch(e.keyCode) { case 40: // down arrow case 38: // up arrow case 16: // shift case 17: // ctrl case 18: // alt break case 9: // tab case 13: // enter if (!this.shown) return this.select() break case 27: // escape if (!this.shown) return this.hide() break default: this.lookup() } e.stopPropagation() e.preventDefault() } , focus: function (e) { this.focused = true } , blur: function (e) { this.focused = false if (!this.mousedover && this.shown) this.hide() } , click: function (e) { e.stopPropagation() e.preventDefault() this.select() this.$element.focus() } , mouseenter: function (e) { this.mousedover = true this.$menu.find('.active').removeClass('active') $(e.currentTarget).addClass('active') } , mouseleave: function (e) { this.mousedover = false if (!this.focused && this.shown) this.hide() } } /* TYPEAHEAD PLUGIN DEFINITION * =========================== */ var old = $.fn.typeahead $.fn.typeahead = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('typeahead') , options = typeof option == 'object' && option if (!data) $this.data('typeahead', (data = new Typeahead(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.typeahead.defaults = { source: [] , items: 8 , menu: '<ul class="typeahead dropdown-menu"></ul>' , item: '<li><a href="#"></a></li>' , minLength: 1 } $.fn.typeahead.Constructor = Typeahead /* TYPEAHEAD NO CONFLICT * =================== */ $.fn.typeahead.noConflict = function () { $.fn.typeahead = old return this } /* TYPEAHEAD DATA-API * ================== */ $(document).on('focus.typeahead.data-api', '[data-provide="typeahead"]', function (e) { var $this = $(this) if ($this.data('typeahead')) return $this.typeahead($this.data()) }) }(window.jQuery); /* ========================================================== * bootstrap-affix.js v2.3.1 * http://twitter.github.com/bootstrap/javascript.html#affix * ========================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================== */ !function ($) { "use strict"; // jshint ;_; /* AFFIX CLASS DEFINITION * ====================== */ var Affix = function (element, options) { this.options = $.extend({}, $.fn.affix.defaults, options) this.$window = $(window) .on('scroll.affix.data-api', $.proxy(this.checkPosition, this)) .on('click.affix.data-api', $.proxy(function () { setTimeout($.proxy(this.checkPosition, this), 1) }, this)) this.$element = $(element) this.checkPosition() } Affix.prototype.checkPosition = function () { if (!this.$element.is(':visible')) return var scrollHeight = $(document).height() , scrollTop = this.$window.scrollTop() , position = this.$element.offset() , offset = this.options.offset , offsetBottom = offset.bottom , offsetTop = offset.top , reset = 'affix affix-top affix-bottom' , affix if (typeof offset != 'object') offsetBottom = offsetTop = offset if (typeof offsetTop == 'function') offsetTop = offset.top() if (typeof offsetBottom == 'function') offsetBottom = offset.bottom() affix = this.unpin != null && (scrollTop + this.unpin <= position.top) ? false : offsetBottom != null && (position.top + this.$element.height() >= scrollHeight - offsetBottom) ? 'bottom' : offsetTop != null && scrollTop <= offsetTop ? 'top' : false if (this.affixed === affix) return this.affixed = affix this.unpin = affix == 'bottom' ? position.top - scrollTop : null this.$element.removeClass(reset).addClass('affix' + (affix ? '-' + affix : '')) } /* AFFIX PLUGIN DEFINITION * ======================= */ var old = $.fn.affix $.fn.affix = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('affix') , options = typeof option == 'object' && option if (!data) $this.data('affix', (data = new Affix(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.affix.Constructor = Affix $.fn.affix.defaults = { offset: 0 } /* AFFIX NO CONFLICT * ================= */ $.fn.affix.noConflict = function () { $.fn.affix = old return this } /* AFFIX DATA-API * ============== */ $(window).on('load', function () { $('[data-spy="affix"]').each(function () { var $spy = $(this) , data = $spy.data() data.offset = data.offset || {} data.offsetBottom && (data.offset.bottom = data.offsetBottom) data.offsetTop && (data.offset.top = data.offsetTop) $spy.affix(data) }) }) }(window.jQuery);
ztfy.bootstrap
/ztfy.bootstrap-0.1.6.tar.gz/ztfy.bootstrap-0.1.6/src/ztfy/bootstrap/resources/js/bootstrap.js
bootstrap.js
.. contents:: Introduction ============ ZTFY.cache is a small package which provides a common interface to handle several cache backends. Currently available backends include Zope native RAM cache and Memcached cache. Cache proxy =========== The main concept included ZTFY.cache package is just those of a small proxy which provides a same interfaces to several proxy classes. When defining a proxy, you just have to set the interface and the registration name matching the given registered cache utility. Cache access is then bound to the ICacheHandler interface, which allows you to set, query and invalidate data in the cache. The cache proxy can be defined as a persistent utility, or through ZCML directives. Using ZCML can allow you to define different caches, according to the used application front-end.
ztfy.cache
/ztfy.cache-0.1.1.tar.gz/ztfy.cache-0.1.1/docs/README.txt
README.txt
==================== ztfy.captcha package ==================== You may find documentation in: - Global README.txt: ztfy/captcha/docs/README.txt - General: ztfy/captcha/docs - Technical: ztfy/captcha/doctests More informations can be found on ZTFY.org_ web site ; a decicated Trac environment is available on ZTFY.captcha_. This package is created and maintained by Thierry Florac_. .. _Thierry Florac: mailto:[email protected] .. _ZTFY.org: http://www.ztfy.org .. _ZTFY.captcha: http://trac.ztfy.org/ztfy.captcha
ztfy.captcha
/ztfy.captcha-0.3.4.tar.gz/ztfy.captcha-0.3.4/README.txt
README.txt
__docformat__ = "restructuredtext" # import standard packages import hashlib import logging import os import random import string import sys from PIL import Image, ImageFont, ImageDraw, ImageFilter # import Zope3 interfaces # import local interfaces from ztfy.cache.interfaces import IPersistentCacheProxyHandler # import Zope3 packages from zope.component import queryUtility # import local packages from ztfy.utils import request as request_utils, session SHA_SEED = str(random.randint(0, sys.maxint)) def getShaSeed(): proxy = queryUtility(IPersistentCacheProxyHandler) if proxy is None: logging.getLogger('ztfy.captcha').warning("No cache handler defined! " "You may get captcha errors in multi-process environments...") return SHA_SEED cache = proxy.getCache() seed = cache.query('ztfy.captcha', 'SHA_SEED') if seed is None: seed = SHA_SEED cache.set('ztfy.captcha', 'SHA_SEED', SHA_SEED) return seed FONTS = {} FONTS_PATH = os.path.join(os.path.dirname(__file__), 'fonts') for f in os.listdir(FONTS_PATH): try: FONTS[f] = ImageFont.truetype(os.path.join(FONTS_PATH, f), random.randint(30, 40)) except: logging.getLogger('ztfy.captcha').error("Can't load font from file '%s'" % f) def getCaptchaImage(text, format='JPEG'): """Generate new captcha""" img = Image.new('RGB', (30 * len(text), 100), 0xffffff) img.format = format d = ImageDraw.Draw(img) x = y = 2 height = random.randint(0, 35) for c in text: font = FONTS[random.choice(FONTS.keys())] w, h = font.getsize(c) height = max(height, h) y = random.randint(2, max(height - h, 2) + 10) d.text((x, y + 5), c, font=font, fill=0x333333) x += w height += 15 for _i in range(5): d.line((random.randint(0, x / 2), random.randint(0, height), random.randint(x / 2, x), random.randint(0, height)), width=1, fill=0x888888) return img.crop((0, 0, x + 4, height + 4)).filter(ImageFilter.SMOOTH_MORE) CHARS = string.ascii_uppercase + string.digits[1:] def getDigest(text): return hashlib.sha256(getShaSeed() + '-----' + (text or '')).hexdigest() def getCaptcha(id, length=5, format='JPEG', request=None): """Create a new random captcha""" text = ''.join([random.choice(CHARS) for _i in range(length)]) image = getCaptchaImage(text, format) if request is None: try: request = request_utils.getRequest() except RuntimeError: pass if request is not None: session.setData(request, 'ztfy.captcha', id, getDigest(text)) return text, image def checkCaptcha(id, text, request=None): if request is None: try: request = request_utils.getRequest() except RuntimeError: return False digest = session.getData(request, 'ztfy.captcha', id) return getDigest(text) == digest
ztfy.captcha
/ztfy.captcha-0.3.4.tar.gz/ztfy.captcha-0.3.4/src/ztfy/captcha/api.py
api.py
__docformat__ = "restructuredtext" # import standard packages import hashlib # import Zope3 interfaces from z3c.form.interfaces import IFieldWidget, ITextWidget, IValidator, IErrorViewSnippet from zope.schema.interfaces import IField # import local interfaces from ztfy.baseskin.layer import IBaseSkinLayer from ztfy.captcha.schema import ICaptcha # import Zope3 packages from z3c.form.browser.text import TextWidget from z3c.form.error import ErrorViewSnippet from z3c.form.validator import SimpleFieldValidator from z3c.form.widget import FieldWidget from zope.component import adapter, adapts from zope.i18n import translate from zope.interface import Interface, implementer, implements, implementsOnly from zope.schema import ValidationError # import local packages from ztfy.captcha.api import checkCaptcha from ztfy.utils.catalog import getObjectId from ztfy.captcha import _ class ICaptchaWidget(ITextWidget): """Captcha widget interface""" class CaptchaWidget(TextWidget): """Captcha widget""" implementsOnly(ICaptchaWidget) ignoreContext = True ignoreRequest = True klass = u'captcha-widget' @property def captcha_id(self): token = '%d::%s' % (getObjectId(self.context), self.name) return hashlib.sha256(token).hexdigest() @adapter(IField, IBaseSkinLayer) @implementer(IFieldWidget) def CaptchaFieldWidget(field, request): """ICaptchaWidget factory""" return FieldWidget(field, CaptchaWidget(request)) class CaptchaValidator(SimpleFieldValidator): """Captcha field validator""" adapts(Interface, IBaseSkinLayer, Interface, ICaptcha, ICaptchaWidget) implements(IValidator) def validate(self, value): result = super(CaptchaValidator, self).validate(value) if value: id = self.widget.captcha_id if not checkCaptcha(id, value.upper(), self.request): raise ValidationError, "Invalid captcha" return result class CaptchaErrorSnippet(ErrorViewSnippet): """Captcha error view snippet""" adapts(ValidationError, None, ICaptchaWidget, None, None, None) implements(IErrorViewSnippet) def createMessage(self): return translate(_("Invalid captcha input"), context=self.request)
ztfy.captcha
/ztfy.captcha-0.3.4.tar.gz/ztfy.captcha-0.3.4/src/ztfy/captcha/browser/widget/__init__.py
__init__.py
==================== ztfy.comment package ==================== You may find documentation in: - Global README.txt: ztfy/comment/docs/README.txt - General: ztfy/comment/docs - Technical: ztfy/comment/doctests More informations can be found on ZTFY.org_ web site ; a decicated Trac environment is available on ZTFY.comment_. This package is created and maintained by Thierry Florac_. .. _Thierry Florac: mailto:[email protected] .. _ZTFY.org: http://www.ztfy.org .. _ZTFY.comment: http://trac.ztfy.org/ztfy.comment
ztfy.comment
/ztfy.comment-0.3.3.tar.gz/ztfy.comment-0.3.3/README.txt
README.txt
import os import shutil import sys import tempfile from optparse import OptionParser tmpeggs = tempfile.mkdtemp() usage = '''\ [DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options] Bootstraps a buildout-based project. Simply run this script in a directory containing a buildout.cfg, using the Python that you want bin/buildout to use. Note that by using --find-links to point to local resources, you can keep this script from going over the network. ''' parser = OptionParser(usage=usage) parser.add_option("-v", "--version", help="use a specific zc.buildout version") parser.add_option("-t", "--accept-buildout-test-releases", dest='accept_buildout_test_releases', action="store_true", default=False, help=("Normally, if you do not specify a --version, the " "bootstrap script and buildout gets the newest " "*final* versions of zc.buildout and its recipes and " "extensions for you. If you use this flag, " "bootstrap and buildout will get the newest releases " "even if they are alphas or betas.")) parser.add_option("-c", "--config-file", help=("Specify the path to the buildout configuration " "file to be used.")) parser.add_option("-f", "--find-links", help=("Specify a URL to search for buildout releases")) parser.add_option("--allow-site-packages", action="store_true", default=False, help=("Let bootstrap.py use existing site packages")) options, args = parser.parse_args() ###################################################################### # load/install setuptools try: if options.allow_site_packages: import setuptools import pkg_resources from urllib.request import urlopen except ImportError: from urllib2 import urlopen ez = {} exec(urlopen('https://bootstrap.pypa.io/ez_setup.py').read(), ez) if not options.allow_site_packages: # ez_setup imports site, which adds site packages # this will remove them from the path to ensure that incompatible versions # of setuptools are not in the path import site # inside a virtualenv, there is no 'getsitepackages'. # We can't remove these reliably if hasattr(site, 'getsitepackages'): for sitepackage_path in site.getsitepackages(): sys.path[:] = [x for x in sys.path if sitepackage_path not in x] setup_args = dict(to_dir=tmpeggs, download_delay=0) ez['use_setuptools'](**setup_args) import setuptools import pkg_resources # This does not (always?) update the default working set. We will # do it. for path in sys.path: if path not in pkg_resources.working_set.entries: pkg_resources.working_set.add_entry(path) ###################################################################### # Install buildout ws = pkg_resources.working_set cmd = [sys.executable, '-c', 'from setuptools.command.easy_install import main; main()', '-mZqNxd', tmpeggs] find_links = os.environ.get( 'bootstrap-testing-find-links', options.find_links or ('http://downloads.buildout.org/' if options.accept_buildout_test_releases else None) ) if find_links: cmd.extend(['-f', find_links]) setuptools_path = ws.find( pkg_resources.Requirement.parse('setuptools')).location requirement = 'zc.buildout' version = options.version if version is None and not options.accept_buildout_test_releases: # Figure out the most recent final version of zc.buildout. import setuptools.package_index _final_parts = '*final-', '*final' def _final_version(parsed_version): for part in parsed_version: if (part[:1] == '*') and (part not in _final_parts): return False return True index = setuptools.package_index.PackageIndex( search_path=[setuptools_path]) if find_links: index.add_find_links((find_links,)) req = pkg_resources.Requirement.parse(requirement) if index.obtain(req) is not None: best = [] bestv = None for dist in index[req.project_name]: distv = dist.parsed_version if _final_version(distv): if bestv is None or distv > bestv: best = [dist] bestv = distv elif distv == bestv: best.append(dist) if best: best.sort() version = best[-1].version if version: requirement = '=='.join((requirement, version)) cmd.append(requirement) import subprocess if subprocess.call(cmd, env=dict(os.environ, PYTHONPATH=setuptools_path)) != 0: raise Exception( "Failed to execute command:\n%s" % repr(cmd)[1:-1]) ###################################################################### # Import and run buildout ws.add_entry(tmpeggs) ws.require(requirement) import zc.buildout.buildout if not [a for a in args if '=' not in a]: args.append('bootstrap') # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args[0:0] = ['-c', options.config_file] zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs)
ztfy.comment
/ztfy.comment-0.3.3.tar.gz/ztfy.comment-0.3.3/bootstrap.py
bootstrap.py
__docformat__ = "restructuredtext" # import standard packages from persistent import Persistent from persistent.list import PersistentList # import Zope3 interfaces from zope.annotation.interfaces import IAnnotations from zope.dublincore.interfaces import IZopeDublinCore # import local interfaces from ztfy.comment.interfaces import IComment, IComments, ICommentsList, ICommentable from ztfy.comment.interfaces import ICommentAddedEvent # import Zope3 packages from zope.component import adapts from zope.event import notify from zope.interface import implements from zope.location import Location, locate from zope.lifecycleevent import ObjectCreatedEvent, ObjectModifiedEvent # import local packages from ztfy.security.search import getPrincipal from ztfy.utils.date import getAge from ztfy.utils.request import getRequest from ztfy.utils.security import unproxied from ztfy.utils.text import textToHTML class CommentAddedEvent(ObjectModifiedEvent): implements(ICommentAddedEvent) def __init__(self, object, comment): super(CommentAddedEvent, self).__init__(object) self.comment = comment class Comment(Persistent, Location): implements(IComment) def __init__(self, body, in_reply_to=None, renderer=None, tags=()): self.body = body self.body_renderer = renderer self.in_reply_to = unproxied(in_reply_to) if isinstance(tags, (str, unicode)): tags = tags.split(',') self.tags = set(tags) @property def date(self): return IZopeDublinCore(self).created def getAge(self): return getAge(self.date) @property def principal_id(self): return IZopeDublinCore(self).creators[0] @property def principal(self): return getPrincipal(self.principal_id).title def render(self, request=None): if request is None: request = getRequest() return textToHTML(self.body, self.body_renderer, request) class Comments(PersistentList): """Comments container class""" implements(ICommentsList) __parent__ = None __name__ = None def append(self, item): super(Comments, self).append(item) locate(item, self) COMMENTS_ANNOTATION_KEY = 'ztfy.comment' class CommentsAdapter(object): adapts(ICommentable) implements(IComments) def __init__(self, context): self.context = context annotations = IAnnotations(context) comments = annotations.get(COMMENTS_ANNOTATION_KEY) if comments is None: comments = annotations[COMMENTS_ANNOTATION_KEY] = Comments() locate(comments, self.context) self.comments = comments def getComments(self, tag=None): if not tag: return self.comments return [c for c in self.comments if tag in c.tags] def addComment(self, body, in_reply_to=None, renderer=None, tags=()): comment = Comment(body, in_reply_to, renderer, tags) notify(ObjectCreatedEvent(comment)) self.comments.append(comment) notify(CommentAddedEvent(self.context, comment))
ztfy.comment
/ztfy.comment-0.3.3.tar.gz/ztfy.comment-0.3.3/src/ztfy/comment/comment.py
comment.py
__docformat__ = "restructuredtext" # import standard packages # import Zope3 interfaces from zope.annotation.interfaces import IAttributeAnnotatable from zope.security.interfaces import IPrincipal # import local interfaces # import Zope3 packages from zope.interface import Interface from zope.interface.common.sequence import IReadSequence, IWriteSequence from zope.lifecycleevent.interfaces import IObjectModifiedEvent from zope.schema import Datetime, Object, Choice, Set # import local packages from schema import CommentField from ztfy.security.schema import Principal from ztfy.comment import _ class ICommentable(IAttributeAnnotatable): """Marker interface for commentable contents""" class IComment(ICommentable): """Base class for comments""" date = Datetime(title=_("Creation date"), description=_("Date and time of comment creation"), required=True, readonly=True) principal_id = Principal(title=_("Creation principal"), description=_("The ID of the principal who added this comment"), required=True, readonly=True) principal = Object(schema=IPrincipal, title=_("Comment creator"), description=_("Principal who added the comment"), required=True, readonly=True) body = CommentField(title=_("Comment body"), description=_("Main content of this comment"), required=True) body_renderer = Choice(title=_("Comment renderer"), description=_("Name of utility used to render comment's body"), required=True, vocabulary='SourceTypes', default=u'zope.source.plaintext') in_reply_to = Object(title=_("Comment's parent"), description=_("Previous comment to which this comment replies"), required=False, schema=ICommentable) tags = Set(title=_("Comment tags"), description=_("A list of internal tags used to classify comments"), required=False) def getAge(): """Return comment age""" def render(request=None): """Render comment body""" class ICommentsListReader(IReadSequence): """Base class reader for comments""" class ICommentsListWriter(IWriteSequence): """Base class writer for comments""" class ICommentsList(IReadSequence, IWriteSequence): """Main class for comments list""" class ICommentsReader(Interface): """Main reader class for comments""" def getComments(tag=None): """Get comments list""" class ICommentsWriter(Interface): """Main writer class for comments""" def addComment(body, in_reply_to=None, renderer=None, tags=None): """Add a new comment""" class IComments(ICommentsReader, ICommentsWriter): """Main class for comments""" class ICommentAddedEvent(IObjectModifiedEvent): """Marker interface for comment added events""" comment = Object(title=_("Added comment"), description=_("The comment object which was added"), required=True, schema=IComment)
ztfy.comment
/ztfy.comment-0.3.3.tar.gz/ztfy.comment-0.3.3/src/ztfy/comment/interfaces.py
interfaces.py
==================== ztfy.extfile package ==================== You may find documentation in: - Global README.txt: ztfy/extfile/docs/README.txt - General: ztfy/extfile/docs - Technical: ztfy/extfile/doctest More informations can be found on ZTFY.org_ web site ; a decicated Trac environment is available on ZTFY.extfile_. This package is created and maintained by Thierry Florac_. .. _Thierry Florac: mailto:[email protected] .. _ZTFY.org: http://www.ztfy.org .. _ZTFY.extfile: http://trac.ztfy.org/ztfy.extfile
ztfy.extfile
/ztfy.extfile-0.2.14.tar.gz/ztfy.extfile-0.2.14/README.txt
README.txt
import os import shutil import sys import tempfile from optparse import OptionParser tmpeggs = tempfile.mkdtemp() usage = '''\ [DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options] Bootstraps a buildout-based project. Simply run this script in a directory containing a buildout.cfg, using the Python that you want bin/buildout to use. Note that by using --find-links to point to local resources, you can keep this script from going over the network. ''' parser = OptionParser(usage=usage) parser.add_option("-v", "--version", help="use a specific zc.buildout version") parser.add_option("-t", "--accept-buildout-test-releases", dest='accept_buildout_test_releases', action="store_true", default=False, help=("Normally, if you do not specify a --version, the " "bootstrap script and buildout gets the newest " "*final* versions of zc.buildout and its recipes and " "extensions for you. If you use this flag, " "bootstrap and buildout will get the newest releases " "even if they are alphas or betas.")) parser.add_option("-c", "--config-file", help=("Specify the path to the buildout configuration " "file to be used.")) parser.add_option("-f", "--find-links", help=("Specify a URL to search for buildout releases")) parser.add_option("--allow-site-packages", action="store_true", default=False, help=("Let bootstrap.py use existing site packages")) options, args = parser.parse_args() ###################################################################### # load/install setuptools try: if options.allow_site_packages: import setuptools import pkg_resources from urllib.request import urlopen except ImportError: from urllib2 import urlopen ez = {} exec(urlopen('https://bootstrap.pypa.io/ez_setup.py').read(), ez) if not options.allow_site_packages: # ez_setup imports site, which adds site packages # this will remove them from the path to ensure that incompatible versions # of setuptools are not in the path import site # inside a virtualenv, there is no 'getsitepackages'. # We can't remove these reliably if hasattr(site, 'getsitepackages'): for sitepackage_path in site.getsitepackages(): sys.path[:] = [x for x in sys.path if sitepackage_path not in x] setup_args = dict(to_dir=tmpeggs, download_delay=0) ez['use_setuptools'](**setup_args) import setuptools import pkg_resources # This does not (always?) update the default working set. We will # do it. for path in sys.path: if path not in pkg_resources.working_set.entries: pkg_resources.working_set.add_entry(path) ###################################################################### # Install buildout ws = pkg_resources.working_set cmd = [sys.executable, '-c', 'from setuptools.command.easy_install import main; main()', '-mZqNxd', tmpeggs] find_links = os.environ.get( 'bootstrap-testing-find-links', options.find_links or ('http://downloads.buildout.org/' if options.accept_buildout_test_releases else None) ) if find_links: cmd.extend(['-f', find_links]) setuptools_path = ws.find( pkg_resources.Requirement.parse('setuptools')).location requirement = 'zc.buildout' version = options.version if version is None and not options.accept_buildout_test_releases: # Figure out the most recent final version of zc.buildout. import setuptools.package_index _final_parts = '*final-', '*final' def _final_version(parsed_version): for part in parsed_version: if (part[:1] == '*') and (part not in _final_parts): return False return True index = setuptools.package_index.PackageIndex( search_path=[setuptools_path]) if find_links: index.add_find_links((find_links,)) req = pkg_resources.Requirement.parse(requirement) if index.obtain(req) is not None: best = [] bestv = None for dist in index[req.project_name]: distv = dist.parsed_version if _final_version(distv): if bestv is None or distv > bestv: best = [dist] bestv = distv elif distv == bestv: best.append(dist) if best: best.sort() version = best[-1].version if version: requirement = '=='.join((requirement, version)) cmd.append(requirement) import subprocess if subprocess.call(cmd, env=dict(os.environ, PYTHONPATH=setuptools_path)) != 0: raise Exception( "Failed to execute command:\n%s" % repr(cmd)[1:-1]) ###################################################################### # Import and run buildout ws.add_entry(tmpeggs) ws.require(requirement) import zc.buildout.buildout if not [a for a in args if '=' not in a]: args.append('bootstrap') # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args[0:0] = ['-c', options.config_file] zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs)
ztfy.extfile
/ztfy.extfile-0.2.14.tar.gz/ztfy.extfile-0.2.14/bootstrap.py
bootstrap.py
# import standard packages # import Zope3 interfaces from zope.app.file.interfaces import IFile, IImage from zope.component.interfaces import IObjectEvent from zope.lifecycleevent.interfaces import IObjectModifiedEvent # import local interfaces # import Zope3 packages from zope.interface import Interface from zope.schema import TextLine # import local packages from ztfy.extfile import _ class IBaseExtFileInfo(Interface): """Base properties of external files""" filename = TextLine(title=_("External file name"), description=_("Identify the file name on the file system"), required=True) def hasData(self): """Check to know if file actually handles data""" class IBaseExtFileWriter(Interface): """External file writing methods""" def moveTempFile(self): """Move temporary file to it's final location""" def deleteFile(self, temporary=False): """Remove external file data on the file system""" def commitDeletedFile(self): """Really purge external file data when transaction is committed""" def resetFile(self, filename): """Reset file data to given filename""" class IBaseExtFile(IBaseExtFileInfo, IBaseExtFileWriter, IFile): """External files base interface""" class IExtFile(IBaseExtFile): """External files main interface""" class IBaseExtImage(IBaseExtFileInfo, IBaseExtFileWriter, IImage): """External images base interface""" class IExtImage(IBaseExtImage): """External images main interface""" class IBaseBlobFile(Interface): """Marker base interface for blob files""" def getBlob(self, mode='r'): """Return internal blob""" class IBlobFile(IBaseBlobFile, IFile): """Marker interface for blob files""" class IBlobImage(IBaseBlobFile, IImage): """Marker interface for blob images""" # Events interfaces class IExtFileModifiedEvent(IObjectModifiedEvent): """An external file is modified""" class IExtFileAfterAddedEvent(IObjectEvent): """An external file was added to a container""" class IExtFileAfterModifiedEvent(IObjectEvent): """An external file has been modified and moved to it's final location"""
ztfy.extfile
/ztfy.extfile-0.2.14.tar.gz/ztfy.extfile-0.2.14/src/ztfy/extfile/interfaces.py
interfaces.py
__docformat__ = "restructuredtext" # import standard packages import transaction # import Zope3 interfaces from zope.lifecycleevent.interfaces import IObjectModifiedEvent, IObjectAddedEvent, IObjectRemovedEvent # import local interfaces from ztfy.extfile.interfaces import IBaseExtFileInfo, \ IExtFileModifiedEvent, IExtFileAfterAddedEvent, IExtFileAfterModifiedEvent # import Zope3 packages from zope.component import adapter from zope.component.interfaces import ObjectEvent from zope.event import notify from zope.interface import implements from zope.lifecycleevent import ObjectModifiedEvent # import local packages class ExtFileModifiedEvent(ObjectModifiedEvent): implements(IExtFileModifiedEvent) class ExtFileAfterAddedEvent(ObjectEvent): implements(IExtFileAfterAddedEvent) class ExtFileAfterModifiedEvent(ObjectEvent): implements(IExtFileAfterModifiedEvent) def _commitDeletedExtFile(status, object): if status: object.commitDeletedFile() @adapter(IBaseExtFileInfo, IObjectAddedEvent) def handleNewExtFile(object, event): # When an external file is added, we define it's filename based on # it's parent, it's name and it's name chooser try: object.moveTempFile() except: object.deleteFile(temporary=True) transaction.get().addAfterCommitHook(_commitDeletedExtFile, kws={'object': object}) raise notify(ExtFileAfterAddedEvent(object)) @adapter(IBaseExtFileInfo, IObjectModifiedEvent) def handleModifiedExtFile(object, event): # When an external file is modified, we have to remove it's content data # and move the new file to it's final location like when object is created object.deleteFile() transaction.get().addAfterCommitHook(_commitDeletedExtFile, kws={'object': object}) object.moveTempFile() notify(ExtFileAfterModifiedEvent(object)) @adapter(IBaseExtFileInfo, IObjectRemovedEvent) def handleDeletedExtFile(object, event): # When an external file is removed, we remove the target file object.deleteFile() transaction.get().addAfterCommitHook(_commitDeletedExtFile, kws={'object': object})
ztfy.extfile
/ztfy.extfile-0.2.14.tar.gz/ztfy.extfile-0.2.14/src/ztfy/extfile/events.py
events.py
__docformat__ = "restructuredtext" # import standard packages import transaction # import Zope3 interfaces from zope.app.publication.zopepublication import ZopePublication from zope.catalog.interfaces import ICatalog from zope.component.interfaces import IComponentRegistry, ISite from zope.intid.interfaces import IIntIds from zope.processlifetime import IDatabaseOpenedWithRoot # import local interfaces from ztfy.extfile.interfaces import IBaseExtFileInfo from ztfy.utils.interfaces import INewSiteManagerEvent # import Zope3 packages from zc.catalog.catalogindex import ValueIndex from zope.catalog.catalog import Catalog from zope.component import adapter, queryUtility from zope.intid import IntIds from zope.location import locate from zope.site import hooks # import local packages from ztfy.utils.site import locateAndRegister def updateDatabaseIfNeeded(context): """Check for missing objects at application startup""" try: sm = context.getSiteManager() except: return default = sm['default'] # Check for required IIntIds utility intids = queryUtility(IIntIds) if intids is None: intids = default.get('IntIds') if intids is None: intids = IntIds() locate(intids, default) default['IntIds'] = intids IComponentRegistry(sm).registerUtility(intids, IIntIds) # Check for required catalog and index catalog = default.get('Catalog') if catalog is None: catalog = Catalog() locateAndRegister(catalog, default, 'Catalog', intids) IComponentRegistry(sm).registerUtility(catalog, ICatalog, 'Catalog') if catalog is not None: if 'filename' not in catalog: index = ValueIndex('filename', IBaseExtFileInfo, False) locateAndRegister(index, catalog, 'filename', intids) @adapter(IDatabaseOpenedWithRoot) def handleOpenedDatabase(event): db = event.database connection = db.open() root = connection.root() root_folder = root.get(ZopePublication.root_name, None) for site in root_folder.values(): if ISite(site, None) is not None: hooks.setSite(site) updateDatabaseIfNeeded(site) transaction.commit() @adapter(INewSiteManagerEvent) def handleNewSiteManager(event): updateDatabaseIfNeeded(event.object)
ztfy.extfile
/ztfy.extfile-0.2.14.tar.gz/ztfy.extfile-0.2.14/src/ztfy/extfile/database.py
database.py
__docformat__ = "restructuredtext" # import standard packages import os import logging logger = logging.getLogger('ZTFY.extfile') import tempfile from cStringIO import StringIO # import Zope3 interfaces from zope.container.interfaces import IContained # import local interfaces from hurry.query.interfaces import IQuery from ztfy.extfile.handler.interfaces import MissingHandlerError, IExtFileHandler from ztfy.extfile.interfaces import IBaseExtFile, IExtFile, IExtImage # import Zope3 packages from zope.app.file.file import File from zope.app.file.image import Image, getImageInfo from zope.component import getUtility, queryUtility from zope.interface import implements from zope.traversing.api import getParent, getName # import local packages from hurry.query.value import Eq from ztfy.extfile import getMagicContentType from ztfy.extfile.namechooser.config import getTempPath, getFullPath from ztfy.utils import catalog from ztfy.extfile import _ BLOCK_SIZE = 1 << 16 class BaseExtFile(File): """A persistent content class handling data stored in an external file""" implements(IBaseExtFile, IContained) _filename = None _deleted = False _handler = '' _size = 0L def __init__(self, data='', contentType='', nameChooser='', handler='', source=None, keep_source=False): self.__parent__ = self.__name__ = None self.contentType = contentType self._handleFile = False self._nameChooser = nameChooser self._handler = handler if data: self.data = data elif source: if os.path.exists(source): self._v_filename = source self._size = os.stat(source)[os.path.stat.ST_SIZE] self._handleFile = not keep_source def _getData(self): """See `IFile` interface""" filename = getattr(self, '_v_filename', None) if filename: f = open(filename, 'rb') data = f.read() f.close() return data filename = getattr(self, '_filename', None) if not filename: return None handler = queryUtility(IExtFileHandler, self._handler) if handler is not None: return handler.readFile(filename, self) return None def _setData(self, data): """See `IFile` interface""" self._saveTempFile(data) data = property(_getData, _setData) @property def filename(self): return self._filename def getSize(self): """See `IFile` interface""" return self._size def __nonzero__(self): return self._size > 0 def _saveTempFile(self, data): """Save data to a temporary local file""" filename = self._getTempFilename() # Check if data is empty but filename exists if (not data) and os.path.isfile(filename): return # Set a flag to know that we handle the file... self._handleFile = True # Check if data is a unicode string (copied from zope.app.file.File class if isinstance(data, unicode): data = data.encode('UTF-8') # Create temporary location directories, if needed directory = os.path.dirname(filename) if not os.path.exists(directory): os.makedirs(directory) # Write data to requested file f = open(filename, 'wb') try: if hasattr(data, 'read'): self._size = 0 _data = data.read(BLOCK_SIZE) size = len(_data) while size > 0: f.write(_data) self._size += size _data = data.read(BLOCK_SIZE) size = len(_data) else: f.write(data) self._size = len(data) finally: f.close() def _getTempFilename(self): """Get temporary file name""" pathname = getTempPath(self._nameChooser) fd, filename = tempfile.mkstemp(prefix='extfile_', suffix='.tmp', dir=pathname) os.close(fd) self._v_filename = filename return filename def _getCurrentFilename(self): """Get current file name""" return getattr(self, '_filename', None) or getattr(self, '_v_filename', None) def moveTempFile(self): """Move temporary file to it's final location""" if hasattr(self, '_v_version'): delattr(self, '_v_version') else: if self.filename: query = getUtility(IQuery) files = query.searchResults(Eq(('Catalog', 'filename'), self.filename)) if (len(files) > 0) and not hasattr(self, '_v_filename'): return self._filename = getFullPath(getParent(self), self, getName(self), self._nameChooser) if hasattr(self, '_v_filename'): handler = queryUtility(IExtFileHandler, self._handler) if handler is None: raise MissingHandlerError, _("You have to define an IExtFileHandler utility to use external files !") if self._handleFile: handler.moveFile(self._v_filename, self._filename) else: handler.copyFile(self._v_filename, self._filename) delattr(self, '_v_filename') # reindex file so that 'filename' property is indexed correctly catalog.indexObject(self, 'Catalog', 'filename') def deleteFile(self, temporary=False): """Mark external file for deletion""" if temporary: logger.debug(" >>> removing temporary file...") filename = getattr(self, '_v_filename', None) if filename: logger.debug(" > file = %s" % filename) self._v_deleted_filename = filename delattr(self, '_v_filename') self._deleted = True elif self._filename: logger.debug(" >>> trying to delete external file...") # remove this file from catalog catalog.unindexObject(self, 'Catalog', 'filename') # look for other ExtFiles with same filename query = getUtility(IQuery) files = query.searchResults(Eq(('Catalog', 'filename'), self._filename)) # remove physical file only when not shared with another file if len(files) > 0: logger.debug(" > remaining contents linked to same file, not deleted !") for f in files: logger.debug(" > file = %s %s %s" % (getName(getParent(f)), getName(f), f.filename)) return logger.debug(" < deleted %s" % self._filename) self._deleted_filename = self._filename self._filename = None self._deleted = True def commitDeletedFile(self): """Delete pointed file if handled by context""" logger.debug(" >>> commitDeletedFile...") if not (self._handleFile and self._deleted): logger.debug(" < not deleted !!") return filename = getattr(self, '_deleted_filename', None) logger.debug(" > filename =" + str(filename)) if filename: handler = queryUtility(IExtFileHandler, self._handler) if handler is None: raise MissingHandlerError, _("You have to define an IExtFileHandler utility to use external files !") handler.deleteFile(filename) delattr(self, '_deleted_filename') def resetFile(self, filename): """Reset file content to given filename""" self.deleteFile() self._filename = filename handler = queryUtility(IExtFileHandler, self._handler) if handler is not None: self._size = handler.getSize(self._filename) # reindex file so that 'filename' property is indexed correctly catalog.indexObject(self, 'Catalog', 'filename') class ExtFile(BaseExtFile): implements(IExtFile) class ExtImage(BaseExtFile, Image): implements(IExtImage) def _setData(self, data): BaseExtFile._setData(self, data) contentType, self._width, self._height = getImageInfo(data) if contentType: self.contentType = contentType if (self._width < 0) or (self._height < 0): contentType = getMagicContentType(data[:4096]) if contentType.startswith('image/'): # error occurred when checking image info? Try with PIL (if available) try: from PIL import Image img = Image.open(StringIO(data)) self.contentType = contentType self._width, self._height = img.size except (IOError, ImportError): pass data = property(BaseExtFile._getData, _setData)
ztfy.extfile
/ztfy.extfile-0.2.14.tar.gz/ztfy.extfile-0.2.14/src/ztfy/extfile/extfile.py
extfile.py
__docformat__ = "restructuredtext" # import standard packages import os from cStringIO import StringIO # import Zope3 interfaces from zope.container.interfaces import IContained # import local interfaces from ztfy.extfile.interfaces import IBaseBlobFile, IBlobFile, IBlobImage # import Zope3 packages from ZODB.blob import Blob from zope.app.file.file import File from zope.app.file.image import Image, getImageInfo from zope.interface import implements # import local packages from ztfy.extfile import getMagicContentType BLOCK_SIZE = 1 << 16 class BaseBlobFile(File): """A persistent content class handling data stored in an external blob""" implements(IBaseBlobFile, IContained) def __init__(self, data='', contentType='', source=None): self.__parent__ = self.__name__ = None self.contentType = contentType self._blob = None if data: self.data = data elif source: if os.path.exists(source): try: f = open(source, 'rb') self.data = f.read() finally: f.close() def getBlob(self, mode='r'): if self._blob is None: return None return self._blob.open(mode=mode) def _getData(self): f = self.getBlob() if f is None: return None try: data = f.read() return data finally: f.close() def _setData(self, data): if self._blob is None: self._blob = Blob() if isinstance(data, unicode): data = data.encode('UTF-8') f = self._blob.open('w') try: if hasattr(data, 'read'): self._size = 0 _data = data.read(BLOCK_SIZE) size = len(_data) while size > 0: f.write(_data) self._size += size _data = data.read(BLOCK_SIZE) size = len(_data) else: f.write(data) self._size = len(data) finally: f.close() data = property(_getData, _setData) def getSize(self): return self._size def __nonzero__(self): return self._size > 0 class BlobFile(BaseBlobFile): """Content class for BLOB files""" implements(IBlobFile) class BlobImage(BaseBlobFile, Image): """Content class for BLOB images""" implements(IBlobImage) def _setData(self, data): BaseBlobFile._setData(self, data) contentType, self._width, self._height = getImageInfo(data) if contentType: self.contentType = contentType if (self._width < 0) or (self._height < 0): contentType = getMagicContentType(data) if contentType.startswith('image/'): # error occurred when checking image info? Try with PIL (if available) try: from PIL import Image img = Image.open(StringIO(data)) self.contentType = contentType self._width, self._height = img.size except (IOError, ImportError): pass data = property(BaseBlobFile._getData, _setData)
ztfy.extfile
/ztfy.extfile-0.2.14.tar.gz/ztfy.extfile-0.2.14/src/ztfy/extfile/blob.py
blob.py
__docformat__ = "restructuredtext" # import standard packages import logging logger = logging.getLogger("ZTFY.extfile") import paramiko import os import time import traceback from hashlib import md5 # import Zope3 interfaces # import local interfaces from ztfy.extfile.handler.interfaces import IExtFileHandler from zope.dublincore.interfaces import IZopeDublinCore # import Zope3 packages from zope.interface import implements # import local packages from ztfy.extfile import _ class SFTPExtFileHandler(object): implements(IExtFileHandler) hostname = 'localhost' port = 22 username = '' password = None private_key = '~/.ssh/id_rsa' _remote_root = '/' _cache_root = None # External properties def _getRemoteRoot(self): return self._remote_root def _setRemoteRoot(self, path): if not path.endswith(os.path.sep): path += os.path.sep self._remote_root = path remote_root = property(_getRemoteRoot, _setRemoteRoot) def _getCacheRoot(self): return self._cache_root def _setCacheRoot(self, path): if not path.endswith(os.path.sep): path += os.path.sep self._cache_root = path cache_root = property(_getCacheRoot, _setCacheRoot) # Internal methods def _connect(self): transport = paramiko.Transport((self.hostname, self.port)) transport.start_client() if self.private_key: key = paramiko.RSAKey.from_private_key_file(os.path.expanduser(self.private_key)) transport.auth_publickey(self.username, key) else: transport.auth_password(self.username, self.password) return transport def _getClient(self): try: transport = self._connect() return transport, transport.open_sftp_client() except: transport = self._connect() return transport, transport.open_sftp_client() def _getCachePath(self, path): if not self.cache_root: return None sign = md5(path) digest = sign.hexdigest() path = os.path.join(self.cache_root, digest[:2], digest[2:4]) if not os.path.exists(path): os.makedirs(path, 0755) return os.path.join(path, digest[4:]) def _getRemotePath(self, path): if path.startswith(os.path.sep): path = path[1:] return os.path.join(self.remote_root, path) # IExtFileHandler methods def exists(self, path): transport, client = self._getClient() try: remote_path = self._getRemotePath(path) try: _attrs = client.stat(remote_path) return True except: return False finally: client.close() transport.stop_thread() def getSize(self, path): transport, client = self._getClient() try: remote_path = self._getRemotePath(path) try: attrs = client.stat(remote_path) return attrs.st_size except: return 0 finally: client.close() transport.stop_thread() def getFile(self, path, parent=None): client = None try: cache_path = self._getCachePath(path) remote_path = self._getRemotePath(path) try: if cache_path: copy_to_cache = True if os.path.exists(cache_path): cache_stats = os.stat(cache_path) if parent is not None: modified = long(time.mktime(IZopeDublinCore(parent).modified.timetuple())) copy_to_cache = cache_stats[os.path.stat.ST_MTIME] < modified else: transport, client = self._getClient() remote_stats = client.stat(remote_path) copy_to_cache = cache_stats[os.path.stat.ST_MTIME] < remote_stats.st_mtime if copy_to_cache: try: if client is None: transport, client = self._getClient() client.get(remote_path, cache_path) except: logger.warning(" >>> Can't read remote file (%s)" % remote_path) if not os.path.exists(cache_path): raise logger.warning(" > Using previously cached file...") f = open(cache_path, 'rb') else: transport, client = self._getClient() f = client.open(remote_path, 'rb') return f except: traceback.print_exc() return '' finally: if client is not None: client.close() transport.stop_thread() def readFile(self, path, parent=None): f = self.getFile(path, parent) if f is None: return '' try: return f.read() finally: f.close() def moveFile(self, source, dest): transport, client = self._getClient() try: remote_path = self._getRemotePath(dest) directories = remote_path.split(os.path.sep) current = '' for directory in directories[1:-1]: current += os.path.sep + directory try: _stat = client.stat(current) except: client.mkdir(current) client.put(source, remote_path) cache_path = self._getCachePath(dest) if cache_path: os.rename(source, cache_path) else: os.unlink(source) finally: client.close() transport.stop_thread() def copyFile(self, source, dest): transport, client = self._getClient() try: remote_path = self._getRemotePath(dest) directories = remote_path.split(os.path.sep) current = '' for directory in directories[1:-1]: current += os.path.sep + directory try: _stat = client.stat(current) except: client.mkdir(current) client.put(source, remote_path) finally: client.close() transport.stop_thread() def deleteFile(self, path): transport, client = self._getClient() try: remote_path = self._getRemotePath(path) try: client.unlink(remote_path) except: pass cache_path = self._getCachePath(path) if cache_path and os.path.exists(cache_path): os.unlink(cache_path) finally: client.close() transport.stop_thread()
ztfy.extfile
/ztfy.extfile-0.2.14.tar.gz/ztfy.extfile-0.2.14/src/ztfy/extfile/handler/sftp/__init__.py
__init__.py
__docformat__ = "restructuredtext" # import standard packages import os # import Zope3 interfaces # import local interfaces from ztfy.extfile.namechooser.interfaces import IExtFileNameChooserConfig # import Zope3 packages from zope.component import queryUtility, getAllUtilitiesRegisteredFor from zope.interface import implements # import local packages DEFAULT_TEMP_DIR = '/var/tmp' DEFAULT_BASE_DIR = '/var/local/zope/extfiles' class ExtFileConfig(object): """Global utility used to configure chooser of external file's name""" implements(IExtFileNameChooserConfig) name = u'' chooser = None _temp_path = DEFAULT_TEMP_DIR _base_path = DEFAULT_BASE_DIR def _getTempPath(self): return self._temp_path def _setTempPath(self, path): if not os.path.exists(path): os.makedirs(path) self._temp_path = path temp_path = property(_getTempPath, _setTempPath) def _getBasePath(self): return self._base_path def _setBasePath(self, path): if not os.path.exists(path): os.makedirs(path) self._base_path = path base_path = property(_getBasePath, _setBasePath) def getConfigs(): """Get list of available name choosers""" return getAllUtilitiesRegisteredFor(IExtFileNameChooserConfig) def getConfig(name=''): """Get configuration for a given name chooser""" config = queryUtility(IExtFileNameChooserConfig, name) if (config is None) and name: config = queryUtility(IExtFileNameChooserConfig) return config def getTempPath(config_name=''): """Get temp path for given name chooser""" config = getConfig(config_name) if config is not None: return config.temp_path return DEFAULT_TEMP_DIR def getBasePath(config_name=''): """Get base path for given name chooser""" config = getConfig(config_name) if config is not None: return config.base_path return DEFAULT_BASE_DIR def getFullPath(parent, extfile, name, config_name=''): """Get full path for specified extfile""" config = getConfig(config_name) if config is not None: base_path = config.base_path file_path = config.chooser.getName(parent, extfile, name) if file_path.startswith(os.path.sep): file_path = file_path[1:] return os.path.join(base_path, file_path) return None
ztfy.extfile
/ztfy.extfile-0.2.14.tar.gz/ztfy.extfile-0.2.14/src/ztfy/extfile/namechooser/config.py
config.py
==================== ZTFY.extfile package ==================== .. contents:: What is ztfy.extfile ? ====================== ztfy.extfile is a package which allows storing File and Image objects data outside of the Zope database (ZODB), into 'external' files. Files can be stored in the local file system, or remotely via protocols like SFTP or NFS (even HTTP is possible) ; an efficient cache system allows to store local copies of the remote files locally. Finally, external files can be stored via Blob objects, provided by the latest versions of the ZODB. How to use ztfy.extfile ? ========================= A set of ztfy.extfile usages are given as doctests in ztfy/extfile/doctests/README.txt.
ztfy.extfile
/ztfy.extfile-0.2.14.tar.gz/ztfy.extfile-0.2.14/docs/README.txt
README.txt
================= ztfy.file package ================= You may find documentation in: - Global README.txt: ztfy/ztfy.file/docs/README.txt - General: ztfy/ztfy.file/docs - Technical: ztfy/ztfy.file/doctest More informations can be found on ZTFY.org_ web site ; a decicated Trac environment is available on ZTFY.file_. This package is created and maintained by Thierry Florac_. .. _Thierry Florac: mailto:[email protected] .. _ZTFY.org: http://www.ztfy.org .. _ZTFY.file: http://trac.ztfy.org/ztfy.file
ztfy.file
/ztfy.file-0.3.13.tar.gz/ztfy.file-0.3.13/README.txt
README.txt
import os import shutil import sys import tempfile from optparse import OptionParser tmpeggs = tempfile.mkdtemp() usage = '''\ [DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options] Bootstraps a buildout-based project. Simply run this script in a directory containing a buildout.cfg, using the Python that you want bin/buildout to use. Note that by using --find-links to point to local resources, you can keep this script from going over the network. ''' parser = OptionParser(usage=usage) parser.add_option("-v", "--version", help="use a specific zc.buildout version") parser.add_option("-t", "--accept-buildout-test-releases", dest='accept_buildout_test_releases', action="store_true", default=False, help=("Normally, if you do not specify a --version, the " "bootstrap script and buildout gets the newest " "*final* versions of zc.buildout and its recipes and " "extensions for you. If you use this flag, " "bootstrap and buildout will get the newest releases " "even if they are alphas or betas.")) parser.add_option("-c", "--config-file", help=("Specify the path to the buildout configuration " "file to be used.")) parser.add_option("-f", "--find-links", help=("Specify a URL to search for buildout releases")) parser.add_option("--allow-site-packages", action="store_true", default=False, help=("Let bootstrap.py use existing site packages")) options, args = parser.parse_args() ###################################################################### # load/install setuptools try: if options.allow_site_packages: import setuptools import pkg_resources from urllib.request import urlopen except ImportError: from urllib2 import urlopen ez = {} exec(urlopen('https://bootstrap.pypa.io/ez_setup.py').read(), ez) if not options.allow_site_packages: # ez_setup imports site, which adds site packages # this will remove them from the path to ensure that incompatible versions # of setuptools are not in the path import site # inside a virtualenv, there is no 'getsitepackages'. # We can't remove these reliably if hasattr(site, 'getsitepackages'): for sitepackage_path in site.getsitepackages(): sys.path[:] = [x for x in sys.path if sitepackage_path not in x] setup_args = dict(to_dir=tmpeggs, download_delay=0) ez['use_setuptools'](**setup_args) import setuptools import pkg_resources # This does not (always?) update the default working set. We will # do it. for path in sys.path: if path not in pkg_resources.working_set.entries: pkg_resources.working_set.add_entry(path) ###################################################################### # Install buildout ws = pkg_resources.working_set cmd = [sys.executable, '-c', 'from setuptools.command.easy_install import main; main()', '-mZqNxd', tmpeggs] find_links = os.environ.get( 'bootstrap-testing-find-links', options.find_links or ('http://downloads.buildout.org/' if options.accept_buildout_test_releases else None) ) if find_links: cmd.extend(['-f', find_links]) setuptools_path = ws.find( pkg_resources.Requirement.parse('setuptools')).location requirement = 'zc.buildout' version = options.version if version is None and not options.accept_buildout_test_releases: # Figure out the most recent final version of zc.buildout. import setuptools.package_index _final_parts = '*final-', '*final' def _final_version(parsed_version): for part in parsed_version: if (part[:1] == '*') and (part not in _final_parts): return False return True index = setuptools.package_index.PackageIndex( search_path=[setuptools_path]) if find_links: index.add_find_links((find_links,)) req = pkg_resources.Requirement.parse(requirement) if index.obtain(req) is not None: best = [] bestv = None for dist in index[req.project_name]: distv = dist.parsed_version if _final_version(distv): if bestv is None or distv > bestv: best = [dist] bestv = distv elif distv == bestv: best.append(dist) if best: best.sort() version = best[-1].version if version: requirement = '=='.join((requirement, version)) cmd.append(requirement) import subprocess if subprocess.call(cmd, env=dict(os.environ, PYTHONPATH=setuptools_path)) != 0: raise Exception( "Failed to execute command:\n%s" % repr(cmd)[1:-1]) ###################################################################### # Import and run buildout ws.add_entry(tmpeggs) ws.require(requirement) import zc.buildout.buildout if not [a for a in args if '=' not in a]: args.append('bootstrap') # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args[0:0] = ['-c', options.config_file] zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs)
ztfy.file
/ztfy.file-0.3.13.tar.gz/ztfy.file-0.3.13/bootstrap.py
bootstrap.py
# import standard packages # import Zope3 interfaces from zope.app.file.interfaces import IFile from zope.lifecycleevent.interfaces import IObjectModifiedEvent from zope.schema.interfaces import IText, IBytes, IVocabularyTokenized # import local interfaces # import Zope3 packages from zope.interface import Interface, Attribute from zope.schema import TextLine, Text, Int, Choice, Tuple, Set, Object # import local packages from ztfy.file import _ # # File container interface # class IFilePropertiesContainer(Interface): """Marker interface used to define contents owning file properties""" class IFilePropertiesContainerAttributes(Interface): """Interface used to list attributes handling file properties""" attributes = Set(title=_("File attributes"), description=_("List of attributes handling file objects"), required=False, value_type=TextLine()) # # File field interface # class IHTMLField(IText): """HTML field interface""" class IFileField(IBytes): """File object field interface""" class IImageField(IFileField): """Image file object field interface""" class ICthumbImageField(IImageField): """Image file object with cthumb interface""" # # Extended file interface # class ILanguageVocabulary(IVocabularyTokenized): """Marker interface for file languages vocabulary""" class IExtendedFile(IFile): """An IFile interface with new attributes""" title = TextLine(title=_("Title"), description=_("Full file title"), required=False) description = Text(title=_("Description"), description=_("Full description, which can be displayed by several presentation templates"), required=False) savename = TextLine(title=_("Save file as..."), description=_("Default name under which the file can be saved"), required=False) language = Choice(title=_("Language"), description=_("File content's main language"), required=False, vocabulary='ZTFY languages') # # Image thumbnailer interface # class IThumbnailGeometry(Interface): """Base interface for IThumbnailGeometry infos""" position = Tuple(title=_("Thumbnail position"), description=_("Position of the square thumbnail, from original image coordinates"), required=False, value_type=Int(), min_length=2, max_length=2) size = Tuple(title=_("Thumbnail size"), description=_("Size of square thumbnail, from original image coordinates"), required=False, value_type=Int(), min_length=2, max_length=2) class IThumbnailer(Interface): """A thumbnailer is a utility used to generate image thumbnails""" order = Attribute(_("Thumbnailer choice order")) def createThumbnail(self, image, size, format=None): """Create a thumbnail for the given image Size is given as an (w,h) tuple """ def createSquareThumbnail(self, image, size, source=None, format=None): """Create a square thumbnail from a selection on the given image Source is given as a (x,y, w,h) tuple """ class IWatermarker(Interface): """A watermarker is a utility used to add watermarks above images""" order = Attribute(_("Watermarker choice order")) def addWatermark(self, image, mark, position='scale', opacity=1, format=None): """Add watermark and returns a new image""" class ICthumbImageFieldData(Interface): """Cthumb image field data""" value = Attribute(_("Image field value")) geometry = Object(title=_("Value geometry"), schema=IThumbnailGeometry) # # Image display interface # DEFAULT_DISPLAYS = { 'thumb': 128, 'cthumb': 128 } class IImageDisplayInfo(Interface): """Image display interface properties""" def getImageSize(self): """Get original image size""" def getDisplaySize(self, display, forced=False): """Get size for the given display If forced is True, the display can be larger than the original source image. """ def getDisplayName(self, display=None, width=None, height=None): """Get matching name for the given size or display""" def getDisplay(self, display, format=None): """Get requested display Display can be specified via : - a name - a width, with wXXX - a height, with hXXX - a size, with XXXxYYY """ class IImageDisplayWriter(Interface): """Image display writing interface""" def clearDisplay(self, display): """Clear selected display""" def clearDisplays(self): """Clear all generated displays""" class IImageDisplay(IImageDisplayInfo, IImageDisplayWriter): """Marker interface for image display Displays are used to generate images thumbnails, as long as the requested size is smaller than the original image size """ class IImageTag(Interface): """Generate HTML <img> tags for an image or display""" def getTag(self, display=None, alt=None, title=None, width=None, height=None, **kw): """Generate HTML tag for given display""" class IImageModifiedEvent(IObjectModifiedEvent): """Event fired when an image property is modified""" # # Archives management # class IArchiveExtractor(Interface): """Archive contents extractor""" def initialize(self, data, mode='r'): """Initialize extractor for given data""" def getContents(self): """Get list of archive contents Each result item is a tuple containing data and file name """
ztfy.file
/ztfy.file-0.3.13.tar.gz/ztfy.file-0.3.13/src/ztfy/file/interfaces.py
interfaces.py
# import standard packages from cStringIO import StringIO from PIL import Image, ImageFilter, ImageEnhance # import Zope3 interfaces from zope.app.file.interfaces import IImage # import local interfaces from ztfy.file.interfaces import IThumbnailer, IThumbnailGeometry, IWatermarker, DEFAULT_DISPLAYS # import Zope3 packages from zope.interface import implements # import local packages class PILThumbnailer(object): """PIL thumbnailer utility""" implements(IThumbnailer) order = 50 def createThumbnail(self, image, size, format=None): # init image if IImage.providedBy(image): image = image.data image = Image.open(StringIO(image)) # check format if not format: format = image.format format = format.upper() if format not in ('GIF', 'JPEG', 'PNG'): format = 'JPEG' # check mode if image.mode == 'P': image = image.convert('RGBA') # generate thumbnail new = StringIO() image.resize(size, Image.ANTIALIAS).filter(ImageFilter.SHARPEN).save(new, format) return new.getvalue(), format.lower() def createSquareThumbnail(self, image, size, source=None, format=None): # init image if IImage.providedBy(image): img = image.data else: img = image img = Image.open(StringIO(img)) # check format if not format: format = img.format format = format.upper() if format not in ('GIF', 'JPEG', 'PNG'): format = 'JPEG' # check mode if img.mode == 'P': img = img.convert('RGBA') # compute thumbnail size img_width, img_height = img.size thu_width, thu_height = size, size ratio = max(img_width * 1.0 / thu_width, img_height * 1.0 / thu_height) if source: x, y, w, h = source else: geometry = IThumbnailGeometry(image, None) if geometry is None: x, y, w, h = 0, 0, img_width, img_height else: (x, y), (w, h) = geometry.position, geometry.size box = (int(x * ratio), int(y * ratio), int((x + w) * ratio), int((y + h) * ratio)) # generate thumbnail new = StringIO() img.crop(box) \ .resize((DEFAULT_DISPLAYS['cthumb'], DEFAULT_DISPLAYS['cthumb']), Image.ANTIALIAS) \ .filter(ImageFilter.SHARPEN) \ .save(new, format) return new.getvalue(), format.lower() class PILWatermarker(object): """PIL watermarker utility""" implements(IWatermarker) order = 50 def _reduce_opacity(self, image, opacity): """Returns an image with reduced opacity.""" assert 0 <= opacity <= 1 if image.mode != 'RGBA': image = image.convert('RGBA') else: image = image.copy() alpha = image.split()[3] alpha = ImageEnhance.Brightness(alpha).enhance(opacity) image.putalpha(alpha) return image def addWatermark(self, image, mark, position='scale', opacity=1, format=None): """Adds a watermark to an image and return a new image""" # init image if IImage.providedBy(image): image = image.data image = Image.open(StringIO(image)) # check format if not format: format = image.format format = format.upper() if format not in ('GIF', 'JPEG', 'PNG'): format = 'JPEG' # check RGBA mode if image.mode != 'RGBA': image = image.convert('RGBA') # init watermark if IImage.providedBy(mark): mark = mark.data mark = Image.open(StringIO(mark)) if opacity < 1: mark = self._reduce_opacity(mark, opacity) # create a transparent layer the size of the image and draw the # watermark in that layer. layer = Image.new('RGBA', image.size, (0, 0, 0, 0)) if position == 'tile': for y in range(0, image.size[1], mark.size[1]): for x in range(0, image.size[0], mark.size[0]): layer.paste(mark, (x, y)) elif position == 'scale': # scale, but preserve the aspect ratio ratio = min(float(image.size[0]) / mark.size[0], float(image.size[1]) / mark.size[1]) w = int(mark.size[0] * ratio) h = int(mark.size[1] * ratio) mark = mark.resize((w, h)) layer.paste(mark, ((image.size[0] - w) / 2, (image.size[1] - h) / 2)) else: layer.paste(mark, position) # composite the watermark with the layer new = StringIO() Image.composite(layer, image, layer).save(new, format) return new.getvalue(), format.lower()
ztfy.file
/ztfy.file-0.3.13.tar.gz/ztfy.file-0.3.13/src/ztfy/file/pil.py
pil.py
# import standard packages from cStringIO import StringIO from persistent import Persistent from persistent.dict import PersistentDict from PIL import Image as PIL_Image # import Zope3 interfaces from zope.annotation.interfaces import IAnnotations from zope.app.file.interfaces import IImage from zope.lifecycleevent.interfaces import IObjectModifiedEvent # import local interfaces from ztfy.file.interfaces import DEFAULT_DISPLAYS from ztfy.file.interfaces import IImageDisplay, IThumbnailGeometry, IThumbnailer, IImageModifiedEvent # import Zope3 packages from zope.app.file import Image from zope.component import adapter, adapts, queryUtility, getAllUtilitiesRegisteredFor from zope.event import notify from zope.interface import implements from zope.lifecycleevent import ObjectCreatedEvent, ObjectRemovedEvent from zope.location import locate # import local packages try: from ztfy.extfile.blob import BlobImage except: BlobImage = Image IMAGE_DISPLAY_ANNOTATIONS_KEY = 'ztfy.file.display' class ImageDisplayAdapter(object): """IImageDisplay adapter""" adapts(IImage) implements(IImageDisplay) def __init__(self, context): self.context = context annotations = IAnnotations(context) displays = annotations.get(IMAGE_DISPLAY_ANNOTATIONS_KEY) if displays is None: displays = annotations[IMAGE_DISPLAY_ANNOTATIONS_KEY] = PersistentDict() self.displays = displays @property def image(self): return self.context def getImageSize(self): width, height = self.context.getImageSize() if (width < 0) or (height < 0): # Not a web format => try to use PIL to get image size try: pil_image = PIL_Image.open(StringIO(self.context.data)) width, height = pil_image.size except IOError: pass return width, height def getDisplaySize(self, display, forced=False): if display == 'cthumb': return DEFAULT_DISPLAYS[display], DEFAULT_DISPLAYS[display] width, height = self.getImageSize() if display in DEFAULT_DISPLAYS: h = w = DEFAULT_DISPLAYS[display] w_ratio = 1.0 * width / w h_ratio = 1.0 * height / h elif display.lower().startswith('w'): w = int(display[1:]) w_ratio = 1.0 * width / w h_ratio = 0.0 elif display.lower().startswith('h'): h = int(display[1:]) h_ratio = 1.0 * height / h w_ratio = 0.0 else: w, h = tuple([int(x) for x in display.split('x')]) w_ratio = 1.0 * width / w h_ratio = 1.0 * height / h if forced: ratio = max(w_ratio, h_ratio) else: ratio = max(1.0, w_ratio, h_ratio) return int(width / ratio), int(height / ratio) def getDisplayName(self, display=None, width=None, height=None): if display: if display == 'cthumb': return display return 'w%d' % self.getDisplaySize(display)[0] return '%dx%d' % (width, height) def createDisplay(self, display, format=None): # check if display is already here display = self.getDisplayName(display) if display in self.displays: return self.displays[display] # check display size with original image size width, height = self.getDisplaySize(display) if (width, height) == self.getImageSize(): return self.image # look for thumbnailer thumbnailer = queryUtility(IThumbnailer) if thumbnailer is None: thumbnailers = sorted(getAllUtilitiesRegisteredFor(IThumbnailer), key=lambda x: x.order) if thumbnailers: thumbnailer = thumbnailers[0] # generate thumbnail if thumbnailer is not None: if display == 'cthumb': thumbnail = thumbnailer.createSquareThumbnail(self.image, DEFAULT_DISPLAYS[display], format=format) else: thumbnail = thumbnailer.createThumbnail(self.image, (width, height), format=format) if isinstance(thumbnail, tuple): thumbnail, format = thumbnail else: format = 'jpeg' if (width > 256) or (height > 256): img_factory = BlobImage else: img_factory = Image img = self.displays[display] = img_factory(thumbnail) notify(ObjectCreatedEvent(img)) locate(img, self.context, '++display++%s.%s' % (display, format)) return img return self.image def getDisplay(self, display, format=None): if '.' in display: display, format = display.split('.', 1) if display in self.displays: return self.displays[display] return self.createDisplay(display, format) def clearDisplay(self, display): if display in self.displays: img = self.displays[display] notify(ObjectRemovedEvent(img)) del self.displays[display] def clearDisplays(self): [self.clearDisplay(display) for display in self.displays.keys()] IMAGE_THUMBNAIL_ANNOTATIONS_KEY = 'ztfy.file.thumbnail' class ThumbnailGeometry(Persistent): implements(IThumbnailGeometry) position = (None, None) size = (None, None) def __init__(self, position=None, size=None): if position is not None: self.position = position if size is not None: self.size = size class ImageThumbnailGeometryAdapter(object): """ISquareThumbnail adapter""" adapts(IImage) implements(IThumbnailGeometry) def __init__(self, context): self.image = context annotations = IAnnotations(context) geometry = annotations.get(IMAGE_THUMBNAIL_ANNOTATIONS_KEY) if geometry is None: geometry = annotations[IMAGE_THUMBNAIL_ANNOTATIONS_KEY] = ThumbnailGeometry() self._getGeometry(geometry) self.geometry = geometry def _getGeometry(self, geometry): w, h = IImageDisplay(self.image).getDisplaySize('thumb') size = min(w, h) geometry.size = (size, size) if w > h: geometry.position = (int((w - size) / 2), 0) else: geometry.position = (0, int((h - size) / 2)) def _getPosition(self): return self.geometry.position def _setPosition(self, value): if value != self.geometry.position: self.geometry.position = value IImageDisplay(self.image).clearDisplay('cthumb') position = property(_getPosition, _setPosition) def _getSize(self): return self.geometry.size def _setSize(self, value): if value != self.geometry.size: self.geometry.size = value IImageDisplay(self.image).clearDisplay('cthumb') size = property(_getSize, _setSize) @adapter(IImage, IImageModifiedEvent) def handleModifiedImage(image, event): IImageDisplay(image).clearDisplays() @adapter(IImage, IObjectModifiedEvent) def handleModifiedImageData(image, event): if 'data' in event.descriptions[0].attributes: IImageDisplay(image).clearDisplays()
ztfy.file
/ztfy.file-0.3.13.tar.gz/ztfy.file-0.3.13/src/ztfy/file/display.py
display.py
# import standard packages # import Zope3 interfaces from zope.catalog.interfaces import ICatalog from zope.lifecycleevent.interfaces import IObjectCopiedEvent, IObjectAddedEvent, IObjectRemovedEvent # import local interfaces from ztfy.file.interfaces import IFilePropertiesContainer, IFilePropertiesContainerAttributes # import Zope3 packages from ZODB.blob import Blob from zope.component import adapter, getUtilitiesFor from zope.event import notify from zope.lifecycleevent import ObjectRemovedEvent from zope.location import locate # import local packages from ztfy.extfile.blob import BaseBlobFile from ztfy.utils import catalog @adapter(IFilePropertiesContainer, IObjectCopiedEvent) def handleCopiedFilePropertiesContainer(object, event): """When a file properties container is copied, we have to tag it for indexation and update it's blobs Effective file indexation will be done only after content have been added to it's new parent container""" object._v_copied_file = True # When an external file container is copied, we have to update it's blobs source = event.original for attr in IFilePropertiesContainerAttributes(source).attributes: value = getattr(source, attr, None) if isinstance(value, BaseBlobFile): getattr(object, attr)._blob = Blob() getattr(object, attr).data = value.data @adapter(IFilePropertiesContainer, IObjectAddedEvent) def handleAddedFilePropertiesContainer(object, event): """When a file properties container is added, we must index it's attributes""" if not hasattr(object, '_v_copied_file'): return for _name, catalog_util in getUtilitiesFor(ICatalog): for attr in IFilePropertiesContainerAttributes(object).attributes: value = getattr(object, attr, None) if value is not None: locate(value, object, value.__name__) catalog.indexObject(value, catalog_util) delattr(object, '_v_copied_file') @adapter(IFilePropertiesContainer, IObjectRemovedEvent) def handleRemovedFilePropertiesContainer(object, event): """When a file properties container is added, we must index it's attributes""" for _name, catalog_util in getUtilitiesFor(ICatalog): for attr in IFilePropertiesContainerAttributes(object).attributes: value = getattr(object, attr, None) if value is not None: notify(ObjectRemovedEvent(value)) catalog.unindexObject(value, catalog_util)
ztfy.file
/ztfy.file-0.3.13.tar.gz/ztfy.file-0.3.13/src/ztfy/file/events.py
events.py
# import standard packages import mimetypes # import Zope3 interfaces from z3c.form.interfaces import NOT_CHANGED from zope.app.file.interfaces import IFile, IImage from zope.location.interfaces import ILocation from zope.schema.interfaces import IField # import local interfaces from ztfy.file.interfaces import IFilePropertiesContainer, IFilePropertiesContainerAttributes, ICthumbImageFieldData, \ IThumbnailGeometry # import Zope3 packages from zope.app.file import File, Image from zope.event import notify from zope.interface import alsoProvides from zope.lifecycleevent import ObjectCreatedEvent, ObjectAddedEvent, ObjectRemovedEvent from zope.location import locate from zope.publisher.browser import FileUpload from zope.security.proxy import removeSecurityProxy # import local packages from ztfy.extfile import getMagicContentType from ztfy.file import _ _marker = object() class FileProperty(object): """Property class used to handle files""" interface = IFile def __init__(self, field, name=None, klass=File, img_klass=None, **args): if not IField.providedBy(field): raise ValueError, _("Provided field must implement IField interface...") if name is None: name = field.__name__ self.__field = field self.__name = name self.__klass = klass self.__img_klass = img_klass self.__args = args def __get__(self, instance, klass): if instance is None: return self value = instance.__dict__.get(self.__name, _marker) if value is _marker: field = self.__field.bind(instance) value = getattr(field, 'default', _marker) if value is _marker: raise AttributeError(self.__name) return value def __set__(self, instance, value): if value is NOT_CHANGED: return if value is not None: filename = None if isinstance(value, tuple): value, filename = value if isinstance(value, FileUpload): value = value.read() if not self.interface.providedBy(value): content_type = getMagicContentType(value) or 'text/plain' if filename and content_type.startswith('text/'): content_type = mimetypes.guess_type(filename)[0] or content_type if (self.__img_klass is not None) and content_type.startswith('image/'): f = self.__img_klass(**self.__args) else: f = self.__klass(**self.__args) notify(ObjectCreatedEvent(f)) f.data = value f.contentType = content_type value = f field = self.__field.bind(instance) field.validate(value) if field.readonly and instance.__dict__.has_key(self.__name): raise ValueError(self.__name, _("Field is readonly")) old_value = instance.__dict__.get(self.__name, _marker) if old_value != value: if (old_value is not _marker) and (old_value is not None): notify(ObjectRemovedEvent(old_value)) if value is not None: filename = '++file++%s' % self.__name if value.contentType: filename += mimetypes.guess_extension(value.contentType) or '' locate(value, removeSecurityProxy(instance), filename) alsoProvides(value, ILocation) alsoProvides(instance, IFilePropertiesContainer) IFilePropertiesContainerAttributes(instance).attributes.add(self.__name) notify(ObjectAddedEvent(value, instance, filename)) instance.__dict__[self.__name] = value def __getattr__(self, name): return getattr(self.__field, name) class ImageProperty(FileProperty): """Property class used to handle images""" interface = IImage def __init__(self, field, name=None, klass=Image, img_klass=None, **args): super(ImageProperty, self).__init__(field, name, klass, img_klass, **args) def __set__(self, instance, value): data = ICthumbImageFieldData(value, None) if data is not None: value = data.value geom = data.geometry super(ImageProperty, self).__set__(instance, value) if data is not None: new_value = instance.__dict__.get(self.__name, _marker) if new_value is not _marker: geometry = IThumbnailGeometry(new_value) if geometry is not None: geometry.position = geom.position geometry.size = geom.size
ztfy.file
/ztfy.file-0.3.13.tar.gz/ztfy.file-0.3.13/src/ztfy/file/property.py
property.py
# import standard packages from datetime import datetime from fanstatic import Library, Resource import re # import Zope3 interfaces from transaction.interfaces import ITransactionManager from zope.dublincore.interfaces import IZopeDublinCore # import local interfaces from ztfy.extfile.interfaces import IBaseBlobFile # import Zope3 packages import zope.datetime # import local packages from ztfy.jqueryui import jquery_imgareaselect from zope.security.proxy import removeSecurityProxy library = Library('ztfy.file', 'resources') ztfy_file = Resource(library, 'js/ztfy.file.js', minified='js/ztfy.file.min.js', depends=[jquery_imgareaselect], bottom=True) _rx_range = re.compile('bytes *= *(\d*) *- *(\d*)', flags=re.I) MAX_RANGE_LENGTH = 1 << 21 # 2 Mb class Range(object): """Range header value parser Copied from Pyramid... """ def __init__(self, start, end): self.start = start self.end = end @classmethod def parse(cls, request): range = request.getHeader('Range') if range is None: return None m = _rx_range.match(range) if not m: return None start, end = m.groups() if not start: return cls(-int(end), None) start = int(start) if not end: return cls(start, None) end = int(end) + 1 if start >= end: return None return cls(start, end) class FileView(object): def show(self): """This is just a refactoring of original zope.app.file.browser.file.FileView class, which according to me didn't handle last modification time correctly... """ context = self.context request = self.request response = request.response if request is not None: header = response.getHeader('Content-Type') if header is None: response.setHeader('Content-Type', context.contentType) response.setHeader('Content-Length', context.getSize()) try: modified = IZopeDublinCore(context).modified except TypeError: modified = None if modified is None or not isinstance(modified, datetime): return context.data # check for last modification date header = request.getHeader('If-Modified-Since', None) lmt = long(zope.datetime.time(modified.isoformat())) if header is not None: header = header.split(';')[0] try: mod_since = long(zope.datetime.time(header)) except: mod_since = None if mod_since is not None: if lmt <= mod_since: response.setStatus(304) return '' response.setHeader('Last-Modified', zope.datetime.rfc1123_date(lmt)) # check content range on blobs if IBaseBlobFile.providedBy(context): # Commit transaction to avoid uncommitted blobs error while generating display ITransactionManager(removeSecurityProxy(context)).get().commit() body_file = removeSecurityProxy(context.getBlob(mode='c')) body_length = context.getSize() range = Range.parse(request) if range is not None: response.setStatus(206) # Partial content range_start = range.start or 0 body_file.seek(range_start) if 'Firefox' in request.getHeader('User-Agent'): range_end = range.end or body_length response.setHeader('Content-Range', 'bytes {first}-{last}/{len}'.format(first=range_start, last=range_end - 1, len=body_length)) response.setHeader('Content-Length', range_end - range_start) return body_file else: range_end = range.end or min(body_length, range_start + MAX_RANGE_LENGTH) ranged_body = body_file.read(range_end - range_start) response.setHeader('Content-Range', 'bytes {first}-{last}/{len}'.format(first=range_start, last=range_start + len(ranged_body) - 1, len=body_length)) return ranged_body else: return body_file else: return context.data
ztfy.file
/ztfy.file-0.3.13.tar.gz/ztfy.file-0.3.13/src/ztfy/file/browser/__init__.py
__init__.py
# import standard packages # import Zope3 interfaces from z3c.form.interfaces import ITextAreaWidget, IFileWidget as IFileWidgetBase # import local interfaces from ztfy.file.interfaces import IThumbnailGeometry # import Zope3 packages from zope.interface import Interface from zope.schema import Bool, Dict, Text, TextLine # import local packages from ztfy.file import _ class IHTMLWidgetSettings(Interface): """HTML widget styling interface""" plugins = TextLine(title=_("TinyMCE plugins"), readonly=True) style_formats = Text(title=_("TinyMCE style_formats setting"), readonly=True) invalid_elements = TextLine(title=_("TinyMCE invalid_elements setting"), readonly=True) class IHTMLWidget(ITextAreaWidget): """IHTMLField widget""" options = Dict(title=_("TinyMCE editor options"), readonly=True) options_as_text = Text(title=_("String output of TinyMCE editor options"), readonly=True) class IFileWidget(IFileWidgetBase): """IFile base widget""" downloadable = Bool(title=_("Content can be downloaded ?"), description=_("It True, current file content can be downloaded"), required=True, default=True) deletable = Bool(title=_("Content can be deleted ?"), description=_("If True, current file content can be deleted"), required=True, readonly=True, default=False) deleted = Bool(title=_("Content is deleted ?"), description=_("If True, we ask for content to be deleted..."), required=True, readonly=True, default=False) class IImageWidget(IFileWidget): """IImage base widget""" class ICthumbImageWidget(IImageWidget, IThumbnailGeometry): """IImage widget with cthumb selection"""
ztfy.file
/ztfy.file-0.3.13.tar.gz/ztfy.file-0.3.13/src/ztfy/file/browser/widget/interfaces.py
interfaces.py
# import standard packages from cStringIO import StringIO from PIL import Image # import Zope3 interfaces from z3c.form.interfaces import IWidget, NOT_CHANGED # import local interfaces from ztfy.file.interfaces import IFileField, IImageField, ICthumbImageField, ICthumbImageFieldData # import Zope3 packages from z3c.form.converter import FileUploadDataConverter, FormatterValidationError from zope.component import adapts from zope.interface import implements from zope.publisher.browser import FileUpload # import local packages from ztfy.file.display import ThumbnailGeometry from ztfy.file import _ class FileFieldDataConverter(FileUploadDataConverter): """Data converter for FileField fields""" adapts(IFileField, IWidget) def toWidgetValue(self, value): if isinstance(value, tuple): value = value[0] return super(FileFieldDataConverter, self).toWidgetValue(value) def toFieldValue(self, value): if isinstance(value, FileUpload): filename = value.filename else: filename = None result = super(FileFieldDataConverter, self).toFieldValue(value) if result is NOT_CHANGED: widget = self.widget if widget.deleted: return None else: return result else: return filename and (result, filename) or result class ImageFieldDataConverter(FileFieldDataConverter): """Data converter for ImageField fields""" adapts(IImageField, IWidget) def toFieldValue(self, value): result = super(ImageFieldDataConverter, self).toFieldValue(value) test_result = isinstance(result, tuple) and result[0] or result if (test_result is not None) and (test_result is not NOT_CHANGED): try: Image.open(StringIO(test_result)) except: raise FormatterValidationError(_("Given file is not in a recognized image format"), value) return result class CthumbImageFieldData(object): implements(ICthumbImageFieldData) def __init__(self, value, geometry): self.value = value self.geometry = geometry def __nonzero__(self): return bool(self.value) class CthumbImageFieldDataConverter(FileFieldDataConverter): """Data converter for CthumbImageField fields""" adapts(ICthumbImageField, IWidget) def toFieldValue(self, value): result = super(CthumbImageFieldDataConverter, self).toFieldValue(value) widget = self.widget return CthumbImageFieldData(result, ThumbnailGeometry(widget.position, widget.size))
ztfy.file
/ztfy.file-0.3.13.tar.gz/ztfy.file-0.3.13/src/ztfy/file/browser/widget/converter.py
converter.py
# import standard packages # import Zope3 interfaces from z3c.form.interfaces import IFieldWidget, NOT_CHANGED # import local interfaces from ztfy.baseskin.layer import IBaseSkinLayer from ztfy.file.browser.widget.interfaces import IHTMLWidget, IHTMLWidgetSettings, IFileWidget, IImageWidget, ICthumbImageWidget from ztfy.file.interfaces import IThumbnailGeometry, IImageDisplay, IHTMLField, IFileField, IImageField, ICthumbImageField # import Zope3 packages from z3c.form.browser.file import FileWidget as FileWidgetBase from z3c.form.browser.textarea import TextAreaWidget from z3c.form.widget import FieldWidget from zope.component import adapter, queryMultiAdapter from zope.interface import implementer, implementsOnly from zope.schema.fieldproperty import FieldProperty # import local packages from ztfy.file.browser import ztfy_file from ztfy.jqueryui import jquery_fancybox, jquery_tinymce from ztfy.file import _ MCE_OPT_PREFIX = "mce_" MCE_OPT_PREFIX_LEN = len(MCE_OPT_PREFIX) class HTMLWidget(TextAreaWidget): """HTML input widget""" implementsOnly(IHTMLWidget) cols = 80 rows = 12 title = _("Click textarea to activate HTML editor !") mce_mode = 'none' mce_editor_selector = 'tiny_mce' mce_theme = 'advanced' mce_plugins = 'safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template' mce_theme_advanced_buttons1 = 'bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect' mce_theme_advanced_buttons2 = 'cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor' mce_theme_advanced_buttons3 = 'tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen' mce_theme_advanced_buttons4 = 'insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak' mce_theme_advanced_toolbar_location = 'top' mce_theme_advanced_toolbar_align = 'left' mce_theme_advanced_statusbar_location = 'bottom' mce_theme_advanced_resizing = True def render(self): jquery_tinymce.need() return TextAreaWidget.render(self) @property def options(self): options = {} attrs = dir(self) for attr in (a for a in attrs if a.startswith(MCE_OPT_PREFIX)): value = getattr(self, attr, None) value = value == True and 'true' or value == False and 'false' or value if value is not None: options[attr[MCE_OPT_PREFIX_LEN:]] = value adapter = queryMultiAdapter((self.field, self.form, self.request), IHTMLWidgetSettings) if adapter is not None: attrs = dir(adapter) for attr in (a for a in attrs if a.startswith(MCE_OPT_PREFIX)): value = getattr(adapter, attr, None) value = value == True and 'true' or value == False and 'false' or value if value is not None: options[attr[MCE_OPT_PREFIX_LEN:]] = value return options @property def options_as_text(self): return ';'.join(('%s=%s' % (a, v) for a, v in self.options.items())) @adapter(IHTMLField, IBaseSkinLayer) @implementer(IFieldWidget) def HTMLFieldWidget(field, request): """IFieldWidget factory for HTMLField""" return FieldWidget(field, HTMLWidget(request)) class FileWidget(FileWidgetBase): """File input widget""" implementsOnly(IFileWidget) downloadable = FieldProperty(IFileWidget['downloadable']) @property def current_value(self): if self.form.ignoreContext: return None return self.field.get(self.context) @property def deletable(self): if self.required: return False if self.value is NOT_CHANGED: return bool(self.current_value) else: return bool(self.value) @property def deleted(self): if self.lang: name, _ignore = self.name.split(':') return self.request.form.get(name + '_' + self.lang + '__delete', None) == 'on' return self.request.form.get(self.name + '__delete', None) == 'on' @adapter(IFileField, IBaseSkinLayer) @implementer(IFieldWidget) def FileFieldWidget(field, request): """IFieldWidget factory for FileField""" return FieldWidget(field, FileWidget(request)) class ImageWidget(FileWidget): """Image input widget""" implementsOnly(IImageWidget) def render(self): jquery_fancybox.need() return super(ImageWidget, self).render() @adapter(IImageField, IBaseSkinLayer) @implementer(IFieldWidget) def ImageFieldWidget(field, request): """IFieldWidget factory for ImageField""" return FieldWidget(field, ImageWidget(request)) class CthumbImageWidget(ImageWidget): """Image input widget with cthumb selection""" implementsOnly(ICthumbImageWidget) def render(self): try: self.widget_value = self.current_value except: self.widget_value = None ztfy_file.need() return super(CthumbImageWidget, self).render() @property def adapter(self): return IImageDisplay(self.widget_value, None) @property def geometry(self): return IThumbnailGeometry(self.widget_value, None) @property def position(self): if self.lang: name, _ignore = self.name.split(':') return (int(round(float(self.request.form.get(name + '_' + self.lang + '__x', 0)))), int(round(float(self.request.form.get(name + '_' + self.lang + '__y', 0))))) return (int(round(float(self.request.form.get(self.name + '__x', 0)))), int(round(float(self.request.form.get(self.name + '__y', 0))))) @property def size(self): if self.lang: name, _ignore = self.name.split(':') return (int(round(float(self.request.form.get(name + '_' + self.lang + '__w', 0)))), int(round(float(self.request.form.get(name + '_' + self.lang + '__h', 0))))) return (int(round(float(self.request.form.get(self.name + '__w', 0)))), int(round(float(self.request.form.get(self.name + '__h', 0))))) @adapter(ICthumbImageField, IBaseSkinLayer) @implementer(IFieldWidget) def CthumbImageFieldWidget(field, request): """IFieldWidget factory for ImageField""" return FieldWidget(field, CthumbImageWidget(request))
ztfy.file
/ztfy.file-0.3.13.tar.gz/ztfy.file-0.3.13/src/ztfy/file/browser/widget/__init__.py
__init__.py
================= ztfy.file package ================= .. contents:: What is ztfy.file ? =================== ztfy.file is a set of classes to be used with Zope3 application server. The purpose of this package is to handle : - custom schema fields with their associated properties and browser widgets to automatically handle fields as external files - automatically handle generation of images thumbnails for any image ; these thumbnails are accessed via a custom namespace ("++display++w128.jpeg" for example to get a thumbnail of 128 pixels width) and are stored via images annotations - allow selection of a square part of a thumbnail to be used as a "mini-square thumbnail". Square thumbnails selection is based on JQuery package extensions, so the ztfy.jqueryui is required to use all functions of ztfy.file package. How to use ztfy.file ? ====================== A set of ztfy.file usages are given as doctests in ztfy/file/doctests/README.txt
ztfy.file
/ztfy.file-0.3.13.tar.gz/ztfy.file-0.3.13/docs/README.txt
README.txt
==================== ztfy.gallery package ==================== You may find documentation in: - Global README.txt: ztfy/gallery/docs/README.txt - General: ztfy/gallery/docs - Technical: ztfy/gallery/doctest More informations can be found on ZTFY.org_ web site ; a decicated Trac environment is available on ZTFY.gallery_. This package is created and maintained by Thierry Florac_. .. _Thierry Florac: mailto:[email protected] .. _ZTFY.org: http://www.ztfy.org .. _ZTFY.gallery: http://trac.ztfy.org/ztfy.gallery
ztfy.gallery
/ztfy.gallery-0.4.1.tar.gz/ztfy.gallery-0.4.1/README.txt
README.txt
__docformat__ = "restructuredtext" # import standard packages # import Zope3 interfaces from zope.container.interfaces import IContained # import local interfaces from ztfy.base.interfaces.container import IOrderedContainer from ztfy.blog.interfaces.paragraph import IParagraphInfo, IParagraphWriter, IParagraph from ztfy.i18n.interfaces import II18nAttributesAware # import Zope3 packages from zope.container.constraints import contains, containers from zope.interface import Interface from zope.schema import Int, Bool, Text, TextLine, URI, Choice, List, Dict, Object # import local packages from ztfy.file.schema import ImageField, FileField from ztfy.i18n.schema import I18nText, I18nTextLine, I18nImage from ztfy.utils.encoding import EncodingField from ztfy.gallery import _ class IGalleryNamespaceTarget(Interface): """Marker interface for targets handling '++gallery++' namespace traverser""" class IGalleryImageBaseInfo(II18nAttributesAware): """Gallery image base interface""" title = I18nTextLine(title=_("Title"), description=_("Image's title"), required=False) description = I18nText(title=_("Description"), description=_("Short description of the image"), required=False) class IGalleryImageInfo(IGalleryImageBaseInfo): """Gallery image infos interface""" credit = TextLine(title=_("Author credit"), description=_("Credit and copyright notices of the image"), required=False) image = ImageField(title=_("Image data"), description=_("Current content of the image"), required=True) image_id = TextLine(title=_("Image ID"), description=_("Unique identifier of this image in the whole collection"), required=False) visible = Bool(title=_("Visible image ?"), description=_("Select 'No' to hide this image"), required=True, default=True) def title_or_id(): """Get image's title or ID""" class IGalleryImage(IGalleryImageInfo, IContained): """Gallery image full interface""" containers('ztfy.gallery.interfaces.IGalleryContainer') class IGalleryImageExtension(Interface): """Gallery image extension info""" title = TextLine(title=_("Extension title"), required=True) url = TextLine(title=_("Extension view URL"), required=True) icon = URI(title=_("Extension icon URL"), required=True) weight = Int(title=_("Extension weight"), required=True, default=50) class IGalleryContainerInfo(Interface): """Gallery container base interface""" def getVisibleImages(): """Get visible images in ordered list""" class IGalleryContainer(IGalleryContainerInfo, IOrderedContainer, IGalleryNamespaceTarget): """Gallery images container interface""" contains(IGalleryImage) class IGalleryContainerTarget(IGalleryNamespaceTarget): """Marker interface for gallery images container target""" class IGalleryManagerPaypalInfo(II18nAttributesAware): """Global Paypal informations for site manager""" paypal_enabled = Bool(title=_("Enable Paypal payments"), description=_("Enable or disable Paypal payments globally"), required=True, default=False) paypal_currency = TextLine(title=_("Paypal currency"), description=_("Currency used for Paypal exchanges"), required=False, max_length=3, default=u'EUR') paypal_button_id = TextLine(title=_("Paypal button ID"), description=_("Internal number of Paypal registered payment button"), required=False) paypal_format_options = I18nText(title=_("'Format' options"), description=_("Enter 'Format' options values ; values and labels may be separated by a '|'"), required=False) paypal_options_label = I18nTextLine(title=_("'Options' label"), description=_("Label applied to 'Options' selection box"), required=False) paypal_options_options = I18nText(title=_("'Options' options"), description=_("Enter 'Options' options values ; values and labels may be separated by '|'"), required=False) paypal_image_field_name = TextLine(title=_("Image ID field name"), description=_("Paypal ID of hidden field containing image ID"), required=False) paypal_image_field_label = I18nTextLine(title=_("Image ID field label"), description=_("Paypal label of field containing image ID"), required=False) add_to_basket_button = I18nImage(title=_("'Add to basket' image"), description=_("Image containing 'Add to basket' link"), required=False) see_basket_button = I18nImage(title=_("'See basket' image"), description=_("Image containing 'See basket' link"), required=False) paypal_pkcs_key = Text(title=_("Paypal basket PKCS key"), description=_("Full PKCS key used to access Paypal basket"), required=False) class IGalleryImagePaypalInfo(II18nAttributesAware): """Gallery image Paypal informations for a single image""" paypal_enabled = Bool(title=_("Enable Paypal payments"), description=_("Enable or disable Paypal payments for this image"), required=True, default=True) paypal_disabled_message = I18nText(title=_("Paypal disabled message"), description=_("Message displayed when Paypal is disabled for this picture"), required=False) # # Gallery paragraphs management # class IGalleryParagraphRenderer(Interface): """Gallery paragraph renderer""" label = TextLine(title=_("Renderer name"), required=True) def update(): """Update gallery paragraph renderer""" def render(): """Render gallery paragraph renderer""" class IGalleryParagraphInfo(IParagraphInfo): """Gallery link paragraph base interface""" renderer = Choice(title=_("Paragraph renderer"), description=_("Renderer used to render this gallery"), required=True, default=u'default', vocabulary="ZTFY Gallery renderers") class IGalleryParagraphWriter(IParagraphWriter): """Gallery link paragraph writer interface""" class IGalleryParagraph(IParagraph, IGalleryParagraphInfo, IGalleryParagraphWriter): """Gallery link interface full interface""" # # Gallery index interfaces # class IGalleryIndexUploadData(Interface): """Gallery index upload interface""" clear = Bool(title=_("Clear index before import ?"), description=_("If 'Yes', index will be cleared before importing new file content"), required=True, default=False) data = FileField(title=_("Uploaded index data"), description=_("Please select a CSV file containing images index"), required=True) language = Choice(title=_("Index language"), description=_("Language matching given index contents"), required=True, vocabulary="ZTFY base languages", default=u'en') encoding = EncodingField(title=_("Data encoding"), description=_("Encoding of the uploaded CSV file"), required=False) headers = Bool(title=_("CSV header ?"), description=_("Is the CSV file containing header line ?"), required=True, default=True) delimiter = TextLine(title=_("Fields delimiter"), description=_("Character used to separate values in CSV file; use \\t for tabulation"), max_length=2, required=True, default=u",") quotechar = TextLine(title=_("Quote character"), description=_("Character used to quote fields containing special characters, such as fields delimiter"), max_length=1, required=True, default=u'"') class IGalleryIndexInfo(Interface): """Gallery index infos interface""" values = Dict(title=_("Gallery index values"), key_type=TextLine(), value_type=Object(schema=IGalleryImageBaseInfo), required=False) class IGalleryIndexWriter(Interface): """Gallery index writer interface""" def clear(self): """Clear index contents""" class IGalleryIndex(IGalleryIndexInfo, IGalleryIndexWriter): """Gallery index full interface""" class IGalleryIndexManager(Interface): """Marker interface for gallery container handling an index""" class IGalleryImageIndexInfo(Interface): """Gallery image index infos interface""" ids = List(title=_("Index keys"), description=_("List of values matching gallery's index keys"), value_type=Choice(vocabulary="ZTFY gallery index"))
ztfy.gallery
/ztfy.gallery-0.4.1.tar.gz/ztfy.gallery-0.4.1/src/ztfy/gallery/interfaces.py
interfaces.py
__docformat__ = "restructuredtext" # import standard packages from persistent import Persistent # import Zope3 interfaces from zope.annotation.interfaces import IAnnotations from zopyx.txng3.core.interfaces.indexable import IIndexableContent # import local interfaces from ztfy.gallery.interfaces import IGalleryImage, IGalleryContainer, IGalleryContainerTarget # import Zope3 packages from zope.component import adapter, adapts from zope.container.contained import Contained from zope.interface import implementer, implements from zope.location import locate from zope.schema.fieldproperty import FieldProperty from zopyx.txng3.core.content import IndexContentCollector # import local packages from ztfy.base.ordered import OrderedContainer from ztfy.extfile.blob import BlobImage from ztfy.file.property import ImageProperty from ztfy.i18n.property import I18nTextProperty class GalleryImage(Persistent, Contained): implements(IGalleryImage) title = I18nTextProperty(IGalleryImage['title']) description = I18nTextProperty(IGalleryImage['description']) credit = FieldProperty(IGalleryImage['credit']) image = ImageProperty(IGalleryImage['image'], klass=BlobImage, img_klass=BlobImage) image_id = FieldProperty(IGalleryImage['image_id']) visible = FieldProperty(IGalleryImage['visible']) class GalleryImageTextIndexer(object): adapts(IGalleryImage) implements(IIndexableContent) def __init__(self, context): self.context = context def indexableContent(self, fields): icc = IndexContentCollector() for field in fields: for lang, value in getattr(self.context, field, {}).items(): if value: icc.addContent(field, value, lang) return icc class GalleryContainer(OrderedContainer): implements(IGalleryContainer) def getVisibleImages(self): return [img for img in self.values() if img.visible] GALLERY_ANNOTATIONS_KEY = 'ztfy.gallery.container' @adapter(IGalleryContainerTarget) @implementer(IGalleryContainer) def GalleryContainerFactory(context): """Gallery container adapter""" annotations = IAnnotations(context) container = annotations.get(GALLERY_ANNOTATIONS_KEY) if container is None: container = annotations[GALLERY_ANNOTATIONS_KEY] = GalleryContainer() locate(container, context, '++gallery++') return container
ztfy.gallery
/ztfy.gallery-0.4.1.tar.gz/ztfy.gallery-0.4.1/src/ztfy/gallery/gallery.py
gallery.py
__docformat__ = "restructuredtext" # import standard packages from persistent import Persistent # import Zope3 interfaces from zope.annotation.interfaces import IAnnotations # import local interfaces from ztfy.blog.interfaces.site import ISiteManager from ztfy.gallery.interfaces import IGalleryManagerPaypalInfo, IGalleryImage, IGalleryImagePaypalInfo # import Zope3 packages from zope.component import adapter from zope.container.contained import Contained from zope.interface import implementer, implements from zope.location import locate from zope.schema.fieldproperty import FieldProperty # import local packages from ztfy.i18n.property import I18nTextProperty, I18nImageProperty class SiteManagerPaypalInfo(Persistent, Contained): implements(IGalleryManagerPaypalInfo) paypal_enabled = FieldProperty(IGalleryManagerPaypalInfo['paypal_enabled']) paypal_currency = FieldProperty(IGalleryManagerPaypalInfo['paypal_currency']) paypal_button_id = FieldProperty(IGalleryManagerPaypalInfo['paypal_button_id']) paypal_format_options = I18nTextProperty(IGalleryManagerPaypalInfo['paypal_format_options']) paypal_options_label = I18nTextProperty(IGalleryManagerPaypalInfo['paypal_options_label']) paypal_options_options = I18nTextProperty(IGalleryManagerPaypalInfo['paypal_options_options']) paypal_image_field_name = FieldProperty(IGalleryManagerPaypalInfo['paypal_image_field_name']) paypal_image_field_label = I18nTextProperty(IGalleryManagerPaypalInfo['paypal_image_field_label']) add_to_basket_button = I18nImageProperty(IGalleryManagerPaypalInfo['add_to_basket_button']) see_basket_button = I18nImageProperty(IGalleryManagerPaypalInfo['see_basket_button']) paypal_pkcs_key = FieldProperty(IGalleryManagerPaypalInfo['paypal_pkcs_key']) PAYPAL_SITE_ANNOTATIONS_KEY = 'ztfy.gallery.sitemanager.paypal' @adapter(ISiteManager) @implementer(IGalleryManagerPaypalInfo) def SiteManagerPaypalFactory(context): annotations = IAnnotations(context) info = annotations.get(PAYPAL_SITE_ANNOTATIONS_KEY) if info is None: info = annotations[PAYPAL_SITE_ANNOTATIONS_KEY] = SiteManagerPaypalInfo() locate(info, context, '++paypal++') return info class GalleryImagePaypalInfo(Persistent, Contained): implements(IGalleryImagePaypalInfo) paypal_enabled = FieldProperty(IGalleryImagePaypalInfo['paypal_enabled']) paypal_disabled_message = I18nTextProperty(IGalleryImagePaypalInfo['paypal_disabled_message']) PAYPAL_IMAGE_ANNOTATIONS_KEY = 'ztfy.gallery.image.paypal' @adapter(IGalleryImage) @implementer(IGalleryImagePaypalInfo) def GalleryImagePaypalFactory(context): annotations = IAnnotations(context) info = annotations.get(PAYPAL_IMAGE_ANNOTATIONS_KEY) if info is None: info = annotations[PAYPAL_IMAGE_ANNOTATIONS_KEY] = GalleryImagePaypalInfo() locate(info, context, '++paypal++') return info
ztfy.gallery
/ztfy.gallery-0.4.1.tar.gz/ztfy.gallery-0.4.1/src/ztfy/gallery/paypal.py
paypal.py
__docformat__ = "restructuredtext" # import standard packages import transaction # import Zope3 interfaces from zope.catalog.interfaces import ICatalog from zope.component.interfaces import IComponentRegistry, ISite from zope.intid.interfaces import IIntIds from zope.processlifetime import IDatabaseOpenedWithRoot # import local interfaces from ztfy.gallery.interfaces import IGalleryImage from ztfy.utils.interfaces import INewSiteManagerEvent # import Zope3 packages from zope.app.publication.zopepublication import ZopePublication from zope.catalog.catalog import Catalog from zope.component import adapter, queryUtility from zope.intid import IntIds from zope.location import locate from zope.site import hooks # import local packages from ztfy.utils.catalog.index import TextIndexNG from ztfy.utils.site import locateAndRegister def updateDatabaseIfNeeded(context): """Check for missing objects at application startup""" try: sm = context.getSiteManager() except: return default = sm['default'] # Check for required IIntIds utility intids = queryUtility(IIntIds) if intids is None: intids = default.get('IntIds') if intids is None: intids = IntIds() locate(intids, default) default['IntIds'] = intids IComponentRegistry(sm).registerUtility(intids, IIntIds) # Check for required catalog and index catalog = default.get('Catalog') if catalog is None: catalog = Catalog() locateAndRegister(catalog, default, 'Catalog', intids) IComponentRegistry(sm).registerUtility(catalog, ICatalog, 'Catalog') if catalog is not None: if 'image_title' not in catalog: index = TextIndexNG('title description', IGalleryImage, False, languages=('fr en'), storage='txng.storages.term_frequencies', dedicated_storage=False, use_stopwords=True, use_normalizer=True, ranking=True) locateAndRegister(index, catalog, 'image_title', intids) @adapter(IDatabaseOpenedWithRoot) def handleOpenedDatabase(event): db = event.database connection = db.open() root = connection.root() root_folder = root.get(ZopePublication.root_name, None) for site in root_folder.values(): if ISite(site, None) is not None: hooks.setSite(site) updateDatabaseIfNeeded(site) transaction.commit() @adapter(INewSiteManagerEvent) def handleNewSiteManager(event): updateDatabaseIfNeeded(event.object)
ztfy.gallery
/ztfy.gallery-0.4.1.tar.gz/ztfy.gallery-0.4.1/src/ztfy/gallery/database.py
database.py
__docformat__ = "restructuredtext" # import standard packages from persistent import Persistent # import Zope3 interfaces from z3c.language.switch.interfaces import II18n from zope.annotation.interfaces import IAnnotations from zope.schema.interfaces import IVocabularyFactory # import local interfaces from ztfy.gallery.interfaces import IGalleryIndex, IGalleryIndexManager, \ IGalleryContainer, IGalleryImageBaseInfo, IGalleryImageIndexInfo, IGalleryImage # import Zope3 packages from zope.component import adapter from zope.container.contained import Contained from zope.interface import implementer, implements, alsoProvides, noLongerProvides, classProvides from zope.location.location import locate from zope.schema.fieldproperty import FieldProperty from zope.schema.vocabulary import SimpleVocabulary, SimpleTerm from zope.traversing import api as traversing_api # import local packages from ztfy.i18n.property import I18nTextProperty from ztfy.utils.traversing import getParent class GalleryIndexEntry(object): """Gallery index entry""" implements(IGalleryImageBaseInfo) title = I18nTextProperty(IGalleryImageBaseInfo['title']) description = I18nTextProperty(IGalleryImageBaseInfo['description']) class GalleryIndex(Persistent, Contained): """Gallery index class""" implements(IGalleryIndex) _values = FieldProperty(IGalleryIndex['values']) @property def values(self): return self._values @values.setter def values(self, data): self._values = data gallery = traversing_api.getParent(self) if data: alsoProvides(gallery, IGalleryIndexManager) elif IGalleryIndexManager.providedBy(gallery): noLongerProvides(gallery, IGalleryIndexManager) def clear(self): if self.values: self.values.clear() GALLERY_INDEX_ANNOTATIONS_KEY = 'ztfy.gallery.index' @adapter(IGalleryContainer) @implementer(IGalleryIndex) def GalleryIndexFactory(context): """Gallery index adapter""" annotations = IAnnotations(context) index = annotations.get(GALLERY_INDEX_ANNOTATIONS_KEY) if index is None: index = annotations[GALLERY_INDEX_ANNOTATIONS_KEY] = GalleryIndex() locate(index, context, '++index++') return index class GalleryIndexValuesVocabulary(SimpleVocabulary): classProvides(IVocabularyFactory) def __init__(self, context): terms = [] if IGalleryImageIndexInfo.providedBy(context): context = context.context gallery = getParent(context, IGalleryContainer) if gallery is not None: index = IGalleryIndex(gallery) if (index is not None) and index.values: terms = [SimpleTerm(v, title='%s - %s' % (v, II18n(t).queryAttribute('title'))) for v, t in index.values.iteritems()] terms.sort(key=lambda x: x.value) super(GalleryIndexValuesVocabulary, self).__init__(terms) class GalleryImageIndexInfo(Persistent): """Gallery image index info""" implements(IGalleryImageIndexInfo) _ids = FieldProperty(IGalleryImageIndexInfo['ids']) def __init__(self, context): self.context = context @property def ids(self): return self._ids @ids.setter def ids(self, values): self._ids = values if values: gallery = getParent(self.context, IGalleryContainer) if gallery is not None: index = IGalleryIndex(gallery) title = {} description = {} for key in values: for lang, value in index.values[key].title.items(): if value: if lang in title: title[lang] += ', ' + value else: title[lang] = value for lang, value in index.values[key].description.items(): if value: if lang in description: description[lang] += ', ' + value else: description[lang] = value self.context.title = title self.context.description = description @adapter(IGalleryImage) @implementer(IGalleryImageIndexInfo) def GalleryImageIndexFactory(context): """Gallery image index adapter""" annotations = IAnnotations(context) index = annotations.get(GALLERY_INDEX_ANNOTATIONS_KEY) if index is None: index = annotations[GALLERY_INDEX_ANNOTATIONS_KEY] = GalleryImageIndexInfo(context) return index
ztfy.gallery
/ztfy.gallery-0.4.1.tar.gz/ztfy.gallery-0.4.1/src/ztfy/gallery/index.py
index.py
__docformat__ = "restructuredtext" # import standard packages import os # import Zope3 interfaces from zope.intid.interfaces import IIntIds from zope.traversing.interfaces import TraversalError # import local interfaces from ztfy.gallery.interfaces import IGalleryImageInfo, IGalleryImage, IGalleryImageExtension, \ IGalleryContainer, IGalleryContainerTarget, IGalleryIndexManager, IGalleryIndex from ztfy.skin.interfaces import IDefaultView from ztfy.skin.layer import IZTFYBackLayer # import Zope3 packages from z3c.form import field from z3c.formjs import ajax from z3c.template.template import getLayoutTemplate, getViewTemplate from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile from zope.component import adapts, getUtility, getAdapters, queryMultiAdapter from zope.event import notify from zope.interface import implements, Interface from zope.lifecycleevent import ObjectCreatedEvent from zope.publisher.browser import BrowserView, BrowserPage from zope.schema import TextLine from zope.traversing import api as traversing_api from zope.traversing import namespace from zope.traversing.browser import absoluteURL # import local packages from ztfy.blog.browser.resource import ZipArchiveExtractor, TarArchiveExtractor from ztfy.file.schema import FileField from ztfy.gallery.browser import ztfy_gallery_back from ztfy.gallery.gallery import GalleryImage from ztfy.i18n.browser import ztfy_i18n from ztfy.jqueryui import jquery_fancybox from ztfy.skin.container import OrderedContainerBaseView from ztfy.skin.form import DialogAddForm, DialogEditForm from ztfy.skin.menu import MenuItem, DialogMenuItem from ztfy.utils.traversing import getParent from ztfy.utils.unicode import translateString from ztfy.gallery import _ class GalleryImageDefaultViewAdapter(object): adapts(IGalleryImage, IZTFYBackLayer, Interface) implements(IDefaultView) viewname = '@@properties.html' def __init__(self, context, request, view): self.context = context self.request = request self.view = view def getAbsoluteURL(self): return """javascript:$.ZTFY.dialog.open('%s/%s')""" % (absoluteURL(self.context, self.request), self.viewname) class GalleryContainerNamespaceTraverser(namespace.view): """++gallery++ namespace""" def traverse(self, name, ignored): result = getParent(self.context, IGalleryContainerTarget) if result is not None: return IGalleryContainer(result) raise TraversalError('++gallery++') class IGalleryImageAddFormMenuTarget(Interface): """Marker interface for gallery images add menu""" class GalleryContainerContentsViewMenuItem(MenuItem): """Gallery container contents menu""" title = _("Images gallery") class IGalleryContainerContentsView(Interface): """Marker interface for gallery container contents view""" class GalleryContainerContentsView(OrderedContainerBaseView): """Gallery container contents view""" implements(IGalleryImageAddFormMenuTarget, IGalleryContainerContentsView) legend = _("Images gallery") cssClasses = { 'table': 'orderable' } output = ViewPageTemplateFile('templates/gallery_contents.pt') def update(self): ztfy_gallery_back.need() jquery_fancybox.need() super(GalleryContainerContentsView, self).update() @property def values(self): return IGalleryContainer(self.context).values() @property def hasIndex(self): gallery = IGalleryContainer(self.context) return IGalleryIndexManager.providedBy(gallery) @property def index(self): gallery = IGalleryContainer(self.context) return IGalleryIndex(gallery) @ajax.handler def ajaxRemove(self): oid = self.request.form.get('id') if oid: intids = getUtility(IIntIds) target = intids.getObject(int(oid)) parent = traversing_api.getParent(target) del parent[traversing_api.getName(target)] return "OK" return "NOK" @ajax.handler def ajaxUpdateOrder(self): self.updateOrder(IGalleryContainer(self.context)) def getImagesExtensions(self, image): return sorted((a[1] for a in getAdapters((image, self.request), IGalleryImageExtension)), key=lambda x: x.weight) class GalleryImageAddForm(DialogAddForm): """Gallery image add form""" legend = _("Adding new gallery image") fields = field.Fields(IGalleryImageInfo) layout = getLayoutTemplate() parent_interface = IGalleryContainerTarget parent_view = GalleryContainerContentsView handle_upload = True resources = (ztfy_i18n,) def create(self, data): return GalleryImage() def add(self, image): prefix = self.prefix + self.widgets.prefix data = self.request.form.get(prefix + 'image') filename = getattr(data, 'filename', None) if filename: filename = translateString(filename, escapeSlashes=True, forceLower=False, spaces='-') if not image.image_id: self._v_image_id = os.path.splitext(filename)[0] if filename in self.context: index = 2 name = '%s-%d' % (filename, index) while name in self.context: index += 1 name = '%s-%d' % (filename, index) filename = name if not filename: index = 1 filename = 'image-%d' % index while filename in self.context: index += 1 filename = 'image-%d' % index self.context[filename] = image def updateContent(self, object, data): super(GalleryImageAddForm, self).updateContent(object, data) if not object.image_id: object.image_id = getattr(self, '_v_image_id', None) class GalleryContainerAddImageMenuItem(DialogMenuItem): """Gallery image add menu""" title = _(":: Add image...") target = GalleryImageAddForm class IArchiveContentAddInfo(Interface): """Schema for images added from archives""" credit = TextLine(title=_("Author credit"), description=_("Default author credits and copyright applied to all images"), required=False) content = FileField(title=_("Archive data"), description=_("Archive content's will be extracted as images ; format can be any ZIP, tar.gz or tar.bz2 file"), required=True) class GalleryContainerImagesFromArchiveAddForm(DialogAddForm): """Add a set of images from a single archive""" legend = _("Adding new resources from archive file") fields = field.Fields(IArchiveContentAddInfo) layout = getLayoutTemplate() parent_interface = IGalleryContainerTarget parent_view = GalleryContainerContentsView handle_upload = True resources = (ztfy_i18n,) def createAndAdd(self, data): prefix = self.prefix + self.widgets.prefix filename = self.request.form.get(prefix + 'content').filename if filename.lower().endswith('.zip'): extractor = ZipArchiveExtractor else: extractor = TarArchiveExtractor content = data.get('content') if isinstance(content, tuple): content = content[0] extractor = extractor(content) for info in extractor.getMembers(): content = extractor.extract(info) if content: name = translateString(extractor.getFilename(info), escapeSlashes=True, forceLower=False, spaces='-') image = GalleryImage() notify(ObjectCreatedEvent(image)) self.context[name] = image image.credit = data.get('credit') image.image = content image.image_id = os.path.splitext(name)[0] class GalleryContainerAddImagesFromArchiveMenuItem(DialogMenuItem): """Resources from archive add menu item""" title = _(":: Add images from archive...") target = GalleryContainerImagesFromArchiveAddForm class GalleryImagePropertiesExtension(object): """Gallery image properties extension""" adapts(IGalleryImage, IZTFYBackLayer) implements(IGalleryImageExtension) title = _("Properties") icon = '/--static--/ztfy.blog/img/search.png' klass = 'search' weight = 1 def __init__(self, context, request): self.context = context self.request = request @property def url(self): return """javascript:$.ZTFY.dialog.open('%s/@@properties.html')""" % absoluteURL(self.context, self.request) class GalleryImageTrashExtension(object): """Gallery image trash extension""" adapts(IGalleryImage, IZTFYBackLayer) implements(IGalleryImageExtension) title = _("Delete image") icon = '/--static--/ztfy.gallery.back/img/trash.png' klass = 'trash' weight = 99 def __init__(self, context, request): self.context = context self.request = request @property def url(self): intids = getUtility(IIntIds) return """javascript:$.ZBlog.gallery.remove(%d, '%s');""" % (intids.register(self.context), traversing_api.getName(self.context)) class GalleryImageEditForm(DialogEditForm): """Gallery image edit form""" legend = _("Edit image properties") fields = field.Fields(IGalleryImageInfo) layout = getLayoutTemplate() parent_interface = IGalleryContainerTarget parent_view = GalleryContainerContentsView handle_upload = True def getOutput(self, writer, parent, changes=()): status = changes and u'OK' or u'NONE' return writer.write({ 'output': status }) class GalleryImageDiapoView(BrowserView): """Display gallery image as diapo""" def __call__(self): self.update() return self.render() def update(self): pass render = getViewTemplate() class GalleryImageIndexView(BrowserPage): """Gallery image default view""" def __call__(self): return queryMultiAdapter((self.context.image, self.request), Interface, 'index.html')()
ztfy.gallery
/ztfy.gallery-0.4.1.tar.gz/ztfy.gallery-0.4.1/src/ztfy/gallery/browser/gallery.py
gallery.py
from ztfy.skin.viewlet import ViewletBase __docformat__ = "restructuredtext" # import standard packages import chardet import codecs import csv from cStringIO import StringIO # import Zope3 interfaces from z3c.language.switch.interfaces import II18n from zope.traversing.interfaces import TraversalError # import local interfaces from ztfy.file.interfaces import IImageDisplay from ztfy.gallery.interfaces import IGalleryIndexUploadData, IGalleryContainerTarget, IGalleryContainer, \ IGalleryIndex, IGalleryImage, IGalleryImageExtension, IGalleryImageIndexInfo, \ IGalleryIndexManager from ztfy.skin.layer import IZTFYBackLayer # import Zope3 packages from z3c.form import field from z3c.template.template import getLayoutTemplate from zope.component import adapts from zope.interface import implements from zope.traversing import namespace from zope.traversing.api import getParent from zope.traversing.browser import absoluteURL # import local packages from ztfy.gallery.browser.gallery import GalleryContainerContentsView from ztfy.gallery.index import GalleryIndexEntry from ztfy.skin.form import DialogAddForm, DialogDisplayForm, DialogEditForm from ztfy.skin.menu import DialogMenuItem from ztfy.gallery import _ class GalleryIndexNamespaceTraverser(namespace.view): """++index++ namespace""" def traverse(self, name, ignored): result = IGalleryIndex(self.context, None) if result is not None: return result raise TraversalError('++index++') class GalleryIndexAddForm(DialogAddForm): """Gallery index add form""" legend = _("Adding new gallery index from CSV file") fields = field.Fields(IGalleryIndexUploadData) layout = getLayoutTemplate() parent_interface = IGalleryContainerTarget parent_view = GalleryContainerContentsView handle_upload = True def createAndAdd(self, data): gallery = IGalleryContainer(self.context) index = IGalleryIndex(gallery, None) if index is not None: if data.get('clear'): index.clear() csv_data = data.get('data') # check for FileField tuple if isinstance(csv_data, tuple): csv_data = csv_data[0] encoding = data.get('encoding') if not encoding: encoding = chardet.detect(csv_data).get('encoding', 'utf-8') language = data.get('language') if encoding != 'utf-8': csv_data = codecs.getreader(encoding)(StringIO(csv_data)).read().encode('utf-8') values = index.values or {} if data.get('headers'): reader = csv.DictReader(StringIO(csv_data), delimiter=str(data.get('delimiter')), quotechar=str(data.get('quotechar'))) for row in reader: key = unicode(row['id']) entry = values.get(key) if entry is None: entry = GalleryIndexEntry() title = entry.title.copy() title.update({ language: unicode(row.get('title'), 'utf-8') }) entry.title = title description = entry.description.copy() description.update({ language: unicode(row.get('description'), 'utf-8') }) entry.description = description values[key] = entry else: reader = csv.reader(StringIO(csv_data), delimiter=str(data.get('delimiter')), quotechar=str(data.get('quotechar'))) for row in reader: key = unicode(row[0]) entry = values.get(key) if entry is None: entry = GalleryIndexEntry() title = entry.title.copy() title.update({ language: unicode(row[1], 'utf-8') }) entry.title = title description = entry.description.copy() description.update({ language: unicode(row[2], 'utf-8') }) entry.description = description values[key] = entry index.values = values class GalleryIndexAddMenuItem(DialogMenuItem): """Gallery index add menu item""" title = _(":: Add gallery index...") target = GalleryIndexAddForm class GalleryIndexContentsView(DialogDisplayForm): """Gallery index contents""" @property def title(self): target = getParent(self.context, IGalleryContainerTarget) i18n = II18n(target, None) if i18n is not None: return i18n.queryAttribute('title', request=self.request) legend = _("Gallery index contents") class GalleryImageIndexExtension(object): """Gallery image index extension""" adapts(IGalleryImage, IZTFYBackLayer) implements(IGalleryImageExtension) title = _("Index") icon = '/--static--/ztfy.gallery.back/img/index.png' klass = 'index' weight = 10 def __new__(self, context, request): if not IGalleryIndexManager.providedBy(getParent(context)): return None return object.__new__(self, context, request) def __init__(self, context, request): self.context = context self.request = request @property def url(self): return """javascript:$.ZTFY.dialog.open('%s/@@indexProperties.html')""" % absoluteURL(self.context, self.request) class GalleryImageIndexEditForm(DialogEditForm): """Gallery image index edit form""" legend = _("Edit image index properties") fields = field.Fields(IGalleryImageIndexInfo) layout = getLayoutTemplate() parent_interface = IGalleryContainerTarget parent_view = None class GalleryImageIndexPrefix(ViewletBase): """Index widgets prefix""" @property def display(self): img = self.context return IImageDisplay(img.image).getDisplay('800x600')
ztfy.gallery
/ztfy.gallery-0.4.1.tar.gz/ztfy.gallery-0.4.1/src/ztfy/gallery/browser/index.py
index.py
(function(a){a.ZBlog.gallery={sorter:function(b){a(b).sortable(a.ZBlog.gallery.sort_options)},sort_options:{handle:"DIV.image",containment:"parent",placeholder:"sorting-holder",stop:function(c,e){var b=new Array();a("FIELDSET.gallery DIV.image").each(function(f){b[b.length]=a(this).attr("id")});var d={ids:b};a.ZTFY.ajax.post(window.location.href+"/@@ajax/ajaxUpdateOrder",d,null,function(h,f,g){jAlert(h.responseText,a.ZTFY.I18n.ERROR_OCCURED,window.location.reload)})}},remove:function(b,c){jConfirm(a.ZTFY.I18n.CONFIRM_REMOVE,a.ZTFY.I18n.CONFIRM,function(e){if(e){var d={id:b};a.ZTFY.form.ajax_source=a('DIV[id="'+c+'"]');a.ZTFY.ajax.post(window.location.href+"/@@ajax/ajaxRemove",d,a.ZBlog.gallery._removeCallback,null,"text")}})},_removeCallback:function(b,c){if((c=="success")&&(b=="OK")){a(a.ZTFY.form.ajax_source).parents("DIV.image_wrapper").remove()}},paypal_switch:function(c){var b=window.location.href;var f=b.substr(0,b.lastIndexOf("/"));var e=f+"/++gallery++/"+c+"/++paypal++/@@switch.html";var d=a("A.paypal",a('DIV[id="'+c+'"]').parents("DIV.image_wrapper"));a.ZTFY.form.ajax_source=c;if(d.hasClass("disabled")){a.ZTFY.ajax.post(e,{},a.ZBlog.gallery._paypalEnableCallback,function(i,g,h){jAlert(i.responseText,a.ZTFY.I18n.ERROR_OCCURED,window.location.reload)},"json")}else{a.ZTFY.dialog.open(e)}},paypal_edit:function(b,c){a.ZTFY.form.edit(b,c,a.ZBlog.gallery._editCallback)},_editCallback:function(b,c){a.ZTFY.form._editCallback(b,c);if((c=="success")&&(b.output=="OK")){var d=a.ZTFY.form.ajax_source;var e=a("A.paypal",a('DIV[id="'+d+'"]').parents("DIV.image_wrapper"));if(b.enabled){e.removeClass("disabled").addClass("enabled");a("IMG",e).attr("src","/--static--/ztfy.gallery.back/img/paypal-enabled.png")}else{e.removeClass("enabled").addClass("disabled");a("IMG",e).attr("src","/--static--/ztfy.gallery.back/img/paypal-disabled.png")}}},_paypalEnableCallback:function(b,c){if((c=="success")&&(b.output=="OK")){var d=a.ZTFY.form.ajax_source;var e=a("A.paypal",a('DIV[id="'+d+'"]').parents("DIV.image_wrapper"));if(e.hasClass("disabled")){e.removeClass("disabled").addClass("enabled");a("IMG",e).attr("src","/--static--/ztfy.gallery.back/img/paypal-enabled.png")}}}}})(jQuery);
ztfy.gallery
/ztfy.gallery-0.4.1.tar.gz/ztfy.gallery-0.4.1/src/ztfy/gallery/browser/resources/js/gallery.back.min.js
gallery.back.min.js
(function($) { $.ZBlog.gallery = { sorter: function(element) { $(element).sortable($.ZBlog.gallery.sort_options); }, sort_options: { handle: 'DIV.image', containment: 'parent', placeholder: 'sorting-holder', stop: function(event, ui) { var ids = new Array(); $('FIELDSET.gallery DIV.image').each(function (i) { ids[ids.length] = $(this).attr('id'); }); var data = { ids: ids } $.ZTFY.ajax.post(window.location.href + '/@@ajax/ajaxUpdateOrder', data, null, function(request, status, error) { jAlert(request.responseText, $.ZTFY.I18n.ERROR_OCCURED, window.location.reload); }); } }, remove: function(oid, source) { jConfirm($.ZTFY.I18n.CONFIRM_REMOVE, $.ZTFY.I18n.CONFIRM, function(confirmed) { if (confirmed) { var data = { id: oid } $.ZTFY.form.ajax_source = $('DIV[id="'+source+'"]'); $.ZTFY.ajax.post(window.location.href + '/@@ajax/ajaxRemove', data, $.ZBlog.gallery._removeCallback, null, 'text'); } }); }, _removeCallback: function(result, status) { if ((status == 'success') && (result == 'OK')) { $($.ZTFY.form.ajax_source).parents('DIV.image_wrapper').remove(); } }, paypal_switch: function(name) { var href = window.location.href; var addr = href.substr(0, href.lastIndexOf('/')); var target = addr + '/++gallery++/' + name + '/++paypal++/@@switch.html'; var link = $('A.paypal', $('DIV[id="'+name+'"]').parents('DIV.image_wrapper')); $.ZTFY.form.ajax_source = name; if (link.hasClass('disabled')) { $.ZTFY.ajax.post(target, {}, $.ZBlog.gallery._paypalEnableCallback, function(request, status, error) { jAlert(request.responseText, $.ZTFY.I18n.ERROR_OCCURED, window.location.reload); }, 'json'); } else { $.ZTFY.dialog.open(target); } }, paypal_edit: function(form, base) { $.ZTFY.form.edit(form, base, $.ZBlog.gallery._editCallback); }, _editCallback: function(result, status) { $.ZTFY.form._editCallback(result, status); if ((status == 'success') && (result.output == 'OK')) { var name = $.ZTFY.form.ajax_source; var link = $('A.paypal', $('DIV[id="'+name+'"]').parents('DIV.image_wrapper')); if (result.enabled) { link.removeClass('disabled').addClass('enabled'); $('IMG', link).attr('src', '/--static--/ztfy.gallery.back/img/paypal-enabled.png'); } else { link.removeClass('enabled').addClass('disabled'); $('IMG', link).attr('src', '/--static--/ztfy.gallery.back/img/paypal-disabled.png'); } } }, _paypalEnableCallback: function(result, status) { if ((status == 'success') && (result.output == 'OK')) { var name = $.ZTFY.form.ajax_source; var link = $('A.paypal', $('DIV[id="'+name+'"]').parents('DIV.image_wrapper')); if (link.hasClass('disabled')) { link.removeClass('disabled').addClass('enabled'); $('IMG', link).attr('src', '/--static--/ztfy.gallery.back/img/paypal-enabled.png'); } } } } })(jQuery);
ztfy.gallery
/ztfy.gallery-0.4.1.tar.gz/ztfy.gallery-0.4.1/src/ztfy/gallery/browser/resources/js/gallery.back.js
gallery.back.js
(function($) { $.ZBlog.gallery = { buy_image: function(id) { $('#fancybox-title').empty(); $.get($('IMG[id="'+id+'"]').parents('A').attr('href') + '/@@buy.html', function(data) { $('<span id="fancybox-title-over"></span>').addClass('nohide') .append(data) .appendTo($('#fancybox-title')); if (typeof(_gaq) != "undefined") { _gaq.push(['_trackEvent', 'Image', 'Buy', id]); } }); }, buy_image_from_thumbnail: function(id) { $.ZTFY.skin.stopEvent(event); $.get($('IMG[id="'+id+'"]').parents('A').attr('href') + '/@@buy.html', function(data) { $.fancybox('<div id="fancybox-title-over" class="fancybox-title-over">' + data + '</div>'); if (typeof(_gaq) != "undefined") { _gaq.push(['_trackEvent', 'Image', 'Buy', id]); } }); }, fancyboxTitleFormatter: function(title, array, index, opts) { var output = ''; var has_title = title && title.length; if ($(array[0]).parents('DIV.gallery').data('paypal-enabled') == 'True') { var id = $('IMG', $(array[index])).attr('id'); if (id) { var klass = has_title ? '' : ' opaque'; output = '<div class="caddie' + klass + '"><a href="javascript:$.ZBlog.gallery.buy_image(\'' + id + '\');">' + '<img src="/--static--/ztfy.gallery.defaultskin/img/caddie.png" title="' + $.ZBlog.gallery.I18n.BUY_PICTURE + '" /></a></div>'; if (typeof(_gaq) != "undefined") { _gaq.push(['_trackEvent', 'Image', 'Display', id]); } } } if (has_title) { output += '<span id="fancybox-title-over"><strong>' + title + '</strong>'; var description = $(array[index]).data('gallery-description'); if (description) output += '<br />' + description; output += '</span>'; } output += '<div class="clearer"><!-- IE bugfix --></div>'; return output; }, fancyboxCompleteCallback: function() { $('<img></img>').attr('src', '/++presentation++/++file++site_watermark') .css('position', 'absolute') .css('right', 30) .css('bottom', 30) .appendTo($('#fancybox-inner')); $("#fancybox-wrap").hover(function() { $("#fancybox-title").slideDown('slow'); }, function() { if (!$('#fancybox-title-over').hasClass('nohide')) { $("#fancybox-title").slideUp('slow'); } }); } } /** * Init I18n strings */ $.ZBlog.gallery.I18n = { BUY_PICTURE: "Buy printed picture" } var lang = $('HTML').attr('lang') || $('HTML').attr('xml:lang'); if (lang && (lang != 'en')) $.ZTFY.getScript('/--static--/ztfy.gallery.defaultskin/js/i18n/' + lang + '.js'); })(jQuery);
ztfy.gallery
/ztfy.gallery-0.4.1.tar.gz/ztfy.gallery-0.4.1/src/ztfy/gallery/defaultskin/resources/js/ztfy.gallery.js
ztfy.gallery.js
__docformat__ = "restructuredtext" # import standard packages # import Zope3 interfaces from hurry.query.interfaces import IQuery from zope.intid.interfaces import IIntIds from zope.session.interfaces import ISession # import local interfaces from ztfy.blog.interfaces.category import ICategorizedContent from ztfy.blog.interfaces.topic import ITopic from ztfy.workflow.interfaces import IWorkflowContent # import Zope3 packages from hurry.query import And from hurry.query.set import AnyOf from hurry.query.value import Eq from zope.component import getUtility from zope.traversing.browser.absoluteurl import absoluteURL # import local packages from ztfy.skin.page import TemplateBasedPage from ztfy.utils.catalog.index import Text from ztfy.utils.traversing import getParent SITE_MANAGER_SESSION_ID = 'ztfy.gallery.site.search' class SiteManagerSearchView(TemplateBasedPage): """Site manager search page""" def __call__(self): form = self.request.form if 'page' in form: session = ISession(self.request)[SITE_MANAGER_SESSION_ID] self.search_text = search_text = session.get('search_text', '') self.search_tag = search_tag = session.get('search_tag', '') or None else: self.search_text = search_text = form.get('search_text', '').strip() self.search_tag = search_tag = form.get('search_tag', '') or None if not search_text: if not search_tag: self.request.response.redirect(absoluteURL(self.context, self.request)) return '' else: intids = getUtility(IIntIds) category = intids.queryObject(search_tag) self.request.response.redirect(absoluteURL(category, self.request)) return '' return super(SiteManagerSearchView, self).__call__() def update(self): super(SiteManagerSearchView, self).update() query = getUtility(IQuery) # Search for matching images params = [] params.append(Text(('Catalog', 'image_title'), { 'query': ' '.join(('%s*' % m for m in self.search_text.split())), 'autoexpand': 'on_miss', 'ranking': True })) # .. get and filter search results topics = {} [ topics.setdefault(getParent(image, ITopic), []).append(image) for image in query.searchResults(And(*params)) ] if self.search_tag: for topic in topics.keys()[:]: ids = ICategorizedContent(topic).categories_ids if ids and (self.search_tag not in ids): del topics[topic] # Search for matching topics params = [] params.append(Eq(('Catalog', 'content_type'), 'ITopic')) params.append(Text(('Catalog', 'title'), { 'query': ' '.join(('%s*' % m for m in self.search_text.split())), 'autoexpand': 'on_miss', 'ranking': True })) if self.search_tag: intids = getUtility(IIntIds) self.category = intids.queryObject(self.search_tag) params.append(AnyOf(('Catalog', 'categories'), (self.search_tag,))) # .. get search results [ topics.setdefault(topic, []) for topic in query.searchResults(And(*params)) ] # .. check topics status and sort for topic in topics.keys()[:]: if not IWorkflowContent(topic).isVisible(): del topics[topic] results = sorted(((topic, topics[topic]) for topic in topics), key=lambda x: IWorkflowContent(x[0]).publication_effective_date, reverse=True) # .. store search settings in session session = ISession(self.request)[SITE_MANAGER_SESSION_ID] session['search_text'] = self.search_text session['search_tag'] = self.search_tag # .. handle pagination page = int(self.request.form.get('page', 0)) page_length = 10 first = page_length * page last = first + page_length - 1 pages = len(results) / page_length if len(results) % page_length: pages += 1 self.results = { 'results': results[first:last + 1], 'pages': pages, 'first': first, 'last': last, 'has_prev': page > 0, 'has_next': last < len(results) - 1 }
ztfy.gallery
/ztfy.gallery-0.4.1.tar.gz/ztfy.gallery-0.4.1/src/ztfy/gallery/skin/search.py
search.py
__docformat__ = "restructuredtext" # import standard packages # import Zope3 interfaces # import local interfaces from ztfy.base.interfaces.container import IOrderedContainer from ztfy.blog.defaultskin.interfaces import ILLUSTRATION_DISPLAY_LEFT, ILLUSTRATION_DISPLAY_VOCABULARY from ztfy.blog.interfaces.blog import IBlog from ztfy.blog.interfaces.section import ISection from ztfy.i18n.interfaces import II18nAttributesAware from ztfy.skin.interfaces import IBasePresentationInfo # import Zope3 packages from zope.container.constraints import contains from zope.interface import Interface from zope.schema import Bool, Int, TextLine, List, Choice, Object # import local packages from ztfy.base.schema import InternalReference from ztfy.file.schema import ImageField from ztfy.i18n.schema import I18nTextLine from ztfy.gallery import _ # # Site presentation management # class ISiteManagerPresentationInfo(IBasePresentationInfo): """Site manager presentation base interface""" site_icon = ImageField(title=_("Site icon"), description=_("Site 'favicon' image"), required=False) site_logo = ImageField(title=_("Site logo"), description=_("Site logo displayed on home page"), required=False) site_watermark = ImageField(title=_("Site watermark"), description=_("Watermark image applied on gallery images"), required=False) news_blog_oid = InternalReference(title=_("News blog OID"), description=_("Internal ID of news blog's target"), required=False) news_entries = Int(title=_("Displayed entries count"), description=_("Number of news topics displayed in front-page"), required=True, default=10) reports_blog_oid = InternalReference(title=_("Reports blog OID"), description=_("Internal ID of reports blog's target"), required=False) footer_section_oid = InternalReference(title=_("Footer topics section OID"), description=_("Internal ID of section containing topics displayed in pages footer"), required=False) facebook_app_id = TextLine(title=_("Facebook application ID"), description=_("Application ID declared on Facebook"), required=False) disqus_site_id = TextLine(title=_("Disqus site ID"), description=_("Site's ID on Disqus comment platform can be used to allow topics comments"), required=False) class ISiteManagerPresentation(ISiteManagerPresentationInfo): """Site manager presentation full interface""" news_blog = Object(title=_("News blog target"), schema=IBlog, readonly=True) reports_blog = Object(title=_("Reports blog target"), schema=IBlog, readonly=True) footer_section = Object(title=_("Footer section target"), schema=ISection, readonly=True) # # Home background images management # class IHomeBackgroundManagerDetailMenuTarget(Interface): """Marker interface for home background image add form menu target""" class IHomeBackgroundImage(II18nAttributesAware): """Home background image interface""" title = I18nTextLine(title=_("Title"), description=_("Image's title, as displayed in front page"), required=True) image = ImageField(title=_("Image data"), description=_("This attribute holds image data ; select an optimized image of 1024 pixels width"), required=True) visible = Bool(title=_("Visible ?"), description=_("Select 'No' to hide this image from home page"), required=True, default=True) class IHomeBackgroundInfo(Interface): """Home background images manager infos interface""" def getImage(): """Retrieve current image to display in home page background""" class IHomeBackgroundManager(IHomeBackgroundInfo, IOrderedContainer): """Home background images manager interface""" contains(IHomeBackgroundImage) class IHomeBackgroundManagerContentsView(Interface): """Background manager contents view marker interface""" # # Topic presentation management # class ITopicPresentationInfo(II18nAttributesAware, IBasePresentationInfo): """Topic presentation base interface""" publication_date = I18nTextLine(title=_("Displayed publication date"), description=_("Date at which this report was done"), required=False) header_format = Choice(title=_("Header format"), description=_("Text format used for content's header"), required=True, default=u'zope.source.plaintext', vocabulary='SourceTypes') display_googleplus = Bool(title=_("Display Google +1 button"), description=_("Display Google +1 button next to content's title"), required=True, default=True) display_fb_like = Bool(title=_("Display Facebook 'like' button"), description=_("Display Facebook 'like' button next to content's title"), required=True, default=True) illustration_position = Choice(title=_("Illustration's position"), description=_("Select position of topic's illustration"), required=True, default=ILLUSTRATION_DISPLAY_LEFT, vocabulary=ILLUSTRATION_DISPLAY_VOCABULARY) illustration_width = Int(title=_("Illustration's width"), description=_("Display width of topic's illustration"), required=True, default=176) linked_resources = List(title=_("Downloadable resources"), description=_("Select list of resources displayed as download links"), required=False, default=[], value_type=Choice(vocabulary="ZTFY content resources")) class ITopicPresentation(ITopicPresentationInfo): """Topic presentation full interface"""
ztfy.gallery
/ztfy.gallery-0.4.1.tar.gz/ztfy.gallery-0.4.1/src/ztfy/gallery/skin/interfaces.py
interfaces.py
__docformat__ = "restructuredtext" # import standard packages import random from persistent import Persistent # import Zope3 interfaces from z3c.language.switch.interfaces import II18n from zope.annotation.interfaces import IAnnotations from zope.app.file.interfaces import IImage from zope.intid.interfaces import IIntIds from zope.traversing.interfaces import TraversalError # import local interfaces from interfaces import IHomeBackgroundImage, IHomeBackgroundManager, \ IHomeBackgroundManagerContentsView, \ IHomeBackgroundManagerDetailMenuTarget from ztfy.blog.interfaces.site import ISiteManager from ztfy.file.interfaces import IImageDisplay from ztfy.skin.interfaces import IDefaultView from ztfy.skin.interfaces.container import IActionsColumn, IContainerTableViewActionsCell # import Zope3 packages from z3c.form import field from z3c.formjs import ajax from z3c.table.column import Column from z3c.template.template import getLayoutTemplate from zope.component import adapter, adapts, getAdapter, queryMultiAdapter, getUtility from zope.container.contained import Contained from zope.i18n import translate from zope.interface import implementer, implements, Interface from zope.location import locate from zope.publisher.browser import BrowserPage from zope.schema.fieldproperty import FieldProperty from zope.traversing import namespace from zope.traversing import api as traversing_api from zope.traversing.browser import absoluteURL # import local packages from ztfy.base.ordered import OrderedContainer from ztfy.extfile.blob import BlobImage from ztfy.file.property import ImageProperty from ztfy.gallery.skin.menu import GallerySkinMenuItem, GallerySkinDialogMenuItem from ztfy.i18n.browser import ztfy_i18n from ztfy.i18n.property import I18nTextProperty from ztfy.skin.container import OrderedContainerBaseView from ztfy.skin.form import DialogAddForm, DialogEditForm from ztfy.skin.layer import IZTFYBrowserLayer, IZTFYBackLayer from ztfy.utils.traversing import getParent from ztfy.utils.unicode import translateString from ztfy.gallery import _ # # Home background images manager # class HomeBackgroundManager(OrderedContainer): """Home background images manager""" implements(IHomeBackgroundManager) def getImage(self): images = [i for i in self.values() if i.visible] if images: return random.choice(images) return None HOME_BACKGROUND_IMAGES_ANNOTATIONS_KEY = 'ztfy.gallery.home.background' @adapter(ISiteManager) @implementer(IHomeBackgroundManager) def HomeBackgroundManagerFactory(context): annotations = IAnnotations(context) manager = annotations.get(HOME_BACKGROUND_IMAGES_ANNOTATIONS_KEY) if manager is None: manager = annotations[HOME_BACKGROUND_IMAGES_ANNOTATIONS_KEY] = HomeBackgroundManager() locate(manager, context, '++home++') return manager class HomeBackgroundManagerNamespaceTraverser(namespace.view): """++home++ namespace""" def traverse(self, name, ignored): site = getParent(self.context, ISiteManager) if site is not None: manager = IHomeBackgroundManager(site) if manager is not None: return manager raise TraversalError('++home++') class HomeBackgroundManagerContentsMenuItem(GallerySkinMenuItem): """HomeBackgroundManager contents menu item""" title = _("Home background images") class HomeBackgroundManagerContentsView(OrderedContainerBaseView): """Home background images manager contents view""" implements(IHomeBackgroundManagerContentsView, IHomeBackgroundManagerDetailMenuTarget) legend = _("Home page background images") @property def values(self): return IHomeBackgroundManager(self.context).values() @ajax.handler def ajaxRemove(self): oid = self.request.form.get('id') if oid: intids = getUtility(IIntIds) target = intids.getObject(int(oid)) parent = traversing_api.getParent(target) del parent[traversing_api.getName(target)] return "OK" return "NOK" @ajax.handler def ajaxUpdateOrder(self): adapter = getAdapter(self.context, IHomeBackgroundManager) self.updateOrder(adapter) class IHomeBackgroundManagerPreviewColumn(Interface): """Marker interface for home background images container preview column""" class HomeBackgroundManagerPreviewColumn(Column): """Home background images container preview column""" implements(IHomeBackgroundManagerPreviewColumn) header = u'' weight = 5 cssClasses = { 'th': 'preview', 'td': 'preview' } def renderCell(self, item): image = IImage(item.image, None) if image is None: return u'' display = IImageDisplay(image).getDisplay('64x64') return '''<img src="%s" alt="%s" />''' % (absoluteURL(display, self.request), II18n(item).queryAttribute('title', request=self.request)) class HomeBackgroundManagerContentsViewActionsColumnCellAdapter(object): adapts(IHomeBackgroundImage, IZTFYBrowserLayer, IHomeBackgroundManagerContentsView, IActionsColumn) implements(IContainerTableViewActionsCell) def __init__(self, context, request, view, column): self.context = context self.request = request self.view = view self.column = column self.intids = getUtility(IIntIds) @property def content(self): klass = "ui-workflow ui-icon ui-icon-trash" result = '''<span class="%s" title="%s" onclick="$.ZTFY.form.remove(%d, this);"></span>''' % (klass, translate(_("Delete image"), context=self.request), self.intids.register(self.context)) return result # # Home background images # class HomeBackgroundImage(Persistent, Contained): """Home background image""" implements(IHomeBackgroundImage) title = I18nTextProperty(IHomeBackgroundImage['title']) image = ImageProperty(IHomeBackgroundImage['image'], klass=BlobImage) visible = FieldProperty(IHomeBackgroundImage['visible']) class HomeBackgroundImageDefaultViewAdapter(object): """Container default view adapter for home background images""" adapts(IHomeBackgroundImage, IZTFYBackLayer, Interface) implements(IDefaultView) viewname = '@@properties.html' def __init__(self, context, request, view): self.context = context self.request = request self.view = view def getAbsoluteURL(self): return '''javascript:$.ZTFY.dialog.open('%s/%s')''' % (absoluteURL(self.context, self.request), self.viewname) class HomeBackgroundImageAddForm(DialogAddForm): """Home background image add form""" title = _("New home background image") legend = _("Adding new background image") fields = field.Fields(IHomeBackgroundImage) layout = getLayoutTemplate() parent_interface = ISiteManager parent_view = HomeBackgroundManagerContentsView handle_upload = True resources = (ztfy_i18n,) def create(self, data): return HomeBackgroundImage() def add(self, image): data = self.request.form.get('form.widgets.image') filename = None if hasattr(data, 'filename'): filename = translateString(data.filename, escapeSlashes=True, forceLower=False, spaces='-') if filename in self.context: index = 2 name = '%s-%d' % (filename, index) while name in self.context: index += 1 name = '%s-%d' % (filename, index) filename = name if not filename: index = 1 filename = 'image-%d' % index while filename in self.context: index += 1 filename = 'image-%d' % index self.context[filename] = image class HomeBackgroundImageAddMenuItem(GallerySkinDialogMenuItem): """Home background image add menu item""" title = _(":: Add image...") target = HomeBackgroundImageAddForm class HomeBackgroundImageEditForm(DialogEditForm): """Home background image edit form""" legend = _("Edit image properties") fields = field.Fields(IHomeBackgroundImage) layout = getLayoutTemplate() parent_interface = ISiteManager parent_view = HomeBackgroundManagerContentsView handle_upload = True class HomeBackgroundImageIndexView(BrowserPage): """Home background image index view""" def __call__(self): return queryMultiAdapter((self.context.image, self.request), Interface, 'index.html')()
ztfy.gallery
/ztfy.gallery-0.4.1.tar.gz/ztfy.gallery-0.4.1/src/ztfy/gallery/skin/home.py
home.py
__docformat__ = "restructuredtext" # import standard packages from persistent import Persistent # import Zope3 interfaces from zope.annotation.interfaces import IAnnotations from zope.intid.interfaces import IIntIds # import local interfaces from ztfy.blog.interfaces.site import ISiteManager from ztfy.blog.interfaces.topic import ITopic from ztfy.gallery.interfaces import IGalleryManagerPaypalInfo from ztfy.gallery.skin.interfaces import ITopicPresentation, ITopicPresentationInfo from ztfy.gallery.skin.layer import IGalleryLayer from ztfy.skin.interfaces import IPresentationTarget # import Zope3 packages from zope.container.contained import Contained from zope.component import adapter, adapts, getUtility from zope.interface import implementer, implements from zope.schema.fieldproperty import FieldProperty # import local packages from ztfy.blog.defaultskin.topic import TopicIndexPreview as TopicIndexPreviewBase from ztfy.gallery.skin.menu import GallerySkinDialogMenuItem from ztfy.i18n.property import I18nTextProperty from ztfy.jqueryui import jquery_tools_12, jquery_fancybox from ztfy.utils.request import setData from ztfy.utils.traversing import getParent from ztfy.gallery import _ TOPIC_PRESENTATION_KEY = 'ztfy.gallery.presentation' class TopicPresentationViewMenuItem(GallerySkinDialogMenuItem): """Topic presentation menu item""" title = _(" :: Presentation model...") class TopicPresentation(Persistent, Contained): """Topic presentation infos""" implements(ITopicPresentation) publication_date = I18nTextProperty(ITopicPresentation['publication_date']) header_format = FieldProperty(ITopicPresentation['header_format']) display_googleplus = FieldProperty(ITopicPresentation['display_googleplus']) display_fb_like = FieldProperty(ITopicPresentationInfo['display_fb_like']) illustration_position = FieldProperty(ITopicPresentation['illustration_position']) illustration_width = FieldProperty(ITopicPresentation['illustration_width']) linked_resources = FieldProperty(ITopicPresentation['linked_resources']) @adapter(ITopic) @implementer(ITopicPresentation) def TopicPresentationFactory(context): annotations = IAnnotations(context) presentation = annotations.get(TOPIC_PRESENTATION_KEY) if presentation is None: presentation = annotations[TOPIC_PRESENTATION_KEY] = TopicPresentation() return presentation class TopicPresentationTargetAdapter(object): adapts(ITopic, IGalleryLayer) implements(IPresentationTarget) target_interface = ITopicPresentationInfo def __init__(self, context, request): self.context, self.request = context, request class TopicIndexPreview(TopicIndexPreviewBase): def __call__(self, images=[]): self.images = images if images: jquery_tools_12.need() jquery_fancybox.need() return super(TopicIndexPreview, self).__call__() @property def oid(self): intids = getUtility(IIntIds) return intids.queryId(self.context) @property def pages(self): index = 0 images = self.images length = len(images) while index < length: yield(images[index:index + 5]) index += 5 @property def paypal(self): site = getParent(self.context, ISiteManager) info = IGalleryManagerPaypalInfo(site) setData('gallery.paypal', info, self.request) return info
ztfy.gallery
/ztfy.gallery-0.4.1.tar.gz/ztfy.gallery-0.4.1/src/ztfy/gallery/skin/topic.py
topic.py
__docformat__ = "restructuredtext" # import standard packages from persistent import Persistent # import Zope3 interfaces from z3c.json.interfaces import IJSONWriter from z3c.language.switch.interfaces import II18n from zope.annotation.interfaces import IAnnotations from zope.catalog.interfaces import ICatalog from zope.intid.interfaces import IIntIds from zope.publisher.interfaces import NotFound # import local interfaces from ztfy.blog.interfaces.category import ICategorizedContent from ztfy.blog.interfaces.site import ISiteManager from ztfy.file.interfaces import IImageDisplay from ztfy.gallery.skin.interfaces import IHomeBackgroundManager from ztfy.gallery.skin.interfaces import ISiteManagerPresentationInfo, ISiteManagerPresentation from ztfy.gallery.skin.layer import IGalleryLayer from ztfy.skin.interfaces import IPresentationTarget from ztfy.workflow.interfaces import IWorkflowContent # import Zope3 packages from zope.component import adapter, adapts, getUtility, queryMultiAdapter, queryUtility from zope.container.contained import Contained from zope.interface import implementer, implements, Interface from zope.location import locate from zope.publisher.browser import BrowserPage from zope.schema.fieldproperty import FieldProperty from zope.traversing.browser import absoluteURL # import local packages from ztfy.blog.browser import ztfy_blog_back from ztfy.blog.browser.site import BaseSiteManagerIndexView from ztfy.blog.defaultskin.site import SiteManagerRssView as BaseSiteManagerRssView from ztfy.file.property import ImageProperty from ztfy.gallery.skin.menu import GallerySkinDialogMenuItem from ztfy.jqueryui import jquery_multiselect from ztfy.gallery import _ SITE_MANAGER_PRESENTATION_KEY = 'ztfy.gallery.presentation' class SiteManagerPresentationViewMenuItem(GallerySkinDialogMenuItem): """Site manager presentation menu item""" title = _(" :: Presentation model...") def render(self): result = super(SiteManagerPresentationViewMenuItem, self).render() if result: jquery_multiselect.need() ztfy_blog_back.need() return result class SiteManagerPresentation(Persistent, Contained): """Site manager presentation infos""" implements(ISiteManagerPresentation) site_icon = ImageProperty(ISiteManagerPresentation['site_icon']) site_logo = ImageProperty(ISiteManagerPresentation['site_logo']) site_watermark = ImageProperty(ISiteManagerPresentation['site_watermark']) news_blog_oid = FieldProperty(ISiteManagerPresentation['news_blog_oid']) news_entries = FieldProperty(ISiteManagerPresentation['news_entries']) reports_blog_oid = FieldProperty(ISiteManagerPresentation['reports_blog_oid']) footer_section_oid = FieldProperty(ISiteManagerPresentation['footer_section_oid']) facebook_app_id = FieldProperty(ISiteManagerPresentation['facebook_app_id']) disqus_site_id = FieldProperty(ISiteManagerPresentation['disqus_site_id']) @property def news_blog(self): if not self.news_blog_oid: return None intids = getUtility(IIntIds) return intids.queryObject(self.news_blog_oid) @property def reports_blog(self): if not self.reports_blog_oid: return None intids = getUtility(IIntIds) return intids.queryObject(self.reports_blog_oid) @property def footer_section(self): if not self.footer_section_oid: return None intids = getUtility(IIntIds) return intids.queryObject(self.footer_section_oid) @adapter(ISiteManager) @implementer(ISiteManagerPresentation) def SiteManagerPresentationFactory(context): annotations = IAnnotations(context) presentation = annotations.get(SITE_MANAGER_PRESENTATION_KEY) if presentation is None: presentation = annotations[SITE_MANAGER_PRESENTATION_KEY] = SiteManagerPresentation() locate(presentation, context, '++presentation++') return presentation class SiteManagerPresentationTargetAdapter(object): adapts(ISiteManager, IGalleryLayer) implements(IPresentationTarget) target_interface = ISiteManagerPresentationInfo def __init__(self, context, request): self.context, self.request = context, request class SiteManagerIndexView(BaseSiteManagerIndexView): """Site manager index page""" @property def background_image(self): manager = IHomeBackgroundManager(self.context, None) if manager is not None: return manager.getImage() @property def categories(self): catalog = queryUtility(ICatalog, 'Catalog') if catalog is not None: index = catalog.get('categories') if index is not None: intids = getUtility(IIntIds) return sorted(((id, intids.queryObject(id)) for id in index.values()), key=lambda x: II18n(x[1]).queryAttribute('shortname', request=self.request)) return [] @property def reports(self): target = self.presentation.reports_blog if (target is not None) and target.visible: return target.getVisibleTopics()[:4] else: return [] @property def news(self): target = self.presentation.news_blog if (target is not None) and target.visible: return target.getVisibleTopics()[:self.presentation.news_entries] else: return [] def getCategory(self, topic): categories = ICategorizedContent(topic).categories if not categories: return '' return ' - '.join(('<a href="%s">%s</a>' % (absoluteURL(category, self.request), II18n(category).queryAttribute('shortname', request=self.request)) for category in categories)) class SiteManagerRssView(BaseSiteManagerRssView): @property def topics(self): result = [] target = self.presentation.reports_blog if (target is not None) and target.visible: result.extend(target.getVisibleTopics()) target = self.presentation.news_blog if (target is not None) and target.visible: result.extend(target.getVisibleTopics()) result.sort(key=lambda x: IWorkflowContent(x).publication_effective_date, reverse=True) return result[:self.presentation.news_entries + 4] class SiteManagerBackgroundURL(BrowserPage): def __call__(self): writer = getUtility(IJSONWriter) image = self.background_image if image is not None: self.request.response.setHeader('Cache-Control', 'private, no-cache, no-store') self.request.response.setHeader('Pragma', 'no-cache') display = IImageDisplay(image.image).getDisplay('w1024') if display is not None: return writer.write({ 'url': absoluteURL(display, self.request), 'title': II18n(image).queryAttribute('title', request=self.request) }) return writer.write('none') @property def background_image(self): manager = IHomeBackgroundManager(self.context, None) if manager is not None: return manager.getImage() class SiteManagerIconView(BrowserPage): """'favicon.ico' site view""" def __call__(self): icon = ISiteManagerPresentation(self.context).site_icon if icon is not None: view = queryMultiAdapter((icon, self.request), Interface, 'index.html') if view is not None: return view() raise NotFound(self.context, 'favicon.ico', self.request)
ztfy.gallery
/ztfy.gallery-0.4.1.tar.gz/ztfy.gallery-0.4.1/src/ztfy/gallery/skin/site.py
site.py
__docformat__ = "restructuredtext" # import standard packages # import Zope3 interfaces from z3c.json.interfaces import IJSONWriter from zope.traversing.interfaces import TraversalError # import local interfaces from ztfy.blog.interfaces.site import ISiteManager from ztfy.gallery.interfaces import IGalleryManagerPaypalInfo, IGalleryImage, IGalleryImagePaypalInfo, \ IGalleryImageExtension from ztfy.skin.interfaces import IDialogEditFormButtons from ztfy.skin.layer import IZTFYBackLayer # import Zope3 packages from z3c.form import field, button from z3c.formjs import ajax, jsaction from z3c.template.template import getLayoutTemplate from zope.component import adapts, getUtility from zope.event import notify from zope.interface import implements from zope.lifecycleevent import ObjectModifiedEvent from zope.traversing import api as traversing_api from zope.traversing import namespace # import local packages from ztfy.gallery.skin.menu import GallerySkinDialogMenuItem from ztfy.skin.form import DialogEditForm from ztfy.utils.traversing import getParent from ztfy.gallery import _ class SiteManagerPaypalNamespaceTraverser(namespace.view): """++paypal++ namespace""" def traverse(self, name, ignored): result = getParent(self.context, ISiteManager) if result is not None: return IGalleryManagerPaypalInfo(result) raise TraversalError('++paypal++') class SiteManagerPaypalEditForm(DialogEditForm): """Site manager Paypal edit form""" legend = _("Edit Paypal properties") fields = field.Fields(IGalleryManagerPaypalInfo) layout = getLayoutTemplate() parent_interface = ISiteManager def getContent(self): return IGalleryManagerPaypalInfo(self.context) class SiteManagerPaypalMenuItem(GallerySkinDialogMenuItem): """Paypal properties menu item""" title = _(":: Paypal account...") target = SiteManagerPaypalEditForm class GalleryImagePaypalNamespaceTraverser(namespace.view): """++paypal++ namespace for images""" def traverse(self, name, ignored): result = IGalleryImagePaypalInfo(self.context, None) if result is not None: return result raise TraversalError('++paypal++') class GalleryImagePaypalExtension(object): """Gallery image Paypal extension""" adapts(IGalleryImage, IZTFYBackLayer) implements(IGalleryImageExtension) def __init__(self, context, request): self.context = context self.request = request self.paypal = IGalleryImagePaypalInfo(self.context) title = _("Enable or disable Paypal") @property def icon(self): if self.paypal.paypal_enabled: name = "enabled" else: name = "disabled" return '/--static--/ztfy.gallery.back/img/paypal-%s.png' % name @property def klass(self): if self.paypal.paypal_enabled: return 'paypal enabled' else: return 'paypal disabled' @property def url(self): return """javascript:$.ZBlog.gallery.paypal_switch('%s');""" % traversing_api.getName(self.context) weight = 50 class GalleryImagePaypalEditForm(DialogEditForm): """Gallery image Paypal edit form""" buttons = button.Buttons(IDialogEditFormButtons) fields = field.Fields(IGalleryImagePaypalInfo) def __call__(self): info = IGalleryImagePaypalInfo(self.context) if info.paypal_enabled: return super(GalleryImagePaypalEditForm, self).__call__() else: info.paypal_enabled = True writer = getUtility(IJSONWriter) return writer.write({ 'output': u'OK' }) @jsaction.handler(buttons['dialog_submit']) def submit_handler(self, event, selector): return '''$.ZBlog.gallery.paypal_edit(this.form);''' @jsaction.handler(buttons['dialog_cancel']) def cancel_handler(self, event, selector): return '$.ZTFY.dialog.close();' @ajax.handler def ajaxEdit(self): writer = getUtility(IJSONWriter) self.updateWidgets() data, errors = self.extractData() if errors: self.status = self.formErrorsMessage self.update() return writer.write({ 'output': self.layout() }) if self.applyChanges(data): parent = getParent(self.context, self.parent_interface) notify(ObjectModifiedEvent(parent)) return writer.write({ 'output': u'OK', 'enabled': IGalleryImagePaypalInfo(self.context).paypal_enabled }) else: return writer.write({ 'output': u'NONE' })
ztfy.gallery
/ztfy.gallery-0.4.1.tar.gz/ztfy.gallery-0.4.1/src/ztfy/gallery/skin/paypal.py
paypal.py
(function($) { var loading = null; var loadingFrame = 1; var loadingTimer = null; var background_url = null; if (typeof($.ZBlog) == 'undefined') { $.ZBlog = {}; } if (typeof($.ZBlog.gallery) == 'undefined') { $.ZBlog.gallery = {}; } $.ZBlog.gallery.skin = { initIndexPage: function(element) { $(element).jScrollPane({ showArrows: true, scrollbarWidth: 11, scrollbarMargin: 3 }); setTimeout($.ZBlog.gallery.skin.loadBackground, 5000); }, initScrollable: function(element) { if (typeof($.fn.scrollable) == 'undefined') return; var $element = $(element); var data = $element.data(); var options = { clickable: data.galleryClickable === undefined ? false : data.galleryClickable, keyboard: data.galleryKeyboard === undefined ? false : data.galleryKeyboard, mousewheel: data.galleryMousewheel === undefined ? true : data.galleryMousewheel }; if (data.galleryPrev !== undefined) options.prev = data.galleryPrev; if (data.galleryNext !== undefined) options.next = data.galleryNext; $element.scrollable(options) .navigator(data.galleryNavigator); }, animateLoading: function() { if (!loading.is(':visible')){ clearInterval(loadingTimer); return; } loading.css('background-position-y', (loadingFrame * -40) + 'px'); loadingFrame = (loadingFrame + 1) % 12; }, loadBackground: function() { loading = $('#banner DIV'); loadingTimer = setInterval('$.ZBlog.gallery.skin.animateLoading();', 66); $.getJSON('getBackgroundURL.json', function(data) { if (data != 'none') { $('#legend SPAN').animate({ opacity: 0 }, 1000); $.get(data.url, function(img) { $('#banner').animate({ opacity: 0 }, 1000, function() { $('#banner').css('background', 'transparent url('+data.url+') scroll no-repeat left top') .animate({ opacity: 1 }, 1000); $('#legend SPAN').text(data.title).animate({ opacity: 1 }, 1000); }); loading.hide(); }); } else { loading.hide(); } setTimeout($.ZBlog.gallery.skin.loadBackground, 10000); }); } } /** * Disable options menu !! */ $(document).bind('contextmenu', function() { return false; }); })(jQuery);
ztfy.gallery
/ztfy.gallery-0.4.1.tar.gz/ztfy.gallery-0.4.1/src/ztfy/gallery/skin/resources/js/gallery.js
gallery.js
==================== ztfy.gallery package ==================== .. contents:: What is ztfy.gallery ? ====================== ZTFY.gallery is an extension to ZTFY.blog package. It's goal is to handle images galleries included into a web site. Package also includes a small basic set of features to be able to sell printed pictures via Paypal. You can get a working sample of package features and skin on my own web site address, http://www.imagesdusport.com (actually only in french). How to use ztfy.gallery ? ========================= ztfy.gallery package usage is described via doctests in ztfy/gallery/doctests/README.txt
ztfy.gallery
/ztfy.gallery-0.4.1.tar.gz/ztfy.gallery-0.4.1/docs/README.txt
README.txt
# import standard packages # import Zope3 interfaces from z3c.form.interfaces import HIDDEN_MODE # import local interfaces from ztfy.geoportal.interfaces import IGeoportalConfigurationUtility, \ IGeoportalLocation, IGeoportalLocationEditForm from ztfy.skin.interfaces import IDialogDisplayFormButtons # import Zope3 packages from z3c.form import field, button from z3c.formjs import jsaction from zope.component import queryUtility from zope.interface import implements # import local packages from ztfy.geoportal.location import GeoportalLocation from ztfy.skin.form import DialogEditForm from ztfy.utils.property import cached_property class GeoportalLocationEditForm(DialogEditForm): """Geoportal location edit form""" implements(IGeoportalLocationEditForm) prefix = 'location.' fields = field.Fields(IGeoportalLocation) buttons = button.Buttons(IDialogDisplayFormButtons) def updateWidgets(self): super(GeoportalLocationEditForm, self).updateWidgets() self.widgets['longitude'].mode = HIDDEN_MODE self.widgets['latitude'].mode = HIDDEN_MODE def getContent(self): location = IGeoportalLocation(self.context, None) if location is not None: return location else: return GeoportalLocation() @cached_property def config(self): return queryUtility(IGeoportalConfigurationUtility) @property def geoportal_key(self): config = self.config if config is not None: return config.api_key @property def geoportal_version(self): config = self.config if config is not None: return config.version @property def geoportal_devel(self): config = self.config if config is not None: return config.development @jsaction.handler(buttons['dialog_close']) def close_handler(self, event, selector): return '$.ZTFY.dialog.close();' def applyChanges(self, data): pass def getOutput(self, writer, parent, changes=()): return writer.write({ 'output': u'PASS' })
ztfy.geoportal
/ztfy.geoportal-0.2.5.tar.gz/ztfy.geoportal-0.2.5/src/ztfy/geoportal/browser/location.py
location.py
(function($) { if (typeof($.ZTFY) == 'undefined') { $.ZTFY = {}; } $.ZTFY.geoportal = { /** * Open Geoportal dialog box */ open: function(prefix, target) { Geoportal = undefined; OpenLayers = undefined; $.ZTFY.dialog.open(target + '?prefix=' + prefix); return false; }, /** * Initialize plug-in and load map */ initPlugin: function(element) { if (window.__Geoportal$timer === undefined) { var __Geoportal$timer = null; } $.ZTFY.geoportal.initMap(element); }, initMap: function(element) { if (typeof(OpenLayers) === 'undefined' || typeof(Geoportal) === 'undefined') { setTimeout($.ZTFY.geoportal.initMap, 300, element); return; } Geoportal.GeoRMHandler.getConfig([$(element).data('geoportal-api-key')], null, null, { onContractsComplete: function() { $($.ZTFY.geoportal).data('geoportal-config', this); $.ZTFY.geoportal.loadMap(element); } }); }, loadMap: function(element) { var map = $.ZTFY.geoportal.initViewer(element); }, /** * Initialize GeoPortal map * * @param target: DIV target ID * @param apiKey: IGN API key * @param territory: ISO territory code * @param projection: SRID or IGNF projection code * @param displayProjection: SRID or IGNF display projection code */ initViewer: function(target, territory, projection, displayProjection) { /** * Class: GeoXYForm * Helper class to automate form update of (X,Y) coordinates */ Geoportal.GeoXYForm = OpenLayers.Class({ containerId: null, /* HTML map container ID */ buttonId: null, /* HTML ID of a container used to enable/disable map visualization */ imgButton: null, /* Image associated to HTML container */ lonId: null, /* ID of HTML field containing longitude */ latId: null, /* ID of HTML field containing latitude */ vectorProjection: 'IGNF:RGF93G', /* Name of corodinates projection */ precision: 1000000, /* Corodinates precision; equivalent of 30cm in geographic projections */ marker: null, /* Path to image used to display coordinates */ container: null, button: null, Lon: null, Lat: null, initialize: function(options) { OpenLayers.Util.extend(this, options); if (typeof(this.vectorProjection) == 'string') { this.vectorProjection = new OpenLayers.Projection(this.vectorProjection); } this.container = parent.document.getElementById(this.containerId); this.button = parent.document.getElementById(this.buttonId); this.Lon = parent.document.getElementById(this.lonId); this.Lat = parent.document.getElementById(this.latId); }, /** * APIMethod: getXInput * Returns the coordinates input field associated with abscissa or longitude */ getXInput: function() { return this.Lon; }, /** * APIMethod: getYInput * Returns the coordinates input field associated with ordinate or latitude. */ getYInput: function() { return this.Lat; }, /** * APIMethod: getX * Returns the coordinates input field value associated with abscissa or longitude. */ getX: function() { if (this.Lon) { return parseFloat(this.Lon.value); } return NaN; }, /** * APIMethod: getY * Returns the coordinates input field value associated with ordinate or latitude. */ getY: function() { if (this.Lat) { return parseFloat(this.Lat.value); } return NaN; }, /** * APIMethod: setX * Assigns the coordinates input field value associated with abscissa or longitude. */ setX: function(x) { if (this.Lon && !isNaN(parseFloat(x))) { this.Lon.value = x; } }, /** * APIMethod: setY * Assigns the coordinates input field value associated with ordinate or latitude. */ setY: function(y) { if (this.Lat && !isNaN(parseFloat(y))) { this.Lat.value = y; } }, /** * APIMethod: getPrecision * Returns the 10**number of figures */ getPrecision: function() { return this.precision ? this.precision : 1000000; }, /** * APIMethod: getNativeProjection * Returns the projection of the vector layer */ getNativeProjection: function() { return this.vectorProjection; }, /** * Constant: CLASS_NAME */ CLASS_NAME: 'Geoportal.GeoXYForm' }); var options = { mode: 'normal', territory: territory || 'FXX', projection: projection || null, displayProjection: displayProjection || 'IGNF:RGF93G' }; var target_id; if (typeof(target) == 'string') { target_id = target; target = $('DIV[id="' + target_id + '"]'); } else { target_id = $(target).attr('id'); } var api_key = $(target).data('geoportal-api-key'); var viewer = new Geoportal.Viewer.Default(target_id, OpenLayers.Util.extend( options, window.gGEOPORTALRIGHTSMANAGEMENT === undefined ? { 'apiKey': apiKey } : gGEOPORTALRIGHTSMANAGEMENT )); viewer.addGeoportalLayers(['ORTHOIMAGERY.ORTHOPHOTOS', 'GEOGRAPHICALGRIDSYSTEMS.MAPS'], {}); viewer.map.getLayersByName('ORTHOIMAGERY.ORTHOPHOTOS')[0].visibility = false; viewer.map.getLayersByName('GEOGRAPHICALGRIDSYSTEMS.MAPS')[0].setOpacity(0.8); var target = $(target).get(0); $.data(target, 'ztfy.geoportal.viewer', viewer); var lonId = 'location-widgets-longitude'; var latId = 'location-widgets-latitude'; var formInfo = { containerId: target_id, lonId: lonId, latId: latId, vectorProjection: new OpenLayers.Projection('EPSG:4326'), /* WGS84 coordinates */ precision: 1000000, marker: '/--static--/ztfy.geoportal/img/pin.png' }; var gpForm = new Geoportal.GeoXYForm(formInfo); viewer.setVariable('gpForm', gpForm); var styles = null; if (gpForm.marker) { styles = new OpenLayers.StyleMap({ 'default': OpenLayers.Util.extend({ externalGraphic: gpForm.marker, graphicOpacity: 1, graphicWidth: 14, graphicHeight: 14, graphicXOffset: 0, graphicYOffset: -14, fill : false }, OpenLayers.Feature.Vector['default']), 'temporary': OpenLayers.Util.extend({ display: 'none' }, OpenLayers.Feature.Vector['temporary']) }); } var dialogs = $.ZTFY.dialog.dialogs; if (dialogs.length > 0) { var src = dialogs[dialogs.length-1].src; var prefix = $.ZTFY.getQueryVar(src, 'prefix'); if (prefix) { prefix = prefix.replace(/\./g, '-'); lonId = prefix + '-longitude'; latId = prefix + '-latitude'; } } var parentFormInfo = { containerId: target, lonId: lonId, latId: latId, vectorProjection: new OpenLayers.Projection('EPSG:4326'), precision: 1000000, marker: '/--static--/ztfy.geoportal/img/pin.png' }; var gpParentForm = new Geoportal.GeoXYForm(parentFormInfo); viewer.setVariable('gpParentForm', gpParentForm); var vlayer= new OpenLayers.Layer.Vector( 'POINT_XY', { projection: gpForm.vectorProjection, displayInLayerSwitcher:false, calculateInRange: function() { return true; }, styleMap: styles } ); viewer.getMap().addLayer(vlayer); var draw_feature= new OpenLayers.Control.DrawFeature( vlayer, OpenLayers.Handler.Point, { autoActivate:true, callbacks: { done: function (geometry) { this.layer.destroyFeatures(); var feature= new OpenLayers.Feature.Vector(geometry, {'pictoUrl': '/--static--/ztfy.geoportal/img/pin.png'}); feature.state = OpenLayers.State.INSERT; this.layer.addFeatures([feature]); $.ZTFY.geoportal.updateXYForm(feature); } }, handlerOptions: { persist: false, layerOptions:{ projection: gpForm.vectorProjection } } } ); viewer.getMap().addControl(draw_feature); OpenLayers.Event.observe(gpForm.getXInput(), "change", $.ZTFY.geoportal.updateFeature); OpenLayers.Event.observe(gpForm.getYInput(), "change", $.ZTFY.geoportal.updateFeature); $.ZTFY.geoportal.updateFeature(); return viewer; }, /** * Get viewer associated with a given target */ getViewer: function(target) { if (typeof(target) == 'string') { var target = $('DIV[id='+target+']').get(0); } return $.data(target, 'ztfy.geoportal.viewer'); }, updateXYForm: function(feature, pix) { if (!feature || !feature.geometry || !feature.geometry.x || !feature.geometry.y) { return; } var viewer = $.ZTFY.geoportal.getViewer('mapviewer'); var pt = feature.geometry.clone(); /* form update */ var gpForm = viewer.getVariable('gpForm'); pt.transform(viewer.getMap().getProjection(), gpForm.getNativeProjection()); var invp = gpForm.getPrecision(); gpForm.setX(Math.round(pt.x*invp)/invp); gpForm.setY(Math.round(pt.y*invp)/invp); /* parent form update */ var gpParentForm = viewer.getVariable('gpParentForm'); if (gpParentForm) { var invp = gpParentForm.getPrecision(); gpParentForm.setX(Math.round(pt.x*invp)/invp); gpParentForm.setY(Math.round(pt.y*invp)/invp); } delete pt; }, updateFeature: function (elt, val) { var viewer = $.ZTFY.geoportal.getViewer('mapviewer'); var vlayer = viewer.getMap().getLayersByName('POINT_XY')[0]; var feature = vlayer.features[0]; var gpForm = viewer.getVariable('gpForm'); var x = gpForm.getX(); var y = gpForm.getY(); if (!isNaN(x) && !isNaN(y)) { // Delete previous point vlayer.destroyFeatures(); // Transform coordinates var geometry = new OpenLayers.Geometry.Point(x,y); geometry.transform(gpForm.getNativeProjection(), viewer.getMap().getProjection()); // Add marker feature = new OpenLayers.Feature.Vector(geometry); feature.state = OpenLayers.State.INSERT; vlayer.addFeatures(feature); // Set map position and zoom scale viewer.getMap().setCenterAtLonLat(x, y, 15); } // Initialize $.ZTFY.geoportal.updateXYForm(feature); return true; }, /** * Hide viewer controls * * @param viewer: GeoPortal viewer containing controls to hide */ hideControls: function(viewer) { viewer.lyrSwCntrl.showControls('none'); viewer.toolBoxCntrl.showControls('none'); viewer.infoCntrl.minimizeControl(); }, /** * Define map position */ setPosition: function(viewer, position, layer, zoom, extent) { var map = viewer.map; map.setCenterAtLonLat(position.lon, position.lat); if (layer) { if (!extent) { var extent = layer.getDataExtent(); } if (extent) { var zoom = map.getZoomForExtent(extent.transform(map.getDisplayProjection(), layer.projection), true); } } if (!zoom) { var zoom = 10; } map.setCenterAtLonLat(position.lon, position.lat, zoom); } } })(jQuery);
ztfy.geoportal
/ztfy.geoportal-0.2.5.tar.gz/ztfy.geoportal-0.2.5/src/ztfy/geoportal/browser/resources/js/ztfy.geoportal.js
ztfy.geoportal.js
(function(a){if(typeof(a.ZTFY)=="undefined"){a.ZTFY={}}a.ZTFY.geoportal={open:function(b,c){Geoportal=undefined;OpenLayers=undefined;a.ZTFY.dialog.open(c+"?prefix="+b);return false},initPlugin:function(c){if(window.__Geoportal$timer===undefined){var b=null}a.ZTFY.geoportal.initMap(c)},initMap:function(b){if(typeof(OpenLayers)==="undefined"||typeof(Geoportal)==="undefined"){setTimeout(a.ZTFY.geoportal.initMap,300,b);return}Geoportal.GeoRMHandler.getConfig([a(b).data("geoportal-api-key")],null,null,{onContractsComplete:function(){a(a.ZTFY.geoportal).data("geoportal-config",this);a.ZTFY.geoportal.loadMap(b)}})},loadMap:function(b){var c=a.ZTFY.geoportal.initViewer(b)},initViewer:function(t,c,r,u){Geoportal.GeoXYForm=OpenLayers.Class({containerId:null,buttonId:null,imgButton:null,lonId:null,latId:null,vectorProjection:"IGNF:RGF93G",precision:1000000,marker:null,container:null,button:null,Lon:null,Lat:null,initialize:function(v){OpenLayers.Util.extend(this,v);if(typeof(this.vectorProjection)=="string"){this.vectorProjection=new OpenLayers.Projection(this.vectorProjection)}this.container=parent.document.getElementById(this.containerId);this.button=parent.document.getElementById(this.buttonId);this.Lon=parent.document.getElementById(this.lonId);this.Lat=parent.document.getElementById(this.latId)},getXInput:function(){return this.Lon},getYInput:function(){return this.Lat},getX:function(){if(this.Lon){return parseFloat(this.Lon.value)}return NaN},getY:function(){if(this.Lat){return parseFloat(this.Lat.value)}return NaN},setX:function(v){if(this.Lon&&!isNaN(parseFloat(v))){this.Lon.value=v}},setY:function(v){if(this.Lat&&!isNaN(parseFloat(v))){this.Lat.value=v}},getPrecision:function(){return this.precision?this.precision:1000000},getNativeProjection:function(){return this.vectorProjection},CLASS_NAME:"Geoportal.GeoXYForm"});var e={mode:"normal",territory:c||"FXX",projection:r||null,displayProjection:u||"IGNF:RGF93G"};var n;if(typeof(t)=="string"){n=t;t=a('DIV[id="'+n+'"]')}else{n=a(t).attr("id")}var j=a(t).data("geoportal-api-key");var d=new Geoportal.Viewer.Default(n,OpenLayers.Util.extend(e,window.gGEOPORTALRIGHTSMANAGEMENT===undefined?{apiKey:apiKey}:gGEOPORTALRIGHTSMANAGEMENT));d.addGeoportalLayers(["ORTHOIMAGERY.ORTHOPHOTOS","GEOGRAPHICALGRIDSYSTEMS.MAPS"],{});d.map.getLayersByName("ORTHOIMAGERY.ORTHOPHOTOS")[0].visibility=false;d.map.getLayersByName("GEOGRAPHICALGRIDSYSTEMS.MAPS")[0].setOpacity(0.8);var t=a(t).get(0);a.data(t,"ztfy.geoportal.viewer",d);var o="location-widgets-longitude";var s="location-widgets-latitude";var l={containerId:n,lonId:o,latId:s,vectorProjection:new OpenLayers.Projection("EPSG:4326"),precision:1000000,marker:"/--static--/ztfy.geoportal/img/pin.png"};var b=new Geoportal.GeoXYForm(l);d.setVariable("gpForm",b);var i=null;if(b.marker){i=new OpenLayers.StyleMap({"default":OpenLayers.Util.extend({externalGraphic:b.marker,graphicOpacity:1,graphicWidth:14,graphicHeight:14,graphicXOffset:0,graphicYOffset:-14,fill:false},OpenLayers.Feature.Vector["default"]),temporary:OpenLayers.Util.extend({display:"none"},OpenLayers.Feature.Vector.temporary)})}var q=a.ZTFY.dialog.dialogs;if(q.length>0){var f=q[q.length-1].src;var p=a.ZTFY.getQueryVar(f,"prefix");if(p){p=p.replace(/\./g,"-");o=p+"-longitude";s=p+"-latitude"}}var h={containerId:t,lonId:o,latId:s,vectorProjection:new OpenLayers.Projection("EPSG:4326"),precision:1000000,marker:"/--static--/ztfy.geoportal/img/pin.png"};var g=new Geoportal.GeoXYForm(h);d.setVariable("gpParentForm",g);var k=new OpenLayers.Layer.Vector("POINT_XY",{projection:b.vectorProjection,displayInLayerSwitcher:false,calculateInRange:function(){return true},styleMap:i});d.getMap().addLayer(k);var m=new OpenLayers.Control.DrawFeature(k,OpenLayers.Handler.Point,{autoActivate:true,callbacks:{done:function(w){this.layer.destroyFeatures();var v=new OpenLayers.Feature.Vector(w,{pictoUrl:"/--static--/ztfy.geoportal/img/pin.png"});v.state=OpenLayers.State.INSERT;this.layer.addFeatures([v]);a.ZTFY.geoportal.updateXYForm(v)}},handlerOptions:{persist:false,layerOptions:{projection:b.vectorProjection}}});d.getMap().addControl(m);OpenLayers.Event.observe(b.getXInput(),"change",a.ZTFY.geoportal.updateFeature);OpenLayers.Event.observe(b.getYInput(),"change",a.ZTFY.geoportal.updateFeature);a.ZTFY.geoportal.updateFeature();return d},getViewer:function(b){if(typeof(b)=="string"){var b=a("DIV[id="+b+"]").get(0)}return a.data(b,"ztfy.geoportal.viewer")},updateXYForm:function(e,d){if(!e||!e.geometry||!e.geometry.x||!e.geometry.y){return}var h=a.ZTFY.geoportal.getViewer("mapviewer");var g=e.geometry.clone();var c=h.getVariable("gpForm");g.transform(h.getMap().getProjection(),c.getNativeProjection());var f=c.getPrecision();c.setX(Math.round(g.x*f)/f);c.setY(Math.round(g.y*f)/f);var b=h.getVariable("gpParentForm");if(b){var f=b.getPrecision();b.setX(Math.round(g.x*f)/f);b.setY(Math.round(g.y*f)/f)}delete g},updateFeature:function(c,b){var e=a.ZTFY.geoportal.getViewer("mapviewer");var f=e.getMap().getLayersByName("POINT_XY")[0];var j=f.features[0];var d=e.getVariable("gpForm");var i=d.getX();var h=d.getY();if(!isNaN(i)&&!isNaN(h)){f.destroyFeatures();var g=new OpenLayers.Geometry.Point(i,h);g.transform(d.getNativeProjection(),e.getMap().getProjection());j=new OpenLayers.Feature.Vector(g);j.state=OpenLayers.State.INSERT;f.addFeatures(j);e.getMap().setCenterAtLonLat(i,h,15)}a.ZTFY.geoportal.updateXYForm(j);return true},hideControls:function(b){b.lyrSwCntrl.showControls("none");b.toolBoxCntrl.showControls("none");b.infoCntrl.minimizeControl()},setPosition:function(g,b,c,e,d){var f=g.map;f.setCenterAtLonLat(b.lon,b.lat);if(c){if(!d){var d=c.getDataExtent()}if(d){var e=f.getZoomForExtent(d.transform(f.getDisplayProjection(),c.projection),true)}}if(!e){var e=10}f.setCenterAtLonLat(b.lon,b.lat,e)}}})(jQuery);
ztfy.geoportal
/ztfy.geoportal-0.2.5.tar.gz/ztfy.geoportal-0.2.5/src/ztfy/geoportal/browser/resources/js/ztfy.geoportal.min.js
ztfy.geoportal.min.js
# import standard packages from decimal import Decimal # import Zope3 interfaces from z3c.form.interfaces import NO_VALUE, IFieldWidget, IMultiWidget # import local interfaces from ztfy.geoportal.schema import ILocationField from ztfy.skin.layer import IZTFYBrowserLayer # import Zope3 packages from z3c.form.browser.multi import MultiWidget from z3c.form.converter import SequenceDataConverter from z3c.form.widget import FieldWidget from zope.component import adapter, adapts from zope.interface import implementer, implements # import local packages from ztfy.geoportal.browser import ztfy_geoportal class ILocationWidget(IMultiWidget): """Location widget interface""" class LocationDataConverter(SequenceDataConverter): """Location data converter""" adapts(ILocationField, ILocationWidget) def toWidgetValue(self, value): if value is self.field.missing_value: return None return str(value[0]), str(value[1]) def toFieldValue(self, value): if not value: return None return (Decimal(value[0]), Decimal(value[1])) class LocationWidget(MultiWidget): """Location widget""" implements(ILocationWidget) @property def longitude_id(self): return '%s-longitude' % self.id @property def longitude_name(self): return '%s.longitude' % self.name @property def longitude(self): return self.value and self.value[0] or '' @property def latitude_id(self): return '%s-latitude' % self.id @property def latitude_name(self): return '%s.latitude' % self.name @property def latitude(self): return self.value and self.value[1] or '' def extract(self, default=NO_VALUE): longitude = self.request.get(self.longitude_name) latitude = self.request.get(self.latitude_name) if not (longitude and latitude): return default return (longitude, latitude) def render(self): result = super(LocationWidget, self).render() if result: ztfy_geoportal.need() return result @adapter(ILocationField, IZTFYBrowserLayer) @implementer(IFieldWidget) def LocationFieldWidgetFactory(field, request): """ILocationField widget factory""" return FieldWidget(field, LocationWidget(request))
ztfy.geoportal
/ztfy.geoportal-0.2.5.tar.gz/ztfy.geoportal-0.2.5/src/ztfy/geoportal/browser/widget/location.py
location.py
__docformat__ = "restructuredtext" # import standard packages # import Zope3 interfaces from zope.annotation.interfaces import IAnnotations # import local interfaces from ztfy.blog.interfaces.blog import IBlog from ztfy.blog.interfaces.site import ISiteManager from ztfy.blog.interfaces.topic import ITopic from ztfy.hplskin.interfaces import ISiteManagerPresentationInfo, IBlogPresentationInfo, ITopicPresentationInfo from ztfy.hplskin.layer import IHPLLayer from ztfy.skin.interfaces import IPresentationTarget # import Zope3 packages from zope.component import adapts from zope.interface import implements from zope.proxy import ProxyBase, setProxiedObject # import local packages from ztfy.blog.defaultskin.topic import TopicPresentation as BaseTopicPresentation, \ TopicIndexView as BaseTopicIndexView, \ TopicResourcesView as BaseTopicResourcesView, \ TopicCommentsView as BaseTopicCommentsView from ztfy.hplskin.menu import HPLSkinDialogMenuItem from ztfy.utils.traversing import getParent from ztfy.hplskin import _ TOPIC_PRESENTATION_KEY = 'ztfy.hplskin.topic.presentation' class TopicPresentationViewMenuItem(HPLSkinDialogMenuItem): """Topic presentation menu item""" title = _(" :: Presentation model...") class TopicPresentation(BaseTopicPresentation): """Topic presentation infos""" implements(ITopicPresentationInfo) class TopicPresentationAdapter(ProxyBase): adapts(ITopic) implements(ITopicPresentationInfo) def __init__(self, context): annotations = IAnnotations(context) presentation = annotations.get(TOPIC_PRESENTATION_KEY) if presentation is None: presentation = annotations[TOPIC_PRESENTATION_KEY] = TopicPresentation() setProxiedObject(self, presentation) class TopicPresentationTargetAdapter(object): adapts(ITopic, IHPLLayer) implements(IPresentationTarget) target_interface = ITopicPresentationInfo def __init__(self, context, request): self.context, self.request = context, request class TopicIndexView(BaseTopicIndexView): """Topic index view""" class TopicResourcesView(BaseTopicResourcesView): """Topic resources view""" @property def resources(self): return ITopicPresentationInfo(self.context).linked_resources class TopicCommentsView(BaseTopicCommentsView): """Topic comments view""" @property def presentation(self): if not self.context.commentable: return None site = getParent(self.context, ISiteManager) if site is not None: return ISiteManagerPresentationInfo(site) blog = getParent(self.context, IBlog) if blog is not None: return IBlogPresentationInfo(blog) return None
ztfy.hplskin
/ztfy.hplskin-0.1.8.tar.gz/ztfy.hplskin-0.1.8/src/ztfy/hplskin/topic.py
topic.py
__docformat__ = "restructuredtext" # import standard packages # import Zope3 interfaces from zope.annotation.interfaces import IAnnotations # import local interfaces from ztfy.blog.interfaces.site import ISiteManager from ztfy.hplskin.interfaces import ISiteManagerPresentationInfo from ztfy.hplskin.layer import IHPLLayer from ztfy.skin.interfaces import IPresentationTarget # import Zope3 packages from zope.component import adapts from zope.interface import implements from zope.proxy import setProxiedObject, ProxyBase # import local packages from ztfy.blog.defaultskin.site import SiteManagerPresentation as BaseSiteManagerPresentation, \ SiteManagerIndexView as BaseSiteManagerIndexView from ztfy.hplskin.menu import HPLSkinDialogMenuItem from ztfy.hplskin import _ SITE_MANAGER_PRESENTATION_KEY = 'ztfy.hplskin.presentation' class SiteManagerPresentationViewMenuItem(HPLSkinDialogMenuItem): """Site manager presentation menu item""" title = _(" :: Presentation model...") class SiteManagerPresentation(BaseSiteManagerPresentation): """Site manager presentation infos""" implements(ISiteManagerPresentationInfo) class SiteManagerPresentationAdapter(ProxyBase): adapts(ISiteManager) implements(ISiteManagerPresentationInfo) def __init__(self, context): annotations = IAnnotations(context) presentation = annotations.get(SITE_MANAGER_PRESENTATION_KEY) if presentation is None: presentation = annotations[SITE_MANAGER_PRESENTATION_KEY] = SiteManagerPresentation() setProxiedObject(self, presentation) class SiteManagerPresentationTargetAdapter(object): adapts(ISiteManager, IHPLLayer) implements(IPresentationTarget) target_interface = ISiteManagerPresentationInfo def __init__(self, context, request): self.context, self.request = context, request class SiteManagerIndexView(BaseSiteManagerIndexView): """Site manager index page"""
ztfy.hplskin
/ztfy.hplskin-0.1.8.tar.gz/ztfy.hplskin-0.1.8/src/ztfy/hplskin/site.py
site.py
__docformat__ = "restructuredtext" # import standard packages from persistent import Persistent # import Zope3 interfaces from zope.app.file.interfaces import IImage from zope.annotation.interfaces import IAnnotations from zope.traversing.interfaces import TraversalError # import local interfaces from ztfy.blog.interfaces.site import ISiteManager from ztfy.file.interfaces import IImageDisplay from ztfy.hplskin.interfaces import IBannerImage, ITopBannerImageAddFormMenuTarget, \ ILeftBannerImageAddFormMenuTarget, IBannerManager, \ IBannerManagerContentsView from ztfy.skin.interfaces.container import IActionsColumn, IContainerTableViewActionsCell from ztfy.skin.layer import IZTFYBrowserLayer # import Zope3 packages from z3c.form import field from z3c.formjs import ajax from z3c.table.column import Column from z3c.template.template import getLayoutTemplate from zope.app.file.image import Image from zope.component import adapts, adapter, getAdapter, queryAdapter, queryMultiAdapter, getUtility from zope.container.contained import Contained from zope.i18n import translate from zope.interface import implements, implementer, Interface from zope.intid.interfaces import IIntIds from zope.location import locate from zope.publisher.browser import BrowserPage from zope.security.proxy import removeSecurityProxy from zope.traversing import namespace, api as traversing_api from zope.traversing.browser import absoluteURL # import local packages from ztfy.base.ordered import OrderedContainer from ztfy.file.property import ImageProperty from ztfy.hplskin.menu import HPLSkinMenuItem, HPLSkinDialogMenuItem from ztfy.skin.container import OrderedContainerBaseView from ztfy.skin.form import DialogAddForm from ztfy.utils.traversing import getParent from ztfy.utils.unicode import translateString from ztfy.hplskin import _ class BannerManager(OrderedContainer): """Banner manager""" implements(IBannerManager) BANNER_MANAGER_ANNOTATIONS_KEY = 'ztfy.hplskin.banner.%s' def BannerManagerFactory(context, name): """Banner manager factory""" annotations = IAnnotations(context) banner_key = BANNER_MANAGER_ANNOTATIONS_KEY % name manager = annotations.get(banner_key) if manager is None: manager = annotations[banner_key] = BannerManager() locate(manager, context, '++banner++%s' % name) return manager class BannerManagerNamespaceTraverser(namespace.view): """++banner++ namespace""" def traverse(self, name, ignored): site = getParent(self.context, ISiteManager) if site is not None: manager = queryAdapter(site, IBannerManager, name) if manager is not None: return manager raise TraversalError('++banner++') class BannerManagerContentsView(OrderedContainerBaseView): """Banner manager contents view""" implements(IBannerManagerContentsView) interface = IBannerImage @property def values(self): adapter = getAdapter(self.context, IBannerManager, self.name) if adapter is not None: return removeSecurityProxy(adapter).values() return [] @ajax.handler def ajaxRemove(self): oid = self.request.form.get('id') if oid: intids = getUtility(IIntIds) target = intids.getObject(int(oid)) parent = traversing_api.getParent(target) del parent[traversing_api.getName(target)] return "OK" return "NOK" @ajax.handler def ajaxUpdateOrder(self): adapter = getAdapter(self.context, IBannerManager, self.name) self.updateOrder(adapter) class IBannerManagerPreviewColumn(Interface): """Marker interface for resource container preview column""" class BannerManagerPreviewColumn(Column): """Resource container preview column""" implements(IBannerManagerPreviewColumn) header = u'' weight = 5 cssClasses = { 'th': 'preview', 'td': 'preview' } def renderCell(self, item): image = IImage(item.image, None) if image is None: return u'' display = IImageDisplay(image).getDisplay('64x64') return '''<img src="%s" alt="%s" />''' % (absoluteURL(display, self.request), traversing_api.getName(image)) class BannerManagerContentsViewActionsColumnCellAdapter(object): adapts(IBannerImage, IZTFYBrowserLayer, IBannerManagerContentsView, IActionsColumn) implements(IContainerTableViewActionsCell) def __init__(self, context, request, view, column): self.context = context self.request = request self.view = view self.column = column self.intids = getUtility(IIntIds) @property def content(self): klass = "ui-workflow ui-icon ui-icon-trash" result = '''<span class="%s" title="%s" onclick="$.ZTFY.form.remove(%d, this);"></span>''' % (klass, translate(_("Delete image"), context=self.request), self.intids.register(self.context)) return result # # Top banner custom classes extensions # @adapter(ISiteManager) @implementer(IBannerManager) def TopBannerManagerFactory(context): return BannerManagerFactory(context, 'top') class TopBannerContentsMenuItem(HPLSkinMenuItem): """TopBanner contents menu item""" title = _("Top banner") class TopBannerContentsView(BannerManagerContentsView): """TopBanner manager contents view""" implements(ITopBannerImageAddFormMenuTarget) legend = _("Top banner images") name = 'top' # # Left banner custom classes extensions # @adapter(ISiteManager) @implementer(IBannerManager) def LeftBannerManagerFactory(context): return BannerManagerFactory(context, 'left') class LeftBannerContentsMenuItem(HPLSkinMenuItem): """LeftBanner contents menu item""" title = _("Left banner") class LeftBannerContentsView(BannerManagerContentsView): """TopBanner manager contents view""" implements(ILeftBannerImageAddFormMenuTarget) legend = _("Left banner images") name = 'left' # # Banner images management # class BannerImage(Persistent, Contained): """Banner image""" implements(IBannerImage) image = ImageProperty(IBannerImage['image'], klass=Image, img_klass=Image) class BannerImageAddForm(DialogAddForm): """Banner image add form""" title = _("New banner image") legend = _("Adding new image") fields = field.Fields(IBannerImage) layout = getLayoutTemplate() parent_interface = ISiteManager handle_upload = True def create(self, data): return BannerImage() def add(self, image): data = self.request.form.get('form.widgets.image') filename = None if hasattr(data, 'filename'): filename = translateString(data.filename, escapeSlashes=True, forceLower=False, spaces='-') if filename in self.context: index = 2 name = '%s-%d' % (filename, index) while name in self.context: index += 1 name = '%s-%d' % (filename, index) filename = name if not filename: index = 1 filename = 'image-%d' % index while filename in self.context: index += 1 filename = 'image-%d' % index self.context[filename] = image class BannerImageAddMenuItem(HPLSkinDialogMenuItem): """Banner image add menu""" title = _(":: Add image...") target = BannerImageAddForm class TopBannerImageAddForm(BannerImageAddForm): parent_view = TopBannerContentsView class LeftBannerImageAddForm(BannerImageAddForm): parent_view = LeftBannerContentsView class BannerImageIndexView(BrowserPage): """Banner image default view""" def __call__(self): return queryMultiAdapter((self.context.image, self.request), Interface, 'index.html')()
ztfy.hplskin
/ztfy.hplskin-0.1.8.tar.gz/ztfy.hplskin-0.1.8/src/ztfy/hplskin/banner.py
banner.py
import os import shutil import sys import tempfile from optparse import OptionParser tmpeggs = tempfile.mkdtemp() usage = '''\ [DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options] Bootstraps a buildout-based project. Simply run this script in a directory containing a buildout.cfg, using the Python that you want bin/buildout to use. Note that by using --find-links to point to local resources, you can keep this script from going over the network. ''' parser = OptionParser(usage=usage) parser.add_option("-v", "--version", help="use a specific zc.buildout version") parser.add_option("-t", "--accept-buildout-test-releases", dest='accept_buildout_test_releases', action="store_true", default=False, help=("Normally, if you do not specify a --version, the " "bootstrap script and buildout gets the newest " "*final* versions of zc.buildout and its recipes and " "extensions for you. If you use this flag, " "bootstrap and buildout will get the newest releases " "even if they are alphas or betas.")) parser.add_option("-c", "--config-file", help=("Specify the path to the buildout configuration " "file to be used.")) parser.add_option("-f", "--find-links", help=("Specify a URL to search for buildout releases")) parser.add_option("--allow-site-packages", action="store_true", default=False, help=("Let bootstrap.py use existing site packages")) options, args = parser.parse_args() ###################################################################### # load/install setuptools try: if options.allow_site_packages: import setuptools import pkg_resources from urllib.request import urlopen except ImportError: from urllib2 import urlopen ez = {} exec(urlopen('https://bootstrap.pypa.io/ez_setup.py').read(), ez) if not options.allow_site_packages: # ez_setup imports site, which adds site packages # this will remove them from the path to ensure that incompatible versions # of setuptools are not in the path import site # inside a virtualenv, there is no 'getsitepackages'. # We can't remove these reliably if hasattr(site, 'getsitepackages'): for sitepackage_path in site.getsitepackages(): sys.path[:] = [x for x in sys.path if sitepackage_path not in x] setup_args = dict(to_dir=tmpeggs, download_delay=0) ez['use_setuptools'](**setup_args) import setuptools import pkg_resources # This does not (always?) update the default working set. We will # do it. for path in sys.path: if path not in pkg_resources.working_set.entries: pkg_resources.working_set.add_entry(path) ###################################################################### # Install buildout ws = pkg_resources.working_set cmd = [sys.executable, '-c', 'from setuptools.command.easy_install import main; main()', '-mZqNxd', tmpeggs] find_links = os.environ.get( 'bootstrap-testing-find-links', options.find_links or ('http://downloads.buildout.org/' if options.accept_buildout_test_releases else None) ) if find_links: cmd.extend(['-f', find_links]) setuptools_path = ws.find( pkg_resources.Requirement.parse('setuptools')).location requirement = 'zc.buildout' version = options.version if version is None and not options.accept_buildout_test_releases: # Figure out the most recent final version of zc.buildout. import setuptools.package_index _final_parts = '*final-', '*final' def _final_version(parsed_version): for part in parsed_version: if (part[:1] == '*') and (part not in _final_parts): return False return True index = setuptools.package_index.PackageIndex( search_path=[setuptools_path]) if find_links: index.add_find_links((find_links,)) req = pkg_resources.Requirement.parse(requirement) if index.obtain(req) is not None: best = [] bestv = None for dist in index[req.project_name]: distv = dist.parsed_version if _final_version(distv): if bestv is None or distv > bestv: best = [dist] bestv = distv elif distv == bestv: best.append(dist) if best: best.sort() version = best[-1].version if version: requirement = '=='.join((requirement, version)) cmd.append(requirement) import subprocess if subprocess.call(cmd, env=dict(os.environ, PYTHONPATH=setuptools_path)) != 0: raise Exception( "Failed to execute command:\n%s" % repr(cmd)[1:-1]) ###################################################################### # Import and run buildout ws.add_entry(tmpeggs) ws.require(requirement) import zc.buildout.buildout if not [a for a in args if '=' not in a]: args.append('bootstrap') # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args[0:0] = ['-c', options.config_file] zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs)
ztfy.i18n
/ztfy.i18n-0.3.5.tar.gz/ztfy.i18n-0.3.5/bootstrap.py
bootstrap.py
# import standard packages # import Zope3 interfaces from zope.schema.interfaces import RequiredMissing, IChoice # import local interfaces from ztfy.i18n.interfaces import IDefaultValueDict, II18nField, II18nTextLineField, II18nTextField, II18nHTMLField, \ II18nFileField, II18nImageField, II18nCthumbImageField # import Zope3 packages from zope.interface import implements from zope.schema import Dict, TextLine, Text, Choice # import local packages from ztfy.file.schema import FileField, ImageField, CthumbImageField class ILanguageField(IChoice): """Marker interface used to identify I18n language field""" class Language(Choice): """A custom language selector field""" implements(ILanguageField) def __init__(self, *args, **kw): super(Language, self).__init__(vocabulary='ZTFY languages', *args, **kw) _marker = dict() class DefaultValueDict(dict): """A custom dictionnary handling a default value""" implements(IDefaultValueDict) def __init__(self, default=None, *args, **kw): super(DefaultValueDict, self).__init__(*args, **kw) self._default = default def __delitem__(self, key): super(DefaultValueDict, self).__delitem__(key) self._p_changed = True def __setitem__(self, key, value): super(DefaultValueDict, self).__setitem__(key, value) self._p_changed = True def __missing__(self, key): return self._default def clear(self): super(DefaultValueDict, self).clear() self._p_changed = True def update(self, b): super(DefaultValueDict, self).update(b) self._p_changed = True def setdefault(self, key, failobj=None): if not self.has_key(key): self._p_changed = True return super(DefaultValueDict, self).setdefault(key, failobj) def pop(self, key, *args): self._p_changed = True return super(DefaultValueDict, self).pop(key, *args) def popitem(self): self._p_changed = True return super(DefaultValueDict, self).popitem() def get(self, key, default=None): result = super(DefaultValueDict, self).get(key, _marker) if result is _marker: if default is not None: result = default else: result = self._default return result def copy(self): result = DefaultValueDict(default=self._default, **self) return result class I18nField(Dict): """Base class for I18n schema fields A I18n field is a mapping object for which keys are languages and values are effective values of the given attribute. Selected values can be returned selectively (for editing), or automatically (to be displayed in an HTML page) based on user's browser's language settings """ implements(II18nField) def __init__(self, default_language=None, key_type=None, value_type=None, default=None, **kw): super(I18nField, self).__init__(key_type=TextLine(), value_type=value_type, default=DefaultValueDict(default), **kw) self._default_language = default_language def _validate(self, value): super(I18nField, self)._validate(value) if self.required: if self.default: return if not value: raise RequiredMissing for lang in value.values(): if lang: return raise RequiredMissing class I18nTextLine(I18nField): """Schema field used to define an I18n textline property""" implements(II18nTextLineField) def __init__(self, key_type=None, value_type=None, value_constraint=None, value_min_length=0, value_max_length=None, **kw): super(I18nTextLine, self).__init__(value_type=TextLine(constraint=value_constraint, min_length=value_min_length, max_length=value_max_length, required=False), **kw) class I18nText(I18nField): """Schema field used to define an I18n text property""" implements(II18nTextField) def __init__(self, key_type=None, value_type=None, value_constraint=None, value_min_length=0, value_max_length=None, **kw): super(I18nText, self).__init__(value_type=Text(constraint=value_constraint, min_length=value_min_length, max_length=value_max_length, required=False), **kw) class I18nHTML(I18nText): """Schema field used to define an I18n HTML text property""" implements(II18nHTMLField) class I18nFile(I18nField): """Schema field used to define an I18n file property I18n files are used when a single file should be provided in several languages. For example, you can publish articles in your own language, but with a set of PDF summaries available in several languages """ implements(II18nFileField) def __init__(self, key_type=None, value_type=None, value_constraint=None, value_min_length=0, value_max_length=None, **kw): super(I18nFile, self).__init__(value_type=FileField(constraint=value_constraint, min_length=value_min_length, max_length=value_max_length, required=False), **kw) def _validate(self, value): return class I18nImage(I18nFile): """Schema field used to define an I18n image property""" implements(II18nImageField) def __init__(self, key_type=None, value_type=None, value_constraint=None, value_min_length=0, value_max_length=None, **kw): super(I18nFile, self).__init__(value_type=ImageField(constraint=value_constraint, min_length=value_min_length, max_length=value_max_length, required=False), **kw) class I18nCthumbImage(I18nImage): """Schema field used to define an I18n image property handling square thumbnails""" implements(II18nCthumbImageField) def __init__(self, key_type=None, value_type=None, value_constraint=None, value_min_length=0, value_max_length=None, **kw): super(I18nFile, self).__init__(value_type=CthumbImageField(constraint=value_constraint, min_length=value_min_length, max_length=value_max_length, required=False), **kw)
ztfy.i18n
/ztfy.i18n-0.3.5.tar.gz/ztfy.i18n-0.3.5/src/ztfy/i18n/schema.py
schema.py
# import standard packages # import Zope3 interfaces from z3c.language.negotiator.interfaces import INegotiatorManager from z3c.language.switch.interfaces import II18n from zope.annotation.interfaces import IAnnotations from zope.location.interfaces import ISublocations # import local interfaces from ztfy.i18n.interfaces import I18nError, II18nManager, II18nManagerInfo, II18nAttributesAware from ztfy.i18n.interfaces import II18nFilePropertiesContainer, II18nFilePropertiesContainerAttributes # import Zope3 packages from zc.set import Set from zope.component import adapts, queryUtility from zope.interface import implements # import local packages from ztfy.i18n.schema import DefaultValueDict from ztfy.utils.request import queryRequest from ztfy.utils.traversing import getParent from ztfy.i18n import _ _marker = DefaultValueDict() class I18nLanguagesAdapter(object): """Adapter class for II18nManager interface""" adapts(II18nManager) implements(II18nManagerInfo) def __init__(self, context): self.context = context self._i18n = getParent(context, II18nManager, allow_context=False) self._negotiator = queryUtility(INegotiatorManager) def _getAvailableLanguages(self): result = getattr(self.context, '_available_languages', _marker) if result is _marker: if self._i18n is not None: result = II18nManagerInfo(self._i18n).availableLanguages elif self._negotiator is not None: result = self._negotiator.offeredLanguages else: result = [u'en', ] return result def _setAvailableLanguages(self, languages): self.context._available_languages = languages availableLanguages = property(_getAvailableLanguages, _setAvailableLanguages) def _getDefaultLanguage(self): result = getattr(self.context, '_default_language', _marker) if result is _marker: if self._i18n is not None: result = II18nManagerInfo(self._i18n).defaultLanguage elif self._negotiator is not None: result = self._negotiator.serverLanguage else: result = u'en' return result def _setDefaultLanguage(self, language): self.context._default_language = language defaultLanguage = property(_getDefaultLanguage, _setDefaultLanguage) class I18nAttributesAdapter(object): """Adapter class for II18nAttributesAware interface""" adapts(II18nAttributesAware) implements(II18n) def __init__(self, context): self.context = context self._i18n = getParent(context, II18nManager) self._negotiator = queryUtility(INegotiatorManager) def getDefaultLanguage(self): if self._i18n is not None: return II18nManagerInfo(self._i18n).defaultLanguage elif self._negotiator is not None: return self._negotiator.serverLanguage else: return u'en' def setDefaultLanguage(self, language): raise I18nError, _("""Default language is defined by I18nManager properties""") def addLanguage(self, language, *args, **kw): raise I18nError, _("""Use I18nManager properties to handle languages list""") def removeLanguage(self, language): raise I18nError, _("""Use I18nManager properties to handle languages list""") def getAvailableLanguages(self): if self._i18n is not None: return II18nManagerInfo(self._i18n).availableLanguages elif self._negotiator is not None: return self._negotiator.offeredLanguages else: return [u'en', ] def getPreferedLanguage(self, request=None): languages = self.getAvailableLanguages() if request is None: request = queryRequest() if (request is not None) and (self._negotiator is not None): return self._negotiator.getLanguage(languages, request) return u'en' def getAttribute(self, name, language=None, request=None, query=False): result = getattr(self.context, name, _marker) if not isinstance(result, DefaultValueDict): return result if language is None: language = self.getPreferedLanguage(request) if query: return result.get(language, _marker) return result.get(language, None) def queryAttribute(self, name, language=None, default=None, request=None): result = self.getAttribute(name, language, request, query=True) if (result is _marker) or (result is None) or (result == ''): language = self.getDefaultLanguage() result = self.getAttribute(name, language, request, query=True) if result is not _marker: return result return default def setAttribute(self, attribute, value, language=None): if language is None: language = self.getDefaultLanguage() current_value = getattr(self.context, attribute) if isinstance(current_value, DefaultValueDict): current_value[language] = value def setAttributes(self, language, **kw): for key in kw: self.setAttribute(key, kw[key], language) I18N_FILE_PROPERTIES_ANNOTATIONS_KEY = 'ztfy.i18n.file.container.attributes' class I18nFilePropertiesContainerAttributesAdapter(object): """File properties container attributes adapter""" adapts(II18nFilePropertiesContainer) implements(II18nFilePropertiesContainerAttributes) def __init__(self, context): self.context = context annotations = IAnnotations(context) attributes = annotations.get(I18N_FILE_PROPERTIES_ANNOTATIONS_KEY) if attributes is None: attributes = annotations[I18N_FILE_PROPERTIES_ANNOTATIONS_KEY] = Set() self.attributes = attributes class I18nFilePropertiesContainerSublocationsAdapter(object): """File properties container sub-locations adapter""" adapts(II18nFilePropertiesContainer) implements(ISublocations) def __init__(self, context): self.context = context def sublocations(self): for attr in II18nFilePropertiesContainerAttributes(self.context).attributes: for value in (v for v in getattr(self.context, attr, {}).values() if v is not None): yield value
ztfy.i18n
/ztfy.i18n-0.3.5.tar.gz/ztfy.i18n-0.3.5/src/ztfy/i18n/adapter.py
adapter.py
# import standard packages # import Zope3 interfaces from zope.catalog.interfaces import ICatalog from zope.lifecycleevent.interfaces import IObjectCopiedEvent, IObjectAddedEvent, IObjectRemovedEvent # import local interfaces from ztfy.i18n.interfaces import II18nFilePropertiesContainer, II18nFilePropertiesContainerAttributes # import Zope3 packages from ZODB.blob import Blob from zope.lifecycleevent import ObjectRemovedEvent from zope.component import adapter, getUtilitiesFor from zope.event import notify from zope.location import locate # import local packages from ztfy.extfile.blob import BaseBlobFile from ztfy.utils import catalog @adapter(II18nFilePropertiesContainer, IObjectAddedEvent) def handleAddedI18nFilePropertiesContainer(object, event): # When a file properties container is added, we must index it's attributes if not hasattr(object, '_v_copied_file'): return for _name, catalog_util in getUtilitiesFor(ICatalog): for attr in II18nFilePropertiesContainerAttributes(object).attributes: for value in getattr(object, attr, {}).values(): if value is not None: locate(value, object, value.__name__) catalog.indexObject(value, catalog_util) delattr(object, '_v_copied_file') @adapter(II18nFilePropertiesContainer, IObjectRemovedEvent) def handleRemovedI18nFilePropertiesContainer(object, event): # When a file properties container is removed, we must unindex it's attributes for _name, catalog_util in getUtilitiesFor(ICatalog): for attr in II18nFilePropertiesContainerAttributes(object).attributes: for value in getattr(object, attr, {}).values(): if value is not None: notify(ObjectRemovedEvent(value)) catalog.unindexObject(value, catalog_util) @adapter(II18nFilePropertiesContainer, IObjectCopiedEvent) def handleCopiedI18nFilePropertiesContainer(object, event): # When a file properties container is copied, we have to tag it for indexation # Effective file indexation will be done only after content have been added to it's new parent container object._v_copied_file = True # We also have to update object's blobs to avoid losing contents... source = event.original for attr in II18nFilePropertiesContainerAttributes(source).attributes: for key, value in getattr(source, attr, {}).items(): if isinstance(value, BaseBlobFile): getattr(object, attr)[key]._blob = Blob() getattr(object, attr)[key].data = value.data
ztfy.i18n
/ztfy.i18n-0.3.5.tar.gz/ztfy.i18n-0.3.5/src/ztfy/i18n/events.py
events.py
__docformat__ = "restructuredtext" # import standard packages # import Zope3 interfaces from zope.schema.interfaces import IVocabularyFactory # import local interfaces # import Zope3 packages from zope.i18n import translate from zope.interface import classProvides from zope.schema.vocabulary import SimpleTerm, SimpleVocabulary # import local packages from ztfy.utils.request import queryRequest from ztfy.i18n import _ BASE_LANGUAGES = { u'aa': _('Afar'), u'ab': _('Abkhazian'), u'ae': _('Avestan'), u'af': _('Afrikaans'), u'ak': _('Akan'), u'am': _('Amharic'), u'an': _('Aragonese'), u'ar': _('Arabic'), u'as': _('Assamese'), u'av': _('Avaric'), u'ay': _('Aymara'), u'az': _('Azerbaijani'), u'ba': _('Bashkir'), u'be': _('Belarusian'), u'bg': _('Bulgarian'), u'bh': _('Bihari'), u'bi': _('Bislama'), u'bm': _('Bambara'), u'bn': _('Bengali'), u'bo': _('Tibetan'), u'br': _('Breton'), u'bs': _('Bosnian'), u'ca': _('Catalan'), u'ce': _('Chechen'), u'ch': _('Chamorro'), u'co': _('Corsican'), u'cr': _('Cree'), u'cs': _('Czech'), u'cu': _('Old Church Slavonic'), u'cv': _('Chuvash'), u'cy': _('Welsh'), u'da': _('Danish'), u'de': _('German'), u'dv': _('Divehi'), u'dz': _('Dzongkha'), u'ee': _('Ewe'), u'el': _('Greek'), u'en': _('English'), u'eo': _('Esperanto'), u'es': _('Spanish'), u'et': _('Estonian'), u'eu': _('Basque'), u'fa': _('Persian'), u'ff': _('Fulah'), u'fi': _('Finnish'), u'fj': _('Fijian'), u'fo': _('Faroese'), u'fr': _('French'), u'fy': _('Western Frisian'), u'ga': _('Irish'), u'gd': _('Scottish Gaelic'), u'gl': _('Galician'), u'gn': _('Guarani'), u'gu': _('Gujarati'), u'gv': _('Manx'), u'ha': _('Hausa'), u'he': _('Hebrew'), u'hi': _('Hindi'), u'ho': _('Hiri Motu'), u'hr': _('Croatian'), u'ht': _('Haitian'), u'hu': _('Hungarian'), u'hy': _('Armenian'), u'hz': _('Herero'), u'ia': _('Interlingua'), u'id': _('Indonesian'), u'ie': _('Interlingue'), u'ig': _('Igbo'), u'ii': _('Sichuan Yi'), u'ik': _('Inupiaq'), u'io': _('Ido'), u'is': _('Icelandic'), u'it': _('Italian'), u'iu': _('Inuktitut'), u'ja': _('Japanese'), u'jv': _('Javanese'), u'ka': _('Georgian'), u'kg': _('Kongo'), u'ki': _('Kikuyu'), u'kj': _('Kwanyama'), u'kk': _('Kazakh'), u'kl': _('Kalaallisut'), u'km': _('Khmer'), u'kn': _('Kannada'), u'ko': _('Korean'), u'kr': _('Kanuri'), u'ks': _('Kashmiri'), u'ku': _('Kurdish'), u'kv': _('Komi'), u'kw': _('Cornish'), u'ky': _('Kirghiz'), u'la': _('Latin'), u'lb': _('Luxembourgish'), u'lg': _('Ganda'), u'li': _('Limburgish'), u'ln': _('Lingala'), u'lo': _('Lao'), u'lt': _('Lithuanian'), u'lu': _('Luba-Katanga'), u'lv': _('Latvian'), u'mg': _('Malagasy'), u'mh': _('Marshallese'), u'mi': _('Maori'), u'mk': _('Macedonian'), u'ml': _('Malayalam'), u'mn': _('Mongolian'), u'mo': _('Moldavian'), u'mr': _('Marathi'), u'ms': _('Malay'), u'mt': _('Maltese'), u'my': _('Burmese'), u'na': _('Nauru'), u'nb': _('Norwegian Bokmal'), u'nd': _('North Ndebele'), u'ne': _('Nepali'), u'ng': _('Ndonga'), u'nl': _('Dutch'), u'nn': _('Norwegian Nynorsk'), u'no': _('Norwegian'), u'nr': _('South Ndebele'), u'nv': _('Navajo'), u'ny': _('Chichewa'), u'oc': _('Occitan'), u'oj': _('Ojibwa'), u'om': _('Oromo'), u'or': _('Oriya'), u'os': _('Ossetian'), u'pa': _('Panjabi'), u'pi': _('Pali'), u'pl': _('Polish'), u'ps': _('Pashto'), u'pt': _('Portuguese'), u'qu': _('Quechua'), u'rm': _('Raeto-Romance'), u'rn': _('Kirundi'), u'ro': _('Romanian'), u'ru': _('Russian'), u'rw': _('Kinyarwanda'), u'sa': _('Sanskrit'), u'sc': _('Sardinian'), u'sd': _('Sindhi'), u'se': _('Northern Sami'), u'sg': _('Sango'), u'si': _('Sinhalese'), u'sk': _('Slovak'), u'sl': _('Slovene'), u'sm': _('Samoan'), u'sn': _('Shona'), u'so': _('Somali'), u'sq': _('Albanian'), u'sr': _('Serbian'), u'ss': _('Swati'), u'st': _('Sotho'), u'su': _('Sundanese'), u'sv': _('Swedish'), u'sw': _('Swahili'), u'ta': _('Tamil'), u'te': _('Telugu'), u'tg': _('Tajik'), u'th': _('Thai'), u'ti': _('Tigrinya'), u'tk': _('Turkmen'), u'tl': _('Tagalog'), u'tn': _('Tswana'), u'to': _('Tonga'), u'tr': _('Turkish'), u'ts': _('Tsonga'), u'tt': _('Tatar'), u'tw': _('Twi'), u'ty': _('Tahitian'), u'ug': _('Uighur'), u'uk': _('Ukrainian'), u'ur': _('Urdu'), u'uz': _('Uzbek'), u've': _('Venda'), u'vi': _('Vietnamese'), u'vo': _('Volapuk'), u'wa': _('Walloon'), u'wo': _('Wolof'), u'xh': _('Xhosa'), u'yi': _('Yiddish'), u'yo': _('Yoruba'), u'za': _('Zhuang'), u'zh': _('Chinese'), u'zu': _('Zulu') } class BaseLanguagesVocabulary(SimpleVocabulary): """Base languages vocabulary, matching ISO 639-1 languages codes""" classProvides(IVocabularyFactory) def __init__(self, *args, **kw): request = queryRequest() terms = sorted([SimpleTerm(v, title=translate(t, context=request)) for v, t in BASE_LANGUAGES.iteritems()]) terms.sort(key=lambda x: x.title) super(BaseLanguagesVocabulary, self).__init__(terms) ISO_LANGUAGES = { u'aa-ET': _("Afar (Ethiopia)"), u'ab-GE': _("Abkhazian"), u'ae-IR': _("Avestan (Iran)"), u'af-ZA': _('Afrikaans'), u'ak-GH': _("Akan (Ghana)"), u'am-ET': _('Amharic (Ethiopia)'), u'an-ES': _("Aragonese (Spain)"), u'ar-AE': _('Arabic united Arab Emirates)'), u'ar-BH': _('Arabic (Bahrain)'), u'ar-DZ': _('Arabic (Algeria)'), u'ar-EG': _('Arabic (Egypt)'), u'ar-IQ': _('Arabic (Iraq)'), u'ar-JO': _('Arabic (Jordan)'), u'ar-KW': _('Arabic (Kuwait)'), u'ar-LB': _('Arabic (Lebanon)'), u'ar-LY': _('Arabic (Libyan Arab Jamahiriya)'), u'ar-MA': _('Arabic (Morocco)'), u'ar-OM': _('Arabic (Oman)'), u'ar-QA': _('Arabic (Qatar)'), u'ar-SA': _('Arabic (Saudi Arabia)'), u'ar-SY': _('Arabic (Syrian Arab Republic)'), u'ar-TN': _('Arabic (Tunisia)'), u'ar-YE': _('Arabic (Yemen)'), u'arn-CL': _('Mapudungun (Chile)'), u'as-IN': _('Assamese (India)'), u'ast-ES': _('Asturien'), u'av-RU': _("Avaric (Russia)"), u'ay-BO': _("Aymara (Bolivia)"), u'az-AZ-Cyrl': _('Azerbaijani (Cyrillic)'), u'az-AZ-Latn': _('Azerbaijani (Latin)'), u'ba-RU': _('Bashkir (Russia)'), u'be-BY': _('Belarusian (Belarus)'), u'ber-DZ': _('Berber (Algeria, Latin)'), u'bg-BG': _('Bulgarian'), u'bh-IN': _("Bihari (India)"), u'bi-VU': _("Bislama (Vanuatu)"), u'bm-ML': _("Bambara (Mali)"), u'bn-IN': _('Bengali (India)'), u'bo-BT': _('Tibetan (Bhutan)'), u'bo-CN': _('Tibetan (China)'), u'br-FR': _('Breton'), u'bs-BA-Cyrl': _('Bosnian (Bosnia Herzegovina, Cyrillic)'), u'bs-BA-Latn': _('Bosnian (Bosnie Herzegovina, Latin)'), u'ca-AD': _('Catalan (Andorra)'), u'ca-ES': _('Catalan (Spain)'), u'ca-FR': _('Catalan (France)'), u'ce-RU': _('Chechen'), u'ch-US': _('Chamorro'), u'co-FR': _('Corsican (France)'), u'cr-CA': _('Cree (Canada)'), u'cs-CZ': _('Czech'), u'cu-BG': _('Old Slavonic'), u'cv-RU': _('Chuvash (Russia)'), u'cy-GB': _('Welsh'), u'da-DK': _('Danish'), u'de-AT': _('German (Austria)'), u'de-CH': _('German (Swotzerland)'), u'de-DE': _('German (Germany)'), u'de-LI': _('German (Liechtenstein)'), u'de-LU': _('German (Luxembourg)'), u'dv-MV': _('Divehi (Maldives)'), u'dz-BT': _('Dzongkha (Bhutan)'), u'ee-GH': _('Ewe (Ghana)'), u'el-GR': _('Greek'), u'en-AU': _('English (Australia)'), u'en-BZ': _('English (Belize)'), u'en-CA': _('English (Canada)'), u'en-CB': _('English (Caraibes)'), u'en-GB': _('English (United Kingdom)'), u'en-IE': _('English (Ireland)'), u'en-IN': _('English (India)'), u'en-JA': _('English (Jamaica)'), u'en-MY': _('English (Malaysia)'), u'en-NZ': _('English (New Zealand)'), u'en-PH': _('English (Philippines)'), u'en-SG': _('English (Singapore)'), u'en-TT': _('English (Trinidad)'), u'en-US': _('English (United States)'), u'en-ZA': _('English (South Africa)'), u'en-ZW': _('English (Zimbabwe)'), u'eo': _('Esperanto'), u'es-AR': _('Spanish (Argentina)'), u'es-BO': _('Spanish (Bolivia)'), u'es-CL': _('Spanish (Chile)'), u'es-CO': _('Spanish (Colombia)'), u'es-CR': _('Spanish (Costa Rica)'), u'es-DO': _('Spanish (Dominican Republic)'), u'es-EC': _('Spanish (Ecuador)'), u'es-ES': _('Spanish (Spain)'), u'es-ES-ts': _('Spanish (Spain, Traditional)'), u'es-GT': _('Spanish (Guatemala)'), u'es-HN': _('Spanish (Honduras)'), u'es-MX': _('Spanish (Mexico)'), u'es-NI': _('Spanish (Nicaragua)'), u'es-PA': _('Spanish (Panama)'), u'es-PE': _('Spanish (Peru)'), u'es-PR': _('Spanish (Puerto Rico)'), u'es-PY': _('Spanish (Paraguay)'), u'es-SV': _('Spanish (El Salvador)'), u'es-UR': _('Spanish (Uruguay)'), u'es-US': _('Spanish (United States)'), u'es-VE': _('Spanish (Venezuela)'), u'et-EE': _('Estonian (Estonia)'), u'eu-ES': _('Basque'), u'fa-IR': _('Persian (Iran)'), u'fi-FI': _('Finish'), u'fil-PH': _('Philippine'), u'fj-FJ': _('Fijian'), u'fo-FO': _('Faroese (Faroe Islands)'), u'fr-FR': _('French (France)'), u'fr-BE': _('French (Belgium)'), u'fr-CA': _('French (Canada)'), u'fr-CH': _('French (Switzerland)'), u'fr-LU': _('French (Luxembourg)'), u'fr-MC': _('French (Monaco)'), u'fur-IT': _('Frioulan (Italia)'), u'fy-NL': _('Frisian (Netherlands)'), u'ga-IE': _('Irish'), u'gbz-AF': _('Dari (Afghanistan)'), u'gd-GB': _('Gaelic (Scotland)'), u'gl-ES': _('Galician'), u'gsw-FR': _('Alsatian (France)'), u'gu-IN': _('Gujarati (India)'), u'ha-NG-Latn': _('Hausa (Nigeria)'), u'he-IL': _('Hebrew (Israel)'), u'hi-IN': _('Hindi (Inde)'), u'hr-BA': _('Croatian (Bosnia Herzegovina, Latin)'), u'hr-HR': _('Croatian (Croatia)'), u'hu-HU': _('Hungarian'), u'hy-AM': _('Armenian (Armenia)'), u'id-ID': _('Indonesian'), u'ii-CN': _('Yi (China)'), u'iu-CA-Cans': _('Inuktitut (Canada, Syllabic)'), u'iu-CA-Latn': _('Inuktitut (Canada, Latin)'), u'is-IS': _('Icelandic'), u'it-CH': _('Italian (Switzerland)'), u'it-IT': _('Italian (Italia)'), u'ja-JP': _('Japanese'), u'ja-JP-mac': _('Japanese (Japan, Mac)'), u'ka-GE': _('Georgian'), u'kk-KZ': _('Kazakh (Kazakhstan)'), u'kl-GL': _('Greenlandic'), u'km-KH': _('Khmer (Cambodia)'), u'kn-IN': _('Kannada (India)'), u'ko-KR': _('Korean (Korea)'), u'kok-IN': _('Konkani (India)'), u'kw-GB': _('Cornish'), u'ky-KG': _('Kirghiz (Kyrgizstan)'), u'lb-LU': _('Luxembourgish'), u'lo-LA': _('Lao'), u'lt-LT': _('Lituanian'), u'lv-LV': _('Latvian'), u'mi-NZ': _('Maori (New Zealand)'), u'mk-MK': _('Macedonian'), u'ml-IN': _('Malayalam (Inde)'), u'mn-CN': _('Mongolian (China)'), u'mn-MN': _('Mongolian (Mongolia)'), u'moh-CA': _('Mohawk (Canada)'), u'mr-IN': _('Marathi (Inde)'), u'ms-BN': _('Malay (Brunei)'), u'ms-MY': _('Malay'), u'mt-MT': _('Maltese'), u'my-MM': _('Burmese (Myanmar)'), u'nb-NO': _('Norwegian (Bokmal)'), u'nn-NO': _('Norwegian (Nynorsk)'), u'ne-NP': _('Nepali'), u'nl-BE': _('Dutch (Belgium)'), u'nl-NL': _('Dutch (Netherlands)'), u'oc-FR': _('Occitan (France)'), u'or-IN': _('Oriya (India)'), u'pa-IN': _('Punjabi (India)'), u'pl-PL': _('Polish'), u'ps-AF': _('Pachto (Afghanistan)'), u'pt-BR': _('Portuguese (Brazil)'), u'pt-PT': _('Portuguese (Portugal)'), u'que-BO': _('Quechua (Bolivia)'), u'que-EC': _('Quechua (Ecuador)'), u'que-PE': _('Quechua (Peru)'), u'rm-CH': _('Romansh'), u'ro-RO': _('Romanian'), u'ru-RU': _('Russian'), u'rw-RW': _('Kinyarwanda (Rwanda)'), u'sa-IN': _('Sanskrit (Inde)'), u'sah-RU': _('Yakut (Russia)'), u'se-FI': _('Sami (Northern, Finland)'), u'se-NO': _('Sami (Northern, Norway)'), u'se-SE': _('Sami (Northern, Sweden)'), u'si-LK': _('Sinhala (Sri Lanka)'), u'sk-SK': _('Slovak'), u'sl-SI': _('Slovenian'), u'sr-BA-Cyrl': _('Serbian (Bosnia Herzegovina, Cyrillic)'), u'sr-BA-Latn': _('Serbian (Bosnia Herzegovina, Latin)'), u'sr-SP-Cyrl': _('Serbian (Serbia and Montenegro, Cyrillic)'), u'sr-SP-Latn': _('Serbian (Serbia and Montenegro, Latin)'), u'sma-NO': _('Sami (Southern, Norway)'), u'sma-SE': _('Sami (Southern, Sweden)'), u'smj-NO': _('Sami (Lule, Norway)'), u'smj-SE': _('Sami (Lule, Sweden)'), u'smn-FI': _('Sami (Inari, Finland)'), u'sms-FI': _('Sami (Skolt, Finland)'), u'sq-AL': _('Albanian'), u'sv-FI': _('Swedish (Finland)'), u'sv-SE': _('Swedish (Sweden)'), u'sw-KE': _('Swahili (Kenya)'), u'syr-SY': _('Syriac'), u'ta-IN': _('Tamil (India)'), u'te-IN': _('Telugu (India)'), u'tg-TJ-Cyrl': _('Tajik (Tajikistan)'), u'th-TH': _('Thai (Thailand)'), u'tk-TM': _('Turkmen (Turkmenistan)'), u'tn-ZA': _('Tswana (South Africa)'), u'tr-TR': _('Turkish'), u'tt-RU': _('Tatar (Russia)'), u'ug-CN': _('Uighur (China)'), u'uk-UA': _('Ukrainian'), u'ur-IN': _('Urdu (Inde)'), u'ur-PK': _('Urdu (Pakistan)'), u'uz-UZ-Cyrl': _('Uzbek uzbekistan, Cyrillic)'), u'uz-UZ-Latn': _('Uzbek uzbekistan, Latin)'), u'vi-VN': _('Vietnamese'), u'wen-DE': _('Sorbian (Germany)'), u'wo-SN': _('Wolof (Senegal)'), u'xh-ZA': _('Xhosa (South Africa)'), u'yo-NG': _('Yoruba (Nigeria)'), u'zh-CHS': _('Chinese (Simplified)'), u'zh-CHT': _('Chinese (Traditional)'), u'zh-CN': _('Chinese (China)'), u'zh-HK': _('Chinese (Hong Kong, China)'), u'zh-MO': _('Chinese (Macao)'), u'zh-SG': _('Chinese (Singapore)'), u'zh-TW': _('Chinese (Taiwan)'), u'zu-ZA': _('Zulu (South Africa)') } class LanguagesVocabulary(SimpleVocabulary): classProvides(IVocabularyFactory) def __init__(self, *args, **kw): request = queryRequest() terms = sorted([SimpleTerm(v, title=translate(t, context=request)) for v, t in ISO_LANGUAGES.iteritems()]) terms.sort(key=lambda x: x.title) super(LanguagesVocabulary, self).__init__(terms)
ztfy.i18n
/ztfy.i18n-0.3.5.tar.gz/ztfy.i18n-0.3.5/src/ztfy/i18n/languages.py
languages.py
# import standard packages import mimetypes # import Zope3 interfaces from z3c.form.interfaces import NOT_CHANGED from zope.app.file.interfaces import IFile from zope.location.interfaces import ILocation # import local interfaces from ztfy.file.interfaces import ICthumbImageFieldData, IThumbnailGeometry from ztfy.i18n.interfaces import II18nFilePropertiesContainer, II18nFilePropertiesContainerAttributes, II18nField # import Zope3 packages from zope.app.file import File, Image from zope.event import notify from zope.i18n import translate from zope.interface import alsoProvides from zope.lifecycleevent import ObjectCreatedEvent, ObjectAddedEvent, ObjectRemovedEvent from zope.location import locate from zope.security.proxy import removeSecurityProxy # import local packages from ztfy.extfile import getMagicContentType from ztfy.utils.request import queryRequest from ztfy.utils.unicode import uninvl from ztfy.i18n import _ _marker = dict() class translated(object): """Automatically translated property decorator To use it, just write: class Test(object): @translated def attr(self): return _("My translated string") """ def __init__(self, func): self.func = func def __get__(self, inst, cls): if inst is None: return self return translate(self.func(inst), context=queryRequest()) class I18nProperty(object): """Base class for I18n properties""" def __init__(self, field, name=None, converters=(), value_converters=()): if not II18nField.providedBy(field): raise ValueError, _("Provided field must implement II18nField interface...") if name is None: name = field.__name__ self.__field = field self.__name = name self.__converters = converters self.__value_converters = value_converters def __get__(self, instance, klass): if instance is None: return self value = instance.__dict__.get(self.__name, _marker) if value is _marker: field = self.__field.bind(instance) value = getattr(field, 'default', _marker) if value is _marker: raise AttributeError(self.__name) return value def __set__(self, instance, value): for converter in self.__converters: value = converter(value) for converter in self.__value_converters: for lang in value: value[lang] = converter(value[lang]) field = self.__field.bind(instance) field.validate(value) if field.readonly and instance.__dict__.has_key(self.__name): raise ValueError(self.__name, _("Field is readonly")) old_value = instance.__dict__.get(self.__name, _marker) if old_value is _marker: old_value = self.__field.default.copy() for k in value: old_value[k] = value[k] instance.__dict__[self.__name] = old_value def __getattr__(self, name): return getattr(self.__field, name) class I18nTextProperty(I18nProperty): """I18n property to handle Text and TextLine values""" def __init__(self, field, name=None, converters=(), value_converters=()): super(I18nTextProperty, self).__init__(field, name, converters=converters, value_converters=(uninvl,) + value_converters) class I18nFileProperty(I18nProperty): """I18n property to handle files""" def __init__(self, field, name=None, converters=(), value_converters=(), klass=File, img_klass=None, **args): super(I18nFileProperty, self).__init__(field, name, converters, value_converters) self.__klass = klass self.__img_klass = img_klass self.__args = args def __set__(self, instance, value): for converter in self._I18nProperty__converters: value = converter(value) for converter in self._I18nProperty__value_converters: for lang in value: value[lang] = converter(value[lang]) filenames = {} for lang in value: if value[lang] is NOT_CHANGED: continue elif value[lang] is not None: if isinstance(value[lang], tuple): value[lang], filenames[lang] = value[lang] if not IFile.providedBy(value[lang]): content_type = getMagicContentType(value[lang]) or 'text/plain' if filenames.get(lang) and content_type.startswith('text/'): content_type = mimetypes.guess_type(filenames[lang])[0] or content_type if (self.__img_klass is not None) and content_type.startswith('image/'): f = self.__img_klass(**self.__args) else: f = self.__klass(**self.__args) notify(ObjectCreatedEvent(f)) f.data = value[lang] f.contentType = content_type value[lang] = f field = self._I18nProperty__field.bind(instance) field.validate(value) if field.readonly and instance.__dict__.has_key(self.__name): raise ValueError(self._I18nProperty__name, _("Field is readonly")) old_value = instance.__dict__.get(self._I18nProperty__name, _marker) if old_value is _marker: old_value = self._I18nProperty__field.default.copy() for k in value: old_file = old_value.get(k, _marker) new_file = value[k] if new_file is NOT_CHANGED: continue elif old_file != new_file: if (old_file is not _marker) and (old_file is not None): notify(ObjectRemovedEvent(old_file)) if new_file is not None: filename = '++i18n++%s:%s' % (self._I18nProperty__name, k) if new_file.contentType: filename += mimetypes.guess_extension(new_file.contentType) or '' locate(new_file, removeSecurityProxy(instance), filename) alsoProvides(new_file, ILocation) alsoProvides(instance, II18nFilePropertiesContainer) II18nFilePropertiesContainerAttributes(instance).attributes.add(self._I18nProperty__name) notify(ObjectAddedEvent(new_file, instance, filename)) old_value[k] = new_file instance.__dict__[self._I18nProperty__name] = old_value class I18nImageProperty(I18nFileProperty): """I18n property to handle images""" def __init__(self, field, name=None, converters=(), value_converters=(), klass=Image, img_klass=None, **args): super(I18nImageProperty, self).__init__(field, name, converters, value_converters, klass, img_klass, **args) def __set__(self, instance, value): values = {} geoms = {} for lang in value: data = ICthumbImageFieldData(value[lang], None) if data is not None: values[lang] = data.value geoms[lang] = data.geometry else: values[lang] = value[lang] super(I18nImageProperty, self).__set__(instance, values) if geoms: new_value = instance.__dict__.get(self._I18nProperty__name, _marker) if new_value is not _marker: for lang in geoms: geometry = IThumbnailGeometry(new_value.get(lang), None) if geometry is not None: geometry.position = geoms[lang].position geometry.size = geoms[lang].size
ztfy.i18n
/ztfy.i18n-0.3.5.tar.gz/ztfy.i18n-0.3.5/src/ztfy/i18n/property.py
property.py
__docformat__ = "restructuredtext" # import standard packages # import Zope3 interfaces # import local interfaces from ztfy.base.interfaces import IBaseContent from ztfy.i18n.interfaces import II18nAttributesAware from ztfy.i18n.schema import I18nTextLine, I18nText, I18nImage, I18nCthumbImage # import Zope3 packages # import local packages from ztfy.i18n import _ # # I18n aware contents interfaces # class II18nBaseContent(IBaseContent, II18nAttributesAware): """Base content interface""" title = I18nTextLine(title=_("Title"), description=_("Content title"), required=True) shortname = I18nTextLine(title=_("Short name"), description=_("Short name of the content can be displayed by several templates"), required=True) description = I18nText(title=_("Description"), description=_("Internal description included in HTML 'meta' headers"), required=False) keywords = I18nTextLine(title=_("Keywords"), description=_("A list of keywords matching content, separated by commas"), required=False) header = I18nImage(title=_("Header image"), description=_("This banner can be displayed by skins on page headers"), required=False) heading = I18nText(title=_("Heading"), description=_("Short header description of the content"), required=False) illustration = I18nCthumbImage(title=_("Illustration"), description=_("This illustration can be displayed by several presentation templates"), required=False) illustration_title = I18nTextLine(title=_("Illustration alternate title"), description=_("This text will be used as an alternate title for the illustration"), required=False)
ztfy.i18n
/ztfy.i18n-0.3.5.tar.gz/ztfy.i18n-0.3.5/src/ztfy/i18n/interfaces/content.py
content.py
# import standard packages # import Zope3 interfaces from zope.schema.interfaces import IDict # import local interfaces # import Zope3 packages from zope.interface import Interface, invariant, Invalid from zope.schema import TextLine, List, Choice, Set # import local packages from ztfy.i18n import _ # # I18n dict utility interface # class IDefaultValueDictReader(Interface): """Default value dict reading methods""" def __missing__(self, key): """Get default value when specified key is missing from dict""" def get(self, key, default=None): """Get given key from dict, or default if key is missing""" def keys(self): """Get dict keys""" def values(self): """Get dict values""" def items(self): """Get dict items""" def copy(self): """Return an exact copy of the given dict, including default value""" class IDefaultValueDictWriter(Interface): """Default value dict writing methods""" def __delitem__(self, key): """Delete specified key from dict""" def __setitem__(self, key, value): """Set specified key with specified value""" def clear(self): """Remove all dict values""" def update(self, b): """Update dict with values from specified dict""" def setdefault(self, key, failobj=None): """Get given key from dict or set it with specified value""" def pop(self, key, *args): """Remove given key from dict and return its value""" def popitem(self): """Pop last item from dict""" class IDefaultValueDict(IDefaultValueDictReader, IDefaultValueDictWriter): """Default value dict marker interface""" # # I18nFile container interface # class II18nFilePropertiesContainer(Interface): """Marker interface used to define contents owning i18n file properties""" class II18nFilePropertiesContainerAttributes(Interface): """Interface used to list attributes handling file properties""" attributes = Set(title=_("File attributes"), description=_("List of attributes handling I18n file objects"), required=False, value_type=TextLine()) # # Define I18n fields interfaces # class II18nField(IDict): """Marker interface used to identify I18n properties""" class II18nTextLineField(II18nField): """Marker interface used to identify I18n textline properties""" class II18nTextField(II18nField): """Marker interface used to identify I18n text properties""" class II18nHTMLField(II18nField): """Marker interface used to identify I18n HTML properties""" class II18nFileField(II18nField): """Marker interface used to identify schema fields holding I18n files""" class II18nImageField(II18nFileField): """Marker interface used to identify schema fields holding I18n images""" class II18nCthumbImageField(II18nImageField): """Marker interface used to identify schema fields holding I18n images with square thumbnails""" # # Define I18n languages management interfaces # class I18nError(Exception): """This exception is raised when errors occurs during I18n operations""" class II18nManagerInfo(Interface): """This interface is used to define available languages Available languages is a subset of languages provided by language negociator. If no negociator is registered, selection fallbacks to 'en' """ availableLanguages = List(title=_("Available languages"), description=_("List of languages available to translate contents properties"), required=True, value_type=Choice(vocabulary="ZTFY I18n languages")) defaultLanguage = Choice(title=_("Default language"), description=_("Default language used to display context ; required fields only apply to default language"), required=True, vocabulary="ZTFY I18n languages") @invariant def defaultInLanguages(self): if self.defaultLanguage not in self.availableLanguages: raise Invalid(_("Default language '%(language)s' must be included in the list of available languages") % { 'language': self.defaultLanguage }) class II18nManager(Interface): """Marker interface used to identify I18n managers""" # # I18n aware contents interfaces # class II18nAttributesAware(Interface): """Marker interface used to identify contents with I18n attributes"""
ztfy.i18n
/ztfy.i18n-0.3.5.tar.gz/ztfy.i18n-0.3.5/src/ztfy/i18n/interfaces/__init__.py
__init__.py
function I18nTabs() { this.settings = new Array(); this.tabs = new Array(); }; I18nTabs.prototype.init = function(settings) { this.settings = settings; }; I18nTabs.prototype.getParam = function(name, default_value) { var value = null; value = (typeof(this.settings[name]) == "undefined") ? default_value : this.settings[name]; // Fix bool values if (value == "true" || value == "false") return (value == "true"); return value; }; I18nTabs.prototype.displayTab = function(tab_id) { var panelElm = document.getElementById('I18nTab_' + tab_id); var panelContainerElm = panelElm ? panelElm.parentNode : null; var tabElm = document.getElementById('I18nHeader_' + tab_id); var tabContainerElm = tabElm ? tabElm.parentNode : null; var selectionClass = this.getParam('selection_class', 'current'); if (tabElm && tabContainerElm) { var nodes = tabContainerElm.childNodes; // Hide all other tabs for (var i=0; i<nodes.length; i++) { if (nodes[i].nodeName == "LI") $(nodes[i]).removeClass(selectionClass); } // Show selected tab $(tabElm).addClass(selectionClass); } if (panelElm && panelContainerElm) { var nodes = panelContainerElm.childNodes; // Hide all other panels for (var i=0; i<nodes.length; i++) { if (nodes[i].nodeName == "DIV") $(nodes[i]).removeClass(selectionClass); } // Show selected panel $(panelElm).addClass(selectionClass); } }; I18nTabs.prototype.getAnchor = function() { var pos, url = document.location.href; if ((pos = url.lastIndexOf('#')) != -1) return url.substring(pos + 1); return ""; }; I18nTabs.prototype.switchTabs = function(name) { var control = document.getElementById('I18nControl_' + name); var ul = control.getElementsByTagName('UL')[0]; var childs = ul.getElementsByTagName('LI'); var mode; var selectionClass = this.getParam('selection_class', 'current'); for (var i=1; i<childs.length; i++) { if ($(childs[i]).hasClass(selectionClass)) { var id = childs[i].id; var pos = id.indexOf('_'); this.tabs[name] = id.substr(pos+1); } if (childs[i].style.display == '') { childs[i].style.display = 'none'; mode = 'all'; } else { childs[i].style.display = ''; mode = 'single'; } } var panel = document.getElementById('I18nPanel_' + name); var lang_tabs = panel.getElementsByTagName('DIV'); for (var it=0; it<lang_tabs.length; it++) { if ($(lang_tabs[it]).hasClass('panel_flag')) { if (mode == 'all') lang_tabs[it].style.display = 'block'; else lang_tabs[it].style.display = ''; } if (lang_tabs[it].parentNode == panel) { if (mode == 'all') $(lang_tabs[it]).addClass(selectionClass); else $(lang_tabs[it]).removeClass(selectionClass); } } $(lang_tabs['I18nTab_' + this.tabs[name]]).addClass(selectionClass); }; // Global instance var i18nTabs = new I18nTabs();
ztfy.i18n
/ztfy.i18n-0.3.5.tar.gz/ztfy.i18n-0.3.5/src/ztfy/i18n/browser/resources/js/ztfy.i18n.js
ztfy.i18n.js
# import standard packages # import Zope3 interfaces from z3c.form.interfaces import IDataConverter from z3c.language.negotiator.interfaces import INegotiatorManager # import local interfaces from ztfy.i18n.browser.widget.interfaces import II18nWidget from ztfy.i18n.interfaces import II18nManager, II18nManagerInfo # import Zope3 packages from z3c.form.widget import Widget from z3c.form.browser.widget import HTMLFormElement from zope.component import queryUtility from zope.interface import implements from zope.schema.fieldproperty import FieldProperty from zope.security.proxy import removeSecurityProxy # import local packages from ztfy.i18n.browser import ztfy_i18n from ztfy.utils.traversing import getParent class I18nWidgetProperty(object): """Base class for I18n widgets properties""" def __init__(self, name): self.__name = name def __get__(self, instance, klass): return instance.__dict__.get(self.__name, None) def __set__(self, instance, value): instance.__dict__[self.__name] = value for widget in instance.widgets.values(): setattr(widget, self.__name, value) class I18nWidget(HTMLFormElement, Widget): """Base class for all I18n widgets""" implements(II18nWidget) langs = FieldProperty(II18nWidget['langs']) original_widget = None # IHTMLCoreAttributes properties klass = "i18n-widget" style = I18nWidgetProperty('style') # IHTMLEventsAttributes properties onclick = I18nWidgetProperty('onclick') ondblclick = I18nWidgetProperty('ondblclick') onmousedown = I18nWidgetProperty('onmousedown') onmouseup = I18nWidgetProperty('onmouseup') onmouseover = I18nWidgetProperty('onmouseover') onmousemove = I18nWidgetProperty('onmousemove') onmouseout = I18nWidgetProperty('onmouseout') onkeypress = I18nWidgetProperty('onkeypress') onkeydown = I18nWidgetProperty('onkeydown') onkeyup = I18nWidgetProperty('onkeyup') # IHTMLFormElement properties disabled = I18nWidgetProperty('disabled') tabindex = I18nWidgetProperty('tabindex') onfocus = I18nWidgetProperty('onfocus') onblur = I18nWidgetProperty('onblur') onchange = I18nWidgetProperty('onchange') def update(self): super(I18nWidget, self).update() manager = getParent(self.context, II18nManager) if manager is not None: self.langs = II18nManagerInfo(manager).availableLanguages else: manager = queryUtility(INegotiatorManager) if manager is not None: self.langs = manager.offeredLanguages else: self.langs = [u'en', ] self.widgets = {} for lang in self.langs: widget = self.widgets[lang] = self.original_widget(self.request) self.initWidget(widget, lang) for lang in self.langs: widget = self.widgets[lang] self.updateWidget(widget, lang) widget.update() def initWidget(self, widget, language): widget.id = str('%s.%s' % (self.name, language)) widget.form = self.form widget.mode = self.mode widget.ignoreContext = self.ignoreContext widget.ignoreRequest = self.ignoreRequest widget.field = self.field.value_type widget.name = str('%s:list' % self.name) widget.label = self.label widget.lang = language def updateWidget(self, widget, language): widget.value = self.getValue(language) def getWidget(self, language): widget = self.widgets[language] return widget.render() def getValue(self, language): self.value = removeSecurityProxy(self.value) if not isinstance(self.value, dict): converter = IDataConverter(self) try: self.value = converter.toFieldValue(self.value) except: self.value = {} return self.value.get(language) def hasValue(self, language): return bool(self.getValue(language)) def render(self): ztfy_i18n.need() return super(I18nWidget, self).render()
ztfy.i18n
/ztfy.i18n-0.3.5.tar.gz/ztfy.i18n-0.3.5/src/ztfy/i18n/browser/widget/widget.py
widget.py
# import standard packages # import Zope3 interfaces from z3c.form.interfaces import IFieldWidget, NOT_CHANGED # import local interfaces from ztfy.file.interfaces import IThumbnailGeometry, IImageDisplay, ICthumbImageFieldData from ztfy.i18n.browser.widget.interfaces import II18nImageWidget, II18nCthumbImageWidget from ztfy.i18n.interfaces import II18nImageField, II18nCthumbImageField from ztfy.skin.layer import IZTFYBrowserLayer # import Zope3 packages from z3c.form.widget import FieldWidget from zope.component import adapter from zope.interface import implementer, implementsOnly # import local packages from ztfy.i18n.browser.widget.file import I18nFileWidget from ztfy.file.browser import ztfy_file from ztfy.file.browser.widget import ImageWidget, CthumbImageWidget class I18nImageWidget(I18nFileWidget): """I18n image input type implementation""" implementsOnly(II18nImageWidget) original_widget = ImageWidget class I18nCthumbImageWidget(I18nImageWidget): """I18n image input with square thumbnails implementation""" implementsOnly(II18nCthumbImageWidget) original_widget = CthumbImageWidget def update(self): super(I18nCthumbImageWidget, self).update() self.widget_value = self.field.get(self.context) def render(self): ztfy_file.need() return super(I18nCthumbImageWidget, self).render() def getAdapter(self, lang): return IImageDisplay(self.widget_value.get(lang), None) def getGeometry(self, lang): return IThumbnailGeometry(self.widget_value.get(lang), None) def getPosition(self, lang): name, _ignore = self.name.split(':') return (int(self.request.form.get(name + '_' + lang + '__x', 0)), int(self.request.form.get(name + '_' + lang + '__y', 0))) def getSize(self, lang): name, _ignore = self.name.split(':') return (int(self.request.form.get(name + '_' + lang + '__w', 0)), int(self.request.form.get(name + '_' + lang + '__h', 0))) def hasValue(self, language): value = self.getValue(language) if ICthumbImageFieldData.providedBy(value): value = value.value if value is NOT_CHANGED: return bool(self.current_value.get(language)) else: return bool(value) @adapter(II18nImageField, IZTFYBrowserLayer) @implementer(IFieldWidget) def I18nImageFieldWidget(field, request): """IFieldWidget factory for I18nImageWidget""" return FieldWidget(field, I18nImageWidget(request)) @adapter(II18nCthumbImageField, IZTFYBrowserLayer) @implementer(IFieldWidget) def I18nCthumbImageFieldWidget(field, request): """IFieldWidget factory for I18nCthumbImageWidget""" return FieldWidget(field, I18nCthumbImageWidget(request))
ztfy.i18n
/ztfy.i18n-0.3.5.tar.gz/ztfy.i18n-0.3.5/src/ztfy/i18n/browser/widget/image.py
image.py
# import standard packages # import Zope3 interfaces from z3c.language.negotiator.interfaces import INegotiatorManager from z3c.language.switch.interfaces import II18n from zope.tales.interfaces import ITALESFunctionNamespace # import local interfaces from ztfy.i18n.interfaces import II18nManager, II18nManagerInfo, \ II18nAttributesAware from ztfy.i18n.tal.interfaces import II18nTalesAPI # import Zope3 packages from zope.component import queryUtility from zope.i18n import translate from zope.interface import implements # import local packages from ztfy.utils import getParent class I18nTalesAdapter(object): implements(II18nTalesAPI, ITALESFunctionNamespace) def __init__(self, context): self.context = context self._i18n = II18n(getParent(self.context, II18nAttributesAware), None) def setEngine(self, engine): self.request = engine.vars['request'] def __getattr__(self, attribute): if self._i18n is not None: value = self._i18n.queryAttribute(attribute, language=self.request.get('language'), request=self.request) else: value = getattr(self.context, attribute, '') if value is None: value = '' return value def translate(self): return translate(self.context, context=self.request) def langs(self): if self._i18n is not None: default_language = self._i18n.getDefaultLanguage() languages = self._i18n.getAvailableLanguages() return sorted(languages, key=lambda x: x == default_language and '__' or x) i18n = getParent(self.context, II18nManager) if i18n is not None: info = II18nManagerInfo(i18n) default_language = info.defaultLanguage return sorted(info.availableLanguages, key=lambda x: x == default_language and '__' or x) negotiator = queryUtility(INegotiatorManager) if negotiator is not None: default_language = negotiator.serverLanguage return sorted(negotiator.offeredLanguages, key=lambda x: x == default_language and '__' or x) return (u'en',) def user_lang(self): if self._i18n is not None: return self._i18n.getPreferedLanguage() return u'en' def default_lang(self): if self._i18n is not None: return self._i18n.getDefaultLanguage() return u'en'
ztfy.i18n
/ztfy.i18n-0.3.5.tar.gz/ztfy.i18n-0.3.5/src/ztfy/i18n/tal/api.py
api.py
# import standard packages # import Zope3 interfaces # import local interfaces # import Zope3 packages from zope.interface import Interface, Attribute # import local packages from ztfy.imgtags import _ # # Pyexiv2 tags interfaces # class IBaseTagInfo(Interface): """Base pyexiv2 tag interface""" key = Attribute(_("Tag key code")) name = Attribute(_("Tag name")) description = Attribute(_("Tag description")) type = Attribute(_("Tag type")) class IBaseTagWriter(Interface): """Base pyexiv2 tag writer interface""" value = Attribute(_("Tag value")) raw_value = Attribute(_("Tag raw value")) class IExifTagInfo(IBaseTagInfo): """Base pyexiv2 EXIF tag interface""" label = Attribute(_("Tag label")) section_name = Attribute(_("Section name")) section_description = Attribute(_("Section description")) human_value = Attribute(_("Tag human value")) def contents_changed(self): """Check if tag contents changed""" class IExifTagWriter(IBaseTagWriter): """Base pyexiv2 EXIF tag writer interface""" class IExifTag(IExifTagInfo, IExifTagWriter): """Pyexiv2 EXIF tag interface""" class IIptcTagInfo(IBaseTagInfo): """Base pyexiv2 IPTC tag interface""" title = Attribute(_("Tag title")) photoshop_name = Attribute(_("Photoshop name")) record_name = Attribute(_("Tag record name")) record_description = Attribute(_("Tag record description")) repeatable = Attribute(_("Repeatable tag ?")) def contents_changed(self): """Check if tag contents changed""" class IIptcTagWriter(IBaseTagWriter): """Base pyexiv2 IPTC tag writer interface""" values = Attribute(_("Tag values")) raw_values = Attribute(_("Tag raw values")) class IIptcTag(IIptcTagInfo, IIptcTagWriter): """Pyexiv2 IPTC tag interface""" class IXmpTagInfo(IBaseTagInfo): """Base pyexiv2 XMP tag interface""" title = Attribute(_("Tag title")) class IXmpTagWriter(IBaseTagWriter): """Base pyexiv2 XMP tag writer interface""" class IXmpTag(IXmpTagInfo, IXmpTagWriter): """Pyexiv2 XMP tag interface""" # # Images tags interfaces # class IImageTags(Interface): """Image tags interface""" metadata = Attribute(_("Raw metadata")) def getExifKeys(self): """Get keys of used EXIF tags""" def getExifTags(self): """Get key/tag dict of used EXIF tags""" def getIptcKeys(self): """Get keys of used IPTC tags""" def getIptcTags(self): """Get key/tag dict of used IPTC tags""" def getXmpKeys(self): """Get keys of used XMP tags""" def getXmpTags(self): """Get key/tag dict of used XMP tags""" def getKeys(self): """Get keys of all used tags""" def getTags(self): """Get key/tag dict of all used tags""" def getTag(self, key): """Get tag for given key Key can also be a list or tuple, in which case given tags are checked until one of them is not null """ def setTag(self, key, value, raw=False): """Set value of given tag""" def getGPSLocation(self, precision=None): """Get GPS coordinates in WGS84 projection system""" def flush(self): """Write modified tags to image""" class IImageTagString(Interface): """Image tag string representation interface""" def toString(self, encoding='utf-8'): """Render tag as string Returns a tuple containing tag name and tag value """ # # Image tag index interface # class IImageTagIndexValue(Interface): """Get index value for a given tag""" def __getattr__(self, attr): """Get indexed value for given tag"""
ztfy.imgtags
/ztfy.imgtags-0.1.3.tar.gz/ztfy.imgtags-0.1.3/src/ztfy/imgtags/interfaces.py
interfaces.py
# import standard packages import chardet from datetime import datetime from pyexiv2 import ImageMetadata from pyexiv2.exif import ExifTag from pyexiv2.utils import Fraction, NotifyingList # import Zope3 interfaces from zope.app.file.interfaces import IImage # import local interfaces from ztfy.imgtags.interfaces import IImageTags, IImageTagString, IImageTagIndexValue, \ IBaseTagInfo, IExifTag, IIptcTag, IXmpTag # import Zope3 packages from zope.component import adapts from zope.interface import implements from ztfy.utils.timezone import tztime # import local packages class ImageTagsAdapter(object): """Image tags adapter""" adapts(IImage) implements(IImageTags) def __init__(self, context): self.context = context self.metadata = ImageMetadata.from_buffer(context.data) self.metadata.read() def getExifKeys(self): return self.metadata.exif_keys def getExifTags(self): data = self.metadata return dict(((tag, data[tag]) for tag in data.exif_keys)) def getIptcKeys(self): return self.metadata.iptc_keys def getIptcTags(self): data = self.metadata return dict(((tag, data[tag]) for tag in data.iptc_keys)) def getXmpKeys(self): return self.metadata.xmp_keys def getXmpTags(self): data = self.metadata return dict(((tag, data[tag]) for tag in data.xmp_keys)) def getKeys(self): data = self.metadata return data.exif_keys + data.iptc_keys + data.xmp_keys def getTags(self): data = self.metadata return dict(((tag, data[tag]) for tag in self.getKeys())) def getTag(self, key): if isinstance(key, (str, unicode)): key = (key,) for k in key: tag = self.metadata.get(k) if tag is not None: return tag def setTag(self, key, value, raw=False): if raw: self.metadata[key].raw_value = value else: self.metadata[key].value = value def getGPSLocation(self, precision=None): def gpsToWgs(value): if isinstance(value, ExifTag): value = value.value assert isinstance(value, NotifyingList) assert isinstance(value[0], Fraction) and isinstance(value[1], Fraction) and isinstance(value[2], Fraction) d0 = value[0].numerator d1 = value[0].denominator d = float(d0) / float(d1) m0 = value[1].numerator m1 = value[1].denominator m = float(m0) / float(m1) s0 = value[2].numerator s1 = value[2].denominator s = float(s0) / float(s1) return d + (m / 60.0) + (s / 3600.0) lon = None lat = None keys = self.getExifKeys() if ('Exif.GPSInfo.GPSLongitude' in keys) and \ ('Exif.GPSInfo.GPSLatitude' in keys): lon = gpsToWgs(self.getTag('Exif.GPSInfo.GPSLongitude')) lon_ref = self.getTag('Exif.GPSInfo.GPSLongitudeRef') if lon_ref and (lon_ref.value != 'E'): lon = -lon lat = gpsToWgs(self.getTag('Exif.GPSInfo.GPSLatitude')) lat_ref = self.getTag('Exif.GPSInfo.GPSLatitudeRef') if lat_ref and (lat_ref.value != 'N'): lat = -lat if precision: if lon: lon = round(lon, precision) if lat: lat = round(lat, precision) return lon, lat def flush(self): self.metadata.write() self.context.data = self.metadata.buffer # # Tags string adapters # class DefaultTagStringAdapter(object): """Default image tag string adapter""" adapts(IBaseTagInfo) implements(IImageTagString) def __init__(self, context): self.context = context def toString(self, encoding='utf-8'): try: return (self.context.name or self.context.key, unicode(str(self.context.value), encoding)) except: encoding = chardet.detect(self.context.value).get('encoding') return (self.context.name or self.context.key, unicode(str(self.context.value), encoding)) class ExifTagStringAdapter(object): """EXIF tag string adapter""" adapts(IExifTag) implements(IImageTagString) def __init__(self, context): self.context = context def toString(self, encoding='utf-8'): try: return (self.context.label or self.context.name or self.context.key, unicode(str(self.context.human_value), encoding)) except: encoding = chardet.detect(self.context.human_value).get('encoding') return (self.context.label or self.context.name or self.context.key, unicode(str(self.context.human_value), encoding)) class IptcTagStringAdapter(object): """IPTC tag string adapter""" adapts(IIptcTag) implements(IImageTagString) def __init__(self, context): self.context = context def toString(self, encoding='utf-8'): try: return (self.context.title or self.context.name or self.context.key, ', '.join((unicode(str(value), encoding) for value in self.context.values))) except: encoding = chardet.detect(self.context.values[0]).get('encoding') return (self.context.title or self.context.name or self.context.key, ', '.join((unicode(str(value), encoding) for value in self.context.values))) class XmpTagStringAdapter(object): """XMP tag string adapter""" adapts(IXmpTag) implements(IImageTagString) def __init__(self, context): self.context = context def toString(self, encoding='utf-8'): try: value = str(self.context.value) except: value = str(self.context.raw_value) try: return (self.context.title or self.context.name or self.context.key, unicode(value, encoding)) except: encoding = chardet.detect(value).get('encoding') return (self.context.title or self.context.name or self.context.key, unicode(value, encoding)) # # Image tag index value # class ImageTagIndexValueAdapter(object): """Image tag index value adapter""" adapts(IImage) implements(IImageTagIndexValue) def __init__(self, context): self.context = context self.tags = IImageTags(context) def __getattr__(self, attr): tag = self.tags.getTag(attr) if tag is not None: value = tag.value if isinstance(value, datetime) and not value.tzinfo: value = tztime(value) return value
ztfy.imgtags
/ztfy.imgtags-0.1.3.tar.gz/ztfy.imgtags-0.1.3/src/ztfy/imgtags/adapter.py
adapter.py
===================== ztfy.jqueryui package ===================== You may find documentation in: - Global README.txt: ztfy/jqueryui/docs/README.txt - General: ztfy/jqueryui/docs - Technical: ztfy/jqueryui/doctests More informations can be found on ZTFY.org_ web site ; a decicated Trac environment is available on ZTFY.jqueryui_. This package is created and maintained by Thierry Florac_. .. _Thierry Florac: mailto:[email protected] .. _ZTFY.org: http://www.ztfy.org .. _ZTFY.jqueryui: http://trac.ztfy.org/ztfy.jqueryui
ztfy.jqueryui
/ztfy.jqueryui-0.7.12.tar.gz/ztfy.jqueryui-0.7.12/README.txt
README.txt
import os import shutil import sys import tempfile from optparse import OptionParser tmpeggs = tempfile.mkdtemp() usage = '''\ [DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options] Bootstraps a buildout-based project. Simply run this script in a directory containing a buildout.cfg, using the Python that you want bin/buildout to use. Note that by using --find-links to point to local resources, you can keep this script from going over the network. ''' parser = OptionParser(usage=usage) parser.add_option("-v", "--version", help="use a specific zc.buildout version") parser.add_option("-t", "--accept-buildout-test-releases", dest='accept_buildout_test_releases', action="store_true", default=False, help=("Normally, if you do not specify a --version, the " "bootstrap script and buildout gets the newest " "*final* versions of zc.buildout and its recipes and " "extensions for you. If you use this flag, " "bootstrap and buildout will get the newest releases " "even if they are alphas or betas.")) parser.add_option("-c", "--config-file", help=("Specify the path to the buildout configuration " "file to be used.")) parser.add_option("-f", "--find-links", help=("Specify a URL to search for buildout releases")) parser.add_option("--allow-site-packages", action="store_true", default=False, help=("Let bootstrap.py use existing site packages")) options, args = parser.parse_args() ###################################################################### # load/install setuptools try: if options.allow_site_packages: import setuptools import pkg_resources from urllib.request import urlopen except ImportError: from urllib2 import urlopen ez = {} exec(urlopen('https://bootstrap.pypa.io/ez_setup.py').read(), ez) if not options.allow_site_packages: # ez_setup imports site, which adds site packages # this will remove them from the path to ensure that incompatible versions # of setuptools are not in the path import site # inside a virtualenv, there is no 'getsitepackages'. # We can't remove these reliably if hasattr(site, 'getsitepackages'): for sitepackage_path in site.getsitepackages(): sys.path[:] = [x for x in sys.path if sitepackage_path not in x] setup_args = dict(to_dir=tmpeggs, download_delay=0) ez['use_setuptools'](**setup_args) import setuptools import pkg_resources # This does not (always?) update the default working set. We will # do it. for path in sys.path: if path not in pkg_resources.working_set.entries: pkg_resources.working_set.add_entry(path) ###################################################################### # Install buildout ws = pkg_resources.working_set cmd = [sys.executable, '-c', 'from setuptools.command.easy_install import main; main()', '-mZqNxd', tmpeggs] find_links = os.environ.get( 'bootstrap-testing-find-links', options.find_links or ('http://downloads.buildout.org/' if options.accept_buildout_test_releases else None) ) if find_links: cmd.extend(['-f', find_links]) setuptools_path = ws.find( pkg_resources.Requirement.parse('setuptools')).location requirement = 'zc.buildout' version = options.version if version is None and not options.accept_buildout_test_releases: # Figure out the most recent final version of zc.buildout. import setuptools.package_index _final_parts = '*final-', '*final' def _final_version(parsed_version): for part in parsed_version: if (part[:1] == '*') and (part not in _final_parts): return False return True index = setuptools.package_index.PackageIndex( search_path=[setuptools_path]) if find_links: index.add_find_links((find_links,)) req = pkg_resources.Requirement.parse(requirement) if index.obtain(req) is not None: best = [] bestv = None for dist in index[req.project_name]: distv = dist.parsed_version if _final_version(distv): if bestv is None or distv > bestv: best = [dist] bestv = distv elif distv == bestv: best.append(dist) if best: best.sort() version = best[-1].version if version: requirement = '=='.join((requirement, version)) cmd.append(requirement) import subprocess if subprocess.call(cmd, env=dict(os.environ, PYTHONPATH=setuptools_path)) != 0: raise Exception( "Failed to execute command:\n%s" % repr(cmd)[1:-1]) ###################################################################### # Import and run buildout ws.add_entry(tmpeggs) ws.require(requirement) import zc.buildout.buildout if not [a for a in args if '=' not in a]: args.append('bootstrap') # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args[0:0] = ['-c', options.config_file] zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs)
ztfy.jqueryui
/ztfy.jqueryui-0.7.12.tar.gz/ztfy.jqueryui-0.7.12/bootstrap.py
bootstrap.py
__docformat__ = "restructuredtext" # import standard packages from fanstatic import Library, Resource, Group # import Zope3 interfaces # import local interfaces # import Zope3 packages # import local packages library = Library('ztfy.jqueryui', 'resources') # Main JQuery library jquery_13 = Resource(library, 'js/jquery-1.3.js', minified='js/jquery-1.3.min.js', bottom=True) jquery_14 = Resource(library, 'js/jquery-1.4.4.js', minified='js/jquery-1.4.4.min.js', bottom=True) jquery_17 = Resource(library, 'js/jquery-1.7.2.js', minified='js/jquery-1.7.2.min.js', bottom=True) jquery_19 = Resource(library, 'js/jquery-1.9.1.js', minified='js/jquery-1.9.1.min.js', bottom=True) jquery = jquery_17 jquery_migrate = Resource(library, 'js/jquery-migrate-1.1.1.js', minified='js/jquery-migrate-1.1.1.min.js', depends=[jquery_19], bottom=True) # JQuery UI jquery_ui_css_main = Resource(library, 'css/jquery-ui-1.7.3.css', minified='css/jquery-ui-1.7.3.min.css') jquery_ui_css = Resource(library, 'css/jquery-ui.theme.css', minified='css/jquery-ui.theme.min.css', depends=[jquery_ui_css_main]) jquery_ui_core_17 = Resource(library, 'js/jquery-ui-core-1.7.3.min.js', depends=[jquery, jquery_ui_css], bottom=True) jquery_ui_base_17 = Resource(library, 'js/jquery-ui-base-1.7.3.min.js', depends=[jquery_ui_core_17, jquery_ui_css], bottom=True) jquery_ui_widgets_17 = Resource(library, 'js/jquery-ui-widgets-1.7.3.min.js', depends=[jquery_ui_base_17, jquery_ui_css], bottom=True) jquery_ui_effects_17 = Resource(library, 'js/jquery-ui-effects-1.7.3.min.js', depends=[jquery_ui_base_17, jquery_ui_css], bottom=True) jquery_ui_all_17 = Group(depends=[jquery_ui_widgets_17, jquery_ui_effects_17]) jquery_ui_core = Resource(library, 'js/jquery-ui-core-1.8.16.min.js', depends=[jquery, jquery_ui_css], bottom=True) jquery_ui_base = Resource(library, 'js/jquery-ui-base-1.8.16.min.js', depends=[jquery_ui_core, jquery_ui_css], bottom=True) jquery_ui_widgets = Resource(library, 'js/jquery-ui-widgets-1.8.16.min.js', depends=[jquery_ui_base, jquery_ui_css], bottom=True) jquery_ui_effects = Resource(library, 'js/jquery-ui-effects-1.8.16.min.js', depends=[jquery_ui_base, jquery_ui_css], bottom=True) jquery_ui_all = Group(depends=[jquery_ui_widgets, jquery_ui_effects]) # JQuery Tools jquery_tools_11 = Resource(library, 'js/jquery-tools-1.1.2.min.js', depends=[jquery], bottom=True) jquery_tools_12 = Resource(library, 'js/jquery-tools-1.2.7.js', minified='js/jquery-tools-1.2.7.min.js', depends=[jquery], bottom=True) jquery_tools = jquery_tools_12 # JQuery I18n jquery_i18n = Resource(library, 'js/jquery-i18n.js', minified='js/jquery-i18n.min.js', depends=[jquery], bottom=True) # JQuery Form jquery_form = Resource(library, 'js/jquery-form-3.27.js', minified='js/jquery-form.min.js', depends=[jquery], bottom=True) # JQuery Tipsy jquery_tipsy_css = Resource(library, 'css/jquery-tipsy.css') jquery_tipsy = Resource(library, 'js/jquery-tipsy.js', depends=[jquery, jquery_tipsy_css], bottom=True) # JQuery Cookie jquery_cookie = Resource(library, 'js/jquery-cookie.js', minified='js/jquery-cookie.min.js', depends=[jquery], bottom=True) # JQuery mousewheel jquery_mousewheel = Resource(library, 'js/jquery-mousewheel.js', minified='js/jquery-mousewheel.min.js', depends=[jquery], bottom=True) # JQuery layout jquery_layout_css = Resource(library, 'css/jquery-layout.css', minified='css/jquery-layout.min.css') jquery_layout = Resource(library, 'js/jquery-layout.js', minified='js/jquery-layout.min.js', depends=[jquery_ui_effects, jquery_layout_css], bottom=True) # JQuery JSON-RPC jquery_json2 = Resource(library, 'js/json2.js', minified='js/json2.min.js', bottom=True) jquery_jsonrpc = Resource(library, 'js/jquery-jsonrpc.js', minified='js/jquery-jsonrpc.min.js', depends=[jquery, jquery_json2], bottom=True) # JQuery Alerts jquery_alerts_css = Resource(library, 'css/jquery-alerts.css', minified='css/jquery-alerts.min.css') jquery_alerts = Resource(library, 'js/jquery-alerts.js', minified='js/jquery-alerts.min.js', depends=[jquery, jquery_i18n, jquery_alerts_css], bottom=True) # JQuery FancyBox jquery_fancybox_css = Resource(library, 'css/jquery-fancybox-1.3.4.css', minified='css/jquery-fancybox.min.css') jquery_fancybox = Resource(library, 'js/jquery-fancybox-1.3.4.js', minified='js/jquery-fancybox.min.js', depends=[jquery, jquery_fancybox_css], bottom=True) # JQuery TreeTable jquery_treetable_css = Resource(library, 'css/jquery-treeTable.css', minified='css/jquery-treeTable.min.css') jquery_treetable = Resource(library, 'js/jquery-treeTable.js', minified='js/jquery-treeTable.min.js', depends=[jquery, jquery_treetable_css], bottom=True) # JQuery DataTables jquery_datatables_css = Resource(library, 'css/jquery-datatables.css', minified='css/jquery-datatables.min.css') jquery_datatables = Resource(library, 'js/jquery-datatables.js', minified='js/jquery-datatables.min.js', depends=[jquery, jquery_datatables_css], bottom=True) # JQuery handsontable jquery_handsontable_css = Resource(library, 'css/jquery-handsontable-full.css', minified='css/jquery-handsontable-full.min.css') jquery_handsontable = Resource(library, 'js/jquery-handsontable-full.js', minified='js/jquery-handsontable-full.min.js', depends=[jquery, jquery_handsontable_css], bottom=True) # JQuery DateTime jquery_datetime_css = Resource(library, 'css/jquery-datetime.css', minified='css/jquery-datetime.min.css') jquery_datetime = Resource(library, 'js/jquery-datetime.js', minified='js/jquery-datetime.min.js', depends=[jquery, jquery_datetime_css], bottom=True) # JQuery Color jquery_color = Resource(library, 'js/jquery-color.js', minified='js/jquery-color.min.js', depends=[jquery], bottom=True) # JQuery ColorPicker jquery_colorpicker_css = Resource(library, 'css/jquery-colorpicker.css', minified='css/jquery-colorpicker.min.css') jquery_colorpicker = Resource(library, 'js/jquery-colorpicker.js', minified='js/jquery-colorpicker.min.js', depends=[jquery, jquery_colorpicker_css], bottom=True) # JQuery imgAreaSelect jquery_imgareaselect_css = Resource(library, 'css/jquery-imgareaselect.css', minified='css/jquery-imgareaselect.min.css') jquery_imgareaselect = Resource(library, 'js/jquery-imgareaselect.js', minified='js/jquery-imgareaselect.min.js', depends=[jquery, jquery_imgareaselect_css], bottom=True) # JQuery Masonry jquery_masonry = Resource(library, 'js/jquery-masonry.js', minified='js/jquery-masonry.min.js', bottom=True) # JQuery jScrollPane jquery_jscrollpane_css = Resource(library, 'css/jquery-jscrollpane.css', minified='css/jquery-jscrollpane.min.css') jquery_jscrollpane = Resource(library, 'js/jquery-jscrollpane.js', minified='js/jquery-jscrollpane.min.js', depends=[jquery, jquery_mousewheel, jquery_jscrollpane_css], bottom=True) # JQuery MultiSelect jquery_multiselect_css = Resource(library, 'css/jquery-multiselect.css', minified='css/jquery-multiselect.min.css') jquery_multiselect = Resource(library, 'js/jquery-multiselect.js', minified='js/jquery-multiselect.min.js', depends=[jquery, jquery_multiselect_css], bottom=True) # JQuery dotdotdot jquery_dotdotdot = Resource(library, 'js/jquery-dotdotdot.js', depends=[jquery], bottom=True) # JQuery LiquidCarousel jquery_liquidcarousel_css = Resource(library, 'css/jquery-liquidcarousel.css') jquery_liquidcarousel = Resource(library, 'js/jquery-liquidcarousel.js', depends=[jquery], bottom=True) # JQuery UploadProgress jquery_progressbar = Resource(library, 'js/jquery-progressbar.js', minified='js/jquery-progressbar.min.js', depends=[jquery], bottom=True) # JQuery TinyMCE jquery_tinymce = Resource(library, 'js/tiny_mce/tiny_mce.js', depends=[jquery], bottom=True)
ztfy.jqueryui
/ztfy.jqueryui-0.7.12.tar.gz/ztfy.jqueryui-0.7.12/src/ztfy/jqueryui/__init__.py
__init__.py
(function(a){a.widget("ui.draggable",a.extend({},a.ui.mouse,{_init:function(){if(this.options.helper=="original"&&!(/^(?:r|a|f)/).test(this.element.css("position"))){this.element[0].style.position="relative"}(this.options.addClasses&&this.element.addClass("ui-draggable"));(this.options.disabled&&this.element.addClass("ui-draggable-disabled"));this._mouseInit()},destroy:function(){if(!this.element.data("draggable")){return}this.element.removeData("draggable").unbind(".draggable").removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled");this._mouseDestroy()},_mouseCapture:function(b){var c=this.options;if(this.helper||c.disabled||a(b.target).is(".ui-resizable-handle")){return false}this.handle=this._getHandle(b);if(!this.handle){return false}return true},_mouseStart:function(b){var c=this.options;this.helper=this._createHelper(b);this._cacheHelperProportions();if(a.ui.ddmanager){a.ui.ddmanager.current=this}this._cacheMargins();this.cssPosition=this.helper.css("position");this.scrollParent=this.helper.scrollParent();this.offset=this.element.offset();this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left};a.extend(this.offset,{click:{left:b.pageX-this.offset.left,top:b.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.originalPosition=this._generatePosition(b);this.originalPageX=b.pageX;this.originalPageY=b.pageY;if(c.cursorAt){this._adjustOffsetFromHelper(c.cursorAt)}if(c.containment){this._setContainment()}this._trigger("start",b);this._cacheHelperProportions();if(a.ui.ddmanager&&!c.dropBehaviour){a.ui.ddmanager.prepareOffsets(this,b)}this.helper.addClass("ui-draggable-dragging");this._mouseDrag(b,true);return true},_mouseDrag:function(b,d){this.position=this._generatePosition(b);this.positionAbs=this._convertPositionTo("absolute");if(!d){var c=this._uiHash();this._trigger("drag",b,c);this.position=c.position}if(!this.options.axis||this.options.axis!="y"){this.helper[0].style.left=this.position.left+"px"}if(!this.options.axis||this.options.axis!="x"){this.helper[0].style.top=this.position.top+"px"}if(a.ui.ddmanager){a.ui.ddmanager.drag(this,b)}return false},_mouseStop:function(c){var d=false;if(a.ui.ddmanager&&!this.options.dropBehaviour){d=a.ui.ddmanager.drop(this,c)}if(this.dropped){d=this.dropped;this.dropped=false}if((this.options.revert=="invalid"&&!d)||(this.options.revert=="valid"&&d)||this.options.revert===true||(a.isFunction(this.options.revert)&&this.options.revert.call(this.element,d))){var b=this;a(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){b._trigger("stop",c);b._clear()})}else{this._trigger("stop",c);this._clear()}return false},_getHandle:function(b){var c=!this.options.handle||!a(this.options.handle,this.element).length?true:false;a(this.options.handle,this.element).find("*").andSelf().each(function(){if(this==b.target){c=true}});return c},_createHelper:function(c){var d=this.options;var b=a.isFunction(d.helper)?a(d.helper.apply(this.element[0],[c])):(d.helper=="clone"?this.element.clone():this.element);if(!b.parents("body").length){b.appendTo((d.appendTo=="parent"?this.element[0].parentNode:d.appendTo))}if(b[0]!=this.element[0]&&!(/(fixed|absolute)/).test(b.css("position"))){b.css("position","absolute")}return b},_adjustOffsetFromHelper:function(b){if(b.left!=undefined){this.offset.click.left=b.left+this.margins.left}if(b.right!=undefined){this.offset.click.left=this.helperProportions.width-b.right+this.margins.left}if(b.top!=undefined){this.offset.click.top=b.top+this.margins.top}if(b.bottom!=undefined){this.offset.click.top=this.helperProportions.height-b.bottom+this.margins.top}},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var b=this.offsetParent.offset();if(this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0])){b.left+=this.scrollParent.scrollLeft();b.top+=this.scrollParent.scrollTop()}if((this.offsetParent[0]==document.body)||(this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&a.browser.msie)){b={top:0,left:0}}return{top:b.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:b.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var b=this.element.position();return{top:b.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:b.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}else{return{top:0,left:0}}},_cacheMargins:function(){this.margins={left:(parseInt(this.element.css("marginLeft"),10)||0),top:(parseInt(this.element.css("marginTop"),10)||0)}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var e=this.options;if(e.containment=="parent"){e.containment=this.helper[0].parentNode}if(e.containment=="document"||e.containment=="window"){this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,a(e.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(a(e.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]}if(!(/^(document|window|parent)$/).test(e.containment)&&e.containment.constructor!=Array){var c=a(e.containment)[0];if(!c){return}var d=a(e.containment).offset();var b=(a(c).css("overflow")!="hidden");this.containment=[d.left+(parseInt(a(c).css("borderLeftWidth"),10)||0)+(parseInt(a(c).css("paddingLeft"),10)||0)-this.margins.left,d.top+(parseInt(a(c).css("borderTopWidth"),10)||0)+(parseInt(a(c).css("paddingTop"),10)||0)-this.margins.top,d.left+(b?Math.max(c.scrollWidth,c.offsetWidth):c.offsetWidth)-(parseInt(a(c).css("borderLeftWidth"),10)||0)-(parseInt(a(c).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,d.top+(b?Math.max(c.scrollHeight,c.offsetHeight):c.offsetHeight)-(parseInt(a(c).css("borderTopWidth"),10)||0)-(parseInt(a(c).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top]}else{if(e.containment.constructor==Array){this.containment=e.containment}}},_convertPositionTo:function(f,h){if(!h){h=this.position}var c=f=="absolute"?1:-1;var e=this.options,b=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,g=(/(html|body)/i).test(b[0].tagName);return{top:(h.top+this.offset.relative.top*c+this.offset.parent.top*c-(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():(g?0:b.scrollTop()))*c)),left:(h.left+this.offset.relative.left*c+this.offset.parent.left*c-(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():g?0:b.scrollLeft())*c))}},_generatePosition:function(e){var h=this.options,b=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,i=(/(html|body)/i).test(b[0].tagName);if(this.cssPosition=="relative"&&!(this.scrollParent[0]!=document&&this.scrollParent[0]!=this.offsetParent[0])){this.offset.relative=this._getRelativeOffset()}var d=e.pageX;var c=e.pageY;if(this.originalPosition){if(this.containment){if(e.pageX-this.offset.click.left<this.containment[0]){d=this.containment[0]+this.offset.click.left}if(e.pageY-this.offset.click.top<this.containment[1]){c=this.containment[1]+this.offset.click.top}if(e.pageX-this.offset.click.left>this.containment[2]){d=this.containment[2]+this.offset.click.left}if(e.pageY-this.offset.click.top>this.containment[3]){c=this.containment[3]+this.offset.click.top}}if(h.grid){var g=this.originalPageY+Math.round((c-this.originalPageY)/h.grid[1])*h.grid[1];c=this.containment?(!(g-this.offset.click.top<this.containment[1]||g-this.offset.click.top>this.containment[3])?g:(!(g-this.offset.click.top<this.containment[1])?g-h.grid[1]:g+h.grid[1])):g;var f=this.originalPageX+Math.round((d-this.originalPageX)/h.grid[0])*h.grid[0];d=this.containment?(!(f-this.offset.click.left<this.containment[0]||f-this.offset.click.left>this.containment[2])?f:(!(f-this.offset.click.left<this.containment[0])?f-h.grid[0]:f+h.grid[0])):f}}return{top:(c-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():(i?0:b.scrollTop())))),left:(d-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():i?0:b.scrollLeft())))}},_clear:function(){this.helper.removeClass("ui-draggable-dragging");if(this.helper[0]!=this.element[0]&&!this.cancelHelperRemoval){this.helper.remove()}this.helper=null;this.cancelHelperRemoval=false},_trigger:function(b,c,d){d=d||this._uiHash();a.ui.plugin.call(this,b,[c,d]);if(b=="drag"){this.positionAbs=this._convertPositionTo("absolute")}return a.widget.prototype._trigger.call(this,b,c,d)},plugins:{},_uiHash:function(b){return{helper:this.helper,position:this.position,absolutePosition:this.positionAbs,offset:this.positionAbs}}}));a.extend(a.ui.draggable,{version:"1.7.3",eventPrefix:"drag",defaults:{addClasses:true,appendTo:"parent",axis:false,cancel:":input,option",connectToSortable:false,containment:false,cursor:"auto",cursorAt:false,delay:0,distance:1,grid:false,handle:false,helper:"original",iframeFix:false,opacity:false,refreshPositions:false,revert:false,revertDuration:500,scope:"default",scroll:true,scrollSensitivity:20,scrollSpeed:20,snap:false,snapMode:"both",snapTolerance:20,stack:false,zIndex:false}});a.ui.plugin.add("draggable","connectToSortable",{start:function(c,e){var d=a(this).data("draggable"),f=d.options,b=a.extend({},e,{item:d.element});d.sortables=[];a(f.connectToSortable).each(function(){var g=a.data(this,"sortable");if(g&&!g.options.disabled){d.sortables.push({instance:g,shouldRevert:g.options.revert});g._refreshItems();g._trigger("activate",c,b)}})},stop:function(c,e){var d=a(this).data("draggable"),b=a.extend({},e,{item:d.element});a.each(d.sortables,function(){if(this.instance.isOver){this.instance.isOver=0;d.cancelHelperRemoval=true;this.instance.cancelHelperRemoval=false;if(this.shouldRevert){this.instance.options.revert=true}this.instance._mouseStop(c);this.instance.options.helper=this.instance.options._helper;if(d.options.helper=="original"){this.instance.currentItem.css({top:"auto",left:"auto"})}}else{this.instance.cancelHelperRemoval=false;this.instance._trigger("deactivate",c,b)}})},drag:function(c,f){var e=a(this).data("draggable"),b=this;var d=function(i){var n=this.offset.click.top,m=this.offset.click.left;var g=this.positionAbs.top,k=this.positionAbs.left;var j=i.height,l=i.width;var p=i.top,h=i.left;return a.ui.isOver(g+n,k+m,p,h,j,l)};a.each(e.sortables,function(g){this.instance.positionAbs=e.positionAbs;this.instance.helperProportions=e.helperProportions;this.instance.offset.click=e.offset.click;if(this.instance._intersectsWith(this.instance.containerCache)){if(!this.instance.isOver){this.instance.isOver=1;this.instance.currentItem=a(b).clone().appendTo(this.instance.element).data("sortable-item",true);this.instance.options._helper=this.instance.options.helper;this.instance.options.helper=function(){return f.helper[0]};c.target=this.instance.currentItem[0];this.instance._mouseCapture(c,true);this.instance._mouseStart(c,true,true);this.instance.offset.click.top=e.offset.click.top;this.instance.offset.click.left=e.offset.click.left;this.instance.offset.parent.left-=e.offset.parent.left-this.instance.offset.parent.left;this.instance.offset.parent.top-=e.offset.parent.top-this.instance.offset.parent.top;e._trigger("toSortable",c);e.dropped=this.instance.element;e.currentItem=e.element;this.instance.fromOutside=e}if(this.instance.currentItem){this.instance._mouseDrag(c)}}else{if(this.instance.isOver){this.instance.isOver=0;this.instance.cancelHelperRemoval=true;this.instance.options.revert=false;this.instance._trigger("out",c,this.instance._uiHash(this.instance));this.instance._mouseStop(c,true);this.instance.options.helper=this.instance.options._helper;this.instance.currentItem.remove();if(this.instance.placeholder){this.instance.placeholder.remove()}e._trigger("fromSortable",c);e.dropped=false}}})}});a.ui.plugin.add("draggable","cursor",{start:function(c,d){var b=a("body"),e=a(this).data("draggable").options;if(b.css("cursor")){e._cursor=b.css("cursor")}b.css("cursor",e.cursor)},stop:function(b,c){var d=a(this).data("draggable").options;if(d._cursor){a("body").css("cursor",d._cursor)}}});a.ui.plugin.add("draggable","iframeFix",{start:function(b,c){var d=a(this).data("draggable").options;a(d.iframeFix===true?"iframe":d.iframeFix).each(function(){a('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>').css({width:this.offsetWidth+"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1000}).css(a(this).offset()).appendTo("body")})},stop:function(b,c){a("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this)})}});a.ui.plugin.add("draggable","opacity",{start:function(c,d){var b=a(d.helper),e=a(this).data("draggable").options;if(b.css("opacity")){e._opacity=b.css("opacity")}b.css("opacity",e.opacity)},stop:function(b,c){var d=a(this).data("draggable").options;if(d._opacity){a(c.helper).css("opacity",d._opacity)}}});a.ui.plugin.add("draggable","scroll",{start:function(c,d){var b=a(this).data("draggable");if(b.scrollParent[0]!=document&&b.scrollParent[0].tagName!="HTML"){b.overflowOffset=b.scrollParent.offset()}},drag:function(d,e){var c=a(this).data("draggable"),f=c.options,b=false;if(c.scrollParent[0]!=document&&c.scrollParent[0].tagName!="HTML"){if(!f.axis||f.axis!="x"){if((c.overflowOffset.top+c.scrollParent[0].offsetHeight)-d.pageY<f.scrollSensitivity){c.scrollParent[0].scrollTop=b=c.scrollParent[0].scrollTop+f.scrollSpeed}else{if(d.pageY-c.overflowOffset.top<f.scrollSensitivity){c.scrollParent[0].scrollTop=b=c.scrollParent[0].scrollTop-f.scrollSpeed}}}if(!f.axis||f.axis!="y"){if((c.overflowOffset.left+c.scrollParent[0].offsetWidth)-d.pageX<f.scrollSensitivity){c.scrollParent[0].scrollLeft=b=c.scrollParent[0].scrollLeft+f.scrollSpeed}else{if(d.pageX-c.overflowOffset.left<f.scrollSensitivity){c.scrollParent[0].scrollLeft=b=c.scrollParent[0].scrollLeft-f.scrollSpeed}}}}else{if(!f.axis||f.axis!="x"){if(d.pageY-a(document).scrollTop()<f.scrollSensitivity){b=a(document).scrollTop(a(document).scrollTop()-f.scrollSpeed)}else{if(a(window).height()-(d.pageY-a(document).scrollTop())<f.scrollSensitivity){b=a(document).scrollTop(a(document).scrollTop()+f.scrollSpeed)}}}if(!f.axis||f.axis!="y"){if(d.pageX-a(document).scrollLeft()<f.scrollSensitivity){b=a(document).scrollLeft(a(document).scrollLeft()-f.scrollSpeed)}else{if(a(window).width()-(d.pageX-a(document).scrollLeft())<f.scrollSensitivity){b=a(document).scrollLeft(a(document).scrollLeft()+f.scrollSpeed)}}}}if(b!==false&&a.ui.ddmanager&&!f.dropBehaviour){a.ui.ddmanager.prepareOffsets(c,d)}}});a.ui.plugin.add("draggable","snap",{start:function(c,d){var b=a(this).data("draggable"),e=b.options;b.snapElements=[];a(e.snap.constructor!=String?(e.snap.items||":data(draggable)"):e.snap).each(function(){var g=a(this);var f=g.offset();if(this!=b.element[0]){b.snapElements.push({item:this,width:g.outerWidth(),height:g.outerHeight(),top:f.top,left:f.left})}})},drag:function(u,p){var g=a(this).data("draggable"),q=g.options;var y=q.snapTolerance;var x=p.offset.left,w=x+g.helperProportions.width,f=p.offset.top,e=f+g.helperProportions.height;for(var v=g.snapElements.length-1;v>=0;v--){var s=g.snapElements[v].left,n=s+g.snapElements[v].width,m=g.snapElements[v].top,A=m+g.snapElements[v].height;if(!((s-y<x&&x<n+y&&m-y<f&&f<A+y)||(s-y<x&&x<n+y&&m-y<e&&e<A+y)||(s-y<w&&w<n+y&&m-y<f&&f<A+y)||(s-y<w&&w<n+y&&m-y<e&&e<A+y))){if(g.snapElements[v].snapping){(g.options.snap.release&&g.options.snap.release.call(g.element,u,a.extend(g._uiHash(),{snapItem:g.snapElements[v].item})))}g.snapElements[v].snapping=false;continue}if(q.snapMode!="inner"){var c=Math.abs(m-e)<=y;var z=Math.abs(A-f)<=y;var j=Math.abs(s-w)<=y;var k=Math.abs(n-x)<=y;if(c){p.position.top=g._convertPositionTo("relative",{top:m-g.helperProportions.height,left:0}).top-g.margins.top}if(z){p.position.top=g._convertPositionTo("relative",{top:A,left:0}).top-g.margins.top}if(j){p.position.left=g._convertPositionTo("relative",{top:0,left:s-g.helperProportions.width}).left-g.margins.left}if(k){p.position.left=g._convertPositionTo("relative",{top:0,left:n}).left-g.margins.left}}var h=(c||z||j||k);if(q.snapMode!="outer"){var c=Math.abs(m-f)<=y;var z=Math.abs(A-e)<=y;var j=Math.abs(s-x)<=y;var k=Math.abs(n-w)<=y;if(c){p.position.top=g._convertPositionTo("relative",{top:m,left:0}).top-g.margins.top}if(z){p.position.top=g._convertPositionTo("relative",{top:A-g.helperProportions.height,left:0}).top-g.margins.top}if(j){p.position.left=g._convertPositionTo("relative",{top:0,left:s}).left-g.margins.left}if(k){p.position.left=g._convertPositionTo("relative",{top:0,left:n-g.helperProportions.width}).left-g.margins.left}}if(!g.snapElements[v].snapping&&(c||z||j||k||h)){(g.options.snap.snap&&g.options.snap.snap.call(g.element,u,a.extend(g._uiHash(),{snapItem:g.snapElements[v].item})))}g.snapElements[v].snapping=(c||z||j||k||h)}}});a.ui.plugin.add("draggable","stack",{start:function(b,c){var e=a(this).data("draggable").options;var d=a.makeArray(a(e.stack.group)).sort(function(g,f){return(parseInt(a(g).css("zIndex"),10)||e.stack.min)-(parseInt(a(f).css("zIndex"),10)||e.stack.min)});a(d).each(function(f){this.style.zIndex=e.stack.min+f});this[0].style.zIndex=e.stack.min+d.length}});a.ui.plugin.add("draggable","zIndex",{start:function(c,d){var b=a(d.helper),e=a(this).data("draggable").options;if(b.css("zIndex")){e._zIndex=b.css("zIndex")}b.css("zIndex",e.zIndex)},stop:function(b,c){var d=a(this).data("draggable").options;if(d._zIndex){a(c.helper).css("zIndex",d._zIndex)}}})})(jQuery);;/* * jQuery UI Droppable 1.7.3 * * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://docs.jquery.com/UI/Droppables * * Depends: * ui.core.js * ui.draggable.js */ (function(a){a.widget("ui.droppable",{_init:function(){var c=this.options,b=c.accept;this.isover=0;this.isout=1;this.options.accept=this.options.accept&&a.isFunction(this.options.accept)?this.options.accept:function(e){return e.is(b)};this.proportions={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight};a.ui.ddmanager.droppables[this.options.scope]=a.ui.ddmanager.droppables[this.options.scope]||[];a.ui.ddmanager.droppables[this.options.scope].push(this);(this.options.addClasses&&this.element.addClass("ui-droppable"))},destroy:function(){var b=a.ui.ddmanager.droppables[this.options.scope];for(var c=0;c<b.length;c++){if(b[c]==this){b.splice(c,1)}}this.element.removeClass("ui-droppable ui-droppable-disabled").removeData("droppable").unbind(".droppable")},_setData:function(b,c){if(b=="accept"){this.options.accept=c&&a.isFunction(c)?c:function(e){return e.is(c)}}else{a.widget.prototype._setData.apply(this,arguments)}},_activate:function(c){var b=a.ui.ddmanager.current;if(this.options.activeClass){this.element.addClass(this.options.activeClass)}(b&&this._trigger("activate",c,this.ui(b)))},_deactivate:function(c){var b=a.ui.ddmanager.current;if(this.options.activeClass){this.element.removeClass(this.options.activeClass)}(b&&this._trigger("deactivate",c,this.ui(b)))},_over:function(c){var b=a.ui.ddmanager.current;if(!b||(b.currentItem||b.element)[0]==this.element[0]){return}if(this.options.accept.call(this.element[0],(b.currentItem||b.element))){if(this.options.hoverClass){this.element.addClass(this.options.hoverClass)}this._trigger("over",c,this.ui(b))}},_out:function(c){var b=a.ui.ddmanager.current;if(!b||(b.currentItem||b.element)[0]==this.element[0]){return}if(this.options.accept.call(this.element[0],(b.currentItem||b.element))){if(this.options.hoverClass){this.element.removeClass(this.options.hoverClass)}this._trigger("out",c,this.ui(b))}},_drop:function(c,d){var b=d||a.ui.ddmanager.current;if(!b||(b.currentItem||b.element)[0]==this.element[0]){return false}var e=false;this.element.find(":data(droppable)").not(".ui-draggable-dragging").each(function(){var f=a.data(this,"droppable");if(f.options.greedy&&a.ui.intersect(b,a.extend(f,{offset:f.element.offset()}),f.options.tolerance)){e=true;return false}});if(e){return false}if(this.options.accept.call(this.element[0],(b.currentItem||b.element))){if(this.options.activeClass){this.element.removeClass(this.options.activeClass)}if(this.options.hoverClass){this.element.removeClass(this.options.hoverClass)}this._trigger("drop",c,this.ui(b));return this.element}return false},ui:function(b){return{draggable:(b.currentItem||b.element),helper:b.helper,position:b.position,absolutePosition:b.positionAbs,offset:b.positionAbs}}});a.extend(a.ui.droppable,{version:"1.7.3",eventPrefix:"drop",defaults:{accept:"*",activeClass:false,addClasses:true,greedy:false,hoverClass:false,scope:"default",tolerance:"intersect"}});a.ui.intersect=function(q,j,o){if(!j.offset){return false}var e=(q.positionAbs||q.position.absolute).left,d=e+q.helperProportions.width,n=(q.positionAbs||q.position.absolute).top,m=n+q.helperProportions.height;var g=j.offset.left,c=g+j.proportions.width,p=j.offset.top,k=p+j.proportions.height;switch(o){case"fit":return(g<e&&d<c&&p<n&&m<k);break;case"intersect":return(g<e+(q.helperProportions.width/2)&&d-(q.helperProportions.width/2)<c&&p<n+(q.helperProportions.height/2)&&m-(q.helperProportions.height/2)<k);break;case"pointer":var h=((q.positionAbs||q.position.absolute).left+(q.clickOffset||q.offset.click).left),i=((q.positionAbs||q.position.absolute).top+(q.clickOffset||q.offset.click).top),f=a.ui.isOver(i,h,p,g,j.proportions.height,j.proportions.width);return f;break;case"touch":return((n>=p&&n<=k)||(m>=p&&m<=k)||(n<p&&m>k))&&((e>=g&&e<=c)||(d>=g&&d<=c)||(e<g&&d>c));break;default:return false;break}};a.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(e,g){var b=a.ui.ddmanager.droppables[e.options.scope];var f=g?g.type:null;var h=(e.currentItem||e.element).find(":data(droppable)").andSelf();droppablesLoop:for(var d=0;d<b.length;d++){if(b[d].options.disabled||(e&&!b[d].options.accept.call(b[d].element[0],(e.currentItem||e.element)))){continue}for(var c=0;c<h.length;c++){if(h[c]==b[d].element[0]){b[d].proportions.height=0;continue droppablesLoop}}b[d].visible=b[d].element.css("display")!="none";if(!b[d].visible){continue}b[d].offset=b[d].element.offset();b[d].proportions={width:b[d].element[0].offsetWidth,height:b[d].element[0].offsetHeight};if(f=="mousedown"){b[d]._activate.call(b[d],g)}}},drop:function(b,c){var d=false;a.each(a.ui.ddmanager.droppables[b.options.scope],function(){if(!this.options){return}if(!this.options.disabled&&this.visible&&a.ui.intersect(b,this,this.options.tolerance)){d=this._drop.call(this,c)}if(!this.options.disabled&&this.visible&&this.options.accept.call(this.element[0],(b.currentItem||b.element))){this.isout=1;this.isover=0;this._deactivate.call(this,c)}});return d},drag:function(b,c){if(b.options.refreshPositions){a.ui.ddmanager.prepareOffsets(b,c)}a.each(a.ui.ddmanager.droppables[b.options.scope],function(){if(this.options.disabled||this.greedyChild||!this.visible){return}var e=a.ui.intersect(b,this,this.options.tolerance);var g=!e&&this.isover==1?"isout":(e&&this.isover==0?"isover":null);if(!g){return}var f;if(this.options.greedy){var d=this.element.parents(":data(droppable):eq(0)");if(d.length){f=a.data(d[0],"droppable");f.greedyChild=(g=="isover"?1:0)}}if(f&&g=="isover"){f.isover=0;f.isout=1;f._out.call(f,c)}this[g]=1;this[g=="isout"?"isover":"isout"]=0;this[g=="isover"?"_over":"_out"].call(this,c);if(f&&g=="isout"){f.isout=0;f.isover=1;f._over.call(f,c)}})}}})(jQuery);;/* * jQuery UI Resizable 1.7.3 * * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://docs.jquery.com/UI/Resizables * * Depends: * ui.core.js */ (function(c){c.widget("ui.resizable",c.extend({},c.ui.mouse,{_init:function(){var e=this,j=this.options;this.element.addClass("ui-resizable");c.extend(this,{_aspectRatio:!!(j.aspectRatio),aspectRatio:j.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:j.helper||j.ghost||j.animate?j.helper||"ui-resizable-helper":null});if(this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)){if(/relative/.test(this.element.css("position"))&&c.browser.opera){this.element.css({position:"relative",top:"auto",left:"auto"})}this.element.wrap(c('<div class="ui-wrapper" style="overflow: hidden;"></div>').css({position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")}));this.element=this.element.parent().data("resizable",this.element.data("resizable"));this.elementIsWrapper=true;this.element.css({marginLeft:this.originalElement.css("marginLeft"),marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom")});this.originalElement.css({marginLeft:0,marginTop:0,marginRight:0,marginBottom:0});this.originalResizeStyle=this.originalElement.css("resize");this.originalElement.css("resize","none");this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"}));this.originalElement.css({margin:this.originalElement.css("margin")});this._proportionallyResize()}this.handles=j.handles||(!c(".ui-resizable-handle",this.element).length?"e,s,se":{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"});if(this.handles.constructor==String){if(this.handles=="all"){this.handles="n,e,s,w,se,sw,ne,nw"}var k=this.handles.split(",");this.handles={};for(var f=0;f<k.length;f++){var h=c.trim(k[f]),d="ui-resizable-"+h;var g=c('<div class="ui-resizable-handle '+d+'"></div>');if(/sw|se|ne|nw/.test(h)){g.css({zIndex:++j.zIndex})}if("se"==h){g.addClass("ui-icon ui-icon-gripsmall-diagonal-se")}this.handles[h]=".ui-resizable-"+h;this.element.append(g)}}this._renderAxis=function(p){p=p||this.element;for(var m in this.handles){if(this.handles[m].constructor==String){this.handles[m]=c(this.handles[m],this.element).show()}if(this.elementIsWrapper&&this.originalElement[0].nodeName.match(/textarea|input|select|button/i)){var n=c(this.handles[m],this.element),o=0;o=/sw|ne|nw|se|n|s/.test(m)?n.outerHeight():n.outerWidth();var l=["padding",/ne|nw|n/.test(m)?"Top":/se|sw|s/.test(m)?"Bottom":/^e$/.test(m)?"Right":"Left"].join("");p.css(l,o);this._proportionallyResize()}if(!c(this.handles[m]).length){continue}}};this._renderAxis(this.element);this._handles=c(".ui-resizable-handle",this.element).disableSelection();this._handles.mouseover(function(){if(!e.resizing){if(this.className){var i=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i)}e.axis=i&&i[1]?i[1]:"se"}});if(j.autoHide){this._handles.hide();c(this.element).addClass("ui-resizable-autohide").hover(function(){c(this).removeClass("ui-resizable-autohide");e._handles.show()},function(){if(!e.resizing){c(this).addClass("ui-resizable-autohide");e._handles.hide()}})}this._mouseInit()},destroy:function(){this._mouseDestroy();var d=function(f){c(f).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing").removeData("resizable").unbind(".resizable").find(".ui-resizable-handle").remove()};if(this.elementIsWrapper){d(this.element);var e=this.element;e.parent().append(this.originalElement.css({position:e.css("position"),width:e.outerWidth(),height:e.outerHeight(),top:e.css("top"),left:e.css("left")})).end().remove()}this.originalElement.css("resize",this.originalResizeStyle);d(this.originalElement)},_mouseCapture:function(e){var f=false;for(var d in this.handles){if(c(this.handles[d])[0]==e.target){f=true}}return this.options.disabled||!!f},_mouseStart:function(f){var i=this.options,e=this.element.position(),d=this.element;this.resizing=true;this.documentScroll={top:c(document).scrollTop(),left:c(document).scrollLeft()};if(d.is(".ui-draggable")||(/absolute/).test(d.css("position"))){d.css({position:"absolute",top:e.top,left:e.left})}if(c.browser.opera&&(/relative/).test(d.css("position"))){d.css({position:"relative",top:"auto",left:"auto"})}this._renderProxy();var j=b(this.helper.css("left")),g=b(this.helper.css("top"));if(i.containment){j+=c(i.containment).scrollLeft()||0;g+=c(i.containment).scrollTop()||0}this.offset=this.helper.offset();this.position={left:j,top:g};this.size=this._helper?{width:d.outerWidth(),height:d.outerHeight()}:{width:d.width(),height:d.height()};this.originalSize=this._helper?{width:d.outerWidth(),height:d.outerHeight()}:{width:d.width(),height:d.height()};this.originalPosition={left:j,top:g};this.sizeDiff={width:d.outerWidth()-d.width(),height:d.outerHeight()-d.height()};this.originalMousePosition={left:f.pageX,top:f.pageY};this.aspectRatio=(typeof i.aspectRatio=="number")?i.aspectRatio:((this.originalSize.width/this.originalSize.height)||1);var h=c(".ui-resizable-"+this.axis).css("cursor");c("body").css("cursor",h=="auto"?this.axis+"-resize":h);d.addClass("ui-resizable-resizing");this._propagate("start",f);return true},_mouseDrag:function(d){var g=this.helper,f=this.options,l={},p=this,i=this.originalMousePosition,m=this.axis;var q=(d.pageX-i.left)||0,n=(d.pageY-i.top)||0;var h=this._change[m];if(!h){return false}var k=h.apply(this,[d,q,n]),j=c.browser.msie&&c.browser.version<7,e=this.sizeDiff;if(this._aspectRatio||d.shiftKey){k=this._updateRatio(k,d)}k=this._respectSize(k,d);this._propagate("resize",d);g.css({top:this.position.top+"px",left:this.position.left+"px",width:this.size.width+"px",height:this.size.height+"px"});if(!this._helper&&this._proportionallyResizeElements.length){this._proportionallyResize()}this._updateCache(k);this._trigger("resize",d,this.ui());return false},_mouseStop:function(g){this.resizing=false;var h=this.options,l=this;if(this._helper){var f=this._proportionallyResizeElements,d=f.length&&(/textarea/i).test(f[0].nodeName),e=d&&c.ui.hasScroll(f[0],"left")?0:l.sizeDiff.height,j=d?0:l.sizeDiff.width;var m={width:(l.size.width-j),height:(l.size.height-e)},i=(parseInt(l.element.css("left"),10)+(l.position.left-l.originalPosition.left))||null,k=(parseInt(l.element.css("top"),10)+(l.position.top-l.originalPosition.top))||null;if(!h.animate){this.element.css(c.extend(m,{top:k,left:i}))}l.helper.height(l.size.height);l.helper.width(l.size.width);if(this._helper&&!h.animate){this._proportionallyResize()}}c("body").css("cursor","auto");this.element.removeClass("ui-resizable-resizing");this._propagate("stop",g);if(this._helper){this.helper.remove()}return false},_updateCache:function(d){var e=this.options;this.offset=this.helper.offset();if(a(d.left)){this.position.left=d.left}if(a(d.top)){this.position.top=d.top}if(a(d.height)){this.size.height=d.height}if(a(d.width)){this.size.width=d.width}},_updateRatio:function(g,f){var h=this.options,i=this.position,e=this.size,d=this.axis;if(g.height){g.width=(e.height*this.aspectRatio)}else{if(g.width){g.height=(e.width/this.aspectRatio)}}if(d=="sw"){g.left=i.left+(e.width-g.width);g.top=null}if(d=="nw"){g.top=i.top+(e.height-g.height);g.left=i.left+(e.width-g.width)}return g},_respectSize:function(k,f){var i=this.helper,h=this.options,q=this._aspectRatio||f.shiftKey,p=this.axis,s=a(k.width)&&h.maxWidth&&(h.maxWidth<k.width),l=a(k.height)&&h.maxHeight&&(h.maxHeight<k.height),g=a(k.width)&&h.minWidth&&(h.minWidth>k.width),r=a(k.height)&&h.minHeight&&(h.minHeight>k.height);if(g){k.width=h.minWidth}if(r){k.height=h.minHeight}if(s){k.width=h.maxWidth}if(l){k.height=h.maxHeight}var e=this.originalPosition.left+this.originalSize.width,n=this.position.top+this.size.height;var j=/sw|nw|w/.test(p),d=/nw|ne|n/.test(p);if(g&&j){k.left=e-h.minWidth}if(s&&j){k.left=e-h.maxWidth}if(r&&d){k.top=n-h.minHeight}if(l&&d){k.top=n-h.maxHeight}var m=!k.width&&!k.height;if(m&&!k.left&&k.top){k.top=null}else{if(m&&!k.top&&k.left){k.left=null}}return k},_proportionallyResize:function(){var j=this.options;if(!this._proportionallyResizeElements.length){return}var f=this.helper||this.element;for(var e=0;e<this._proportionallyResizeElements.length;e++){var g=this._proportionallyResizeElements[e];if(!this.borderDif){var d=[g.css("borderTopWidth"),g.css("borderRightWidth"),g.css("borderBottomWidth"),g.css("borderLeftWidth")],h=[g.css("paddingTop"),g.css("paddingRight"),g.css("paddingBottom"),g.css("paddingLeft")];this.borderDif=c.map(d,function(k,m){var l=parseInt(k,10)||0,n=parseInt(h[m],10)||0;return l+n})}if(c.browser.msie&&!(!(c(f).is(":hidden")||c(f).parents(":hidden").length))){continue}g.css({height:(f.height()-this.borderDif[0]-this.borderDif[2])||0,width:(f.width()-this.borderDif[1]-this.borderDif[3])||0})}},_renderProxy:function(){var e=this.element,h=this.options;this.elementOffset=e.offset();if(this._helper){this.helper=this.helper||c('<div style="overflow:hidden;"></div>');var d=c.browser.msie&&c.browser.version<7,f=(d?1:0),g=(d?2:-1);this.helper.addClass(this._helper).css({width:this.element.outerWidth()+g,height:this.element.outerHeight()+g,position:"absolute",left:this.elementOffset.left-f+"px",top:this.elementOffset.top-f+"px",zIndex:++h.zIndex});this.helper.appendTo("body").disableSelection()}else{this.helper=this.element}},_change:{e:function(f,e,d){return{width:this.originalSize.width+e}},w:function(g,e,d){var i=this.options,f=this.originalSize,h=this.originalPosition;return{left:h.left+e,width:f.width-e}},n:function(g,e,d){var i=this.options,f=this.originalSize,h=this.originalPosition;return{top:h.top+d,height:f.height-d}},s:function(f,e,d){return{height:this.originalSize.height+d}},se:function(f,e,d){return c.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[f,e,d]))},sw:function(f,e,d){return c.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[f,e,d]))},ne:function(f,e,d){return c.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[f,e,d]))},nw:function(f,e,d){return c.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[f,e,d]))}},_propagate:function(e,d){c.ui.plugin.call(this,e,[d,this.ui()]);(e!="resize"&&this._trigger(e,d,this.ui()))},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}}));c.extend(c.ui.resizable,{version:"1.7.3",eventPrefix:"resize",defaults:{alsoResize:false,animate:false,animateDuration:"slow",animateEasing:"swing",aspectRatio:false,autoHide:false,cancel:":input,option",containment:false,delay:0,distance:1,ghost:false,grid:false,handles:"e,s,se",helper:false,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:1000}});c.ui.plugin.add("resizable","alsoResize",{start:function(e,f){var d=c(this).data("resizable"),g=d.options;_store=function(h){c(h).each(function(){c(this).data("resizable-alsoresize",{width:parseInt(c(this).width(),10),height:parseInt(c(this).height(),10),left:parseInt(c(this).css("left"),10),top:parseInt(c(this).css("top"),10)})})};if(typeof(g.alsoResize)=="object"&&!g.alsoResize.parentNode){if(g.alsoResize.length){g.alsoResize=g.alsoResize[0];_store(g.alsoResize)}else{c.each(g.alsoResize,function(h,i){_store(h)})}}else{_store(g.alsoResize)}},resize:function(f,h){var e=c(this).data("resizable"),i=e.options,g=e.originalSize,k=e.originalPosition;var j={height:(e.size.height-g.height)||0,width:(e.size.width-g.width)||0,top:(e.position.top-k.top)||0,left:(e.position.left-k.left)||0},d=function(l,m){c(l).each(function(){var p=c(this),q=c(this).data("resizable-alsoresize"),o={},n=m&&m.length?m:["width","height","top","left"];c.each(n||["width","height","top","left"],function(r,t){var s=(q[t]||0)+(j[t]||0);if(s&&s>=0){o[t]=s||null}});if(/relative/.test(p.css("position"))&&c.browser.opera){e._revertToRelativePosition=true;p.css({position:"absolute",top:"auto",left:"auto"})}p.css(o)})};if(typeof(i.alsoResize)=="object"&&!i.alsoResize.nodeType){c.each(i.alsoResize,function(l,m){d(l,m)})}else{d(i.alsoResize)}},stop:function(e,f){var d=c(this).data("resizable");if(d._revertToRelativePosition&&c.browser.opera){d._revertToRelativePosition=false;el.css({position:"relative"})}c(this).removeData("resizable-alsoresize-start")}});c.ui.plugin.add("resizable","animate",{stop:function(h,m){var n=c(this).data("resizable"),i=n.options;var g=n._proportionallyResizeElements,d=g.length&&(/textarea/i).test(g[0].nodeName),e=d&&c.ui.hasScroll(g[0],"left")?0:n.sizeDiff.height,k=d?0:n.sizeDiff.width;var f={width:(n.size.width-k),height:(n.size.height-e)},j=(parseInt(n.element.css("left"),10)+(n.position.left-n.originalPosition.left))||null,l=(parseInt(n.element.css("top"),10)+(n.position.top-n.originalPosition.top))||null;n.element.animate(c.extend(f,l&&j?{top:l,left:j}:{}),{duration:i.animateDuration,easing:i.animateEasing,step:function(){var o={width:parseInt(n.element.css("width"),10),height:parseInt(n.element.css("height"),10),top:parseInt(n.element.css("top"),10),left:parseInt(n.element.css("left"),10)};if(g&&g.length){c(g[0]).css({width:o.width,height:o.height})}n._updateCache(o);n._propagate("resize",h)}})}});c.ui.plugin.add("resizable","containment",{start:function(e,q){var s=c(this).data("resizable"),i=s.options,k=s.element;var f=i.containment,j=(f instanceof c)?f.get(0):(/parent/.test(f))?k.parent().get(0):f;if(!j){return}s.containerElement=c(j);if(/document/.test(f)||f==document){s.containerOffset={left:0,top:0};s.containerPosition={left:0,top:0};s.parentData={element:c(document),left:0,top:0,width:c(document).width(),height:c(document).height()||document.body.parentNode.scrollHeight}}else{var m=c(j),h=[];c(["Top","Right","Left","Bottom"]).each(function(p,o){h[p]=b(m.css("padding"+o))});s.containerOffset=m.offset();s.containerPosition=m.position();s.containerSize={height:(m.innerHeight()-h[3]),width:(m.innerWidth()-h[1])};var n=s.containerOffset,d=s.containerSize.height,l=s.containerSize.width,g=(c.ui.hasScroll(j,"left")?j.scrollWidth:l),r=(c.ui.hasScroll(j)?j.scrollHeight:d);s.parentData={element:j,left:n.left,top:n.top,width:g,height:r}}},resize:function(f,p){var s=c(this).data("resizable"),h=s.options,e=s.containerSize,n=s.containerOffset,l=s.size,m=s.position,q=s._aspectRatio||f.shiftKey,d={top:0,left:0},g=s.containerElement;if(g[0]!=document&&(/static/).test(g.css("position"))){d=n}if(m.left<(s._helper?n.left:0)){s.size.width=s.size.width+(s._helper?(s.position.left-n.left):(s.position.left-d.left));if(q){s.size.height=s.size.width/h.aspectRatio}s.position.left=h.helper?n.left:0}if(m.top<(s._helper?n.top:0)){s.size.height=s.size.height+(s._helper?(s.position.top-n.top):s.position.top);if(q){s.size.width=s.size.height*h.aspectRatio}s.position.top=s._helper?n.top:0}s.offset.left=s.parentData.left+s.position.left;s.offset.top=s.parentData.top+s.position.top;var k=Math.abs((s._helper?s.offset.left-d.left:(s.offset.left-d.left))+s.sizeDiff.width),r=Math.abs((s._helper?s.offset.top-d.top:(s.offset.top-n.top))+s.sizeDiff.height);var j=s.containerElement.get(0)==s.element.parent().get(0),i=/relative|absolute/.test(s.containerElement.css("position"));if(j&&i){k-=s.parentData.left}if(k+s.size.width>=s.parentData.width){s.size.width=s.parentData.width-k;if(q){s.size.height=s.size.width/s.aspectRatio}}if(r+s.size.height>=s.parentData.height){s.size.height=s.parentData.height-r;if(q){s.size.width=s.size.height*s.aspectRatio}}},stop:function(e,m){var p=c(this).data("resizable"),f=p.options,k=p.position,l=p.containerOffset,d=p.containerPosition,g=p.containerElement;var i=c(p.helper),q=i.offset(),n=i.outerWidth()-p.sizeDiff.width,j=i.outerHeight()-p.sizeDiff.height;if(p._helper&&!f.animate&&(/relative/).test(g.css("position"))){c(this).css({left:q.left-d.left-l.left,width:n,height:j})}if(p._helper&&!f.animate&&(/static/).test(g.css("position"))){c(this).css({left:q.left-d.left-l.left,width:n,height:j})}}});c.ui.plugin.add("resizable","ghost",{start:function(f,g){var d=c(this).data("resizable"),h=d.options,e=d.size;d.ghost=d.originalElement.clone();d.ghost.css({opacity:0.25,display:"block",position:"relative",height:e.height,width:e.width,margin:0,left:0,top:0}).addClass("ui-resizable-ghost").addClass(typeof h.ghost=="string"?h.ghost:"");d.ghost.appendTo(d.helper)},resize:function(e,f){var d=c(this).data("resizable"),g=d.options;if(d.ghost){d.ghost.css({position:"relative",height:d.size.height,width:d.size.width})}},stop:function(e,f){var d=c(this).data("resizable"),g=d.options;if(d.ghost&&d.helper){d.helper.get(0).removeChild(d.ghost.get(0))}}});c.ui.plugin.add("resizable","grid",{resize:function(d,l){var n=c(this).data("resizable"),g=n.options,j=n.size,h=n.originalSize,i=n.originalPosition,m=n.axis,k=g._aspectRatio||d.shiftKey;g.grid=typeof g.grid=="number"?[g.grid,g.grid]:g.grid;var f=Math.round((j.width-h.width)/(g.grid[0]||1))*(g.grid[0]||1),e=Math.round((j.height-h.height)/(g.grid[1]||1))*(g.grid[1]||1);if(/^(se|s|e)$/.test(m)){n.size.width=h.width+f;n.size.height=h.height+e}else{if(/^(ne)$/.test(m)){n.size.width=h.width+f;n.size.height=h.height+e;n.position.top=i.top-e}else{if(/^(sw)$/.test(m)){n.size.width=h.width+f;n.size.height=h.height+e;n.position.left=i.left-f}else{n.size.width=h.width+f;n.size.height=h.height+e;n.position.top=i.top-e;n.position.left=i.left-f}}}}});var b=function(d){return parseInt(d,10)||0};var a=function(d){return !isNaN(parseInt(d,10))}})(jQuery);;/* * jQuery UI Selectable 1.7.3 * * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://docs.jquery.com/UI/Selectables * * Depends: * ui.core.js */ (function(a){a.widget("ui.selectable",a.extend({},a.ui.mouse,{_init:function(){var b=this;this.element.addClass("ui-selectable");this.dragged=false;var c;this.refresh=function(){c=a(b.options.filter,b.element[0]);c.each(function(){var d=a(this);var e=d.offset();a.data(this,"selectable-item",{element:this,$element:d,left:e.left,top:e.top,right:e.left+d.outerWidth(),bottom:e.top+d.outerHeight(),startselected:false,selected:d.hasClass("ui-selected"),selecting:d.hasClass("ui-selecting"),unselecting:d.hasClass("ui-unselecting")})})};this.refresh();this.selectees=c.addClass("ui-selectee");this._mouseInit();this.helper=a(document.createElement("div")).css({border:"1px dotted black"}).addClass("ui-selectable-helper")},destroy:function(){this.element.removeClass("ui-selectable ui-selectable-disabled").removeData("selectable").unbind(".selectable");this._mouseDestroy()},_mouseStart:function(d){var b=this;this.opos=[d.pageX,d.pageY];if(this.options.disabled){return}var c=this.options;this.selectees=a(c.filter,this.element[0]);this._trigger("start",d);a(c.appendTo).append(this.helper);this.helper.css({"z-index":100,position:"absolute",left:d.clientX,top:d.clientY,width:0,height:0});if(c.autoRefresh){this.refresh()}this.selectees.filter(".ui-selected").each(function(){var e=a.data(this,"selectable-item");e.startselected=true;if(!d.metaKey){e.$element.removeClass("ui-selected");e.selected=false;e.$element.addClass("ui-unselecting");e.unselecting=true;b._trigger("unselecting",d,{unselecting:e.element})}});a(d.target).parents().andSelf().each(function(){var e=a.data(this,"selectable-item");if(e){e.$element.removeClass("ui-unselecting").addClass("ui-selecting");e.unselecting=false;e.selecting=true;e.selected=true;b._trigger("selecting",d,{selecting:e.element});return false}})},_mouseDrag:function(i){var c=this;this.dragged=true;if(this.options.disabled){return}var e=this.options;var d=this.opos[0],h=this.opos[1],b=i.pageX,g=i.pageY;if(d>b){var f=b;b=d;d=f}if(h>g){var f=g;g=h;h=f}this.helper.css({left:d,top:h,width:b-d,height:g-h});this.selectees.each(function(){var j=a.data(this,"selectable-item");if(!j||j.element==c.element[0]){return}var k=false;if(e.tolerance=="touch"){k=(!(j.left>b||j.right<d||j.top>g||j.bottom<h))}else{if(e.tolerance=="fit"){k=(j.left>d&&j.right<b&&j.top>h&&j.bottom<g)}}if(k){if(j.selected){j.$element.removeClass("ui-selected");j.selected=false}if(j.unselecting){j.$element.removeClass("ui-unselecting");j.unselecting=false}if(!j.selecting){j.$element.addClass("ui-selecting");j.selecting=true;c._trigger("selecting",i,{selecting:j.element})}}else{if(j.selecting){if(i.metaKey&&j.startselected){j.$element.removeClass("ui-selecting");j.selecting=false;j.$element.addClass("ui-selected");j.selected=true}else{j.$element.removeClass("ui-selecting");j.selecting=false;if(j.startselected){j.$element.addClass("ui-unselecting");j.unselecting=true}c._trigger("unselecting",i,{unselecting:j.element})}}if(j.selected){if(!i.metaKey&&!j.startselected){j.$element.removeClass("ui-selected");j.selected=false;j.$element.addClass("ui-unselecting");j.unselecting=true;c._trigger("unselecting",i,{unselecting:j.element})}}}});return false},_mouseStop:function(d){var b=this;this.dragged=false;var c=this.options;a(".ui-unselecting",this.element[0]).each(function(){var e=a.data(this,"selectable-item");e.$element.removeClass("ui-unselecting");e.unselecting=false;e.startselected=false;b._trigger("unselected",d,{unselected:e.element})});a(".ui-selecting",this.element[0]).each(function(){var e=a.data(this,"selectable-item");e.$element.removeClass("ui-selecting").addClass("ui-selected");e.selecting=false;e.selected=true;e.startselected=true;b._trigger("selected",d,{selected:e.element})});this._trigger("stop",d);this.helper.remove();return false}}));a.extend(a.ui.selectable,{version:"1.7.3",defaults:{appendTo:"body",autoRefresh:true,cancel:":input,option",delay:0,distance:0,filter:"*",tolerance:"touch"}})})(jQuery);;/* * jQuery UI Sortable 1.7.3 * * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://docs.jquery.com/UI/Sortables * * Depends: * ui.core.js */ (function(a){a.widget("ui.sortable",a.extend({},a.ui.mouse,{_init:function(){var b=this.options;this.containerCache={};this.element.addClass("ui-sortable");this.refresh();this.floating=this.items.length?(/left|right/).test(this.items[0].item.css("float")):false;this.offset=this.element.offset();this._mouseInit()},destroy:function(){this.element.removeClass("ui-sortable ui-sortable-disabled").removeData("sortable").unbind(".sortable");this._mouseDestroy();for(var b=this.items.length-1;b>=0;b--){this.items[b].item.removeData("sortable-item")}},_mouseCapture:function(e,f){if(this.reverting){return false}if(this.options.disabled||this.options.type=="static"){return false}this._refreshItems(e);var d=null,c=this,b=a(e.target).parents().each(function(){if(a.data(this,"sortable-item")==c){d=a(this);return false}});if(a.data(e.target,"sortable-item")==c){d=a(e.target)}if(!d){return false}if(this.options.handle&&!f){var g=false;a(this.options.handle,d).find("*").andSelf().each(function(){if(this==e.target){g=true}});if(!g){return false}}this.currentItem=d;this._removeCurrentsFromItems();return true},_mouseStart:function(e,f,b){var g=this.options,c=this;this.currentContainer=this;this.refreshPositions();this.helper=this._createHelper(e);this._cacheHelperProportions();this._cacheMargins();this.scrollParent=this.helper.scrollParent();this.offset=this.currentItem.offset();this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left};this.helper.css("position","absolute");this.cssPosition=this.helper.css("position");a.extend(this.offset,{click:{left:e.pageX-this.offset.left,top:e.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.originalPosition=this._generatePosition(e);this.originalPageX=e.pageX;this.originalPageY=e.pageY;if(g.cursorAt){this._adjustOffsetFromHelper(g.cursorAt)}this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]};if(this.helper[0]!=this.currentItem[0]){this.currentItem.hide()}this._createPlaceholder();if(g.containment){this._setContainment()}if(g.cursor){if(a("body").css("cursor")){this._storedCursor=a("body").css("cursor")}a("body").css("cursor",g.cursor)}if(g.opacity){if(this.helper.css("opacity")){this._storedOpacity=this.helper.css("opacity")}this.helper.css("opacity",g.opacity)}if(g.zIndex){if(this.helper.css("zIndex")){this._storedZIndex=this.helper.css("zIndex")}this.helper.css("zIndex",g.zIndex)}if(this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"){this.overflowOffset=this.scrollParent.offset()}this._trigger("start",e,this._uiHash());if(!this._preserveHelperProportions){this._cacheHelperProportions()}if(!b){for(var d=this.containers.length-1;d>=0;d--){this.containers[d]._trigger("activate",e,c._uiHash(this))}}if(a.ui.ddmanager){a.ui.ddmanager.current=this}if(a.ui.ddmanager&&!g.dropBehaviour){a.ui.ddmanager.prepareOffsets(this,e)}this.dragging=true;this.helper.addClass("ui-sortable-helper");this._mouseDrag(e);return true},_mouseDrag:function(f){this.position=this._generatePosition(f);this.positionAbs=this._convertPositionTo("absolute");if(!this.lastPositionAbs){this.lastPositionAbs=this.positionAbs}if(this.options.scroll){var g=this.options,b=false;if(this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"){if((this.overflowOffset.top+this.scrollParent[0].offsetHeight)-f.pageY<g.scrollSensitivity){this.scrollParent[0].scrollTop=b=this.scrollParent[0].scrollTop+g.scrollSpeed}else{if(f.pageY-this.overflowOffset.top<g.scrollSensitivity){this.scrollParent[0].scrollTop=b=this.scrollParent[0].scrollTop-g.scrollSpeed}}if((this.overflowOffset.left+this.scrollParent[0].offsetWidth)-f.pageX<g.scrollSensitivity){this.scrollParent[0].scrollLeft=b=this.scrollParent[0].scrollLeft+g.scrollSpeed}else{if(f.pageX-this.overflowOffset.left<g.scrollSensitivity){this.scrollParent[0].scrollLeft=b=this.scrollParent[0].scrollLeft-g.scrollSpeed}}}else{if(f.pageY-a(document).scrollTop()<g.scrollSensitivity){b=a(document).scrollTop(a(document).scrollTop()-g.scrollSpeed)}else{if(a(window).height()-(f.pageY-a(document).scrollTop())<g.scrollSensitivity){b=a(document).scrollTop(a(document).scrollTop()+g.scrollSpeed)}}if(f.pageX-a(document).scrollLeft()<g.scrollSensitivity){b=a(document).scrollLeft(a(document).scrollLeft()-g.scrollSpeed)}else{if(a(window).width()-(f.pageX-a(document).scrollLeft())<g.scrollSensitivity){b=a(document).scrollLeft(a(document).scrollLeft()+g.scrollSpeed)}}}if(b!==false&&a.ui.ddmanager&&!g.dropBehaviour){a.ui.ddmanager.prepareOffsets(this,f)}}this.positionAbs=this._convertPositionTo("absolute");if(!this.options.axis||this.options.axis!="y"){this.helper[0].style.left=this.position.left+"px"}if(!this.options.axis||this.options.axis!="x"){this.helper[0].style.top=this.position.top+"px"}for(var d=this.items.length-1;d>=0;d--){var e=this.items[d],c=e.item[0],h=this._intersectsWithPointer(e);if(!h){continue}if(c!=this.currentItem[0]&&this.placeholder[h==1?"next":"prev"]()[0]!=c&&!a.ui.contains(this.placeholder[0],c)&&(this.options.type=="semi-dynamic"?!a.ui.contains(this.element[0],c):true)){this.direction=h==1?"down":"up";if(this.options.tolerance=="pointer"||this._intersectsWithSides(e)){this._rearrange(f,e)}else{break}this._trigger("change",f,this._uiHash());break}}this._contactContainers(f);if(a.ui.ddmanager){a.ui.ddmanager.drag(this,f)}this._trigger("sort",f,this._uiHash());this.lastPositionAbs=this.positionAbs;return false},_mouseStop:function(c,d){if(!c){return}if(a.ui.ddmanager&&!this.options.dropBehaviour){a.ui.ddmanager.drop(this,c)}if(this.options.revert){var b=this;var e=b.placeholder.offset();b.reverting=true;a(this.helper).animate({left:e.left-this.offset.parent.left-b.margins.left+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollLeft),top:e.top-this.offset.parent.top-b.margins.top+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollTop)},parseInt(this.options.revert,10)||500,function(){b._clear(c)})}else{this._clear(c,d)}return false},cancel:function(){var b=this;if(this.dragging){this._mouseUp();if(this.options.helper=="original"){this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else{this.currentItem.show()}for(var c=this.containers.length-1;c>=0;c--){this.containers[c]._trigger("deactivate",null,b._uiHash(this));if(this.containers[c].containerCache.over){this.containers[c]._trigger("out",null,b._uiHash(this));this.containers[c].containerCache.over=0}}}if(this.placeholder[0].parentNode){this.placeholder[0].parentNode.removeChild(this.placeholder[0])}if(this.options.helper!="original"&&this.helper&&this.helper[0].parentNode){this.helper.remove()}a.extend(this,{helper:null,dragging:false,reverting:false,_noFinalSort:null});if(this.domPosition.prev){a(this.domPosition.prev).after(this.currentItem)}else{a(this.domPosition.parent).prepend(this.currentItem)}return true},serialize:function(d){var b=this._getItemsAsjQuery(d&&d.connected);var c=[];d=d||{};a(b).each(function(){var e=(a(d.item||this).attr(d.attribute||"id")||"").match(d.expression||(/(.+)[-=_](.+)/));if(e){c.push((d.key||e[1]+"[]")+"="+(d.key&&d.expression?e[1]:e[2]))}});return c.join("&")},toArray:function(d){var b=this._getItemsAsjQuery(d&&d.connected);var c=[];d=d||{};b.each(function(){c.push(a(d.item||this).attr(d.attribute||"id")||"")});return c},_intersectsWith:function(m){var e=this.positionAbs.left,d=e+this.helperProportions.width,k=this.positionAbs.top,j=k+this.helperProportions.height;var f=m.left,c=f+m.width,n=m.top,i=n+m.height;var o=this.offset.click.top,h=this.offset.click.left;var g=(k+o)>n&&(k+o)<i&&(e+h)>f&&(e+h)<c;if(this.options.tolerance=="pointer"||this.options.forcePointerForContainers||(this.options.tolerance!="pointer"&&this.helperProportions[this.floating?"width":"height"]>m[this.floating?"width":"height"])){return g}else{return(f<e+(this.helperProportions.width/2)&&d-(this.helperProportions.width/2)<c&&n<k+(this.helperProportions.height/2)&&j-(this.helperProportions.height/2)<i)}},_intersectsWithPointer:function(d){var e=a.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,d.top,d.height),c=a.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,d.left,d.width),g=e&&c,b=this._getDragVerticalDirection(),f=this._getDragHorizontalDirection();if(!g){return false}return this.floating?(((f&&f=="right")||b=="down")?2:1):(b&&(b=="down"?2:1))},_intersectsWithSides:function(e){var c=a.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,e.top+(e.height/2),e.height),d=a.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,e.left+(e.width/2),e.width),b=this._getDragVerticalDirection(),f=this._getDragHorizontalDirection();if(this.floating&&f){return((f=="right"&&d)||(f=="left"&&!d))}else{return b&&((b=="down"&&c)||(b=="up"&&!c))}},_getDragVerticalDirection:function(){var b=this.positionAbs.top-this.lastPositionAbs.top;return b!=0&&(b>0?"down":"up")},_getDragHorizontalDirection:function(){var b=this.positionAbs.left-this.lastPositionAbs.left;return b!=0&&(b>0?"right":"left")},refresh:function(b){this._refreshItems(b);this.refreshPositions()},_connectWith:function(){var b=this.options;return b.connectWith.constructor==String?[b.connectWith]:b.connectWith},_getItemsAsjQuery:function(b){var l=this;var g=[];var e=[];var h=this._connectWith();if(h&&b){for(var d=h.length-1;d>=0;d--){var k=a(h[d]);for(var c=k.length-1;c>=0;c--){var f=a.data(k[c],"sortable");if(f&&f!=this&&!f.options.disabled){e.push([a.isFunction(f.options.items)?f.options.items.call(f.element):a(f.options.items,f.element).not(".ui-sortable-helper"),f])}}}}e.push([a.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):a(this.options.items,this.element).not(".ui-sortable-helper"),this]);for(var d=e.length-1;d>=0;d--){e[d][0].each(function(){g.push(this)})}return a(g)},_removeCurrentsFromItems:function(){var d=this.currentItem.find(":data(sortable-item)");for(var c=0;c<this.items.length;c++){for(var b=0;b<d.length;b++){if(d[b]==this.items[c].item[0]){this.items.splice(c,1)}}}},_refreshItems:function(b){this.items=[];this.containers=[this];var h=this.items;var p=this;var f=[[a.isFunction(this.options.items)?this.options.items.call(this.element[0],b,{item:this.currentItem}):a(this.options.items,this.element),this]];var l=this._connectWith();if(l){for(var e=l.length-1;e>=0;e--){var m=a(l[e]);for(var d=m.length-1;d>=0;d--){var g=a.data(m[d],"sortable");if(g&&g!=this&&!g.options.disabled){f.push([a.isFunction(g.options.items)?g.options.items.call(g.element[0],b,{item:this.currentItem}):a(g.options.items,g.element),g]);this.containers.push(g)}}}}for(var e=f.length-1;e>=0;e--){var k=f[e][1];var c=f[e][0];for(var d=0,n=c.length;d<n;d++){var o=a(c[d]);o.data("sortable-item",k);h.push({item:o,instance:k,width:0,height:0,left:0,top:0})}}},refreshPositions:function(b){if(this.offsetParent&&this.helper){this.offset.parent=this._getParentOffset()}for(var d=this.items.length-1;d>=0;d--){var e=this.items[d];if(e.instance!=this.currentContainer&&this.currentContainer&&e.item[0]!=this.currentItem[0]){continue}var c=this.options.toleranceElement?a(this.options.toleranceElement,e.item):e.item;if(!b){e.width=c.outerWidth();e.height=c.outerHeight()}var f=c.offset();e.left=f.left;e.top=f.top}if(this.options.custom&&this.options.custom.refreshContainers){this.options.custom.refreshContainers.call(this)}else{for(var d=this.containers.length-1;d>=0;d--){var f=this.containers[d].element.offset();this.containers[d].containerCache.left=f.left;this.containers[d].containerCache.top=f.top;this.containers[d].containerCache.width=this.containers[d].element.outerWidth();this.containers[d].containerCache.height=this.containers[d].element.outerHeight()}}},_createPlaceholder:function(d){var b=d||this,e=b.options;if(!e.placeholder||e.placeholder.constructor==String){var c=e.placeholder;e.placeholder={element:function(){var f=a(document.createElement(b.currentItem[0].nodeName)).addClass(c||b.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper")[0];if(!c){f.style.visibility="hidden"}return f},update:function(f,g){if(c&&!e.forcePlaceholderSize){return}if(!g.height()){g.height(b.currentItem.innerHeight()-parseInt(b.currentItem.css("paddingTop")||0,10)-parseInt(b.currentItem.css("paddingBottom")||0,10))}if(!g.width()){g.width(b.currentItem.innerWidth()-parseInt(b.currentItem.css("paddingLeft")||0,10)-parseInt(b.currentItem.css("paddingRight")||0,10))}}}}b.placeholder=a(e.placeholder.element.call(b.element,b.currentItem));b.currentItem.after(b.placeholder);e.placeholder.update(b,b.placeholder)},_contactContainers:function(d){for(var c=this.containers.length-1;c>=0;c--){if(this._intersectsWith(this.containers[c].containerCache)){if(!this.containers[c].containerCache.over){if(this.currentContainer!=this.containers[c]){var h=10000;var g=null;var e=this.positionAbs[this.containers[c].floating?"left":"top"];for(var b=this.items.length-1;b>=0;b--){if(!a.ui.contains(this.containers[c].element[0],this.items[b].item[0])){continue}var f=this.items[b][this.containers[c].floating?"left":"top"];if(Math.abs(f-e)<h){h=Math.abs(f-e);g=this.items[b]}}if(!g&&!this.options.dropOnEmpty){continue}this.currentContainer=this.containers[c];g?this._rearrange(d,g,null,true):this._rearrange(d,null,this.containers[c].element,true);this._trigger("change",d,this._uiHash());this.containers[c]._trigger("change",d,this._uiHash(this));this.options.placeholder.update(this.currentContainer,this.placeholder)}this.containers[c]._trigger("over",d,this._uiHash(this));this.containers[c].containerCache.over=1}}else{if(this.containers[c].containerCache.over){this.containers[c]._trigger("out",d,this._uiHash(this));this.containers[c].containerCache.over=0}}}},_createHelper:function(c){var d=this.options;var b=a.isFunction(d.helper)?a(d.helper.apply(this.element[0],[c,this.currentItem])):(d.helper=="clone"?this.currentItem.clone():this.currentItem);if(!b.parents("body").length){a(d.appendTo!="parent"?d.appendTo:this.currentItem[0].parentNode)[0].appendChild(b[0])}if(b[0]==this.currentItem[0]){this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")}}if(b[0].style.width==""||d.forceHelperSize){b.width(this.currentItem.width())}if(b[0].style.height==""||d.forceHelperSize){b.height(this.currentItem.height())}return b},_adjustOffsetFromHelper:function(b){if(b.left!=undefined){this.offset.click.left=b.left+this.margins.left}if(b.right!=undefined){this.offset.click.left=this.helperProportions.width-b.right+this.margins.left}if(b.top!=undefined){this.offset.click.top=b.top+this.margins.top}if(b.bottom!=undefined){this.offset.click.top=this.helperProportions.height-b.bottom+this.margins.top}},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var b=this.offsetParent.offset();if(this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0])){b.left+=this.scrollParent.scrollLeft();b.top+=this.scrollParent.scrollTop()}if((this.offsetParent[0]==document.body)||(this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&a.browser.msie)){b={top:0,left:0}}return{top:b.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:b.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var b=this.currentItem.position();return{top:b.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:b.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}else{return{top:0,left:0}}},_cacheMargins:function(){this.margins={left:(parseInt(this.currentItem.css("marginLeft"),10)||0),top:(parseInt(this.currentItem.css("marginTop"),10)||0)}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var e=this.options;if(e.containment=="parent"){e.containment=this.helper[0].parentNode}if(e.containment=="document"||e.containment=="window"){this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,a(e.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(a(e.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]}if(!(/^(document|window|parent)$/).test(e.containment)){var c=a(e.containment)[0];var d=a(e.containment).offset();var b=(a(c).css("overflow")!="hidden");this.containment=[d.left+(parseInt(a(c).css("borderLeftWidth"),10)||0)+(parseInt(a(c).css("paddingLeft"),10)||0)-this.margins.left,d.top+(parseInt(a(c).css("borderTopWidth"),10)||0)+(parseInt(a(c).css("paddingTop"),10)||0)-this.margins.top,d.left+(b?Math.max(c.scrollWidth,c.offsetWidth):c.offsetWidth)-(parseInt(a(c).css("borderLeftWidth"),10)||0)-(parseInt(a(c).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,d.top+(b?Math.max(c.scrollHeight,c.offsetHeight):c.offsetHeight)-(parseInt(a(c).css("borderTopWidth"),10)||0)-(parseInt(a(c).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top]}},_convertPositionTo:function(f,h){if(!h){h=this.position}var c=f=="absolute"?1:-1;var e=this.options,b=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,g=(/(html|body)/i).test(b[0].tagName);return{top:(h.top+this.offset.relative.top*c+this.offset.parent.top*c-(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():(g?0:b.scrollTop()))*c)),left:(h.left+this.offset.relative.left*c+this.offset.parent.left*c-(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():g?0:b.scrollLeft())*c))}},_generatePosition:function(e){var h=this.options,b=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,i=(/(html|body)/i).test(b[0].tagName);if(this.cssPosition=="relative"&&!(this.scrollParent[0]!=document&&this.scrollParent[0]!=this.offsetParent[0])){this.offset.relative=this._getRelativeOffset()}var d=e.pageX;var c=e.pageY;if(this.originalPosition){if(this.containment){if(e.pageX-this.offset.click.left<this.containment[0]){d=this.containment[0]+this.offset.click.left}if(e.pageY-this.offset.click.top<this.containment[1]){c=this.containment[1]+this.offset.click.top}if(e.pageX-this.offset.click.left>this.containment[2]){d=this.containment[2]+this.offset.click.left}if(e.pageY-this.offset.click.top>this.containment[3]){c=this.containment[3]+this.offset.click.top}}if(h.grid){var g=this.originalPageY+Math.round((c-this.originalPageY)/h.grid[1])*h.grid[1];c=this.containment?(!(g-this.offset.click.top<this.containment[1]||g-this.offset.click.top>this.containment[3])?g:(!(g-this.offset.click.top<this.containment[1])?g-h.grid[1]:g+h.grid[1])):g;var f=this.originalPageX+Math.round((d-this.originalPageX)/h.grid[0])*h.grid[0];d=this.containment?(!(f-this.offset.click.left<this.containment[0]||f-this.offset.click.left>this.containment[2])?f:(!(f-this.offset.click.left<this.containment[0])?f-h.grid[0]:f+h.grid[0])):f}}return{top:(c-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():(i?0:b.scrollTop())))),left:(d-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():i?0:b.scrollLeft())))}},_rearrange:function(g,f,c,e){c?c[0].appendChild(this.placeholder[0]):f.item[0].parentNode.insertBefore(this.placeholder[0],(this.direction=="down"?f.item[0]:f.item[0].nextSibling));this.counter=this.counter?++this.counter:1;var d=this,b=this.counter;window.setTimeout(function(){if(b==d.counter){d.refreshPositions(!e)}},0)},_clear:function(d,e){this.reverting=false;var f=[],b=this;if(!this._noFinalSort&&this.currentItem[0].parentNode){this.placeholder.before(this.currentItem)}this._noFinalSort=null;if(this.helper[0]==this.currentItem[0]){for(var c in this._storedCSS){if(this._storedCSS[c]=="auto"||this._storedCSS[c]=="static"){this._storedCSS[c]=""}}this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else{this.currentItem.show()}if(this.fromOutside&&!e){f.push(function(g){this._trigger("receive",g,this._uiHash(this.fromOutside))})}if((this.fromOutside||this.domPosition.prev!=this.currentItem.prev().not(".ui-sortable-helper")[0]||this.domPosition.parent!=this.currentItem.parent()[0])&&!e){f.push(function(g){this._trigger("update",g,this._uiHash())})}if(!a.ui.contains(this.element[0],this.currentItem[0])){if(!e){f.push(function(g){this._trigger("remove",g,this._uiHash())})}for(var c=this.containers.length-1;c>=0;c--){if(a.ui.contains(this.containers[c].element[0],this.currentItem[0])&&!e){f.push((function(g){return function(h){g._trigger("receive",h,this._uiHash(this))}}).call(this,this.containers[c]));f.push((function(g){return function(h){g._trigger("update",h,this._uiHash(this))}}).call(this,this.containers[c]))}}}for(var c=this.containers.length-1;c>=0;c--){if(!e){f.push((function(g){return function(h){g._trigger("deactivate",h,this._uiHash(this))}}).call(this,this.containers[c]))}if(this.containers[c].containerCache.over){f.push((function(g){return function(h){g._trigger("out",h,this._uiHash(this))}}).call(this,this.containers[c]));this.containers[c].containerCache.over=0}}if(this._storedCursor){a("body").css("cursor",this._storedCursor)}if(this._storedOpacity){this.helper.css("opacity",this._storedOpacity)}if(this._storedZIndex){this.helper.css("zIndex",this._storedZIndex=="auto"?"":this._storedZIndex)}this.dragging=false;if(this.cancelHelperRemoval){if(!e){this._trigger("beforeStop",d,this._uiHash());for(var c=0;c<f.length;c++){f[c].call(this,d)}this._trigger("stop",d,this._uiHash())}return false}if(!e){this._trigger("beforeStop",d,this._uiHash())}this.placeholder[0].parentNode.removeChild(this.placeholder[0]);if(this.helper[0]!=this.currentItem[0]){this.helper.remove()}this.helper=null;if(!e){for(var c=0;c<f.length;c++){f[c].call(this,d)}this._trigger("stop",d,this._uiHash())}this.fromOutside=false;return true},_trigger:function(){if(a.widget.prototype._trigger.apply(this,arguments)===false){this.cancel()}},_uiHash:function(c){var b=c||this;return{helper:b.helper,placeholder:b.placeholder||a([]),position:b.position,absolutePosition:b.positionAbs,offset:b.positionAbs,item:b.currentItem,sender:c?c.element:null}}}));a.extend(a.ui.sortable,{getter:"serialize toArray",version:"1.7.3",eventPrefix:"sort",defaults:{appendTo:"parent",axis:false,cancel:":input,option",connectWith:false,containment:false,cursor:"auto",cursorAt:false,delay:0,distance:1,dropOnEmpty:true,forcePlaceholderSize:false,forceHelperSize:false,grid:false,handle:false,helper:"original",items:"> *",opacity:false,placeholder:false,revert:false,scroll:true,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1000}})})(jQuery);;
ztfy.jqueryui
/ztfy.jqueryui-0.7.12.tar.gz/ztfy.jqueryui-0.7.12/src/ztfy/jqueryui/resources/js/jquery-ui-base-1.7.3.min.js
jquery-ui-base-1.7.3.min.js
(function($){ $.fn.liquidcarousel = function(options) { var defaults = { height: 150, duration: 100, hidearrows: true, centered: true }; var options = $.extend(defaults, options); return this.each(function() { var divobj = $(this); $(divobj).height(options.height); $(divobj).css('overflow', 'hidden'); $('> .wrapper', divobj).height(options.height) .css('overflow', 'hidden') .css('float', 'left'); $('> .wrapper > ul', divobj).height(options.height) .css('float', 'left') .css('margin', '0') .css('padding', '0') .css('display', 'block'); $('> .wrapper > ul > li', divobj).height(options.height) .css('display', 'block') .css('float', 'left'); var originalmarginright = parseInt($('> .wrapper > ul > li', divobj).css('marginRight')); var originalmarginleft = parseInt($('> .wrapper > ul > li', divobj).css('marginLeft')); var visiblelis = 0; var totallis = $('> .wrapper > ul > li', this).length; var currentposition = 0; var liwidth = $('> .wrapper > ul > li:first', divobj).outerWidth(true); var additionalmargin = 0; var totalwidth = liwidth + additionalmargin; $(window).resize(function(e){ var divwidth = $(divobj).width(); var availablewidth = (divwidth - $('> .previous', divobj).outerWidth(true) - $('> .next', divobj).outerWidth(true)); previousvisiblelis = visiblelis; visiblelis = Math.floor((availablewidth / liwidth)); if (visiblelis < totallis) { additionalmargin = Math.floor((availablewidth - (visiblelis * liwidth))/visiblelis); } else { if (options.centered) { additionalmargin = Math.floor((availablewidth - (totallis * liwidth))/totallis); } else { additionalmargin = 0; } } halfadditionalmargin = Math.floor(additionalmargin/2); totalwidth = liwidth + additionalmargin; $('> .wrapper > ul > li', divobj).css('marginRight', originalmarginright + halfadditionalmargin); $('> .wrapper > ul > li', divobj).css('marginLeft',originalmarginleft + halfadditionalmargin); if (visiblelis > previousvisiblelis || totallis <= visiblelis) { currentposition -= (visiblelis-previousvisiblelis); if (currentposition < 0 || totallis <= visiblelis ) { currentposition = 0; } } $('> .wrapper > ul', divobj).css('marginLeft', -(currentposition * totalwidth)); if (visiblelis >= totallis || ((divwidth >= (totallis * liwidth)) && options.hidearrows) ) { if (options.hidearrows) { $('> .previous', divobj).css('visibility', 'hidden'); $('> .next', divobj).css('visibility', 'hidden'); } $('> .wrapper', divobj).width(totallis * totalwidth); $('> ul', divobj).width(totallis * totalwidth); $('> .wrapper', divobj).css('marginLeft', 0); currentposition = 0; } else { $('> .previous', divobj).css('visibility', currentposition > 0 ? 'visible' : 'hidden'); $('> .next', divobj).css('visibility', currentposition < totallis - visiblelis ? 'visible' : 'hidden'); $('> .wrapper', divobj).width(visiblelis * totalwidth); $('> ul', divobj).width(visiblelis * totalwidth); } }); $('> .next', divobj).click(function(){ if (totallis <= visiblelis) { currentposition = 0; } else if ((currentposition + (visiblelis*2)) < totallis) { currentposition += visiblelis; } else if ((currentposition + (visiblelis*2)) >= totallis -1) { currentposition = totallis - visiblelis; } $('> .wrapper > ul', divobj).stop(); $('> .wrapper > ul', divobj).animate({'marginLeft': -(currentposition * totalwidth)}, options.duration); $('> .next', divobj).css('visibility', currentposition < totallis - visiblelis ? 'visible' : 'hidden'); $('> .previous', divobj).css('visibility', currentposition > 0 ? 'visible' : 'hidden'); }); $('> .previous', divobj).click(function(){ if ((currentposition - visiblelis) > 0) { currentposition -= visiblelis; } else if ((currentposition - (visiblelis*2)) <= 0) { currentposition = 0; } $('> .wrapper > ul', divobj).stop(); $('> .wrapper > ul', divobj).animate({'marginLeft': -(currentposition * totalwidth)}, options.duration); $('> .previous', divobj).css('visibility', currentposition > 0 ? 'visible' : 'hidden'); $('> .next', divobj).css('visibility', currentposition < totallis - visiblelis ? 'visible' : 'hidden'); }); $('> .next', divobj).dblclick(function(e){ e.preventDefault(); clearSelection(); }); $('> .previous', divobj).dblclick(function(e){ e.preventDefault(); clearSelection(); }); function clearSelection() { if (document.selection && document.selection.empty) { document.selection.empty(); } else if (window.getSelection) { var sel = window.getSelection(); sel.removeAllRanges(); } } $(window).resize(); }); }; })(jQuery);
ztfy.jqueryui
/ztfy.jqueryui-0.7.12.tar.gz/ztfy.jqueryui-0.7.12/src/ztfy/jqueryui/resources/js/jquery-liquidcarousel.js
jquery-liquidcarousel.js
(function(E,B){function ka(a,b,d){if(d===B&&a.nodeType===1){d=a.getAttribute("data-"+b);if(typeof d==="string"){try{d=d==="true"?true:d==="false"?false:d==="null"?null:!c.isNaN(d)?parseFloat(d):Ja.test(d)?c.parseJSON(d):d}catch(e){}c.data(a,b,d)}else d=B}return d}function U(){return false}function ca(){return true}function la(a,b,d){d[0].type=a;return c.event.handle.apply(b,d)}function Ka(a){var b,d,e,f,h,l,k,o,x,r,A,C=[];f=[];h=c.data(this,this.nodeType?"events":"__events__");if(typeof h==="function")h= h.events;if(!(a.liveFired===this||!h||!h.live||a.button&&a.type==="click")){if(a.namespace)A=RegExp("(^|\\.)"+a.namespace.split(".").join("\\.(?:.*\\.)?")+"(\\.|$)");a.liveFired=this;var J=h.live.slice(0);for(k=0;k<J.length;k++){h=J[k];h.origType.replace(X,"")===a.type?f.push(h.selector):J.splice(k--,1)}f=c(a.target).closest(f,a.currentTarget);o=0;for(x=f.length;o<x;o++){r=f[o];for(k=0;k<J.length;k++){h=J[k];if(r.selector===h.selector&&(!A||A.test(h.namespace))){l=r.elem;e=null;if(h.preType==="mouseenter"|| h.preType==="mouseleave"){a.type=h.preType;e=c(a.relatedTarget).closest(h.selector)[0]}if(!e||e!==l)C.push({elem:l,handleObj:h,level:r.level})}}}o=0;for(x=C.length;o<x;o++){f=C[o];if(d&&f.level>d)break;a.currentTarget=f.elem;a.data=f.handleObj.data;a.handleObj=f.handleObj;A=f.handleObj.origHandler.apply(f.elem,arguments);if(A===false||a.isPropagationStopped()){d=f.level;if(A===false)b=false;if(a.isImmediatePropagationStopped())break}}return b}}function Y(a,b){return(a&&a!=="*"?a+".":"")+b.replace(La, "`").replace(Ma,"&")}function ma(a,b,d){if(c.isFunction(b))return c.grep(a,function(f,h){return!!b.call(f,h,f)===d});else if(b.nodeType)return c.grep(a,function(f){return f===b===d});else if(typeof b==="string"){var e=c.grep(a,function(f){return f.nodeType===1});if(Na.test(b))return c.filter(b,e,!d);else b=c.filter(b,e)}return c.grep(a,function(f){return c.inArray(f,b)>=0===d})}function na(a,b){var d=0;b.each(function(){if(this.nodeName===(a[d]&&a[d].nodeName)){var e=c.data(a[d++]),f=c.data(this, e);if(e=e&&e.events){delete f.handle;f.events={};for(var h in e)for(var l in e[h])c.event.add(this,h,e[h][l],e[h][l].data)}}})}function Oa(a,b){b.src?c.ajax({url:b.src,async:false,dataType:"script"}):c.globalEval(b.text||b.textContent||b.innerHTML||"");b.parentNode&&b.parentNode.removeChild(b)}function oa(a,b,d){var e=b==="width"?a.offsetWidth:a.offsetHeight;if(d==="border")return e;c.each(b==="width"?Pa:Qa,function(){d||(e-=parseFloat(c.css(a,"padding"+this))||0);if(d==="margin")e+=parseFloat(c.css(a, "margin"+this))||0;else e-=parseFloat(c.css(a,"border"+this+"Width"))||0});return e}function da(a,b,d,e){if(c.isArray(b)&&b.length)c.each(b,function(f,h){d||Ra.test(a)?e(a,h):da(a+"["+(typeof h==="object"||c.isArray(h)?f:"")+"]",h,d,e)});else if(!d&&b!=null&&typeof b==="object")c.isEmptyObject(b)?e(a,""):c.each(b,function(f,h){da(a+"["+f+"]",h,d,e)});else e(a,b)}function S(a,b){var d={};c.each(pa.concat.apply([],pa.slice(0,b)),function(){d[this]=a});return d}function qa(a){if(!ea[a]){var b=c("<"+ a+">").appendTo("body"),d=b.css("display");b.remove();if(d==="none"||d==="")d="block";ea[a]=d}return ea[a]}function fa(a){return c.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:false}var t=E.document,c=function(){function a(){if(!b.isReady){try{t.documentElement.doScroll("left")}catch(j){setTimeout(a,1);return}b.ready()}}var b=function(j,s){return new b.fn.init(j,s)},d=E.jQuery,e=E.$,f,h=/^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/,l=/\S/,k=/^\s+/,o=/\s+$/,x=/\W/,r=/\d/,A=/^<(\w+)\s*\/?>(?:<\/\1>)?$/, C=/^[\],:{}\s]*$/,J=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,w=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,I=/(?:^|:|,)(?:\s*\[)+/g,L=/(webkit)[ \/]([\w.]+)/,g=/(opera)(?:.*version)?[ \/]([\w.]+)/,i=/(msie) ([\w.]+)/,n=/(mozilla)(?:.*? rv:([\w.]+))?/,m=navigator.userAgent,p=false,q=[],u,y=Object.prototype.toString,F=Object.prototype.hasOwnProperty,M=Array.prototype.push,N=Array.prototype.slice,O=String.prototype.trim,D=Array.prototype.indexOf,R={};b.fn=b.prototype={init:function(j, s){var v,z,H;if(!j)return this;if(j.nodeType){this.context=this[0]=j;this.length=1;return this}if(j==="body"&&!s&&t.body){this.context=t;this[0]=t.body;this.selector="body";this.length=1;return this}if(typeof j==="string")if((v=h.exec(j))&&(v[1]||!s))if(v[1]){H=s?s.ownerDocument||s:t;if(z=A.exec(j))if(b.isPlainObject(s)){j=[t.createElement(z[1])];b.fn.attr.call(j,s,true)}else j=[H.createElement(z[1])];else{z=b.buildFragment([v[1]],[H]);j=(z.cacheable?z.fragment.cloneNode(true):z.fragment).childNodes}return b.merge(this, j)}else{if((z=t.getElementById(v[2]))&&z.parentNode){if(z.id!==v[2])return f.find(j);this.length=1;this[0]=z}this.context=t;this.selector=j;return this}else if(!s&&!x.test(j)){this.selector=j;this.context=t;j=t.getElementsByTagName(j);return b.merge(this,j)}else return!s||s.jquery?(s||f).find(j):b(s).find(j);else if(b.isFunction(j))return f.ready(j);if(j.selector!==B){this.selector=j.selector;this.context=j.context}return b.makeArray(j,this)},selector:"",jquery:"1.4.4",length:0,size:function(){return this.length}, toArray:function(){return N.call(this,0)},get:function(j){return j==null?this.toArray():j<0?this.slice(j)[0]:this[j]},pushStack:function(j,s,v){var z=b();b.isArray(j)?M.apply(z,j):b.merge(z,j);z.prevObject=this;z.context=this.context;if(s==="find")z.selector=this.selector+(this.selector?" ":"")+v;else if(s)z.selector=this.selector+"."+s+"("+v+")";return z},each:function(j,s){return b.each(this,j,s)},ready:function(j){b.bindReady();if(b.isReady)j.call(t,b);else q&&q.push(j);return this},eq:function(j){return j=== -1?this.slice(j):this.slice(j,+j+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(N.apply(this,arguments),"slice",N.call(arguments).join(","))},map:function(j){return this.pushStack(b.map(this,function(s,v){return j.call(s,v,s)}))},end:function(){return this.prevObject||b(null)},push:M,sort:[].sort,splice:[].splice};b.fn.init.prototype=b.fn;b.extend=b.fn.extend=function(){var j,s,v,z,H,G=arguments[0]||{},K=1,Q=arguments.length,ga=false; if(typeof G==="boolean"){ga=G;G=arguments[1]||{};K=2}if(typeof G!=="object"&&!b.isFunction(G))G={};if(Q===K){G=this;--K}for(;K<Q;K++)if((j=arguments[K])!=null)for(s in j){v=G[s];z=j[s];if(G!==z)if(ga&&z&&(b.isPlainObject(z)||(H=b.isArray(z)))){if(H){H=false;v=v&&b.isArray(v)?v:[]}else v=v&&b.isPlainObject(v)?v:{};G[s]=b.extend(ga,v,z)}else if(z!==B)G[s]=z}return G};b.extend({noConflict:function(j){E.$=e;if(j)E.jQuery=d;return b},isReady:false,readyWait:1,ready:function(j){j===true&&b.readyWait--; if(!b.readyWait||j!==true&&!b.isReady){if(!t.body)return setTimeout(b.ready,1);b.isReady=true;if(!(j!==true&&--b.readyWait>0))if(q){var s=0,v=q;for(q=null;j=v[s++];)j.call(t,b);b.fn.trigger&&b(t).trigger("ready").unbind("ready")}}},bindReady:function(){if(!p){p=true;if(t.readyState==="complete")return setTimeout(b.ready,1);if(t.addEventListener){t.addEventListener("DOMContentLoaded",u,false);E.addEventListener("load",b.ready,false)}else if(t.attachEvent){t.attachEvent("onreadystatechange",u);E.attachEvent("onload", b.ready);var j=false;try{j=E.frameElement==null}catch(s){}t.documentElement.doScroll&&j&&a()}}},isFunction:function(j){return b.type(j)==="function"},isArray:Array.isArray||function(j){return b.type(j)==="array"},isWindow:function(j){return j&&typeof j==="object"&&"setInterval"in j},isNaN:function(j){return j==null||!r.test(j)||isNaN(j)},type:function(j){return j==null?String(j):R[y.call(j)]||"object"},isPlainObject:function(j){if(!j||b.type(j)!=="object"||j.nodeType||b.isWindow(j))return false;if(j.constructor&& !F.call(j,"constructor")&&!F.call(j.constructor.prototype,"isPrototypeOf"))return false;for(var s in j);return s===B||F.call(j,s)},isEmptyObject:function(j){for(var s in j)return false;return true},error:function(j){throw j;},parseJSON:function(j){if(typeof j!=="string"||!j)return null;j=b.trim(j);if(C.test(j.replace(J,"@").replace(w,"]").replace(I,"")))return E.JSON&&E.JSON.parse?E.JSON.parse(j):(new Function("return "+j))();else b.error("Invalid JSON: "+j)},noop:function(){},globalEval:function(j){if(j&& l.test(j)){var s=t.getElementsByTagName("head")[0]||t.documentElement,v=t.createElement("script");v.type="text/javascript";if(b.support.scriptEval)v.appendChild(t.createTextNode(j));else v.text=j;s.insertBefore(v,s.firstChild);s.removeChild(v)}},nodeName:function(j,s){return j.nodeName&&j.nodeName.toUpperCase()===s.toUpperCase()},each:function(j,s,v){var z,H=0,G=j.length,K=G===B||b.isFunction(j);if(v)if(K)for(z in j){if(s.apply(j[z],v)===false)break}else for(;H<G;){if(s.apply(j[H++],v)===false)break}else if(K)for(z in j){if(s.call(j[z], z,j[z])===false)break}else for(v=j[0];H<G&&s.call(v,H,v)!==false;v=j[++H]);return j},trim:O?function(j){return j==null?"":O.call(j)}:function(j){return j==null?"":j.toString().replace(k,"").replace(o,"")},makeArray:function(j,s){var v=s||[];if(j!=null){var z=b.type(j);j.length==null||z==="string"||z==="function"||z==="regexp"||b.isWindow(j)?M.call(v,j):b.merge(v,j)}return v},inArray:function(j,s){if(s.indexOf)return s.indexOf(j);for(var v=0,z=s.length;v<z;v++)if(s[v]===j)return v;return-1},merge:function(j, s){var v=j.length,z=0;if(typeof s.length==="number")for(var H=s.length;z<H;z++)j[v++]=s[z];else for(;s[z]!==B;)j[v++]=s[z++];j.length=v;return j},grep:function(j,s,v){var z=[],H;v=!!v;for(var G=0,K=j.length;G<K;G++){H=!!s(j[G],G);v!==H&&z.push(j[G])}return z},map:function(j,s,v){for(var z=[],H,G=0,K=j.length;G<K;G++){H=s(j[G],G,v);if(H!=null)z[z.length]=H}return z.concat.apply([],z)},guid:1,proxy:function(j,s,v){if(arguments.length===2)if(typeof s==="string"){v=j;j=v[s];s=B}else if(s&&!b.isFunction(s)){v= s;s=B}if(!s&&j)s=function(){return j.apply(v||this,arguments)};if(j)s.guid=j.guid=j.guid||s.guid||b.guid++;return s},access:function(j,s,v,z,H,G){var K=j.length;if(typeof s==="object"){for(var Q in s)b.access(j,Q,s[Q],z,H,v);return j}if(v!==B){z=!G&&z&&b.isFunction(v);for(Q=0;Q<K;Q++)H(j[Q],s,z?v.call(j[Q],Q,H(j[Q],s)):v,G);return j}return K?H(j[0],s):B},now:function(){return(new Date).getTime()},uaMatch:function(j){j=j.toLowerCase();j=L.exec(j)||g.exec(j)||i.exec(j)||j.indexOf("compatible")<0&&n.exec(j)|| [];return{browser:j[1]||"",version:j[2]||"0"}},browser:{}});b.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(j,s){R["[object "+s+"]"]=s.toLowerCase()});m=b.uaMatch(m);if(m.browser){b.browser[m.browser]=true;b.browser.version=m.version}if(b.browser.webkit)b.browser.safari=true;if(D)b.inArray=function(j,s){return D.call(s,j)};if(!/\s/.test("\u00a0")){k=/^[\s\xA0]+/;o=/[\s\xA0]+$/}f=b(t);if(t.addEventListener)u=function(){t.removeEventListener("DOMContentLoaded",u, false);b.ready()};else if(t.attachEvent)u=function(){if(t.readyState==="complete"){t.detachEvent("onreadystatechange",u);b.ready()}};return E.jQuery=E.$=b}();(function(){c.support={};var a=t.documentElement,b=t.createElement("script"),d=t.createElement("div"),e="script"+c.now();d.style.display="none";d.innerHTML=" <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";var f=d.getElementsByTagName("*"),h=d.getElementsByTagName("a")[0],l=t.createElement("select"), k=l.appendChild(t.createElement("option"));if(!(!f||!f.length||!h)){c.support={leadingWhitespace:d.firstChild.nodeType===3,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/red/.test(h.getAttribute("style")),hrefNormalized:h.getAttribute("href")==="/a",opacity:/^0.55$/.test(h.style.opacity),cssFloat:!!h.style.cssFloat,checkOn:d.getElementsByTagName("input")[0].value==="on",optSelected:k.selected,deleteExpando:true,optDisabled:false,checkClone:false, scriptEval:false,noCloneEvent:true,boxModel:null,inlineBlockNeedsLayout:false,shrinkWrapBlocks:false,reliableHiddenOffsets:true};l.disabled=true;c.support.optDisabled=!k.disabled;b.type="text/javascript";try{b.appendChild(t.createTextNode("window."+e+"=1;"))}catch(o){}a.insertBefore(b,a.firstChild);if(E[e]){c.support.scriptEval=true;delete E[e]}try{delete b.test}catch(x){c.support.deleteExpando=false}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function r(){c.support.noCloneEvent= false;d.detachEvent("onclick",r)});d.cloneNode(true).fireEvent("onclick")}d=t.createElement("div");d.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";a=t.createDocumentFragment();a.appendChild(d.firstChild);c.support.checkClone=a.cloneNode(true).cloneNode(true).lastChild.checked;c(function(){var r=t.createElement("div");r.style.width=r.style.paddingLeft="1px";t.body.appendChild(r);c.boxModel=c.support.boxModel=r.offsetWidth===2;if("zoom"in r.style){r.style.display="inline";r.style.zoom= 1;c.support.inlineBlockNeedsLayout=r.offsetWidth===2;r.style.display="";r.innerHTML="<div style='width:4px;'></div>";c.support.shrinkWrapBlocks=r.offsetWidth!==2}r.innerHTML="<table><tr><td style='padding:0;display:none'></td><td>t</td></tr></table>";var A=r.getElementsByTagName("td");c.support.reliableHiddenOffsets=A[0].offsetHeight===0;A[0].style.display="";A[1].style.display="none";c.support.reliableHiddenOffsets=c.support.reliableHiddenOffsets&&A[0].offsetHeight===0;r.innerHTML="";t.body.removeChild(r).style.display= "none"});a=function(r){var A=t.createElement("div");r="on"+r;var C=r in A;if(!C){A.setAttribute(r,"return;");C=typeof A[r]==="function"}return C};c.support.submitBubbles=a("submit");c.support.changeBubbles=a("change");a=b=d=f=h=null}})();var ra={},Ja=/^(?:\{.*\}|\[.*\])$/;c.extend({cache:{},uuid:0,expando:"jQuery"+c.now(),noData:{embed:true,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:true},data:function(a,b,d){if(c.acceptData(a)){a=a==E?ra:a;var e=a.nodeType,f=e?a[c.expando]:null,h= c.cache;if(!(e&&!f&&typeof b==="string"&&d===B)){if(e)f||(a[c.expando]=f=++c.uuid);else h=a;if(typeof b==="object")if(e)h[f]=c.extend(h[f],b);else c.extend(h,b);else if(e&&!h[f])h[f]={};a=e?h[f]:h;if(d!==B)a[b]=d;return typeof b==="string"?a[b]:a}}},removeData:function(a,b){if(c.acceptData(a)){a=a==E?ra:a;var d=a.nodeType,e=d?a[c.expando]:a,f=c.cache,h=d?f[e]:e;if(b){if(h){delete h[b];d&&c.isEmptyObject(h)&&c.removeData(a)}}else if(d&&c.support.deleteExpando)delete a[c.expando];else if(a.removeAttribute)a.removeAttribute(c.expando); else if(d)delete f[e];else for(var l in a)delete a[l]}},acceptData:function(a){if(a.nodeName){var b=c.noData[a.nodeName.toLowerCase()];if(b)return!(b===true||a.getAttribute("classid")!==b)}return true}});c.fn.extend({data:function(a,b){var d=null;if(typeof a==="undefined"){if(this.length){var e=this[0].attributes,f;d=c.data(this[0]);for(var h=0,l=e.length;h<l;h++){f=e[h].name;if(f.indexOf("data-")===0){f=f.substr(5);ka(this[0],f,d[f])}}}return d}else if(typeof a==="object")return this.each(function(){c.data(this, a)});var k=a.split(".");k[1]=k[1]?"."+k[1]:"";if(b===B){d=this.triggerHandler("getData"+k[1]+"!",[k[0]]);if(d===B&&this.length){d=c.data(this[0],a);d=ka(this[0],a,d)}return d===B&&k[1]?this.data(k[0]):d}else return this.each(function(){var o=c(this),x=[k[0],b];o.triggerHandler("setData"+k[1]+"!",x);c.data(this,a,b);o.triggerHandler("changeData"+k[1]+"!",x)})},removeData:function(a){return this.each(function(){c.removeData(this,a)})}});c.extend({queue:function(a,b,d){if(a){b=(b||"fx")+"queue";var e= c.data(a,b);if(!d)return e||[];if(!e||c.isArray(d))e=c.data(a,b,c.makeArray(d));else e.push(d);return e}},dequeue:function(a,b){b=b||"fx";var d=c.queue(a,b),e=d.shift();if(e==="inprogress")e=d.shift();if(e){b==="fx"&&d.unshift("inprogress");e.call(a,function(){c.dequeue(a,b)})}}});c.fn.extend({queue:function(a,b){if(typeof a!=="string"){b=a;a="fx"}if(b===B)return c.queue(this[0],a);return this.each(function(){var d=c.queue(this,a,b);a==="fx"&&d[0]!=="inprogress"&&c.dequeue(this,a)})},dequeue:function(a){return this.each(function(){c.dequeue(this, a)})},delay:function(a,b){a=c.fx?c.fx.speeds[a]||a:a;b=b||"fx";return this.queue(b,function(){var d=this;setTimeout(function(){c.dequeue(d,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var sa=/[\n\t]/g,ha=/\s+/,Sa=/\r/g,Ta=/^(?:href|src|style)$/,Ua=/^(?:button|input)$/i,Va=/^(?:button|input|object|select|textarea)$/i,Wa=/^a(?:rea)?$/i,ta=/^(?:radio|checkbox)$/i;c.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan", colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};c.fn.extend({attr:function(a,b){return c.access(this,a,b,true,c.attr)},removeAttr:function(a){return this.each(function(){c.attr(this,a,"");this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(c.isFunction(a))return this.each(function(x){var r=c(this);r.addClass(a.call(this,x,r.attr("class")))});if(a&&typeof a==="string")for(var b=(a||"").split(ha),d=0,e=this.length;d<e;d++){var f=this[d];if(f.nodeType=== 1)if(f.className){for(var h=" "+f.className+" ",l=f.className,k=0,o=b.length;k<o;k++)if(h.indexOf(" "+b[k]+" ")<0)l+=" "+b[k];f.className=c.trim(l)}else f.className=a}return this},removeClass:function(a){if(c.isFunction(a))return this.each(function(o){var x=c(this);x.removeClass(a.call(this,o,x.attr("class")))});if(a&&typeof a==="string"||a===B)for(var b=(a||"").split(ha),d=0,e=this.length;d<e;d++){var f=this[d];if(f.nodeType===1&&f.className)if(a){for(var h=(" "+f.className+" ").replace(sa," "), l=0,k=b.length;l<k;l++)h=h.replace(" "+b[l]+" "," ");f.className=c.trim(h)}else f.className=""}return this},toggleClass:function(a,b){var d=typeof a,e=typeof b==="boolean";if(c.isFunction(a))return this.each(function(f){var h=c(this);h.toggleClass(a.call(this,f,h.attr("class"),b),b)});return this.each(function(){if(d==="string")for(var f,h=0,l=c(this),k=b,o=a.split(ha);f=o[h++];){k=e?k:!l.hasClass(f);l[k?"addClass":"removeClass"](f)}else if(d==="undefined"||d==="boolean"){this.className&&c.data(this, "__className__",this.className);this.className=this.className||a===false?"":c.data(this,"__className__")||""}})},hasClass:function(a){a=" "+a+" ";for(var b=0,d=this.length;b<d;b++)if((" "+this[b].className+" ").replace(sa," ").indexOf(a)>-1)return true;return false},val:function(a){if(!arguments.length){var b=this[0];if(b){if(c.nodeName(b,"option")){var d=b.attributes.value;return!d||d.specified?b.value:b.text}if(c.nodeName(b,"select")){var e=b.selectedIndex;d=[];var f=b.options;b=b.type==="select-one"; if(e<0)return null;var h=b?e:0;for(e=b?e+1:f.length;h<e;h++){var l=f[h];if(l.selected&&(c.support.optDisabled?!l.disabled:l.getAttribute("disabled")===null)&&(!l.parentNode.disabled||!c.nodeName(l.parentNode,"optgroup"))){a=c(l).val();if(b)return a;d.push(a)}}return d}if(ta.test(b.type)&&!c.support.checkOn)return b.getAttribute("value")===null?"on":b.value;return(b.value||"").replace(Sa,"")}return B}var k=c.isFunction(a);return this.each(function(o){var x=c(this),r=a;if(this.nodeType===1){if(k)r= a.call(this,o,x.val());if(r==null)r="";else if(typeof r==="number")r+="";else if(c.isArray(r))r=c.map(r,function(C){return C==null?"":C+""});if(c.isArray(r)&&ta.test(this.type))this.checked=c.inArray(x.val(),r)>=0;else if(c.nodeName(this,"select")){var A=c.makeArray(r);c("option",this).each(function(){this.selected=c.inArray(c(this).val(),A)>=0});if(!A.length)this.selectedIndex=-1}else this.value=r}})}});c.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true}, attr:function(a,b,d,e){if(!a||a.nodeType===3||a.nodeType===8)return B;if(e&&b in c.attrFn)return c(a)[b](d);e=a.nodeType!==1||!c.isXMLDoc(a);var f=d!==B;b=e&&c.props[b]||b;var h=Ta.test(b);if((b in a||a[b]!==B)&&e&&!h){if(f){b==="type"&&Ua.test(a.nodeName)&&a.parentNode&&c.error("type property can't be changed");if(d===null)a.nodeType===1&&a.removeAttribute(b);else a[b]=d}if(c.nodeName(a,"form")&&a.getAttributeNode(b))return a.getAttributeNode(b).nodeValue;if(b==="tabIndex")return(b=a.getAttributeNode("tabIndex"))&& b.specified?b.value:Va.test(a.nodeName)||Wa.test(a.nodeName)&&a.href?0:B;return a[b]}if(!c.support.style&&e&&b==="style"){if(f)a.style.cssText=""+d;return a.style.cssText}f&&a.setAttribute(b,""+d);if(!a.attributes[b]&&a.hasAttribute&&!a.hasAttribute(b))return B;a=!c.support.hrefNormalized&&e&&h?a.getAttribute(b,2):a.getAttribute(b);return a===null?B:a}});var X=/\.(.*)$/,ia=/^(?:textarea|input|select)$/i,La=/\./g,Ma=/ /g,Xa=/[^\w\s.|`]/g,Ya=function(a){return a.replace(Xa,"\\$&")},ua={focusin:0,focusout:0}; c.event={add:function(a,b,d,e){if(!(a.nodeType===3||a.nodeType===8)){if(c.isWindow(a)&&a!==E&&!a.frameElement)a=E;if(d===false)d=U;else if(!d)return;var f,h;if(d.handler){f=d;d=f.handler}if(!d.guid)d.guid=c.guid++;if(h=c.data(a)){var l=a.nodeType?"events":"__events__",k=h[l],o=h.handle;if(typeof k==="function"){o=k.handle;k=k.events}else if(!k){a.nodeType||(h[l]=h=function(){});h.events=k={}}if(!o)h.handle=o=function(){return typeof c!=="undefined"&&!c.event.triggered?c.event.handle.apply(o.elem, arguments):B};o.elem=a;b=b.split(" ");for(var x=0,r;l=b[x++];){h=f?c.extend({},f):{handler:d,data:e};if(l.indexOf(".")>-1){r=l.split(".");l=r.shift();h.namespace=r.slice(0).sort().join(".")}else{r=[];h.namespace=""}h.type=l;if(!h.guid)h.guid=d.guid;var A=k[l],C=c.event.special[l]||{};if(!A){A=k[l]=[];if(!C.setup||C.setup.call(a,e,r,o)===false)if(a.addEventListener)a.addEventListener(l,o,false);else a.attachEvent&&a.attachEvent("on"+l,o)}if(C.add){C.add.call(a,h);if(!h.handler.guid)h.handler.guid= d.guid}A.push(h);c.event.global[l]=true}a=null}}},global:{},remove:function(a,b,d,e){if(!(a.nodeType===3||a.nodeType===8)){if(d===false)d=U;var f,h,l=0,k,o,x,r,A,C,J=a.nodeType?"events":"__events__",w=c.data(a),I=w&&w[J];if(w&&I){if(typeof I==="function"){w=I;I=I.events}if(b&&b.type){d=b.handler;b=b.type}if(!b||typeof b==="string"&&b.charAt(0)==="."){b=b||"";for(f in I)c.event.remove(a,f+b)}else{for(b=b.split(" ");f=b[l++];){r=f;k=f.indexOf(".")<0;o=[];if(!k){o=f.split(".");f=o.shift();x=RegExp("(^|\\.)"+ c.map(o.slice(0).sort(),Ya).join("\\.(?:.*\\.)?")+"(\\.|$)")}if(A=I[f])if(d){r=c.event.special[f]||{};for(h=e||0;h<A.length;h++){C=A[h];if(d.guid===C.guid){if(k||x.test(C.namespace)){e==null&&A.splice(h--,1);r.remove&&r.remove.call(a,C)}if(e!=null)break}}if(A.length===0||e!=null&&A.length===1){if(!r.teardown||r.teardown.call(a,o)===false)c.removeEvent(a,f,w.handle);delete I[f]}}else for(h=0;h<A.length;h++){C=A[h];if(k||x.test(C.namespace)){c.event.remove(a,r,C.handler,h);A.splice(h--,1)}}}if(c.isEmptyObject(I)){if(b= w.handle)b.elem=null;delete w.events;delete w.handle;if(typeof w==="function")c.removeData(a,J);else c.isEmptyObject(w)&&c.removeData(a)}}}}},trigger:function(a,b,d,e){var f=a.type||a;if(!e){a=typeof a==="object"?a[c.expando]?a:c.extend(c.Event(f),a):c.Event(f);if(f.indexOf("!")>=0){a.type=f=f.slice(0,-1);a.exclusive=true}if(!d){a.stopPropagation();c.event.global[f]&&c.each(c.cache,function(){this.events&&this.events[f]&&c.event.trigger(a,b,this.handle.elem)})}if(!d||d.nodeType===3||d.nodeType=== 8)return B;a.result=B;a.target=d;b=c.makeArray(b);b.unshift(a)}a.currentTarget=d;(e=d.nodeType?c.data(d,"handle"):(c.data(d,"__events__")||{}).handle)&&e.apply(d,b);e=d.parentNode||d.ownerDocument;try{if(!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()]))if(d["on"+f]&&d["on"+f].apply(d,b)===false){a.result=false;a.preventDefault()}}catch(h){}if(!a.isPropagationStopped()&&e)c.event.trigger(a,b,e,true);else if(!a.isDefaultPrevented()){var l;e=a.target;var k=f.replace(X,""),o=c.nodeName(e,"a")&&k=== "click",x=c.event.special[k]||{};if((!x._default||x._default.call(d,a)===false)&&!o&&!(e&&e.nodeName&&c.noData[e.nodeName.toLowerCase()])){try{if(e[k]){if(l=e["on"+k])e["on"+k]=null;c.event.triggered=true;e[k]()}}catch(r){}if(l)e["on"+k]=l;c.event.triggered=false}}},handle:function(a){var b,d,e,f;d=[];var h=c.makeArray(arguments);a=h[0]=c.event.fix(a||E.event);a.currentTarget=this;b=a.type.indexOf(".")<0&&!a.exclusive;if(!b){e=a.type.split(".");a.type=e.shift();d=e.slice(0).sort();e=RegExp("(^|\\.)"+ d.join("\\.(?:.*\\.)?")+"(\\.|$)")}a.namespace=a.namespace||d.join(".");f=c.data(this,this.nodeType?"events":"__events__");if(typeof f==="function")f=f.events;d=(f||{})[a.type];if(f&&d){d=d.slice(0);f=0;for(var l=d.length;f<l;f++){var k=d[f];if(b||e.test(k.namespace)){a.handler=k.handler;a.data=k.data;a.handleObj=k;k=k.handler.apply(this,h);if(k!==B){a.result=k;if(k===false){a.preventDefault();a.stopPropagation()}}if(a.isImmediatePropagationStopped())break}}}return a.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "), fix:function(a){if(a[c.expando])return a;var b=a;a=c.Event(b);for(var d=this.props.length,e;d;){e=this.props[--d];a[e]=b[e]}if(!a.target)a.target=a.srcElement||t;if(a.target.nodeType===3)a.target=a.target.parentNode;if(!a.relatedTarget&&a.fromElement)a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement;if(a.pageX==null&&a.clientX!=null){b=t.documentElement;d=t.body;a.pageX=a.clientX+(b&&b.scrollLeft||d&&d.scrollLeft||0)-(b&&b.clientLeft||d&&d.clientLeft||0);a.pageY=a.clientY+(b&&b.scrollTop|| d&&d.scrollTop||0)-(b&&b.clientTop||d&&d.clientTop||0)}if(a.which==null&&(a.charCode!=null||a.keyCode!=null))a.which=a.charCode!=null?a.charCode:a.keyCode;if(!a.metaKey&&a.ctrlKey)a.metaKey=a.ctrlKey;if(!a.which&&a.button!==B)a.which=a.button&1?1:a.button&2?3:a.button&4?2:0;return a},guid:1E8,proxy:c.proxy,special:{ready:{setup:c.bindReady,teardown:c.noop},live:{add:function(a){c.event.add(this,Y(a.origType,a.selector),c.extend({},a,{handler:Ka,guid:a.handler.guid}))},remove:function(a){c.event.remove(this, Y(a.origType,a.selector),a)}},beforeunload:{setup:function(a,b,d){if(c.isWindow(this))this.onbeforeunload=d},teardown:function(a,b){if(this.onbeforeunload===b)this.onbeforeunload=null}}}};c.removeEvent=t.removeEventListener?function(a,b,d){a.removeEventListener&&a.removeEventListener(b,d,false)}:function(a,b,d){a.detachEvent&&a.detachEvent("on"+b,d)};c.Event=function(a){if(!this.preventDefault)return new c.Event(a);if(a&&a.type){this.originalEvent=a;this.type=a.type}else this.type=a;this.timeStamp= c.now();this[c.expando]=true};c.Event.prototype={preventDefault:function(){this.isDefaultPrevented=ca;var a=this.originalEvent;if(a)if(a.preventDefault)a.preventDefault();else a.returnValue=false},stopPropagation:function(){this.isPropagationStopped=ca;var a=this.originalEvent;if(a){a.stopPropagation&&a.stopPropagation();a.cancelBubble=true}},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=ca;this.stopPropagation()},isDefaultPrevented:U,isPropagationStopped:U,isImmediatePropagationStopped:U}; var va=function(a){var b=a.relatedTarget;try{for(;b&&b!==this;)b=b.parentNode;if(b!==this){a.type=a.data;c.event.handle.apply(this,arguments)}}catch(d){}},wa=function(a){a.type=a.data;c.event.handle.apply(this,arguments)};c.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){c.event.special[a]={setup:function(d){c.event.add(this,b,d&&d.selector?wa:va,a)},teardown:function(d){c.event.remove(this,b,d&&d.selector?wa:va)}}});if(!c.support.submitBubbles)c.event.special.submit={setup:function(){if(this.nodeName.toLowerCase()!== "form"){c.event.add(this,"click.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="submit"||d==="image")&&c(b).closest("form").length){a.liveFired=B;return la("submit",this,arguments)}});c.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="text"||d==="password")&&c(b).closest("form").length&&a.keyCode===13){a.liveFired=B;return la("submit",this,arguments)}})}else return false},teardown:function(){c.event.remove(this,".specialSubmit")}};if(!c.support.changeBubbles){var V, xa=function(a){var b=a.type,d=a.value;if(b==="radio"||b==="checkbox")d=a.checked;else if(b==="select-multiple")d=a.selectedIndex>-1?c.map(a.options,function(e){return e.selected}).join("-"):"";else if(a.nodeName.toLowerCase()==="select")d=a.selectedIndex;return d},Z=function(a,b){var d=a.target,e,f;if(!(!ia.test(d.nodeName)||d.readOnly)){e=c.data(d,"_change_data");f=xa(d);if(a.type!=="focusout"||d.type!=="radio")c.data(d,"_change_data",f);if(!(e===B||f===e))if(e!=null||f){a.type="change";a.liveFired= B;return c.event.trigger(a,b,d)}}};c.event.special.change={filters:{focusout:Z,beforedeactivate:Z,click:function(a){var b=a.target,d=b.type;if(d==="radio"||d==="checkbox"||b.nodeName.toLowerCase()==="select")return Z.call(this,a)},keydown:function(a){var b=a.target,d=b.type;if(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(d==="checkbox"||d==="radio")||d==="select-multiple")return Z.call(this,a)},beforeactivate:function(a){a=a.target;c.data(a,"_change_data",xa(a))}},setup:function(){if(this.type=== "file")return false;for(var a in V)c.event.add(this,a+".specialChange",V[a]);return ia.test(this.nodeName)},teardown:function(){c.event.remove(this,".specialChange");return ia.test(this.nodeName)}};V=c.event.special.change.filters;V.focus=V.beforeactivate}t.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(e){e=c.event.fix(e);e.type=b;return c.event.trigger(e,null,e.target)}c.event.special[b]={setup:function(){ua[b]++===0&&t.addEventListener(a,d,true)},teardown:function(){--ua[b]=== 0&&t.removeEventListener(a,d,true)}}});c.each(["bind","one"],function(a,b){c.fn[b]=function(d,e,f){if(typeof d==="object"){for(var h in d)this[b](h,e,d[h],f);return this}if(c.isFunction(e)||e===false){f=e;e=B}var l=b==="one"?c.proxy(f,function(o){c(this).unbind(o,l);return f.apply(this,arguments)}):f;if(d==="unload"&&b!=="one")this.one(d,e,f);else{h=0;for(var k=this.length;h<k;h++)c.event.add(this[h],d,l,e)}return this}});c.fn.extend({unbind:function(a,b){if(typeof a==="object"&&!a.preventDefault)for(var d in a)this.unbind(d, a[d]);else{d=0;for(var e=this.length;d<e;d++)c.event.remove(this[d],a,b)}return this},delegate:function(a,b,d,e){return this.live(b,d,e,a)},undelegate:function(a,b,d){return arguments.length===0?this.unbind("live"):this.die(b,null,d,a)},trigger:function(a,b){return this.each(function(){c.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){var d=c.Event(a);d.preventDefault();d.stopPropagation();c.event.trigger(d,b,this[0]);return d.result}},toggle:function(a){for(var b=arguments,d= 1;d<b.length;)c.proxy(a,b[d++]);return this.click(c.proxy(a,function(e){var f=(c.data(this,"lastToggle"+a.guid)||0)%d;c.data(this,"lastToggle"+a.guid,f+1);e.preventDefault();return b[f].apply(this,arguments)||false}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var ya={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};c.each(["live","die"],function(a,b){c.fn[b]=function(d,e,f,h){var l,k=0,o,x,r=h||this.selector;h=h?this:c(this.context);if(typeof d=== "object"&&!d.preventDefault){for(l in d)h[b](l,e,d[l],r);return this}if(c.isFunction(e)){f=e;e=B}for(d=(d||"").split(" ");(l=d[k++])!=null;){o=X.exec(l);x="";if(o){x=o[0];l=l.replace(X,"")}if(l==="hover")d.push("mouseenter"+x,"mouseleave"+x);else{o=l;if(l==="focus"||l==="blur"){d.push(ya[l]+x);l+=x}else l=(ya[l]||l)+x;if(b==="live"){x=0;for(var A=h.length;x<A;x++)c.event.add(h[x],"live."+Y(l,r),{data:e,selector:r,handler:f,origType:l,origHandler:f,preType:o})}else h.unbind("live."+Y(l,r),f)}}return this}}); c.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error".split(" "),function(a,b){c.fn[b]=function(d,e){if(e==null){e=d;d=null}return arguments.length>0?this.bind(b,d,e):this.trigger(b)};if(c.attrFn)c.attrFn[b]=true});E.attachEvent&&!E.addEventListener&&c(E).bind("unload",function(){for(var a in c.cache)if(c.cache[a].handle)try{c.event.remove(c.cache[a].handle.elem)}catch(b){}}); (function(){function a(g,i,n,m,p,q){p=0;for(var u=m.length;p<u;p++){var y=m[p];if(y){var F=false;for(y=y[g];y;){if(y.sizcache===n){F=m[y.sizset];break}if(y.nodeType===1&&!q){y.sizcache=n;y.sizset=p}if(y.nodeName.toLowerCase()===i){F=y;break}y=y[g]}m[p]=F}}}function b(g,i,n,m,p,q){p=0;for(var u=m.length;p<u;p++){var y=m[p];if(y){var F=false;for(y=y[g];y;){if(y.sizcache===n){F=m[y.sizset];break}if(y.nodeType===1){if(!q){y.sizcache=n;y.sizset=p}if(typeof i!=="string"){if(y===i){F=true;break}}else if(k.filter(i, [y]).length>0){F=y;break}}y=y[g]}m[p]=F}}}var d=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,e=0,f=Object.prototype.toString,h=false,l=true;[0,0].sort(function(){l=false;return 0});var k=function(g,i,n,m){n=n||[];var p=i=i||t;if(i.nodeType!==1&&i.nodeType!==9)return[];if(!g||typeof g!=="string")return n;var q,u,y,F,M,N=true,O=k.isXML(i),D=[],R=g;do{d.exec("");if(q=d.exec(R)){R=q[3];D.push(q[1]);if(q[2]){F=q[3]; break}}}while(q);if(D.length>1&&x.exec(g))if(D.length===2&&o.relative[D[0]])u=L(D[0]+D[1],i);else for(u=o.relative[D[0]]?[i]:k(D.shift(),i);D.length;){g=D.shift();if(o.relative[g])g+=D.shift();u=L(g,u)}else{if(!m&&D.length>1&&i.nodeType===9&&!O&&o.match.ID.test(D[0])&&!o.match.ID.test(D[D.length-1])){q=k.find(D.shift(),i,O);i=q.expr?k.filter(q.expr,q.set)[0]:q.set[0]}if(i){q=m?{expr:D.pop(),set:C(m)}:k.find(D.pop(),D.length===1&&(D[0]==="~"||D[0]==="+")&&i.parentNode?i.parentNode:i,O);u=q.expr?k.filter(q.expr, q.set):q.set;if(D.length>0)y=C(u);else N=false;for(;D.length;){q=M=D.pop();if(o.relative[M])q=D.pop();else M="";if(q==null)q=i;o.relative[M](y,q,O)}}else y=[]}y||(y=u);y||k.error(M||g);if(f.call(y)==="[object Array]")if(N)if(i&&i.nodeType===1)for(g=0;y[g]!=null;g++){if(y[g]&&(y[g]===true||y[g].nodeType===1&&k.contains(i,y[g])))n.push(u[g])}else for(g=0;y[g]!=null;g++)y[g]&&y[g].nodeType===1&&n.push(u[g]);else n.push.apply(n,y);else C(y,n);if(F){k(F,p,n,m);k.uniqueSort(n)}return n};k.uniqueSort=function(g){if(w){h= l;g.sort(w);if(h)for(var i=1;i<g.length;i++)g[i]===g[i-1]&&g.splice(i--,1)}return g};k.matches=function(g,i){return k(g,null,null,i)};k.matchesSelector=function(g,i){return k(i,null,null,[g]).length>0};k.find=function(g,i,n){var m;if(!g)return[];for(var p=0,q=o.order.length;p<q;p++){var u,y=o.order[p];if(u=o.leftMatch[y].exec(g)){var F=u[1];u.splice(1,1);if(F.substr(F.length-1)!=="\\"){u[1]=(u[1]||"").replace(/\\/g,"");m=o.find[y](u,i,n);if(m!=null){g=g.replace(o.match[y],"");break}}}}m||(m=i.getElementsByTagName("*")); return{set:m,expr:g}};k.filter=function(g,i,n,m){for(var p,q,u=g,y=[],F=i,M=i&&i[0]&&k.isXML(i[0]);g&&i.length;){for(var N in o.filter)if((p=o.leftMatch[N].exec(g))!=null&&p[2]){var O,D,R=o.filter[N];D=p[1];q=false;p.splice(1,1);if(D.substr(D.length-1)!=="\\"){if(F===y)y=[];if(o.preFilter[N])if(p=o.preFilter[N](p,F,n,y,m,M)){if(p===true)continue}else q=O=true;if(p)for(var j=0;(D=F[j])!=null;j++)if(D){O=R(D,p,j,F);var s=m^!!O;if(n&&O!=null)if(s)q=true;else F[j]=false;else if(s){y.push(D);q=true}}if(O!== B){n||(F=y);g=g.replace(o.match[N],"");if(!q)return[];break}}}if(g===u)if(q==null)k.error(g);else break;u=g}return F};k.error=function(g){throw"Syntax error, unrecognized expression: "+g;};var o=k.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+\-]*)\))?/, POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(g){return g.getAttribute("href")}},relative:{"+":function(g,i){var n=typeof i==="string",m=n&&!/\W/.test(i);n=n&&!m;if(m)i=i.toLowerCase();m=0;for(var p=g.length,q;m<p;m++)if(q=g[m]){for(;(q=q.previousSibling)&&q.nodeType!==1;);g[m]=n||q&&q.nodeName.toLowerCase()=== i?q||false:q===i}n&&k.filter(i,g,true)},">":function(g,i){var n,m=typeof i==="string",p=0,q=g.length;if(m&&!/\W/.test(i))for(i=i.toLowerCase();p<q;p++){if(n=g[p]){n=n.parentNode;g[p]=n.nodeName.toLowerCase()===i?n:false}}else{for(;p<q;p++)if(n=g[p])g[p]=m?n.parentNode:n.parentNode===i;m&&k.filter(i,g,true)}},"":function(g,i,n){var m,p=e++,q=b;if(typeof i==="string"&&!/\W/.test(i)){m=i=i.toLowerCase();q=a}q("parentNode",i,p,g,m,n)},"~":function(g,i,n){var m,p=e++,q=b;if(typeof i==="string"&&!/\W/.test(i)){m= i=i.toLowerCase();q=a}q("previousSibling",i,p,g,m,n)}},find:{ID:function(g,i,n){if(typeof i.getElementById!=="undefined"&&!n)return(g=i.getElementById(g[1]))&&g.parentNode?[g]:[]},NAME:function(g,i){if(typeof i.getElementsByName!=="undefined"){for(var n=[],m=i.getElementsByName(g[1]),p=0,q=m.length;p<q;p++)m[p].getAttribute("name")===g[1]&&n.push(m[p]);return n.length===0?null:n}},TAG:function(g,i){return i.getElementsByTagName(g[1])}},preFilter:{CLASS:function(g,i,n,m,p,q){g=" "+g[1].replace(/\\/g, "")+" ";if(q)return g;q=0;for(var u;(u=i[q])!=null;q++)if(u)if(p^(u.className&&(" "+u.className+" ").replace(/[\t\n]/g," ").indexOf(g)>=0))n||m.push(u);else if(n)i[q]=false;return false},ID:function(g){return g[1].replace(/\\/g,"")},TAG:function(g){return g[1].toLowerCase()},CHILD:function(g){if(g[1]==="nth"){var i=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(g[2]==="even"&&"2n"||g[2]==="odd"&&"2n+1"||!/\D/.test(g[2])&&"0n+"+g[2]||g[2]);g[2]=i[1]+(i[2]||1)-0;g[3]=i[3]-0}g[0]=e++;return g},ATTR:function(g,i,n, m,p,q){i=g[1].replace(/\\/g,"");if(!q&&o.attrMap[i])g[1]=o.attrMap[i];if(g[2]==="~=")g[4]=" "+g[4]+" ";return g},PSEUDO:function(g,i,n,m,p){if(g[1]==="not")if((d.exec(g[3])||"").length>1||/^\w/.test(g[3]))g[3]=k(g[3],null,null,i);else{g=k.filter(g[3],i,n,true^p);n||m.push.apply(m,g);return false}else if(o.match.POS.test(g[0])||o.match.CHILD.test(g[0]))return true;return g},POS:function(g){g.unshift(true);return g}},filters:{enabled:function(g){return g.disabled===false&&g.type!=="hidden"},disabled:function(g){return g.disabled=== true},checked:function(g){return g.checked===true},selected:function(g){return g.selected===true},parent:function(g){return!!g.firstChild},empty:function(g){return!g.firstChild},has:function(g,i,n){return!!k(n[3],g).length},header:function(g){return/h\d/i.test(g.nodeName)},text:function(g){return"text"===g.type},radio:function(g){return"radio"===g.type},checkbox:function(g){return"checkbox"===g.type},file:function(g){return"file"===g.type},password:function(g){return"password"===g.type},submit:function(g){return"submit"=== g.type},image:function(g){return"image"===g.type},reset:function(g){return"reset"===g.type},button:function(g){return"button"===g.type||g.nodeName.toLowerCase()==="button"},input:function(g){return/input|select|textarea|button/i.test(g.nodeName)}},setFilters:{first:function(g,i){return i===0},last:function(g,i,n,m){return i===m.length-1},even:function(g,i){return i%2===0},odd:function(g,i){return i%2===1},lt:function(g,i,n){return i<n[3]-0},gt:function(g,i,n){return i>n[3]-0},nth:function(g,i,n){return n[3]- 0===i},eq:function(g,i,n){return n[3]-0===i}},filter:{PSEUDO:function(g,i,n,m){var p=i[1],q=o.filters[p];if(q)return q(g,n,i,m);else if(p==="contains")return(g.textContent||g.innerText||k.getText([g])||"").indexOf(i[3])>=0;else if(p==="not"){i=i[3];n=0;for(m=i.length;n<m;n++)if(i[n]===g)return false;return true}else k.error("Syntax error, unrecognized expression: "+p)},CHILD:function(g,i){var n=i[1],m=g;switch(n){case "only":case "first":for(;m=m.previousSibling;)if(m.nodeType===1)return false;if(n=== "first")return true;m=g;case "last":for(;m=m.nextSibling;)if(m.nodeType===1)return false;return true;case "nth":n=i[2];var p=i[3];if(n===1&&p===0)return true;var q=i[0],u=g.parentNode;if(u&&(u.sizcache!==q||!g.nodeIndex)){var y=0;for(m=u.firstChild;m;m=m.nextSibling)if(m.nodeType===1)m.nodeIndex=++y;u.sizcache=q}m=g.nodeIndex-p;return n===0?m===0:m%n===0&&m/n>=0}},ID:function(g,i){return g.nodeType===1&&g.getAttribute("id")===i},TAG:function(g,i){return i==="*"&&g.nodeType===1||g.nodeName.toLowerCase()=== i},CLASS:function(g,i){return(" "+(g.className||g.getAttribute("class"))+" ").indexOf(i)>-1},ATTR:function(g,i){var n=i[1];n=o.attrHandle[n]?o.attrHandle[n](g):g[n]!=null?g[n]:g.getAttribute(n);var m=n+"",p=i[2],q=i[4];return n==null?p==="!=":p==="="?m===q:p==="*="?m.indexOf(q)>=0:p==="~="?(" "+m+" ").indexOf(q)>=0:!q?m&&n!==false:p==="!="?m!==q:p==="^="?m.indexOf(q)===0:p==="$="?m.substr(m.length-q.length)===q:p==="|="?m===q||m.substr(0,q.length+1)===q+"-":false},POS:function(g,i,n,m){var p=o.setFilters[i[2]]; if(p)return p(g,n,i,m)}}},x=o.match.POS,r=function(g,i){return"\\"+(i-0+1)},A;for(A in o.match){o.match[A]=RegExp(o.match[A].source+/(?![^\[]*\])(?![^\(]*\))/.source);o.leftMatch[A]=RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[A].source.replace(/\\(\d+)/g,r))}var C=function(g,i){g=Array.prototype.slice.call(g,0);if(i){i.push.apply(i,g);return i}return g};try{Array.prototype.slice.call(t.documentElement.childNodes,0)}catch(J){C=function(g,i){var n=0,m=i||[];if(f.call(g)==="[object Array]")Array.prototype.push.apply(m, g);else if(typeof g.length==="number")for(var p=g.length;n<p;n++)m.push(g[n]);else for(;g[n];n++)m.push(g[n]);return m}}var w,I;if(t.documentElement.compareDocumentPosition)w=function(g,i){if(g===i){h=true;return 0}if(!g.compareDocumentPosition||!i.compareDocumentPosition)return g.compareDocumentPosition?-1:1;return g.compareDocumentPosition(i)&4?-1:1};else{w=function(g,i){var n,m,p=[],q=[];n=g.parentNode;m=i.parentNode;var u=n;if(g===i){h=true;return 0}else if(n===m)return I(g,i);else if(n){if(!m)return 1}else return-1; for(;u;){p.unshift(u);u=u.parentNode}for(u=m;u;){q.unshift(u);u=u.parentNode}n=p.length;m=q.length;for(u=0;u<n&&u<m;u++)if(p[u]!==q[u])return I(p[u],q[u]);return u===n?I(g,q[u],-1):I(p[u],i,1)};I=function(g,i,n){if(g===i)return n;for(g=g.nextSibling;g;){if(g===i)return-1;g=g.nextSibling}return 1}}k.getText=function(g){for(var i="",n,m=0;g[m];m++){n=g[m];if(n.nodeType===3||n.nodeType===4)i+=n.nodeValue;else if(n.nodeType!==8)i+=k.getText(n.childNodes)}return i};(function(){var g=t.createElement("div"), i="script"+(new Date).getTime(),n=t.documentElement;g.innerHTML="<a name='"+i+"'/>";n.insertBefore(g,n.firstChild);if(t.getElementById(i)){o.find.ID=function(m,p,q){if(typeof p.getElementById!=="undefined"&&!q)return(p=p.getElementById(m[1]))?p.id===m[1]||typeof p.getAttributeNode!=="undefined"&&p.getAttributeNode("id").nodeValue===m[1]?[p]:B:[]};o.filter.ID=function(m,p){var q=typeof m.getAttributeNode!=="undefined"&&m.getAttributeNode("id");return m.nodeType===1&&q&&q.nodeValue===p}}n.removeChild(g); n=g=null})();(function(){var g=t.createElement("div");g.appendChild(t.createComment(""));if(g.getElementsByTagName("*").length>0)o.find.TAG=function(i,n){var m=n.getElementsByTagName(i[1]);if(i[1]==="*"){for(var p=[],q=0;m[q];q++)m[q].nodeType===1&&p.push(m[q]);m=p}return m};g.innerHTML="<a href='#'></a>";if(g.firstChild&&typeof g.firstChild.getAttribute!=="undefined"&&g.firstChild.getAttribute("href")!=="#")o.attrHandle.href=function(i){return i.getAttribute("href",2)};g=null})();t.querySelectorAll&& function(){var g=k,i=t.createElement("div");i.innerHTML="<p class='TEST'></p>";if(!(i.querySelectorAll&&i.querySelectorAll(".TEST").length===0)){k=function(m,p,q,u){p=p||t;m=m.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!u&&!k.isXML(p))if(p.nodeType===9)try{return C(p.querySelectorAll(m),q)}catch(y){}else if(p.nodeType===1&&p.nodeName.toLowerCase()!=="object"){var F=p.getAttribute("id"),M=F||"__sizzle__";F||p.setAttribute("id",M);try{return C(p.querySelectorAll("#"+M+" "+m),q)}catch(N){}finally{F|| p.removeAttribute("id")}}return g(m,p,q,u)};for(var n in g)k[n]=g[n];i=null}}();(function(){var g=t.documentElement,i=g.matchesSelector||g.mozMatchesSelector||g.webkitMatchesSelector||g.msMatchesSelector,n=false;try{i.call(t.documentElement,"[test!='']:sizzle")}catch(m){n=true}if(i)k.matchesSelector=function(p,q){q=q.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!k.isXML(p))try{if(n||!o.match.PSEUDO.test(q)&&!/!=/.test(q))return i.call(p,q)}catch(u){}return k(q,null,null,[p]).length>0}})();(function(){var g= t.createElement("div");g.innerHTML="<div class='test e'></div><div class='test'></div>";if(!(!g.getElementsByClassName||g.getElementsByClassName("e").length===0)){g.lastChild.className="e";if(g.getElementsByClassName("e").length!==1){o.order.splice(1,0,"CLASS");o.find.CLASS=function(i,n,m){if(typeof n.getElementsByClassName!=="undefined"&&!m)return n.getElementsByClassName(i[1])};g=null}}})();k.contains=t.documentElement.contains?function(g,i){return g!==i&&(g.contains?g.contains(i):true)}:t.documentElement.compareDocumentPosition? function(g,i){return!!(g.compareDocumentPosition(i)&16)}:function(){return false};k.isXML=function(g){return(g=(g?g.ownerDocument||g:0).documentElement)?g.nodeName!=="HTML":false};var L=function(g,i){for(var n,m=[],p="",q=i.nodeType?[i]:i;n=o.match.PSEUDO.exec(g);){p+=n[0];g=g.replace(o.match.PSEUDO,"")}g=o.relative[g]?g+"*":g;n=0;for(var u=q.length;n<u;n++)k(g,q[n],m);return k.filter(p,m)};c.find=k;c.expr=k.selectors;c.expr[":"]=c.expr.filters;c.unique=k.uniqueSort;c.text=k.getText;c.isXMLDoc=k.isXML; c.contains=k.contains})();var Za=/Until$/,$a=/^(?:parents|prevUntil|prevAll)/,ab=/,/,Na=/^.[^:#\[\.,]*$/,bb=Array.prototype.slice,cb=c.expr.match.POS;c.fn.extend({find:function(a){for(var b=this.pushStack("","find",a),d=0,e=0,f=this.length;e<f;e++){d=b.length;c.find(a,this[e],b);if(e>0)for(var h=d;h<b.length;h++)for(var l=0;l<d;l++)if(b[l]===b[h]){b.splice(h--,1);break}}return b},has:function(a){var b=c(a);return this.filter(function(){for(var d=0,e=b.length;d<e;d++)if(c.contains(this,b[d]))return true})}, not:function(a){return this.pushStack(ma(this,a,false),"not",a)},filter:function(a){return this.pushStack(ma(this,a,true),"filter",a)},is:function(a){return!!a&&c.filter(a,this).length>0},closest:function(a,b){var d=[],e,f,h=this[0];if(c.isArray(a)){var l,k={},o=1;if(h&&a.length){e=0;for(f=a.length;e<f;e++){l=a[e];k[l]||(k[l]=c.expr.match.POS.test(l)?c(l,b||this.context):l)}for(;h&&h.ownerDocument&&h!==b;){for(l in k){e=k[l];if(e.jquery?e.index(h)>-1:c(h).is(e))d.push({selector:l,elem:h,level:o})}h= h.parentNode;o++}}return d}l=cb.test(a)?c(a,b||this.context):null;e=0;for(f=this.length;e<f;e++)for(h=this[e];h;)if(l?l.index(h)>-1:c.find.matchesSelector(h,a)){d.push(h);break}else{h=h.parentNode;if(!h||!h.ownerDocument||h===b)break}d=d.length>1?c.unique(d):d;return this.pushStack(d,"closest",a)},index:function(a){if(!a||typeof a==="string")return c.inArray(this[0],a?c(a):this.parent().children());return c.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var d=typeof a==="string"?c(a,b||this.context): c.makeArray(a),e=c.merge(this.get(),d);return this.pushStack(!d[0]||!d[0].parentNode||d[0].parentNode.nodeType===11||!e[0]||!e[0].parentNode||e[0].parentNode.nodeType===11?e:c.unique(e))},andSelf:function(){return this.add(this.prevObject)}});c.each({parent:function(a){return(a=a.parentNode)&&a.nodeType!==11?a:null},parents:function(a){return c.dir(a,"parentNode")},parentsUntil:function(a,b,d){return c.dir(a,"parentNode",d)},next:function(a){return c.nth(a,2,"nextSibling")},prev:function(a){return c.nth(a, 2,"previousSibling")},nextAll:function(a){return c.dir(a,"nextSibling")},prevAll:function(a){return c.dir(a,"previousSibling")},nextUntil:function(a,b,d){return c.dir(a,"nextSibling",d)},prevUntil:function(a,b,d){return c.dir(a,"previousSibling",d)},siblings:function(a){return c.sibling(a.parentNode.firstChild,a)},children:function(a){return c.sibling(a.firstChild)},contents:function(a){return c.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:c.makeArray(a.childNodes)}},function(a, b){c.fn[a]=function(d,e){var f=c.map(this,b,d);Za.test(a)||(e=d);if(e&&typeof e==="string")f=c.filter(e,f);f=this.length>1?c.unique(f):f;if((this.length>1||ab.test(e))&&$a.test(a))f=f.reverse();return this.pushStack(f,a,bb.call(arguments).join(","))}});c.extend({filter:function(a,b,d){if(d)a=":not("+a+")";return b.length===1?c.find.matchesSelector(b[0],a)?[b[0]]:[]:c.find.matches(a,b)},dir:function(a,b,d){var e=[];for(a=a[b];a&&a.nodeType!==9&&(d===B||a.nodeType!==1||!c(a).is(d));){a.nodeType===1&& e.push(a);a=a[b]}return e},nth:function(a,b,d){b=b||1;for(var e=0;a;a=a[d])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){for(var d=[];a;a=a.nextSibling)a.nodeType===1&&a!==b&&d.push(a);return d}});var za=/ jQuery\d+="(?:\d+|null)"/g,$=/^\s+/,Aa=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Ba=/<([\w:]+)/,db=/<tbody/i,eb=/<|&#?\w+;/,Ca=/<(?:script|object|embed|option|style)/i,Da=/checked\s*(?:[^=]|=\s*.checked.)/i,fb=/\=([^="'>\s]+\/)>/g,P={option:[1, "<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]};P.optgroup=P.option;P.tbody=P.tfoot=P.colgroup=P.caption=P.thead;P.th=P.td;if(!c.support.htmlSerialize)P._default=[1,"div<div>","</div>"];c.fn.extend({text:function(a){if(c.isFunction(a))return this.each(function(b){var d= c(this);d.text(a.call(this,b,d.text()))});if(typeof a!=="object"&&a!==B)return this.empty().append((this[0]&&this[0].ownerDocument||t).createTextNode(a));return c.text(this)},wrapAll:function(a){if(c.isFunction(a))return this.each(function(d){c(this).wrapAll(a.call(this,d))});if(this[0]){var b=c(a,this[0].ownerDocument).eq(0).clone(true);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var d=this;d.firstChild&&d.firstChild.nodeType===1;)d=d.firstChild;return d}).append(this)}return this}, wrapInner:function(a){if(c.isFunction(a))return this.each(function(b){c(this).wrapInner(a.call(this,b))});return this.each(function(){var b=c(this),d=b.contents();d.length?d.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){c(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){c.nodeName(this,"body")||c(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.appendChild(a)})}, prepend:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this)});else if(arguments.length){var a=c(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b, this.nextSibling)});else if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,c(arguments[0]).toArray());return a}},remove:function(a,b){for(var d=0,e;(e=this[d])!=null;d++)if(!a||c.filter(a,[e]).length){if(!b&&e.nodeType===1){c.cleanData(e.getElementsByTagName("*"));c.cleanData([e])}e.parentNode&&e.parentNode.removeChild(e)}return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++)for(b.nodeType===1&&c.cleanData(b.getElementsByTagName("*"));b.firstChild;)b.removeChild(b.firstChild); return this},clone:function(a){var b=this.map(function(){if(!c.support.noCloneEvent&&!c.isXMLDoc(this)){var d=this.outerHTML,e=this.ownerDocument;if(!d){d=e.createElement("div");d.appendChild(this.cloneNode(true));d=d.innerHTML}return c.clean([d.replace(za,"").replace(fb,'="$1">').replace($,"")],e)[0]}else return this.cloneNode(true)});if(a===true){na(this,b);na(this.find("*"),b.find("*"))}return b},html:function(a){if(a===B)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(za,""):null; else if(typeof a==="string"&&!Ca.test(a)&&(c.support.leadingWhitespace||!$.test(a))&&!P[(Ba.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Aa,"<$1></$2>");try{for(var b=0,d=this.length;b<d;b++)if(this[b].nodeType===1){c.cleanData(this[b].getElementsByTagName("*"));this[b].innerHTML=a}}catch(e){this.empty().append(a)}}else c.isFunction(a)?this.each(function(f){var h=c(this);h.html(a.call(this,f,h.html()))}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(c.isFunction(a))return this.each(function(b){var d= c(this),e=d.html();d.replaceWith(a.call(this,b,e))});if(typeof a!=="string")a=c(a).detach();return this.each(function(){var b=this.nextSibling,d=this.parentNode;c(this).remove();b?c(b).before(a):c(d).append(a)})}else return this.pushStack(c(c.isFunction(a)?a():a),"replaceWith",a)},detach:function(a){return this.remove(a,true)},domManip:function(a,b,d){var e,f,h,l=a[0],k=[];if(!c.support.checkClone&&arguments.length===3&&typeof l==="string"&&Da.test(l))return this.each(function(){c(this).domManip(a, b,d,true)});if(c.isFunction(l))return this.each(function(x){var r=c(this);a[0]=l.call(this,x,b?r.html():B);r.domManip(a,b,d)});if(this[0]){e=l&&l.parentNode;e=c.support.parentNode&&e&&e.nodeType===11&&e.childNodes.length===this.length?{fragment:e}:c.buildFragment(a,this,k);h=e.fragment;if(f=h.childNodes.length===1?h=h.firstChild:h.firstChild){b=b&&c.nodeName(f,"tr");f=0;for(var o=this.length;f<o;f++)d.call(b?c.nodeName(this[f],"table")?this[f].getElementsByTagName("tbody")[0]||this[f].appendChild(this[f].ownerDocument.createElement("tbody")): this[f]:this[f],f>0||e.cacheable||this.length>1?h.cloneNode(true):h)}k.length&&c.each(k,Oa)}return this}});c.buildFragment=function(a,b,d){var e,f,h;b=b&&b[0]?b[0].ownerDocument||b[0]:t;if(a.length===1&&typeof a[0]==="string"&&a[0].length<512&&b===t&&!Ca.test(a[0])&&(c.support.checkClone||!Da.test(a[0]))){f=true;if(h=c.fragments[a[0]])if(h!==1)e=h}if(!e){e=b.createDocumentFragment();c.clean(a,b,e,d)}if(f)c.fragments[a[0]]=h?e:1;return{fragment:e,cacheable:f}};c.fragments={};c.each({appendTo:"append", prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){c.fn[a]=function(d){var e=[];d=c(d);var f=this.length===1&&this[0].parentNode;if(f&&f.nodeType===11&&f.childNodes.length===1&&d.length===1){d[b](this[0]);return this}else{f=0;for(var h=d.length;f<h;f++){var l=(f>0?this.clone(true):this).get();c(d[f])[b](l);e=e.concat(l)}return this.pushStack(e,a,d.selector)}}});c.extend({clean:function(a,b,d,e){b=b||t;if(typeof b.createElement==="undefined")b=b.ownerDocument|| b[0]&&b[0].ownerDocument||t;for(var f=[],h=0,l;(l=a[h])!=null;h++){if(typeof l==="number")l+="";if(l){if(typeof l==="string"&&!eb.test(l))l=b.createTextNode(l);else if(typeof l==="string"){l=l.replace(Aa,"<$1></$2>");var k=(Ba.exec(l)||["",""])[1].toLowerCase(),o=P[k]||P._default,x=o[0],r=b.createElement("div");for(r.innerHTML=o[1]+l+o[2];x--;)r=r.lastChild;if(!c.support.tbody){x=db.test(l);k=k==="table"&&!x?r.firstChild&&r.firstChild.childNodes:o[1]==="<table>"&&!x?r.childNodes:[];for(o=k.length- 1;o>=0;--o)c.nodeName(k[o],"tbody")&&!k[o].childNodes.length&&k[o].parentNode.removeChild(k[o])}!c.support.leadingWhitespace&&$.test(l)&&r.insertBefore(b.createTextNode($.exec(l)[0]),r.firstChild);l=r.childNodes}if(l.nodeType)f.push(l);else f=c.merge(f,l)}}if(d)for(h=0;f[h];h++)if(e&&c.nodeName(f[h],"script")&&(!f[h].type||f[h].type.toLowerCase()==="text/javascript"))e.push(f[h].parentNode?f[h].parentNode.removeChild(f[h]):f[h]);else{f[h].nodeType===1&&f.splice.apply(f,[h+1,0].concat(c.makeArray(f[h].getElementsByTagName("script")))); d.appendChild(f[h])}return f},cleanData:function(a){for(var b,d,e=c.cache,f=c.event.special,h=c.support.deleteExpando,l=0,k;(k=a[l])!=null;l++)if(!(k.nodeName&&c.noData[k.nodeName.toLowerCase()]))if(d=k[c.expando]){if((b=e[d])&&b.events)for(var o in b.events)f[o]?c.event.remove(k,o):c.removeEvent(k,o,b.handle);if(h)delete k[c.expando];else k.removeAttribute&&k.removeAttribute(c.expando);delete e[d]}}});var Ea=/alpha\([^)]*\)/i,gb=/opacity=([^)]*)/,hb=/-([a-z])/ig,ib=/([A-Z])/g,Fa=/^-?\d+(?:px)?$/i, jb=/^-?\d/,kb={position:"absolute",visibility:"hidden",display:"block"},Pa=["Left","Right"],Qa=["Top","Bottom"],W,Ga,aa,lb=function(a,b){return b.toUpperCase()};c.fn.css=function(a,b){if(arguments.length===2&&b===B)return this;return c.access(this,a,b,true,function(d,e,f){return f!==B?c.style(d,e,f):c.css(d,e)})};c.extend({cssHooks:{opacity:{get:function(a,b){if(b){var d=W(a,"opacity","opacity");return d===""?"1":d}else return a.style.opacity}}},cssNumber:{zIndex:true,fontWeight:true,opacity:true, zoom:true,lineHeight:true},cssProps:{"float":c.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,d,e){if(!(!a||a.nodeType===3||a.nodeType===8||!a.style)){var f,h=c.camelCase(b),l=a.style,k=c.cssHooks[h];b=c.cssProps[h]||h;if(d!==B){if(!(typeof d==="number"&&isNaN(d)||d==null)){if(typeof d==="number"&&!c.cssNumber[h])d+="px";if(!k||!("set"in k)||(d=k.set(a,d))!==B)try{l[b]=d}catch(o){}}}else{if(k&&"get"in k&&(f=k.get(a,false,e))!==B)return f;return l[b]}}},css:function(a,b,d){var e,f=c.camelCase(b), h=c.cssHooks[f];b=c.cssProps[f]||f;if(h&&"get"in h&&(e=h.get(a,true,d))!==B)return e;else if(W)return W(a,b,f)},swap:function(a,b,d){var e={},f;for(f in b){e[f]=a.style[f];a.style[f]=b[f]}d.call(a);for(f in b)a.style[f]=e[f]},camelCase:function(a){return a.replace(hb,lb)}});c.curCSS=c.css;c.each(["height","width"],function(a,b){c.cssHooks[b]={get:function(d,e,f){var h;if(e){if(d.offsetWidth!==0)h=oa(d,b,f);else c.swap(d,kb,function(){h=oa(d,b,f)});if(h<=0){h=W(d,b,b);if(h==="0px"&&aa)h=aa(d,b,b); if(h!=null)return h===""||h==="auto"?"0px":h}if(h<0||h==null){h=d.style[b];return h===""||h==="auto"?"0px":h}return typeof h==="string"?h:h+"px"}},set:function(d,e){if(Fa.test(e)){e=parseFloat(e);if(e>=0)return e+"px"}else return e}}});if(!c.support.opacity)c.cssHooks.opacity={get:function(a,b){return gb.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var d=a.style;d.zoom=1;var e=c.isNaN(b)?"":"alpha(opacity="+b*100+")",f= d.filter||"";d.filter=Ea.test(f)?f.replace(Ea,e):d.filter+" "+e}};if(t.defaultView&&t.defaultView.getComputedStyle)Ga=function(a,b,d){var e;d=d.replace(ib,"-$1").toLowerCase();if(!(b=a.ownerDocument.defaultView))return B;if(b=b.getComputedStyle(a,null)){e=b.getPropertyValue(d);if(e===""&&!c.contains(a.ownerDocument.documentElement,a))e=c.style(a,d)}return e};if(t.documentElement.currentStyle)aa=function(a,b){var d,e,f=a.currentStyle&&a.currentStyle[b],h=a.style;if(!Fa.test(f)&&jb.test(f)){d=h.left; e=a.runtimeStyle.left;a.runtimeStyle.left=a.currentStyle.left;h.left=b==="fontSize"?"1em":f||0;f=h.pixelLeft+"px";h.left=d;a.runtimeStyle.left=e}return f===""?"auto":f};W=Ga||aa;if(c.expr&&c.expr.filters){c.expr.filters.hidden=function(a){var b=a.offsetHeight;return a.offsetWidth===0&&b===0||!c.support.reliableHiddenOffsets&&(a.style.display||c.css(a,"display"))==="none"};c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)}}var mb=c.now(),nb=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, ob=/^(?:select|textarea)/i,pb=/^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,qb=/^(?:GET|HEAD)$/,Ra=/\[\]$/,T=/\=\?(&|$)/,ja=/\?/,rb=/([?&])_=[^&]*/,sb=/^(\w+:)?\/\/([^\/?#]+)/,tb=/%20/g,ub=/#.*$/,Ha=c.fn.load;c.fn.extend({load:function(a,b,d){if(typeof a!=="string"&&Ha)return Ha.apply(this,arguments);else if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var f=a.slice(e,a.length);a=a.slice(0,e)}e="GET";if(b)if(c.isFunction(b)){d=b;b=null}else if(typeof b=== "object"){b=c.param(b,c.ajaxSettings.traditional);e="POST"}var h=this;c.ajax({url:a,type:e,dataType:"html",data:b,complete:function(l,k){if(k==="success"||k==="notmodified")h.html(f?c("<div>").append(l.responseText.replace(nb,"")).find(f):l.responseText);d&&h.each(d,[l.responseText,k,l])}});return this},serialize:function(){return c.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?c.makeArray(this.elements):this}).filter(function(){return this.name&& !this.disabled&&(this.checked||ob.test(this.nodeName)||pb.test(this.type))}).map(function(a,b){var d=c(this).val();return d==null?null:c.isArray(d)?c.map(d,function(e){return{name:b.name,value:e}}):{name:b.name,value:d}}).get()}});c.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){c.fn[b]=function(d){return this.bind(b,d)}});c.extend({get:function(a,b,d,e){if(c.isFunction(b)){e=e||d;d=b;b=null}return c.ajax({type:"GET",url:a,data:b,success:d,dataType:e})}, getScript:function(a,b){return c.get(a,null,b,"script")},getJSON:function(a,b,d){return c.get(a,b,d,"json")},post:function(a,b,d,e){if(c.isFunction(b)){e=e||d;d=b;b={}}return c.ajax({type:"POST",url:a,data:b,success:d,dataType:e})},ajaxSetup:function(a){c.extend(c.ajaxSettings,a)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return new E.XMLHttpRequest},accepts:{xml:"application/xml, text/xml",html:"text/html", script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},ajax:function(a){var b=c.extend(true,{},c.ajaxSettings,a),d,e,f,h=b.type.toUpperCase(),l=qb.test(h);b.url=b.url.replace(ub,"");b.context=a&&a.context!=null?a.context:b;if(b.data&&b.processData&&typeof b.data!=="string")b.data=c.param(b.data,b.traditional);if(b.dataType==="jsonp"){if(h==="GET")T.test(b.url)||(b.url+=(ja.test(b.url)?"&":"?")+(b.jsonp||"callback")+"=?");else if(!b.data|| !T.test(b.data))b.data=(b.data?b.data+"&":"")+(b.jsonp||"callback")+"=?";b.dataType="json"}if(b.dataType==="json"&&(b.data&&T.test(b.data)||T.test(b.url))){d=b.jsonpCallback||"jsonp"+mb++;if(b.data)b.data=(b.data+"").replace(T,"="+d+"$1");b.url=b.url.replace(T,"="+d+"$1");b.dataType="script";var k=E[d];E[d]=function(m){if(c.isFunction(k))k(m);else{E[d]=B;try{delete E[d]}catch(p){}}f=m;c.handleSuccess(b,w,e,f);c.handleComplete(b,w,e,f);r&&r.removeChild(A)}}if(b.dataType==="script"&&b.cache===null)b.cache= false;if(b.cache===false&&l){var o=c.now(),x=b.url.replace(rb,"$1_="+o);b.url=x+(x===b.url?(ja.test(b.url)?"&":"?")+"_="+o:"")}if(b.data&&l)b.url+=(ja.test(b.url)?"&":"?")+b.data;b.global&&c.active++===0&&c.event.trigger("ajaxStart");o=(o=sb.exec(b.url))&&(o[1]&&o[1].toLowerCase()!==location.protocol||o[2].toLowerCase()!==location.host);if(b.dataType==="script"&&h==="GET"&&o){var r=t.getElementsByTagName("head")[0]||t.documentElement,A=t.createElement("script");if(b.scriptCharset)A.charset=b.scriptCharset; A.src=b.url;if(!d){var C=false;A.onload=A.onreadystatechange=function(){if(!C&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){C=true;c.handleSuccess(b,w,e,f);c.handleComplete(b,w,e,f);A.onload=A.onreadystatechange=null;r&&A.parentNode&&r.removeChild(A)}}}r.insertBefore(A,r.firstChild);return B}var J=false,w=b.xhr();if(w){b.username?w.open(h,b.url,b.async,b.username,b.password):w.open(h,b.url,b.async);try{if(b.data!=null&&!l||a&&a.contentType)w.setRequestHeader("Content-Type", b.contentType);if(b.ifModified){c.lastModified[b.url]&&w.setRequestHeader("If-Modified-Since",c.lastModified[b.url]);c.etag[b.url]&&w.setRequestHeader("If-None-Match",c.etag[b.url])}o||w.setRequestHeader("X-Requested-With","XMLHttpRequest");w.setRequestHeader("Accept",b.dataType&&b.accepts[b.dataType]?b.accepts[b.dataType]+", */*; q=0.01":b.accepts._default)}catch(I){}if(b.beforeSend&&b.beforeSend.call(b.context,w,b)===false){b.global&&c.active--===1&&c.event.trigger("ajaxStop");w.abort();return false}b.global&& c.triggerGlobal(b,"ajaxSend",[w,b]);var L=w.onreadystatechange=function(m){if(!w||w.readyState===0||m==="abort"){J||c.handleComplete(b,w,e,f);J=true;if(w)w.onreadystatechange=c.noop}else if(!J&&w&&(w.readyState===4||m==="timeout")){J=true;w.onreadystatechange=c.noop;e=m==="timeout"?"timeout":!c.httpSuccess(w)?"error":b.ifModified&&c.httpNotModified(w,b.url)?"notmodified":"success";var p;if(e==="success")try{f=c.httpData(w,b.dataType,b)}catch(q){e="parsererror";p=q}if(e==="success"||e==="notmodified")d|| c.handleSuccess(b,w,e,f);else c.handleError(b,w,e,p);d||c.handleComplete(b,w,e,f);m==="timeout"&&w.abort();if(b.async)w=null}};try{var g=w.abort;w.abort=function(){w&&Function.prototype.call.call(g,w);L("abort")}}catch(i){}b.async&&b.timeout>0&&setTimeout(function(){w&&!J&&L("timeout")},b.timeout);try{w.send(l||b.data==null?null:b.data)}catch(n){c.handleError(b,w,null,n);c.handleComplete(b,w,e,f)}b.async||L();return w}},param:function(a,b){var d=[],e=function(h,l){l=c.isFunction(l)?l():l;d[d.length]= encodeURIComponent(h)+"="+encodeURIComponent(l)};if(b===B)b=c.ajaxSettings.traditional;if(c.isArray(a)||a.jquery)c.each(a,function(){e(this.name,this.value)});else for(var f in a)da(f,a[f],b,e);return d.join("&").replace(tb,"+")}});c.extend({active:0,lastModified:{},etag:{},handleError:function(a,b,d,e){a.error&&a.error.call(a.context,b,d,e);a.global&&c.triggerGlobal(a,"ajaxError",[b,a,e])},handleSuccess:function(a,b,d,e){a.success&&a.success.call(a.context,e,d,b);a.global&&c.triggerGlobal(a,"ajaxSuccess", [b,a])},handleComplete:function(a,b,d){a.complete&&a.complete.call(a.context,b,d);a.global&&c.triggerGlobal(a,"ajaxComplete",[b,a]);a.global&&c.active--===1&&c.event.trigger("ajaxStop")},triggerGlobal:function(a,b,d){(a.context&&a.context.url==null?c(a.context):c.event).trigger(b,d)},httpSuccess:function(a){try{return!a.status&&location.protocol==="file:"||a.status>=200&&a.status<300||a.status===304||a.status===1223}catch(b){}return false},httpNotModified:function(a,b){var d=a.getResponseHeader("Last-Modified"), e=a.getResponseHeader("Etag");if(d)c.lastModified[b]=d;if(e)c.etag[b]=e;return a.status===304},httpData:function(a,b,d){var e=a.getResponseHeader("content-type")||"",f=b==="xml"||!b&&e.indexOf("xml")>=0;a=f?a.responseXML:a.responseText;f&&a.documentElement.nodeName==="parsererror"&&c.error("parsererror");if(d&&d.dataFilter)a=d.dataFilter(a,b);if(typeof a==="string")if(b==="json"||!b&&e.indexOf("json")>=0)a=c.parseJSON(a);else if(b==="script"||!b&&e.indexOf("javascript")>=0)c.globalEval(a);return a}}); if(E.ActiveXObject)c.ajaxSettings.xhr=function(){if(E.location.protocol!=="file:")try{return new E.XMLHttpRequest}catch(a){}try{return new E.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}};c.support.ajax=!!c.ajaxSettings.xhr();var ea={},vb=/^(?:toggle|show|hide)$/,wb=/^([+\-]=)?([\d+.\-]+)(.*)$/,ba,pa=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];c.fn.extend({show:function(a,b,d){if(a||a===0)return this.animate(S("show", 3),a,b,d);else{d=0;for(var e=this.length;d<e;d++){a=this[d];b=a.style.display;if(!c.data(a,"olddisplay")&&b==="none")b=a.style.display="";b===""&&c.css(a,"display")==="none"&&c.data(a,"olddisplay",qa(a.nodeName))}for(d=0;d<e;d++){a=this[d];b=a.style.display;if(b===""||b==="none")a.style.display=c.data(a,"olddisplay")||""}return this}},hide:function(a,b,d){if(a||a===0)return this.animate(S("hide",3),a,b,d);else{a=0;for(b=this.length;a<b;a++){d=c.css(this[a],"display");d!=="none"&&c.data(this[a],"olddisplay", d)}for(a=0;a<b;a++)this[a].style.display="none";return this}},_toggle:c.fn.toggle,toggle:function(a,b,d){var e=typeof a==="boolean";if(c.isFunction(a)&&c.isFunction(b))this._toggle.apply(this,arguments);else a==null||e?this.each(function(){var f=e?a:c(this).is(":hidden");c(this)[f?"show":"hide"]()}):this.animate(S("toggle",3),a,b,d);return this},fadeTo:function(a,b,d,e){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,d,e)},animate:function(a,b,d,e){var f=c.speed(b, d,e);if(c.isEmptyObject(a))return this.each(f.complete);return this[f.queue===false?"each":"queue"](function(){var h=c.extend({},f),l,k=this.nodeType===1,o=k&&c(this).is(":hidden"),x=this;for(l in a){var r=c.camelCase(l);if(l!==r){a[r]=a[l];delete a[l];l=r}if(a[l]==="hide"&&o||a[l]==="show"&&!o)return h.complete.call(this);if(k&&(l==="height"||l==="width")){h.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY];if(c.css(this,"display")==="inline"&&c.css(this,"float")==="none")if(c.support.inlineBlockNeedsLayout)if(qa(this.nodeName)=== "inline")this.style.display="inline-block";else{this.style.display="inline";this.style.zoom=1}else this.style.display="inline-block"}if(c.isArray(a[l])){(h.specialEasing=h.specialEasing||{})[l]=a[l][1];a[l]=a[l][0]}}if(h.overflow!=null)this.style.overflow="hidden";h.curAnim=c.extend({},a);c.each(a,function(A,C){var J=new c.fx(x,h,A);if(vb.test(C))J[C==="toggle"?o?"show":"hide":C](a);else{var w=wb.exec(C),I=J.cur()||0;if(w){var L=parseFloat(w[2]),g=w[3]||"px";if(g!=="px"){c.style(x,A,(L||1)+g);I=(L|| 1)/J.cur()*I;c.style(x,A,I+g)}if(w[1])L=(w[1]==="-="?-1:1)*L+I;J.custom(I,L,g)}else J.custom(I,C,"")}});return true})},stop:function(a,b){var d=c.timers;a&&this.queue([]);this.each(function(){for(var e=d.length-1;e>=0;e--)if(d[e].elem===this){b&&d[e](true);d.splice(e,1)}});b||this.dequeue();return this}});c.each({slideDown:S("show",1),slideUp:S("hide",1),slideToggle:S("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){c.fn[a]=function(d,e,f){return this.animate(b, d,e,f)}});c.extend({speed:function(a,b,d){var e=a&&typeof a==="object"?c.extend({},a):{complete:d||!d&&b||c.isFunction(a)&&a,duration:a,easing:d&&b||b&&!c.isFunction(b)&&b};e.duration=c.fx.off?0:typeof e.duration==="number"?e.duration:e.duration in c.fx.speeds?c.fx.speeds[e.duration]:c.fx.speeds._default;e.old=e.complete;e.complete=function(){e.queue!==false&&c(this).dequeue();c.isFunction(e.old)&&e.old.call(this)};return e},easing:{linear:function(a,b,d,e){return d+e*a},swing:function(a,b,d,e){return(-Math.cos(a* Math.PI)/2+0.5)*e+d}},timers:[],fx:function(a,b,d){this.options=b;this.elem=a;this.prop=d;if(!b.orig)b.orig={}}});c.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this);(c.fx.step[this.prop]||c.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a=parseFloat(c.css(this.elem,this.prop));return a&&a>-1E4?a:0},custom:function(a,b,d){function e(l){return f.step(l)} var f=this,h=c.fx;this.startTime=c.now();this.start=a;this.end=b;this.unit=d||this.unit||"px";this.now=this.start;this.pos=this.state=0;e.elem=this.elem;if(e()&&c.timers.push(e)&&!ba)ba=setInterval(h.tick,h.interval)},show:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur());c(this.elem).show()},hide:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.hide=true; this.custom(this.cur(),0)},step:function(a){var b=c.now(),d=true;if(a||b>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var e in this.options.curAnim)if(this.options.curAnim[e]!==true)d=false;if(d){if(this.options.overflow!=null&&!c.support.shrinkWrapBlocks){var f=this.elem,h=this.options;c.each(["","X","Y"],function(k,o){f.style["overflow"+o]=h.overflow[k]})}this.options.hide&&c(this.elem).hide();if(this.options.hide|| this.options.show)for(var l in this.options.curAnim)c.style(this.elem,l,this.options.orig[l]);this.options.complete.call(this.elem)}return false}else{a=b-this.startTime;this.state=a/this.options.duration;b=this.options.easing||(c.easing.swing?"swing":"linear");this.pos=c.easing[this.options.specialEasing&&this.options.specialEasing[this.prop]||b](this.state,a,0,1,this.options.duration);this.now=this.start+(this.end-this.start)*this.pos;this.update()}return true}};c.extend(c.fx,{tick:function(){for(var a= c.timers,b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length||c.fx.stop()},interval:13,stop:function(){clearInterval(ba);ba=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){c.style(a.elem,"opacity",a.now)},_default:function(a){if(a.elem.style&&a.elem.style[a.prop]!=null)a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit;else a.elem[a.prop]=a.now}}});if(c.expr&&c.expr.filters)c.expr.filters.animated=function(a){return c.grep(c.timers,function(b){return a=== b.elem}).length};var xb=/^t(?:able|d|h)$/i,Ia=/^(?:body|html)$/i;c.fn.offset="getBoundingClientRect"in t.documentElement?function(a){var b=this[0],d;if(a)return this.each(function(l){c.offset.setOffset(this,a,l)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);try{d=b.getBoundingClientRect()}catch(e){}var f=b.ownerDocument,h=f.documentElement;if(!d||!c.contains(h,b))return d||{top:0,left:0};b=f.body;f=fa(f);return{top:d.top+(f.pageYOffset||c.support.boxModel&& h.scrollTop||b.scrollTop)-(h.clientTop||b.clientTop||0),left:d.left+(f.pageXOffset||c.support.boxModel&&h.scrollLeft||b.scrollLeft)-(h.clientLeft||b.clientLeft||0)}}:function(a){var b=this[0];if(a)return this.each(function(x){c.offset.setOffset(this,a,x)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);c.offset.initialize();var d,e=b.offsetParent,f=b.ownerDocument,h=f.documentElement,l=f.body;d=(f=f.defaultView)?f.getComputedStyle(b,null):b.currentStyle; for(var k=b.offsetTop,o=b.offsetLeft;(b=b.parentNode)&&b!==l&&b!==h;){if(c.offset.supportsFixedPosition&&d.position==="fixed")break;d=f?f.getComputedStyle(b,null):b.currentStyle;k-=b.scrollTop;o-=b.scrollLeft;if(b===e){k+=b.offsetTop;o+=b.offsetLeft;if(c.offset.doesNotAddBorder&&!(c.offset.doesAddBorderForTableAndCells&&xb.test(b.nodeName))){k+=parseFloat(d.borderTopWidth)||0;o+=parseFloat(d.borderLeftWidth)||0}e=b.offsetParent}if(c.offset.subtractsBorderForOverflowNotVisible&&d.overflow!=="visible"){k+= parseFloat(d.borderTopWidth)||0;o+=parseFloat(d.borderLeftWidth)||0}d=d}if(d.position==="relative"||d.position==="static"){k+=l.offsetTop;o+=l.offsetLeft}if(c.offset.supportsFixedPosition&&d.position==="fixed"){k+=Math.max(h.scrollTop,l.scrollTop);o+=Math.max(h.scrollLeft,l.scrollLeft)}return{top:k,left:o}};c.offset={initialize:function(){var a=t.body,b=t.createElement("div"),d,e,f,h=parseFloat(c.css(a,"marginTop"))||0;c.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px", height:"1px",visibility:"hidden"});b.innerHTML="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";a.insertBefore(b,a.firstChild);d=b.firstChild;e=d.firstChild;f=d.nextSibling.firstChild.firstChild;this.doesNotAddBorder=e.offsetTop!==5;this.doesAddBorderForTableAndCells= f.offsetTop===5;e.style.position="fixed";e.style.top="20px";this.supportsFixedPosition=e.offsetTop===20||e.offsetTop===15;e.style.position=e.style.top="";d.style.overflow="hidden";d.style.position="relative";this.subtractsBorderForOverflowNotVisible=e.offsetTop===-5;this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==h;a.removeChild(b);c.offset.initialize=c.noop},bodyOffset:function(a){var b=a.offsetTop,d=a.offsetLeft;c.offset.initialize();if(c.offset.doesNotIncludeMarginInBodyOffset){b+=parseFloat(c.css(a, "marginTop"))||0;d+=parseFloat(c.css(a,"marginLeft"))||0}return{top:b,left:d}},setOffset:function(a,b,d){var e=c.css(a,"position");if(e==="static")a.style.position="relative";var f=c(a),h=f.offset(),l=c.css(a,"top"),k=c.css(a,"left"),o=e==="absolute"&&c.inArray("auto",[l,k])>-1;e={};var x={};if(o)x=f.position();l=o?x.top:parseInt(l,10)||0;k=o?x.left:parseInt(k,10)||0;if(c.isFunction(b))b=b.call(a,d,h);if(b.top!=null)e.top=b.top-h.top+l;if(b.left!=null)e.left=b.left-h.left+k;"using"in b?b.using.call(a, e):f.css(e)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),e=Ia.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.css(a,"marginTop"))||0;d.left-=parseFloat(c.css(a,"marginLeft"))||0;e.top+=parseFloat(c.css(b[0],"borderTopWidth"))||0;e.left+=parseFloat(c.css(b[0],"borderLeftWidth"))||0;return{top:d.top-e.top,left:d.left-e.left}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent||t.body;a&&!Ia.test(a.nodeName)&& c.css(a,"position")==="static";)a=a.offsetParent;return a})}});c.each(["Left","Top"],function(a,b){var d="scroll"+b;c.fn[d]=function(e){var f=this[0],h;if(!f)return null;if(e!==B)return this.each(function(){if(h=fa(this))h.scrollTo(!a?e:c(h).scrollLeft(),a?e:c(h).scrollTop());else this[d]=e});else return(h=fa(f))?"pageXOffset"in h?h[a?"pageYOffset":"pageXOffset"]:c.support.boxModel&&h.document.documentElement[d]||h.document.body[d]:f[d]}});c.each(["Height","Width"],function(a,b){var d=b.toLowerCase(); c.fn["inner"+b]=function(){return this[0]?parseFloat(c.css(this[0],d,"padding")):null};c.fn["outer"+b]=function(e){return this[0]?parseFloat(c.css(this[0],d,e?"margin":"border")):null};c.fn[d]=function(e){var f=this[0];if(!f)return e==null?null:this;if(c.isFunction(e))return this.each(function(l){var k=c(this);k[d](e.call(this,l,k[d]()))});if(c.isWindow(f))return f.document.compatMode==="CSS1Compat"&&f.document.documentElement["client"+b]||f.document.body["client"+b];else if(f.nodeType===9)return Math.max(f.documentElement["client"+ b],f.body["scroll"+b],f.documentElement["scroll"+b],f.body["offset"+b],f.documentElement["offset"+b]);else if(e===B){f=c.css(f,d);var h=parseFloat(f);return c.isNaN(h)?f:h}else return this.css(d,typeof e==="string"?e:e+"px")}})})(window);
ztfy.jqueryui
/ztfy.jqueryui-0.7.12.tar.gz/ztfy.jqueryui-0.7.12/src/ztfy/jqueryui/resources/js/jquery-1.4.4.min.js
jquery-1.4.4.min.js
(function(B){var L,T,Q,M,d,m,J,A,O,z,C=0,H={},j=[],e=0,G={},y=[],f=null,o=new Image(),i=/\.(jpg|gif|png|bmp|jpeg)(.*)?$/i,k=/[^\.]\.(swf)\s*$/i,p,N=1,h=0,t="",b,c,P=false,s=B.extend(B("<div/>")[0],{prop:0}),S=B.browser.msie&&B.browser.version<7&&!window.XMLHttpRequest,r=function(){T.hide();o.onerror=o.onload=null;if(f){f.abort()}L.empty()},x=function(){if(false===H.onError(j,C,H)){T.hide();P=false;return}H.titleShow=false;H.width="auto";H.height="auto";L.html('<p id="fancybox-error">The requested content cannot be loaded.<br />Please try again later.</p>');n()},w=function(){var Z=j[C],W,Y,ab,aa,V,X;r();H=B.extend({},B.fn.fancybox.defaults,(typeof B(Z).data("fancybox")=="undefined"?H:B(Z).data("fancybox")));X=H.onStart(j,C,H);if(X===false){P=false;return}else{if(typeof X=="object"){H=B.extend(H,X)}}ab=H.title||(Z.nodeName?B(Z).attr("title"):Z.title)||"";if(Z.nodeName&&!H.orig){H.orig=B(Z).children("img:first").length?B(Z).children("img:first"):B(Z)}if(ab===""&&H.orig&&H.titleFromAlt){ab=H.orig.attr("alt")}W=H.href||(Z.nodeName?B(Z).attr("href"):Z.href)||null;if((/^(?:javascript)/i).test(W)||W=="#"){W=null}if(H.type){Y=H.type;if(!W){W=H.content}}else{if(H.content){Y="html"}else{if(W){if(W.match(i)){Y="image"}else{if(W.match(k)){Y="swf"}else{if(B(Z).hasClass("iframe")){Y="iframe"}else{if(W.indexOf("#")===0){Y="inline"}else{Y="ajax"}}}}}}}if(!Y){x();return}if(Y=="inline"){Z=W.substr(W.indexOf("#"));Y=B(Z).length>0?"inline":"ajax"}H.type=Y;H.href=W;H.title=ab;if(H.autoDimensions){if(H.type=="html"||H.type=="inline"||H.type=="ajax"){H.width="auto";H.height="auto"}else{H.autoDimensions=false}}if(H.modal){H.overlayShow=true;H.hideOnOverlayClick=false;H.hideOnContentClick=false;H.enableEscapeButton=false;H.showCloseButton=false}H.padding=parseInt(H.padding,10);H.margin=parseInt(H.margin,10);L.css("padding",(H.padding+H.margin));B(".fancybox-inline-tmp").unbind("fancybox-cancel").bind("fancybox-change",function(){B(this).replaceWith(m.children())});switch(Y){case"html":L.html(H.content);n();break;case"inline":if(B(Z).parent().is("#fancybox-content")===true){P=false;return}B('<div class="fancybox-inline-tmp" />').hide().insertBefore(B(Z)).bind("fancybox-cleanup",function(){B(this).replaceWith(m.children())}).bind("fancybox-cancel",function(){B(this).replaceWith(L.children())});B(Z).appendTo(L);n();break;case"image":P=false;B.fancybox.showActivity();o=new Image();o.onerror=function(){x()};o.onload=function(){P=true;o.onerror=o.onload=null;F()};o.src=W;break;case"swf":H.scrolling="no";aa='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+H.width+'" height="'+H.height+'"><param name="movie" value="'+W+'"></param>';V="";B.each(H.swf,function(ac,ad){aa+='<param name="'+ac+'" value="'+ad+'"></param>';V+=" "+ac+'="'+ad+'"'});aa+='<embed src="'+W+'" type="application/x-shockwave-flash" width="'+H.width+'" height="'+H.height+'"'+V+"></embed></object>";L.html(aa);n();break;case"ajax":P=false;B.fancybox.showActivity();H.ajax.win=H.ajax.success;f=B.ajax(B.extend({},H.ajax,{url:W,data:H.ajax.data||{},error:function(ac,ae,ad){if(ac.status>0){x()}},success:function(ad,af,ac){var ae=typeof ac=="object"?ac:f;if(ae.status==200){if(typeof H.ajax.win=="function"){X=H.ajax.win(W,ad,af,ac);if(X===false){T.hide();return}else{if(typeof X=="string"||typeof X=="object"){ad=X}}}L.html(ad);n()}}}));break;case"iframe":E();break}},n=function(){var V=H.width,W=H.height;if(V.toString().indexOf("%")>-1){V=parseInt((B(window).width()-(H.margin*2))*parseFloat(V)/100,10)+"px"}else{V=V=="auto"?"auto":V+"px"}if(W.toString().indexOf("%")>-1){W=parseInt((B(window).height()-(H.margin*2))*parseFloat(W)/100,10)+"px"}else{W=W=="auto"?"auto":W+"px"}L.wrapInner('<div style="width:'+V+";height:"+W+";overflow: "+(H.scrolling=="auto"?"auto":(H.scrolling=="yes"?"scroll":"hidden"))+';position:relative;"></div>');H.width=L.width();H.height=L.height();E()},F=function(){H.width=o.width;H.height=o.height;B("<img />").attr({id:"fancybox-img",src:o.src,alt:H.title}).appendTo(L);E()},E=function(){var W,V;T.hide();if(M.is(":visible")&&false===G.onCleanup(y,e,G)){B.event.trigger("fancybox-cancel");P=false;return}P=true;B(m.add(Q)).unbind();B(window).unbind("resize.fb scroll.fb");B(document).unbind("keydown.fb");if(M.is(":visible")&&G.titlePosition!=="outside"){M.css("height",M.height())}y=j;e=C;G=H;if(G.overlayShow){Q.css({"background-color":G.overlayColor,opacity:G.overlayOpacity,cursor:G.hideOnOverlayClick?"pointer":"auto",height:B(document).height()});if(!Q.is(":visible")){if(S){B("select:not(#fancybox-tmp select)").filter(function(){return this.style.visibility!=="hidden"}).css({visibility:"hidden"}).one("fancybox-cleanup",function(){this.style.visibility="inherit"})}Q.show()}}else{Q.hide()}c=R();l();if(M.is(":visible")){B(J.add(O).add(z)).hide();W=M.position(),b={top:W.top,left:W.left,width:M.width(),height:M.height()};V=(b.width==c.width&&b.height==c.height);m.fadeTo(G.changeFade,0.3,function(){var X=function(){m.html(L.contents()).fadeTo(G.changeFade,1,v)};B.event.trigger("fancybox-change");m.empty().removeAttr("filter").css({"border-width":G.padding,width:c.width-G.padding*2,height:H.autoDimensions?"auto":c.height-h-G.padding*2});if(V){X()}else{s.prop=0;B(s).animate({prop:1},{duration:G.changeSpeed,easing:G.easingChange,step:U,complete:X})}});return}M.removeAttr("style");m.css("border-width",G.padding);if(G.transitionIn=="elastic"){b=I();m.html(L.contents());M.show();if(G.opacity){c.opacity=0}s.prop=0;B(s).animate({prop:1},{duration:G.speedIn,easing:G.easingIn,step:U,complete:v});return}if(G.titlePosition=="inside"&&h>0){A.show()}m.css({width:c.width-G.padding*2,height:H.autoDimensions?"auto":c.height-h-G.padding*2}).html(L.contents());M.css(c).fadeIn(G.transitionIn=="none"?0:G.speedIn,v)},D=function(V){if(V&&V.length){if(G.titlePosition=="float"){return'<table id="fancybox-title-float-wrap" cellpadding="0" cellspacing="0"><tr><td id="fancybox-title-float-left"></td><td id="fancybox-title-float-main">'+V+'</td><td id="fancybox-title-float-right"></td></tr></table>'}return'<div id="fancybox-title-'+G.titlePosition+'">'+V+"</div>"}return false},l=function(){t=G.title||"";h=0;A.empty().removeAttr("style").removeClass();if(G.titleShow===false){A.hide();return}t=B.isFunction(G.titleFormat)?G.titleFormat(t,y,e,G):D(t);if(!t||t===""){A.hide();return}A.addClass("fancybox-title-"+G.titlePosition).html(t).appendTo("body").show();switch(G.titlePosition){case"inside":A.css({width:c.width-(G.padding*2),marginLeft:G.padding,marginRight:G.padding});h=A.outerHeight(true);A.appendTo(d);c.height+=h;break;case"over":A.css({marginLeft:G.padding,width:c.width-(G.padding*2),bottom:G.padding}).appendTo(d);break;case"float":A.css("left",parseInt((A.width()-c.width-40)/2,10)*-1).appendTo(M);break;default:A.css({width:c.width-(G.padding*2),paddingLeft:G.padding,paddingRight:G.padding}).appendTo(M);break}A.hide()},g=function(){if(G.enableEscapeButton||G.enableKeyboardNav){B(document).bind("keydown.fb",function(V){if(V.keyCode==27&&G.enableEscapeButton){V.preventDefault();B.fancybox.close()}else{if((V.keyCode==37||V.keyCode==39)&&G.enableKeyboardNav&&V.target.tagName!=="INPUT"&&V.target.tagName!=="TEXTAREA"&&V.target.tagName!=="SELECT"){V.preventDefault();B.fancybox[V.keyCode==37?"prev":"next"]()}}})}if(!G.showNavArrows){O.hide();z.hide();return}if((G.cyclic&&y.length>1)||e!==0){O.show()}if((G.cyclic&&y.length>1)||e!=(y.length-1)){z.show()}},v=function(){if(!B.support.opacity){m.get(0).style.removeAttribute("filter");M.get(0).style.removeAttribute("filter")}if(H.autoDimensions){m.css("height","auto")}M.css("height","auto");if(t&&t.length){A.show()}if(G.showCloseButton){J.show()}g();if(G.hideOnContentClick){m.bind("click",B.fancybox.close)}if(G.hideOnOverlayClick){Q.bind("click",B.fancybox.close)}B(window).bind("resize.fb",B.fancybox.resize);if(G.centerOnScroll){B(window).bind("scroll.fb",B.fancybox.center)}if(G.type=="iframe"){B('<iframe id="fancybox-frame" name="fancybox-frame'+new Date().getTime()+'" frameborder="0" hspace="0" '+(B.browser.msie?'allowtransparency="true""':"")+' scrolling="'+H.scrolling+'" src="'+G.href+'"></iframe>').appendTo(m)}M.show();P=false;B.fancybox.center();G.onComplete(y,e,G);K()},K=function(){var V,W;if((y.length-1)>e){V=y[e+1].href;if(typeof V!=="undefined"&&V.match(i)){W=new Image();W.src=V}}if(e>0){V=y[e-1].href;if(typeof V!=="undefined"&&V.match(i)){W=new Image();W.src=V}}},U=function(W){var V={width:parseInt(b.width+(c.width-b.width)*W,10),height:parseInt(b.height+(c.height-b.height)*W,10),top:parseInt(b.top+(c.top-b.top)*W,10),left:parseInt(b.left+(c.left-b.left)*W,10)};if(typeof c.opacity!=="undefined"){V.opacity=W<0.5?0.5:W}M.css(V);m.css({width:V.width-G.padding*2,height:V.height-(h*W)-G.padding*2})},u=function(){return[B(window).width()-(G.margin*2),B(window).height()-(G.margin*2),B(document).scrollLeft()+G.margin,B(document).scrollTop()+G.margin]},R=function(){var V=u(),Z={},W=G.autoScale,X=G.padding*2,Y;if(G.width.toString().indexOf("%")>-1){Z.width=parseInt((V[0]*parseFloat(G.width))/100,10)}else{Z.width=G.width+X}if(G.height.toString().indexOf("%")>-1){Z.height=parseInt((V[1]*parseFloat(G.height))/100,10)}else{Z.height=G.height+X}if(W&&(Z.width>V[0]||Z.height>V[1])){if(H.type=="image"||H.type=="swf"){Y=(G.width)/(G.height);if((Z.width)>V[0]){Z.width=V[0];Z.height=parseInt(((Z.width-X)/Y)+X,10)}if((Z.height)>V[1]){Z.height=V[1];Z.width=parseInt(((Z.height-X)*Y)+X,10)}}else{Z.width=Math.min(Z.width,V[0]);Z.height=Math.min(Z.height,V[1])}}Z.top=parseInt(Math.max(V[3]-20,V[3]+((V[1]-Z.height-40)*0.5)),10);Z.left=parseInt(Math.max(V[2]-20,V[2]+((V[0]-Z.width-40)*0.5)),10);return Z},q=function(V){var W=V.offset();W.top+=parseInt(V.css("paddingTop"),10)||0;W.left+=parseInt(V.css("paddingLeft"),10)||0;W.top+=parseInt(V.css("border-top-width"),10)||0;W.left+=parseInt(V.css("border-left-width"),10)||0;W.width=V.width();W.height=V.height();return W},I=function(){var Y=H.orig?B(H.orig):false,X={},W,V;if(Y&&Y.length){W=q(Y);X={width:W.width+(G.padding*2),height:W.height+(G.padding*2),top:W.top-G.padding-20,left:W.left-G.padding-20}}else{V=u();X={width:G.padding*2,height:G.padding*2,top:parseInt(V[3]+V[1]*0.5,10),left:parseInt(V[2]+V[0]*0.5,10)}}return X},a=function(){if(!T.is(":visible")){clearInterval(p);return}B("div",T).css("top",(N*-40)+"px");N=(N+1)%12};B.fn.fancybox=function(V){if(!B(this).length){return this}B(this).data("fancybox",B.extend({},V,(B.metadata?B(this).metadata():{}))).unbind("click.fb").bind("click.fb",function(X){X.preventDefault();if(P){return}P=true;B(this).blur();j=[];C=0;var W=B(this).attr("rel")||"";if(!W||W==""||W==="nofollow"){j.push(this)}else{j=B("a[rel="+W+"], area[rel="+W+"]");C=j.index(this)}w();return});return this};B.fancybox=function(Y){var X;if(P){return}P=true;X=typeof arguments[1]!=="undefined"?arguments[1]:{};j=[];C=parseInt(X.index,10)||0;if(B.isArray(Y)){for(var W=0,V=Y.length;W<V;W++){if(typeof Y[W]=="object"){B(Y[W]).data("fancybox",B.extend({},X,Y[W]))}else{Y[W]=B({}).data("fancybox",B.extend({content:Y[W]},X))}}j=jQuery.merge(j,Y)}else{if(typeof Y=="object"){B(Y).data("fancybox",B.extend({},X,Y))}else{Y=B({}).data("fancybox",B.extend({content:Y},X))}j.push(Y)}if(C>j.length||C<0){C=0}w()};B.fancybox.showActivity=function(){clearInterval(p);T.show();p=setInterval(a,66)};B.fancybox.hideActivity=function(){T.hide()};B.fancybox.next=function(){return B.fancybox.pos(e+1)};B.fancybox.prev=function(){return B.fancybox.pos(e-1)};B.fancybox.pos=function(V){if(P){return}V=parseInt(V);j=y;if(V>-1&&V<y.length){C=V;w()}else{if(G.cyclic&&y.length>1){C=V>=y.length?0:y.length-1;w()}}return};B.fancybox.cancel=function(){if(P){return}P=true;B.event.trigger("fancybox-cancel");r();H.onCancel(j,C,H);P=false};B.fancybox.close=function(){if(P||M.is(":hidden")){return}P=true;if(G&&false===G.onCleanup(y,e,G)){P=false;return}r();B(J.add(O).add(z)).hide();B(m.add(Q)).unbind();B(window).unbind("resize.fb scroll.fb");B(document).unbind("keydown.fb");m.find("iframe").attr("src",S&&/^https/i.test(window.location.href||"")?"javascript:void(false)":"about:blank");if(G.titlePosition!=="inside"){A.empty()}M.stop();function V(){Q.fadeOut("fast");A.empty().hide();M.hide();B.event.trigger("fancybox-cleanup");m.empty();G.onClosed(y,e,G);y=H=[];e=C=0;G=H={};P=false}if(G.transitionOut=="elastic"){b=I();var W=M.position();c={top:W.top,left:W.left,width:M.width(),height:M.height()};if(G.opacity){c.opacity=1}A.empty().hide();s.prop=1;B(s).animate({prop:0},{duration:G.speedOut,easing:G.easingOut,step:U,complete:V})}else{M.fadeOut(G.transitionOut=="none"?0:G.speedOut,V)}};B.fancybox.resize=function(){if(Q.is(":visible")){Q.css("height",B(document).height())}B.fancybox.center(true)};B.fancybox.center=function(){var V,W;if(P){return}W=arguments[0]===true?1:0;V=u();if(!W&&(M.width()>V[0]||M.height()>V[1])){return}M.stop().animate({top:parseInt(Math.max(V[3]-20,V[3]+((V[1]-m.height()-40)*0.5)-G.padding)),left:parseInt(Math.max(V[2]-20,V[2]+((V[0]-m.width()-40)*0.5)-G.padding))},typeof arguments[0]=="number"?arguments[0]:200)};B.fancybox.init=function(){if(B("#fancybox-wrap").length){return}B("body").append(L=B('<div id="fancybox-tmp"></div>'),T=B('<div id="fancybox-loading"><div></div></div>'),Q=B('<div id="fancybox-overlay"></div>'),M=B('<div id="fancybox-wrap"></div>'));d=B('<div id="fancybox-outer"></div>').append('<div class="fancybox-bg" id="fancybox-bg-n"></div><div class="fancybox-bg" id="fancybox-bg-ne"></div><div class="fancybox-bg" id="fancybox-bg-e"></div><div class="fancybox-bg" id="fancybox-bg-se"></div><div class="fancybox-bg" id="fancybox-bg-s"></div><div class="fancybox-bg" id="fancybox-bg-sw"></div><div class="fancybox-bg" id="fancybox-bg-w"></div><div class="fancybox-bg" id="fancybox-bg-nw"></div>').appendTo(M);d.append(m=B('<div id="fancybox-content"></div>'),J=B('<a id="fancybox-close"></a>'),A=B('<div id="fancybox-title"></div>'),O=B('<a href="javascript:;" id="fancybox-left"><span class="fancy-ico" id="fancybox-left-ico"></span></a>'),z=B('<a href="javascript:;" id="fancybox-right"><span class="fancy-ico" id="fancybox-right-ico"></span></a>'));J.click(B.fancybox.close);T.click(B.fancybox.cancel);O.click(function(V){V.preventDefault();B.fancybox.prev()});z.click(function(V){V.preventDefault();B.fancybox.next()});if(B.fn.mousewheel){M.bind("mousewheel.fb",function(V,W){if(P){V.preventDefault()}else{if(B(V.target).get(0).clientHeight==0||B(V.target).get(0).scrollHeight===B(V.target).get(0).clientHeight){V.preventDefault();B.fancybox[W>0?"prev":"next"]()}}})}if(!B.support.opacity){M.addClass("fancybox-ie")}if(S){T.addClass("fancybox-ie6");M.addClass("fancybox-ie6");B('<iframe id="fancybox-hide-sel-frame" src="'+(/^https/i.test(window.location.href||"")?"javascript:void(false)":"about:blank")+'" scrolling="no" border="0" frameborder="0" tabindex="-1"></iframe>').prependTo(d)}};B.fn.fancybox.defaults={padding:10,margin:40,opacity:false,modal:false,cyclic:false,scrolling:"auto",width:560,height:340,autoScale:true,autoDimensions:true,centerOnScroll:false,ajax:{},swf:{wmode:"transparent"},hideOnOverlayClick:true,hideOnContentClick:false,overlayShow:true,overlayOpacity:0.7,overlayColor:"#777",titleShow:true,titlePosition:"float",titleFormat:null,titleFromAlt:false,transitionIn:"fade",transitionOut:"fade",speedIn:300,speedOut:300,changeSpeed:300,changeFade:"fast",easingIn:"swing",easingOut:"swing",showCloseButton:true,showNavArrows:true,enableEscapeButton:true,enableKeyboardNav:true,onStart:function(){},onCancel:function(){},onComplete:function(){},onCleanup:function(){},onClosed:function(){},onError:function(){}};B(document).ready(function(){B.fancybox.init()})})(jQuery);
ztfy.jqueryui
/ztfy.jqueryui-0.7.12.tar.gz/ztfy.jqueryui-0.7.12/src/ztfy/jqueryui/resources/js/jquery-fancybox-1.3.4.min.js
jquery-fancybox-1.3.4.min.js
(function(e,c){e.tools=e.tools||{version:"@VERSION"};var a=[],d={},j,m=[75,76,38,39,74,72,40,37],i={};j=e.tools.dateinput={conf:{format:"mm/dd/yy",formatter:"default",selectors:false,yearRange:[-5,5],lang:"en",offset:[0,0],speed:0,firstDay:0,min:c,max:c,trigger:0,toggle:0,editable:0,css:{prefix:"cal",input:"date",root:0,head:0,title:0,prev:0,next:0,month:0,year:0,days:0,body:0,weeks:0,today:0,current:0,week:0,off:0,sunday:0,focus:0,disabled:0,trigger:0}},addFormatter:function(p,q){d[p]=q},localize:function(q,p){e.each(p,function(r,s){p[r]=s.split(",")});i[q]=p}};j.localize("en",{months:"January,February,March,April,May,June,July,August,September,October,November,December",shortMonths:"Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec",days:"Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday",shortDays:"Sun,Mon,Tue,Wed,Thu,Fri,Sat"});function o(p,q){return new Date(p,q+1,0).getDate()}function h(q,p){q=""+q;p=p||2;while(q.length<p){q="0"+q}return q}var n=e("<a/>");function l(x,s,z,q){var v=s.getDate(),p=s.getDay(),t=s.getMonth(),w=s.getFullYear(),r={d:v,dd:h(v),ddd:i[q].shortDays[p],dddd:i[q].days[p],m:t+1,mm:h(t+1),mmm:i[q].shortMonths[t],mmmm:i[q].months[t],yy:String(w).slice(2),yyyy:w};var u=d[x](z,s,r,q);return n.html(u).html()}j.addFormatter("default",function(s,q,p,r){return s.replace(/d{1,4}|m{1,4}|yy(?:yy)?|"[^"]*"|'[^']*'/g,function(t){return t in p?p[t]:t})});j.addFormatter("prefixed",function(s,q,p,r){return s.replace(/%(d{1,4}|m{1,4}|yy(?:yy)?|"[^"]*"|'[^']*')/g,function(u,t){return t in p?p[t]:u})});function g(p){return parseInt(p,10)}function f(q,p){return q.getFullYear()===p.getFullYear()&&q.getMonth()==p.getMonth()&&q.getDate()==p.getDate()}function b(r){if(r===c){return}if(r.constructor==Date){return r}if(typeof r=="string"){var q=r.split("-");if(q.length==3){return new Date(g(q[0]),g(q[1])-1,g(q[2]))}if(!(/^-?\d+$/).test(r)){return}r=g(r)}var p=new Date;p.setDate(p.getDate()+r);return p}function k(y,v){var B=this,p=new Date,J=p.getFullYear(),x=v.css,P=i[v.lang],G=e("#"+x.root),S=G.find("#"+x.title),A,K,q,R,u,O,E=y.attr("data-value")||v.value||y.val(),H=y.attr("min")||v.min,I=y.attr("max")||v.max,N,F;if(H===0){H="0"}E=b(E)||p;H=b(H||new Date(J+v.yearRange[0],1,1));I=b(I||new Date(J+v.yearRange[1]+1,1,-1));if(!P){throw"Dateinput: invalid language: "+v.lang}if(y.attr("type")=="date"){var F=y.clone(),z=F.wrap("<div/>").parent().html(),M=e(z.replace(/type/i,"type=text data-orig-type"));if(v.value){M.val(v.value)}y.replaceWith(M);y=M}y.addClass(x.input);var Q=y.add(B);if(!G.length){G=e("<div><div><a/><div/><a/></div><div><div/><div/></div></div>").hide().css({position:"absolute"}).attr("id",x.root);G.children().eq(0).attr("id",x.head).end().eq(1).attr("id",x.body).children().eq(0).attr("id",x.days).end().eq(1).attr("id",x.weeks).end().end().end().find("a").eq(0).attr("id",x.prev).end().eq(1).attr("id",x.next);S=G.find("#"+x.head).find("div").attr("id",x.title);if(v.selectors){var r=e("<select/>").attr("id",x.month),w=e("<select/>").attr("id",x.year);S.html(r.add(w))}var s=G.find("#"+x.days);for(var L=0;L<7;L++){s.append(e("<span/>").text(P.shortDays[(L+v.firstDay)%7]))}e("body").append(G)}if(v.trigger){A=e("<a/>").attr("href","#").addClass(x.trigger).click(function(T){v.toggle?B.toggle():B.show();return T.preventDefault()}).insertAfter(y)}var t=G.find("#"+x.weeks);w=G.find("#"+x.year);r=G.find("#"+x.month);function D(U,T,V){E=U;R=U.getFullYear();u=U.getMonth();O=U.getDate();V||(V=e.Event("api"));if(V.type=="click"&&!e.browser.msie){y.focus()}V.type="beforeChange";Q.trigger(V,[U]);if(V.isDefaultPrevented()){return}y.val(l(T.formatter,U,T.format,T.lang));V.type="change";Q.trigger(V);y.data("date",U);B.hide(V)}function C(T){T.type="onShow";Q.trigger(T);e(document).on("keydown.d",function(X){if(X.ctrlKey){return true}var V=X.keyCode;if(V==8||V==46){y.val("");return B.hide(X)}if(V==27||V==9){return B.hide(X)}if(e(m).index(V)>=0){if(!N){B.show(X);return X.preventDefault()}var Y=e("#"+x.weeks+" a"),W=e("."+x.focus),U=Y.index(W);W.removeClass(x.focus);if(V==74||V==40){U+=7}else{if(V==75||V==38){U-=7}else{if(V==76||V==39){U+=1}else{if(V==72||V==37){U-=1}}}}if(U>41){B.addMonth();W=e("#"+x.weeks+" a:eq("+(U-42)+")")}else{if(U<0){B.addMonth(-1);W=e("#"+x.weeks+" a:eq("+(U+42)+")")}else{W=Y.eq(U)}}W.addClass(x.focus);return X.preventDefault()}if(V==34){return B.addMonth()}if(V==33){return B.addMonth(-1)}if(V==36){return B.today()}if(V==13){if(!e(X.target).is("select")){e("."+x.focus).click()}}return e([16,17,18,9]).index(V)>=0});e(document).on("click.d",function(V){var U=V.target;if(!e(U).parents("#"+x.root).length&&U!=y[0]&&(!A||U!=A[0])){B.hide(V)}})}e.extend(B,{show:function(T){if(y.attr("readonly")||y.attr("disabled")||N){return}T=T||e.Event();T.type="onBeforeShow";Q.trigger(T);if(T.isDefaultPrevented()){return}e.each(a,function(){this.hide()});N=true;r.off("change").change(function(){B.setValue(g(w.val()),g(e(this).val()))});w.off("change").change(function(){B.setValue(g(e(this).val()),g(r.val()))});K=G.find("#"+x.prev).off("click").click(function(V){if(!K.hasClass(x.disabled)){B.addMonth(-1)}return false});q=G.find("#"+x.next).off("click").click(function(V){if(!q.hasClass(x.disabled)){B.addMonth()}return false});B.setValue(E);var U=y.offset();if(/iPad/i.test(navigator.userAgent)){U.top-=e(window).scrollTop()}G.css({top:U.top+y.outerHeight({margins:true})+v.offset[0],left:U.left+v.offset[1]});if(v.speed){G.show(v.speed,function(){C(T)})}else{G.show();C(T)}return B},setValue:function(ac,aa,ae){var V=g(aa)>=-1?new Date(g(ac),g(aa),g(ae==c||isNaN(ae)?1:ae)):ac||E;if(V<H){V=H}else{if(V>I){V=I}}if(typeof ac=="string"){V=b(ac)}ac=V.getFullYear();aa=V.getMonth();ae=V.getDate();if(aa==-1){aa=11;ac--}else{if(aa==12){aa=0;ac++}}if(!N){D(V,v);return B}u=aa;R=ac;O=ae;var Y=new Date(ac,aa,1-v.firstDay),U=Y.getDay(),ag=o(ac,aa),ad=o(ac,aa-1),T;if(v.selectors){r.empty();e.each(P.months,function(ai,ah){if(H<new Date(ac,ai+1,1)&&I>new Date(ac,ai,0)){r.append(e("<option/>").html(ah).attr("value",ai))}});w.empty();var ab=p.getFullYear();for(var X=ab+v.yearRange[0];X<ab+v.yearRange[1];X++){if(H<new Date(X+1,0,1)&&I>new Date(X,0,0)){w.append(e("<option/>").text(X))}}r.val(aa);w.val(ac)}else{S.html(P.months[aa]+" "+ac)}t.empty();K.add(q).removeClass(x.disabled);for(var W=!U?-7:0,af,Z;W<(!U?35:42);W++){af=e("<a/>");if(W%7===0){T=e("<div/>").addClass(x.week);t.append(T)}if(W<U){af.addClass(x.off);Z=ad-U+W+1;V=new Date(ac,aa-1,Z)}else{if(W>=U+ag){af.addClass(x.off);Z=W-ag-U+1;V=new Date(ac,aa+1,Z)}else{Z=W-U+1;V=new Date(ac,aa,Z);if(f(E,V)){af.attr("id",x.current).addClass(x.focus)}else{if(f(p,V)){af.attr("id",x.today)}}}}if(H&&V<H){af.add(K).addClass(x.disabled)}if(I&&V>I){af.add(q).addClass(x.disabled)}af.attr("href","#"+Z).text(Z).data("date",V);T.append(af)}t.find("a").click(function(ai){var ah=e(this);if(!ah.hasClass(x.disabled)){e("#"+x.current).removeAttr("id");ah.attr("id",x.current);D(ah.data("date"),v,ai)}return false});if(x.sunday){t.find("."+x.week).each(function(){var ah=v.firstDay?7-v.firstDay:0;e(this).children().slice(ah,ah+1).addClass(x.sunday)})}return B},setMin:function(U,T){H=b(U);if(T&&E<H){B.setValue(H)}return B},setMax:function(U,T){I=b(U);if(T&&E>I){B.setValue(I)}return B},today:function(){return B.setValue(p)},addDay:function(T){return this.setValue(R,u,O+(T||1))},addMonth:function(T){var V=u+(T||1),U=o(R,V),W=O<=U?O:U;return this.setValue(R,V,W)},addYear:function(T){return this.setValue(R+(T||1),u,O)},destroy:function(){y.add(document).off("click.d keydown.d");G.add(A).remove();y.removeData("dateinput").removeClass(x.input);if(F){y.replaceWith(F)}},hide:function(T){if(N){T=e.Event();T.type="onHide";Q.trigger(T);if(T.isDefaultPrevented()){return}e(document).off("click.d keydown.d");G.hide();N=false}return B},toggle:function(){return B.isOpen()?B.hide():B.show()},getConf:function(){return v},getInput:function(){return y},getCalendar:function(){return G},getValue:function(T){return T?l(v.formatter,E,T,v.lang):E},isOpen:function(){return N}});e.each(["onBeforeShow","onShow","change","onHide"],function(U,T){if(e.isFunction(v[T])){e(B).on(T,v[T])}B[T]=function(V){if(V){e(B).on(T,V)}return B}});if(!v.editable){y.on("focus.d click.d",B.show).keydown(function(U){var T=U.keyCode;if(!N&&e(m).index(T)>=0){B.show(U);return U.preventDefault()}else{if(T==8||T==46){y.val("")}}return U.shiftKey||U.ctrlKey||U.altKey||T==9?true:U.preventDefault()})}if(b(y.val())){D(E,v)}}e.expr[":"].date=function(q){var p=q.getAttribute("type");return p&&p=="date"||!!e(q).data("dateinput")};e.fn.dateinput=function(p){if(this.data("dateinput")){return this}p=e.extend(true,{},j.conf,p);e.each(p.css,function(r,s){if(!s&&r!="prefix"){p.css[r]=(p.css.prefix||"")+(s||r)}});var q;this.each(function(){var s=new k(e(this),p);a.push(s);var r=s.getInput().data("dateinput",s);q=q?q.add(r):r});return q?q:this}})(jQuery);(function(c){c.tools=c.tools||{version:"@VERSION"};c.tools.overlay={addEffect:function(e,f,g){b[e]=[f,g]},conf:{close:null,closeOnClick:true,closeOnEsc:true,closeSpeed:"fast",effect:"default",fixed:!c.browser.msie||c.browser.version>6,left:"center",load:false,mask:null,oneInstance:true,speed:"normal",target:null,top:"10%"}};var d=[],b={};c.tools.overlay.addEffect("default",function(h,g){var f=this.getConf(),e=c(window);if(!f.fixed){h.top+=e.scrollTop();h.left+=e.scrollLeft()}h.position=f.fixed?"fixed":"absolute";this.getOverlay().css(h).fadeIn(f.speed,g)},function(e){this.getOverlay().fadeOut(this.getConf().closeSpeed,e)});function a(h,m){var o=this,f=h.add(o),n=c(window),k,j,i,e=c.tools.expose&&(m.mask||m.expose),l=Math.random().toString().slice(10);if(e){if(typeof e=="string"){e={color:e}}e.closeOnClick=e.closeOnEsc=false}var g=m.target||h.attr("rel");j=g?c(g):null||h;if(!j.length){throw"Could not find Overlay: "+g}if(h&&h.index(j)==-1){h.click(function(p){o.load(p);return p.preventDefault()})}c.extend(o,{load:function(u){if(o.isOpened()){return o}var r=b[m.effect];if(!r){throw'Overlay: cannot find effect : "'+m.effect+'"'}if(m.oneInstance){c.each(d,function(){this.close(u)})}u=u||c.Event();u.type="onBeforeLoad";f.trigger(u);if(u.isDefaultPrevented()){return o}i=true;if(e){c(j).expose(e)}var t=m.top,s=m.left,p=j.outerWidth({margin:true}),q=j.outerHeight({margin:true});if(typeof t=="string"){t=t=="center"?Math.max((n.height()-q)/2,0):parseInt(t,10)/100*n.height()}if(s=="center"){s=Math.max((n.width()-p)/2,0)}r[0].call(o,{top:t,left:s},function(){if(i){u.type="onLoad";f.trigger(u)}});if(e&&m.closeOnClick){c.mask.getMask().one("click",o.close)}if(m.closeOnClick){c(document).on("click."+l,function(v){if(!c(v.target).parents(j).length){o.close(v)}})}if(m.closeOnEsc){c(document).on("keydown."+l,function(v){if(v.keyCode==27){o.close(v)}})}return o},close:function(p){if(!o.isOpened()){return o}p=p||c.Event();p.type="onBeforeClose";f.trigger(p);if(p.isDefaultPrevented()){return}i=false;b[m.effect][1].call(o,function(){p.type="onClose";f.trigger(p)});c(document).off("click."+l+" keydown."+l);if(e){c.mask.close()}return o},getOverlay:function(){return j},getTrigger:function(){return h},getClosers:function(){return k},isOpened:function(){return i},getConf:function(){return m}});c.each("onBeforeLoad,onStart,onLoad,onBeforeClose,onClose".split(","),function(q,p){if(c.isFunction(m[p])){c(o).on(p,m[p])}o[p]=function(r){if(r){c(o).on(p,r)}return o}});k=j.find(m.close||".close");if(!k.length&&!m.close){k=c('<a class="close"></a>');j.prepend(k)}k.click(function(p){o.close(p)});if(m.load){o.load()}}c.fn.overlay=function(e){var f=this.data("overlay");if(f){return f}if(c.isFunction(e)){e={onBeforeLoad:e}}e=c.extend(true,{},c.tools.overlay.conf,e);this.each(function(){f=new a(c(this),e);d.push(f);c(this).data("overlay",f)});return e.api?f:this}})(jQuery);(function(e){var c=e.tools.overlay,a=e(window);e.extend(c.conf,{start:{top:null,left:null},fadeInSpeed:"fast",zIndex:9999});function d(g){var h=g.offset();return{top:h.top+g.height()/2,left:h.left+g.width()/2}}var f=function(r,q){var k=this.getOverlay(),o=this.getConf(),i=this.getTrigger(),s=this,t=k.outerWidth({margin:true}),m=k.data("img"),n=o.fixed?"fixed":"absolute";if(!m){var l=k.css("backgroundImage");if(!l){throw"background-image CSS property not set for overlay"}l=l.slice(l.indexOf("(")+1,l.indexOf(")")).replace(/\"/g,"");k.css("backgroundImage","none");m=e('<img src="'+l+'"/>');m.css({border:0,display:"none"}).width(t);e("body").append(m);k.data("img",m)}var j=o.start.top||Math.round(a.height()/2),h=o.start.left||Math.round(a.width()/2);if(i){var g=d(i);j=g.top;h=g.left}if(o.fixed){j-=a.scrollTop();h-=a.scrollLeft()}else{r.top+=a.scrollTop();r.left+=a.scrollLeft()}m.css({position:"absolute",top:j,left:h,width:0,zIndex:o.zIndex}).show();r.position=n;k.css(r);m.animate({top:r.top,left:r.left,width:t},o.speed,function(){k.css("zIndex",o.zIndex+1).fadeIn(o.fadeInSpeed,function(){if(s.isOpened()&&!e(this).index(k)){q.call()}else{k.hide()}})}).css("position",n)};var b=function(g){var k=this.getOverlay().hide(),j=this.getConf(),i=this.getTrigger(),h=k.data("img"),l={top:j.start.top,left:j.start.left,width:0};if(i){e.extend(l,d(i))}if(j.fixed){h.css({position:"absolute"}).animate({top:"+="+a.scrollTop(),left:"+="+a.scrollLeft()},0)}h.animate(l,j.closeSpeed,g)};c.addEffect("apple",f,b)})(jQuery);(function(f){f.tools=f.tools||{version:"@VERSION"};var d;d=f.tools.rangeinput={conf:{min:0,max:100,step:"any",steps:0,value:0,precision:undefined,vertical:0,keyboard:true,progress:false,speed:100,css:{input:"range",slider:"slider",progress:"progress",handle:"handle"}}};var h,a;f.fn.drag=function(i){document.ondragstart=function(){return false};i=f.extend({x:true,y:true,drag:true},i);h=h||f(document).on("mousedown mouseup",function(m){var k=f(m.target);if(m.type=="mousedown"&&k.data("drag")){var n=k.position(),j=m.pageX-n.left,l=m.pageY-n.top,o=true;h.on("mousemove.drag",function(r){var p=r.pageX-j,s=r.pageY-l,q={};if(i.x){q.left=p}if(i.y){q.top=s}if(o){k.trigger("dragStart");o=false}if(i.drag){k.css(q)}k.trigger("drag",[s,p]);a=k});m.preventDefault()}else{try{if(a){a.trigger("dragEnd")}}finally{h.off("mousemove.drag");a=null}}});return this.data("drag",true)};function b(j,i){var k=Math.pow(10,i);return Math.round(j*k)/k}function g(l,j){var i=parseInt(l.css(j),10);if(i){return i}var k=l[0].currentStyle;return k&&k.width&&parseInt(k.width,10)}function c(i){var j=i.data("events");return j&&j.onSlide}function e(r,p){var u=this,q=p.css,w=f("<div><div/><a href='#'/></div>").data("rangeinput",u),k,v,l,y,m;r.before(w);var C=w.addClass(q.slider).find("a").addClass(q.handle),o=w.find("div").addClass(q.progress);f.each("min,max,step,value".split(","),function(F,E){var G=r.attr(E);if(parseFloat(G)){p[E]=parseFloat(G,10)}});var t=p.max-p.min,n=p.step=="any"?0:p.step,z=p.precision;if(z===undefined){z=n.toString().split(".");z=z.length===2?z[1].length:0}if(r.attr("type")=="range"){var s=r.clone().wrap("<div/>").parent().html(),A=f(s.replace(/type/i,"type=text data-orig-type"));A.val(p.value);r.replaceWith(A);r=A}r.addClass(q.input);var D=f(u).add(r),j=true;function i(F,E,J,H){if(J===undefined){J=E/y*t}else{if(H){J-=p.min}}if(n){J=Math.round(J/n)*n}if(E===undefined||n){E=J*y/t}if(isNaN(J)){return u}E=Math.max(0,Math.min(E,y));J=E/y*t;if(H||!k){J+=p.min}if(k){if(H){E=y-E}else{J=p.max-J}}J=b(J,z);var I=F.type=="click";if(j&&v!==undefined&&!I){F.type="onSlide";D.trigger(F,[J,E]);if(F.isDefaultPrevented()){return u}}var G=I?p.speed:0,K=I?function(){F.type="change";D.trigger(F,[J])}:null;if(k){C.animate({top:E},G,K);if(p.progress){o.animate({height:y-E+C.height()/2},G)}}else{C.animate({left:E},G,K);if(p.progress){o.animate({width:E+C.width()/2},G)}}v=J;m=E;r.val(J);return u}f.extend(u,{getValue:function(){return v},setValue:function(F,E){x();return i(E||f.Event("api"),undefined,F,true)},getConf:function(){return p},getProgress:function(){return o},getHandle:function(){return C},getInput:function(){return r},step:function(F,G){G=G||f.Event();var E=p.step=="any"?1:p.step;u.setValue(v+E*(F||1),G)},stepUp:function(E){return u.step(E||1)},stepDown:function(E){return u.step(-E||-1)}});f.each("onSlide,change".split(","),function(F,E){if(f.isFunction(p[E])){f(u).on(E,p[E])}u[E]=function(G){if(G){f(u).on(E,G)}return u}});C.drag({drag:false}).on("dragStart",function(){x();j=c(f(u))||c(r)}).on("drag",function(F,G,E){if(r.is(":disabled")){return false}i(F,k?G:E)}).on("dragEnd",function(E){if(!E.isDefaultPrevented()){E.type="change";D.trigger(E,[v])}}).click(function(E){return E.preventDefault()});w.click(function(F){if(r.is(":disabled")||F.target==C[0]){return F.preventDefault()}x();var E=k?C.height()/2:C.width()/2;i(F,k?y-l-E+F.pageY:F.pageX-l-E)});if(p.keyboard){r.keydown(function(G){if(r.attr("readonly")){return}var F=G.keyCode,E=f([75,76,38,33,39]).index(F)!=-1,H=f([74,72,40,34,37]).index(F)!=-1;if((E||H)&&!(G.shiftKey||G.altKey||G.ctrlKey)){if(E){u.step(F==33?10:1,G)}else{if(H){u.step(F==34?-10:-1,G)}}return G.preventDefault()}})}r.blur(function(E){var F=f(this).val();if(F!==v){u.setValue(F,E)}});f.extend(r[0],{stepUp:u.stepUp,stepDown:u.stepDown});function x(){k=p.vertical||g(w,"height")>g(w,"width");if(k){y=g(w,"height")-g(C,"height");l=w.offset().top+y}else{y=g(w,"width")-g(C,"width");l=w.offset().left}}function B(){x();u.setValue(p.value!==undefined?p.value:p.min)}B();if(!y){f(window).load(B)}}f.expr[":"].range=function(j){var i=j.getAttribute("type");return i&&i=="range"||!!f(j).filter("input").data("rangeinput")};f.fn.rangeinput=function(i){if(this.data("rangeinput")){return this}i=f.extend(true,{},d.conf,i);var j;this.each(function(){var l=new e(f(this),f.extend(true,{},i));var k=l.getInput().data("rangeinput",l);j=j?j.add(k):k});return j?j:this}})(jQuery);(function(b){b.tools=b.tools||{version:"@VERSION"};b.tools.scrollable={conf:{activeClass:"active",circular:false,clonedClass:"cloned",disabledClass:"disabled",easing:"swing",initialIndex:0,item:"> *",items:".items",keyboard:true,mousewheel:false,next:".next",prev:".prev",size:1,speed:400,vertical:false,touch:true,wheelSpeed:0}};function d(i,g){var f=parseInt(i.css(g),10);if(f){return f}var h=i[0].currentStyle;return h&&h.width&&parseInt(h.width,10)}function e(f,h){var g=b(h);return g.length<2?g:f.parent().find(h)}var c;function a(q,o){var r=this,g=q.add(r),f=q.children(),m=0,i=o.vertical;if(!c){c=r}if(f.length>1){f=b(o.items,q)}if(o.size>1){o.circular=false}b.extend(r,{getConf:function(){return o},getIndex:function(){return m},getSize:function(){return r.getItems().size()},getNaviButtons:function(){return h.add(k)},getRoot:function(){return q},getItemWrap:function(){return f},getItems:function(){return f.find(o.item).not("."+o.clonedClass)},move:function(t,s){return r.seekTo(m+t,s)},next:function(s){return r.move(o.size,s)},prev:function(s){return r.move(-o.size,s)},begin:function(s){return r.seekTo(0,s)},end:function(s){return r.seekTo(r.getSize()-1,s)},focus:function(){c=r;return r},addItem:function(s){s=b(s);if(!o.circular){f.append(s);k.removeClass("disabled")}else{f.children().last().before(s);f.children().first().replaceWith(s.clone().addClass(o.clonedClass))}g.trigger("onAddItem",[s]);return r},seekTo:function(s,x,u){if(!s.jquery){s*=1}if(o.circular&&s===0&&m==-1&&x!==0){return r}if(!o.circular&&s<0||s>r.getSize()||s<-1){return r}var v=s;if(s.jquery){s=r.getItems().index(s)}else{v=r.getItems().eq(s)}var w=b.Event("onBeforeSeek");if(!u){g.trigger(w,[s,x]);if(w.isDefaultPrevented()||!v.length){return r}}var t=i?{top:-v.position().top}:{left:-v.position().left};m=s;c=r;if(x===undefined){x=o.speed}f.animate(t,x,o.easing,u||function(){g.trigger("onSeek",[s])});return r}});b.each(["onBeforeSeek","onSeek","onAddItem"],function(t,s){if(b.isFunction(o[s])){b(r).on(s,o[s])}r[s]=function(u){if(u){b(r).on(s,u)}return r}});if(o.circular){var n=r.getItems().slice(-1).clone().prependTo(f),l=r.getItems().eq(1).clone().appendTo(f);n.add(l).addClass(o.clonedClass);r.onBeforeSeek(function(u,s,t){if(u.isDefaultPrevented()){return}if(s==-1){r.seekTo(n,t,function(){r.end(0)});return u.preventDefault()}else{if(s==r.getSize()){r.seekTo(l,t,function(){r.begin(0)})}}});var p=q.parents().add(q).filter(function(){if(b(this).css("display")==="none"){return true}});if(p.length){p.show();r.seekTo(0,0,function(){});p.hide()}else{r.seekTo(0,0,function(){})}}var h=e(q,o.prev).click(function(s){s.stopPropagation();r.prev()}),k=e(q,o.next).click(function(s){s.stopPropagation();r.next()});if(!o.circular){r.onBeforeSeek(function(t,s){setTimeout(function(){if(!t.isDefaultPrevented()){h.toggleClass(o.disabledClass,s<=0);k.toggleClass(o.disabledClass,s>=r.getSize()-1)}},1)});if(!o.initialIndex){h.addClass(o.disabledClass)}}if(r.getSize()<2){h.add(k).addClass(o.disabledClass)}if(o.mousewheel&&b.fn.mousewheel){q.mousewheel(function(s,t){if(o.mousewheel){r.move(t<0?1:-1,o.wheelSpeed||50);return false}})}if(o.touch){var j={};f[0].ontouchstart=function(u){var s=u.touches[0];j.x=s.clientX;j.y=s.clientY};f[0].ontouchmove=function(w){if(w.touches.length==1&&!f.is(":animated")){var v=w.touches[0],u=j.x-v.clientX,s=j.y-v.clientY;r[i&&s>0||!i&&u>0?"next":"prev"]();w.preventDefault()}}}if(o.keyboard){b(document).on("keydown.scrollable",function(s){if(!o.keyboard||s.altKey||s.ctrlKey||s.metaKey||b(s.target).is(":input")){return}if(o.keyboard!="static"&&c!=r){return}var t=s.keyCode;if(i&&(t==38||t==40)){r.move(t==38?-1:1);return s.preventDefault()}if(!i&&(t==37||t==39)){r.move(t==37?-1:1);return s.preventDefault()}})}if(o.initialIndex){r.seekTo(o.initialIndex,0,function(){})}}b.fn.scrollable=function(f){var g=this.data("scrollable");if(g){return g}f=b.extend({},b.tools.scrollable.conf,f);this.each(function(){g=new a(b(this),f);b(this).data("scrollable",g)});return f.api?g:this}})(jQuery);(function(b){var a=b.tools.scrollable;a.autoscroll={conf:{autoplay:true,interval:3000,autopause:true}};b.fn.autoscroll=function(d){if(typeof d=="number"){d={interval:d}}var e=b.extend({},a.autoscroll.conf,d),c;this.each(function(){var h=b(this).data("scrollable"),g=h.getRoot(),j,i=false;function f(){if(j){clearTimeout(j)}j=setTimeout(function(){h.next()},e.interval)}if(h){c=h}h.play=function(){if(j){return}i=false;g.on("onSeek",f);f()};h.pause=function(){j=clearTimeout(j);g.off("onSeek",f)};h.resume=function(){i||h.play()};h.stop=function(){i=true;h.pause()};if(e.autopause){g.add(h.getNaviButtons()).hover(h.pause,h.resume)}if(e.autoplay){h.play()}});return e.api?c:this}})(jQuery);(function(b){var a=b.tools.scrollable;a.navigator={conf:{navi:".navi",naviItem:null,activeClass:"active",indexed:false,idPrefix:null,history:false}};function c(d,f){var e=b(f);return e.length<2?e:d.parent().find(f)}b.fn.navigator=function(e){if(typeof e=="string"){e={navi:e}}e=b.extend({},a.navigator.conf,e);var d;this.each(function(){var g=b(this).data("scrollable"),j=e.navi.jquery?e.navi:c(g.getRoot(),e.navi),i=g.getNaviButtons(),m=e.activeClass,h=e.history&&!!history.pushState,n=g.getConf().size;if(g){d=g}g.getNaviButtons=function(){return i.add(j)};if(h){history.pushState({i:0},"");b(window).on("popstate",function(o){var p=o.originalEvent.state;if(p){g.seekTo(p.i)}})}function l(p,o,q){g.seekTo(o);q.preventDefault();if(h){history.pushState({i:o},"")}}function f(){return j.find(e.naviItem||"> *")}function k(o){var p=b("<"+(e.naviItem||"a")+"/>").click(function(q){l(b(this),o,q)});if(o===0){p.addClass(m)}if(e.indexed){p.text(o+1)}if(e.idPrefix){p.attr("id",e.idPrefix+o)}return p.appendTo(j)}if(f().length){f().each(function(o){b(this).click(function(p){l(b(this),o,p)})})}else{b.each(g.getItems(),function(o){if(o%n==0){k(o)}})}g.onBeforeSeek(function(p,o){setTimeout(function(){if(!p.isDefaultPrevented()){var q=o/n,r=f().eq(q);if(r.length){f().removeClass(m).eq(q).addClass(m)}}},1)});g.onAddItem(function(q,p){var o=g.getItems().index(p);if(o%n==0){k(o)}})});return e.api?d:this}})(jQuery);(function(e){e.tools=e.tools||{version:"@VERSION"};e.tools.tabs={conf:{tabs:"a",current:"current",onBeforeClick:null,onClick:null,effect:"default",initialEffect:false,initialIndex:0,event:"click",rotate:false,slideUpSpeed:400,slideDownSpeed:400,history:false},addEffect:function(f,g){d[f]=g}};var d={"default":function(g,f){this.getPanes().hide().eq(g).show();f.call()},fade:function(h,f){var g=this.getConf(),k=g.fadeOutSpeed,j=this.getPanes();if(k){j.fadeOut(k)}else{j.hide()}j.eq(h).fadeIn(g.fadeInSpeed,f)},slide:function(h,f){var g=this.getConf();this.getPanes().slideUp(g.slideUpSpeed);this.getPanes().eq(h).slideDown(g.slideDownSpeed,f)},ajax:function(g,f){this.getPanes().eq(0).load(this.getTabs().eq(g).attr("href"),f)}};var c,b;e.tools.tabs.addEffect("horizontal",function(h,f){if(c){return}var g=this.getPanes().eq(h),j=this.getCurrentPane();b||(b=this.getPanes().eq(0).width());c=true;g.show();j.animate({width:0},{step:function(i){g.css("width",b-i)},complete:function(){e(this).hide();f.call();c=false}});if(!j.length){f.call();c=false}});function a(f,k,i){var g=this,h=f.add(this),j=f.find(i.tabs),l=k.jquery?k:f.children(k),m;if(!j.length){j=f.children()}if(!l.length){l=f.parent().find(k)}if(!l.length){l=e(k)}e.extend(this,{click:function(n,s){var p=j.eq(n),r=!f.data("tabs");if(typeof n=="string"&&n.replace("#","")){p=j.filter('[href*="'+n.replace("#","")+'"]');n=Math.max(j.index(p),0)}if(i.rotate){var q=j.length-1;if(n<0){return g.click(q,s)}if(n>q){return g.click(0,s)}}if(!p.length){if(m>=0){return g}n=i.initialIndex;p=j.eq(n)}if(n===m){return g}s=s||e.Event();s.type="onBeforeClick";h.trigger(s,[n]);if(s.isDefaultPrevented()){return}var o=r?i.initialEffect&&i.effect||"default":i.effect;d[o].call(g,n,function(){m=n;s.type="onClick";h.trigger(s,[n])});j.removeClass(i.current);p.addClass(i.current);return g},getConf:function(){return i},getTabs:function(){return j},getPanes:function(){return l},getCurrentPane:function(){return l.eq(m)},getCurrentTab:function(){return j.eq(m)},getIndex:function(){return m},next:function(){return g.click(m+1)},prev:function(){return g.click(m-1)},destroy:function(){j.off(i.event).removeClass(i.current);l.find('a[href^="#"]').off("click.T");return g}});e.each("onBeforeClick,onClick".split(","),function(o,n){if(e.isFunction(i[n])){e(g).on(n,i[n])}g[n]=function(p){if(p){e(g).on(n,p)}return g}});if(i.history&&e.fn.history){e.tools.history.init(j);i.event="history"}j.each(function(n){e(this).on(i.event,function(o){g.click(n,o);return o.preventDefault()})});l.find('a[href^="#"]').on("click.T",function(n){g.click(e(this).attr("href"),n)});if(location.hash&&i.tabs=="a"&&f.find('[href="'+location.hash+'"]').length){g.click(location.hash)}else{if(i.initialIndex===0||i.initialIndex>0){g.click(i.initialIndex)}}}e.fn.tabs=function(g,f){var h=this.data("tabs");if(h){h.destroy();this.removeData("tabs")}if(e.isFunction(f)){f={onBeforeClick:f}}f=e.extend({},e.tools.tabs.conf,f);this.each(function(){h=new a(e(this),g,f);e(this).data("tabs",h)});return f.api?h:this}})(jQuery);(function(c){var a;a=c.tools.tabs.slideshow={conf:{next:".forward",prev:".backward",disabledClass:"disabled",autoplay:false,autopause:true,interval:3000,clickable:true,api:false}};function b(l,j){var o=this,f=l.add(this),k=l.data("tabs"),e,d=true;function i(q){var p=c(q);return p.length<2?p:l.parent().find(q)}var n=i(j.next).click(function(){k.next()});var m=i(j.prev).click(function(){k.prev()});function h(){e=setTimeout(function(){k.next()},j.interval)}c.extend(o,{getTabs:function(){return k},getConf:function(){return j},play:function(){if(e){return o}var p=c.Event("onBeforePlay");f.trigger(p);if(p.isDefaultPrevented()){return o}d=false;f.trigger("onPlay");f.on("onClick",h);h();return o},pause:function(){if(!e){return o}var p=c.Event("onBeforePause");f.trigger(p);if(p.isDefaultPrevented()){return o}e=clearTimeout(e);f.trigger("onPause");f.off("onClick",h);return o},resume:function(){d||o.play()},stop:function(){o.pause();d=true}});c.each("onBeforePlay,onPlay,onBeforePause,onPause".split(","),function(q,p){if(c.isFunction(j[p])){c(o).on(p,j[p])}o[p]=function(r){return c(o).on(p,r)}});if(j.autopause){k.getTabs().add(n).add(m).add(k.getPanes()).hover(o.pause,o.resume)}if(j.autoplay){o.play()}if(j.clickable){k.getPanes().click(function(){k.next()})}if(!k.getConf().rotate){var g=j.disabledClass;if(!k.getIndex()){m.addClass(g)}k.onBeforeClick(function(q,p){m.toggleClass(g,!p);n.toggleClass(g,p==k.getTabs().length-1)})}}c.fn.slideshow=function(d){var e=this.data("slideshow");if(e){return e}d=c.extend({},a.conf,d);this.each(function(){e=new b(c(this),d);c(this).data("slideshow",e)});return d.api?e:this}})(jQuery);(function(b){b.tools=b.tools||{version:"@VERSION"};var e;e=b.tools.expose={conf:{maskId:"exposeMask",loadSpeed:"slow",closeSpeed:"fast",closeOnClick:true,closeOnEsc:true,zIndex:9998,opacity:0.8,startOpacity:0,color:"#fff",onLoad:null,onClose:null}};function f(){if(b.browser.msie){var k=b(document).height(),j=b(window).height();return[window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth,k-j<20?j:k]}return[b(document).width(),b(document).height()]}function h(j){if(j){return j.call(b.mask)}}var i,d,c,a,g;b.mask={load:function(j,l){if(c){return this}if(typeof j=="string"){j={color:j}}j=j||a;a=j=b.extend(b.extend({},e.conf),j);i=b("#"+j.maskId);if(!i.length){i=b("<div/>").attr("id",j.maskId);b("body").append(i)}var k=f();i.css({position:"absolute",top:0,left:0,width:k[0],height:k[1],display:"none",opacity:j.startOpacity,zIndex:j.zIndex});if(j.color){i.css("backgroundColor",j.color)}if(h(j.onBeforeLoad)===false){return this}if(j.closeOnEsc){b(document).on("keydown.mask",function(m){if(m.keyCode==27){b.mask.close(m)}})}if(j.closeOnClick){i.on("click.mask",function(m){b.mask.close(m)})}b(window).on("resize.mask",function(){b.mask.fit()});if(l&&l.length){g=l.eq(0).css("zIndex");b.each(l,function(){var m=b(this);if(!/relative|absolute|fixed/i.test(m.css("position"))){m.css("position","relative")}});d=l.css({zIndex:Math.max(j.zIndex+1,g=="auto"?0:g)})}i.css({display:"block"}).fadeTo(j.loadSpeed,j.opacity,function(){b.mask.fit();h(j.onLoad);c="full"});c=true;return this},close:function(){if(c){if(h(a.onBeforeClose)===false){return this}i.fadeOut(a.closeSpeed,function(){h(a.onClose);if(d){d.css({zIndex:g})}c=false});b(document).off("keydown.mask");i.off("click.mask");b(window).off("resize.mask")}return this},fit:function(){if(c){var j=f();i.css({width:j[0],height:j[1]})}},getMask:function(){return i},isLoaded:function(j){return j?c=="full":c},getConf:function(){return a},getExposed:function(){return d}};b.fn.mask=function(j){b.mask.load(j);return this};b.fn.expose=function(j){b.mask.load(j,this);return this}})(jQuery);(function(){var h=document.all,j="http://www.adobe.com/go/getflashplayer",c=typeof jQuery=="function",e=/(\d+)[^\d]+(\d+)[^\d]*(\d*)/,b={width:"100%",height:"100%",id:"_"+(""+Math.random()).slice(9),allowfullscreen:true,allowscriptaccess:"always",quality:"high",version:[3,0],onFail:null,expressInstall:null,w3c:false,cachebusting:false};if(window.attachEvent){window.attachEvent("onbeforeunload",function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){}})}function i(m,l){if(l){for(var f in l){if(l.hasOwnProperty(f)){m[f]=l[f]}}}return m}function a(f,n){var m=[];for(var l in f){if(f.hasOwnProperty(l)){m[l]=n(f[l])}}return m}window.flashembed=function(f,m,l){if(typeof f=="string"){f=document.getElementById(f.replace("#",""))}if(!f){return}if(typeof m=="string"){m={src:m}}return new d(f,i(i({},b),m),l)};var g=i(window.flashembed,{conf:b,getVersion:function(){var m,f;try{f=navigator.plugins["Shockwave Flash"].description.slice(16)}catch(o){try{m=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");f=m&&m.GetVariable("$version")}catch(n){try{m=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");f=m&&m.GetVariable("$version")}catch(l){}}}f=e.exec(f);return f?[f[1],f[3]]:[0,0]},asString:function(l){if(l===null||l===undefined){return null}var f=typeof l;if(f=="object"&&l.push){f="array"}switch(f){case"string":l=l.replace(new RegExp('(["\\\\])',"g"),"\\$1");l=l.replace(/^\s?(\d+\.?\d*)%/,"$1pct");return'"'+l+'"';case"array":return"["+a(l,function(o){return g.asString(o)}).join(",")+"]";case"function":return'"function()"';case"object":var m=[];for(var n in l){if(l.hasOwnProperty(n)){m.push('"'+n+'":'+g.asString(l[n]))}}return"{"+m.join(",")+"}"}return String(l).replace(/\s/g," ").replace(/\'/g,'"')},getHTML:function(o,l){o=i({},o);var n='<object width="'+o.width+'" height="'+o.height+'" id="'+o.id+'" name="'+o.id+'"';if(o.cachebusting){o.src+=((o.src.indexOf("?")!=-1?"&":"?")+Math.random())}if(o.w3c||!h){n+=' data="'+o.src+'" type="application/x-shockwave-flash"'}else{n+=' classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'}n+=">";if(o.w3c||h){n+='<param name="movie" value="'+o.src+'" />'}o.width=o.height=o.id=o.w3c=o.src=null;o.onFail=o.version=o.expressInstall=null;for(var m in o){if(o[m]){n+='<param name="'+m+'" value="'+o[m]+'" />'}}var p="";if(l){for(var f in l){if(l[f]){var q=l[f];p+=f+"="+encodeURIComponent(/function|object/.test(typeof q)?g.asString(q):q)+"&"}}p=p.slice(0,-1);n+='<param name="flashvars" value=\''+p+"' />"}n+="</object>";return n},isSupported:function(f){return k[0]>f[0]||k[0]==f[0]&&k[1]>=f[1]}});var k=g.getVersion();function d(f,n,m){if(g.isSupported(n.version)){f.innerHTML=g.getHTML(n,m)}else{if(n.expressInstall&&g.isSupported([6,65])){f.innerHTML=g.getHTML(i(n,{src:n.expressInstall}),{MMredirectURL:location.href,MMplayerType:"PlugIn",MMdoctitle:document.title})}else{if(!f.innerHTML.replace(/\s/g,"")){f.innerHTML="<h2>Flash version "+n.version+" or greater is required</h2><h3>"+(k[0]>0?"Your version is "+k:"You have no flash plugin installed")+"</h3>"+(f.tagName=="A"?"<p>Click here to download latest version</p>":"<p>Download latest version from <a href='"+j+"'>here</a></p>");if(f.tagName=="A"){f.onclick=function(){location.href=j}}}if(n.onFail){var l=n.onFail.call(this);if(typeof l=="string"){f.innerHTML=l}}}}if(h){window[n.id]=document.getElementById(n.id)}i(this,{getRoot:function(){return f},getOptions:function(){return n},getConf:function(){return m},getApi:function(){return f.firstChild}})}if(c){jQuery.tools=jQuery.tools||{version:"@VERSION"};jQuery.tools.flashembed={conf:b};jQuery.fn.flashembed=function(l,f){return this.each(function(){jQuery(this).data("flashembed",flashembed(this,l,f))})}}})();(function(d){var f,c,b,a;d.tools=d.tools||{version:"@VERSION"};d.tools.history={init:function(g){if(a){return}if(d.browser.msie&&d.browser.version<"8"){if(!c){c=d("<iframe/>").attr("src","javascript:false;").hide().get(0);d("body").append(c);setInterval(function(){var i=c.contentWindow.document,j=i.location.hash;if(f!==j){d(window).trigger("hash",j)}},100);e(location.hash||"#")}}else{setInterval(function(){var i=location.hash;if(i!==f){d(window).trigger("hash",i)}},100)}b=!b?g:b.add(g);g.click(function(i){var h=d(this).attr("href");if(c){e(h)}if(h.slice(0,1)!="#"){location.href="#"+h;return i.preventDefault()}});a=true}};function e(g){if(g){var i=c.contentWindow.document;i.open().close();i.location.hash=g}}d(window).on("hash",function(i,g){if(g){b.filter(function(){var h=d(this).attr("href");return h==g||h==g.replace("#","")}).trigger("history",[g])}else{b.eq(0).trigger("history",[g])}f=g});d.fn.history=function(g){d.tools.history.init(this);return this.on("history",g)}})(jQuery);(function(a){a.fn.mousewheel=function(d){return this[d?"on":"trigger"]("wheel",d)};a.event.special.wheel={setup:function(){a.event.add(this,c,b,{})},teardown:function(){a.event.remove(this,c,b)}};var c=!a.browser.mozilla?"mousewheel":"DOMMouseScroll"+(a.browser.version<"1.9"?" mousemove":"");function b(d){switch(d.type){case"mousemove":return a.extend(d.data,{clientX:d.clientX,clientY:d.clientY,pageX:d.pageX,pageY:d.pageY});case"DOMMouseScroll":a.extend(d,d.data);if(d.originalEvent!==undefined){d.delta=-d.originalEvent.detail/3}else{d.delta=-d.detail/3}break;case"mousewheel":if(d.originalEvent instanceof WheelEvent){d.delta=d.originalEvent.wheelDelta/120}else{d.delta=d.wheelDelta/120}break}d.type="wheel";return a.event.handle.call(this,d,d.delta)}})(jQuery);(function(d){d.tools=d.tools||{version:"@VERSION"};d.tools.tooltip={conf:{effect:"toggle",fadeOutSpeed:"fast",predelay:0,delay:30,opacity:1,tip:0,fadeIE:false,position:["top","center"],offset:[0,0],relative:false,cancelDefault:true,events:{def:"mouseenter,mouseleave",input:"focus,blur",widget:"focus mouseenter,blur mouseleave",tooltip:"mouseenter,mouseleave"},layout:"<div/>",tipClass:"tooltip"},addEffect:function(e,g,f){c[e]=[g,f]}};var c={toggle:[function(e){var f=this.getConf(),g=this.getTip(),h=f.opacity;if(h<1){g.css({opacity:h})}g.show();e.call()},function(e){this.getTip().hide();e.call()}],fade:[function(e){var f=this.getConf();if(!d.browser.msie||f.fadeIE){this.getTip().fadeTo(f.fadeInSpeed,f.opacity,e)}else{this.getTip().show();e()}},function(e){var f=this.getConf();if(!d.browser.msie||f.fadeIE){this.getTip().fadeOut(f.fadeOutSpeed,e)}else{this.getTip().hide();e()}}]};function b(g,i,f){var k=f.relative?g.position().top:g.offset().top,j=f.relative?g.position().left:g.offset().left,l=f.position[0];k-=i.outerHeight()-f.offset[0];j+=g.outerWidth()+f.offset[1];if(/iPad/i.test(navigator.userAgent)){k-=d(window).scrollTop()}var e=i.outerHeight()+g.outerHeight();if(l=="center"){k+=e/2}if(l=="bottom"){k+=e}l=f.position[1];var h=i.outerWidth()+g.outerWidth();if(l=="center"){j-=h/2}if(l=="left"){j-=h}return{top:k,left:j}}function a(h,j){var r=this,g=h.add(r),o,f=0,q=0,m=h.attr("title"),i=h.attr("data-tooltip"),s=c[j.effect],n,l=h.is(":input"),e=l&&h.is(":checkbox, :radio, select, :button, :submit"),k=h.attr("type"),p=j.events[k]||j.events[l?(e?"widget":"input"):"def"];if(!s){throw'Nonexistent effect "'+j.effect+'"'}p=p.split(/,\s*/);if(p.length!=2){throw"Tooltip: bad events configuration for "+k}h.on(p[0],function(t){clearTimeout(f);if(j.predelay){q=setTimeout(function(){r.show(t)},j.predelay)}else{r.show(t)}}).on(p[1],function(t){clearTimeout(q);if(j.delay){f=setTimeout(function(){r.hide(t)},j.delay)}else{r.hide(t)}});if(m&&j.cancelDefault){h.removeAttr("title");h.data("title",m)}d.extend(r,{show:function(u){if(!o){if(i){o=d(i)}else{if(j.tip){o=d(j.tip).eq(0)}else{if(m){o=d(j.layout).addClass(j.tipClass).appendTo(document.body).hide().append(m)}else{o=h.next();if(!o.length){o=h.parent().next()}}}}if(!o.length){throw"Cannot find tooltip for "+h}}if(r.isShown()){return r}o.stop(true,true);var v=b(h,o,j);if(j.tip){o.html(h.data("title"))}u=d.Event();u.type="onBeforeShow";g.trigger(u,[v]);if(u.isDefaultPrevented()){return r}v=b(h,o,j);o.css({position:"absolute",top:v.top,left:v.left});n=true;s[0].call(r,function(){u.type="onShow";n="full";g.trigger(u)});var t=j.events.tooltip.split(/,\s*/);if(!o.data("__set")){o.off(t[0]).on(t[0],function(){clearTimeout(f);clearTimeout(q)});if(t[1]&&!h.is("input:not(:checkbox, :radio), textarea")){o.off(t[1]).on(t[1],function(w){if(w.relatedTarget!=h[0]){h.trigger(p[1].split(" ")[0])}})}if(!j.tip){o.data("__set",true)}}return r},hide:function(t){if(!o||!r.isShown()){return r}t=d.Event();t.type="onBeforeHide";g.trigger(t);if(t.isDefaultPrevented()){return}n=false;c[j.effect][1].call(r,function(){t.type="onHide";g.trigger(t)});return r},isShown:function(t){return t?n=="full":n},getConf:function(){return j},getTip:function(){return o},getTrigger:function(){return h}});d.each("onHide,onBeforeShow,onShow,onBeforeHide".split(","),function(u,t){if(d.isFunction(j[t])){d(r).on(t,j[t])}r[t]=function(v){if(v){d(r).on(t,v)}return r}})}d.fn.tooltip=function(e){var f=this.data("tooltip");if(f){return f}e=d.extend(true,{},d.tools.tooltip.conf,e);if(typeof e.position=="string"){e.position=e.position.split(/,?\s/)}this.each(function(){f=new a(d(this),e);d(this).data("tooltip",f)});return e.api?f:this}})(jQuery);(function(d){var c=d.tools.tooltip;c.dynamic={conf:{classNames:"top right bottom left"}};function b(h){var e=d(window);var g=e.width()+e.scrollLeft();var f=e.height()+e.scrollTop();return[h.offset().top<=e.scrollTop(),g<=h.offset().left+h.width(),f<=h.offset().top+h.height(),e.scrollLeft()>=h.offset().left]}function a(f){var e=f.length;while(e--){if(f[e]){return false}}return true}d.fn.dynamic=function(g){if(typeof g=="number"){g={speed:g}}g=d.extend({},c.dynamic.conf,g);var e=d.extend(true,{},g),f=g.classNames.split(/\s/),h;this.each(function(){var i=d(this).tooltip().onBeforeShow(function(n,o){var m=this.getTip(),l=this.getConf();if(!h){h=[l.position[0],l.position[1],l.offset[0],l.offset[1],d.extend({},l)]}d.extend(l,h[4]);l.position=[h[0],h[1]];l.offset=[h[2],h[3]];m.css({visibility:"hidden",position:"absolute",top:o.top,left:o.left}).show();var j=d.extend(true,{},e),k=b(m);if(!a(k)){if(k[2]){d.extend(l,j.top);l.position[0]="top";m.addClass(f[0])}if(k[3]){d.extend(l,j.right);l.position[1]="right";m.addClass(f[1])}if(k[0]){d.extend(l,j.bottom);l.position[0]="bottom";m.addClass(f[2])}if(k[1]){d.extend(l,j.left);l.position[1]="left";m.addClass(f[3])}if(k[0]||k[2]){l.offset[0]*=-1}if(k[1]||k[3]){l.offset[1]*=-1}}m.css({visibility:"visible"}).hide()});i.onBeforeShow(function(){var k=this.getConf(),j=this.getTip();setTimeout(function(){k.position=[h[0],h[1]];k.offset=[h[2],h[3]]},0)});i.onHide(function(){var j=this.getTip();j.removeClass(g.classNames)});ret=i});return g.api?ret:this}})(jQuery);(function(b){var a=b.tools.tooltip;b.extend(a.conf,{direction:"up",bounce:false,slideOffset:10,slideInSpeed:200,slideOutSpeed:200,slideFade:!b.browser.msie});var c={up:["-","top"],down:["+","top"],left:["-","left"],right:["+","left"]};a.addEffect("slide",function(d){var f=this.getConf(),g=this.getTip(),h=f.slideFade?{opacity:f.opacity}:{},e=c[f.direction]||c.up;h[e[1]]=e[0]+"="+f.slideOffset;if(f.slideFade){g.css({opacity:0})}g.show().animate(h,f.slideInSpeed,d)},function(e){var g=this.getConf(),i=g.slideOffset,h=g.slideFade?{opacity:0}:{},f=c[g.direction]||c.up;var d=""+f[0];if(g.bounce){d=d=="+"?"-":"+"}h[f[1]]=d+"="+i;this.getTip().animate(h,g.slideOutSpeed,function(){b(this).hide();e.call()})})})(jQuery);(function(f){f.tools=f.tools||{version:"@VERSION"};var j=/\[type=([a-z]+)\]/,h=/^-?[0-9]*(\.[0-9]+)?$/,c=f.tools.dateinput,a=/^([a-z0-9_\.\-\+]+)@([\da-z\.\-]+)\.([a-z\.]{2,6})$/i,g=/^(https?:\/\/)?[\da-z\.\-]+\.[a-z\.]{2,6}[#&+_\?\/\w \.\-=]*$/i,i;i=f.tools.validator={conf:{grouped:false,effect:"default",errorClass:"invalid",inputEvent:null,errorInputEvent:"keyup",formEvent:"submit",lang:"en",message:"<div/>",messageAttr:"data-message",messageClass:"error",offset:[0,0],position:"center right",singleError:false,speed:"normal"},messages:{"*":{en:"Please correct this value"}},localize:function(n,m){f.each(m,function(o,p){i.messages[o]=i.messages[o]||{};i.messages[o][n]=p})},localizeFn:function(m,n){i.messages[m]=i.messages[m]||{};f.extend(i.messages[m],n)},fn:function(n,o,m){if(f.isFunction(o)){m=o}else{if(typeof o=="string"){o={en:o}}this.messages[n.key||n]=o}var p=j.exec(n);if(p){n=e(p[1])}k.push([n,m])},addEffect:function(m,n,o){b[m]=[n,o]}};function l(o,n,q){n=f(n).first()||n;var t=o.offset().top,p=o.offset().left,r=q.position.split(/,?\s+/),s=r[0],u=r[1];t-=n.outerHeight()-q.offset[0];p+=o.outerWidth()+q.offset[1];if(/iPad/i.test(navigator.userAgent)){t-=f(window).scrollTop()}var v=n.outerHeight()+o.outerHeight();if(s=="center"){t+=v/2}if(s=="bottom"){t+=v}var m=o.outerWidth();if(u=="center"){p-=(m+n.outerWidth())/2}if(u=="left"){p-=m}return{top:t,left:p}}function e(n){function m(){return this.getAttribute("type")==n}m.key='[type="'+n+'"]';return m}var k=[],b={"default":[function(m){var n=this.getConf();f.each(m,function(p,q){var o=q.input;o.addClass(n.errorClass);var r=o.data("msg.el");if(!r){r=f(n.message).addClass(n.messageClass).appendTo(document.body);o.data("msg.el",r)}r.css({visibility:"hidden"}).find("p").remove();f.each(q.messages,function(u,t){f("<p/>").html(t).appendTo(r)});if(r.outerWidth()==r.parent().width()){r.add(r.find("p")).css({display:"inline"})}var s=l(o,r,n);r.css({visibility:"visible",position:"absolute",top:s.top,left:s.left}).fadeIn(n.speed)})},function(m){var n=this.getConf();m.removeClass(n.errorClass).each(function(){var o=f(this).data("msg.el");if(o){o.css({visibility:"hidden"})}})}]};f.each("email,url,number".split(","),function(n,m){f.expr[":"][m]=function(o){return o.getAttribute("type")===m}});f.fn.oninvalid=function(m){return this[m?"on":"trigger"]("OI",m)};i.fn(":email","Please enter a valid email address",function(n,m){return !m||a.test(m)});i.fn(":url","Please enter a valid URL",function(n,m){return !m||g.test(m)});i.fn(":number","Please enter a numeric value.",function(n,m){return h.test(m)});i.fn("[max]","Please enter a value no larger than $1",function(o,n){if(n===""||c&&o.is(":date")){return true}var m=o.attr("max");return parseFloat(n)<=parseFloat(m)?true:[m]});i.fn("[min]","Please enter a value of at least $1",function(o,m){if(m===""||c&&o.is(":date")){return true}var n=o.attr("min");return parseFloat(m)>=parseFloat(n)?true:[n]});i.fn("[required]","Please complete this mandatory field.",function(n,m){if(n.is(":checkbox")){return n.is(":checked")}return !!m});i.fn("[pattern]",function(n,m){return m===""||new RegExp("^"+n.attr("pattern")+"$").test(m)});i.fn(":radio","Please select an option.",function(n){var o=false;var m=f("[name='"+n.attr("name")+"']").each(function(p,q){if(f(q).is(":checked")){o=true}});return(o)?true:false});function d(m,r,p){var o=this,q=r.add(o);m=m.not(":button, :image, :reset, :submit");r.attr("novalidate","novalidate");function n(w,u,s){if(!p.grouped&&w.length){return}var v;if(s===false||f.isArray(s)){v=i.messages[u.key||u]||i.messages["*"];v=v[p.lang]||i.messages["*"].en;var t=v.match(/\$\d/g);if(t&&f.isArray(s)){f.each(t,function(x){v=v.replace(this,s[x])})}}else{v=s[p.lang]||s}w.push(v)}f.extend(o,{getConf:function(){return p},getForm:function(){return r},getInputs:function(){return m},reflow:function(){m.each(function(){var s=f(this),t=s.data("msg.el");if(t){var u=l(s,t,p);t.css({top:u.top,left:u.left})}});return o},invalidate:function(s,t){if(!t){var u=[];f.each(s,function(w,x){var v=m.filter("[name='"+w+"']");if(v.length){v.trigger("OI",[x]);u.push({input:v,messages:[x]})}});s=u;t=f.Event()}t.type="onFail";q.trigger(t,[s]);if(!t.isDefaultPrevented()){b[p.effect][0].call(o,s,t)}return o},reset:function(s){s=s||m;s.removeClass(p.errorClass).each(function(){var t=f(this).data("msg.el");if(t){t.remove();f(this).data("msg.el",null)}}).off(p.errorInputEvent+".v"||"");return o},destroy:function(){r.off(p.formEvent+".V reset.V");m.off(p.inputEvent+".V change.V");return o.reset()},checkValidity:function(t,w){t=t||m;t=t.not(":disabled");var v={};t=t.filter(function(){var x=f(this).attr("name");if(!v[x]){v[x]=true;return f(this)}});if(!t.length){return true}w=w||f.Event();w.type="onBeforeValidate";q.trigger(w,[t]);if(w.isDefaultPrevented()){return w.result}var s=[];t.each(function(){var z=[],x=f(this).data("messages",z),y=c&&x.is(":date")?"onHide.v":p.errorInputEvent+".v";x.off(y);f.each(k,function(){var C=this,A=C[0];if(x.filter(A).length){var B=C[1].call(o,x,x.val());if(B!==true){w.type="onBeforeFail";q.trigger(w,[x,A]);if(w.isDefaultPrevented()){return false}var D=x.attr(p.messageAttr);if(D){z=[D];return false}else{n(z,A,B)}}}});if(z.length){s.push({input:x,messages:z});x.trigger("OI",[z]);if(p.errorInputEvent){x.on(y,function(A){o.checkValidity(x,A)})}}if(p.singleError&&s.length){return false}});var u=b[p.effect];if(!u){throw'Validator: cannot find effect "'+p.effect+'"'}if(s.length){o.invalidate(s,w);return false}else{u[1].call(o,t,w);w.type="onSuccess";q.trigger(w,[t]);t.off(p.errorInputEvent+".v")}return true}});f.each("onBeforeValidate,onBeforeFail,onFail,onSuccess".split(","),function(t,s){if(f.isFunction(p[s])){f(o).on(s,p[s])}o[s]=function(u){if(u){f(o).on(s,u)}return o}});if(p.formEvent){r.on(p.formEvent+".V",function(s){if(!o.checkValidity(null,s)){return s.preventDefault()}s.target=r;s.type=p.formEvent})}r.on("reset.V",function(){o.reset()});if(m[0]&&m[0].validity){m.each(function(){this.oninvalid=function(){return false}})}if(r[0]){r[0].checkValidity=o.checkValidity}if(p.inputEvent){m.on(p.inputEvent+".V",function(s){o.checkValidity(f(this),s)})}m.filter(":checkbox, select").filter("[required]").on("change.V",function(t){var s=f(this);if(this.checked||(s.is("select")&&f(this).val())){b[p.effect][1].call(o,s,t)}});m.filter(":radio[required]").on("change.V",function(t){var s=f("[name='"+f(t.srcElement).attr("name")+"']");if((s!=null)&&(s.length!=0)){o.checkValidity(s,t)}});f(window).resize(function(){o.reflow()})}f.fn.validator=function(n){var m=this.data("validator");if(m){m.destroy();this.removeData("validator")}n=f.extend(true,{},i.conf,n);if(this.is("form")){return this.each(function(){var o=f(this);m=new d(o.find(":input"),o,n);o.data("validator",m)})}else{m=new d(this,this.eq(0).closest("form"),n);return this.data("validator",m)}}})(jQuery);
ztfy.jqueryui
/ztfy.jqueryui-0.7.12.tar.gz/ztfy.jqueryui-0.7.12/src/ztfy/jqueryui/resources/js/jquery-tools-1.2.7.min.js
jquery-tools-1.2.7.min.js
(function(d){d.tools=d.tools||{};d.tools.tabs={version:"1.0.4",conf:{tabs:"a",current:"current",onBeforeClick:null,onClick:null,effect:"default",initialIndex:0,event:"click",api:false,rotate:false},addEffect:function(e,f){c[e]=f}};var c={"default":function(f,e){this.getPanes().hide().eq(f).show();e.call()},fade:function(g,e){var f=this.getConf(),j=f.fadeOutSpeed,h=this.getPanes();if(j){h.fadeOut(j)}else{h.hide()}h.eq(g).fadeIn(f.fadeInSpeed,e)},slide:function(f,e){this.getPanes().slideUp(200);this.getPanes().eq(f).slideDown(400,e)},ajax:function(f,e){this.getPanes().eq(0).load(this.getTabs().eq(f).attr("href"),e)}};var b;d.tools.tabs.addEffect("horizontal",function(f,e){if(!b){b=this.getPanes().eq(0).width()}this.getCurrentPane().animate({width:0},function(){d(this).hide()});this.getPanes().eq(f).animate({width:b},function(){d(this).show();e.call()})});function a(g,h,f){var e=this,j=d(this),i;d.each(f,function(k,l){if(d.isFunction(l)){j.bind(k,l)}});d.extend(this,{click:function(k,n){var o=e.getCurrentPane();var l=g.eq(k);if(typeof k=="string"&&k.replace("#","")){l=g.filter("[href*="+k.replace("#","")+"]");k=Math.max(g.index(l),0)}if(f.rotate){var m=g.length-1;if(k<0){return e.click(m,n)}if(k>m){return e.click(0,n)}}if(!l.length){if(i>=0){return e}k=f.initialIndex;l=g.eq(k)}if(k===i){return e}n=n||d.Event();n.type="onBeforeClick";j.trigger(n,[k]);if(n.isDefaultPrevented()){return}c[f.effect].call(e,k,function(){n.type="onClick";j.trigger(n,[k])});n.type="onStart";j.trigger(n,[k]);if(n.isDefaultPrevented()){return}i=k;g.removeClass(f.current);l.addClass(f.current);return e},getConf:function(){return f},getTabs:function(){return g},getPanes:function(){return h},getCurrentPane:function(){return h.eq(i)},getCurrentTab:function(){return g.eq(i)},getIndex:function(){return i},next:function(){return e.click(i+1)},prev:function(){return e.click(i-1)},bind:function(k,l){j.bind(k,l);return e},onBeforeClick:function(k){return this.bind("onBeforeClick",k)},onClick:function(k){return this.bind("onClick",k)},unbind:function(k){j.unbind(k);return e}});g.each(function(k){d(this).bind(f.event,function(l){e.click(k,l);return false})});if(location.hash){e.click(location.hash)}else{if(f.initialIndex===0||f.initialIndex>0){e.click(f.initialIndex)}}h.find("a[href^=#]").click(function(k){e.click(d(this).attr("href"),k)})}d.fn.tabs=function(i,f){var g=this.eq(typeof f=="number"?f:0).data("tabs");if(g){return g}if(d.isFunction(f)){f={onBeforeClick:f}}var h=d.extend({},d.tools.tabs.conf),e=this.length;f=d.extend(h,f);this.each(function(l){var j=d(this);var k=j.find(f.tabs);if(!k.length){k=j.children()}var m=i.jquery?i:j.children(i);if(!m.length){m=e==1?d(i):j.parent().find(i)}g=new a(k,m,f);j.data("tabs",g)});return f.api?g:this}})(jQuery); (function(c){var d=[];c.tools=c.tools||{};c.tools.tooltip={version:"1.1.2",conf:{effect:"toggle",fadeOutSpeed:"fast",tip:null,predelay:0,delay:30,opacity:1,lazy:undefined,position:["top","center"],offset:[0,0],cancelDefault:true,relative:false,oneInstance:true,events:{def:"mouseover,mouseout",input:"focus,blur",widget:"focus mouseover,blur mouseout",tooltip:"mouseover,mouseout"},api:false},addEffect:function(e,g,f){b[e]=[g,f]}};var b={toggle:[function(e){var f=this.getConf(),g=this.getTip(),h=f.opacity;if(h<1){g.css({opacity:h})}g.show();e.call()},function(e){this.getTip().hide();e.call()}],fade:[function(e){this.getTip().fadeIn(this.getConf().fadeInSpeed,e)},function(e){this.getTip().fadeOut(this.getConf().fadeOutSpeed,e)}]};function a(f,g){var p=this,k=c(this);f.data("tooltip",p);var l=f.next();if(g.tip){l=c(g.tip);if(l.length>1){l=f.nextAll(g.tip).eq(0);if(!l.length){l=f.parent().nextAll(g.tip).eq(0)}}}function o(u){var t=g.relative?f.position().top:f.offset().top,s=g.relative?f.position().left:f.offset().left,v=g.position[0];t-=l.outerHeight()-g.offset[0];s+=f.outerWidth()+g.offset[1];var q=l.outerHeight()+f.outerHeight();if(v=="center"){t+=q/2}if(v=="bottom"){t+=q}v=g.position[1];var r=l.outerWidth()+f.outerWidth();if(v=="center"){s-=r/2}if(v=="left"){s-=r}return{top:t,left:s}}var i=f.is(":input"),e=i&&f.is(":checkbox, :radio, select, :button"),h=f.attr("type"),n=g.events[h]||g.events[i?(e?"widget":"input"):"def"];n=n.split(/,\s*/);if(n.length!=2){throw"Tooltip: bad events configuration for "+h}f.bind(n[0],function(r){if(g.oneInstance){c.each(d,function(){this.hide()})}var q=l.data("trigger");if(q&&q[0]!=this){l.hide().stop(true,true)}r.target=this;p.show(r);n=g.events.tooltip.split(/,\s*/);l.bind(n[0],function(){p.show(r)});if(n[1]){l.bind(n[1],function(){p.hide(r)})}});f.bind(n[1],function(q){p.hide(q)});if(!c.browser.msie&&!i&&!g.predelay){f.mousemove(function(){if(!p.isShown()){f.triggerHandler("mouseover")}})}if(g.opacity<1){l.css("opacity",g.opacity)}var m=0,j=f.attr("title");if(j&&g.cancelDefault){f.removeAttr("title");f.data("title",j)}c.extend(p,{show:function(r){if(r){f=c(r.target)}clearTimeout(l.data("timer"));if(l.is(":animated")||l.is(":visible")){return p}function q(){l.data("trigger",f);var t=o(r);if(g.tip&&j){l.html(f.data("title"))}r=r||c.Event();r.type="onBeforeShow";k.trigger(r,[t]);if(r.isDefaultPrevented()){return p}t=o(r);l.css({position:"absolute",top:t.top,left:t.left});var s=b[g.effect];if(!s){throw'Nonexistent effect "'+g.effect+'"'}s[0].call(p,function(){r.type="onShow";k.trigger(r)})}if(g.predelay){clearTimeout(m);m=setTimeout(q,g.predelay)}else{q()}return p},hide:function(r){clearTimeout(l.data("timer"));clearTimeout(m);if(!l.is(":visible")){return}function q(){r=r||c.Event();r.type="onBeforeHide";k.trigger(r);if(r.isDefaultPrevented()){return}b[g.effect][1].call(p,function(){r.type="onHide";k.trigger(r)})}if(g.delay&&r){l.data("timer",setTimeout(q,g.delay))}else{q()}return p},isShown:function(){return l.is(":visible, :animated")},getConf:function(){return g},getTip:function(){return l},getTrigger:function(){return f},bind:function(q,r){k.bind(q,r);return p},onHide:function(q){return this.bind("onHide",q)},onBeforeShow:function(q){return this.bind("onBeforeShow",q)},onShow:function(q){return this.bind("onShow",q)},onBeforeHide:function(q){return this.bind("onBeforeHide",q)},unbind:function(q){k.unbind(q);return p}});c.each(g,function(q,r){if(c.isFunction(r)){p.bind(q,r)}})}c.prototype.tooltip=function(e){var f=this.eq(typeof e=="number"?e:0).data("tooltip");if(f){return f}var g=c.extend(true,{},c.tools.tooltip.conf);if(c.isFunction(e)){e={onBeforeShow:e}}else{if(typeof e=="string"){e={tip:e}}}e=c.extend(true,g,e);if(typeof e.position=="string"){e.position=e.position.split(/,?\s/)}if(e.lazy!==false&&(e.lazy===true||this.length>20)){this.one("mouseover",function(h){f=new a(c(this),e);f.show(h);d.push(f)})}else{this.each(function(){f=new a(c(this),e);d.push(f)})}return e.api?f:this}})(jQuery); (function(b){b.tools=b.tools||{};b.tools.scrollable={version:"1.1.2",conf:{size:5,vertical:false,speed:400,keyboard:true,keyboardSteps:null,disabledClass:"disabled",hoverClass:null,clickable:true,activeClass:"active",easing:"swing",loop:false,items:".items",item:null,prev:".prev",next:".next",prevPage:".prevPage",nextPage:".nextPage",api:false}};var c;function a(o,m){var r=this,p=b(this),d=!m.vertical,e=o.children(),k=0,i;if(!c){c=r}b.each(m,function(s,t){if(b.isFunction(t)){p.bind(s,t)}});if(e.length>1){e=b(m.items,o)}function l(t){var s=b(t);return m.globalNav?s:o.parent().find(t)}o.data("finder",l);var f=l(m.prev),h=l(m.next),g=l(m.prevPage),n=l(m.nextPage);b.extend(r,{getIndex:function(){return k},getClickIndex:function(){var s=r.getItems();return s.index(s.filter("."+m.activeClass))},getConf:function(){return m},getSize:function(){return r.getItems().size()},getPageAmount:function(){return Math.ceil(this.getSize()/m.size)},getPageIndex:function(){return Math.ceil(k/m.size)},getNaviButtons:function(){return f.add(h).add(g).add(n)},getRoot:function(){return o},getItemWrap:function(){return e},getItems:function(){return e.children(m.item)},getVisibleItems:function(){return r.getItems().slice(k,k+m.size)},seekTo:function(s,w,t){if(s<0){s=0}if(k===s){return r}if(b.isFunction(w)){t=w}if(s>r.getSize()-m.size){return m.loop?r.begin():this.end()}var u=r.getItems().eq(s);if(!u.length){return r}var v=b.Event("onBeforeSeek");p.trigger(v,[s]);if(v.isDefaultPrevented()){return r}if(w===undefined||b.isFunction(w)){w=m.speed}function x(){if(t){t.call(r,s)}p.trigger("onSeek",[s])}if(d){e.animate({left:-u.position().left},w,m.easing,x)}else{e.animate({top:-u.position().top},w,m.easing,x)}c=r;k=s;v=b.Event("onStart");p.trigger(v,[s]);if(v.isDefaultPrevented()){return r}f.add(g).toggleClass(m.disabledClass,s===0);h.add(n).toggleClass(m.disabledClass,s>=r.getSize()-m.size);return r},move:function(u,t,s){i=u>0;return this.seekTo(k+u,t,s)},next:function(t,s){return this.move(1,t,s)},prev:function(t,s){return this.move(-1,t,s)},movePage:function(w,v,u){i=w>0;var s=m.size*w;var t=k%m.size;if(t>0){s+=(w>0?-t:m.size-t)}return this.move(s,v,u)},prevPage:function(t,s){return this.movePage(-1,t,s)},nextPage:function(t,s){return this.movePage(1,t,s)},setPage:function(t,u,s){return this.seekTo(t*m.size,u,s)},begin:function(t,s){i=false;return this.seekTo(0,t,s)},end:function(t,s){i=true;var u=this.getSize()-m.size;return u>0?this.seekTo(u,t,s):r},reload:function(){p.trigger("onReload");return r},focus:function(){c=r;return r},click:function(u){var v=r.getItems().eq(u),s=m.activeClass,t=m.size;if(u<0||u>=r.getSize()){return r}if(t==1){if(m.loop){return r.next()}if(u===0||u==r.getSize()-1){i=(i===undefined)?true:!i}return i===false?r.prev():r.next()}if(t==2){if(u==k){u--}r.getItems().removeClass(s);v.addClass(s);return r.seekTo(u,time,fn)}if(!v.hasClass(s)){r.getItems().removeClass(s);v.addClass(s);var x=Math.floor(t/2);var w=u-x;if(w>r.getSize()-t){w=r.getSize()-t}if(w!==u){return r.seekTo(w)}}return r},bind:function(s,t){p.bind(s,t);return r},unbind:function(s){p.unbind(s);return r}});b.each("onBeforeSeek,onStart,onSeek,onReload".split(","),function(s,t){r[t]=function(u){return r.bind(t,u)}});f.addClass(m.disabledClass).click(function(){r.prev()});h.click(function(){r.next()});n.click(function(){r.nextPage()});if(r.getSize()<m.size){h.add(n).addClass(m.disabledClass)}g.addClass(m.disabledClass).click(function(){r.prevPage()});var j=m.hoverClass,q="keydown."+Math.random().toString().substring(10);r.onReload(function(){if(j){r.getItems().hover(function(){b(this).addClass(j)},function(){b(this).removeClass(j)})}if(m.clickable){r.getItems().each(function(s){b(this).unbind("click.scrollable").bind("click.scrollable",function(t){if(b(t.target).is("a")){return}return r.click(s)})})}if(m.keyboard){b(document).unbind(q).bind(q,function(t){if(t.altKey||t.ctrlKey){return}if(m.keyboard!="static"&&c!=r){return}var u=m.keyboardSteps;if(d&&(t.keyCode==37||t.keyCode==39)){r.move(t.keyCode==37?-u:u);return t.preventDefault()}if(!d&&(t.keyCode==38||t.keyCode==40)){r.move(t.keyCode==38?-u:u);return t.preventDefault()}return true})}else{b(document).unbind(q)}});r.reload()}b.fn.scrollable=function(d){var e=this.eq(typeof d=="number"?d:0).data("scrollable");if(e){return e}var f=b.extend({},b.tools.scrollable.conf);d=b.extend(f,d);d.keyboardSteps=d.keyboardSteps||d.size;this.each(function(){e=new a(b(this),d);b(this).data("scrollable",e)});return d.api?e:this}})(jQuery); (function(c){c.tools=c.tools||{};c.tools.overlay={version:"1.1.2",addEffect:function(e,f,g){b[e]=[f,g]},conf:{top:"10%",left:"center",absolute:false,speed:"normal",closeSpeed:"fast",effect:"default",close:null,oneInstance:true,closeOnClick:true,closeOnEsc:true,api:false,expose:null,target:null}};var b={};c.tools.overlay.addEffect("default",function(e){this.getOverlay().fadeIn(this.getConf().speed,e)},function(e){this.getOverlay().fadeOut(this.getConf().closeSpeed,e)});var d=[];function a(g,k){var o=this,m=c(this),n=c(window),j,i,h,e=k.expose&&c.tools.expose.version;var f=k.target||g.attr("rel");i=f?c(f):null||g;if(!i.length){throw"Could not find Overlay: "+f}if(g&&g.index(i)==-1){g.click(function(p){o.load(p);return p.preventDefault()})}c.each(k,function(p,q){if(c.isFunction(q)){m.bind(p,q)}});c.extend(o,{load:function(u){if(o.isOpened()){return o}var r=b[k.effect];if(!r){throw'Overlay: cannot find effect : "'+k.effect+'"'}if(k.oneInstance){c.each(d,function(){this.close(u)})}u=u||c.Event();u.type="onBeforeLoad";m.trigger(u);if(u.isDefaultPrevented()){return o}h=true;if(e){i.expose().load(u)}var t=k.top;var s=k.left;var p=i.outerWidth({margin:true});var q=i.outerHeight({margin:true});if(typeof t=="string"){t=t=="center"?Math.max((n.height()-q)/2,0):parseInt(t,10)/100*n.height()}if(s=="center"){s=Math.max((n.width()-p)/2,0)}if(!k.absolute){t+=n.scrollTop();s+=n.scrollLeft()}i.css({top:t,left:s,position:"absolute"});u.type="onStart";m.trigger(u);r[0].call(o,function(){if(h){u.type="onLoad";m.trigger(u)}});if(k.closeOnClick){c(document).bind("click.overlay",function(w){if(!o.isOpened()){return}var v=c(w.target);if(v.parents(i).length>1){return}c.each(d,function(){this.close(w)})})}if(k.closeOnEsc){c(document).unbind("keydown.overlay").bind("keydown.overlay",function(v){if(v.keyCode==27){c.each(d,function(){this.close(v)})}})}return o},close:function(q){if(!o.isOpened()){return o}q=q||c.Event();q.type="onBeforeClose";m.trigger(q);if(q.isDefaultPrevented()){return}h=false;b[k.effect][1].call(o,function(){q.type="onClose";m.trigger(q)});var p=true;c.each(d,function(){if(this.isOpened()){p=false}});if(p){c(document).unbind("click.overlay").unbind("keydown.overlay")}return o},getContent:function(){return i},getOverlay:function(){return i},getTrigger:function(){return g},getClosers:function(){return j},isOpened:function(){return h},getConf:function(){return k},bind:function(p,q){m.bind(p,q);return o},unbind:function(p){m.unbind(p);return o}});c.each("onBeforeLoad,onStart,onLoad,onBeforeClose,onClose".split(","),function(p,q){o[q]=function(r){return o.bind(q,r)}});if(e){if(typeof k.expose=="string"){k.expose={color:k.expose}}c.extend(k.expose,{api:true,closeOnClick:k.closeOnClick,closeOnEsc:false});var l=i.expose(k.expose);l.onBeforeClose(function(p){o.close(p)});o.onClose(function(p){l.close(p)})}j=i.find(k.close||".close");if(!j.length&&!k.close){j=c('<div class="close"></div>');i.prepend(j)}j.click(function(p){o.close(p)})}c.fn.overlay=function(e){var f=this.eq(typeof e=="number"?e:0).data("overlay");if(f){return f}if(c.isFunction(e)){e={onBeforeLoad:e}}var g=c.extend({},c.tools.overlay.conf);e=c.extend(true,g,e);this.each(function(){f=new a(c(this),e);d.push(f);c(this).data("overlay",f)});return e.api?f:this}})(jQuery); (function(b){var a=b.tools.overlay;a.plugins=a.plugins||{};a.plugins.gallery={version:"1.0.0",conf:{imgId:"img",next:".next",prev:".prev",info:".info",progress:".progress",disabledClass:"disabled",activeClass:"active",opacity:0.8,speed:"slow",template:"<strong>${title}</strong> <span>Image ${index} of ${total}</span>",autohide:true,preload:true,api:false}};b.fn.gallery=function(d){var o=b.extend({},a.plugins.gallery.conf),m;b.extend(o,d);m=this.overlay();var r=this,j=m.getOverlay(),k=j.find(o.next),g=j.find(o.prev),e=j.find(o.info),c=j.find(o.progress),h=g.add(k).add(e).css({opacity:o.opacity}),s=m.getClosers(),l;function p(u){c.fadeIn();h.hide();s.hide();var t=u.attr("href");var v=new Image();v.onload=function(){c.fadeOut();var y=b("#"+o.imgId,j);if(!y.length){y=b("<img/>").attr("id",o.imgId).css("visibility","hidden");j.prepend(y)}y.attr("src",t).css("visibility","hidden");var z=v.width;var A=(b(window).width()-z)/2;l=r.index(r.filter("[href="+t+"]"));r.removeClass(o.activeClass).eq(l).addClass(o.activeClass);var w=o.disabledClass;h.removeClass(w);if(l===0){g.addClass(w)}if(l==r.length-1){k.addClass(w)}var B=o.template.replace("${title}",u.attr("title")||u.data("title")).replace("${index}",l+1).replace("${total}",r.length);var x=parseInt(e.css("paddingLeft"),10)+parseInt(e.css("paddingRight"),10);e.html(B).css({width:z-x});j.animate({width:z,height:v.height,left:A},o.speed,function(){y.hide().css("visibility","visible").fadeIn(function(){if(!o.autohide){h.fadeIn();s.show()}})})};v.onerror=function(){j.fadeIn().html("Cannot find image "+t)};v.src=t;if(o.preload){r.filter(":eq("+(l-1)+"), :eq("+(l+1)+")").each(function(){var w=new Image();w.src=b(this).attr("href")})}}function f(t,u){t.click(function(){if(t.hasClass(o.disabledClass)){return}var v=r.eq(i=l+(u?1:-1));if(v.length){p(v)}})}f(k,true);f(g);b(document).keydown(function(t){if(!j.is(":visible")||t.altKey||t.ctrlKey){return}if(t.keyCode==37||t.keyCode==39){var u=t.keyCode==37?g:k;u.click();return t.preventDefault()}return true});function q(){if(!j.is(":animated")){h.show();s.show()}}if(o.autohide){j.hover(q,function(){h.fadeOut();s.hide()}).mousemove(q)}var n;this.each(function(){var v=b(this),u=b(this).overlay(),t=u;u.onBeforeLoad(function(){p(v)});u.onClose(function(){r.removeClass(o.activeClass)})});return o.api?n:this}})(jQuery); (function(d){var b=d.tools.overlay;b.effects=b.effects||{};b.effects.apple={version:"1.0.1"};d.extend(b.conf,{start:{absolute:true,top:null,left:null},fadeInSpeed:"fast",zIndex:9999});function c(f){var g=f.offset();return[g.top+f.height()/2,g.left+f.width()/2]}var e=function(n){var k=this.getOverlay(),f=this.getConf(),i=this.getTrigger(),q=this,r=k.outerWidth({margin:true}),m=k.data("img");if(!m){var l=k.css("backgroundImage");if(!l){throw"background-image CSS property not set for overlay"}l=l.substring(l.indexOf("(")+1,l.indexOf(")")).replace(/\"/g,"");k.css("backgroundImage","none");m=d('<img src="'+l+'"/>');m.css({border:0,position:"absolute",display:"none"}).width(r);d("body").append(m);k.data("img",m)}var o=d(window),j=f.start.top||Math.round(o.height()/2),h=f.start.left||Math.round(o.width()/2);if(i){var g=c(i);j=g[0];h=g[1]}if(!f.start.absolute){j+=o.scrollTop();h+=o.scrollLeft()}m.css({top:j,left:h,width:0,zIndex:f.zIndex}).show();m.animate({top:k.css("top"),left:k.css("left"),width:r},f.speed,function(){k.css("zIndex",f.zIndex+1).fadeIn(f.fadeInSpeed,function(){if(q.isOpened()&&!d(this).index(k)){n.call()}else{k.hide()}})})};var a=function(f){var h=this.getOverlay(),i=this.getConf(),g=this.getTrigger(),l=i.start.top,k=i.start.left;h.hide();if(g){var j=c(g);l=j[0];k=j[1]}h.data("img").animate({top:l,left:k,width:0},i.closeSpeed,f)};b.addEffect("apple",e,a)})(jQuery); (function(b){b.tools=b.tools||{};b.tools.expose={version:"1.0.5",conf:{maskId:null,loadSpeed:"slow",closeSpeed:"fast",closeOnClick:true,closeOnEsc:true,zIndex:9998,opacity:0.8,color:"#456",api:false}};function a(){if(b.browser.msie){var f=b(document).height(),e=b(window).height();return[window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth,f-e<20?e:f]}return[b(window).width(),b(document).height()]}function c(h,g){var e=this,j=b(this),d=null,f=false,i=0;b.each(g,function(k,l){if(b.isFunction(l)){j.bind(k,l)}});b(window).resize(function(){e.fit()});b.extend(this,{getMask:function(){return d},getExposed:function(){return h},getConf:function(){return g},isLoaded:function(){return f},load:function(n){if(f){return e}i=h.eq(0).css("zIndex");if(g.maskId){d=b("#"+g.maskId)}if(!d||!d.length){var l=a();d=b("<div/>").css({position:"absolute",top:0,left:0,width:l[0],height:l[1],display:"none",opacity:0,zIndex:g.zIndex});if(g.maskId){d.attr("id",g.maskId)}b("body").append(d);var k=d.css("backgroundColor");if(!k||k=="transparent"||k=="rgba(0, 0, 0, 0)"){d.css("backgroundColor",g.color)}if(g.closeOnEsc){b(document).bind("keydown.unexpose",function(o){if(o.keyCode==27){e.close()}})}if(g.closeOnClick){d.bind("click.unexpose",function(o){e.close(o)})}}n=n||b.Event();n.type="onBeforeLoad";j.trigger(n);if(n.isDefaultPrevented()){return e}b.each(h,function(){var o=b(this);if(!/relative|absolute|fixed/i.test(o.css("position"))){o.css("position","relative")}});h.css({zIndex:Math.max(g.zIndex+1,i=="auto"?0:i)});var m=d.height();if(!this.isLoaded()){d.css({opacity:0,display:"block"}).fadeTo(g.loadSpeed,g.opacity,function(){if(d.height()!=m){d.css("height",m)}n.type="onLoad";j.trigger(n)})}f=true;return e},close:function(k){if(!f){return e}k=k||b.Event();k.type="onBeforeClose";j.trigger(k);if(k.isDefaultPrevented()){return e}d.fadeOut(g.closeSpeed,function(){k.type="onClose";j.trigger(k);h.css({zIndex:b.browser.msie?i:null})});f=false;return e},fit:function(){if(d){var k=a();d.css({width:k[0],height:k[1]})}},bind:function(k,l){j.bind(k,l);return e},unbind:function(k){j.unbind(k);return e}});b.each("onBeforeLoad,onLoad,onBeforeClose,onClose".split(","),function(k,l){e[l]=function(m){return e.bind(l,m)}})}b.fn.expose=function(d){var e=this.eq(typeof d=="number"?d:0).data("expose");if(e){return e}if(typeof d=="string"){d={color:d}}var f=b.extend({},b.tools.expose.conf);d=b.extend(f,d);this.each(function(){e=new c(b(this),d);b(this).data("expose",e)});return d.api?e:this}})(jQuery);
ztfy.jqueryui
/ztfy.jqueryui-0.7.12.tar.gz/ztfy.jqueryui-0.7.12/src/ztfy/jqueryui/resources/js/jquery-tools-1.1.2.min.js
jquery-tools-1.1.2.min.js
(function(c){var qa=Math.min,E=Math.max,ia=Math.floor,R=function(a){return"string"===c.type(a)},fa=function(a,b){if(c.isArray(b))for(var d=0,g=b.length;d<g;d++){var h=b[d];try{R(h)&&(h=eval(h)),c.isFunction(h)&&h(a)}catch(j){}}};c.layout={version:"1.3.rc30.6",revision:0.033006,browser:{mozilla:!!c.browser.mozilla,webkit:!!c.browser.webkit||!!c.browser.safari,msie:!!c.browser.msie,isIE6:c.browser.msie&&6==c.browser.version,boxModel:c.support.boxModel||!c.browser.msie,version:c.browser.version},effects:{slide:{all:{duration:"fast"}, north:{direction:"up"},south:{direction:"down"},east:{direction:"right"},west:{direction:"left"}},drop:{all:{duration:"slow"},north:{direction:"up"},south:{direction:"down"},east:{direction:"right"},west:{direction:"left"}},scale:{all:{duration:"fast"}},blind:{},clip:{},explode:{},fade:{},fold:{},puff:{},size:{all:{easing:"swing"}}},config:{optionRootKeys:"effects panes north south west east center".split(" "),allPanes:["north","south","west","east","center"],borderPanes:["north","south","west","east"], oppositeEdge:{north:"south",south:"north",east:"west",west:"east"},offscreenCSS:{left:"-99999px",right:"auto"},offscreenReset:"offscreenReset",hidden:{visibility:"hidden"},visible:{visibility:"visible"},resizers:{cssReq:{position:"absolute",padding:0,margin:0,fontSize:"1px",textAlign:"left",overflow:"hidden"},cssDemo:{background:"#DDD",border:"none"}},togglers:{cssReq:{position:"absolute",display:"block",padding:0,margin:0,overflow:"hidden",textAlign:"center",fontSize:"1px",cursor:"pointer",zIndex:1}, cssDemo:{background:"#AAA"}},content:{cssReq:{position:"relative"},cssDemo:{overflow:"auto",padding:"10px"},cssDemoPane:{overflow:"hidden",padding:0}},panes:{cssReq:{position:"absolute",margin:0},cssDemo:{padding:"10px",background:"#FFF",border:"1px solid #BBB",overflow:"auto"}},north:{side:"Top",sizeType:"Height",dir:"horz",cssReq:{top:0,bottom:"auto",left:0,right:0,width:"auto"}},south:{side:"Bottom",sizeType:"Height",dir:"horz",cssReq:{top:"auto",bottom:0,left:0,right:0,width:"auto"}},east:{side:"Right", sizeType:"Width",dir:"vert",cssReq:{left:"auto",right:0,top:"auto",bottom:"auto",height:"auto"}},west:{side:"Left",sizeType:"Width",dir:"vert",cssReq:{left:0,right:"auto",top:"auto",bottom:"auto",height:"auto"}},center:{dir:"center",cssReq:{left:"auto",right:"auto",top:"auto",bottom:"auto",height:"auto",width:"auto"}}},callbacks:{},getParentPaneElem:function(a){a=c(a);if(a=a.data("layout")||a.data("parentLayout")){a=a.container;if(a.data("layoutPane"))return a;a=a.closest("."+c.layout.defaults.panes.paneClass); if(a.data("layoutPane"))return a}return null},getParentPaneInstance:function(a){return(a=c.layout.getParentPaneElem(a))?a.data("layoutPane"):null},getParentLayoutInstance:function(a){return(a=c.layout.getParentPaneElem(a))?a.data("parentLayout"):null},getEventObject:function(c){return"object"===typeof c&&c.stopPropagation?c:null},parsePaneName:function(a){var b=c.layout.getEventObject(a);return b?(b.stopPropagation(),c(this).data("layoutEdge")):a},plugins:{draggable:!!c.fn.draggable,effects:{core:!!c.effects, slide:c.effects&&c.effects.slide}},onCreate:[],onLoad:[],onReady:[],onDestroy:[],onUnload:[],afterOpen:[],afterClose:[],scrollbarWidth:function(){return window.scrollbarWidth||c.layout.getScrollbarSize("width")},scrollbarHeight:function(){return window.scrollbarHeight||c.layout.getScrollbarSize("height")},getScrollbarSize:function(a){var b=c('<div style="position: absolute; top: -10000px; left: -10000px; width: 100px; height: 100px; overflow: scroll;"></div>').appendTo("body"),d={width:b.width()- b[0].clientWidth,height:b.height()-b[0].clientHeight};b.remove();window.scrollbarWidth=d.width;window.scrollbarHeight=d.height;return a.match(/^(width|height)$/)?d[a]:d},showInvisibly:function(a,b){if(!a)return{};a.jquery||(a=c(a));var d={display:a.css("display"),visibility:a.css("visibility")};return b||"none"===d.display?(a.css({display:"block",visibility:"hidden"}),d):{}},getElementDimensions:function(a){var b={},d=b.css={},g={},h,j,r=c.layout.cssNum,l=a.offset();b.offsetLeft=l.left;b.offsetTop= l.top;c.each(["Left","Right","Top","Bottom"],function(r,l){h=d["border"+l]=c.layout.borderWidth(a,l);j=d["padding"+l]=c.layout.cssNum(a,"padding"+l);g[l]=h+j;b["inset"+l]=j});b.offsetWidth=a.innerWidth();b.offsetHeight=a.innerHeight();b.outerWidth=a.outerWidth();b.outerHeight=a.outerHeight();b.innerWidth=E(0,b.outerWidth-g.Left-g.Right);b.innerHeight=E(0,b.outerHeight-g.Top-g.Bottom);d.width=a.width();d.height=a.height();d.top=r(a,"top",!0);d.bottom=r(a,"bottom",!0);d.left=r(a,"left",!0);d.right= r(a,"right",!0);return b},getElementCSS:function(c,b){var d={},g=c[0].style,h=b.split(","),j=["Top","Bottom","Left","Right"],r=["Color","Style","Width"],l,A,I,J,y,q;for(J=0;J<h.length;J++)if(l=h[J],l.match(/(border|padding|margin)$/))for(y=0;4>y;y++)if(A=j[y],"border"===l)for(q=0;3>q;q++)I=r[q],d[l+A+I]=g[l+A+I];else d[l+A]=g[l+A];else d[l]=g[l];return d},cssWidth:function(a,b){if(0>=b)return 0;if(!c.layout.browser.boxModel)return b;var d=c.layout.borderWidth,g=c.layout.cssNum,d=b-d(a,"Left")-d(a, "Right")-g(a,"paddingLeft")-g(a,"paddingRight");return E(0,d)},cssHeight:function(a,b){if(0>=b)return 0;if(!c.layout.browser.boxModel)return b;var d=c.layout.borderWidth,g=c.layout.cssNum,d=b-d(a,"Top")-d(a,"Bottom")-g(a,"paddingTop")-g(a,"paddingBottom");return E(0,d)},cssNum:function(a,b,d){a.jquery||(a=c(a));var g=c.layout.showInvisibly(a),b=c.curCSS(a[0],b,!0),d=d&&"auto"==b?b:parseInt(b,10)||0;a.css(g);return d},borderWidth:function(a,b){a.jquery&&(a=a[0]);var d="border"+b.substr(0,1).toUpperCase()+ b.substr(1);return"none"===c.curCSS(a,d+"Style",!0)?0:parseInt(c.curCSS(a,d+"Width",!0),10)||0},isMouseOverElem:function(a,b){var d=c(b||this),g=d.offset(),h=g.top,g=g.left,j=g+d.outerWidth(),d=h+d.outerHeight(),r=a.pageX,l=a.pageY;return c.layout.browser.msie&&0>r&&0>l||r>=g&&r<=j&&l>=h&&l<=d},msg:function(a,b,d,g){c.isPlainObject(a)&&window.debugData?("string"===typeof b?(g=d,d=b):"object"===typeof d&&(g=d,d=null),d=d||"log( <object> )",g=c.extend({sort:!1,returnHTML:!1,display:!1},g),!0===b||g.display? debugData(a,d,g):window.console&&console.log(debugData(a,d,g))):b?alert(a):window.console?console.log(a):(b=c("#layoutLogger"),b.length||(b=c('<div id="layoutLogger" style="position: '+(c.support.fixedPosition?"fixed":"absolute")+'; top: 5px; z-index: 999999; max-width: 25%; overflow: hidden; border: 1px solid #000; border-radius: 5px; background: #FBFBFB; box-shadow: 0 2px 10px rgba(0,0,0,0.3);"><div style="font-size: 13px; font-weight: bold; padding: 5px 10px; background: #F6F6F6; border-radius: 5px 5px 0 0; cursor: move;"><span style="float: right; padding-left: 7px; cursor: pointer;" title="Remove Console" onclick="$(this).closest(\'#layoutLogger\').remove()">X</span>Layout console.log</div><ul style="font-size: 13px; font-weight: none; list-style: none; margin: 0; padding: 0 0 2px;"></ul></div>').appendTo("body"), b.css("left",c(window).width()-b.outerWidth()-5),c.ui.draggable&&b.draggable({handle:":first-child"})),b.children("ul").append('<li style="padding: 4px 10px; margin: 0; border-top: 1px solid #CCC;">'+a.replace(/\</g,"&lt;").replace(/\>/g,"&gt;")+"</li>"))}};c.layout.defaults={name:"",containerSelector:"",containerClass:"ui-layout-container",scrollToBookmarkOnLoad:!0,resizeWithWindow:!0,resizeWithWindowDelay:200,resizeWithWindowMaxDelay:0,onresizeall_start:null,onresizeall_end:null,onload_start:null, onload_end:null,onunload_start:null,onunload_end:null,initPanes:!0,showErrorMessages:!0,showDebugMessages:!1,zIndex:null,zIndexes:{pane_normal:0,content_mask:1,resizer_normal:2,pane_sliding:100,pane_animate:1E3,resizer_drag:1E4},errors:{pane:"pane",selector:"selector",addButtonError:"Error Adding Button \n\nInvalid ",containerMissing:"UI Layout Initialization Error\n\nThe specified layout-container does not exist.",centerPaneMissing:"UI Layout Initialization Error\n\nThe center-pane element does not exist.\n\nThe center-pane is a required element.", noContainerHeight:"UI Layout Initialization Warning\n\nThe layout-container \"CONTAINER\" has no height.\n\nTherefore the layout is 0-height and hence 'invisible'!",callbackError:"UI Layout Callback Error\n\nThe EVENT callback is not a valid function."},panes:{applyDemoStyles:!1,closable:!0,resizable:!0,slidable:!0,initClosed:!1,initHidden:!1,contentSelector:".ui-layout-content",contentIgnoreSelector:".ui-layout-ignore",findNestedContent:!1,paneClass:"ui-layout-pane",resizerClass:"ui-layout-resizer", togglerClass:"ui-layout-toggler",buttonClass:"ui-layout-button",minSize:0,maxSize:0,spacing_open:6,spacing_closed:6,togglerLength_open:50,togglerLength_closed:50,togglerAlign_open:"center",togglerAlign_closed:"center",togglerContent_open:"",togglerContent_closed:"",resizerDblClickToggle:!0,autoResize:!0,autoReopen:!0,resizerDragOpacity:1,maskContents:!1,maskObjects:!1,maskZindex:null,resizingGrid:!1,livePaneResizing:!1,liveContentResizing:!1,liveResizingTolerance:1,sliderCursor:"pointer",slideTrigger_open:"click", slideTrigger_close:"mouseleave",slideDelay_open:300,slideDelay_close:300,hideTogglerOnSlide:!1,preventQuickSlideClose:c.layout.browser.webkit,preventPrematureSlideClose:!1,tips:{Open:"Open",Close:"Close",Resize:"Resize",Slide:"Slide Open",Pin:"Pin",Unpin:"Un-Pin",noRoomToOpen:"Not enough room to show this panel.",minSizeWarning:"Panel has reached its minimum size",maxSizeWarning:"Panel has reached its maximum size"},showOverflowOnHover:!1,enableCursorHotkey:!0,customHotkeyModifier:"SHIFT",fxName:"slide", fxSpeed:null,fxSettings:{},fxOpacityFix:!0,animatePaneSizing:!1,childOptions:null,initChildLayout:!0,destroyChildLayout:!0,resizeChildLayout:!0,triggerEventsOnLoad:!1,triggerEventsDuringLiveResize:!0,onshow_start:null,onshow_end:null,onhide_start:null,onhide_end:null,onopen_start:null,onopen_end:null,onclose_start:null,onclose_end:null,onresize_start:null,onresize_end:null,onsizecontent_start:null,onsizecontent_end:null,onswap_start:null,onswap_end:null,ondrag_start:null,ondrag_end:null},north:{paneSelector:".ui-layout-north", size:"auto",resizerCursor:"n-resize",customHotkey:""},south:{paneSelector:".ui-layout-south",size:"auto",resizerCursor:"s-resize",customHotkey:""},east:{paneSelector:".ui-layout-east",size:200,resizerCursor:"e-resize",customHotkey:""},west:{paneSelector:".ui-layout-west",size:200,resizerCursor:"w-resize",customHotkey:""},center:{paneSelector:".ui-layout-center",minWidth:0,minHeight:0}};c.layout.optionsMap={layout:"stateManagement effects zIndexes errors name zIndex scrollToBookmarkOnLoad showErrorMessages resizeWithWindow resizeWithWindowDelay resizeWithWindowMaxDelay onresizeall onresizeall_start onresizeall_end onload onunload".split(" "), center:"paneClass contentSelector contentIgnoreSelector findNestedContent applyDemoStyles triggerEventsOnLoad showOverflowOnHover maskContents maskObjects liveContentResizing childOptions initChildLayout resizeChildLayout destroyChildLayout onresize onresize_start onresize_end onsizecontent onsizecontent_start onsizecontent_end".split(" "),noDefault:["paneSelector","resizerCursor","customHotkey"]};c.layout.transformData=function(c){var b={panes:{},center:{}},d,g,h,j,r,l,A;if("object"!==typeof c)return b; for(g in c){d=b;r=c[g];h=g.split("__");A=h.length-1;for(l=0;l<=A;l++)j=h[l],l===A?d[j]=r:d[j]||(d[j]={}),d=d[j]}return b};c.layout.backwardCompatibility={map:{applyDefaultStyles:"applyDemoStyles",resizeNestedLayout:"resizeChildLayout",resizeWhileDragging:"livePaneResizing",resizeContentWhileDragging:"liveContentResizing",triggerEventsWhileDragging:"triggerEventsDuringLiveResize",maskIframesOnResize:"maskContents",useStateCookie:"stateManagement.enabled","cookie.autoLoad":"stateManagement.autoLoad", "cookie.autoSave":"stateManagement.autoSave","cookie.keys":"stateManagement.stateKeys","cookie.name":"stateManagement.cookie.name","cookie.domain":"stateManagement.cookie.domain","cookie.path":"stateManagement.cookie.path","cookie.expires":"stateManagement.cookie.expires","cookie.secure":"stateManagement.cookie.secure",noRoomToOpenTip:"tips.noRoomToOpen",togglerTip_open:"tips.Close",togglerTip_closed:"tips.Open",resizerTip:"tips.Resize",sliderTip:"tips.Slide"},renameOptions:function(a){function b(c, b){for(var d=c.split("."),g=d.length-1,j={branch:a,key:d[g]},h=0,p;h<g;h++)p=d[h],j.branch=void 0==j.branch[p]?b?j.branch[p]={}:{}:j.branch[p];return j}var d=c.layout.backwardCompatibility.map,g,h,j,r;for(r in d)g=b(r),j=g.branch[g.key],void 0!==j&&(h=b(d[r],!0),h.branch[h.key]=j,delete g.branch[g.key])},renameAllOptions:function(a){var b=c.layout.backwardCompatibility.renameOptions;b(a);a.defaults&&("object"!==typeof a.panes&&(a.panes={}),c.extend(!0,a.panes,a.defaults),delete a.defaults);a.panes&& b(a.panes);c.each(c.layout.config.allPanes,function(c,g){a[g]&&b(a[g])});return a}};c.fn.layout=function(a){function b(f){if(!f)return!0;var o=f.keyCode;if(33>o)return!0;var u={38:"north",40:"south",37:"west",39:"east"},a=f.shiftKey,e=f.ctrlKey,i,x,b,k;e&&(37<=o&&40>=o)&&q[u[o]].enableCursorHotkey?k=u[o]:(e||a)&&c.each(j.borderPanes,function(f,c){i=q[c];x=i.customHotkey;b=i.customHotkeyModifier;if(a&&"SHIFT"==b||e&&"CTRL"==b||e&&a)if(x&&o===(isNaN(x)||9>=x?x.toUpperCase().charCodeAt(0):x))return k= c,!1});if(!k||!v[k]||!q[k].closable||p[k].isHidden)return!0;ga(k);f.stopPropagation();return f.returnValue=!1}function d(f){if(C()){this&&this.tagName&&(f=this);var o;R(f)?o=v[f]:c(f).data("layoutRole")?o=c(f):c(f).parents().each(function(){if(c(this).data("layoutRole"))return o=c(this),!1});if(o&&o.length){var u=o.data("layoutEdge"),f=p[u];f.cssSaved&&g(u);if(f.isSliding||f.isResizing||f.isClosed)f.cssSaved=!1;else{var a={zIndex:q.zIndexes.resizer_normal+1},e={},i=o.css("overflow"),x=o.css("overflowX"), b=o.css("overflowY");"visible"!=i&&(e.overflow=i,a.overflow="visible");x&&!x.match(/visible|auto/)&&(e.overflowX=x,a.overflowX="visible");b&&!b.match(/visible|auto/)&&(e.overflowY=x,a.overflowY="visible");f.cssSaved=e;o.css(a);c.each(j.allPanes,function(f,o){o!=u&&g(o)})}}}}function g(f){if(C()){this&&this.tagName&&(f=this);var o;R(f)?o=v[f]:c(f).data("layoutRole")?o=c(f):c(f).parents().each(function(){if(c(this).data("layoutRole"))return o=c(this),!1});if(o&&o.length){var f=o.data("layoutEdge"), f=p[f],u=f.cssSaved||{};!f.isSliding&&!f.isResizing&&o.css("zIndex",q.zIndexes.pane_normal);o.css(u);f.cssSaved=!1}}}var h=c.layout.browser,j=c.layout.config,r=c.layout.cssWidth,l=c.layout.cssHeight,A=c.layout.getElementDimensions,I=c.layout.getElementCSS,J=c.layout.getEventObject,y=c.layout.parsePaneName,q=c.extend(!0,{},c.layout.defaults);q.effects=c.extend(!0,{},c.layout.effects);var p={id:"layout"+c.now(),initialized:!1,container:{},north:{},south:{},east:{},west:{},center:{}},O={north:null,south:null, east:null,west:null,center:null},H={data:{},set:function(f,o,c){H.clear(f);H.data[f]=setTimeout(o,c)},clear:function(f){var o=H.data;o[f]&&(clearTimeout(o[f]),delete o[f])}},S=function(f,o,u){var a=q;(a.showErrorMessages||u&&a.showDebugMessages)&&c.layout.msg(a.name+" / "+f,!1!==o);return!1},B=function(f,o,u){var a=o&&R(o),e=a?p[o]:p,i=a?q[o]:q,x=q.name,b=f+(f.match(/_/)?"":"_end"),k=b.match(/_end$/)?b.substr(0,b.length-4):"",m=i[b]||i[k],d="NC",j=[];!a&&"boolean"!==c.type(u)&&(u=o);if(m)try{R(m)&& (m.match(/,/)?(j=m.split(","),m=eval(j[0])):m=eval(m)),c.isFunction(m)&&(d=j.length?m(j[1]):a?m(o,v[o],e,i,x):m(z,e,i,x))}catch(g){S(q.errors.callbackError.replace(/EVENT/,c.trim(o+" "+b)),!1)}!u&&!1!==d&&(a?(u=v[o],i=q[o],e=p[o],u.triggerHandler("layoutpane"+b,[o,u,e,i,x]),k&&u.triggerHandler("layoutpane"+k,[o,u,e,i,x])):(t.triggerHandler("layout"+b,[z,e,i,x]),k&&t.triggerHandler("layout"+k,[z,e,i,x])));("onresize_end"===f||"onsizecontent_end"===f)&&ra(o);return d},Fa=function(f){if(!h.mozilla){var o= v[f];"IFRAME"===p[f].tagName?o.css(j.hidden).css(j.visible):o.find("IFRAME").css(j.hidden).css(j.visible)}},ja=function(f){var o=v[f],f=j[f].dir,o={minWidth:1001-r(o,1E3),minHeight:1001-l(o,1E3)};"horz"===f&&(o.minSize=o.minHeight);"vert"===f&&(o.minSize=o.minWidth);return o},Ra=function(f,o,u){var a=f;R(f)?a=v[f]:f.jquery||(a=c(f));f=l(a,o);a.css({height:f,visibility:"visible"});0<f&&0<a.innerWidth()?u&&a.data("autoHidden")&&(a.show().data("autoHidden",!1),h.mozilla||a.css(j.hidden).css(j.visible)): u&&!a.data("autoHidden")&&a.hide().data("autoHidden",!0)},T=function(f,o,a){a||(a=j[f].dir);R(o)&&o.match(/%/)&&(o="100%"===o?-1:parseInt(o,10)/100);if(0===o)return 0;if(1<=o)return parseInt(o,10);var D=q,e=0;"horz"==a?e=w.innerHeight-(v.north?D.north.spacing_open:0)-(v.south?D.south.spacing_open:0):"vert"==a&&(e=w.innerWidth-(v.west?D.west.spacing_open:0)-(v.east?D.east.spacing_open:0));if(-1===o)return e;if(0<o)return ia(e*o);if("center"==f)return 0;var a="horz"===a?"height":"width",D=v[f],f="height"=== a?N[f]:!1,e=c.layout.showInvisibly(D),i=D.css(a),x=f?f.css(a):0;D.css(a,"auto");f&&f.css(a,"auto");o="height"===a?D.outerHeight():D.outerWidth();D.css(a,i).css(e);f&&f.css(a,x);return o},Y=function(f,o){var a=v[f],c=q[f],e=p[f],i=o?c.spacing_open:0,c=o?c.spacing_closed:0;return!a||e.isHidden?0:e.isClosed||e.isSliding&&o?c:"horz"===j[f].dir?a.outerHeight()+i:a.outerWidth()+i},P=function(f,o){if(C()){var a=q[f],c=p[f],e=j[f],i=e.dir;e.side.toLowerCase();e.sizeType.toLowerCase();var e=void 0!=o?o:c.isSliding, x=a.spacing_open,b=j.oppositeEdge[f],k=p[b],m=v[b],d=!m||!1===k.isVisible||k.isSliding?0:"horz"==i?m.outerHeight():m.outerWidth(),b=(!m||k.isHidden?0:q[b][!1!==k.isClosed?"spacing_closed":"spacing_open"])||0,k="horz"==i?w.innerHeight:w.innerWidth,m=ja("center"),m="horz"==i?E(q.center.minHeight,m.minHeight):E(q.center.minWidth,m.minWidth),e=k-x-(e?0:T("center",m,i)+d+b),i=c.minSize=E(T(f,a.minSize),ja(f).minSize),e=c.maxSize=qa(a.maxSize?T(f,a.maxSize):1E5,e),c=c.resizerPosition={},x=w.insetTop,d= w.insetLeft,b=w.innerWidth,k=w.innerHeight,a=a.spacing_open;switch(f){case "north":c.min=x+i;c.max=x+e;break;case "west":c.min=d+i;c.max=d+e;break;case "south":c.min=x+k-e-a;c.max=x+k-i-a;break;case "east":c.min=d+b-e-a,c.max=d+b-i-a}}},sa=function(f,a){var u=c(f),D=u.data("layoutRole"),e=u.data("layoutEdge"),i=q[e][D+"Class"],e="-"+e,b=u.hasClass(i+"-closed")?"-closed":"-open",d="-closed"===b?"-open":"-closed",b=i+"-hover "+(i+e+"-hover ")+(i+b+"-hover ")+(i+e+b+"-hover ");a&&(b+=i+d+"-hover "+(i+ e+d+"-hover "));"resizer"==D&&u.hasClass(i+"-sliding")&&(b+=i+"-sliding-hover "+(i+e+"-sliding-hover "));return c.trim(b)},ta=function(f,a){var u=c(a||this);f&&"toggler"===u.data("layoutRole")&&f.stopPropagation();u.addClass(sa(u))},Q=function(f,a){var u=c(a||this);u.removeClass(sa(u,!0))},Ga=function(){c.fn.disableSelection&&c("body").disableSelection()},Ha=function(f,a){var u=a||this,D=c(u).data("layoutEdge"),e=D+"ResizerLeave";H.clear(D+"_openSlider");H.clear(e);a?!p[D].isResizing&&c.fn.enableSelection&& c("body").enableSelection():H.set(e,function(){Ha(f,u)},200)},C=function(){return p.initialized||p.creatingLayout?!0:ka()},ka=function(f){var a=q;if(!t.is(":visible"))return!f&&(h.webkit&&"BODY"===t[0].tagName)&&setTimeout(function(){ka(!0)},50),!1;if(!Ia("center").length)return S(a.errors.centerPaneMissing);p.creatingLayout=!0;c.extend(w,A(t));Sa();a.scrollToBookmarkOnLoad&&(f=self.location,f.hash&&f.replace(f.hash));z.hasParentLayout?a.resizeWithWindow=!1:a.resizeWithWindow&&c(window).bind("resize."+ G,Ta);delete p.creatingLayout;p.initialized=!0;fa(z,c.layout.onReady);B("onload_end");return!0},ua=function(f,a){var c=y.call(this,f),D=v[c];if(D){var e=N[c],i=a||q[c].childOptions,D=i.containerSelector?D.find(i.containerSelector):e||D,b=(e=D.length)?O[c]=D.data("layout")||null:null;!b&&(e&&i)&&(b=O[c]=D.eq(0).layout(i)||null);b&&(b.hasParentLayout=!0)}z[c].child=O[c]},Ta=function(){var f=Number(q.resizeWithWindowDelay);10>f&&(f=100);H.clear("winResize");H.set("winResize",function(){H.clear("winResize"); H.clear("winResizeRepeater");var f=A(t);(f.innerWidth!==w.innerWidth||f.innerHeight!==w.innerHeight)&&ba()},f);H.data.winResizeRepeater||Ja()},Ja=function(){var f=Number(q.resizeWithWindowMaxDelay);0<f&&H.set("winResizeRepeater",function(){Ja();ba()},f)},Ka=function(){B("onunload_start");fa(z,c.layout.onUnload);B("onunload_end")},La=function(f){f=f?f.split(","):j.borderPanes;c.each(f,function(f,a){var D=q[a];if(D.enableCursorHotkey||D.customHotkey)return c(document).bind("keydown."+G,b),!1})},Va= function(){function f(f){var a=q[f],e=q.panes;a.fxSettings||(a.fxSettings={});e.fxSettings||(e.fxSettings={});c.each(["_open","_close","_size"],function(o,u){var i="fxName"+u,b="fxSpeed"+u,D="fxSettings"+u,d=a[i]=a[i]||e[i]||a.fxName||e.fxName||"none";if(d==="none"||!c.effects||!c.effects[d]||!q.effects[d])d=a[i]="none";d=q.effects[d]||{};i=d.all||null;d=d[f]||null;a[b]=a[b]||e[b]||a.fxSpeed||e.fxSpeed||null;a[D]=c.extend(true,{},i,d,e.fxSettings,a.fxSettings,e[D],a[D])});delete a.fxName;delete a.fxSpeed; delete a.fxSettings}var o,u,b,e,i,x;a=c.layout.transformData(a);a=c.layout.backwardCompatibility.renameAllOptions(a);if(!c.isEmptyObject(a.panes)){o=c.layout.optionsMap.noDefault;e=0;for(i=o.length;e<i;e++)b=o[e],delete a.panes[b];o=c.layout.optionsMap.layout;e=0;for(i=o.length;e<i;e++)b=o[e],delete a.panes[b]}o=c.layout.optionsMap.layout;var d=c.layout.config.optionRootKeys;for(b in a)e=a[b],0>c.inArray(b,d)&&0>c.inArray(b,o)&&(a.panes[b]||(a.panes[b]=c.isPlainObject(e)?c.extend(!0,{},e):e),delete a[b]); c.extend(!0,q,a);c.each(j.allPanes,function(e,d){j[d]=c.extend(!0,{},j.panes,j[d]);u=q.panes;x=q[d];if("center"===d){o=c.layout.optionsMap.center;e=0;for(i=o.length;e<i;e++)if(b=o[e],!a.center[b]&&(a.panes[b]||!x[b]))x[b]=u[b]}else if(x=q[d]=c.extend(!0,{},u,x),f(d),x.resizerClass||(x.resizerClass="ui-layout-resizer"),!x.togglerClass)x.togglerClass="ui-layout-toggler";x.paneClass||(x.paneClass="ui-layout-pane")});e=a.zIndex;d=q.zIndexes;0<e&&(d.pane_normal=e,d.content_mask=E(e+1,d.content_mask),d.resizer_normal= E(e+2,d.resizer_normal));delete q.panes},Ia=function(f){f=q[f].paneSelector;if("#"===f.substr(0,1))return t.find(f).eq(0);var a=t.children(f).eq(0);return a.length?a:t.children("form:first").children(f).eq(0)},Sa=function(f){y(f);c.each(j.allPanes,function(f,a){Ma(a,!0)});va();c.each(j.borderPanes,function(f,a){v[a]&&p[a].isVisible&&(P(a),U(a))});V("center");c.each(j.allPanes,function(f,a){var c=q[a];v[a]&&(p[a].isVisible&&(ca(a),c.triggerEventsOnLoad?B("onresize_end",a):ra(a)),c.initChildLayout&& c.childOptions&&ua(a))})},Ma=function(f,a){if(a||C()){var c=q[f],b=p[f],e=j[f],i=e.dir,x="center"===f,K={},k=v[f],m,h;k?wa(f,!1,!0,!1):N[f]=!1;k=v[f]=Ia(f);if(k.length){k.data("layoutCSS")||k.data("layoutCSS",I(k,"position,top,left,bottom,right,width,height,overflow,zIndex,display,backgroundColor,padding,margin,border"));z[f]={name:f,pane:v[f],content:N[f],options:q[f],state:p[f],child:O[f]};k.data({parentLayout:z,layoutPane:z[f],layoutEdge:f,layoutRole:"pane"}).css(e.cssReq).css("zIndex",q.zIndexes.pane_normal).css(c.applyDemoStyles? e.cssDemo:{}).addClass(c.paneClass+" "+c.paneClass+"-"+f).bind("mouseenter."+G,ta).bind("mouseleave."+G,Q);e={hide:"",show:"",toggle:"",close:"",open:"",slideOpen:"",slideClose:"",slideToggle:"",size:"manualSizePane",sizePane:"manualSizePane",sizeContent:"",sizeHandles:"",enableClosable:"",disableClosable:"",enableSlideable:"",disableSlideable:"",enableResizable:"",disableResizable:"",swapPanes:"swapPanes",swap:"swapPanes",move:"swapPanes",removePane:"removePane",remove:"removePane",createChildLayout:"", resizeChildLayout:"",resizeAll:"resizeAll",resizeLayout:"resizeAll"};for(h in e)k.bind("layoutpane"+h.toLowerCase()+"."+G,z[e[h]||h]);xa(f,!1);x||(m=b.size=T(f,c.size),x=T(f,c.minSize)||1,h=T(f,c.maxSize)||1E5,0<m&&(m=E(qa(m,h),x)),b.isClosed=!1,b.isSliding=!1,b.isResizing=!1,b.isHidden=!1,b.pins||(b.pins=[]));b.tagName=k[0].tagName;b.edge=f;b.noRoom=!1;b.isVisible=!0;switch(f){case "north":K.top=w.insetTop;K.left=w.insetLeft;K.right=w.insetRight;break;case "south":K.bottom=w.insetBottom;K.left=w.insetLeft; K.right=w.insetRight;break;case "west":K.left=w.insetLeft;break;case "east":K.right=w.insetRight}"horz"===i?K.height=l(k,m):"vert"===i&&(K.width=r(k,m));k.css(K);"horz"!=i&&V(f,!0);c.initClosed&&c.closable&&!c.initHidden?W(f,!0,!0):c.initHidden||c.initClosed?ya(f):b.noRoom||k.css("display","block");k.css("visibility","visible");c.showOverflowOnHover&&k.hover(d,g);p.initialized&&(va(f),La(f),ba(),b.isVisible&&(c.triggerEventsOnLoad?B("onresize_end",f):ra(f)),c.initChildLayout&&c.childOptions&&ua(f))}else v[f]= !1}},va=function(f){f=f?f.split(","):j.borderPanes;c.each(f,function(f,a){var b=v[a];F[a]=!1;L[a]=!1;if(b){var b=q[a],e=p[a],i=j[a],d="#"===b.paneSelector.substr(0,1)?b.paneSelector.substr(1):"",g=b.resizerClass,k=b.togglerClass;i.side.toLowerCase();var i="-"+a,m=z[a],h=m.resizer=F[a]=c("<div></div>"),m=m.toggler=b.closable?L[a]=c("<div></div>"):!1;!e.isVisible&&b.slidable&&h.attr("title",b.tips.Slide).css("cursor",b.sliderCursor);h.attr("id",d?d+"-resizer":"").data({parentLayout:z,layoutPane:z[a], layoutEdge:a,layoutRole:"resizer"}).css(j.resizers.cssReq).css("zIndex",q.zIndexes.resizer_normal).css(b.applyDemoStyles?j.resizers.cssDemo:{}).addClass(g+" "+g+i).hover(ta,Q).hover(Ga,Ha).appendTo(t);m&&(m.attr("id",d?d+"-toggler":"").data({parentLayout:z,layoutPane:z[a],layoutEdge:a,layoutRole:"toggler"}).css(j.togglers.cssReq).css(b.applyDemoStyles?j.togglers.cssDemo:{}).addClass(k+" "+k+i).hover(ta,Q).bind("mouseenter",Ga).appendTo(h),b.togglerContent_open&&c("<span>"+b.togglerContent_open+"</span>").data({layoutEdge:a, layoutRole:"togglerContent"}).data("layoutRole","togglerContent").data("layoutEdge",a).addClass("content content-open").css("display","none").appendTo(m),b.togglerContent_closed&&c("<span>"+b.togglerContent_closed+"</span>").data({layoutEdge:a,layoutRole:"togglerContent"}).addClass("content content-closed").css("display","none").appendTo(m),Na(a));Wa(a);e.isVisible?za(a):(Aa(a),Z(a,!0))}});da()},xa=function(f,a){if(C()){var c=q[f],b=c.contentSelector,e=z[f],i=v[f],d;b&&(d=e.content=N[f]=c.findNestedContent? i.find(b).eq(0):i.children(b).eq(0));d&&d.length?(d.data("layoutRole","content"),d.data("layoutCSS")||d.data("layoutCSS",I(d,"height")),d.css(j.content.cssReq),c.applyDemoStyles&&(d.css(j.content.cssDemo),i.css(j.content.cssDemoPane)),p[f].content={},!1!==a&&ca(f)):e.content=N[f]=!1}},Wa=function(f){var a=c.layout.plugins.draggable,f=f?f.split(","):j.borderPanes;c.each(f,function(f,e){var i=q[e];if(!a||!v[e]||!i.resizable)return i.resizable=!1,!0;var d=p[e],g=q.zIndexes,k=j[e],m="horz"==k.dir?"top": "left",h=e+",center,"+j.oppositeEdge[e]+("horz"==k.dir?",west,east":""),r=F[e],l=i.resizerClass,w=0,A,y,z=l+"-drag",C=l+"-"+e+"-drag",Xa=l+"-dragging",J=l+"-"+e+"-dragging",G=l+"-dragging-limit",E=l+"-"+e+"-dragging-limit",I=!1;d.isClosed||r.attr("title",i.tips.Resize).css("cursor",i.resizerCursor);r.draggable({containment:t[0],axis:"horz"==k.dir?"y":"x",delay:0,distance:1,grid:i.resizingGrid,helper:"clone",opacity:i.resizerDragOpacity,addClasses:!1,zIndex:g.resizer_drag,start:function(f,a){i=q[e]; d=p[e];y=i.livePaneResizing;if(!1===B("ondrag_start",e))return!1;d.isResizing=!0;H.clear(e+"_closeSlider");P(e);A=d.resizerPosition;w=a.position[m];r.addClass(z+" "+C);I=!1;c("body").disableSelection();la(h)},drag:function(f,a){I||(a.helper.addClass(Xa+" "+J).css({right:"auto",bottom:"auto"}).children().css("visibility","hidden"),I=!0,d.isSliding&&v[e].css("zIndex",g.pane_sliding));var c=0;a.position[m]<A.min?(a.position[m]=A.min,c=-1):a.position[m]>A.max&&(a.position[m]=A.max,c=1);c?(a.helper.addClass(G+ " "+E),window.defaultStatus=0<c&&e.match(/north|west/)||0>c&&e.match(/south|east/)?i.tips.maxSizeWarning:i.tips.minSizeWarning):(a.helper.removeClass(G+" "+E),window.defaultStatus="");y&&Math.abs(a.position[m]-w)>=i.liveResizingTolerance&&(w=a.position[m],b(f,a,e))},stop:function(f,a){c("body").enableSelection();window.defaultStatus="";r.removeClass(z+" "+C);d.isResizing=!1;b(f,a,e,!0,h)}})});var b=function(f,a,c,o,b){var d=a.position,u=j[c],f=q[c],a=p[c],g;switch(c){case "north":g=d.top;break;case "west":g= d.left;break;case "south":g=w.offsetHeight-d.top-f.spacing_open;break;case "east":g=w.offsetWidth-d.left-f.spacing_open}g-=w["inset"+u.side];o?(!1!==B("ondrag_end",c)&&ma(c,g,!1,!0),Ba(),a.isSliding&&b&&la(b,!0)):Math.abs(g-a.size)<f.liveResizingTolerance||(ma(c,g,!1,!0),aa.each(Oa))}},Oa=function(){var f=c(this),a=f.data("layoutMask"),a=p[a];"IFRAME"==a.tagName&&a.isVisible&&f.css({top:a.offsetTop,left:a.offsetLeft,width:a.outerWidth,height:a.outerHeight})},la=function(a,o){var b=a?a.split(","): c.layout.config.allPanes,d=q.zIndexes,e,i;c.each(b,function(a,f){i=p[f];e=q[f];i.isVisible&&(!o&&e.maskContents||e.maskObjects)&&Ya(f).each(function(){Oa.call(this);this.style.zIndex=i.isSliding?d.pane_sliding+1:d.pane_normal+1;this.style.display="block"})})},Ba=function(){var a;c.each(c.layout.config.borderPanes,function(c,b){if(p[b].isResizing)return a=!0,!1});a||aa.hide()},Ya=function(a){for(var b=c([]),d,g=0,e=aa.length;g<e;g++)d=aa.eq(g),d.data("layoutMask")===a&&(b=b.add(d));if(b.length)return b; b=v[a];d=p[a];var g=q[a],e=q.zIndexes,i=c([]),x,j,k,m,h;if(g.maskContents||g.maskObjects)for(h=0;h<(g.maskObjects?2:1);h++)x=g.maskObjects&&0==h,j=document.createElement(x?"iframe":"div"),k=c(j).data("layoutMask",a),j.className="ui-layout-mask ui-layout-mask-"+a,m=j.style,m.display="block",m.position="absolute",x&&(j.frameborder=0,j.src="about:blank",m.opacity=0,m.filter="Alpha(Opacity='0')",m.border=0),"IFRAME"==d.tagName?(m.zIndex=e.pane_normal+1,t.append(j)):(k.addClass("ui-layout-mask-inside-pane"), m.zIndex=g.maskZindex||e.content_mask,m.top=0,m.left=0,m.width="100%",m.height="100%",b.append(j)),i=i.add(j),aa=aa.add(j);return i},wa=function(a,b,d,g){if(C()){var a=y.call(this,a),e=v[a],i=N[a],x=F[a],j=L[a];e&&c.isEmptyObject(e.data())&&(e=!1);i&&c.isEmptyObject(i.data())&&(i=!1);x&&c.isEmptyObject(x.data())&&(x=!1);j&&c.isEmptyObject(j.data())&&(j=!1);e&&e.stop(!0,!0);var k=q[a],m=O[a]||(e?e.data("layout"):0)||(i?i.data("layout"):0)||null;if((void 0!==g?g:k.destroyChildLayout)&&m&&!m.destroyed)m.destroy(!0), m.destroyed&&(m=null);e&&b&&!m?e.remove():e&&e[0]&&(b=k.paneClass,g=b+"-"+a,b=[b,b+"-open",b+"-closed",b+"-sliding",g,g+"-open",g+"-closed",g+"-sliding"],c.merge(b,sa(e,!0)),e.removeClass(b.join(" ")).removeData("parentLayout").removeData("layoutPane").removeData("layoutRole").removeData("layoutEdge").removeData("autoHidden").unbind("."+G),i&&i.data("layout")?(i.width(i.width()),m.resizeAll()):i&&i.css(i.data("layoutCSS")).removeData("layoutCSS").removeData("layoutRole"),e.data("layout")||e.css(e.data("layoutCSS")).removeData("layoutCSS")); j&&j.remove();x&&x.remove();z[a]=v[a]=N[a]=F[a]=L[a]=O[a]=!1;d||ba()}},na=function(a){var c=v[a],b=c[0].style;q[a].useOffscreenClose?(c.data(j.offscreenReset)||c.data(j.offscreenReset,{left:b.left,right:b.right}),c.css(j.offscreenCSS)):c.hide().removeData(j.offscreenReset)},Pa=function(a){var c=v[a],a=q[a],b=j.offscreenCSS,d=c.data(j.offscreenReset),e=c[0].style;c.show().removeData(j.offscreenReset);if(a.useOffscreenClose&&d&&(e.left==b.left&&(e.left=d.left),e.right==b.right))e.right=d.right},ya= function(a,c){if(C()){var b=y.call(this,a),d=q[b],e=p[b],i=F[b];v[b]&&!e.isHidden&&!(p.initialized&&!1===B("onhide_start",b))&&(e.isSliding=!1,i&&i.hide(),!p.initialized||e.isClosed?(e.isClosed=!0,e.isHidden=!0,e.isVisible=!1,p.initialized||na(b),V("horz"===j[b].dir?"":"center"),(p.initialized||d.triggerEventsOnLoad)&&B("onhide_end",b)):(e.isHiding=!0,W(b,!1,c)))}},oa=function(a,c,b,d){if(C()){var a=y.call(this,a),e=p[a];v[a]&&e.isHidden&&!1!==B("onshow_start",a)&&(e.isSliding=!1,e.isShowing=!0,!1=== c?W(a,!0):ea(a,!1,b,d))}},ga=function(a,c){if(C()){var b=J(a),d=y.call(this,a),e=p[d];b&&b.stopImmediatePropagation();e.isHidden?oa(d):e.isClosed?ea(d,!!c):W(d)}},Za=function(a){var c=p[a];na(a);c.isClosed=!0;c.isVisible=!1},W=function(a,c,b,d){function e(){k.isMoving=!1;Z(i,!0);var a=j.oppositeEdge[i];p[a].noRoom&&(P(a),U(a));Ba();if(!d&&(p.initialized||h.triggerEventsOnLoad))l||B("onclose_end",i),l&&B("onshow_end",i),w&&B("onhide_end",i)}var i=y.call(this,a);if(!p.initialized&&v[i])Za(i);else if(C()){var g= v[i],h=q[i],k=p[i],m=j[i],r,l,w;t.queue(function(a){if(!g||!h.closable&&!k.isShowing&&!k.isHiding||!c&&k.isClosed&&!k.isShowing)return a();var f=!k.isShowing&&!1===B("onclose_start",i);l=k.isShowing;w=k.isHiding;delete k.isShowing;delete k.isHiding;if(f)return a();r=!b&&!k.isClosed&&"none"!=h.fxName_close;k.isMoving=!0;k.isClosed=!0;k.isVisible=!1;w?k.isHidden=!0:l&&(k.isHidden=!1);k.isSliding?ha(i,!1):V("horz"===j[i].dir?"":"center",!1);Aa(i);r?(la("center"+("horz"==m.dir?",west,east":""),!0),pa(i, !0),g.hide(h.fxName_close,h.fxSettings_close,h.fxSpeed_close,function(){pa(i,false);k.isClosed&&e();a()})):(na(i),e(),a())})}},Aa=function(a){var b=F[a],d=L[a],g=q[a],e=j[a].side.toLowerCase(),i=g.resizerClass,x=g.togglerClass,h="-"+a;b.css(e,w["inset"+j[a].side]).removeClass(i+"-open "+i+h+"-open").removeClass(i+"-sliding "+i+h+"-sliding").addClass(i+"-closed "+i+h+"-closed").unbind("dblclick."+G);g.resizable&&c.layout.plugins.draggable&&b.draggable("disable").removeClass("ui-state-disabled").css("cursor", "default").attr("title","");d&&(d.removeClass(x+"-open "+x+h+"-open").addClass(x+"-closed "+x+h+"-closed").attr("title",g.tips.Open),d.children(".content-open").hide(),d.children(".content-closed").css("display","block"));Ca(a,!1);p.initialized&&da()},ea=function(a,c,b,d){function e(){k.isMoving=!1;Fa(i);k.isSliding||(Ba(),V("vert"==j[i].dir?"center":"",!1));za(i)}if(C()){var i=y.call(this,a),g=v[i],h=q[i],k=p[i],m=j[i],r,l;t.queue(function(a){if(!g||!h.resizable&&!h.closable&&!k.isShowing||k.isVisible&& !k.isSliding)return a();if(k.isHidden&&!k.isShowing)a(),oa(i,!0);else{h.autoResize&&k.size!=h.size?X(i,h.size,!0,!0,!0):P(i,c);var f=B("onopen_start",i);if("abort"===f)return a();"NC"!==f&&P(i,c);if(k.minSize>k.maxSize)return Ca(i,!1),!d&&h.tips.noRoomToOpen&&alert(h.tips.noRoomToOpen),a();c?ha(i,!0):k.isSliding?ha(i,!1):h.slidable&&Z(i,!1);k.noRoom=!1;U(i);l=k.isShowing;delete k.isShowing;r=!b&&k.isClosed&&"none"!=h.fxName_open;k.isMoving=!0;k.isVisible=!0;k.isClosed=!1;l&&(k.isHidden=!1);r?(f="center"+ ("horz"==m.dir?",west,east":""),k.isSliding&&(f+=","+j.oppositeEdge[i]),la(f,!0),pa(i,!0),g.show(h.fxName_open,h.fxSettings_open,h.fxSpeed_open,function(){pa(i,false);k.isVisible&&e();a()})):(Pa(i),e(),a())}})}},za=function(a,b){var d=v[a],g=F[a],e=L[a],i=q[a],h=p[a],r=j[a].side.toLowerCase(),k=i.resizerClass,m=i.togglerClass,l="-"+a;g.css(r,w["inset"+j[a].side]+Y(a)).removeClass(k+"-closed "+k+l+"-closed").addClass(k+"-open "+k+l+"-open");h.isSliding?g.addClass(k+"-sliding "+k+l+"-sliding"):g.removeClass(k+ "-sliding "+k+l+"-sliding");i.resizerDblClickToggle&&g.bind("dblclick",ga);Q(0,g);i.resizable&&c.layout.plugins.draggable?g.draggable("enable").css("cursor",i.resizerCursor).attr("title",i.tips.Resize):h.isSliding||g.css("cursor","default");e&&(e.removeClass(m+"-closed "+m+l+"-closed").addClass(m+"-open "+m+l+"-open").attr("title",i.tips.Close),Q(0,e),e.children(".content-closed").hide(),e.children(".content-open").css("display","block"));Ca(a,!h.isSliding);c.extend(h,A(d));p.initialized&&(da(),ca(a, !0));if(!b&&(p.initialized||i.triggerEventsOnLoad)&&d.is(":visible"))B("onopen_end",a),h.isShowing&&B("onshow_end",a),p.initialized&&B("onresize_end",a)},Qa=function(a){function c(){e.isClosed?e.isMoving||ea(d,!0):ha(d,!0)}if(C()){var b=J(a),d=y.call(this,a),e=p[d],a=q[d].slideDelay_open;b&&b.stopImmediatePropagation();e.isClosed&&b&&"mouseenter"===b.type&&0<a?H.set(d+"_openSlider",c,a):c()}},Da=function(a){function b(){e.isClosed?ha(g,!1):e.isMoving||W(g)}if(C()){var d=J(a),g=y.call(this,a),a=q[g], e=p[g],i=e.isMoving?1E3:300;!e.isClosed&&!e.isResizing&&("click"===a.slideTrigger_close?b():a.preventQuickSlideClose&&e.isMoving||a.preventPrematureSlideClose&&d&&c.layout.isMouseOverElem(d,v[g])||(d?H.set(g+"_closeSlider",b,E(a.slideDelay_close,i)):b()))}},pa=function(a,c){var b=v[a],d=p[a],e=q[a],i=q.zIndexes;c?(b.css({zIndex:i.pane_animate}),"south"==a?b.css({top:w.insetTop+w.innerHeight-b.outerHeight()}):"east"==a&&b.css({left:w.insetLeft+w.innerWidth-b.outerWidth()})):(b.css({zIndex:d.isSliding? i.pane_sliding:i.pane_normal}),"south"==a?b.css({top:"auto"}):"east"==a&&!b.css("left").match(/\-99999/)&&b.css({left:"auto"}),h.msie&&(e.fxOpacityFix&&"slide"!=e.fxName_open&&b.css("filter")&&1==b.css("opacity"))&&b[0].style.removeAttribute("filter"))},Z=function(a,c){var b=q[a],d=F[a],e=b.slideTrigger_open.toLowerCase();if(d&&(!c||b.slidable))e.match(/mouseover/)?e=b.slideTrigger_open="mouseenter":e.match(/click|dblclick|mouseenter/)||(e=b.slideTrigger_open="click"),d[c?"bind":"unbind"](e+"."+G, Qa).css("cursor",c?b.sliderCursor:"default").attr("title",c?b.tips.Slide:"")},ha=function(a,c){function b(c){H.clear(a+"_closeSlider");c.stopPropagation()}var d=q[a],e=p[a],i=q.zIndexes,g=d.slideTrigger_close.toLowerCase(),h=c?"bind":"unbind",k=v[a],j=F[a];e.isSliding=c;H.clear(a+"_closeSlider");c&&Z(a,!1);k.css("zIndex",c?i.pane_sliding:i.pane_normal);j.css("zIndex",c?i.pane_sliding+2:i.resizer_normal);g.match(/click|mouseleave/)||(g=d.slideTrigger_close="mouseleave");j[h](g,Da);"mouseleave"===g&& (k[h]("mouseleave."+G,Da),j[h]("mouseenter."+G,b),k[h]("mouseenter."+G,b));c?"click"===g&&!d.resizable&&(j.css("cursor",c?d.sliderCursor:"default"),j.attr("title",c?d.tips.Close:"")):H.clear(a+"_closeSlider")},U=function(a,b,d,g){var b=q[a],e=p[a],i=j[a],h=v[a],l=F[a],k="vert"===i.dir,m=!1;if("center"===a||k&&e.noVerticalRoom)(m=0<=e.maxHeight)&&e.noRoom?(Pa(a),l&&l.show(),e.isVisible=!0,e.noRoom=!1,k&&(e.noVerticalRoom=!1),Fa(a)):!m&&!e.noRoom&&(na(a),l&&l.hide(),e.isVisible=!1,e.noRoom=!0);if("center"!== a)if(e.minSize<=e.maxSize){if(e.size>e.maxSize?X(a,e.maxSize,d,g,!0):e.size<e.minSize?X(a,e.minSize,d,g,!0):l&&(e.isVisible&&h.is(":visible"))&&(d=i.side.toLowerCase(),g=e.size+w["inset"+i.side],c.layout.cssNum(l,d)!=g&&l.css(d,g)),e.noRoom)e.wasOpen&&b.closable?b.autoReopen?ea(a,!1,!0,!0):e.noRoom=!1:oa(a,e.wasOpen,!0,!0)}else e.noRoom||(e.noRoom=!0,e.wasOpen=!e.isClosed&&!e.isSliding,e.isClosed||(b.closable?W(a,!0,!0):ya(a,!0)))},ma=function(a,c,b,d){if(C()){var a=y.call(this,a),e=q[a],i=p[a],i= e.livePaneResizing&&!i.isResizing;e.autoResize=!1;X(a,c,b,i,d)}},X=function(a,b,d,g,e){function i(){for(var a="width"===M?m.outerWidth():m.outerHeight(),a=[{pane:h,count:1,target:b,actual:a,correct:b===a,attempt:b,cssSize:H}],e=a[0],f="Inaccurate size after resizing the "+h+"-pane.";!e.correct;){thisTry={pane:h,count:e.count+1,target:b};thisTry.attempt=e.actual>b?E(0,e.attempt-(e.actual-b)):E(0,e.attempt+(b-e.actual));thisTry.cssSize=("horz"==j[h].dir?l:r)(v[h],thisTry.attempt);m.css(M,thisTry.cssSize); thisTry.actual="width"==M?m.outerWidth():m.outerHeight();thisTry.correct=b===thisTry.actual;1===a.length&&(S(f,!1,!0),S(e,!1,!0));S(thisTry,!1,!0);if(3<a.length)break;a.push(thisTry);e=a[a.length-1]}k.size=b;c.extend(k,A(m));k.isVisible&&m.is(":visible")&&(Ea&&Ea.css(z,b+w[Ua]),ca(h));!d&&(!J&&p.initialized&&k.isVisible)&&B("onresize_end",h);d||(k.isSliding||V("horz"==j[h].dir?"":"center",J,g),da());e=j.oppositeEdge[h];b<I&&p[e].noRoom&&(P(e),U(e,!1,d));1<a.length&&S(f+"\nSee the Error Console for details.", !0,!0)}if(C()){var h=y.call(this,a),K=q[h],k=p[h],m=v[h],Ea=F[h],z=j[h].side.toLowerCase(),M=j[h].sizeType.toLowerCase(),Ua="inset"+j[h].side,J=k.isResizing&&!K.triggerEventsDuringLiveResize,G=!0!==e&&K.animatePaneSizing,I,H;t.queue(function(a){P(h);I=k.size;b=T(h,b);b=E(b,T(h,K.minSize));b=qa(b,k.maxSize);if(b<k.minSize)a(),U(h,!1,d);else{if(!g&&b===I)return a();!d&&(p.initialized&&k.isVisible)&&B("onresize_start",h);H=("horz"==j[h].dir?l:r)(v[h],b);if(G&&m.is(":visible")){var e=c.layout.effects.size[h]|| c.layout.effects.size.all,e=K.fxSettings_size.easing||e.easing,f=q.zIndexes,w={};w[M]=H+"px";k.isMoving=!0;m.css({zIndex:f.pane_animate}).show().animate(w,K.fxSpeed_size,e,function(){m.css({zIndex:k.isSliding?f.pane_sliding:f.pane_normal});k.isMoving=!1;i();a()})}else m.css(M,H),m.is(":visible")?i():(k.size=b,c.extend(k,A(m))),a()}})}},V=function(a,b,d){a=(a?a:"east,west,center").split(",");c.each(a,function(a,e){if(v[e]){var f=q[e],g=p[e],j=v[e],k=!0,m={},k={top:Y("north",!0),bottom:Y("south",!0), left:Y("west",!0),right:Y("east",!0),width:0,height:0};k.width=w.innerWidth-k.left-k.right;k.height=w.innerHeight-k.bottom-k.top;k.top+=w.insetTop;k.bottom+=w.insetBottom;k.left+=w.insetLeft;k.right+=w.insetRight;c.extend(g,A(j));if("center"===e){if(!d&&g.isVisible&&k.width===g.outerWidth&&k.height===g.outerHeight)return!0;c.extend(g,ja(e),{maxWidth:k.width,maxHeight:k.height});m=k;m.width=r(j,m.width);m.height=l(j,m.height);k=0<=m.width&&0<=m.height;if(!p.initialized&&f.minWidth>g.outerWidth){var f= f.minWidth-g.outerWidth,t=q.east.minSize||0,z=q.west.minSize||0,M=p.east.size,y=p.west.size,C=M,J=y;0<f&&(p.east.isVisible&&M>t)&&(C=E(M-t,M-f),f-=M-C);0<f&&(p.west.isVisible&&y>z)&&(J=E(y-z,y-f),f-=y-J);if(0===f){M&&M!=t&&X("east",C,!0,d,!0);y&&y!=z&&X("west",J,!0,d,!0);V("center",b,d);return}}}else{g.isVisible&&!g.noVerticalRoom&&c.extend(g,A(j),ja(e));if(!d&&!g.noVerticalRoom&&k.height===g.outerHeight)return!0;m.top=k.top;m.bottom=k.bottom;m.height=l(j,k.height);g.maxHeight=m.height;k=0<=g.maxHeight; k||(g.noVerticalRoom=!0)}k?(!b&&p.initialized&&B("onresize_start",e),j.css(m),"center"!==e&&da(e),g.noRoom&&(!g.isClosed&&!g.isHidden)&&U(e),g.isVisible&&(c.extend(g,A(j)),p.initialized&&ca(e))):!g.noRoom&&g.isVisible&&U(e);if(!g.isVisible)return!0;"center"===e&&(g=h.isIE6||!h.boxModel,v.north&&(g||"IFRAME"==p.north.tagName)&&v.north.css("width",r(v.north,w.innerWidth)),v.south&&(g||"IFRAME"==p.south.tagName)&&v.south.css("width",r(v.south,w.innerWidth)));!b&&p.initialized&&B("onresize_end",e)}})}, ba=function(a){y(a);if(p.initialized){if(t.is(":visible:")&&(c.extend(p.container,A(t)),w.outerHeight)){if(!1===B("onresizeall_start"))return!1;var b,d,g;c.each(["south","north","east","west"],function(a,c){v[c]&&(g=p[c],d=q[c],d.autoResize&&g.size!=d.size?X(c,d.size,!0,!0,!0):(P(c),U(c,!1,!0,!0)))});V("",!0,!0);da();d=q;c.each(j.allPanes,function(a,c){(b=v[c])&&p[c].isVisible&&B("onresize_end",c)});B("onresizeall_end")}}else ka()},ra=function(a){a=y.call(this,a);if(q[a].resizeChildLayout){var c= v[a],b=N[a],d=z[a],e=O[a];d.child&&!e&&(e=d.child.container,e=O[a]=(e?e.data("layout"):0)||null);e&&e.destroyed&&(e=O[a]=null);e||(e=O[a]=c.data("layout")||(b?b.data("layout"):0)||null);d.child=O[a];e&&e.resizeAll()}},ca=function(a,b){if(C()){var d=y.call(this,a),d=d?d.split(","):j.allPanes;c.each(d,function(a,c){function d(a){return E(l.css.paddingBottom,parseInt(a.css("marginBottom"),10)||0)}function f(){var a=q[c].contentIgnoreSelector,a=h.nextAll().not(a||":lt(0)"),b=a.filter(":visible"),g=b.filter(":last"); u={top:h[0].offsetTop,height:h.outerHeight(),numFooters:a.length,hiddenFooters:a.length-b.length,spaceBelow:0};u.spaceAbove=u.top;u.bottom=u.top+u.height;u.spaceBelow=g.length?g[0].offsetTop+g.outerHeight()-u.bottom+d(g):d(h)}var g=v[c],h=N[c],j=q[c],l=p[c],u=l.content;if(!g||!h||!g.is(":visible"))return!0;if(!h.length&&(xa(c,!1),!h))return;if(!1!==B("onsizecontent_start",c)){if(!l.isMoving&&!l.isResizing||j.liveContentResizing||b||void 0==u.top)f(),0<u.hiddenFooters&&"hidden"===g.css("overflow")&& (g.css("overflow","visible"),f(),g.css("overflow","hidden"));g=l.innerHeight-(u.spaceAbove-l.css.paddingTop)-(u.spaceBelow-l.css.paddingBottom);if(!h.is(":visible")||u.height!=g)Ra(h,g,!0),u.height=g;p.initialized&&B("onsizecontent_end",c)}})}},da=function(a){a=(a=y.call(this,a))?a.split(","):j.borderPanes;c.each(a,function(a,b){var d=q[b],e=p[b],f=v[b],g=F[b],h=L[b],k;if(f&&g){var m=j[b].dir,t=e.isClosed?"_closed":"_open",A=d["spacing"+t],y=d["togglerAlign"+t],t=d["togglerLength"+t],z;if(0===A)g.hide(); else{!e.noRoom&&!e.isHidden&&g.show();"horz"===m?(z=w.innerWidth,e.resizerLength=z,f=c.layout.cssNum(f,"left"),g.css({width:r(g,z),height:l(g,A),left:-9999<f?f:w.insetLeft})):(z=f.outerHeight(),e.resizerLength=z,g.css({height:l(g,z),width:r(g,A),top:w.insetTop+Y("north",!0)}));Q(d,g);if(h){if(0===t||e.isSliding&&d.hideTogglerOnSlide){h.hide();return}h.show();if(!(0<t)||"100%"===t||t>z)t=z,y=0;else if(R(y))switch(y){case "top":case "left":y=0;break;case "bottom":case "right":y=z-t;break;default:y= ia((z-t)/2)}else f=parseInt(y,10),y=0<=y?f:z-t+f;if("horz"===m){var B=r(h,t);h.css({width:B,height:l(h,A),left:y,top:0});h.children(".content").each(function(){k=c(this);k.css("marginLeft",ia((B-k.outerWidth())/2))})}else{var C=l(h,t);h.css({height:C,width:r(h,A),top:y,left:0});h.children(".content").each(function(){k=c(this);k.css("marginTop",ia((C-k.outerHeight())/2))})}Q(0,h)}if(!p.initialized&&(d.initHidden||e.noRoom))g.hide(),h&&h.hide()}}})},Na=function(a){if(C()){var c=y.call(this,a),a=L[c], b=q[c];a&&(b.closable=!0,a.bind("click."+G,function(a){a.stopPropagation();ga(c)}).css("visibility","visible").css("cursor","pointer").attr("title",p[c].isClosed?b.tips.Open:b.tips.Close).show())}},Ca=function(a,b){c.layout.plugins.buttons&&c.each(p[a].pins,function(d,g){c.layout.buttons.setPinState(z,c(g),a,b)})},t=c(this).eq(0);if(!t.length)return S(q.errors.containerMissing);if(t.data("layoutContainer")&&t.data("layout"))return t.data("layout");var v={},N={},F={},L={},aa=c([]),w=p.container,G= p.id,z={options:q,state:p,container:t,panes:v,contents:N,resizers:F,togglers:L,hide:ya,show:oa,toggle:ga,open:ea,close:W,slideOpen:Qa,slideClose:Da,slideToggle:function(a){a=y.call(this,a);ga(a,!0)},setSizeLimits:P,_sizePane:X,sizePane:ma,sizeContent:ca,swapPanes:function(a,b){function d(a){var b=v[a],e=N[a];return!b?!1:{pane:a,P:b?b[0]:!1,C:e?e[0]:!1,state:c.extend(!0,{},p[a]),options:c.extend(!0,{},q[a])}}function g(a,b){if(a){var d=a.P,e=a.C,f=a.pane,h=j[b],i=h.side.toLowerCase(),o="inset"+h.side, l=c.extend(!0,{},p[b]),u=q[b],t={resizerCursor:u.resizerCursor};c.each(["fxName","fxSpeed","fxSettings"],function(a,b){t[b+"_open"]=u[b+"_open"];t[b+"_close"]=u[b+"_close"];t[b+"_size"]=u[b+"_size"]});v[b]=c(d).data({layoutPane:z[b],layoutEdge:b}).css(j.hidden).css(h.cssReq);N[b]=e?c(e):!1;q[b]=c.extend(!0,{},a.options,t);p[b]=c.extend(!0,{},a.state);d.className=d.className.replace(RegExp(u.paneClass+"-"+f,"g"),u.paneClass+"-"+b);va(b);h.dir!=j[f].dir?(d=r[b]||0,P(b),d=E(d,p[b].minSize),ma(b,d,!0, !0)):F[b].css(i,w[o]+(p[b].isVisible?Y(b):0));a.state.isVisible&&!l.isVisible?za(b,!0):(Aa(b),Z(b,!0));a=null}}if(C()){var e=y.call(this,a);p[e].edge=b;p[b].edge=e;if(!1===B("onswap_start",e)||!1===B("onswap_start",b))p[e].edge=e,p[b].edge=b;else{var h=d(e),l=d(b),r={};r[e]=h?h.state.size:0;r[b]=l?l.state.size:0;v[e]=!1;v[b]=!1;p[e]={};p[b]={};L[e]&&L[e].remove();L[b]&&L[b].remove();F[e]&&F[e].remove();F[b]&&F[b].remove();F[e]=F[b]=L[e]=L[b]=!1;g(h,b);g(l,e);h=l=r=null;v[e]&&v[e].css(j.visible);v[b]&& v[b].css(j.visible);ba();B("onswap_end",e);B("onswap_end",b)}}},initContent:xa,addPane:Ma,removePane:wa,createChildLayout:ua,enableClosable:Na,disableClosable:function(a,b){if(C()){var c=y.call(this,a),d=L[c];d&&(q[c].closable=!1,p[c].isClosed&&ea(c,!1,!0),d.unbind("."+G).css("visibility",b?"hidden":"visible").css("cursor","default").attr("title",""))}},enableSlidable:function(a){if(C()){var a=y.call(this,a),b=F[a];b&&b.data("draggable")&&(q[a].slidable=!0,s.isClosed&&Z(a,!0))}},disableSlidable:function(a){if(C()){var a= y.call(this,a),b=F[a];b&&(q[a].slidable=!1,p[a].isSliding?W(a,!1,!0):(Z(a,!1),b.css("cursor","default").attr("title",""),Q(null,b[0])))}},enableResizable:function(a){if(C()){var a=y.call(this,a),b=F[a],c=q[a];b&&b.data("draggable")&&(c.resizable=!0,b.draggable("enable"),p[a].isClosed||b.css("cursor",c.resizerCursor).attr("title",c.tips.Resize))}},disableResizable:function(a){if(C()){var a=y.call(this,a),b=F[a];b&&b.data("draggable")&&(q[a].resizable=!1,b.draggable("disable").css("cursor","default").attr("title", ""),Q(null,b[0]))}},allowOverflow:d,resetOverflow:g,destroy:function(a,b){c(window).unbind("."+G);c(document).unbind("."+G);"object"===typeof a?y(a):b=a;t.clearQueue().removeData("layout").removeData("layoutContainer").removeClass(q.containerClass).unbind("."+G);aa.remove();c.each(j.allPanes,function(a,c){wa(c,!1,!0,b)});t.data("layoutCSS")&&!t.data("layoutRole")&&t.css(t.data("layoutCSS")).removeData("layoutCSS");"BODY"===w.tagName&&(t=c("html")).data("layoutCSS")&&t.css(t.data("layoutCSS")).removeData("layoutCSS"); fa(z,c.layout.onDestroy);Ka();for(n in z)n.match(/^(container|options)$/)||delete z[n];z.destroyed=!0;return z},initPanes:C,resizeAll:ba,runCallbacks:B,hasParentLayout:!1,children:O,north:!1,south:!1,west:!1,east:!1,center:!1};return"cancel"===function(){Va();var a=q;p.creatingLayout=!0;fa(z,c.layout.onCreate);if(!1===B("onload_start"))return"cancel";var b=t[0],d=w.tagName=b.tagName,g=w.id=b.id,e=w.className=b.className,b=q,h=b.name,j="BODY"===d,l={},k=t.data("parentLayout"),m=t.data("layoutEdge"), r=k&&m;w.selector=t.selector.split(".slice")[0];w.ref=(b.name?b.name+" layout / ":"")+d+(g?"#"+g:e?".["+e+"]":"");t.data({layout:z,layoutContainer:G}).addClass(b.containerClass);d={destroy:"",initPanes:"",resizeAll:"resizeAll",resize:"resizeAll"};for(h in d)t.bind("layout"+h.toLowerCase()+"."+G,z[d[h]||h]);r&&(z.hasParentLayout=!0,k[m].child=k.children[m]=t.data("layout"));t.data("layoutCSS")||(j?(l=c.extend(I(t,"overflow,position,margin,padding,border"),{height:t.css("height"),overflow:t.css("overflow"), overflowX:t.css("overflowX"),overflowY:t.css("overflowY")}),d=c("html"),d.data("layoutCSS",{height:"auto",overflow:d.css("overflow"),overflowX:d.css("overflowX"),overflowY:d.css("overflowY")})):l=I(t,"overflow,position,margin,padding,border,top,bottom,left,right,width,height,overflow,overflowX,overflowY"),t.data("layoutCSS",l));try{if(j)c("html").css({height:"100%",overflow:"hidden",overflowX:"hidden",overflowY:"hidden"}),c("body").css({position:"relative",height:"100%",overflow:"hidden",overflowX:"hidden", overflowY:"hidden",margin:0,padding:0,border:"none"}),c.extend(w,A(t));else{var l={overflow:"hidden",overflowX:"hidden",overflowY:"hidden"},v=t.css("position");t.css("height");if(!r&&(!v||!v.match(/fixed|absolute|relative/)))l.position="relative";t.css(l);t.is(":visible")&&(c.extend(w,A(t)),1>w.innerHeight&&S(b.errors.noContainerHeight.replace(/CONTAINER/,w.ref)))}}catch(y){}La();c(window).bind("unload."+G,Ka);fa(z,c.layout.onLoad);a.initPanes&&ka();delete p.creatingLayout;return p.initialized}()? null:z};c.ui||(c.ui={});c.ui.cookie={acceptsCookies:!!navigator.cookieEnabled,read:function(a){for(var b=document.cookie,b=b?b.split(";"):[],d,g=0,h=b.length;g<h;g++){d=c.trim(b[g]).split("=");if(d[0]==a)return decodeURIComponent(d[1])}return null},write:function(a,b,c){var g="",h="",j=false,c=c||{},r=c.expires;if(r&&r.toUTCString)h=r;else if(r===null||typeof r==="number"){h=new Date;if(r>0)h.setDate(h.getDate()+r);else{h.setFullYear(1970);j=true}}h&&(g=g+(";expires="+h.toUTCString()));c.path&&(g= g+(";path="+c.path));c.domain&&(g=g+(";domain="+c.domain));c.secure&&(g=g+";secure");document.cookie=a+"="+(j?"":encodeURIComponent(b))+g},clear:function(a){c.ui.cookie.write(a,"",{expires:-1})}};c.cookie||(c.cookie=function(a,b,d){var g=c.ui.cookie;if(b===null)g.clear(a);else{if(b===void 0)return g.read(a);g.write(a,b,d)}});c.layout.plugins.stateManagement=!0;c.layout.config.optionRootKeys.push("stateManagement");c.layout.defaults.stateManagement={enabled:!1,autoSave:!0,autoLoad:!0,stateKeys:"north.size,south.size,east.size,west.size,north.isClosed,south.isClosed,east.isClosed,west.isClosed,north.isHidden,south.isHidden,east.isHidden,west.isHidden", cookie:{name:"",domain:"",path:"",expires:"",secure:!1}};c.layout.optionsMap.layout.push("stateManagement");c.layout.state={saveCookie:function(a,b,d){var g=a.options,h=g.stateManagement,d=c.extend(true,{},h.cookie,d||null),a=a.state.stateData=a.readState(b||h.stateKeys);c.ui.cookie.write(d.name||g.name||"Layout",c.layout.state.encodeJSON(a),d);return c.extend(true,{},a)},deleteCookie:function(a){a=a.options;c.ui.cookie.clear(a.stateManagement.cookie.name||a.name||"Layout")},readCookie:function(a){a= a.options;return(a=c.ui.cookie.read(a.stateManagement.cookie.name||a.name||"Layout"))?c.layout.state.decodeJSON(a):{}},loadCookie:function(a){var b=c.layout.state.readCookie(a);if(b){a.state.stateData=c.extend(true,{},b);a.loadState(b)}return b},loadState:function(a,b,d){b=c.layout.transformData(b);if(!c.isEmptyObject(b)){c.extend(true,a.options,b);if(a.state.initialized){var g,h,j,r,l,A=d===false;c.each(c.layout.config.borderPanes,function(c,d){state=a.state[d];h=b[d];if(typeof h=="object"){j=h.size; l=h.initClosed;r=h.initHidden;(g=state.isVisible)||a.sizePane(d,j,false,false);r===true?a.hide(d,A):l===false?a.open(d,false,A):l===true?a.close(d,false,A):r===false&&a.show(d,false,A);g&&a.sizePane(d,j,false,A)}})}}},readState:function(a,b){var d={},g={isClosed:"initClosed",isHidden:"initHidden"},h=a.state,j=c.layout.config.allPanes,r,l,A;if(!b)b=a.options.stateManagement.stateKeys;c.isArray(b)&&(b=b.join(","));for(var b=b.replace(/__/g,".").split(","),I=0,E=b.length;I<E;I++){r=b[I].split(".");l= r[0];r=r[1];if(!(c.inArray(l,j)<0)){A=h[l][r];if(A!=void 0){r=="isClosed"&&h[l].isSliding&&(A=true);(d[l]||(d[l]={}))[g[r]?g[r]:r]=A}}}return d},encodeJSON:function(a){function b(a){var c=[],h=0,j,r,l;for(j in a){r=a[j];l=typeof r;l=="string"?r='"'+r+'"':l=="object"&&(r=b(r));c[h++]='"'+j+'":'+r}return"{"+c.join(",")+"}"}return b(a)},decodeJSON:function(a){try{return c.parseJSON?c.parseJSON(a):window.eval("("+a+")")||{}}catch(b){return{}}},_create:function(a){var b=c.layout.state;c.extend(a,{readCookie:function(){return b.readCookie(a)}, deleteCookie:function(){b.deleteCookie(a)},saveCookie:function(c,d){return b.saveCookie(a,c,d)},loadCookie:function(){return b.loadCookie(a)},loadState:function(c,d){b.loadState(a,c,d)},readState:function(c){return b.readState(a,c)},encodeJSON:b.encodeJSON,decodeJSON:b.decodeJSON});a.state.stateData={};var d=a.options.stateManagement;if(d.enabled)d.autoLoad?a.loadCookie():a.state.stateData=a.readCookie()},_unload:function(a){var b=a.options.stateManagement;if(b.enabled)b.autoSave?a.saveCookie():a.state.stateData= a.readState()}};c.layout.onCreate.push(c.layout.state._create);c.layout.onUnload.push(c.layout.state._unload);c.layout.plugins.buttons=!0;c.layout.defaults.autoBindCustomButtons=!1;c.layout.optionsMap.layout.push("autoBindCustomButtons");c.layout.buttons={init:function(a){var b=a.options.name||"",d;c.each(["toggle","open","close","pin","toggle-slide","open-slide"],function(g,h){c.each(c.layout.config.borderPanes,function(g,r){c(".ui-layout-button-"+h+"-"+r).each(function(){d=c(this).data("layoutName")|| c(this).attr("layoutName");(d==void 0||d===b)&&a.bindButton(this,h,r)})})})},get:function(a,b,d,g){var h=c(b),a=a.options,j=a.errors.addButtonError;if(h.length)if(c.inArray(d,c.layout.config.borderPanes)<0){c.layout.msg(j+" "+a.errors.pane+": "+d,true);h=c("")}else{b=a[d].buttonClass+"-"+g;h.addClass(b+" "+b+"-"+d).data("layoutName",a.name)}else c.layout.msg(j+" "+a.errors.selector+": "+b,true);return h},bind:function(a,b,d,g){var h=c.layout.buttons;switch(d.toLowerCase()){case "toggle":h.addToggle(a, b,g);break;case "open":h.addOpen(a,b,g);break;case "close":h.addClose(a,b,g);break;case "pin":h.addPin(a,b,g);break;case "toggle-slide":h.addToggle(a,b,g,true);break;case "open-slide":h.addOpen(a,b,g,true)}return a},addToggle:function(a,b,d,g){c.layout.buttons.get(a,b,d,"toggle").click(function(b){a.toggle(d,!!g);b.stopPropagation()});return a},addOpen:function(a,b,d,g){c.layout.buttons.get(a,b,d,"open").attr("title",a.options[d].tips.Close).click(function(b){a.open(d,!!g);b.stopPropagation()});return a}, addClose:function(a,b,d){c.layout.buttons.get(a,b,d,"close").attr("title",a.options[d].tips.Open).click(function(b){a.close(d);b.stopPropagation()});return a},addPin:function(a,b,d){var g=c.layout.buttons,h=g.get(a,b,d,"pin");if(h.length){var j=a.state[d];h.click(function(b){g.setPinState(a,c(this),d,j.isSliding||j.isClosed);j.isSliding||j.isClosed?a.open(d):a.close(d);b.stopPropagation()});g.setPinState(a,h,d,!j.isClosed&&!j.isSliding);j.pins.push(b)}return a},setPinState:function(a,b,c,g){var h= b.attr("pin");if(!(h&&g===(h=="down"))){var a=a.options[c],h=a.buttonClass+"-pin",j=h+"-"+c,c=h+"-up "+j+"-up",h=h+"-down "+j+"-down";b.attr("pin",g?"down":"up").attr("title",g?a.tips.Unpin:a.tips.Pin).removeClass(g?c:h).addClass(g?h:c)}},syncPinBtns:function(a,b,d){c.each(state[b].pins,function(g,h){c.layout.buttons.setPinState(a,c(h),b,d)})},_load:function(a){var b=c.layout.buttons;c.extend(a,{bindButton:function(c,d,j){return b.bind(a,c,d,j)},addToggleBtn:function(c,d,j){return b.addToggle(a,c, d,j)},addOpenBtn:function(c,d,j){return b.addOpen(a,c,d,j)},addCloseBtn:function(c,d){return b.addClose(a,c,d)},addPinBtn:function(c,d){return b.addPin(a,c,d)}});for(var d=0;d<4;d++)a.state[c.layout.config.borderPanes[d]].pins=[];a.options.autoBindCustomButtons&&b.init(a)},_unload:function(){}};c.layout.onLoad.push(c.layout.buttons._load);c.layout.plugins.browserZoom=!0;c.layout.defaults.browserZoomCheckInterval=1E3;c.layout.optionsMap.layout.push("browserZoomCheckInterval");c.layout.browserZoom= {_init:function(a){c.layout.browserZoom.ratio()!==false&&c.layout.browserZoom._setTimer(a)},_setTimer:function(a){if(!a.destroyed){var b=a.options,d=a.state,g=a.hasParentLayout?5E3:Math.max(b.browserZoomCheckInterval,100);setTimeout(function(){if(!a.destroyed&&b.resizeWithWindow){var g=c.layout.browserZoom.ratio();if(g!==d.browserZoom){d.browserZoom=g;a.resizeAll()}c.layout.browserZoom._setTimer(a)}},g)}},ratio:function(){function a(a,b){return(parseInt(a,10)/parseInt(b,10)*100).toFixed()}var b=window, d=screen,g=document,h=g.documentElement||g.body,j=c.layout.browser,r=j.version,l,A,E;return j.msie&&r>8||!j.msie?false:d.deviceXDPI?a(d.deviceXDPI,d.systemXDPI):j.webkit&&(l=g.body.getBoundingClientRect)?a(l.left-l.right,g.body.offsetWidth):j.webkit&&(A=b.outerWidth)?a(A,b.innerWidth):(A=d.width)&&(E=h.clientWidth)?a(A,E):false}};c.layout.onReady.push(c.layout.browserZoom._init)})(jQuery);
ztfy.jqueryui
/ztfy.jqueryui-0.7.12.tar.gz/ztfy.jqueryui-0.7.12/src/ztfy/jqueryui/resources/js/jquery-layout.min.js
jquery-layout.min.js