FIX: conflict in settings.py
authorYasin <mohammed-yasin.rahman@lip6.fr>
Mon, 9 Sep 2013 09:21:40 +0000 (11:21 +0200)
committerYasin <mohammed-yasin.rahman@lip6.fr>
Mon, 9 Sep 2013 09:21:40 +0000 (11:21 +0200)
628 files changed:
.gitignore
LICENSE [new file with mode: 0644]
Makefile
README
README.migrations [new file with mode: 0644]
auth/backend.py [deleted file]
auth/css/login.css
auth/manifoldbackend.py
auth/templates/widget-login.html
auth/views.py
debian/control
debug_platform/__init__.py [moved from plugins/googlemap/__init__.py with 100% similarity]
debug_platform/urls.py [new file with mode: 0644]
debug_platform/views.py [new file with mode: 0644]
devel/server-loop.sh
manifold/core/__init__.py [new file with mode: 0644]
manifold/core/filter.py [new file with mode: 0644]
manifold/core/query.py [new file with mode: 0644]
manifold/core/result_value.py [new file with mode: 0644]
manifold/css/manifold.css [new file with mode: 0644]
manifold/js/class.js [new file with mode: 0644]
manifold/js/manifold-query.js
manifold/js/manifold.js
manifold/js/metadata.js
manifold/js/plugin-sample.html [new file with mode: 0644]
manifold/js/plugin.js [new file with mode: 0644]
manifold/manifoldapi.py
manifold/manifoldproxy.py
manifold/manifoldquery.py [deleted file]
manifold/manifoldresult.py
manifold/metadata.py
manifold/util/__init__.py [new file with mode: 0644]
manifold/util/clause.py [new file with mode: 0644]
manifold/util/frozendict.py [new file with mode: 0644]
manifold/util/misc.py [new file with mode: 0644]
manifold/util/predicate.py [new file with mode: 0644]
manifold/util/singleton.py [new file with mode: 0644]
manifold/util/type.py [new file with mode: 0644]
myslice/config.py
myslice/settings.py
myslice/urls.py
myslice/viewutils.py
plugins/active_filters/__init__.py [new file with mode: 0644]
plugins/active_filters/static/active_filters.html [new file with mode: 0644]
plugins/active_filters/static/css/active_filters.css [new file with mode: 0644]
plugins/active_filters/static/img/details_close.png [new file with mode: 0644]
plugins/active_filters/static/img/details_open.png [new file with mode: 0644]
plugins/active_filters/static/js/active_filters.js [new file with mode: 0644]
plugins/code_editor/__init__.py [new file with mode: 0644]
plugins/code_editor/static/code_editor.html [new file with mode: 0644]
plugins/code_editor/static/img/handle-h.png [new file with mode: 0644]
plugins/code_editor/static/img/handle-v.png [new file with mode: 0644]
plugins/code_editor/static/img/initializing.png [new file with mode: 0644]
plugins/code_editor/static/js/Actions.js [new file with mode: 0644]
plugins/code_editor/static/js/EditorCM.js [new file with mode: 0644]
plugins/code_editor/static/js/LayoutCM.js [new file with mode: 0644]
plugins/code_editor/static/js/code_editor.js [new file with mode: 0644]
plugins/code_editor/static/js/moo-clientcide-1.3.js [new file with mode: 0644]
plugins/debug_platform/__init__.py [new file with mode: 0644]
plugins/debug_platform/static/css/debug_platform.css [new file with mode: 0644]
plugins/debug_platform/static/debug_platform.html [new file with mode: 0644]
plugins/debug_platform/static/js/debug_platform.js [new file with mode: 0644]
plugins/form/__init__.py [new file with mode: 0644]
plugins/form/static/css/form.css [new file with mode: 0644]
plugins/form/static/form.html [new file with mode: 0644]
plugins/form/static/js/form.js [new file with mode: 0644]
plugins/form/static/js/jquery.validate.js [new file with mode: 0644]
plugins/googlemap/googlemap.html [deleted file]
plugins/googlemap/googlemap.js [deleted file]
plugins/googlemaps/__init__.py [moved from plugins/googlemap/googlemap.py with 72% similarity]
plugins/googlemaps/static/css/googlemaps.css [moved from plugins/googlemap/googlemap.css with 97% similarity]
plugins/googlemaps/static/googlemaps.html [new file with mode: 0644]
plugins/googlemaps/static/js/googlemaps.js [new file with mode: 0644]
plugins/googlemaps/static/js/markerclusterer.js [moved from plugins/googlemap/markerclusterer.js with 100% similarity]
plugins/googlemaps/static/js/markerclusterer_compiled.js [moved from plugins/googlemap/markerclusterer_compiled.js with 100% similarity]
plugins/googlemaps/static/js/markerclusterer_packed.js [moved from plugins/googlemap/markerclusterer_packed.js with 100% similarity]
plugins/hazelnut/DataTables.php [deleted file]
plugins/hazelnut/__init__.py
plugins/hazelnut/hazelnut.html [deleted file]
plugins/hazelnut/hazelnut.js [deleted file]
plugins/hazelnut/hazelnut.py [deleted file]
plugins/hazelnut/static/css/hazelnut.css [moved from plugins/hazelnut/hazelnut.css with 100% similarity]
plugins/hazelnut/static/hazelnut.html [new file with mode: 0644]
plugins/hazelnut/static/img/README [moved from plugins/hazelnut/img/README with 100% similarity]
plugins/hazelnut/static/img/tablesort-bullet1.png [moved from plugins/hazelnut/img/tablesort-bullet1.png with 100% similarity]
plugins/hazelnut/static/img/tablesort-bullet2.png [moved from plugins/hazelnut/img/tablesort-bullet2.png with 100% similarity]
plugins/hazelnut/static/img/tablesort-col-alt.png [moved from plugins/hazelnut/img/tablesort-col-alt.png with 100% similarity]
plugins/hazelnut/static/img/tablesort-gradient.png [moved from plugins/hazelnut/img/tablesort-gradient.png with 100% similarity]
plugins/hazelnut/static/img/tablesort-header-down.png [moved from plugins/hazelnut/img/tablesort-header-down.png with 100% similarity]
plugins/hazelnut/static/img/tablesort-header-sortable.png [moved from plugins/hazelnut/img/tablesort-header-sortable.png with 100% similarity]
plugins/hazelnut/static/img/tablesort-header-up.png [moved from plugins/hazelnut/img/tablesort-header-up.png with 100% similarity]
plugins/hazelnut/static/img/tablesort-header.png [moved from plugins/hazelnut/img/tablesort-header.png with 100% similarity]
plugins/hazelnut/static/img/tablesort-td-alt.png [moved from plugins/hazelnut/img/tablesort-td-alt.png with 100% similarity]
plugins/hazelnut/static/img/toggle-hidden.png [moved from plugins/hazelnut/img/toggle-hidden.png with 100% similarity]
plugins/hazelnut/static/img/toggle-visible.png [moved from plugins/hazelnut/img/toggle-visible.png with 100% similarity]
plugins/hazelnut/static/js/hazelnut.js [new file with mode: 0644]
plugins/lists/static/css/simplelist.css [moved from plugins/lists/simplelist.css with 100% similarity]
plugins/lists/static/css/staticlist.css [moved from plugins/lists/staticlist.css with 100% similarity]
plugins/lists/static/js/simplelist.js [moved from plugins/lists/simplelist.js with 55% similarity]
plugins/lists/static/js/with-datatables.js [moved from plugins/lists/with-datatables.js with 100% similarity]
plugins/lists/static/simplelist.html [moved from plugins/lists/simplelist.html with 100% similarity]
plugins/lists/static/staticlist.html [moved from plugins/lists/staticlist.html with 100% similarity]
plugins/messages/static/css/messages.css [moved from plugins/messages/messages.css with 100% similarity]
plugins/messages/static/js/messages.js [moved from plugins/messages/messages.js with 100% similarity]
plugins/messages/static/messages.html [moved from plugins/messages/messages.html with 100% similarity]
plugins/myplugin/__init__.py [new file with mode: 0644]
plugins/myplugin/static/css/myplugin.css [new file with mode: 0644]
plugins/myplugin/static/js/myplugin.js [new file with mode: 0644]
plugins/myplugin/static/myplugin.html [new file with mode: 0644]
plugins/pres_view/__init__.py [new file with mode: 0644]
plugins/pres_view/config_method_animation [new file with mode: 0644]
plugins/pres_view/config_method_dynamic [new file with mode: 0644]
plugins/pres_view/config_method_static [new file with mode: 0644]
plugins/pres_view/config_method_static.bk [new file with mode: 0644]
plugins/pres_view/daemon-todo/daemon.py [new file with mode: 0644]
plugins/pres_view/daemon-todo/event2.py [new file with mode: 0644]
plugins/pres_view/daemon-todo/eventc.py [new file with mode: 0644]
plugins/pres_view/daemon-todo/eventd.py [new file with mode: 0644]
plugins/pres_view/static/css/jquery-ui.css [new file with mode: 0644]
plugins/pres_view/static/css/pres_view.css [new file with mode: 0644]
plugins/pres_view/static/js/MooTools.js [new file with mode: 0644]
plugins/pres_view/static/js/afficher_par_id.js [new file with mode: 0644]
plugins/pres_view/static/js/config.js [new file with mode: 0644]
plugins/pres_view/static/js/dynamic.js [new file with mode: 0644]
plugins/pres_view/static/js/initmap.js [new file with mode: 0644]
plugins/pres_view/static/js/jquery-ui.min.js [new file with mode: 0644]
plugins/pres_view/static/js/jquery.min.js [new file with mode: 0644]
plugins/pres_view/static/js/mootools-core.js [new file with mode: 0644]
plugins/pres_view/static/js/pres_view.js [new file with mode: 0644]
plugins/pres_view/static/js/recup_data.js [new file with mode: 0644]
plugins/pres_view/static/js/recup_direct.js [new file with mode: 0644]
plugins/pres_view/static/js/recup_liste.js [new file with mode: 0644]
plugins/pres_view/static/js/recup_tout_sites.js [new file with mode: 0644]
plugins/pres_view/static/js/visible.js [new file with mode: 0644]
plugins/pres_view/static/pres_view.html [new file with mode: 0644]
plugins/query_editor/__init__.py [new file with mode: 0644]
plugins/query_editor/static/css/demo_page.css [new file with mode: 0644]
plugins/query_editor/static/css/demo_table.css [new file with mode: 0644]
plugins/query_editor/static/css/query_editor.css [new file with mode: 0644]
plugins/query_editor/static/filter_input_integer.html [new file with mode: 0644]
plugins/query_editor/static/filter_input_others.html [new file with mode: 0644]
plugins/query_editor/static/filter_input_string.html [new file with mode: 0644]
plugins/query_editor/static/filter_input_string_values.html [new file with mode: 0644]
plugins/query_editor/static/img/details_close.png [new file with mode: 0644]
plugins/query_editor/static/img/myslice-icon-filter.png [new file with mode: 0644]
plugins/query_editor/static/js/query_editor.js [new file with mode: 0644]
plugins/query_editor/static/query_editor.html [new file with mode: 0644]
plugins/querycode/static/css/querycode.css [moved from plugins/querycode/querycode.css with 100% similarity]
plugins/querycode/static/js/querycode.js [moved from plugins/querycode/querycode.js with 97% similarity]
plugins/querycode/static/querycode.html [moved from plugins/querycode/querycode.html with 100% similarity]
plugins/quickfilter/static/css/quickfilter.css [moved from plugins/quickfilter/quickfilter.css with 100% similarity]
plugins/quickfilter/static/js/quickfilter.js [moved from plugins/quickfilter/quickfilter.js with 100% similarity]
plugins/quickfilter/static/quickfilter.html [moved from plugins/quickfilter/quickfilter.html with 100% similarity]
plugins/resources_selected/__init__.py [new file with mode: 0644]
plugins/resources_selected/static/css/resources_selected.css [new file with mode: 0644]
plugins/resources_selected/static/js/resources_selected.js [new file with mode: 0644]
plugins/resources_selected/static/resources_selected.html [new file with mode: 0644]
plugins/senslabmap/static/css/senslabmap.css [moved from plugins/senslabmap/senslabmap.css with 100% similarity]
plugins/senslabmap/static/js/grenoble.js [moved from plugins/senslabmap/grenoble.js with 100% similarity]
plugins/senslabmap/static/js/senslabmap.js [moved from plugins/senslabmap/senslabmap.js with 100% similarity]
plugins/senslabmap/static/js/three.js [moved from plugins/senslabmap/three.js with 100% similarity]
plugins/senslabmap/static/js/viewer3D.js [moved from plugins/senslabmap/viewer3D.js with 100% similarity]
plugins/senslabmap/static/senslabmap.html [moved from plugins/senslabmap/senslabmap.html with 100% similarity]
plugins/stack/static/stack.html [moved from plugins/stack/stack.html with 100% similarity]
plugins/tabs/static/css/tabs.css [moved from plugins/tabs/tabs.css with 100% similarity]
plugins/tabs/static/js/tabs.js [new file with mode: 0644]
plugins/tabs/static/tabs.html [moved from plugins/tabs/tabs.html with 100% similarity]
plugins/tabs/tabs.py
plugins/updater/WARNING [new file with mode: 0644]
plugins/updater/__init__.py
plugins/updater/static/css/updater.css [moved from plugins/updater/updater.css with 100% similarity]
plugins/updater/static/js/updater.js [new file with mode: 0644]
plugins/updater/static/updater.html [new file with mode: 0644]
plugins/updater/updater.html [deleted file]
plugins/updater/updater.js [deleted file]
plugins/updater/updater.py [deleted file]
plugins/wizard/__init__.py [new file with mode: 0644]
plugins/wizard/static/css/wizard.css [new file with mode: 0644]
plugins/wizard/static/js/wizard.js [new file with mode: 0644]
plugins/wizard/static/test.html [new file with mode: 0644]
plugins/wizard/static/wizard.html [new file with mode: 0644]
portal/__init__.py [new file with mode: 0644]
portal/accountview.py [new file with mode: 0644]
portal/actions.py [new file with mode: 0644]
portal/contactview.py [new file with mode: 0644]
portal/dashboardview.py [new file with mode: 0644]
portal/event.py [new file with mode: 0644]
portal/forms.py [new file with mode: 0644]
portal/homeview.py [new file with mode: 0644]
portal/img/account_validated.png [new file with mode: 0644]
portal/img/account_validated.png.olf [new file with mode: 0644]
portal/migrations/0001_initial.py [new file with mode: 0644]
portal/migrations/0002_extend_slice.py [new file with mode: 0644]
portal/migrations/0003_extend_slice.py [new file with mode: 0644]
portal/migrations/__init__.py [new file with mode: 0644]
portal/models.py [new file with mode: 0644]
portal/platformsview.py [new file with mode: 0644]
portal/platformview.py [new file with mode: 0644]
portal/portalpage.py [new file with mode: 0644]
portal/registrationview.py [new file with mode: 0644]
portal/signals.py [new file with mode: 0644]
portal/slicerequestview.py [new file with mode: 0644]
portal/sliceview.py [new file with mode: 0644]
portal/static/css/dashboard.css [new file with mode: 0644]
portal/static/css/my_account.common.css [new file with mode: 0644]
portal/static/css/my_account.profile.css [new file with mode: 0644]
portal/static/css/onelab.css [new file with mode: 0644]
portal/static/css/registration.css [new file with mode: 0644]
portal/static/css/validate_pending.css [new file with mode: 0644]
portal/static/img/authority-icon.png [new file with mode: 0644]
portal/static/img/experiments.png [new file with mode: 0644]
portal/static/img/ques_icon.png [new file with mode: 0644]
portal/static/img/resource-icon.png [new file with mode: 0644]
portal/static/img/slice-icon.png [new file with mode: 0644]
portal/static/img/testbeds.png [new file with mode: 0644]
portal/static/img/user-icon.png [new file with mode: 0644]
portal/static/img/user.png [new file with mode: 0644]
portal/static/jquery.validate.js [new file with mode: 0644]
portal/static/my_account.edit_profile.js [new file with mode: 0644]
portal/static/my_account.register.js [new file with mode: 0644]
portal/templates/account_validated.html [new file with mode: 0644]
portal/templates/contact.html [new file with mode: 0644]
portal/templates/contact_sent.html [new file with mode: 0644]
portal/templates/dashboard.html [new file with mode: 0644]
portal/templates/home-view.html [new file with mode: 0644]
portal/templates/my_account.html [new file with mode: 0644]
portal/templates/platform.html [new file with mode: 0644]
portal/templates/platforms.html [new file with mode: 0644]
portal/templates/register_user_wizard.html [new file with mode: 0644]
portal/templates/registration_view.html [new file with mode: 0644]
portal/templates/slice_request.html [new file with mode: 0644]
portal/templates/slice_request_email.txt [new file with mode: 0644]
portal/templates/slicereq_recvd.html [new file with mode: 0644]
portal/templates/user-registration-step2.html [new file with mode: 0644]
portal/templates/user_register.html [new file with mode: 0644]
portal/templates/user_register_complete.html [new file with mode: 0644]
portal/templates/user_register_email.txt [new file with mode: 0644]
portal/templates/user_register_email_subject.txt [new file with mode: 0644]
portal/templates/user_request_email.txt [new file with mode: 0644]
portal/templates/validate_pending.html [new file with mode: 0644]
portal/templateviews.py [new file with mode: 0644]
portal/tests.py [new file with mode: 0644]
portal/tests/__init__.py [new file with mode: 0644]
portal/tests/models.py [new file with mode: 0755]
portal/urls.py [new file with mode: 0644]
portal/util.py [new file with mode: 0644]
portal/views.py [new file with mode: 0644]
requirements.txt [new file with mode: 0644]
requirements/common.txt [new file with mode: 0644]
requirements/dev.txt [new file with mode: 0644]
requirements/prod.txt [new file with mode: 0644]
requirements/test.txt [new file with mode: 0644]
reset.py [new file with mode: 0755]
sample/__init__.py [new file with mode: 0644]
sample/templates/websockets.html [new file with mode: 0644]
sample/templates/websockets2.html [new file with mode: 0644]
sample/urls.py [new file with mode: 0644]
sample/views.py [new file with mode: 0644]
third-party/bootstrap
third-party/bootstrap-3.0.0/css/bootstrap-theme.css [new file with mode: 0644]
third-party/bootstrap-3.0.0/css/bootstrap-theme.min.css [new file with mode: 0644]
third-party/bootstrap-3.0.0/css/bootstrap.css [new file with mode: 0644]
third-party/bootstrap-3.0.0/css/bootstrap.min.css [new file with mode: 0644]
third-party/bootstrap-3.0.0/fonts/glyphicons-halflings-regular.eot [new file with mode: 0644]
third-party/bootstrap-3.0.0/fonts/glyphicons-halflings-regular.svg [new file with mode: 0644]
third-party/bootstrap-3.0.0/fonts/glyphicons-halflings-regular.ttf [new file with mode: 0644]
third-party/bootstrap-3.0.0/fonts/glyphicons-halflings-regular.woff [new file with mode: 0644]
third-party/bootstrap-3.0.0/js/bootstrap.js [new file with mode: 0644]
third-party/bootstrap-3.0.0/js/bootstrap.min.js [new file with mode: 0644]
third-party/codemirror-3.15/.gitattributes [new file with mode: 0644]
third-party/codemirror-3.15/.gitignore [new file with mode: 0644]
third-party/codemirror-3.15/.travis.yml [new file with mode: 0644]
third-party/codemirror-3.15/CONTRIBUTING.md [new file with mode: 0644]
third-party/codemirror-3.15/LICENSE [new file with mode: 0644]
third-party/codemirror-3.15/README.md [new file with mode: 0644]
third-party/codemirror-3.15/addon/comment/comment.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/dialog/dialog.css [new file with mode: 0644]
third-party/codemirror-3.15/addon/dialog/dialog.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/display/placeholder.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/edit/closebrackets.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/edit/closetag.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/edit/continuecomment.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/edit/continuelist.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/edit/matchbrackets.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/edit/matchtags.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/edit/trailingspace.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/fold/brace-fold.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/fold/foldcode.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/fold/foldgutter.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/fold/indent-fold.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/fold/xml-fold.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/hint/anyword-hint.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/hint/html-hint.js [new file with mode: 0755]
third-party/codemirror-3.15/addon/hint/javascript-hint.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/hint/pig-hint.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/hint/python-hint.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/hint/show-hint.css [new file with mode: 0644]
third-party/codemirror-3.15/addon/hint/show-hint.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/hint/xml-hint.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/lint/coffeescript-lint.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/lint/javascript-lint.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/lint/json-lint.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/lint/lint.css [new file with mode: 0644]
third-party/codemirror-3.15/addon/lint/lint.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/merge/dep/diff_match_patch.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/merge/merge.css [new file with mode: 0644]
third-party/codemirror-3.15/addon/merge/merge.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/mode/loadmode.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/mode/multiplex.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/mode/multiplex_test.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/mode/overlay.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/runmode/colorize.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/runmode/runmode-standalone.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/runmode/runmode.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/runmode/runmode.node.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/search/match-highlighter.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/search/search.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/search/searchcursor.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/selection/active-line.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/selection/mark-selection.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/tern/tern.css [new file with mode: 0644]
third-party/codemirror-3.15/addon/tern/tern.js [new file with mode: 0644]
third-party/codemirror-3.15/addon/tern/worker.js [new file with mode: 0644]
third-party/codemirror-3.15/bin/compress [new file with mode: 0755]
third-party/codemirror-3.15/bin/lint [new file with mode: 0755]
third-party/codemirror-3.15/bin/source-highlight [new file with mode: 0755]
third-party/codemirror-3.15/bower.json [new file with mode: 0644]
third-party/codemirror-3.15/demo/activeline.html [new file with mode: 0644]
third-party/codemirror-3.15/demo/anywordhint.html [new file with mode: 0644]
third-party/codemirror-3.15/demo/bidi.html [new file with mode: 0644]
third-party/codemirror-3.15/demo/btree.html [new file with mode: 0644]
third-party/codemirror-3.15/demo/buffers.html [new file with mode: 0644]
third-party/codemirror-3.15/demo/changemode.html [new file with mode: 0644]
third-party/codemirror-3.15/demo/closebrackets.html [new file with mode: 0644]
third-party/codemirror-3.15/demo/closetag.html [new file with mode: 0644]
third-party/codemirror-3.15/demo/complete.html [new file with mode: 0644]
third-party/codemirror-3.15/demo/emacs.html [new file with mode: 0644]
third-party/codemirror-3.15/demo/folding.html [new file with mode: 0644]
third-party/codemirror-3.15/demo/fullscreen.html [new file with mode: 0644]
third-party/codemirror-3.15/demo/html5complete.html [new file with mode: 0644]
third-party/codemirror-3.15/demo/indentwrap.html [new file with mode: 0644]
third-party/codemirror-3.15/demo/lint.html [new file with mode: 0644]
third-party/codemirror-3.15/demo/loadmode.html [new file with mode: 0644]
third-party/codemirror-3.15/demo/marker.html [new file with mode: 0644]
third-party/codemirror-3.15/demo/markselection.html [new file with mode: 0644]
third-party/codemirror-3.15/demo/matchhighlighter.html [new file with mode: 0644]
third-party/codemirror-3.15/demo/matchtags.html [new file with mode: 0644]
third-party/codemirror-3.15/demo/merge.html [new file with mode: 0644]
third-party/codemirror-3.15/demo/multiplex.html [new file with mode: 0644]
third-party/codemirror-3.15/demo/mustache.html [new file with mode: 0644]
third-party/codemirror-3.15/demo/placeholder.html [new file with mode: 0644]
third-party/codemirror-3.15/demo/preview.html [new file with mode: 0644]
third-party/codemirror-3.15/demo/resize.html [new file with mode: 0644]
third-party/codemirror-3.15/demo/runmode.html [new file with mode: 0644]
third-party/codemirror-3.15/demo/search.html [new file with mode: 0644]
third-party/codemirror-3.15/demo/spanaffectswrapping_shim.html [new file with mode: 0644]
third-party/codemirror-3.15/demo/tern.html [new file with mode: 0644]
third-party/codemirror-3.15/demo/theme.html [new file with mode: 0644]
third-party/codemirror-3.15/demo/trailingspace.html [new file with mode: 0644]
third-party/codemirror-3.15/demo/variableheight.html [new file with mode: 0644]
third-party/codemirror-3.15/demo/vim.html [new file with mode: 0644]
third-party/codemirror-3.15/demo/visibletabs.html [new file with mode: 0644]
third-party/codemirror-3.15/demo/widget.html [new file with mode: 0644]
third-party/codemirror-3.15/demo/xmlcomplete.html [new file with mode: 0644]
third-party/codemirror-3.15/doc/baboon.png [new file with mode: 0644]
third-party/codemirror-3.15/doc/baboon_vector.svg [new file with mode: 0644]
third-party/codemirror-3.15/doc/compress.html [new file with mode: 0644]
third-party/codemirror-3.15/doc/docs.css [new file with mode: 0644]
third-party/codemirror-3.15/doc/internals.html [new file with mode: 0644]
third-party/codemirror-3.15/doc/manual.html [new file with mode: 0644]
third-party/codemirror-3.15/doc/modes.html [new file with mode: 0644]
third-party/codemirror-3.15/doc/oldrelease.html [new file with mode: 0644]
third-party/codemirror-3.15/doc/realworld.html [new file with mode: 0644]
third-party/codemirror-3.15/doc/reporting.html [new file with mode: 0644]
third-party/codemirror-3.15/doc/upgrade_v2.2.html [new file with mode: 0644]
third-party/codemirror-3.15/doc/upgrade_v3.html [new file with mode: 0644]
third-party/codemirror-3.15/index.html [new file with mode: 0644]
third-party/codemirror-3.15/keymap/emacs.js [new file with mode: 0644]
third-party/codemirror-3.15/keymap/extra.js [new file with mode: 0644]
third-party/codemirror-3.15/keymap/vim.js [new file with mode: 0644]
third-party/codemirror-3.15/lib/codemirror.css [new file with mode: 0644]
third-party/codemirror-3.15/lib/codemirror.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/apl/apl.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/apl/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/asterisk/asterisk.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/asterisk/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/clike/clike.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/clike/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/clike/scala.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/clojure/clojure.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/clojure/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/cobol/cobol.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/cobol/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/coffeescript/LICENSE [new file with mode: 0644]
third-party/codemirror-3.15/mode/coffeescript/coffeescript.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/coffeescript/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/commonlisp/commonlisp.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/commonlisp/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/css/css.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/css/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/css/scss.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/css/scss_test.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/css/test.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/d/d.js [new file with mode: 0755]
third-party/codemirror-3.15/mode/d/index.html [new file with mode: 0755]
third-party/codemirror-3.15/mode/diff/diff.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/diff/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/ecl/ecl.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/ecl/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/erlang/erlang.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/erlang/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/gas/gas.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/gas/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/gfm/gfm.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/gfm/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/gfm/test.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/go/go.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/go/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/groovy/groovy.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/groovy/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/haml/haml.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/haml/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/haml/test.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/haskell/haskell.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/haskell/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/haxe/haxe.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/haxe/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/htmlembedded/htmlembedded.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/htmlembedded/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/htmlmixed/htmlmixed.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/htmlmixed/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/http/http.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/http/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/jade/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/jade/jade.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/javascript/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/javascript/javascript.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/javascript/test.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/javascript/typescript.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/jinja2/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/jinja2/jinja2.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/less/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/less/less.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/livescript/LICENSE [new file with mode: 0644]
third-party/codemirror-3.15/mode/livescript/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/livescript/livescript.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/livescript/livescript.ls [new file with mode: 0644]
third-party/codemirror-3.15/mode/lua/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/lua/lua.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/markdown/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/markdown/markdown.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/markdown/test.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/meta.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/mirc/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/mirc/mirc.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/nginx/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/nginx/nginx.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/ntriples/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/ntriples/ntriples.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/ocaml/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/ocaml/ocaml.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/pascal/LICENSE [new file with mode: 0644]
third-party/codemirror-3.15/mode/pascal/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/pascal/pascal.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/perl/LICENSE [new file with mode: 0644]
third-party/codemirror-3.15/mode/perl/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/perl/perl.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/php/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/php/php.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/pig/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/pig/pig.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/properties/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/properties/properties.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/python/LICENSE.txt [new file with mode: 0644]
third-party/codemirror-3.15/mode/python/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/python/python.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/q/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/q/q.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/r/LICENSE [new file with mode: 0644]
third-party/codemirror-3.15/mode/r/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/r/r.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/rpm/changes/changes.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/rpm/changes/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/rpm/spec/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/rpm/spec/spec.css [new file with mode: 0644]
third-party/codemirror-3.15/mode/rpm/spec/spec.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/rst/LICENSE.txt [new file with mode: 0644]
third-party/codemirror-3.15/mode/rst/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/rst/rst.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/ruby/LICENSE [new file with mode: 0644]
third-party/codemirror-3.15/mode/ruby/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/ruby/ruby.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/rust/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/rust/rust.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/sass/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/sass/sass.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/scheme/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/scheme/scheme.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/shell/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/shell/shell.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/sieve/LICENSE [new file with mode: 0644]
third-party/codemirror-3.15/mode/sieve/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/sieve/sieve.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/smalltalk/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/smalltalk/smalltalk.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/smarty/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/smarty/smarty.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/smartymixed/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/smartymixed/smartymixed.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/sparql/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/sparql/sparql.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/sql/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/sql/sql.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/stex/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/stex/stex.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/stex/test.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/tcl/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/tcl/tcl.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/tiddlywiki/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/tiddlywiki/tiddlywiki.css [new file with mode: 0644]
third-party/codemirror-3.15/mode/tiddlywiki/tiddlywiki.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/tiki/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/tiki/tiki.css [new file with mode: 0644]
third-party/codemirror-3.15/mode/tiki/tiki.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/turtle/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/turtle/turtle.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/vb/LICENSE.txt [new file with mode: 0644]
third-party/codemirror-3.15/mode/vb/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/vb/vb.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/vbscript/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/vbscript/vbscript.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/velocity/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/velocity/velocity.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/verilog/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/verilog/verilog.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/xml/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/xml/xml.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/xquery/LICENSE [new file with mode: 0644]
third-party/codemirror-3.15/mode/xquery/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/xquery/test.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/xquery/xquery.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/yaml/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/yaml/yaml.js [new file with mode: 0644]
third-party/codemirror-3.15/mode/z80/index.html [new file with mode: 0644]
third-party/codemirror-3.15/mode/z80/z80.js [new file with mode: 0644]
third-party/codemirror-3.15/package.json [new file with mode: 0644]
third-party/codemirror-3.15/test/comment_test.js [new file with mode: 0644]
third-party/codemirror-3.15/test/doc_test.js [new file with mode: 0644]
third-party/codemirror-3.15/test/driver.js [new file with mode: 0644]
third-party/codemirror-3.15/test/emacs_test.js [new file with mode: 0644]
third-party/codemirror-3.15/test/index.html [new file with mode: 0644]
third-party/codemirror-3.15/test/lint/acorn.js [new file with mode: 0644]
third-party/codemirror-3.15/test/lint/lint.js [new file with mode: 0644]
third-party/codemirror-3.15/test/lint/parse-js.js [new file with mode: 0644]
third-party/codemirror-3.15/test/lint/walk.js [new file with mode: 0644]
third-party/codemirror-3.15/test/mode_test.css [new file with mode: 0644]
third-party/codemirror-3.15/test/mode_test.js [new file with mode: 0644]
third-party/codemirror-3.15/test/phantom_driver.js [new file with mode: 0644]
third-party/codemirror-3.15/test/run.js [new file with mode: 0755]
third-party/codemirror-3.15/test/test.js [new file with mode: 0644]
third-party/codemirror-3.15/test/vim_test.js [new file with mode: 0644]
third-party/codemirror-3.15/theme/3024-day.css [new file with mode: 0644]
third-party/codemirror-3.15/theme/3024-night.css [new file with mode: 0644]
third-party/codemirror-3.15/theme/ambiance-mobile.css [new file with mode: 0644]
third-party/codemirror-3.15/theme/ambiance.css [new file with mode: 0644]
third-party/codemirror-3.15/theme/base16-dark.css [new file with mode: 0644]
third-party/codemirror-3.15/theme/base16-light.css [new file with mode: 0644]
third-party/codemirror-3.15/theme/blackboard.css [new file with mode: 0644]
third-party/codemirror-3.15/theme/cobalt.css [new file with mode: 0644]
third-party/codemirror-3.15/theme/eclipse.css [new file with mode: 0644]
third-party/codemirror-3.15/theme/elegant.css [new file with mode: 0644]
third-party/codemirror-3.15/theme/erlang-dark.css [new file with mode: 0644]
third-party/codemirror-3.15/theme/lesser-dark.css [new file with mode: 0644]
third-party/codemirror-3.15/theme/midnight.css [new file with mode: 0644]
third-party/codemirror-3.15/theme/monokai.css [new file with mode: 0644]
third-party/codemirror-3.15/theme/neat.css [new file with mode: 0644]
third-party/codemirror-3.15/theme/night.css [new file with mode: 0644]
third-party/codemirror-3.15/theme/rubyblue.css [new file with mode: 0644]
third-party/codemirror-3.15/theme/solarized.css [new file with mode: 0644]
third-party/codemirror-3.15/theme/tomorrow-night-eighties.css [new file with mode: 0644]
third-party/codemirror-3.15/theme/twilight.css [new file with mode: 0644]
third-party/codemirror-3.15/theme/vibrant-ink.css [new file with mode: 0644]
third-party/codemirror-3.15/theme/xq-dark.css [new file with mode: 0644]
third-party/codemirror-3.15/theme/xq-light.css [new file with mode: 0644]
third-party/jquery-notify/alert.png [new file with mode: 0644]
third-party/jquery-notify/jquery.notify.js [new file with mode: 0644]
third-party/jquery-notify/jquery.notify.min.js [new file with mode: 0644]
third-party/jquery-notify/style.css [new file with mode: 0644]
third-party/jquery-notify/ui.notify.css [new file with mode: 0644]
third-party/jquery/js/jquery.validate.js [new file with mode: 0644]
third-party/mustache/mustache.js [new file with mode: 0644]
third-party/smartwizard-1636c86/images/loader.gif [new file with mode: 0644]
third-party/smartwizard-1636c86/index.htm [new file with mode: 0644]
third-party/smartwizard-1636c86/js/jquery-1.4.2.min.js [new file with mode: 0644]
third-party/smartwizard-1636c86/js/jquery.smartWizard-2.0.js [new file with mode: 0644]
third-party/smartwizard-1636c86/js/jquery.smartWizard-2.0.min.js [new file with mode: 0644]
third-party/smartwizard-1636c86/readme.md [new file with mode: 0644]
third-party/smartwizard-1636c86/services/service.php [new file with mode: 0644]
third-party/smartwizard-1636c86/smartwizard2-ajax.htm [new file with mode: 0644]
third-party/smartwizard-1636c86/smartwizard2-multiple.htm [new file with mode: 0644]
third-party/smartwizard-1636c86/smartwizard2-validation.php [new file with mode: 0644]
third-party/smartwizard-1636c86/smartwizard2-vertical.htm [new file with mode: 0644]
third-party/smartwizard-1636c86/styles/smart_wizard.css [new file with mode: 0644]
third-party/smartwizard-1636c86/styles/smart_wizard_vertical.css [new file with mode: 0644]
trash/dashboard.py
trash/pluginview.py
trash/sampleviews.py
trash/sliceview.py [deleted file]
trash/trashutils.py [new file with mode: 0644]
trash/urls.py [new file with mode: 0644]
unfold/composite.py
unfold/js/plugin_helper.js [moved from unfold/js/plugin.js with 71% similarity]
unfold/js/unfold-helper.js
unfold/page.py
unfold/plugin.py
unfold/static.py [new file with mode: 0644]
unfold/templates/plugin-init.js
unfold/templates/plugin.html
views/css/layout-unfold2.css
views/css/topmenu.css
views/img/onelab-logo.png [new file with mode: 0644]
views/templates/base.html [new file with mode: 0644]
views/templates/layout-unfold1.html
views/templates/layout-unfold2.html
views/templates/messages-header.html [new file with mode: 0644]
views/templates/messages.html [new file with mode: 0644]
views/templates/view-login.html [deleted file]
views/templates/widget-topmenu.html

index 8e93643..d2fb6c4 100644 (file)
@@ -1,9 +1,17 @@
+# any local dbfile
+*.sqlite3
+# here is a mode to 'record' the backend answers and replay them offline
+offline-*
+# the usual useless crap
 TAGS
 *.pyc
-*.sqlite3
 *~
+# these essentially are copies/links from other places
 all-static/
 all-templates/
-offline-*
+django-static/
+# various working files
 play/
 *.leftovers
+*.hide
+entrypoints.ongoing/
diff --git a/LICENSE b/LICENSE
new file mode 100644 (file)
index 0000000..94a9ed0
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,674 @@
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.  We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors.  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+  To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights.  Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received.  You must make sure that they, too, receive
+or can get the source code.  And you must show them these terms so they
+know their rights.
+
+  Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+  For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software.  For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+  Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so.  This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software.  The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable.  Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products.  If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+  Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary.  To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                       TERMS AND CONDITIONS
+
+  0. Definitions.
+
+  "This License" refers to version 3 of the GNU General Public License.
+
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
+
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+  1. Source Code.
+
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
+
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+  The Corresponding Source for a work in source code form is that
+same work.
+
+  2. Basic Permissions.
+
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Use with the GNU Affero General Public License.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+  If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+  15. Disclaimer of Warranty.
+
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+    <program>  Copyright (C) <year>  <name of author>
+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+  The GNU General Public License does not permit incorporating your program
+into proprietary programs.  If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.  But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
index 3553855..235336b 100644 (file)
--- a/Makefile
+++ b/Makefile
@@ -81,6 +81,20 @@ THIRD-PARTY-RESOURCES += $(shell ls third-party/syntaxhighlighter/scripts/shBrus
 THIRD-PARTY-RESOURCES += $(shell ls third-party/syntaxhighlighter/styles/shCore.css)
 THIRD-PARTY-RESOURCES += $(shell ls third-party/syntaxhighlighter/styles/shCoreDefault.css)
 THIRD-PARTY-RESOURCES += $(shell ls third-party/syntaxhighlighter/styles/shThemeDefault.css)
+# wizard plugin
+THIRD-PARTY-RESOURCES += $(shell ls third-party/smartwizard-1636c86/js/jquery.smartWizard-2.0.js)
+#THIRD-PARTY-RESOURCES += $(shell ls third-party/smartwizard-1636c86/js/jquery.smartWizard-2.0.min.js)
+THIRD-PARTY-RESOURCES += $(shell ls third-party/smartwizard-1636c86/styles/smart_wizard.css)
+# jquery.notify
+THIRD-PARTY-RESOURCES += $(shell ls third-party/jquery-notify/jquery.notify.js)
+THIRD-PARTY-RESOURCES += $(shell ls third-party/jquery-notify/jquery.notify.min.js)
+THIRD-PARTY-RESOURCES += $(shell ls third-party/jquery-notify/ui.notify.css)
+# CodeMirror
+THIRD-PARTY-RESOURCES += $(shell ls third-party/codemirror-3.15/lib/codemirror.js) 
+THIRD-PARTY-RESOURCES += $(shell ls third-party/codemirror-3.15/lib/codemirror.css) 
+THIRD-PARTY-RESOURCES += $(shell ls third-party/codemirror-3.15/mode/sql/sql.js)
+# Mustache.js
+THIRD-PARTY-RESOURCES += $(shell ls third-party/mustache/mustache.js)
 
 
 thirdparty-js:
diff --git a/README b/README
index 3859fa3..21a79b8 100644 (file)
--- a/README
+++ b/README
@@ -1,4 +1,6 @@
-his file documents the contents of this module
+This file documents the contents of this module
+
+Last update 4 sept. 2013
 
 See the devel/ subdir for more devel-oriented doc.
 
@@ -8,13 +10,9 @@ See the devel/ subdir for more devel-oriented doc.
 ** should be straightforward
 ** see devel/django-install.txt in case of trouble
 
-* git clone git://git.onelab.eu/myslice-django.git
+* git clone git://git.onelab.eu/myslice.git
 -- or --
-* git clone ssh://yourlogin@git.onelab.eu/git/myslice-django.git
-
-* edit myslice/settings.py and
-** change DEVELOPER_ROOT if you didnt clone into ~/git/myslice-django
-** change the location of your backend API (not yet supported)
+* git clone ssh://yourlogin@git.onelab.eu/git/myslice.git
 
 * edit myslice/config.py and enter the details of your manifold backend
 
@@ -22,7 +20,9 @@ See the devel/ subdir for more devel-oriented doc.
 $ manage.py syncdb
 
 * gather static files
-$ make static
+$ ./manage.py collectstatic (formerly, we used make static, which is deprecated)
+-- or --
+$ ./manage.py collectstatic --noinput
 
 * run a local server:
 $ manage.py runserver 0.0.0.0:8000
@@ -33,17 +33,22 @@ when you just need to hit ^C yourself when your static files need to be refreshe
 * use it from your browser 
 (See more notes on using the development server below)
 
+* install dependencies 
+$ pip install -r path/to/requirements/file.txt
+Note. not quite sure what this is about, I could not spot this file..
+
 ==================== Status
 
 *** Authentication ***
 
-Although there still are a few hard-coded accounts in the system, you
-will only be able to see some static views and won't be able to send
-real queries if you use these, so you'd better use a real account (one
-that your manifold backend knows about).
+Should be mostly fine
+Not quite sure if/how the user gets proper notifications when
+. his session has expired (i.e. his frontend is not logged into the backend any longer)
+. his credentials have expired (i.e. the uploaded credentials, e.g. SFA delegated cred)
+  expired and she needs to run e.g. sfi myslice again
+
+Hard-coded accounts (from a very early stage) are gone
 
-For logging out: click on 'logged as *jean*', this shows a
-confirmation page for logging out. this is intended to be temporary.
 
 *** Packaging ***
 
@@ -54,35 +59,9 @@ It seems like our app won't work on f14 as is because Django is only 1.3.1 on f1
 Plan is to target f18 but I lack a test machine.
 Also of course I'll try to tackle debian/ubunti at some point.
 
-*** Features ***
-
-We have a basic model for asynchroneous queries (referring to manifold
-queries) and for plugins (in the most general sense a plugin is just a
-piece of the output that may be connected to a query)
-
-Right now the UI has a handful of demo views only; as of this writing
-only the list of slices actually comes from the manifold backend in an
-asynchroneous way.
-
-Also all the views are gathered in the trash/ locations for now, being
-that they're only for assessment purposes.
+There also is a working packaging for debian(s) and ubuntu(s) that we use 
+on an almost daily basis to upgrade manifold.pl.sophia.inria.fr
 
-* dahsboard : has one async. query and 2 plugins that share that
-  query; the intent was to demo a different layout in both cases,
-  although the datatables one won't work yet at this point.
-
-* the 'Plugin' view demonstrates most of the available plugins.
-
-* slice view : only demonstrates how to use URLs to pass arguments along
-
-* scroll view : mostly it only illustrates that some pages can be made
-  public (no need to login)
-
-* tab view : a hand-made tab widget
-
-Not much effort has yet been put into coming up with a nice layout,
-feel free to tweak that but it's probably still way too early for
-this.
 
 ==================== 
 
@@ -92,35 +71,46 @@ Third party tools shipped:
 * datatables
 * spin
 * bootstrap
-* and others are added as we build the system when they become needed
 
-I've tried to keep track of the version I picked and to have an easy upgrade path.
+Others are added as we build the system when they become needed
+Look in third-party/ for a more detailed list
+
+As a rule of thumb, please try to keep in mind that these will need to
+be upgraded over time I've tried to keep track of the version I picked
+and to have an easy upgrade path (depending on the way the original
+package is published)
 
 ==================== Contents: 1st level subdirs
 
 ========== code from git
-* myslice: 
+
+* myslice/
   this is the django 'project', where to look for
   . settings.py
   . urls.py
 
-* manifold:
+* manifold/
   the code for dealing with queries, sending them to the backend, and offering the /manifold/proxy/ URL
 
-* unfold:
+* unfold/
   the code for building / rendering plugins 
 
-* plugins:
+* plugins/
   the actual code for plugins
 
-* auth: 
+* auth/ 
   a django 'app' that deals with authentication; see especially
   auth.backend.MyCustomBackend 
   for how to use a separate authentication system, 
   as well as settings.py for how to enable it
 
+* portal/
+  this is where the first implementation of myslice, with complete
+  user-management including registration, is taking place
+
 * trash/
-  rough/preliminary views in here - as the name suggests this is temporary
+  rough/preliminary scaffolding views are in here
+  as the name suggests this is temporary
 
 * views/
   will receive actual views over time 
@@ -145,6 +135,8 @@ I've tried to keep track of the version I picked and to have an easy upgrade pat
   $ make static 
   $ make clean-static 
 
+* django-static
+
 * myslice.sqlite3
   this is where django stores its own stuff, as per settings.py
 
@@ -162,8 +154,8 @@ I've tried to keep track of the version I picked and to have an easy upgrade pat
       plugins/templates/plugins.html,
       plugins/static/js/simplelist.js 
       plugins/static/css/simplelist.css
-   which I have tried doing for a while but I found mmyself just hopping around in the file tree all
-   day long, wasting cycles all along
+   which I have tried doing for a while but I found myself just hopping around in the file tree all
+   day long, wasting cycles big time
 
 .. as that does not make sense IMHO, I've rewritten the tool for gathering these pieces (this is in
    the Makefile). Bottom line is we can essentially store this wherever we want.
@@ -217,3 +209,42 @@ that would reset all-static/ and all-templates/ for you from the other contents
 
 
 
+======== update django database to reflect changes in existing models without any migration system (e.g., south) =========
+
+# older version
+$python manage.py reset <your_app>
+
+#Django 1.5.1 or later
+$python manage.py flush
+
+This will update the database tables for your app, but will completely destroy any data that existed in those tables. 
+If the changes you made to your app model do not break your old schema (for instance, you added a new, optional field) 
+you can simply dump the data before and reload it afterwards, like so:
+
+$python manage.py syncdb
+$python manage.py dumpdata <your_app> > temp_data.json
+$python manage.py flush
+$python manage.py loaddata temp_data.json
+
+If your changes break your old schema this won't work - in which case tools like south or django evolution are great.
+
+======== update django database to reflect changes in existing models with migration system (e.g., south) =========
+
+As south is already installed , you just have to do:
+
+$./manage.py migrate
+
+if it fails:
+
+1. go to myslice directory
+2. do sqlite3 myslice.sqlite3 [if sqlite3: command not found, do $apt-get install sqlite3]
+3. check the list of tables with sqlite> .tables
+4. if you find those tables that was mentioned in the failure message while running $./manage.py migrate
+       do sqlite> DROP TABLE mentioned_table 
+       [mentioned_table = the tables that was explicity mentioned in the failure message of $./manage.py migrate]
+5. sqlite> .quit
+6. $./manage.py migrate  
+
+
+
+
diff --git a/README.migrations b/README.migrations
new file mode 100644 (file)
index 0000000..0d52816
--- /dev/null
@@ -0,0 +1,4 @@
+see reset.sh
+
+./manage.py schemamigration portal --initial
+./manage.py schemamigration portal extend_slice --auto
diff --git a/auth/backend.py b/auth/backend.py
deleted file mode 100644 (file)
index 4c93676..0000000
+++ /dev/null
@@ -1,40 +0,0 @@
-# import the User object
-from django.contrib.auth.models import User
-
-import time
-
-# Name my backend 'MyCustomBackend'
-class MyCustomBackend:
-
-    hard_wired_users = { 'jean': '1234',
-                         'root': '2345',
-                         'jacques': '3456',
-                         }
-
-
-    # Create an authentication method
-    # This is called by the standard Django login procedure
-    def authenticate(self, token=None):
-        username=token['username']
-        password=token['password']
-        users=MyCustomBackend.hard_wired_users
-        if username not in users: return None
-        if password != users[username]: return None
-        try:
-            # Check if the user exists in Django's local database
-            user = User.objects.get(email=username)
-        except User.DoesNotExist:
-            print 'creating django user',username
-            # Create a user in Django's local database
-            # warning: the trick here is pass current time as an id, and name as email
-            # create_user(username, email=None, password=None)
-            user = User.objects.create_user(time.time(), username, 'password-doesnt-matter')
-
-        return user
-
-    # Required for your backend to work properly - unchanged in most scenarios
-    def get_user(self, user_id):
-        try:
-            return User.objects.get(pk=user_id)
-        except User.DoesNotExist:
-            return None
index 06528ee..0d0ba19 100644 (file)
@@ -1,3 +1,7 @@
+p.login-status {
+    font-weight: bold;
+}
+
 p.login { 
     font-style: italic;
 }
@@ -6,7 +10,7 @@ input.login {
 }    
 input[type="password"] {
     border: solid 1px #444;
-    background-image: url( '/all-static/img/form_input_password.png' );
+    background-image: url( '../img/form_input_password.png' );
     background-repeat: repeat-x;
     background-position: top;
 }
index 73ba446..529ef0f 100644 (file)
@@ -3,6 +3,7 @@ import time
 from django.contrib.auth.models import User
 
 from manifold.manifoldapi import ManifoldAPI, ManifoldResult
+from manifold.core.query        import Query
 
 # Name my backend 'ManifoldBackend'
 class ManifoldBackend:
@@ -20,34 +21,36 @@ class ManifoldBackend:
 
             auth = {'AuthMethod': 'password', 'Username': username, 'AuthString': password}
             api = ManifoldAPI(auth)
-            # Authenticate user and get session key
-            # the new API would expect Get('local:session') instead
-            session_result = api.GetSession()
-            session = session_result.ok_value()
-            if not session:
-                print "GetSession failed",session_result.error()
+            sessions_result = api.forward(Query.create('local:session').to_dict())
+            print "result"
+            sessions = sessions_result.ok_value()
+            print "ok"
+            if not sessions:
+                print "GetSession failed", sessions_result.error()
                 return
-            
-            print 'DEALING with session',session
-            #self.session = session
-            # Change GetSession() at some point to return expires as well
-            expires = time.time() + (24 * 60 * 60)
+            print "first", sessions
+            session = sessions[0]
+            print "SESSION=", session
 
             # Change to session authentication
-            api.auth = {'AuthMethod': 'session', 'session': session}
+            api.auth = {'AuthMethod': 'session', 'session': session['session']}
             self.api = api
 
             # Get account details
             # the new API would expect Get('local:user') instead
-            persons_result = api.GetPersons(auth)
+            persons_result = api.forward(Query.get('local:user').to_dict())
             persons = persons_result.ok_value()
             if not persons:
                 print "GetPersons failed",persons_result.error()
                 return
             person = persons[0]
+            print "PERSON=", person
 
-            request.session['manifold'] = {'auth': api.auth, 'person': person, 'expires': expires}
-        except:
+            request.session['manifold'] = {'auth': api.auth, 'person': person, 'expires': session['expires']}
+        except Exception, e:
+            print "E: manifoldbackend", e
+            import traceback
+            traceback.print_exc()
             return None
 
         try:
@@ -56,8 +59,8 @@ class ManifoldBackend:
         except User.DoesNotExist:
             # Create a user in Django's local database
             user = User.objects.create_user(username, username, 'passworddoesntmatter')
-            user.first_name = person['first_name']
-            user.last_name = person['last_name']
+            user.first_name = "DUMMY_FIRST_NAME" #person['first_name']
+            user.last_name = "DUMMY LAST NAME" # person['last_name']
             user.email = person['email']
         return user
 
index ac90bcc..b79e33f 100644 (file)
@@ -1,14 +1,16 @@
 {% insert_str prelude 'css/login.css' %}
 <p class='login-status'> {{ state }} </p>
-<a href="/" alt="Home"><img class="logo" src="{{ STATIC_URL }}img/myslice-logo.png" alt="MySlice" /></a>
+<!--<a href="/" alt="Home"><img class="logo" src="{{ STATIC_URL }}img/myslice-logo.png" alt="MySlice" /></a>-->
+<div class='well well-lg'>
 <form action="/login/" method="post">
   {% csrf_token %}
   {% if next %}
   <input type="hidden" name="next" value="{{ next }}" />
   {% endif %}
-  <p class='login'>username</p>
+  <p class='login'>Username</p>
   <input class='login' type="text" name="username" value="{{ username}}" /><br />
-  <p class='login'>password</p>
+  <p class='login'>Password</p>
   <input class='login' type="password" name="password" value="" /><br />
   <input type="submit" value="Log In" />
 </form>
+</div>
index 2a9ff83..104d11c 100644 (file)
@@ -1,52 +1,12 @@
-# Create your views here.
-from django.core.context_processors import csrf
-from django.template import RequestContext
-from django.shortcuts import render_to_response
-from django.contrib.auth import authenticate, login, logout
+from django.contrib.auth import logout
 from django.http import HttpResponseRedirect
 
-from auth.backend import MyCustomBackend
-
-from myslice.viewutils import the_user
-from myslice.config import Config
-
-def login_user(request):
-    state = "Please log in below..."
-    username = password = ''
-    env={'hard_wired_users':MyCustomBackend.hard_wired_users,
-         'manifold_url':Config.manifold_url,
-         }
-
-    if request.POST:
-        username = request.POST.get('username')
-        password = request.POST.get('password')
-        
-        # pass request within the token, so manifold session key could be attached to the request session.
-        token = {'username': username, 'password': password, 'request': request}    
-
-        user = authenticate(token=token)
-        if user is not None:
-            if user.is_active:
-                login(request, user)
-                #state = "You're successfully logged in!"
-                return HttpResponseRedirect ('/login-ok')
-            else:
-                env['state'] = "Your account is not active, please contact the site admin."
-                return render_to_response('view-login.html',env, context_instance=RequestContext(request))
-        else:
-            env['state'] = "Your username and/or password were incorrect."
-            return render_to_response('view-login.html',env, context_instance=RequestContext(request))
-    else:
-        state='Welcome to MySlice'
-        env['state']=state
-        env['username']=the_user(request)
-        return render_to_response('view-login.html',env, context_instance=RequestContext(request))
-
 # hard question : where should we redirect requests to logout if user is not logged in ?
 def logout_user (request):
     # check that we're indeed logged in
     if not request.user.is_authenticated():
         return HttpResponseRedirect ('/')
+    print "LOGGING OUT"
     logout(request)
     return HttpResponseRedirect ('/')
         
index f30669b..7e8cc46 100644 (file)
@@ -7,11 +7,11 @@ Build-Depends: devscripts, debhelper (>=7.0.50~), debconf, dpatch, python-setupt
 
 Package: myslice
 Architecture: any
-Depends: unfold
+Depends: unfold, python-django-south
 Description: Myslice plugins, based on django and unfold frontend
 
 # Thierry: the recipe I'm using somehow only works with several packages
 Package: unfold
 Architecture: any
-Depends: python, python-django
+Depends: python, python-django, python-pyparsing
 Description: Generic django-based frontend for manifold backends
diff --git a/debug_platform/urls.py b/debug_platform/urls.py
new file mode 100644 (file)
index 0000000..15063d1
--- /dev/null
@@ -0,0 +1,31 @@
+# -*- coding: utf-8 -*-
+#
+# debug/urls.py: URL mappings for the debug application
+# This file is part of the Manifold project.
+#
+# Authors:
+#   Jordan Augé <jordan.auge@lip6.fr>
+# Copyright 2013, UPMC Sorbonne Universités / LIP6
+#
+# This program is free software; you can redistribute it and/or modify it under
+# the terms of the GNU General Public License as published by the Free Software
+# Foundation; either version 3, or (at your option) any later version.
+# 
+# This program is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
+# details.
+# 
+# You should have received a copy of the GNU General Public License along with
+# this program; see the file COPYING.  If not, write to the Free Software
+# Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+from django.conf.urls           import patterns, include, url
+from debug_platform.views       import PlatformView
+from portal.dashboardview       import DashboardView
+
+urlpatterns = patterns('',
+    #(r'platform/(?P<platform_name>[\w\.]+)/?$', 'debug.platform'),
+    url(r'^platform/?$', PlatformView.as_view(), name='debugplatform'),
+    #url(r'^platform/(?P<platform_name>[\w\.]+)/?$', PlatformView.as_view(), name='debug_platform'),
+)
diff --git a/debug_platform/views.py b/debug_platform/views.py
new file mode 100644 (file)
index 0000000..f56661b
--- /dev/null
@@ -0,0 +1,62 @@
+# -*- coding: utf-8 -*-
+#
+# portal/views.py: views for the portal application
+# This file is part of the Manifold project.
+#
+# Authors:
+#   Jordan Augé <jordan.auge@lip6.fr>
+#   Mohammed Yasin Rahman <mohammed-yasin.rahman@lip6.fr>
+# Copyright 2013, UPMC Sorbonne Universités / LIP6
+#
+# This program is free software; you can redistribute it and/or modify it under
+# the terms of the GNU General Public License as published by the Free Software
+# Foundation; either version 3, or (at your option) any later version.
+# 
+# This program is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
+# details.
+# 
+# You should have received a copy of the GNU General Public License along with
+# this program; see the file COPYING.  If not, write to the Free Software
+# Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+from django.conf                 import settings
+from django.contrib.sites.models import Site, RequestSite
+from django.contrib              import messages
+from django.views.generic        import View
+from django.views.generic.base   import TemplateView
+from django.shortcuts            import render
+from manifold.core.query         import Query
+from unfold.page                 import Page
+from myslice.viewutils           import topmenu_items, the_user
+from django.http                 import HttpResponseRedirect
+from plugins.debug_platform      import DebugPlatform
+
+class PlatformView(TemplateView):
+    template_name = "view-unfold1.html"
+
+    def get_context_data(self, **kwargs):
+
+        page = Page(self.request)
+
+        debug_platform = DebugPlatform(page = page)
+
+        context = super(PlatformView, self).get_context_data(**kwargs)
+
+        context['ALL_STATIC'] = "all_static"
+        context['unfold1_main'] = debug_platform.render(self.request)
+
+        # XXX This is repeated in all pages
+        # more general variables expected in the template
+        context['title'] = 'Test view that combines various plugins'
+        # the menu items on the top
+        context['topmenu_items'] = topmenu_items('Dashboard', self.request) 
+        # so we can sho who is logged
+        context['username'] = the_user(self.request) 
+
+        prelude_env = page.prelude_env()
+        context.update(prelude_env)
+
+        return context
+
index 1eacb71..4ff84bf 100755 (executable)
@@ -7,6 +7,7 @@ hostname | grep -q '^z' && port=8080 || port=80
 [[ -n "$@" ]] && port=$1
 
 while true; do 
-    make all-static all-templates
+    ./manage.py collectstatic --noinput
     ./manage.py runserver 0.0.0.0:$port
+       sleep 1
 done
diff --git a/manifold/core/__init__.py b/manifold/core/__init__.py
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/manifold/core/filter.py b/manifold/core/filter.py
new file mode 100644 (file)
index 0000000..3a21348
--- /dev/null
@@ -0,0 +1,407 @@
+from types import StringTypes
+try:
+    set
+except NameError:
+    from sets import Set
+    set = Set
+
+import time
+import datetime # Jordan
+#from manifold.util.parameter import Parameter, Mixed, python_type
+from manifold.util.predicate import Predicate, eq
+from itertools                  import ifilter
+
+class Filter(set):
+    """
+    A filter is a set of predicates
+    """
+
+    #def __init__(self, s=()):
+    #    super(Filter, self).__init__(s)
+
+    @staticmethod
+    def from_list(l):
+        f = Filter()
+        try:
+            for element in l:
+                f.add(Predicate(*element))
+        except Exception, e:
+            print "Error in setting Filter from list", e
+            return None
+        return f
+        
+    @staticmethod
+    def from_dict(d):
+        f = Filter()
+        for key, value in d.items():
+            if key[0] in Predicate.operators.keys():
+                f.add(Predicate(key[1:], key[0], value))
+            else:
+                f.add(Predicate(key, '=', value))
+        return f
+
+    def to_list(self):
+        ret = []
+        for predicate in self:
+            ret.append(predicate.to_list())
+        return ret
+        
+
+    @staticmethod
+    def from_clause(clause):
+        """
+        NOTE: We can only handle simple clauses formed of AND fields.
+        """
+        raise Exception, "Not implemented"
+
+    def filter_by(self, predicate):
+        self.add(predicate)
+        return self
+
+    def __str__(self):
+        return ' AND '.join([str(pred) for pred in self])
+
+    def __repr__(self):
+        return '<Filter: %s>' % ' AND '.join([str(pred) for pred in self])
+
+    def __key(self):
+        return tuple([hash(pred) for pred in self])
+
+    def __hash__(self):
+        return hash(self.__key())
+
+    def __additem__(self, value):
+        if value.__class__ != Predicate:
+            raise TypeError("Element of class Predicate expected, received %s" % value.__class__.__name__)
+        set.__additem__(self, value)
+
+    def keys(self):
+        return set([x.key for x in self])
+
+    # XXX THESE FUNCTIONS SHOULD ACCEPT MULTIPLE FIELD NAMES
+
+    def has(self, key):
+        for x in self:
+            if x.key == key:
+                return True
+        return False
+
+    def has_op(self, key, op):
+        for x in self:
+            if x.key == key and x.op == op:
+                return True
+        return False
+
+    def has_eq(self, key):
+        return self.has_op(key, eq)
+
+    def get(self, key):
+        ret = []
+        for x in self:
+            if x.key == key:
+                ret.append(x)
+        return ret
+
+    def delete(self, key):
+        to_del = []
+        for x in self:
+            if x.key == key:
+                to_del.append(x)
+        for x in to_del:
+            self.remove(x)
+            
+        #self = filter(lambda x: x.key != key, self)
+
+    def get_op(self, key, op):
+        if isinstance(op, (list, tuple, set)):
+            for x in self:
+                if x.key == key and x.op in op:
+                    return x.value
+        else:
+            for x in self:
+                if x.key == key and x.op == op:
+                    return x.value
+        return None
+
+    def get_eq(self, key):
+        return self.get_op(key, eq)
+
+    def set_op(self, key, op, value):
+        for x in self:
+            if x.key == key and x.op == op:
+                x.value = value
+                return
+        raise KeyError, key
+
+    def set_eq(self, key, value):
+        return self.set_op(key, eq, value)
+
+    def get_predicates(self, key):
+        # XXX Would deserve returning a filter (cf usage in SFA gateway)
+        ret = []
+        for x in self:
+            if x.key == key:
+                ret.append(x)
+        return ret
+
+#    def filter(self, dic):
+#        # We go through every filter sequentially
+#        for predicate in self:
+#            print "predicate", predicate
+#            dic = predicate.filter(dic)
+#        return dic
+
+    def match(self, dic, ignore_missing=True):
+        for predicate in self:
+            if not predicate.match(dic, ignore_missing):
+                return False
+        return True
+
+    def filter(self, l):
+        output = []
+        for x in l:
+            if self.match(x):
+                output.append(x)
+        return output
+
+    def get_field_names(self):
+        field_names = set()
+        for predicate in self:
+            field_names |= predicate.get_field_names()
+        return field_names
+
+#class OldFilter(Parameter, dict):
+#    """
+#    A type of parameter that represents a filter on one or more
+#    columns of a database table.
+#    Special features provide support for negation, upper and lower bounds, 
+#    as well as sorting and clipping.
+#
+#
+#    fields should be a dictionary of field names and types.
+#    As of PLCAPI-4.3-26, we provide support for filtering on
+#    sequence types as well, with the special '&' and '|' modifiers.
+#    example : fields = {'node_id': Parameter(int, "Node identifier"),
+#                        'hostname': Parameter(int, "Fully qualified hostname", max = 255),
+#                        ...}
+#
+#
+#    filter should be a dictionary of field names and values
+#    representing  the criteria for filtering. 
+#    example : filter = { 'hostname' : '*.edu' , site_id : [34,54] }
+#    Whether the filter represents an intersection (AND) or a union (OR) 
+#    of these criteria is determined by the join_with argument 
+#    provided to the sql method below
+#
+#    Special features:
+#
+#    * a field starting with '&' or '|' should refer to a sequence type
+#      the semantic is then that the object value (expected to be a list)
+#      should contain all (&) or any (|) value specified in the corresponding
+#      filter value. See other examples below.
+#    example : filter = { '|role_ids' : [ 20, 40 ] }
+#    example : filter = { '|roles' : ['tech', 'pi'] }
+#    example : filter = { '&roles' : ['admin', 'tech'] }
+#    example : filter = { '&roles' : 'tech' }
+#
+#    * a field starting with the ~ character means negation.
+#    example :  filter = { '~peer_id' : None }
+#
+#    * a field starting with < [  ] or > means lower than or greater than
+#      < > uses strict comparison
+#      [ ] is for using <= or >= instead
+#    example :  filter = { ']event_id' : 2305 }
+#    example :  filter = { '>time' : 1178531418 }
+#      in this example the integer value denotes a unix timestamp
+#
+#    * if a value is a sequence type, then it should represent 
+#      a list of possible values for that field
+#    example : filter = { 'node_id' : [12,34,56] }
+#
+#    * a (string) value containing either a * or a % character is
+#      treated as a (sql) pattern; * are replaced with % that is the
+#      SQL wildcard character.
+#    example :  filter = { 'hostname' : '*.jp' } 
+#
+#    * the filter's keys starting with '-' are special and relate to sorting and clipping
+#    * '-SORT' : a field name, or an ordered list of field names that are used for sorting
+#      these fields may start with + (default) or - for denoting increasing or decreasing order
+#    example : filter = { '-SORT' : [ '+node_id', '-hostname' ] }
+#    * '-OFFSET' : the number of first rows to be ommitted
+#    * '-LIMIT' : the amount of rows to be returned 
+#    example : filter = { '-OFFSET' : 100, '-LIMIT':25}
+#
+#    Here are a few realistic examples
+#
+#    GetNodes ( { 'node_type' : 'regular' , 'hostname' : '*.edu' , '-SORT' : 'hostname' , '-OFFSET' : 30 , '-LIMIT' : 25 } )
+#      would return regular (usual) nodes matching '*.edu' in alphabetical order from 31th to 55th
+#
+#    GetPersons ( { '|role_ids' : [ 20 , 40] } )
+#      would return all persons that have either pi (20) or tech (40) roles
+#
+#    GetPersons ( { '&role_ids' : 10 } )
+#    GetPersons ( { '&role_ids' : 10 } )
+#    GetPersons ( { '|role_ids' : [ 10 ] } )
+#    GetPersons ( { '|role_ids' : [ 10 ] } )
+#      all 4 forms are equivalent and would return all admin users in the system
+#    """
+#
+#    def __init__(self, fields = {}, filter = {}, doc = "Attribute filter"):
+#        # Store the filter in our dict instance
+#        dict.__init__(self, filter)
+#
+#        # Declare ourselves as a type of parameter that can take
+#        # either a value or a list of values for each of the specified
+#        # fields.
+#        self.fields = dict ( [ ( field, Mixed (expected, [expected])) 
+#                                 for (field,expected) in fields.iteritems() ] )
+#
+#        # Null filter means no filter
+#        Parameter.__init__(self, self.fields, doc = doc, nullok = True)
+#
+#    def sql(self, api, join_with = "AND"):
+#        """
+#        Returns a SQL conditional that represents this filter.
+#        """
+#
+#        # So that we always return something
+#        if join_with == "AND":
+#            conditionals = ["True"]
+#        elif join_with == "OR":
+#            conditionals = ["False"]
+#        else:
+#            assert join_with in ("AND", "OR")
+#
+#        # init 
+#        sorts = []
+#        clips = []
+#
+#        for field, value in self.iteritems():
+#            # handle negation, numeric comparisons
+#            # simple, 1-depth only mechanism
+#
+#            modifiers={'~' : False, 
+#                       '<' : False, '>' : False,
+#                       '[' : False, ']' : False,
+#                       '-' : False,
+#                       '&' : False, '|' : False,
+#                       '{': False ,
+#                       }
+#            def check_modifiers(field):
+#                if field[0] in modifiers.keys():
+#                    modifiers[field[0]] = True
+#                    field = field[1:]
+#                    return check_modifiers(field)
+#                return field
+#            field = check_modifiers(field)
+#
+#            # filter on fields
+#            if not modifiers['-']:
+#                if field not in self.fields:
+#                    raise PLCInvalidArgument, "Invalid filter field '%s'" % field
+#
+#                # handling array fileds always as compound values
+#                if modifiers['&'] or modifiers['|']:
+#                    if not isinstance(value, (list, tuple, set)):
+#                        value = [value,]
+#
+#                if isinstance(value, (list, tuple, set)):
+#                    # handling filters like '~slice_id':[]
+#                    # this should return true, as it's the opposite of 'slice_id':[] which is false
+#                    # prior to this fix, 'slice_id':[] would have returned ``slice_id IN (NULL) '' which is unknown 
+#                    # so it worked by coincidence, but the negation '~slice_ids':[] would return false too
+#                    if not value:
+#                        if modifiers['&'] or modifiers['|']:
+#                            operator = "="
+#                            value = "'{}'"
+#                        else:
+#                            field=""
+#                            operator=""
+#                            value = "FALSE"
+#                    else:
+#                        value = map(str, map(api.db.quote, value))
+#                        if modifiers['&']:
+#                            operator = "@>"
+#                            value = "ARRAY[%s]" % ", ".join(value)
+#                        elif modifiers['|']:
+#                            operator = "&&"
+#                            value = "ARRAY[%s]" % ", ".join(value)
+#                        else:
+#                            operator = "IN"
+#                            value = "(%s)" % ", ".join(value)
+#                else:
+#                    if value is None:
+#                        operator = "IS"
+#                        value = "NULL"
+#                    elif isinstance(value, StringTypes) and \
+#                            (value.find("*") > -1 or value.find("%") > -1):
+#                        operator = "LIKE"
+#                        # insert *** in pattern instead of either * or %
+#                        # we dont use % as requests are likely to %-expansion later on
+#                        # actual replacement to % done in PostgreSQL.py
+#                        value = value.replace ('*','***')
+#                        value = value.replace ('%','***')
+#                        value = str(api.db.quote(value))
+#                    else:
+#                        operator = "="
+#                        if modifiers['<']:
+#                            operator='<'
+#                        if modifiers['>']:
+#                            operator='>'
+#                        if modifiers['[']:
+#                            operator='<='
+#                        if modifiers[']']:
+#                            operator='>='
+#                        #else:
+#                        #    value = str(api.db.quote(value))
+#                        # jordan
+#                        if isinstance(value, StringTypes) and value[-2:] != "()": # XXX
+#                            value = str(api.db.quote(value))
+#                        if isinstance(value, datetime.datetime):
+#                            value = str(api.db.quote(str(value)))
+# 
+#                #if prefix: 
+#                #    field = "%s.%s" % (prefix,field)
+#                if field:
+#                    clause = "\"%s\" %s %s" % (field, operator, value)
+#                else:
+#                    clause = "%s %s %s" % (field, operator, value)
+#
+#                if modifiers['~']:
+#                    clause = " ( NOT %s ) " % (clause)
+#
+#                conditionals.append(clause)
+#            # sorting and clipping
+#            else:
+#                if field not in ('SORT','OFFSET','LIMIT'):
+#                    raise PLCInvalidArgument, "Invalid filter, unknown sort and clip field %r"%field
+#                # sorting
+#                if field == 'SORT':
+#                    if not isinstance(value,(list,tuple,set)):
+#                        value=[value]
+#                    for field in value:
+#                        order = 'ASC'
+#                        if field[0] == '+':
+#                            field = field[1:]
+#                        elif field[0] == '-':
+#                            field = field[1:]
+#                            order = 'DESC'
+#                        if field not in self.fields:
+#                            raise PLCInvalidArgument, "Invalid field %r in SORT filter"%field
+#                        sorts.append("%s %s"%(field,order))
+#                # clipping
+#                elif field == 'OFFSET':
+#                    clips.append("OFFSET %d"%value)
+#                # clipping continued
+#                elif field == 'LIMIT' :
+#                    clips.append("LIMIT %d"%value)
+#
+#        where_part = (" %s " % join_with).join(conditionals)
+#        clip_part = ""
+#        if sorts:
+#            clip_part += " ORDER BY " + ",".join(sorts)
+#        if clips:
+#            clip_part += " " + " ".join(clips)
+##       print 'where_part=',where_part,'clip_part',clip_part
+#        return (where_part,clip_part)
+#
diff --git a/manifold/core/query.py b/manifold/core/query.py
new file mode 100644 (file)
index 0000000..764336f
--- /dev/null
@@ -0,0 +1,585 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+#
+# Query representation
+#
+# Copyright (C) UPMC Paris Universitas
+# Authors:
+#   Jordan Augé         <jordan.auge@lip6.fr>
+#   Marc-Olivier Buob   <marc-olivier.buob@lip6.fr>
+#   Thierry Parmentelat <thierry.parmentelat@inria.fr>
+
+from types                      import StringTypes
+from manifold.core.filter       import Filter, Predicate
+from manifold.util.frozendict   import frozendict
+from manifold.util.type         import returns, accepts
+from manifold.util.clause       import Clause
+import copy
+
+import json
+import uuid
+
+def uniqid (): 
+    return uuid.uuid4().hex
+
+debug=False
+debug=True
+
+class ParameterError(StandardError): pass
+
+class Query(object):
+    """
+    Implements a TopHat query.
+
+    We assume this is a correct DAG specification.
+
+    1/ A field designates several tables = OR specification.
+    2/ The set of fields specifies a AND between OR clauses.
+    """
+
+    #--------------------------------------------------------------------------- 
+    # Constructor
+    #--------------------------------------------------------------------------- 
+
+    def __init__(self, *args, **kwargs):
+
+        self.query_uuid = uniqid()
+
+        # Initialize optional parameters
+        self.clear()
+    
+        #l = len(kwargs.keys())
+        len_args = len(args)
+
+        if len(args) == 1:
+            if isinstance(args[0], dict):
+                kwargs = args[0]
+                args = []
+
+        # Initialization from a tuple
+
+        if len_args in range(2, 7) and type(args) == tuple:
+            # Note: range(x,y) <=> [x, y[
+
+            # XXX UGLY
+            if len_args == 3:
+                self.action = 'get'
+                self.params = {}
+                self.timestamp     = 'now'
+                self.object, self.filters, self.fields = args
+            elif len_args == 4:
+                self.object, self.filters, self.params, self.fields = args
+                self.action = 'get'
+                self.timestamp     = 'now'
+            else:
+                self.action, self.object, self.filters, self.params, self.fields, self.timestamp = args
+
+        # Initialization from a dict
+        elif "object" in kwargs:
+            if "action" in kwargs:
+                self.action = kwargs["action"]
+                del kwargs["action"]
+            else:
+                print "W: defaulting to get action"
+                self.action = "get"
+
+
+            self.object = kwargs["object"]
+            del kwargs["object"]
+
+            if "filters" in kwargs:
+                self.filters = kwargs["filters"]
+                del kwargs["filters"]
+            else:
+                self.filters = Filter()
+
+            if "fields" in kwargs:
+                self.fields = set(kwargs["fields"])
+                del kwargs["fields"]
+            else:
+                self.fields = set()
+
+            # "update table set x = 3" => params == set
+            if "params" in kwargs:
+                self.params = kwargs["params"]
+                del kwargs["params"]
+            else:
+                self.params = {}
+
+            if "timestamp" in kwargs:
+                self.timestamp = kwargs["timestamp"]
+                del kwargs["timestamp"]
+            else:
+                self.timestamp = "now" 
+
+            if kwargs:
+                raise ParameterError, "Invalid parameter(s) : %r" % kwargs.keys()
+        #else:
+        #        raise ParameterError, "No valid constructor found for %s : args = %r" % (self.__class__.__name__, args)
+
+        self.sanitize()
+
+    def sanitize(self):
+        if not self.filters:   self.filters   = Filter()
+        if not self.params:    self.params    = {}
+        if not self.fields:    self.fields    = set()
+        if not self.timestamp: self.timestamp = "now" 
+
+        if isinstance(self.filters, list):
+            f = self.filters
+            self.filters = Filter()
+            for x in f:
+                pred = Predicate(x)
+                self.filters.add(pred)
+        elif isinstance(self.filters, Clause):
+            self.filters = Filter.from_clause(self.filters)
+
+        if isinstance(self.fields, list):
+            self.fields = set(self.fields)
+
+        for field in self.fields:
+            if not isinstance(field, StringTypes):
+                raise TypeError("Invalid field name %s (string expected, got %s)" % (field, type(field)))
+
+    #--------------------------------------------------------------------------- 
+    # Helpers
+    #--------------------------------------------------------------------------- 
+
+    def copy(self):
+        return copy.deepcopy(self)
+
+    def clear(self):
+        self.action = 'get'
+        self.object = None
+        self.filters = Filter()
+        self.params  = {}
+        self.fields  = set()
+        self.timestamp  = 'now' # ignored for now
+
+    def to_sql(self, platform='', multiline=False):
+        get_params_str = lambda : ', '.join(['%s = %r' % (k, v) for k, v in self.get_params().items()])
+        get_select_str = lambda : ', '.join(self.get_select()) 
+
+        table  = self.get_from()
+        select = 'SELECT %s' % (get_select_str()    if self.get_select()    else '*')
+        where  = 'WHERE %s'  % self.get_where()     if self.get_where()     else ''
+        at     = 'AT %s'     % self.get_timestamp() if self.get_timestamp() else ''
+        params = 'SET %s'    % get_params_str()     if self.get_params()    else ''
+
+        sep = ' ' if not multiline else '\n  '
+        if platform: platform = "%s:" % platform
+        strmap = {
+            'get'   : '%(select)s%(sep)s%(at)s%(sep)sFROM %(platform)s%(table)s%(sep)s%(where)s%(sep)s',                                           
+            'update': 'UPDATE %(platform)s%(table)s%(sep)s%(params)s%(sep)s%(where)s%(sep)s%(select)s',       
+            'create': 'INSERT INTO %(platform)s%(table)s%(sep)s%(params)s%(sep)s%(select)s',
+            'delete': 'DELETE FROM %(platform)s%(table)s%(sep)s%(where)s'
+        }
+
+        return strmap[self.action] % locals()
+
+    @returns(StringTypes)
+    def __str__(self):
+        return self.to_sql(multiline=True)
+
+    @returns(StringTypes)
+    def __repr__(self):
+        return self.to_sql()
+
+    def __key(self):
+        return (self.action, self.object, self.filters, frozendict(self.params), frozenset(self.fields))
+
+    def __hash__(self):
+        return hash(self.__key())
+
+    #--------------------------------------------------------------------------- 
+    # Conversion
+    #--------------------------------------------------------------------------- 
+
+    def to_dict(self):
+        return {
+            'action': self.action,
+            'object': self.object,
+            'timestamp': self.timestamp,
+            'filters': self.filters.to_list(),
+            'params': self.params,
+            'fields': list(self.fields)
+        }
+
+    def to_json (self, analyzed_query=None):
+        query_uuid=self.query_uuid
+        a=self.action
+        o=self.object
+        t=self.timestamp
+        f=json.dumps (self.filters.to_list())
+        p=json.dumps (self.params)
+        c=json.dumps (list(self.fields))
+        # xxx unique can be removed, but for now we pad the js structure
+        unique=0
+
+        if not analyzed_query:
+            aq = 'null'
+        else:
+            aq = analyzed_query.to_json()
+        sq="{}"
+        
+        result= """ new ManifoldQuery('%(a)s', '%(o)s', '%(t)s', %(f)s, %(p)s, %(c)s, %(unique)s, '%(query_uuid)s', %(aq)s, %(sq)s)"""%locals()
+        if debug: print 'ManifoldQuery.to_json:',result
+        return result
+    
+    # this builds a ManifoldQuery object from a dict as received from javascript through its ajax request 
+    # we use a json-encoded string - see manifold.js for the sender part 
+    # e.g. here's what I captured from the server's output
+    # manifoldproxy.proxy: request.POST <QueryDict: {u'json': [u'{"action":"get","object":"resource","timestamp":"latest","filters":[["slice_hrn","=","ple.inria.omftest"]],"params":[],"fields":["hrn","hostname"],"unique":0,"query_uuid":"436aae70a48141cc826f88e08fbd74b1","analyzed_query":null,"subqueries":{}}']}>
+    def fill_from_POST (self, POST_dict):
+        try:
+            json_string=POST_dict['json']
+            dict=json.loads(json_string)
+            for (k,v) in dict.iteritems(): 
+                setattr(self,k,v)
+        except:
+            print "Could not decode incoming ajax request as a Query, POST=",POST_dict
+            if (debug):
+                import traceback
+                traceback.print_exc()
+        self.sanitize()
+
+    #--------------------------------------------------------------------------- 
+    # Accessors
+    #--------------------------------------------------------------------------- 
+
+    @returns(StringTypes)
+    def get_action(self):
+        return self.action
+
+    @returns(frozenset)
+    def get_select(self):
+        return frozenset(self.fields)
+
+    @returns(StringTypes)
+    def get_from(self):
+        return self.object
+
+    @returns(Filter)
+    def get_where(self):
+        return self.filters
+
+    @returns(dict)
+    def get_params(self):
+        return self.params
+
+    @returns(StringTypes)
+    def get_timestamp(self):
+        return self.timestamp
+
+#DEPRECATED#
+#DEPRECATED#    def make_filters(self, filters):
+#DEPRECATED#        return Filter(filters)
+#DEPRECATED#
+#DEPRECATED#    def make_fields(self, fields):
+#DEPRECATED#        if isinstance(fields, (list, tuple)):
+#DEPRECATED#            return set(fields)
+#DEPRECATED#        else:
+#DEPRECATED#            raise Exception, "Invalid field specification"
+
+    #--------------------------------------------------------------------------- 
+    # LINQ-like syntax
+    #--------------------------------------------------------------------------- 
+
+    @classmethod
+    #@returns(Query)
+    def action(self, action, object):
+        """
+        (Internal usage). Craft a Query according to an action name 
+        See methods: get, update, delete, execute.
+        Args:
+            action: A String among {"get", "update", "delete", "execute"}
+            object: The name of the queried object (String)
+        Returns:
+            The corresponding Query instance
+        """
+        query = Query()
+        query.action = action
+        query.object = object
+        return query
+
+    @classmethod
+    #@returns(Query)
+    def get(self, object):
+        """
+        Craft the Query which fetches the records related to a given object
+        Args:
+            object: The name of the queried object (String)
+        Returns:
+            The corresponding Query instance
+        """
+        return self.action("get", object)
+
+    @classmethod
+    #@returns(Query)
+    def update(self, object):
+        """
+        Craft the Query which updates the records related to a given object
+        Args:
+            object: The name of the queried object (String)
+        Returns:
+            The corresponding Query instance
+        """
+        return self.action("update", object)
+    
+    @classmethod
+    #@returns(Query)
+    def create(self, object):
+        """
+        Craft the Query which create the records related to a given object
+        Args:
+            object: The name of the queried object (String)
+        Returns:
+            The corresponding Query instance
+        """
+        return self.action("create", object)
+    
+    @classmethod
+    #@returns(Query)
+    def delete(self, object):
+        """
+        Craft the Query which delete the records related to a given object
+        Args:
+            object: The name of the queried object (String)
+        Returns:
+            The corresponding Query instance
+        """
+        return self.action("delete", object)
+    
+    @classmethod
+    #@returns(Query)
+    def execute(self, object):
+        """
+        Craft the Query which execute a processing related to a given object
+        Args:
+            object: The name of the queried object (String)
+        Returns:
+            The corresponding Query instance
+        """
+        return self.action("execute", object)
+
+    #@returns(Query)
+    def at(self, timestamp):
+        """
+        Set the timestamp carried by the query
+        Args:
+            timestamp: The timestamp (it may be a python timestamp, a string
+                respecting the "%Y-%m-%d %H:%M:%S" python format, or "now")
+        Returns:
+            The self Query instance
+        """
+        self.timestamp = timestamp
+        return self
+
+    def filter_by(self, *args):
+        """
+        Args:
+            args: It may be:
+                - the parts of a Predicate (key, op, value)
+                - None
+                - a Filter instance
+                - a set/list/tuple of Predicate instances
+        """
+        if len(args) == 1:
+            filters = args[0]
+            if filters == None:
+                self.filters = Filter()
+                return self
+            if not isinstance(filters, (set, list, tuple, Filter)):
+                filters = [filters]
+            for predicate in filters:
+                self.filters.add(predicate)
+        elif len(args) == 3: 
+            predicate = Predicate(*args)
+            self.filters.add(predicate)
+        else:
+            raise Exception, 'Invalid expression for filter'
+        return self
+            
+    def select(self, *fields):
+
+        # Accept passing iterables
+        if len(fields) == 1:
+            tmp, = fields
+            if not tmp:
+                fields = None
+            elif isinstance(tmp, (list, tuple, set, frozenset)):
+                fields = tuple(tmp)
+
+        if not fields:
+            # Delete all fields
+            self.fields = set()
+            return self
+
+        for field in fields:
+            self.fields.add(field)
+        return self
+
+    def set(self, params):
+        self.params.update(params)
+        return self
+
+    def __or__(self, query):
+        assert self.action == query.action
+        assert self.object == query.object
+        assert self.timestamp == query.timestamp # XXX
+        filter = self.filters | query.filters
+        # fast dict union
+        # http://my.safaribooksonline.com/book/programming/python/0596007973/python-shortcuts/pythoncook2-chp-4-sect-17
+        params = dict(self.params, **query.params)
+        fields = self.fields | query.fields
+        return Query.action(self.action, self.object).filter_by(filter).select(fields)
+
+    def __and__(self, query):
+        assert self.action == query.action
+        assert self.object == query.object
+        assert self.timestamp == query.timestamp # XXX
+        filter = self.filters & query.filters
+        # fast dict intersection
+        # http://my.safaribooksonline.com/book/programming/python/0596007973/python-shortcuts/pythoncook2-chp-4-sect-17
+        params =  dict.fromkeys([x for x in self.params if x in query.params])
+        fields = self.fields & query.fields
+        return Query.action(self.action, self.object).filter_by(filter).select(fields)
+
+    def __le__(self, query):
+        return ( self == self & query ) or ( query == self | query )
+
+class AnalyzedQuery(Query):
+
+    # XXX we might need to propagate special parameters sur as DEBUG, etc.
+
+    def __init__(self, query=None, metadata=None):
+        self.clear()
+        self.metadata = metadata
+        if query:
+            self.query_uuid = query.query_uuid
+            self.analyze(query)
+        else:
+            self.query_uuid = uniqid()
+
+    @returns(StringTypes)
+    def __str__(self):
+        out = []
+        fields = self.get_select()
+        fields = ", ".join(fields) if fields else '*'
+        out.append("SELECT %s FROM %s WHERE %s" % (
+            fields,
+            self.get_from(),
+            self.get_where()
+        ))
+        cpt = 1
+        for method, subquery in self.subqueries():
+            out.append('  [SQ #%d : %s] %s' % (cpt, method, str(subquery)))
+            cpt += 1
+
+        return "\n".join(out)
+
+    def clear(self):
+        super(AnalyzedQuery, self).clear()
+        self._subqueries = {}
+
+    def subquery(self, method):
+        # Allows for the construction of a subquery
+        if not method in self._subqueries:
+            analyzed_query = AnalyzedQuery(metadata=self.metadata)
+            analyzed_query.action = self.action
+            try:
+                type = self.metadata.get_field_type(self.object, method)
+            except ValueError ,e: # backwards 1..N
+                type = method
+            analyzed_query.object = type
+            self._subqueries[method] = analyzed_query
+        return self._subqueries[method]
+
+    def get_subquery(self, method):
+        return self._subqueries.get(method, None)
+
+    def remove_subquery(self, method):
+        del self._subqueries[method]
+
+    def get_subquery_names(self):
+        return set(self._subqueries.keys())
+
+    def get_subqueries(self):
+        return self._subqueries
+
+    def subqueries(self):
+        for method, subquery in self._subqueries.iteritems():
+            yield (method, subquery)
+
+    def filter_by(self, filters):
+        if not isinstance(filters, (set, list, tuple, Filter)):
+            filters = [filters]
+        for predicate in filters:
+            if predicate and '.' in predicate.key:
+                method, subkey = predicate.key.split('.', 1)
+                # Method contains the name of the subquery, we need the type
+                # XXX type = self.metadata.get_field_type(self.object, method)
+                sub_pred = Predicate(subkey, predicate.op, predicate.value)
+                self.subquery(method).filter_by(sub_pred)
+            else:
+                super(AnalyzedQuery, self).filter_by(predicate)
+        return self
+
+    def select(self, *fields):
+
+        # XXX passing None should reset fields in all subqueries
+
+        # Accept passing iterables
+        if len(fields) == 1:
+            tmp, = fields
+            if isinstance(tmp, (list, tuple, set, frozenset)):
+                fields = tuple(tmp)
+
+        for field in fields:
+            if field and '.' in field:
+                method, subfield = field.split('.', 1)
+                # Method contains the name of the subquery, we need the type
+                # XXX type = self.metadata.get_field_type(self.object, method)
+                self.subquery(method).select(subfield)
+            else:
+                super(AnalyzedQuery, self).select(field)
+        return self
+
+    def set(self, params):
+        for param, value in self.params.items():
+            if '.' in param:
+                method, subparam = param.split('.', 1)
+                # Method contains the name of the subquery, we need the type
+                # XXX type = self.metadata.get_field_type(self.object, method)
+                self.subquery(method).set({subparam: value})
+            else:
+                super(AnalyzedQuery, self).set({param: value})
+        return self
+        
+    def analyze(self, query):
+        self.clear()
+        self.action = query.action
+        self.object = query.object
+        self.filter_by(query.filters)
+        self.set(query.params)
+        self.select(query.fields)
+
+    def to_json (self):
+        query_uuid=self.query_uuid
+        a=self.action
+        o=self.object
+        t=self.timestamp
+        f=json.dumps (self.filters.to_list())
+        p=json.dumps (self.params)
+        c=json.dumps (list(self.fields))
+        # xxx unique can be removed, but for now we pad the js structure
+        unique=0
+
+        aq = 'null'
+        sq=", ".join ( [ "'%s':%s" % (object, subquery.to_json())
+                  for (object, subquery) in self._subqueries.iteritems()])
+        sq="{%s}"%sq
+        
+        result= """ new ManifoldQuery('%(a)s', '%(o)s', '%(t)s', %(f)s, %(p)s, %(c)s, %(unique)s, '%(query_uuid)s', %(aq)s, %(sq)s)"""%locals()
+        if debug: print 'ManifoldQuery.to_json:',result
+        return result
diff --git a/manifold/core/result_value.py b/manifold/core/result_value.py
new file mode 100644 (file)
index 0000000..4fe505f
--- /dev/null
@@ -0,0 +1,254 @@
+# Inspired from GENI error codes
+
+import time
+import pprint
+
+class ResultValue(dict):
+
+    # type
+    SUCCESS     = 0
+    WARNING     = 1
+    ERROR       = 2
+
+    # origin
+    CORE        = 0
+    GATEWAY     = 1
+
+    # code
+    SUCCESS     = 0
+    SERVERBUSY  = 32001
+    BADARGS     = 1
+    ERROR       = 2
+    FORBIDDEN   = 3
+    BADVERSION  = 4
+    SERVERERROR = 5
+    TOOBIG      = 6
+    REFUSED     = 7
+    TIMEDOUT    = 8
+    DBERROR     = 9
+    RPCERROR    = 10
+
+    # description
+    ERRSTR = {
+        SUCCESS     : 'Success',
+        SERVERBUSY  : 'Server is (temporarily) too busy; try again later',
+        BADARGS     : 'Bad Arguments: malformed',
+        ERROR       : 'Error (other)',
+        FORBIDDEN   : 'Operation Forbidden: eg supplied credentials do not provide sufficient privileges (on the given slice)',
+        BADVERSION  : 'Bad Version (eg of RSpec)',
+        SERVERERROR : 'Server Error',
+        TOOBIG      : 'Too Big (eg request RSpec)',
+        REFUSED     : 'Operation Refused',
+        TIMEDOUT    : 'Operation Timed Out',
+        DBERROR     : 'Database Error',
+        RPCERROR    : ''
+    }
+
+    ALLOWED_FIELDS = set(['origin', 'type', 'code', 'value', 'description', 'traceback', 'ts'])
+
+    def __init__(self, **kwargs):
+        
+        # Checks
+        given = set(kwargs.keys())
+        cstr_success = set(['code', 'origin', 'value']) <= given
+        cstr_error   = set(['code', 'type', 'origin', 'description']) <= given
+        assert given <= self.ALLOWED_FIELDS, "Wrong fields in ResultValue constructor: %r" % (given - self.ALLOWED_FIELDS)
+        assert cstr_success or cstr_error, 'Incomplete set of fields in ResultValue constructor: %r' % given
+        
+        dict.__init__(self, **kwargs)
+
+        # Set missing fields to None
+        for field in self.ALLOWED_FIELDS - given:
+            self[field] = None
+        if not 'ts' in self:
+            self['ts'] = time.time()
+            
+
+    # Internal MySlice errors   : return ERROR
+    # Internal MySlice warnings : return RESULT WITH WARNINGS
+    # Debug                     : add DEBUG INFORMATION
+    # Gateway errors            : return RESULT WITH WARNING
+    # all Gateways errors       : return ERROR
+    
+    @classmethod
+    def get_result_value(self, results, result_value_array):
+        # let's analyze the results of the query plan
+        # XXX we should inspect all errors to determine whether to return a
+        # result or not
+        if not result_value_array:
+            # No error
+            return ResultValue(code=self.SUCCESS, origin=[self.CORE, 0], value=results)
+        else:
+            # Handle errors
+            return ResultValue(code=self.WARNING, origin=[self.CORE, 0], description=result_value_array, value=results)
+
+    @classmethod
+    def get_error(self, error):
+        return ResultValue(code=error, origin=[self.CORE, 0], value=self.ERRSTR[error])
+
+    @classmethod
+    def get_success(self, result):
+        return ResultValue(code=self.SUCCESS, origin=[self.CORE, 0], value=result) 
+
+    def ok_value(self):
+        return self['value']
+
+    def error(self):
+        err = "%r" % self['description']
+
+    @staticmethod
+    def to_html (raw_dict):
+        return pprint.pformat (raw_dict).replace("\\n","<br/>")
+
+# 67    <code>
+# 68      <value>9</value>
+# 69      <label>DBERROR</label>
+# 70      <description>Database Error</description>
+# 71    </code>
+# 72    <code>
+# 73      <value>10</value>
+# 74      <label>RPCERROR</label>
+# 75      <description>RPC Error</description>
+# 76    </code>
+# 77    <code>
+# 78      <value>11</value>
+# 79      <label>UNAVAILABLE</label>
+# 80      <description>Unavailable (eg server in lockdown)</description>
+# 81    </code>
+# 82    <code>
+# 83      <value>12</value>
+# 84      <label>SEARCHFAILED</label>
+# 85      <description>Search Failed (eg for slice)</description>
+# 86    </code>
+# 87    <code>
+# 88      <value>13</value>
+# 89      <label>UNSUPPORTED</label>
+# 90      <description>Operation Unsupported</description>
+# 91    </code>
+# 92    <code>
+# 93      <value>14</value>
+# 94      <label>BUSY</label>
+# 95      <description>Busy (resource, slice, or server); try again
+# later</description>
+# 96    </code>
+# 97    <code>
+# 98      <value>15</value>
+# 99      <label>EXPIRED</label>
+# 100     <description>Expired (eg slice)</description>
+# 101   </code>
+# 102   <code>
+# 103     <value>16</value>
+# 104     <label>INPROGRESS</label>
+# 105     <description>In Progress</description>
+# 106   </code>
+# 107   <code>
+# 108     <value>17</value>
+# 109     <label>ALREADYEXISTS</label>
+# 110     <description>Already Exists (eg slice)</description>
+# 111   </code>
+# 112 <!-- 18+ not in original ProtoGENI implementation or Error Code --
+# 113   -- proposal. -->
+# 114   <code>
+# 115     <value>18</value>
+# 116     <label>MISSINGARGS</label>
+# 117     <description>Required argument(s) missing</description>
+# 118   </code>
+# 119   <code>
+# 120     <value>19</value>
+# 121     <label>OUTOFRANGE</label>
+# 122     <description>Input Argument outside of legal range</description>
+# 123   </code>
+# 124   <code>
+# 125     <value>20</value>
+# 126     <label>CREDENTIAL_INVALID</label>
+# 127     <description>Not authorized: Supplied credential is
+# invalid</description>
+# 128   </code>
+# 129   <code>
+# 130     <value>21</value>
+# 131     <label>CREDENTIAL_EXPIRED</label>
+# 132     <description>Not authorized: Supplied credential expired</description>
+# 133   </code>
+# 134   <code>
+# 135     <value>22</value>
+# 136     <label>CREDENTIAL_MISMATCH</label>
+# 137     <description>Not authorized: Supplied credential does not match client
+# certificate or does not match the given slice URN</description>
+# 138   </code>
+# 139   <code>
+# 140     <value>23</value>
+# 141     <label>CREDENTIAL_SIGNER_UNTRUSTED</label>
+# 142     <description>Not authorized: Supplied credential not signed by a trusted
+# authority</description>
+# 143   </code>
+# 144   <code>
+# 145     <value>24</value>
+# 146     <label>VLAN_UNAVAILABLE</label>
+# 147     <description>VLAN tag(s) requested not available (likely stitching
+# failure)</description>
+# 148   </code>
+# 149 </geni-error-codes>
+# 150 
+# <!--
+# || 0    || SUCCESS      || "Success" ||
+# || 1    || BADARGS      || "Bad Arguments: malformed arguments" ||
+# || 2    || ERROR        || "Error (other)" ||
+# || 3    || FORBIDDEN    || "Operation Forbidden: eg supplied credentials do # not provide sufficient privileges (on given slice)" ||
+# || 4    || BADVERSION   || "Bad Version (eg of RSpec)" ||
+# || 5    || SERVERERROR  || "Server Error" ||
+# || 6    || TOOBIG       || "Too Big (eg request RSpec)" ||
+# || 7    || REFUSED      || "Operation Refused" ||
+# || 8    || TIMEDOUT     || "Operation Timed Out" ||
+# || 9    || DBERROR      || "Database Error" ||
+# || 10   || RPCERROR     || "RPC Error" ||
+# || 11   || UNAVAILABLE  || "Unavailable (eg server in lockdown)" ||
+# || 12   || SEARCHFAILED         || "Search Failed (eg for slice)" ||
+# || 13   || UNSUPPORTED  || "Operation Unsupported" ||
+# || 14   || BUSY         || "Busy (resource, slice, or server); try again # later" ||
+# || 15   || EXPIRED      || "Expired (eg slice)" ||
+# || 16   || INPROGRESS   || "In Progress" ||
+# || 17   || ALREADYEXISTS        || "Already Exists (eg the slice}" ||
+# || 18   || MISSINGARGS  || "Required argument(s) missing" ||
+# || 19   || OUTOFRANGE   || "Requested expiration time or other argument not # valid" ||
+# || 20   || CREDENTIAL_INVALID   || "Not authorized: Supplied credential is # invalid" ||
+# || 21   || CREDENTIAL_EXPIRED   || "Not authorized: Supplied credential # expired" ||
+# || 22   || CREDENTIAL_MISMATCH   || "Not authorized: Supplied credential # does not match the supplied client certificate or does not match the given slice # URN" ||
+# || 23   || CREDENTIAL_SIGNER_UNTRUSTED   || "Not authorized: Supplied # credential not signed by trusted authority" ||
+# || 24   || VLAN_UNAVAILABLE     || "VLAN tag(s) requested not available # (likely stitching failure)" ||
+# 
+# 18+ not in original ProtoGENI implementation or Error Code proposal.
+# 
+# Maping to SFA Faults:
+# SfaAuthenticationFailure: FORBIDDEN
+# SfaDBErrr: DBERROR
+# SfaFault: ERROR
+# SfaPermissionDenied: FORBIDDEN
+# SfaNotImplemented: UNSUPPORTED
+# SfaAPIError: SERVERERROR
+# MalformedHrnException: BADARGS
+# NonExistingRecord: SEARCHFAILED
+# ExistingRecord: ALREADYEXISTS
+# NonexistingCredType: SEARCHFAILED? FORBIDDEN? CREDENTIAL_INVALID?
+# NonexitingFile: SEARCHFAILED
+# InvalidRPCParams: RPCERROR
+# ConnectionKeyGIDMismatch: FORBIDDEN? CREDENTIAL_MISMATCH?
+# MissingCallerGID: SEARCHFAILED? CREDENTIAL_MISMATCH?
+# RecordNotFound: SEARCHFAILED
+# PlanetLAbRecordDoesNotExist: SEARCHFAILED
+# PermissionError: FORBIDDEN
+# InsufficientRights: FORBIDDEN
+# MissingDelegateBit: CREDENTIAL_INVALID? FORBIDDEN?
+# ChildRightsNotSubsetOfParent: CREDENTIAL_INVALID
+# CertMissingParent: FORBIDDEN? CREDENTIAL_INVALID?
+# CertNotSignedByParent: FORBIDDEN
+# GidParentHrn: FORBIDDEN? CREDENTIAL_INVALID?
+# GidInvalidParentHrn: FORBIDDEN? CREDENTIAL_INVALID?
+# SliverDoesNotExist: SEARCHFAILED
+# MissingTrustedRoots: SERVERERROR
+# MissingSfaInfo: SERVERERROR
+# InvalidRSpec: BADARGS
+# InvalidRSpecElement: BADARGS
+# AccountNotEnabled: REFUSED? FORBIDDEN?
+# CredentialNotVerifiable: CREDENTIAL_INVALID
+# CertExpired: EXPIRED? FORBIDDEN?
+# -->
diff --git a/manifold/css/manifold.css b/manifold/css/manifold.css
new file mode 100644 (file)
index 0000000..42c034d
--- /dev/null
@@ -0,0 +1,4 @@
+.template {
+       visibility: hidden;
+       position: absolute;
+}
diff --git a/manifold/js/class.js b/manifold/js/class.js
new file mode 100644 (file)
index 0000000..63b570c
--- /dev/null
@@ -0,0 +1,64 @@
+/* Simple JavaScript Inheritance
+ * By John Resig http://ejohn.org/
+ * MIT Licensed.
+ */
+// Inspired by base2 and Prototype
+(function(){
+  var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
+  // The base Class implementation (does nothing)
+  this.Class = function(){};
+  // Create a new Class that inherits from this class
+  Class.extend = function(prop) {
+    var _super = this.prototype;
+   
+    // Instantiate a base class (but only create the instance,
+    // don't run the init constructor)
+    initializing = true;
+    var prototype = new this();
+    initializing = false;
+   
+    // Copy the properties over onto the new prototype
+    for (var name in prop) {
+      // Check if we're overwriting an existing function
+      prototype[name] = typeof prop[name] == "function" &&
+        typeof _super[name] == "function" && fnTest.test(prop[name]) ?
+        (function(name, fn){
+          return function() {
+            var tmp = this._super;
+           
+            // Add a new ._super() method that is the same method
+            // but on the super-class
+            this._super = _super[name];
+           
+            // The method only need to be bound temporarily, so we
+            // remove it when we're done executing
+            var ret = fn.apply(this, arguments);        
+            this._super = tmp;
+           
+            return ret;
+          };
+        })(name, prop[name]) :
+        prop[name];
+    }
+   
+    // The dummy class constructor
+    function Class() {
+      // All construction is actually done in the init method
+      if ( !initializing && this.init )
+        this.init.apply(this, arguments);
+    }
+   
+    // Populate our constructed prototype object
+    Class.prototype = prototype;
+   
+    // Enforce the constructor to be what we expect
+    Class.prototype.constructor = Class;
+    // And make this class extendable
+    Class.extend = arguments.callee;
+   
+    return Class;
+  };
+})();
index 7d885ae..4da77da 100644 (file)
@@ -1,8 +1,8 @@
-function ManifoldQuery(action, subject, timestamp, filters, params, fields, unique, query_uuid, aq, sq) {  
+function ManifoldQuery(action, object, timestamp, filters, params, fields, unique, query_uuid, aq, sq) {  
     // get, update, delete, create
     var action;
     // slice, user, network... 
-    var subject; 
+    var object; 
     // timestamp, now, latest(cache) : date of the results queried    
     var timestamp;
     // key(field),op(=<>),value
@@ -23,17 +23,17 @@ function ManifoldQuery(action, subject, timestamp, filters, params, fields, uniq
 /*-------------------------------------------------------------
               Query properties are SQL like : 
 ---------------------------------------------------------------
-SELECT fields FROM subject WHERE filter;
-UPDATE subject SET field=value WHERE filter; / returns SELECT 
-DELETE FROM subject WHERE filter
-INSERT INTO subject VALUES(field=value)
+SELECT fields FROM object WHERE filter;
+UPDATE object SET field=value WHERE filter; / returns SELECT 
+DELETE FROM object WHERE filter
+INSERT INTO object VALUES(field=value)
 -------------------------------------------------------------*/
     
     this.__repr = function () {
-       res  = "ManyfoldQuery ";
+       res  = "ManifoldQuery ";
        res += " id=" + this.query_uuid;
        res += " a=" + this.action;
-       res += " s=" + this.subject;
+       res += " o=" + this.object;
        res += " ts=" + this.timestamp;
        res += " flts=" + this.filters;
        res += " flds=" + this.fields;
@@ -42,9 +42,31 @@ INSERT INTO subject VALUES(field=value)
     }  
 
     this.clone = function() {
-        q = new ManifoldQuery();
-        return jQuery.extend(true, q, this);
+        // 
+        var q = new ManifoldQuery();
+        q.action     = this.action;
+        q.object     = this.object;
+        q.timestamp  = this.timestamp;
+        q.filters    = this.filters.slice();
+        q.fields     = this.fields.slice();
+        q.query_uuid = this.query_uuid;
+
+        if (this.analyzed_query)
+            q.analyzed_query = this.analyzed_query.clone();
+        else
+            q.analyzed_query = null;
+
+        if (this.subqueries) {
+            q.subqueries = {}
+            for (method in this.subqueries)
+                q.subqueries[method] = this.subqueries[method].clone();
+        }
+
+        // deep extend not working for custom objects
+        // $.extend(true, q, this);
+        return q;
     }
+
     this.add_filter = function(key, op, value) {
         this.filters.push(new Array(key, op, value));
     }
@@ -74,7 +96,7 @@ INSERT INTO subject VALUES(field=value)
     }
 
     // FIXME These functions computing diff's between queries are meant to be shared
-    this.diff_fields = function (otherQuery) {
+    this.diff_fields = function(otherQuery) {
         var f1 = this.fields;
         var f2 = otherQuery.fields;
 
@@ -87,7 +109,7 @@ INSERT INTO subject VALUES(field=value)
     }
 
     // FIXME Modify filter to filters
-    this.diff_filter = function (otherQuery) {
+    this.diff_filter = function(otherQuery) {
         var f1 = this.filters;
         var f2 = otherQuery.filters;
         
@@ -98,9 +120,38 @@ INSERT INTO subject VALUES(field=value)
         
         return {'added':added, 'removed':removed};
     } 
+
+    // Callaback received 3 parameters: query, data, parent_query
+    this.iter_subqueries = function(callback, data)
+    {
+        rec = function(query, callback, data, parent_query) {
+            callback(query, data, parent_query);
+            jQuery.each(query.subqueries, function(object, subquery) {
+                rec(subquery, callback, data, query);
+            });
+        };
+
+        if (this.analyzed_query !== undefined)
+            query = this.analyzed_query;
+        else
+            query = this;
+
+        rec(query, callback, data, null);
+    }
+
+    this.select = function(field)
+    {
+        this.fields.push(field);
+    }
+
+    this.unselect = function(field)
+    {   
+        this.fields = $.grep(this.fields, function(x) { return x != field; });
+    }
+
 // we send queries as a json string now 
 //    this.as_POST = function() {
-//        return {'action': this.action, 'subject': this.subject, 'timestamp': this.timestamp,
+//        return {'action': this.action, 'object': this.object, 'timestamp': this.timestamp,
 //             'filters': this.filters, 'params': this.params, 'fields': this.fields};
 //    }
     this.analyze_subqueries = function() {
@@ -108,7 +159,7 @@ INSERT INTO subject VALUES(field=value)
         var q = new ManifoldQuery();
         q.query_uuid = this.query_uuid;
         q.action = this.action;
-        q.subject = this.subject;
+        q.object = this.object;
         q.timestamp = this.timestamp;
 
         /* Filters */
@@ -118,17 +169,17 @@ INSERT INTO subject VALUES(field=value)
             var v = filter[2];
             var pos = k.indexOf('.');
             if (pos != -1) {
-                var subject = k.substr(0, pos);
+                var object = k.substr(0, pos);
                 var field = k.substr(pos+1);
-                if (jQuery.inArray(this.subject, q.subqueries) == -1) {
-                    q.subqueries[this.subject] = new ManifoldQuery();
-                    q.subqueries[this.subject].action = this.action;
-                    q.subqueries[this.subject].subject = this.subject;
-                    q.subqueries[this.subject].timestamp = this.timestamp;
+                if (!q.subqueries[object]) {
+                    q.subqueries[object] = new ManifoldQuery();
+                    q.subqueries[object].action = q.action;
+                    q.subqueries[object].object = object;
+                    q.subqueries[object].timestamp = q.timestamp;
                 }
-                q.subqueries[this.subject].filters.push(Array(field, op, v));
+                q.subqueries[object].filters.push(Array(field, op, v));
             } else {
-                q.filters.push(this.filter);
+                q.filters.push(filter);
             }
         });
 
@@ -136,15 +187,15 @@ INSERT INTO subject VALUES(field=value)
         jQuery.each(this.params, function(param, value) {
             var pos = param.indexOf('.');
             if (pos != -1) {
-                var subject = param.substr(0, pos);
+                var object = param.substr(0, pos);
                 var field = param.substr(pos+1);
-                if (jQuery.inArray(this.subject, q.subqueries) == -1) {
-                    q.subqueries[this.subject] = new ManifoldQuery();
-                    q.subqueries[this.subject].action = this.action;
-                    q.subqueries[this.subject].subject = this.subject;
-                    q.subqueries[this.subject].timestamp = this.timestamp;
+                if (!q.subqueries[object]) {
+                    q.subqueries[object] = new ManifoldQuery();
+                    q.subqueries[object].action = q.action;
+                    q.subqueries[object].object = object;
+                    q.subqueries[object].timestamp = q.timestamp;
                 }
-                q.subqueries[this.subject].params[field] = value;
+                q.subqueries[object].params[field] = value;
             } else {
                 q.params[field] = value;
             }
@@ -154,15 +205,15 @@ INSERT INTO subject VALUES(field=value)
         jQuery.each(this.fields, function(i, v) {
             var pos = v.indexOf('.');
             if (pos != -1) {
-                var subject = v.substr(0, pos);
+                var object = v.substr(0, pos);
                 var field = v.substr(pos+1);
-                if (jQuery.inArray(this.subject, q.subqueries) == -1) {
-                    q.subqueries[this.subject] = new ManifoldQuery();
-                    q.subqueries[this.subject].action = this.action;
-                    q.subqueries[this.subject].subject = this.subject;
-                    q.subqueries[this.subject].timestamp = this.timestamp;
+                if (!q.subqueries[object]) {
+                    q.subqueries[object] = new ManifoldQuery();
+                    q.subqueries[object].action = q.action;
+                    q.subqueries[object].object = object;
+                    q.subqueries[object].timestamp = q.timestamp;
                 }
-                q.subqueries[this.subject].fields.push(field);
+                q.subqueries[object].fields.push(field);
             } else {
                 q.fields.push(v);
             }
@@ -171,14 +222,50 @@ INSERT INTO subject VALUES(field=value)
     }
  
     /* constructor */
-    this.action = action;
-    this.subject = subject;
-    this.timestamp = timestamp;
-    this.filters = filters;
-    this.params = params;
-    this.fields = fields;
-    this.unique = unique;
+    if (typeof action == "undefined")
+        this.action = "get";
+    else
+        this.action = action;
+    
+    if (typeof object == "undefined")
+        this.object = null;
+    else
+        this.object = object;
+
+    if (typeof timestamp == "undefined")
+        this.timestamp = "now";
+    else
+        this.timestamp = timestamp;
+
+    if (typeof filters == "undefined")
+        this.filters = [];
+    else
+        this.filters = filters;
+
+    if (typeof params == "undefined")
+        this.params = {};
+    else
+        this.params = params;
+
+    if (typeof fields == "undefined")
+        this.fields = [];
+    else
+        this.fields = fields;
+
+    if (typeof unique == "undefined")
+        this.unique = false;
+    else
+        this.unique = unique;
+
     this.query_uuid = query_uuid;
-    this.analyzed_query = aq;
-    this.subqueries = sq;
+
+    if (typeof aq == "undefined")
+        this.analyzed_query = null;
+    else
+        this.analyzed_query = aq;
+
+    if (typeof sq == "undefined")
+        this.subqueries = {};
+    else
+        this.subqueries = sq;
 }  
index 81c61ce..826ea32 100644 (file)
@@ -17,144 +17,982 @@ function debug_query (msg, query) {
     else messages.debug ("debug_query: " + msg + " query= " + query);
 }
 
+// http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/
+Object.toType = (function toType(global) {
+  return function(obj) {
+    if (obj === global) {
+      return "global";
+    }
+    return ({}).toString.call(obj).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
+  }
+})(this);
+
 /* ------------------------------------------------------------ */
-// this namespace holds functions for globally managing query objects
+
+// Constants that should be somehow moved to a plugin.js file
+var FILTER_ADDED   = 1;
+var FILTER_REMOVED = 2;
+var CLEAR_FILTERS  = 3;
+var FIELD_ADDED    = 4;
+var FIELD_REMOVED  = 5;
+var CLEAR_FIELDS   = 6;
+var NEW_RECORD     = 7;
+var CLEAR_RECORDS  = 8;
+var FIELD_STATE_CHANGED = 9;
+
+var IN_PROGRESS    = 101;
+var DONE           = 102;
+
+/* Update requests related to subqueries */
+var SET_ADD        = 201;
+var SET_REMOVED    = 202;
+
+// request
+var FIELD_REQUEST_CHANGE  = 301;
+var FIELD_REQUEST_ADD     = 302;
+var FIELD_REQUEST_REMOVE  = 303;
+var FIELD_REQUEST_ADD_RESET = 304;
+var FIELD_REQUEST_REMOVE_RESET = 305;
+// status
+var FIELD_REQUEST_PENDING = 401;
+var FIELD_REQUEST_SUCCESS = 402;
+var FIELD_REQUEST_FAILURE = 403;
+
+/* Query status */
+var STATUS_NONE               = 500; // Query has not been started yet
+var STATUS_GET_IN_PROGRESS    = 501; // Query has been sent, no result has been received
+var STATUS_GET_RECEIVED       = 502; // Success
+var STATUS_GET_ERROR          = 503; // Error
+var STATUS_UPDATE_PENDING     = 504;
+var STATUS_UPDATE_IN_PROGRESS = 505;
+var STATUS_UPDATE_RECEIVED    = 506;
+var STATUS_UPDATE_ERROR       = 507;
+
+/* Requests for query cycle */
+var RUN_UPDATE     = 601;
+
+/* MANIFOLD types */
+var TYPE_VALUE  = 1;
+var TYPE_RECORD = 2;
+var TYPE_LIST_OF_VALUES = 3;
+var TYPE_LIST_OF_RECORDS = 4;
+
+
+// A structure for storing queries
+
+function QueryExt(query, parent_query_ext, main_query_ext, update_query_ext, disabled) {
+
+    /* Constructor */
+    if (typeof query == "undefined")
+        throw "Must pass a query in QueryExt constructor";
+    this.query                 = query;
+    this.parent_query_ext      = (typeof parent_query_ext      == "undefined") ? null  : parent_query_ext;
+    this.main_query_ext        = (typeof main_query_ext        == "undefined") ? null  : main_query_ext;
+    this.update_query_ext      = (typeof update_query_ext      == "undefined") ? null  : update_query_ext;
+    this.update_query_orig_ext = (typeof update_query_orig_ext == "undefined") ? null  : update_query_orig_ext;
+    this.disabled              = (typeof update_query_ext      == "undefined") ? false : disabled;
+    
+    this.status       = null;
+    this.results      = null;
+    // update_query null unless we are a main_query (aka parent_query == null); only main_query_fields can be updated...
+}
+
+function QueryStore() {
+
+    this.main_queries     = {};
+    this.analyzed_queries = {};
+
+    /* Insertion */
+
+    this.insert = function(query)
+    {
+        // We expect only main_queries are inserted
+
+        /* If the query has not been analyzed, then we analyze it */
+        if (query.analyzed_query == null) {
+            query.analyze_subqueries();
+        }
+
+        /* We prepare the update query corresponding to the main query and store both */
+        /* Note: they have the same UUID */
+
+        // XXX query.change_action() should become deprecated
+        update_query = query.clone();
+        update_query.action = 'update';
+        update_query.analyzed_query.action = 'update';
+        update_query.params = {};
+        update_query_ext = new QueryExt(update_query);
+
+        /* We remember the original query to be able to reset it */
+        update_query_orig_ext = new QueryExt(update_query.clone());
+
+
+        /* We store the main query */
+        query_ext = new QueryExt(query, null, null, update_query_ext, update_query_orig_ext, false);
+        manifold.query_store.main_queries[query.query_uuid] = query_ext;
+        /* Note: the update query does not have an entry! */
+
+
+        // The query is disabled; since it is incomplete until we know the content of the set of subqueries
+        // XXX unless we have no subqueries ???
+        // we will complete with params when records are received... this has to be done by the manager
+        // SET_ADD, SET_REMOVE will change the status of the elements of the set
+        // UPDATE will change also, etc.
+        // XXX We need a proper structure to store this information...
+
+        // We also need to insert all queries and subqueries from the analyzed_query
+        // XXX We need the root of all subqueries
+        query.iter_subqueries(function(sq, data, parent_query) {
+            if (parent_query)
+                parent_query_ext = manifold.query_store.find_analyzed_query_ext(parent_query.query_uuid);
+            else
+                parent_query_ext = null;
+            // XXX parent_query_ext == false
+            // XXX main.subqueries = {} # Normal, we need analyzed_query
+            sq_ext = new QueryExt(sq, parent_query_ext, query_ext)
+            manifold.query_store.analyzed_queries[sq.query_uuid] = sq_ext;
+        });
+
+        // XXX We have spurious update queries...
+    }
+
+    /* Searching */
+
+    this.find_query_ext = function(query_uuid)
+    {
+        return this.main_queries[query_uuid];
+    }
+
+    this.find_query = function(query_uuid)
+    {
+        return this.find_query_ext(query_uuid).query;
+    }
+
+    this.find_analyzed_query_ext = function(query_uuid)
+    {
+        return this.analyzed_queries[query_uuid];
+    }
+
+    this.find_analyzed_query = function(query_uuid)
+    {
+        return this.find_analyzed_query_ext(query_uuid).query;
+    }
+}
+
+/*!
+ * This namespace holds functions for globally managing query objects
+ * \Class Manifold
+ */
 var manifold = {
 
+    /************************************************************************** 
+     * Helper functions
+     **************************************************************************/ 
+
+    separator: '__',
+
+    spin_presets: {},
+
+    spin: function(locator, active /*= true */) {
+        active = typeof active !== 'undefined' ? active : true;
+        try {
+            if (active) {
+                $(locator).spin(manifold.spin_presets);
+            } else {
+                $(locator).spin(false);
+            }
+        } catch (err) { messages.debug("Cannot turn spins on/off " + err); }
+    },
+
+    get_type: function(variable)
+    {
+        switch(Object.toType(variable)) {
+            case 'number':
+            case 'string':
+                return TYPE_VALUE;
+            case 'object':
+                return TYPE_RECORD;
+            case 'array':
+                if ((variable.length > 0) && (Object.toType(variable[0]) === 'object'))
+                    return TYPE_LIST_OF_RECORDS;
+                else
+                    return TYPE_LIST_OF_VALUES;
+        }
+    },
+
+    /************************************************************************** 
+     * Metadata management
+     **************************************************************************/ 
+
+     metadata: {
+
+        get_table: function(method)
+        {
+            var table = MANIFOLD_METADATA[method];
+            return (typeof table === 'undefined') ? null : table;
+        },
+
+        get_columns: function(method)
+        {
+            var table = this.get_table(method);
+            if (!table) {
+                return null;
+            }
+
+            return (typeof table.column === 'undefined') ? null : table.column;
+        },
+
+        get_key: function(method)
+        {
+            var table = this.get_table(method);
+            if (!table)
+                return null;
+
+            return (typeof table.key === 'undefined') ? null : table.key;
+        },
+
+
+        get_column: function(method, name)
+        {
+            var columns = this.get_columns(method);
+            if (!columns)
+                return null;
+
+            $.each(columns, function(i, c) {
+                if (c.name == name)
+                    return c
+            });
+            return null;
+        },
+
+        get_type: function(method, name)
+        {
+            var table = this.get_table(method);
+            if (!table)
+                return null;
+
+            return (typeof table.type === 'undefined') ? null : table.type;
+        }
+
+     },
+
+    /************************************************************************** 
+     * Query management
+     **************************************************************************/ 
+
+    query_store: new QueryStore(),
+
+    // XXX Remaining functions are deprecated since they are replaced by the query store
+
+    /*!
+     * Associative array storing the set of queries active on the page
+     * \memberof Manifold
+     */
     all_queries: {},
 
+    /*!
+     * Insert a query in the global hash table associating uuids to queries.
+     * If the query has no been analyzed yet, let's do it.
+     * \fn insert_query(query)
+     * \memberof Manifold
+     * \param ManifoldQuery query Query to be added
+     */
     insert_query : function (query) { 
-       manifold.all_queries[query.query_uuid]=query; 
+        // NEW API
+        manifold.query_store.insert(query);
+
+        // FORMER API
+        if (query.analyzed_query == null) {
+            query.analyze_subqueries();
+        }
+        manifold.all_queries[query.query_uuid]=query;
     },
+
+    /*!
+     * Returns the query associated to a UUID
+     * \fn find_query(query_uuid)
+     * \memberof Manifold
+     * \param string query_uuid The UUID of the query to be returned
+     */
     find_query : function (query_uuid) { 
-       return manifold.all_queries[query_uuid];
+        return manifold.all_queries[query_uuid];
     },
 
+    /************************************************************************** 
+     * Query execution
+     **************************************************************************/ 
+
     // trigger a query asynchroneously
     proxy_url : '/manifold/proxy/json/',
 
     asynchroneous_debug : true,
 
+    /**
+     * \brief We use js function closure to be able to pass the query (array)
+     * to the callback function used when data is received
+     */
+    success_closure: function(query, publish_uuid, callback /*domid*/)
+    {
+        return function(data, textStatus) {
+            manifold.asynchroneous_success(data, query, publish_uuid, callback /*domid*/);
+        }
+    },
+
+    run_query: function(query, callback)
+    {
+        // default value for callback = null
+        if (typeof callback === 'undefined')
+            callback = null; 
+
+        var query_json = JSON.stringify(query);
+
+        /* Nothing related to pubsub here... for the moment at least. */
+        //query.iter_subqueries(function (sq) {
+        //    manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
+        //});
+
+        $.post(manifold.proxy_url, {'json': query_json} , manifold.success_closure(query, null, callback /*domid*/));
+    },
+
     // Executes all async. queries
     // input queries are specified as a list of {'query_uuid': <query_uuid>, 'id': <possibly null>}
     asynchroneous_exec : function (query_publish_dom_tuples) {
-       // start spinners
-
-       // in case the spin stuff was not loaded, let's make sure we proceed to the exit 
-       try {
-           if (manifold.asynchroneous_debug) 
-               messages.debug("Turning on spin with " + jQuery(".need-spin").length + " matches for .need-spin");
-           jQuery('.need-spin').spin(spin_presets);
-       } catch (err) { messages.debug("Cannot turn on spins " + err); }
-       
-       // We use js function closure to be able to pass the query (array) to the
-       // callback function used when data is received
-       var success_closure = function(query, publish_uuid, domid) {
-           return function(data, textStatus) {manifold.asynchroneous_success(data, query, publish_uuid, domid);}};
-       
-       // Loop through input array, and use publish_uuid to publish back results
-       jQuery.each(query_publish_dom_tuples, function(index, tuple) {
-           var query=manifold.find_query(tuple.query_uuid);
-           var query_json=JSON.stringify (query);
-           var publish_uuid=tuple.publish_uuid;
-           // by default we publish using the same uuid of course
-           if (publish_uuid==undefined) publish_uuid=query.query_uuid;
-           if (manifold.asynchroneous_debug) {
-               messages.debug("sending POST on " + manifold.proxy_url + " to be published on " + publish_uuid);
-               messages.debug("... ctd... with actual query= " + query.__repr());
-           }
-           // not quite sure what happens if we send a string directly, as POST data is named..
-           // this gets reconstructed on the proxy side with ManifoldQuery.fill_from_POST
-            jQuery.post(manifold.proxy_url, {'json':query_json} , success_closure(query, publish_uuid, tuple.domid));
-       })
-           },
+        // start spinners
 
-    // if set domid allows the result to be directed to just one plugin
-    // most of the time publish_uuid will be query.query_uuid
-    // however in some cases we wish to publish the results under a different uuid
-    // e.g. an updater wants to publish its results as if from the original (get) query
-    asynchroneous_success : function (data, query, publish_uuid, domid) {
-       // xxx should have a nicer declaration of that enum in sync with the python code somehow
-       if (data.code == 1) {
-           alert("Your session has expired, please log in again");
-           window.location="/logout/";
-           return;
-       } else if (data.code != 0) {
-           messages.error("Error received from manifold backend at " + MANIFOLD_URL + " [" + data.output + "]");
-           // publish error code and text message on a separate channel for whoever is interested
-           jQuery.publish("/results/" + publish_uuid + "/failed", [data.code, data.output] );
-           return;
-       }
-       // once everything is checked we can use the 'value' part of the manifoldresult
-       var value=data.value;
-       if (value) {
-            if (!!domid) {
-               /* Directly inform the requestor */
-               if (manifold.asynchroneous_debug) messages.debug("directing results to " + domid);
-               jQuery('#' + domid).trigger('results', [value]);
-            } else {
-               /* Publish an update announce */
-               var channel="/results/" + publish_uuid + "/changed";
-               if (manifold.asynchroneous_debug) messages.debug("publishing results on " + channel);
-               jQuery.publish(channel, [value, query]);
+        // in case the spin stuff was not loaded, let's make sure we proceed to the exit 
+        //try {
+        //    if (manifold.asynchroneous_debug) 
+        //   messages.debug("Turning on spin with " + jQuery(".need-spin").length + " matches for .need-spin");
+        //    jQuery('.need-spin').spin(manifold.spin_presets);
+        //} catch (err) { messages.debug("Cannot turn on spins " + err); }
+        
+        // Loop through input array, and use publish_uuid to publish back results
+        jQuery.each(query_publish_dom_tuples, function(index, tuple) {
+            var query=manifold.find_query(tuple.query_uuid);
+            var query_json=JSON.stringify (query);
+            var publish_uuid=tuple.publish_uuid;
+            // by default we publish using the same uuid of course
+            if (publish_uuid==undefined) publish_uuid=query.query_uuid;
+            if (manifold.asynchroneous_debug) {
+                messages.debug("sending POST on " + manifold.proxy_url + " to be published on " + publish_uuid);
+                messages.debug("... ctd... with actual query= " + query.__repr());
             }
 
-       }
+            query.iter_subqueries(function (sq) {
+                manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
+            });
+
+            // not quite sure what happens if we send a string directly, as POST data is named..
+            // this gets reconstructed on the proxy side with ManifoldQuery.fill_from_POST
+                jQuery.post(manifold.proxy_url, {'json':query_json} , manifold.success_closure(query, publish_uuid, tuple.callback /*domid*/));
+        })
     },
 
-}; // manifold object
-/* ------------------------------------------------------------ */
+    /**
+     * \brief Forward a query to the manifold backend
+     * \param query (dict) the query to be executed asynchronously
+     * \param callback (function) the function to be called when the query terminates
+     * Deprecated:
+     * \param domid (string) the domid to be notified about the results (null for using the pub/sub system
+     */
+    forward: function(query, callback /*domid*/) {
+        var query_json = JSON.stringify(query);
+        $.post(manifold.proxy_url, {'json': query_json} , manifold.success_closure(query, query.query_uuid, callback/*domid*/));
+    },
 
-// extend jQuery/$ with pubsub capabilities
-/* https://gist.github.com/661855 */
-(function($) {
+    /*!
+     * Returns whether a query expects a unique results.
+     * This is the case when the filters contain a key of the object
+     * \fn query_expects_unique_result(query)
+     * \memberof Manifold
+     * \param ManifoldQuery query Query for which we are testing whether it expects a unique result
+     */
+    query_expects_unique_result: function(query) {
+        /* XXX we need functions to query metadata */
+        //var keys = MANIFOLD_METADATA[query.object]['keys']; /* array of array of field names */
+        /* TODO requires keys in metadata */
+        return true;
+    },
 
-  var o = $({});
-
-  $.subscribe = function( channel, selector, data, fn) {
-    /* borrowed from jQuery */
-    if ( data == null && fn == null ) {
-        // ( channel, fn )
-        fn = selector;
-        data = selector = undefined;
-    } else if ( fn == null ) {
-        if ( typeof selector === "string" ) {
-            // ( channel, selector, fn )
-            fn = data;
-            data = undefined;
-        } else {
-            // ( channel, data, fn )
-            fn = data;
-            data = selector;
-            selector = undefined;
+    /*!
+     * Publish result
+     * \fn publish_result(query, results)
+     * \memberof Manifold
+     * \param ManifoldQuery query Query which has received results
+     * \param array results results corresponding to query
+     */
+    publish_result: function(query, result) {
+        if (typeof result === 'undefined')
+            result = [];
+
+        // NEW PLUGIN API
+        manifold.raise_record_event(query.query_uuid, CLEAR_RECORDS);
+        $.each(result, function(i, record) {
+            manifold.raise_record_event(query.query_uuid, NEW_RECORD, record);
+        });
+        manifold.raise_record_event(query.query_uuid, DONE);
+
+        // OLD PLUGIN API BELOW
+        /* Publish an update announce */
+        var channel="/results/" + query.query_uuid + "/changed";
+        if (manifold.asynchroneous_debug)
+            messages.debug("publishing result on " + channel);
+        jQuery.publish(channel, [result, query]);
+    },
+
+    /*!
+     * Recursively publish result
+     * \fn publish_result_rec(query, result)
+     * \memberof Manifold
+     * \param ManifoldQuery query Query which has received result
+     * \param array result result corresponding to query
+     */
+    publish_result_rec: function(query, result) {
+        /* If the result is not unique, only publish the top query;
+         * otherwise, publish the main object as well as subqueries
+         * XXX how much recursive are we ?
+         */
+        if (manifold.query_expects_unique_result(query)) {
+            /* Also publish subqueries */
+            jQuery.each(query.subqueries, function(object, subquery) {
+                manifold.publish_result_rec(subquery, result[0][object]);
+                /* TODO remove object from result */
+            });
         }
-    }
-    /* </ugly> */
+        manifold.publish_result(query, result);
+    },
+
+    setup_update_query: function(query, records)
+    {
+        // We don't prepare an update query if the result has more than 1 entry
+        if (records.length != 1)
+            return;
+        var query_ext = manifold.query_store.find_query_ext(query.query_uuid);
+
+        var record = records[0];
+
+        var update_query_ext = query_ext.update_query_ext;
+        var update_query = update_query_ext.query;
+        var update_query_ext = query_ext.update_query_ext;
+        var update_query_orig = query_ext.update_query_orig_ext.query;
+
+        // Testing whether the result has subqueries (one level deep only)
+        // iif the query has subqueries
+        var count = 0;
+        var obj = query.analyzed_query.subqueries;
+        for (method in obj) {
+            if (obj.hasOwnProperty(method)) {
+                var key = manifold.metadata.get_key(method);
+                if (!key)
+                    continue;
+                if (key.length > 1)
+                    continue;
+                key = key[0];
+                var sq_keys = [];
+                var subrecords = record[method];
+                if (!subrecords)
+                    continue
+                $.each(subrecords, function (i, subrecord) {
+                    sq_keys.push(subrecord[key]);
+                });
+                update_query.params[method] = sq_keys;
+                update_query_orig.params[method] = sq_keys.slice();
+                count++;
+            }
+        }
+
+        if (count > 0) {
+            update_query_ext.disabled = false;
+            update_query_orig_ext.disabled = false;
+        }
+    },
+
+    process_get_query_records: function(query, records)
+    {
+        this.setup_update_query(query, records);
 
-    /* We use an indirection function that will clone the object passed in
-     * parameter to the subscribe callback 
+        /* Publish full results */
+        tmp_query = manifold.find_query(query.query_uuid);
+        manifold.publish_result_rec(tmp_query.analyzed_query, records);
+    },
+
+    /**
      * 
-     * FIXME currently we only clone query objects which are the only ones
-     * supported and editable, we might have the same issue with results but
-     * the page load time will be severely affected...
+     * What we need to do when receiving results from an update query:
+     * - differences between what we had, what we requested, and what we obtained
+     *    . what we had : update_query_orig (simple fields and set fields managed differently)
+     *    . what we requested : update_query
+     *    . what we received : records
+     * - raise appropriate events
+     *
+     * The normal process is that results similar to Get will be pushed in the
+     * pubsub mechanism, thus repopulating everything while we only need
+     * diff's. This means we need to move the publish functionalities in the
+     * previous 'process_get_query_records' function.
      */
-    o.on.apply(o, [channel, selector, data, function() { 
-        for(i = 1; i < arguments.length; i++) {
-            if ( arguments[i].constructor.name == 'ManifoldQuery' )
-                arguments[i] = arguments[i].clone();
+    process_update_query_records: function(query, records)
+    {
+        // First issue: we request everything, and not only what we modify, so will will have to ignore some fields
+        var query_uuid        = query.query_uuid;
+        var query_ext         = manifold.query_store.find_analyzed_query_ext(query_uuid);
+        var update_query      = query_ext.main_query_ext.update_query_ext.query;
+        var update_query_orig = query_ext.main_query_ext.update_query_orig_ext.query;
+        
+        // Since we update objects one at a time, we can get the first record
+        var record = records[0];
+
+        // Let's iterate over the object properties
+        for (var field in record) {
+            switch (this.get_type(record[field])) {
+                case TYPE_VALUE:
+                    // Did we ask for a change ?
+                    var update_value = update_query[field];
+                    if (!update_value)
+                        // Not requested, if it has changed: OUT OF SYNC
+                        // How we can know ?
+                        // We assume it won't have changed
+                        continue;
+
+                    var result_value = record[field];
+                    if (!result_value)
+                        throw "Internal error";
+
+                    data = {
+                        request: FIELD_REQUEST_CHANGE,
+                        key   : field,
+                        value : update_value,
+                        status: (update_value == result_value) ? FIELD_REQUEST_SUCCESS : FIELD_REQUEST_FAILURE,
+                    }
+                    manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
+
+                    break;
+                case TYPE_RECORD:
+                    throw "Not implemented";
+                    break;
+
+                case TYPE_LIST_OF_VALUES:
+                    // Same as list of records, but we don't have to extract keys
+                    var result_keys  = record[field]
+                    
+                    // The rest of exactly the same (XXX factorize)
+                    var update_keys  = update_query_orig.params[field];
+                    var query_keys   = update_query.params[field];
+                    var added_keys   = $.grep(query_keys, function (x) { return $.inArray(x, update_keys) == -1 });
+                    var removed_keys = $.grep(update_keys, function (x) { return $.inArray(x, query_keys) == -1 });
+
+
+                    $.each(added_keys, function(i, key) {
+                        if ($.inArray(key, result_keys) == -1) {
+                            data = {
+                                request: FIELD_REQUEST_ADD,
+                                key   : field,
+                                value : key,
+                                status: FIELD_REQUEST_FAILURE,
+                            }
+                        } else {
+                            data = {
+                                request: FIELD_REQUEST_ADD,
+                                key   : field,
+                                value : key,
+                                status: FIELD_REQUEST_SUCCESS,
+                            }
+                        }
+                        manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
+                    });
+                    $.each(removed_keys, function(i, key) {
+                        if ($.inArray(key, result_keys) == -1) {
+                            data = {
+                                request: FIELD_REQUEST_REMOVE,
+                                key   : field,
+                                value : key,
+                                status: FIELD_REQUEST_SUCCESS,
+                            }
+                        } else {
+                            data = {
+                                request: FIELD_REQUEST_REMOVE,
+                                key   : field,
+                                value : key,
+                                status: FIELD_REQUEST_FAILURE,
+                            }
+                        }
+                        manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
+                    });
+
+
+                    break;
+                case TYPE_LIST_OF_RECORDS:
+                    // example: slice.resource
+                    //  - update_query_orig.params.resource = resources in slice before update
+                    //  - update_query.params.resource = resource requested in slice
+                    //  - keys from field = resources obtained
+                    var key = manifold.metadata.get_key(field);
+                    if (!key)
+                        continue;
+                    if (key.length > 1) {
+                        throw "Not implemented";
+                        continue;
+                    }
+                    key = key[0];
+
+                    /* XXX should be modified for multiple keys */
+                    var result_keys  = $.map(record[field], function(x) { return x[key]; });
+
+                    var update_keys  = update_query_orig.params[field];
+                    var query_keys   = update_query.params[field];
+                    var added_keys   = $.grep(query_keys, function (x) { return $.inArray(x, update_keys) == -1 });
+                    var removed_keys = $.grep(update_keys, function (x) { return $.inArray(x, query_keys) == -1 });
+
+
+                    $.each(added_keys, function(i, key) {
+                        if ($.inArray(key, result_keys) == -1) {
+                            data = {
+                                request: FIELD_REQUEST_ADD,
+                                key   : field,
+                                value : key,
+                                status: FIELD_REQUEST_FAILURE,
+                            }
+                        } else {
+                            data = {
+                                request: FIELD_REQUEST_ADD,
+                                key   : field,
+                                value : key,
+                                status: FIELD_REQUEST_SUCCESS,
+                            }
+                        }
+                        manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
+                    });
+                    $.each(removed_keys, function(i, key) {
+                        if ($.inArray(key, result_keys) == -1) {
+                            data = {
+                                request: FIELD_REQUEST_REMOVE,
+                                key   : field,
+                                value : key,
+                                status: FIELD_REQUEST_SUCCESS,
+                            }
+                        } else {
+                            data = {
+                                request: FIELD_REQUEST_REMOVE,
+                                key   : field,
+                                value : key,
+                                status: FIELD_REQUEST_FAILURE,
+                            }
+                        }
+                        manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
+                    });
+
+
+                    break;
+            }
+        }
+        
+        // XXX Now we need to adapt 'update' and 'update_orig' queries as if we had done a get
+        this.setup_update_query(query, records);
+    },
+
+    process_query_records: function(query, records)
+    {
+        if (query.action == 'get') {
+            this.process_get_query_records(query, records);
+        } else if (query.action == 'update') {
+            this.process_update_query_records(query, records);
+        }
+    },
+
+    // if set domid allows the result to be directed to just one plugin
+    // most of the time publish_uuid will be query.query_uuid
+    // however in some cases we wish to publish the result under a different uuid
+    // e.g. an updater wants to publish its result as if from the original (get) query
+    asynchroneous_success : function (data, query, publish_uuid, callback /*domid*/) {
+        // xxx should have a nicer declaration of that enum in sync with the python code somehow
+
+        /* If a callback has been specified, we redirect results to it */
+        if (!!callback) { callback(data); return; }
+
+        if (data.code == 2) { // ERROR
+            // We need to make sense of error codes here
+            alert("Your session has expired, please log in again");
+            window.location="/logout/";
+            return;
+        }
+        if (data.code == 1) { // WARNING
+            messages.error("Some errors have been received from the manifold backend at " + MANIFOLD_URL + " [" + data.description + "]");
+            // publish error code and text message on a separate channel for whoever is interested
+            if (publish_uuid)
+                $.publish("/results/" + publish_uuid + "/failed", [data.code, data.description] );
+
+            $("#notifications").notify("create", "sticky", {
+              title: 'Warning',
+              text: data.description
+            },{
+              expires: false,
+              speed: 1000
+            });
+            
         }
-        fn.apply(o, arguments);
-    }]);
-  };
+        // once everything is checked we can use the 'value' part of the manifoldresult
+        var result=data.value;
+        if (result) {
+            /* Eventually update the content of related queries (update, etc) */
+            this.process_query_records(query, result);
 
-  $.unsubscribe = function() {
-    o.off.apply(o, arguments);
-  };
+            /* Publish results: disabled here, done in the previous call */
+            //tmp_query = manifold.find_query(query.query_uuid);
+            //manifold.publish_result_rec(tmp_query.analyzed_query, result);
+        }
+    },
+
+    /************************************************************************** 
+     * Plugin API helpers
+     **************************************************************************/ 
+
+    raise_event_handler: function(type, query_uuid, event_type, value)
+    {
+        if ((type != 'query') && (type != 'record'))
+            throw 'Incorrect type for manifold.raise_event()';
+
+        var channels = [ manifold.get_channel(type, query_uuid), manifold.get_channel(type, '*') ];
+
+        $.each(channels, function(i, channel) {
+            if (value === undefined)
+                $('.plugin').trigger(channel, [event_type]);
+            else
+                $('.plugin').trigger(channel, [event_type, value]);
+        });
+    },
+
+    raise_query_event: function(query_uuid, event_type, value)
+    {
+        manifold.raise_event_handler('query', query_uuid, event_type, value);
+    },
+
+    raise_record_event: function(query_uuid, event_type, value)
+    {
+        manifold.raise_event_handler('record', query_uuid, event_type, value);
+    },
+
+
+    raise_event: function(query_uuid, event_type, value)
+    {
+        // Query uuid has been updated with the key of a new element
+        query_ext    = manifold.query_store.find_analyzed_query_ext(query_uuid);
+        query = query_ext.query;
+
+        switch(event_type) {
+            case FIELD_STATE_CHANGED:
+                // value is an object (request, key, value, status)
+                // update is only possible is the query is not pending, etc
+                // SET_ADD is on a subquery, FIELD_STATE_CHANGED on the query itself
+                // we should map SET_ADD on this...
+
+                // 1. Update internal query store about the change in status
+
+                // 2. Update the update query
+                update_query      = query_ext.main_query_ext.update_query_ext.query;
+                update_query_orig = query_ext.main_query_ext.update_query_orig_ext.query;
+
+                switch(value.request) {
+                    case FIELD_REQUEST_CHANGE:
+                        update_query.params[value.key] = value.value;
+                        break;
+                    case FIELD_REQUEST_ADD:
+                        if ($.inArray(value.value, update_query_orig.params[value.key]) != -1)
+                            value.request = FIELD_REQUEST_ADD_RESET;
+                        update_query.params[value.key].push(value.value);
+                        break;
+                    case FIELD_REQUEST_REMOVE:
+                        if ($.inArray(value.value, update_query_orig.params[value.key]) == -1)
+                            value.request = FIELD_REQUEST_REMOVE_RESET;
+
+                        var arr = update_query.params[value.key];
+                        arr = $.grep(arr, function(x) { return x != value.value; });
+                        update_query.params[value.key] = arr;
+
+                        break;
+                    case FIELD_REQUEST_ADD_RESET:
+                    case FIELD_REQUEST_REMOVE_RESET:
+                        // XXX We would need to keep track of the original query
+                        throw "Not implemented";
+                        break;
+                }
+
+                // 3. Inform others about the change
+                // a) the main query...
+                manifold.raise_record_event(query_uuid, event_type, value);
+
+                // b) subqueries eventually (dot in the key)
+                // Let's unfold 
+                var path_array = value.key.split('.');
+                var value_key = value.key.split('.');
+
+                var cur_query = query;
+                if (cur_query.analyzed_query)
+                    cur_query = cur_query.analyzed_query;
+                $.each(path_array, function(i, method) {
+                    cur_query = cur_query.subqueries[method];
+                    value_key.shift(); // XXX check that method is indeed shifted
+                });
+                value.key = value_key;
+
+                manifold.raise_record_event(cur_query.query_uuid, event_type, value);
+
+                // XXX make this DOT a global variable... could be '/'
+                break;
 
-  $.publish = function() {
-    o.trigger.apply(o, arguments);
-  };
+            case SET_ADD:
+            case SET_REMOVED:
+    
+                // update is only possible is the query is not pending, etc
+                // CHECK status !
+
+                // XXX we can only update subqueries of the main query. Check !
+                // assert query_ext.parent_query == query_ext.main_query
+                // old // update_query = query_ext.main_query_ext.update_query_ext.query;
+
+                // This SET_ADD is called on a subquery, so we have to
+                // recontruct the path of the key in the main_query
+                // We then call FIELD_STATE_CHANGED which is the equivalent for the main query
+
+                var path = "";
+                var sq = query_ext;
+                while (sq.parent_query_ext) {
+                    if (path != "")
+                        path = '.' + path;
+                    path = sq.query.object + path;
+                    sq = sq.parent_query_ext;
+                }
+
+                main_query = query_ext.main_query_ext.query;
+                data = {
+                    request: (event_type == SET_ADD) ? FIELD_REQUEST_ADD : FIELD_REQUEST_REMOVE,
+                    key   : path,
+                    value : value,
+                    status: FIELD_REQUEST_PENDING,
+                };
+                this.raise_event(main_query.query_uuid, FIELD_STATE_CHANGED, data);
+
+                // old //update_query.params[path].push(value);
+                // old // console.log('Updated query params', update_query);
+                // NOTE: update might modify the fields in Get
+                // NOTE : we have to modify all child queries
+                // NOTE : parts of a query might not be started (eg slice.measurements, how to handle ?)
+
+                // if everything is done right, update_query should not be null. It is updated when we received results from the get query
+                // object = the same as get
+                // filter = key : update a single object for now
+                // fields = the same as get
+                manifold.raise_query_event(query_uuid, event_type, value);
+
+                break;
+
+            case RUN_UPDATE:
+                manifold.run_query(query_ext.main_query_ext.update_query_ext.query);
+                break;
+
+            case FILTER_ADDED:
+                manifold.raise_query_event(query_uuid, event_type, value);
+                break;
+            case FILTER_REMOVED:
+                manifold.raise_query_event(query_uuid, event_type, value);
+                break;
+            case FIELD_ADDED:
+                main_query = query_ext.main_query_ext.query;
+                main_update_query = query_ext.main_query_ext.update_query;
+                query.select(value);
+
+                // Here we need the full path through all subqueries
+                path = ""
+                // XXX We might need the query name in the QueryExt structure
+                main_query.select(value);
+
+                // XXX When is an update query associated ?
+                // XXX main_update_query.select(value);
+
+                manifold.raise_query_event(query_uuid, event_type, value);
+                break;
+
+            case FIELD_REMOVED:
+                query = query_ext.query;
+                main_query = query_ext.main_query_ext.query;
+                main_update_query = query_ext.main_query_ext.update_query;
+                query.unselect(value);
+                main_query.unselect(value);
+
+                // We need to inform about changes in these queries to the respective plugins
+                // Note: query & main_query have the same UUID
+                manifold.raise_query_event(query_uuid, event_type, value);
+                break;
+        }
+        // We need to inform about changes in these queries to the respective plugins
+        // Note: query, main_query & update_query have the same UUID
+        manifold.raise_query_event(query_uuid, event_type, value);
+        // We are targeting the same object with get and update
+        // The notion of query is bad, we should have a notion of destination, and issue queries on the destination
+        // NOTE: Editing a subquery == editing a local view on the destination
+
+        // XXX We might need to run the new query again and manage the plugins in the meantime with spinners...
+        // For the time being, we will collect all columns during the first query
+    },
+
+    /* Publish/subscribe channels for internal use */
+    get_channel: function(type, query_uuid) 
+    {
+        if ((type !== 'query') && (type != 'record'))
+            return null;
+        return '/' + type + '/' + query_uuid;
+    },
+
+}; // manifold object
+/* ------------------------------------------------------------ */
+
+(function($) {
 
+    // OLD PLUGIN API: extend jQuery/$ with pubsub capabilities
+    // https://gist.github.com/661855
+    var o = $({});
+    $.subscribe = function( channel, selector, data, fn) {
+      /* borrowed from jQuery */
+      if ( data == null && fn == null ) {
+          // ( channel, fn )
+          fn = selector;
+          data = selector = undefined;
+      } else if ( fn == null ) {
+          if ( typeof selector === "string" ) {
+              // ( channel, selector, fn )
+              fn = data;
+              data = undefined;
+          } else {
+              // ( channel, data, fn )
+              fn = data;
+              data = selector;
+              selector = undefined;
+          }
+      }
+      /* </ugly> */
+  
+      /* We use an indirection function that will clone the object passed in
+       * parameter to the subscribe callback 
+       * 
+       * FIXME currently we only clone query objects which are the only ones
+       * supported and editable, we might have the same issue with results but
+       * the page load time will be severely affected...
+       */
+      o.on.apply(o, [channel, selector, data, function() { 
+          for(i = 1; i < arguments.length; i++) {
+              if ( arguments[i].constructor.name == 'ManifoldQuery' )
+                  arguments[i] = arguments[i].clone();
+          }
+          fn.apply(o, arguments);
+      }]);
+    };
+  
+    $.unsubscribe = function() {
+      o.off.apply(o, arguments);
+    };
+  
+    $.publish = function() {
+      o.trigger.apply(o, arguments);
+    };
+  
 }(jQuery));
 
 /* ------------------------------------------------------------ */
index eefdcbf..28e6c12 100644 (file)
@@ -3,11 +3,11 @@ var metadata = {
     get : function () {
        return MANIFOLD_METADATA;
     },
-    // returns all fields of a given subject
-    fields : function (subject) {
+    // returns all fields of a given object
+    fields : function (object) {
        var result=new Array();
        jQuery.each(MANIFOLD_METADATA, function(s,obj){
-            if(s==subject){
+            if(s==object){
                jQuery.each(obj['column'], function(i,f){
                     result.push(f);
                });
@@ -19,10 +19,10 @@ var metadata = {
        return result;
     },
     // returns all properties of a given field
-    field : function (subject, field) {
+    field : function (object, field) {
        var result=new Array();
        jQuery.each(MANIFOLD_METADATA, function(s,obj){
-            if(s==subject){
+            if(s==object){
                jQuery.each(obj['column'], function(i,f){
                     if(f['column']==field){
                        result.push(f);
@@ -34,11 +34,11 @@ var metadata = {
        });
        return result[0];
     },
-    // returns the value of a property from a field within a subject (type of object : resource,node,lease,slice...)
-    property : function (subject, field, property) {
+    // returns the value of a property from a field within a object (type of object : resource,node,lease,slice...)
+    property : function (object, field, property) {
        var result=null;
        jQuery.each(MANIFOLD_METADATA, function(s,obj){
-            if(s==subject){
+            if(s==object){
                jQuery.each(obj['column'], function(i,f){
                     if(f['column']==field){
                        result=f[property];
diff --git a/manifold/js/plugin-sample.html b/manifold/js/plugin-sample.html
new file mode 100644 (file)
index 0000000..975270f
--- /dev/null
@@ -0,0 +1,103 @@
+<!doctype html>
+<html>
+<head>
+       <meta charset="utf-8">
+       <title>Extensible jQuery</title>
+       
+       <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
+       <script type="text/javascript" src="simple-inheritance.js"></script>
+       <script type="text/javascript">
+       $.plugin = function(name, object) {
+               $.fn[name] = function(options) {
+                       var args = Array.prototype.slice.call(arguments, 1);
+                       return this.each(function() {
+                               var instance = $.data(this, name);
+                               if (instance) {
+                                       instance[options].apply(instance, args);
+                               } else {
+                                       instance = $.data(this, name, new object(options, this));
+                               }
+                       });
+               };
+       };
+       
+       var Stepper = Class.extend({
+               init: function(options, element) {
+                       this.options = $.extend({
+                               value: 0,
+                               stepSize: 1
+                       }, options);
+                       this.element = $(element);
+                       this.display();
+               },
+               stepUp: function(steps) {
+                       this.options.value += this.options.stepSize * steps;
+                       this.display();
+               },
+               stepDown: function(steps) {
+                       this.options.value -= this.options.stepSize * steps;
+                       this.display();
+               },
+               value: function() {
+                       return this.options.value;
+               },
+               display: function() {
+                       this.element.html(this.options.value);
+               }
+       });
+       
+       var Pager = Stepper.extend({
+               init: function(options, element) {
+                       this._super(options, element);
+                       this.options.pageSize = this.options.pageSize || 10;
+               },
+               pageUp: function() {
+                       this.options.value += this.options.pageSize * this.options.stepSize;
+                       this.display();
+               },
+               pageDown: function() {
+                       this.options.value -= this.options.pageSize * this.options.stepSize;
+                       this.display();
+               }
+       });
+       
+       $.plugin('stepper', Stepper);
+       $.plugin('pager', Pager);
+       
+       $(document).ready(function() {
+               
+               // instantiate and use a stepper via jQuery
+               $('#stepper').stepper({ value: 5 });
+               var stepper = $('#stepper').data('stepper');
+               
+               console.log(stepper.value());
+               
+               $('#stepper').stepper('stepUp', 3);
+               console.log(stepper.value());
+               
+               
+               // instantiate and use a pager via jQuery
+               $('#pager').pager({ value: 30 });
+               var pager = $('#pager').data('pager');
+               
+               console.log(pager.value());
+               
+               $('#pager').pager('stepUp', 3);
+               console.log(pager.value());
+               
+               $('#pager').pager('pageUp');
+               console.log(pager.value());
+               
+               
+               // instantiate and use a stepper directly
+               var stepper2 = new Stepper({ value: 20 }, '#stepper2');
+               
+               console.log(stepper2.value());
+               
+               stepper2.stepDown(2);
+               console.log(stepper2.value());
+               
+               
+               // modify stepper
+               Function.prototype.partial = function() {
+                       var fn = this,
diff --git a/manifold/js/plugin.js b/manifold/js/plugin.js
new file mode 100644 (file)
index 0000000..dd12379
--- /dev/null
@@ -0,0 +1,264 @@
+// INHERITANCE
+// http://alexsexton.com/blog/2010/02/using-inheritance-patterns-to-organize-large-jquery-applications/
+// We will use John Resig's proposal
+
+// http://pastie.org/517177
+
+// NOTE: missing a destroy function
+
+$.plugin = function(name, object) {
+    $.fn[name] = function(options) {
+        var args = Array.prototype.slice.call(arguments, 1);
+        return this.each(function() {
+            var instance = $.data(this, name);
+            if (instance) {
+                instance[options].apply(instance, args);
+            } else {
+                instance = $.data(this, name, new object(options, this));
+            }
+        });
+    };
+};
+
+var Plugin = Class.extend({
+
+    init: function(options, element)
+    {
+        // Mix in the passed in options with the default options
+        this.options = $.extend({}, this.default_options, options);
+
+        // Save the element reference, both as a jQuery
+        // reference and a normal reference
+        this.element  = element;
+        this.$element = $(element);
+
+        // return this so we can chain/use the bridge with less code.
+        return this;
+    },
+
+    has_query_handler: function() {
+        return (typeof this.on_filter_added === 'function');
+    },
+
+    _query_handler: function(prefix, event_type, data)
+    {
+        // We suppose this.query_handler_prefix has been defined if this
+        // callback is triggered    
+        var fn;
+        switch(event_type) {
+            case FILTER_ADDED:
+                fn = 'filter_added';
+                break;
+            case FILTER_REMOVED:
+                fn = 'filter_removed';
+                break;
+            case CLEAR_FILTERS:
+                fn = 'filter_clear';
+                break;
+            case FIELD_ADDED:
+                fn = 'field_added';
+                break;
+            case FIELD_REMOVED:
+                fn = 'field_removed';
+                break;
+            case CLEAR_FIELDS:
+                fn = 'field_clear';
+                break;
+            default:
+                return;
+        } // switch
+        
+        fn = 'on_' + prefix + fn;
+        if (typeof this[fn] === 'function') {
+            // call with data as parameter
+            // XXX implement anti loop
+            this[fn](data);
+        }
+    },
+
+    _record_handler: function(prefix, event_type, record)
+    {
+        // We suppose this.query_handler_prefix has been defined if this
+        // callback is triggered    
+        var fn;
+        switch(event_type) {
+            case NEW_RECORD:
+                fn = 'new_record';
+                break;
+            case CLEAR_RECORDS:
+                fn = 'clear_records';
+                break;
+            case IN_PROGRESS:
+                fn = 'query_in_progress';
+                break;
+            case DONE:
+                fn = 'query_done';
+                break;
+            case FIELD_STATE_CHANGED:
+                fn = 'field_state_changed';
+                break;
+            default:
+                return;
+        } // switch
+        
+        fn = 'on_' + prefix + fn;
+        if (typeof this[fn] === 'function') {
+            // call with data as parameter
+            // XXX implement anti loop
+            this[fn](record);
+        }
+    },
+
+    get_handler_function: function(type, prefix)
+    {
+        
+        return $.proxy(function(e, event_type, record) {
+            return this['_' + type + '_handler'](prefix, event_type, record);
+        }, this);
+    },
+
+    listen_query: function(query_uuid, prefix)
+    {
+        // default: prefix = ''
+        prefix = (typeof prefix === 'undefined') ? '' : (prefix + '_');
+
+        this.$element.on(manifold.get_channel('query', query_uuid),  this.get_handler_function('query',  prefix));
+        this.$element.on(manifold.get_channel('record', query_uuid),  this.get_handler_function('record', prefix));
+    },
+
+    default_options: {},
+
+    /* Helper functions for naming HTML elements (ID, classes), with support for filters and fields */
+
+    id: function()
+    {
+        var ret = this.options.plugin_uuid;
+        for (var i = 0; i < arguments.length; i++) {
+            ret = ret + manifold.separator + arguments[i];
+        }
+        return ret;
+    },
+
+    el: function()
+    {
+        if (arguments.length == 0) {
+            return $('#' + this.id());
+        } else {
+            // We make sure to search _inside_ the dom tag of the plugin
+            return $('#' + this.id.apply(this, arguments), this.el());
+        }
+    },
+
+    els: function(cls)
+    {
+        return $('.' + cls, this.el());
+    },
+
+    id_from_filter: function(filter, use_value)
+    {
+        use_value = typeof use_value !== 'undefined' ? use_value : true;
+
+        var key    = filter[0];
+        var op     = filter[1];
+        var value  = filter[2];
+        var op_str = this.getOperatorLabel(op);
+        var s      = manifold.separator;
+
+        if (use_value) {
+            return 'filter' + s + key + s + op_str + s + value;
+        } else {
+            return 'filter' + s + key + s + op_str;
+        }
+    },
+
+    str_from_filter: function(filter)
+    {
+        return filter[0] + ' ' + filter[1] + ' ' + filter[2];
+    },
+
+    array_from_id: function(id)
+    {
+        var ret = id.split(manifold.separator);
+        ret.shift(); // remove plugin_uuid at the beginning
+        return ret;
+    },
+
+    id_from_field: function(field)
+    {
+        return 'field' + manifold.separator + field;
+    },
+
+    field_from_id: function(id)
+    {
+        var array;
+        if (typeof id === 'string') {
+            array = id.split(manifold.separator);
+        } else { // We suppose we have an array ('object')
+            array = id;
+        }
+        // array = ['field', FIELD_NAME]
+        return array[1];
+    },
+
+    id_from_key: function(key_field, value)
+    {
+        
+        return key_field + manifold.separator + unfold.escape_id(value).replace(/\\/g, '');
+    },
+
+    id_from_record: function(method, record)
+    {
+        var keys = manifold.metadata.get_key(method);
+        if (!keys)
+            return;
+        if (keys.length > 1)
+            return;
+
+        var key = keys[0];
+        switch (Object.toType(key)) {
+            case 'string':
+                if (!(key in record))
+                    return null;
+                return this.id_from_key(key, record[key]);
+    
+            default:
+                throw 'Not implemented';
+        }
+    },
+
+    key_from_id: function(id)
+    {
+        // NOTE this works only for simple keys
+
+        var array;
+        if (typeof id === 'string') {
+            array = id.split(manifold.separator);
+        } else { // We suppose we have an array ('object')
+            array = id;
+        }
+
+        // arguments has the initial id but lacks the key field name (see id_from_key), so we are even
+        // we finally add +1 for the plugin_uuid at the beginning
+        return array[arguments.length + 1];
+    },
+
+    /* SPIN */
+
+    spin: function()
+    {
+        manifold.spin(this.element);
+    },
+
+    unspin: function()
+    {
+        manifold.spin(this.element, false);
+    },
+
+    /* TEMPLATE */
+
+    load_template: function(name, ctx)
+    {
+        return Mustache.render(this.el(name).html(), ctx);
+    },
+
+});
index 504e182..8d4d1ac 100644 (file)
@@ -3,11 +3,19 @@ import xmlrpclib
 
 from myslice.config import Config
 
-from manifoldresult import ManifoldResult, ManifoldCode
+from django.contrib import messages
+from manifoldresult import ManifoldResult, ManifoldCode, ManifoldException
+from manifold.core.result_value import ResultValue
 
 debug=False
 debug=True
 
+def mytruncate (obj, l):
+    # we will add '..' 
+    l1=l-2
+    repr="%s"%obj
+    return (repr[:l1]+'..') if len(repr)>l1 else repr
+
 class ManifoldAPI:
 
     def __init__(self, auth=None, cainfo=None):
@@ -24,6 +32,18 @@ class ManifoldAPI:
 
     def __repr__ (self): return "ManifoldAPI[%s]"%self.url
 
+    # a one-liner to give a hint of what the return value looks like
+    def _print_result (self, result):
+        if not result:                        print "[no/empty result]"
+        elif isinstance (result,str):         print "result is '%s'"%result
+        elif isinstance (result,list):        print "result is a %d-elts list"%len(result)
+        elif isinstance (result,dict):        
+            print "result is a dict with %d keys : %s"%(len(result),result.keys())
+            for (k,v) in result.iteritems(): 
+                if v is None: continue
+                print '+++',k,':',mytruncate (v,60)
+        else:                                 print "[dont know how to display result] %s"%result
+
     # xxx temporary code for scaffolding a ManifolResult on top of an API that does not expose error info
     # as of march 2013 we work with an API that essentially either returns the value, or raises 
     # an xmlrpclib.Fault exception with always the same 8002 code
@@ -32,55 +52,45 @@ class ManifoldAPI:
     # a SESSION_EXPIRED code
     def __getattr__(self, methodName):
         def func(*args, **kwds):
-            if (debug): 
-                print "entering ManifoldAPI.%s"%methodName,
-                print "args",args,
-                print "kwds",kwds
             try:
+                if debug:
+                    print "====> ManifoldAPI.%s"%methodName,"auth",self.auth,"args",args,"kwds",kwds
                 result=getattr(self.server, methodName)(self.auth, *args, **kwds)
-                ### attempt to cope with old APIs and new APIs
-                if isinstance (result, dict) and 'code' in result:
-                    # this sounds like a result from a new API, leave it untouched
-                    pass
-                else:
-                    if debug:
-                        print '<=== backend call', methodName, args, kwds
-                        print '.... ctd', 'Authmethod=',self.auth['AuthMethod'], self.url,'->',
-                        if not result:                        print "[no/empty result]"
-                        elif isinstance (result,str):         print "result is '%s'"%result
-                        elif isinstance (result,list):        print "result is a %d-elts list"%len(result)
-                        else:                                 print "[dont know how to display result]"
-                    return ManifoldResult (code=ManifoldCode.SUCCESS, value=result)
-            except xmlrpclib.Fault, error:
-                ### xxx this is very rough for now
-                # until we have some agreement about how the API calls should return error conditions
-                # in some less unpolite way than this anonymous exception, we assume it's a problem with the session
-                # that needs to be refreshed
-                if error.faultCode == 8002:
-                    reason="most likely your session has expired"
-                    reason += " (the manifold API has no unambiguous error reporting mechanism yet)"
-                    return ManifoldResult (code=ManifoldCode.SESSION_EXPIRED, output=reason)
-                else:
-                    reason="xmlrpclib.Fault with faultCode = %s (not taken as session expired)"%error.faultCode
-                    return ManifoldResult (code=ManifoldCode.UNKNOWN_ERROR, output=reason)
+                if debug:
+                    print '<==== backend call %s(*%s,**%s) returned'%(methodName,args,kwds),
+                    print '.ctd. Authmethod=',self.auth['AuthMethod'], self.url,'->',
+                    self._print_result(result)
+                    print '===== ManifoldAPI call done'
+
+                return ResultValue(**result)
+
             except Exception,error:
-                print "ManifoldAPI: unexpected exception",error
-                return ManifoldResult (code=ManifoldCode.UNKNOWN_ERROR, output="%s"%error)
+                # XXX Connection refused for example
+                print "** API ERROR **"
+                import traceback
+                traceback.print_exc()
+                if debug: print "KO (unexpected exception)",error
+                raise ManifoldException ( ManifoldResult (code=ManifoldCode.UNKNOWN_ERROR, output="%s"%error) )
+
         return func
 
-    def send_manifold_query (self, query):
-        (action,subject)= (query.action,query.subject)
-        # use e.g. self.Get rather than self.server.Get so we use the __getattr__ code
-        if action=='get':
-# this makes the backend to squeak and one can't login anymore...
-#            return self.Get(subject, query.filters, query.timestamp, query.fields)
-            return self.Get(subject, query.filters, {}, query.fields)
-        elif action=='update':
-            answer=self.Update(subject, query.filters, query.params, query.fields)
-            if not isinstance (answer, ManifoldResult): print "UNEXECPECTED answer", answer
-            return answer
-        else:
-            warning="WARNING: ManifoldAPI.send_manifold_query: %s not implemented for now"%action
-            print warning
-            print 3
-            return ManifoldResult(code=ManifoldCode.NOT_IMPLEMENTED, output=warning)
+def execute_query(request, query):
+    if not 'manifold' in request.session or not 'auth' in request.session['manifold']:
+        print "W: Used hardcoded demo account for execute_query"
+        manifold_api_session_auth = {'AuthMethod': 'password', 'Username': 'demo', 'AuthString': 'demo'}
+    else:
+        manifold_api_session_auth = request.session['manifold']['auth']
+    manifold_api = ManifoldAPI(auth=manifold_api_session_auth)
+    print "-"*80
+    print query
+    print query.to_dict()
+    print "-"*80
+    result = manifold_api.forward(query.to_dict())
+    if result['code'] == 2:
+        raise Exception, 'Error running query: %r' % result
+
+    # XXX Handle errors
+    #Error running query: {'origin': [0, 'XMLRPCAPI'], 'code': 2, 'description': 'No such session: No row was found for one()', 'traceback': 'Traceback (most recent call last):\n  File "/usr/local/lib/python2.7/dist-packages/manifold/core/xmlrpc_api.py", line 68, in xmlrpc_forward\n    user = Auth(auth).check()\n  File "/usr/local/lib/python2.7/dist-packages/manifold/auth/__init__.py", line 245, in check\n    return self.auth_method.check()\n  File "/usr/local/lib/python2.7/dist-packages/manifold/auth/__init__.py", line 95, in check\n    raise AuthenticationFailure, "No such session: %s" % e\nAuthenticationFailure: No such session: No row was found for one()\n', 'type': 2, 'ts': None, 'value': None}
+
+
+    return result['value'] 
index 80e8066..720e564 100644 (file)
@@ -3,8 +3,11 @@ import json
 #from django.core import serializers
 from django.http import HttpResponse, HttpResponseForbidden
 
-from manifold.manifoldquery import ManifoldQuery
+#from manifold.manifoldquery import ManifoldQuery
+from manifold.core.query import Query
+from manifold.core.result_value import ResultValue
 from manifold.manifoldapi import ManifoldAPI
+from manifold.manifoldresult import ManifoldException
 
 debug=False
 debug=True
@@ -46,11 +49,19 @@ with the query passed using POST"""
     try:
         # translate incoming POST request into a query object
         if debug: print 'manifoldproxy.proxy: request.POST',request.POST
-        manifold_query = ManifoldQuery()
+        manifold_query = Query()
+        #manifold_query = ManifoldQuery()
         manifold_query.fill_from_POST(request.POST)
-        offline_filename="offline-%s-%s.json"%(manifold_query.action,manifold_query.subject)
+        offline_filename="offline-%s-%s.json"%(manifold_query.action,manifold_query.object)
         # retrieve session for request
-        manifold_api_session_auth = request.session['manifold']['auth']
+
+        # We allow some requests to use the ADMIN user account
+        if (manifold_query.get_from() == 'local:user' and manifold_query.get_action() == 'create') or (manifold_query.get_from() == 'local:platform' and manifold_query.get_action() == 'get'):
+            print "W: Used hardcoded demo account for admin queries"
+            manifold_api_session_auth = {'AuthMethod': 'password', 'Username': 'demo', 'AuthString': 'demo'}
+        else:
+            manifold_api_session_auth = request.session['manifold']['auth']
+
         if debug_empty and manifold_query.action.lower()=='get':
             json_answer=json.dumps({'code':0,'value':[]})
             print "By-passing : debug_empty & 'get' request : returning a fake empty list"
@@ -71,29 +82,33 @@ with the query passed using POST"""
                 
         # actually forward
         manifold_api= ManifoldAPI(auth=manifold_api_session_auth)
-        if debug: print 'manifoldproxy.proxy: sending to backend', manifold_query
-        answer=manifold_api.send_manifold_query (manifold_query)
-        if debug: 
-            print '<=== manifoldproxy.proxy: received from backend with code', answer['code']
-            if answer['code']==0:
-                print ".... ctd ",
-                value=answer['value']
-                if isinstance (value, list): print "result is a list with %d entries"%len(value)
-                elif isinstance (value, dict): print "result is a dict with keys %s"%value.keys()
-                else: print "result is other (type=%s) : %s"%(type(value),value)
-        json_answer=json.dumps(answer)
+        if debug: print '===> manifoldproxy.proxy: sending to backend', manifold_query
+        # for the benefit of the python code, manifoldAPI raises an exception if something is wrong
+        # however in this case we want to propagate the complete manifold result to the js world
+
+
+        result = manifold_api.forward(manifold_query.to_dict())
+
+        # XXX TEMP HACK
+        if 'description' in result and result['description'] and isinstance(result['description'], (tuple, list, set, frozenset)):
+            result [ 'description' ] = [ ResultValue.to_html (x) for x in result['description'] ]
+
+        json_answer=json.dumps(result)
         # if in debug mode we save this so we can use offline mode later
-        if (debug):
+        if debug:
             with (file(offline_filename,"w")) as f:
                 f.write(json_answer)
+
         # this is an artificial delay added for debugging purposes only
         if debug_spin>0:
             print "Adding additional artificial delay",debug_spin
             import time
             time.sleep(debug_spin)
+
         return HttpResponse (json_answer, mimetype="application/json")
 
     except:
+        print "** PROXY ERROR **"
         import traceback
         traceback.print_exc()
 
diff --git a/manifold/manifoldquery.py b/manifold/manifoldquery.py
deleted file mode 100644 (file)
index 91b6c0b..0000000
+++ /dev/null
@@ -1,162 +0,0 @@
-import json
-import uuid
-
-def uniqid (): 
-    return uuid.uuid4().hex
-
-debug=False
-debug=True
-
-class ManifoldQuery:
-
-    def __init__ (self, action=None, subject=None, timestamp='now',
-                  filters=[], params=[], fields=[],
-                  sort=None, limit=None, offset=None,
-                  ):
-        self.query_uuid=uniqid()
-        # settable
-        self.action=action
-        self.subject=subject
-        self.timestamp=timestamp
-        self.filters=filters
-        self.params=params
-        self.fields=fields
-        # xxx these are unused for now....
-        self.sort=sort
-        self.limit=limit
-        self.offset=offset
-        # internal data - likewise, this is unused as of yet, although we have
-        # (untested) code below in analyze_subqueries to compute these..
-        self.analyzed_query=None
-        self.subqueries = {}
-
-    def __repr__ (self):
-        result="[[Q: id=%(query_uuid)s - %(action)s on %(subject)s "%self.__dict__
-        result += " with %d filters, %d fields"%(len(self.filters),len(self.params))
-        result += "]]"
-        return result
-
-    def to_json (self):
-        query_uuid=self.query_uuid
-        a=self.action
-        s=self.subject
-        t=self.timestamp
-        f=json.dumps (self.filters)
-        p=json.dumps (self.params)
-        c=json.dumps (self.fields)
-        # xxx unique can be removed, but for now we pad the js structure
-        unique=0
-
-        aq = self.analyzed_query.to_json() if self.analyzed_query else 'null'
-        # subqueries is a dictionary subject:query
-        if not self.subqueries: 
-            sq="{}"
-        else:
-            sq=", ".join ( [ "'%s':%s" % (subject, subquery.to_json())
-                      for (subject, subquery) in self.subqueries.iteritems()])
-            sq="{%s}"%sq
-        
-        result= """ new ManifoldQuery('%(a)s', '%(s)s', '%(t)s', %(f)s, %(p)s, %(c)s, %(unique)s, '%(query_uuid)s', %(aq)s, %(sq)s)"""%locals()
-        if debug: print 'ManifoldQuery.to_json:',result
-        return result
-    
-    # this builds a ManifoldQuery object from a dict as received from javascript through its ajax request 
-    # we use a json-encoded string - see manifold.js for the sender part 
-    # e.g. here's what I captured from the server's output
-    # manifoldproxy.proxy: request.POST <QueryDict: {u'json': [u'{"action":"get","subject":"resource","timestamp":"latest","filters":[["slice_hrn","=","ple.inria.omftest"]],"params":[],"fields":["hrn","hostname"],"unique":0,"query_uuid":"436aae70a48141cc826f88e08fbd74b1","analyzed_query":null,"subqueries":{}}']}>
-    def fill_from_POST (self, POST_dict):
-        try:
-            json_string=POST_dict['json']
-            dict=json.loads(json_string)
-            for (k,v) in dict.iteritems(): 
-                setattr(self,k,v)
-        except:
-            print "Could not decode incoming ajax request as a Query, POST=",POST_dict
-            if (debug):
-                import traceback
-                traceback.print_exc()
-
-    # not used yet ..
-    def analyze_subqueries(self):
-        analyzed_query = ManifoldQuery()
-        analyzed_query.query_uuid = self.query_uuid
-        analyzed_query.action = self.action
-        analyzed_query.subject = self.subject
-        analyzed_query.timestamp = self.timestamp
-
-        # analyse query filters
-        # filter syntax : ['key', 'oparation', 'value']
-        for filter in self.filters:
-            key = filter[0]
-            operation = filter[1]
-            value = filter[2]
-            if '.' in key:
-                parts=key.split('.')
-                subject = parts[0]
-                field = parts[1]
-                if not analyzed_query.subqueries[subject]:
-                    subquery = ManifoldQuery()
-                    subquery.action = self.action
-                    subquery.subject = subject
-                    subquery.timestamp = self.timestamp
-                    analyzed_query.subqueries[subject] = subquery
-
-                analyzed_query.subqueries[subject].filters.append([field, operation, value])
-            else:
-                analyzed_query.filters.append(filter)
-
-        # analyse query params
-        # params syntax : params = {'param1': value1, 'param2': value2, ...}
-        for param in self.params.keys():
-            if '.' in param:
-                parts=param.split('.')
-                subject = parts[0]
-                field = parts[1]
-                if not analyzed_query.subqueries[subject]:
-                    subquery = ManifoldQuery()
-                    subquery.action = self.action
-                    subquery.subject = subject
-                    subquery.timestamp = self.timestamp
-                    analyzed_query.subqueries[subject] = subquery
-
-                analyzed_query.subqueries[subject].params[field] = self.params[param]
-            else:
-                analyzed_query.params[param] = self.params[param]
-
-        # analyse query fields
-        # fields syntax: fields = [element1, element2, ....]
-        for element in self.fields:
-            if '.' in element:
-                parts=element.split('.')
-                subject = parts[0]
-                field = parts[1]
-                if not analyzed_query.subqueries[subject]:
-                    subquery = ManifoldQuery()
-                    subquery.action = self.action
-                    subquery.subject = subject
-                    subquery.timestamp = self.timestamp
-                    analyzed_query.subqueries[subject] = subquery
-
-                analyzed_query.subqueries[subject].fields.append(field)
-            else:
-                analyzed_query.fields.append(element)        
-
-
-        # default subqueries 
-        if analyzed_query.subject == 'slice':
-            if not analyzed_query.subqueries['resource']:
-                subquery = ManifoldQuery()
-                subquery.action = self.action
-                subquery.subject = subject
-                subquery.timestamp = self.timestamp
-                analyzed_query.subqueries['resource'] = subquery
-
-            if not analyzed_query.subqueries['lease']:
-                subquery = ManifoldQuery()
-                subquery.action = self.action
-                subquery.subject = subject
-                subquery.timestamp = self.timestamp
-                analyzed_query.subqueries['lease'] = subquery
-
-
-        self.analyzed_query = analyzed_query
index 1c812f0..a20c5b0 100644 (file)
@@ -15,17 +15,23 @@ class ManifoldResult (dict):
         self['code']=code
         self['value']=value
         self['output']=output
+        self['description'] = '' # Jordan: needed by javascript code
 
     def from_json (self, json_string):
         d=json.dumps(json_string)
         for k in ['code','value','output']:
             self[k]=d[k]
 
+    # raw accessors
+    def code (self): return self['code']
+    def output (self): return self['output']
+
     # this returns None if there's a problem, the value otherwise
     def ok_value (self):
         if self['code']==ManifoldCode.SUCCESS:
             return self['value']
 
+    # both data in a single string
     def error (self):
         return "code=%s -- %s"%(self['code'],self['output'])
     
@@ -35,8 +41,17 @@ class ManifoldResult (dict):
         if self['code']==0:
             value=self['value']
             if isinstance(value,list): result += " [value=list with %d elts]"%len(value)
-            else: result += " [value=other %s]"%value
+            elif isinstance(value,dict): result += " [value=dict with keys %s]"%value.keys()
+            else: result += " [value=%s: %s]"%(type(value).__name__,value)
         else:
             result += " [output=%s]"%self['output']
         result += "]]"
         return result
+
+# probably simpler to use a single class and transport the whole result there
+# instead of a clumsy set of derived classes 
+class ManifoldException (Exception):
+    def __init__ (self, manifold_result):
+        self.manifold_result=manifold_result
+    def __repr__ (self):
+        return "Manifold Exception %s"%(self.manifold_result.error())
index 99af3d0..6f4c5ce 100644 (file)
@@ -14,41 +14,56 @@ class MetaData:
 
     def __init__ (self, auth):
         self.auth=auth
-        self.hash_by_subject={}
+        self.hash_by_object={}
 
     def fetch (self):
         offline_filename="offline-metadata.json"
         if work_offline:
             try:
                 with file(offline_metadata) as f:
-                    self.hash_by_subject=json.loads(f.read())
+                    self.hash_by_object=json.loads(f.read())
                 return
             except:
                 print "metadata.work_offline: failed to decode %s"%offline_filename
         manifold_api = ManifoldAPI(self.auth)
-        fields = ['table', 'column.column',
-                  'column.description','column.header', 'column.title',
-                  'column.unit', 'column.info_type',
-                  'column.resource_type', 'column.value_type',
-                  'column.allowed_values', 'column.platforms.platform',
-                  'column.platforms.platform_url']
-        rows_result = manifold_api.Get('metadata:table', [], [], fields)
-        rows = rows_result.ok_value()
-        if not rows:
-            print "Failed to retrieve metadata",rows_result.error()
-            rows=[]
-        self.hash_by_subject = dict ( [ (row['table'], row) for row in rows ] )
+        fields = ['table', 'column.name', 'column.qualifier', 'column.type', 'column.is_array', 'column.description', 'column.default', 'key', 'capability']
+        #fields = ['table', 'column.column',
+        #          'column.description','column.header', 'column.title',
+        #          'column.unit', 'column.info_type',
+        #          'column.resource_type', 'column.value_type',
+        #          'column.allowed_values', 'column.platforms.platform',
+        #          'column.platforms.platform_url']
+        result = manifold_api.Get({
+            'object': 'local:object', # proposed to replace metadata:table
+            'fields':     fields 
+        })
+
+        if result['code'] == 1: # warning
+            messages.warning(request, result['description'])
+        elif result['code'] == 2:
+            messages.error(request, result['description'])
+            # XXX FAIL HERE XXX
+
+        rows = result.ok_value()
+# API errors will be handled by the outer logic
+#        if not rows:
+#            print "Failed to retrieve metadata",rows_result.error()
+#            rows=[]
+        self.hash_by_object = dict ( [ (row['table'], row) for row in rows ] )
         # save for next time we use offline mode
-        if debug:
+        if debug and rows:
             with file(offline_filename,'w') as f:
-                f.write(json.dumps(self.hash_by_subject))
+                f.write(json.dumps(self.hash_by_object))
 
     def to_json(self):
-        return json.dumps(self.hash_by_subject)
+        return json.dumps(self.hash_by_object)
 
-    def details_by_subject (self, subject):
-        return self.hash_by_subject[subject]
+    def details_by_object (self, object):
+        return self.hash_by_object[object]
 
-    def sorted_fields_by_subject (self, subject):
-        return self.hash_by_subject[subject]['columns'].sort()
+    def sorted_fields_by_object (self, object):
+        return self.hash_by_object[object]['column'].sort()
 
+    def get_field_type(self, object, field):
+        print "Temp fix for metadata::get_field_type() -> consider moving to manifold.core.metadata soon"
+        return field
diff --git a/manifold/util/__init__.py b/manifold/util/__init__.py
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/manifold/util/clause.py b/manifold/util/clause.py
new file mode 100644 (file)
index 0000000..670a689
--- /dev/null
@@ -0,0 +1,103 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+#
+# Implements a clause
+# - a "tree" (more precisely a predecessor map, typically computed thanks to a DFS) 
+# - a set of needed fields (those queried by the user)
+#
+# Copyright (C) UPMC Paris Universitas
+# Authors:
+#   Jordan Augé       <jordan.auge@lip6.fr> 
+#   Marc-Olivier Buob <marc-olivier.buob@lip6.fr>
+
+import pyparsing as pp
+import operator, re
+
+from manifold.util.predicate import Predicate
+from types                 import StringTypes
+
+# XXX When to use Keyword vs. Regex vs. CaselessLiteral
+# XXX capitalization ?
+
+# Instead of CaselessLiteral, try using CaselessKeyword. Keywords are better
+# choice for grammar keywords, since they inherently avoid mistaking the leading
+# 'in' of 'inside' as the keyword 'in' in your grammar.
+
+
+class Clause(object):
+
+    def __new__(cls, *args, **kwargs):
+        if len(args) == 1 and isinstance(args[0], StringTypes):
+            return ClauseStringParser().parse(args[0])
+        return super(Clause, cls).__new__(cls, *args, **kwargs)
+
+    def __init__(self, *args, **kwargs):
+        if len(args) == 2:
+            # unary
+            self.operator = Predicate.operators[args[0]]
+            self.operands = [args[1]]
+        elif len(args) == 3:
+            self.operator = Predicate.operators[args[1]]
+            self.operands = [args[0], args[2]]
+        else:
+            raise Exception, "Clause can only be unary or binary"
+                
+    def opstr(self, operator):
+        ops = [string for string, op in Predicate.operators.items() if op == operator]
+        return ops[0] if ops else ''
+
+    def __repr__(self):
+        if len(self.operands) == 1:
+            return "%s(%s)" % (self.operator, self.operands[0])
+        else:
+            return "(%s %s %s)" % (self.operands[0], self.opstr(self.operator), self.operands[1])
+
+class ClauseStringParser(object):
+
+    def __init__(self):
+        """
+        BNF HERE
+        """
+
+        #integer = pp.Word(nums)
+        #floatNumber = pp.Regex(r'\d+(\.\d*)?([eE]\d+)?')
+        point = pp.Literal( "." )
+        e     = pp.CaselessLiteral( "E" )
+
+        # Regex string representing the set of possible operators
+        # Example : ">=|<=|!=|>|<|="
+        OPERATOR_RX = '|'.join([re.sub('\|', '\|', o) for o in Predicate.operators.keys()])
+
+        # predicate
+        field = pp.Word(pp.alphanums + '_')
+        operator = pp.Regex(OPERATOR_RX).setName("operator")
+        value = pp.QuotedString('"') #| pp.Combine( pp.Word( "+-"+ pp.nums, pp.nums) + pp.Optional( point + pp.Optional( pp.Word( pp.nums ) ) ) + pp.Optional( e + pp.Word( "+-"+pp.nums, pp.nums ) ) )
+
+        predicate = (field + operator + value).setParseAction(self.handlePredicate)
+
+        # clause of predicates
+        and_op = pp.CaselessLiteral("and") | pp.Keyword("&&")
+        or_op  = pp.CaselessLiteral("or")  | pp.Keyword("||")
+        not_op = pp.Keyword("!")
+
+        predicate_precedence_list = [
+            (not_op, 1, pp.opAssoc.RIGHT, lambda x: self.handleClause(*x)),
+            (and_op, 2, pp.opAssoc.LEFT,  lambda x: self.handleClause(*x)),
+            (or_op,  2, pp.opAssoc.LEFT,  lambda x: self.handleClause(*x))
+        ]
+        clause = pp.operatorPrecedence(predicate, predicate_precedence_list)
+
+        self.bnf = clause
+
+    def handlePredicate(self, args):
+        return Predicate(*args)
+
+    def handleClause(self, args):
+        return Clause(*args)
+
+    def parse(self, string):
+        return self.bnf.parseString(string,parseAll=True)
+
+if __name__ == "__main__":
+    print ClauseStringParser().parse('country == "Europe" || ts > "01-01-2007" && country == "France"')
+    print Clause('country == "Europe" || ts > "01-01-2007" && country == "France"')
diff --git a/manifold/util/frozendict.py b/manifold/util/frozendict.py
new file mode 100644 (file)
index 0000000..32902cb
--- /dev/null
@@ -0,0 +1,47 @@
+import copy
+
+class frozendict(dict):
+    def _blocked_attribute(obj):
+        raise AttributeError, "A frozendict cannot be modified."
+    _blocked_attribute = property(_blocked_attribute)
+
+    __delitem__ = __setitem__ = clear = _blocked_attribute
+    pop = popitem = setdefault = update = _blocked_attribute
+
+    def __new__(cls, *args, **kw):
+        new = dict.__new__(cls)
+
+        args_ = []
+        for arg in args:
+            if isinstance(arg, dict):
+                arg = copy.copy(arg)
+                for k, v in arg.items():
+                    if isinstance(v, dict):
+                        arg[k] = frozendict(v)
+                    elif isinstance(v, list):
+                        v_ = list()
+                        for elm in v:
+                            if isinstance(elm, dict):
+                                v_.append( frozendict(elm) )
+                            else:
+                                v_.append( elm )
+                        arg[k] = tuple(v_)
+                args_.append( arg )
+            else:
+                args_.append( arg )
+
+        dict.__init__(new, *args_, **kw)
+        return new
+
+    def __init__(self, *args, **kw):
+        pass
+
+    def __hash__(self):
+        try:
+            return self._cached_hash
+        except AttributeError:
+            h = self._cached_hash = hash(tuple(sorted(self.items())))
+            return h
+
+    def __repr__(self):
+        return "frozendict(%s)" % dict.__repr__(self)
diff --git a/manifold/util/misc.py b/manifold/util/misc.py
new file mode 100644 (file)
index 0000000..4494dcf
--- /dev/null
@@ -0,0 +1,13 @@
+import os, glob, inspect
+
+
+# Define the inclusion operator
+class contains(type): pass
+
+def find_local_modules(filepath):
+    modules = []
+    for f in glob.glob(os.path.dirname(filepath)+"/*.py"):
+        name = os.path.basename(f)[:-3]
+        if name != '__init__':
+            modules.append(name)
+    return modules 
diff --git a/manifold/util/predicate.py b/manifold/util/predicate.py
new file mode 100644 (file)
index 0000000..3b5ba80
--- /dev/null
@@ -0,0 +1,235 @@
+from types import StringTypes
+
+from operator import (
+    and_, or_, inv, add, mul, sub, mod, truediv, lt, le, ne, gt, ge, eq, neg
+    )
+
+# Define the inclusion operators
+class contains(type): pass
+class included(type): pass
+
+
+# New modifier: { contains 
+class Predicate:
+
+    operators = {
+        '=='       : eq,
+        '!='       : ne,
+        '<'        : lt,
+        '<='       : le,
+        '>'        : gt,
+        '>='       : ge,
+        '&&'       : and_,
+        '||'       : or_,
+        'CONTAINS' : contains,
+        'INCLUDED' : included
+    }
+
+    operators_short = {
+        '=' : eq,
+        '~' : ne,
+        '<' : lt,
+        '[' : le,
+        '>' : gt,
+        ']' : ge,
+        '&' : and_,
+        '|' : or_,
+        '}' : contains,
+        '{' : included
+    }
+
+    def __init__(self, *args, **kwargs):
+        """
+        \brief Build a predicate (left, operator, right)
+        \param You can pass:
+            - three args (left, operator, right)
+            - one argument (list or tuple) containing three elements (variable, operator, value)
+            "operator" is a String defined in operators or in operators_short and refers
+                tMao a binary operation.
+            "left" and "right" refers to a variable/constant involved in the Predicate.
+        """
+        if len(args) == 3:
+            key, op, value = args
+        elif len(args) == 1 and isinstance(args[0], (tuple,list)) and len(args[0]) == 3:
+            key, op, value = args[0]
+        elif len(args) == 1 and isinstance(args[0], Predicate):
+            key, op, value = args[0].get_tuple()
+        else:
+            raise Exception, "Bad initializer for Predicate (args=%r)" % args
+
+        assert not isinstance(value, (frozenset, dict, set)), "Invalid value type (the only valid containers are tuples and lists) (type = %r)" % type(value)
+        if isinstance(value, list):
+            value = tuple(value)
+
+        self.key = key
+        if isinstance(op, StringTypes):
+            op = op.upper()
+        if op in self.operators.keys():
+            self.op = self.operators[op]
+        elif op in self.operators_short.keys():
+            self.op = self.operators_short[op]
+        else:
+            self.op = op
+
+        if isinstance(value, list):
+            self.value = tuple(value)
+        else:
+            self.value = value
+
+    def __str__(self):
+        key, op, value = self.get_str_tuple()
+        if isinstance(value, (tuple, list, set, frozenset)):
+            value = [repr(v) for v in value]
+            value = "[%s]" % ", ".join(value)
+        return "%s %s %r" % (key, op, value) 
+
+    def __repr__(self):
+        return "Predicate<%s %s %r>" % self.get_str_tuple()
+
+    def __hash__(self):
+        return hash(self.get_tuple())
+
+    def __eq__(self, predicate):
+        if not predicate:
+            return False
+        return self.get_tuple() == predicate.get_tuple()
+
+    def get_key(self):
+        return self.key
+    
+    def set_key(self, key):
+        self.key = key
+
+    def get_op(self):
+        return self.op
+
+    def get_value(self):
+        return self.value
+
+    def set_value(self, value):
+        self.value = value
+
+    def get_tuple(self):
+        return (self.key, self.op, self.value)
+
+
+    def get_str_op(self):
+        op_str = [s for s, op in self.operators.iteritems() if op == self.op]
+        return op_str[0]
+
+    def get_str_tuple(self):
+        return (self.key, self.get_str_op(), self.value,)
+
+    def to_list(self):
+        return list(self.get_str_tuple())
+
+    def match(self, dic, ignore_missing=False):
+        if isinstance(self.key, tuple):
+            print "PREDICATE MATCH", self.key
+            print dic
+            print "-----------------------------"
+        
+        # Can we match ?
+        if self.key not in dic:
+            return ignore_missing
+
+        if self.op == eq:
+            if isinstance(self.value, list):
+                return (dic[self.key] in self.value) # array ?
+            else:
+                return (dic[self.key] == self.value)
+        elif self.op == ne:
+            if isinstance(self.value, list):
+                return (dic[self.key] not in self.value) # array ?
+            else:
+                return (dic[self.key] != self.value) # array ?
+        elif self.op == lt:
+            if isinstance(self.value, StringTypes):
+                # prefix match
+                return dic[self.key].startswith('%s.' % self.value)
+            else:
+                return (dic[self.key] < self.value)
+        elif self.op == le:
+            if isinstance(self.value, StringTypes):
+                return dic[self.key] == self.value or dic[self.key].startswith('%s.' % self.value)
+            else:
+                return (dic[self.key] <= self.value)
+        elif self.op == gt:
+            if isinstance(self.value, StringTypes):
+                # prefix match
+                return self.value.startswith('%s.' % dic[self.key])
+            else:
+                return (dic[self.key] > self.value)
+        elif self.op == ge:
+            if isinstance(self.value, StringTypes):
+                # prefix match
+                return dic[self.key] == self.value or self.value.startswith('%s.' % dic[self.key])
+            else:
+                return (dic[self.key] >= self.value)
+        elif self.op == and_:
+            return (dic[self.key] & self.value) # array ?
+        elif self.op == or_:
+            return (dic[self.key] | self.value) # array ?
+        elif self.op == contains:
+            method, subfield = self.key.split('.', 1)
+            return not not [ x for x in dic[method] if x[subfield] == self.value] 
+        elif self.op == included:
+            return dic[self.key] in self.value
+        else:
+            raise Exception, "Unexpected table format: %r" % dic
+
+    def filter(self, dic):
+        """
+        Filter dic according to the current predicate.
+        """
+
+        if '.' in self.key:
+            # users.hrn
+            method, subfield = self.key.split('.', 1)
+            if not method in dic:
+                return None # XXX
+
+            if isinstance(dic[method], dict):
+                # We have a 1..1 relationship: apply the same filter to the dict
+                subpred = Predicate(subfield, self.op, self.value)
+                match = subpred.match(dic[method])
+                return dic if match else None
+
+            elif isinstance(dic[method], (list, tuple)):
+                # 1..N relationships
+                match = False
+                if self.op == contains:
+                    return dic if self.match(dic) else None
+                else:
+                    subpred = Predicate(subfield, self.op, self.value)
+                    dic[method] = subpred.filter(dic[method])
+                    return dic
+            else:
+                raise Exception, "Unexpected table format: %r", dic
+
+
+        else:
+            # Individual field operations: this could be simplified, since we are now using operators_short !!
+            # XXX match
+            print "current predicate", self
+            print "matching", dic
+            print "----"
+            return dic if self.match(dic) else None
+
+    def get_field_names(self):
+        if isinstance(self.key, (list, tuple, set, frozenset)):
+            return set(self.key)
+        else:
+            return set([self.key])
+
+    def get_value_names(self):
+        if isinstance(self.value, (list, tuple, set, frozenset)):
+            return set(self.value)
+        else:
+            return set([self.value])
+
+    def has_empty_value(self):
+        if isinstance(self.value, (list, tuple, set, frozenset)):
+            return not any(self.value)
+        else:
+            return not self.value
diff --git a/manifold/util/singleton.py b/manifold/util/singleton.py
new file mode 100644 (file)
index 0000000..b622c13
--- /dev/null
@@ -0,0 +1,19 @@
+#-------------------------------------------------------------------------
+# Class Singleton
+#
+# Classes that inherit from Singleton can be instanciated only once 
+#-------------------------------------------------------------------------
+
+class Singleton(type):
+    def __init__(cls, name, bases, dic):
+        super(Singleton,cls).__init__(name,bases,dic)
+        cls.instance=None
+
+    def __call__(cls, *args, **kw):
+        if cls.instance is None:
+            cls.instance=super(Singleton,cls).__call__(*args,**kw)
+        return cls.instance
+
+
+# See also
+# http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
diff --git a/manifold/util/type.py b/manifold/util/type.py
new file mode 100644 (file)
index 0000000..5d7ab1e
--- /dev/null
@@ -0,0 +1,143 @@
+# http://wiki.python.org/moin/PythonDecoratorLibrary#Type_Enforcement_.28accepts.2Freturns.29
+'''
+One of three degrees of enforcement may be specified by passing
+the 'debug' keyword argument to the decorator:
+    0 -- NONE:   No type-checking. Decorators disabled.
+    1 -- MEDIUM: Print warning message to stderr. (Default)
+    2 -- STRONG: Raise TypeError with message.
+If 'debug' is not passed to the decorator, the default level is used.
+
+Example usage:
+    >>> NONE, MEDIUM, STRONG = 0, 1, 2
+    >>>
+    >>> @accepts(int, int, int)
+    ... @returns(float)
+    ... def average(x, y, z):
+    ...     return (x + y + z) / 2
+    ...
+    >>> average(5.5, 10, 15.0)
+    TypeWarning:  'average' method accepts (int, int, int), but was given
+    (float, int, float)
+    15.25
+    >>> average(5, 10, 15)
+    TypeWarning:  'average' method returns (float), but result is (int)
+    15
+
+Needed to cast params as floats in function def (or simply divide by 2.0).
+
+    >>> TYPE_CHECK = STRONG
+    >>> @accepts(int, debug=TYPE_CHECK)
+    ... @returns(int, debug=TYPE_CHECK)
+    ... def fib(n):
+    ...     if n in (0, 1): return n
+    ...     return fib(n-1) + fib(n-2)
+    ...
+    >>> fib(5.3)
+    Traceback (most recent call last):
+      ...
+    TypeError: 'fib' method accepts (int), but was given (float)
+
+'''
+import sys
+from itertools import izip
+
+def accepts(*types, **kw):
+    '''Function decorator. Checks decorated function's arguments are
+    of the expected types.
+
+    Parameters:
+    types -- The expected types of the inputs to the decorated function.
+             Must specify type for each parameter.
+    kw    -- Optional specification of 'debug' level (this is the only valid
+             keyword argument, no other should be given).
+             debug = ( 0 | 1 | 2 )
+
+    '''
+    if not kw:
+        # default level: MEDIUM
+        debug = 2
+    else:
+        debug = kw['debug']
+    try:
+        def decorator(f):
+            def newf(*args):
+                if debug is 0:
+                    return f(*args)
+                assert len(args) == len(types)
+                argtypes = tuple(map(type, args))
+                if not compare_types(types, argtypes):
+                # if argtypes != types:
+                    msg = info(f.__name__, types, argtypes, 0)
+                    if debug is 1:
+                        print >> sys.stderr, 'TypeWarning: ', msg
+                    elif debug is 2:
+                        raise TypeError, msg
+                return f(*args)
+            newf.__name__ = f.__name__
+            return newf
+        return decorator
+    except KeyError, key:
+        raise KeyError, key + "is not a valid keyword argument"
+    except TypeError, msg:
+        raise TypeError, msg
+
+def compare_types(expected, actual):
+    if isinstance(expected, tuple):
+        if isinstance(actual, tuple):
+            for x, y in izip(expected, actual):
+                if not compare_types(x ,y):
+                    return False
+            return True
+        else:
+            return actual == type(None) or actual in expected
+    else:
+        return actual == type(None) or actual == expected or issubclass(actual, expected)
+
+def returns(ret_type, **kw):
+    '''Function decorator. Checks decorated function's return value
+    is of the expected type.
+
+    Parameters:
+    ret_type -- The expected type of the decorated function's return value.
+                Must specify type for each parameter.
+    kw       -- Optional specification of 'debug' level (this is the only valid
+                keyword argument, no other should be given).
+                debug=(0 | 1 | 2)
+    '''
+    try:
+        if not kw:
+            # default level: MEDIUM
+            debug = 1
+        else:
+            debug = kw['debug']
+        def decorator(f):
+            def newf(*args):
+                result = f(*args)
+                if debug is 0:
+                    return result
+                res_type = type(result)
+                if not compare_types(ret_type, res_type): 
+                # if res_type != ret_type: # JORDAN: fix to allow for # StringTypes = (str, unicode)
+                # XXX note that this check should be recursive
+                    msg = info(f.__name__, (ret_type,), (res_type,), 1)
+                    if debug is 1:
+                        print >> sys.stderr, 'TypeWarning: ', msg
+                    elif debug is 2:
+                        raise TypeError, msg
+                return result
+            newf.__name__ = f.__name__
+            return newf
+        return decorator
+    except KeyError, key:
+        raise KeyError, key + "is not a valid keyword argument"
+    except TypeError, msg:
+        raise TypeError, msg
+
+def info(fname, expected, actual, flag):
+    '''Convenience function returns nicely formatted error/warning msg.'''
+    format = lambda types: ', '.join([str(t).split("'")[1] for t in types])
+    msg = "'{}' method ".format( fname )\
+          + ("accepts", "returns")[flag] + " ({}), but ".format(expected)\
+          + ("was given", "result is")[flag] + " ({})".format(actual)
+    return msg
+
index 6ef5061..f6285b2 100644 (file)
@@ -1,16 +1,17 @@
 class Config:
 
-    # production should use https of course
+# this version of unfold expects a backend that runs a new API
 
-# an old-fashioned API - that's what is currently only supported   
-    #manifold_url = "http://manifold.pl.sophia.inria.fr:7080/"
-    manifold_url = "http://localhost:7080/"
-# this one runs a new API, but currently (april 2013) there are missing
-# features; GetSession and GetPersons are still there (they should go away) and 
-# the code for retrieving metadata does not work as-is, and I have no clue 
-# what it should become anyways, so...
-#    manifold_url = "http://dev.myslice.info:7080/"
+# production should probably use https of course
 
+
+# if you use a development backend running on this box
+#    manifold_url = "http://localhost:7080/"
+# the INRIA setup
+#    manifold_url = "http://manifold.pl.sophia.inria.fr:7080/"
+# the OpenLab-wide backend as managed by UPMC
+#    manifold_url = "http://dev.myslice.info:7080/" # development version
+     manifold_url = "http://test.myslice.info:7080/" #stable manifol
     # exporting these details to js
     @staticmethod
     def manifold_js_export ():
index 2dbb861..25c2a26 100644 (file)
@@ -24,11 +24,19 @@ if not ROOT:
 
 ####################
 ADMINS = (
-    # ('Your Name', 'your_email@example.com'),
+    # ('your_name', 'your_email@test.com'),
 )
 
 MANAGERS = ADMINS
 
+# Mail configuration
+#DEFAULT_FROM_EMAIL = "root@theseus.ipv6.lip6.fr"
+#EMAIL_HOST_PASSWORD = "mypassword"
+
+EMAIL_HOST = "localhost"
+EMAIL_PORT = 25
+EMAIL_USE_TLS = False
+
 DATABASES = {
     'default': {
         'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
@@ -80,24 +88,51 @@ STATIC_ROOT = os.path.join(ROOT,'django-static')
 
 # URL prefix for static files.
 # Example: "http://media.lawrence.com/static/"
-STATIC_URL = '/all-static/'
+# thierry STATIC_URL = '/all-static/'
+STATIC_URL = '/static/'
 
 # Additional locations of static files
 STATICFILES_DIRS = (
     # Put strings here, like "/home/html/static" or "C:/www/django/static".
     # Always use forward slashes, even on Windows.
     # Don't forget to use absolute paths, not relative paths.
-    os.path.join(ROOT,'all-static'),
+    # thierry os.path.join(ROOT,'all-static'),
+    ('js', os.path.join(ROOT,'manifold/js')),
+    ('css', os.path.join(ROOT,'manifold/css')),
+    ('js', os.path.join(ROOT,'unfold/js')),
+    ('css', os.path.join(ROOT,'unfold/css')),
+    ('js', os.path.join(ROOT,'auth/js')),
+    ('css', os.path.join(ROOT,'auth/css')),
+    ('img', os.path.join(ROOT,'auth/img')),
+    ('css', os.path.join(ROOT,'views/css')),
+    ('img', os.path.join(ROOT,'views/img')),
 )
 
+# Needed by PluginFinder
+PLUGIN_DIR = os.path.join(ROOT,'plugins')
+# ThirdPartyFinder
+THIRDPARTY_DIR = os.path.join(ROOT, 'third-party')
+
 # List of finder classes that know how to find static files in
 # various locations.
 STATICFILES_FINDERS = (
     'django.contrib.staticfiles.finders.FileSystemFinder',
     'django.contrib.staticfiles.finders.AppDirectoriesFinder',
+    'unfold.static.PluginFinder',
+    'unfold.static.ThirdPartyFinder',
 #    'django.contrib.staticfiles.finders.DefaultStorageFinder',
 )
 
+#TEMPLATE_CONTEXT_PROCESSORS = (
+#    'django.contrib.auth.context_processors.auth',
+#    'django.core.context_processors.debug',
+#    'django.core.context_processors.i18n',
+#    'django.core.context_processors.media',
+#    'django.core.context_processors.static',
+#    'django.core.context_processors.request',
+#    'django.contrib.messages.context_processors.messages',
+#)
+
 # Make this unique, and don't share it with anybody.
 SECRET_KEY = 't%n(3h)&amp;r^n8(+8)(sp29t^$c2#t(m3)e2!02l8w1#36tl#t27'
 
@@ -149,12 +184,24 @@ INSTALLED_APPS = (
     # views - more or less stable 
     'views',
     'trash',
+    'south', # managing database migrations
     # Uncomment the next line to enable the admin:
     # 'django.contrib.admin',
     # Uncomment the next line to enable admin documentation:
     # 'django.contrib.admindocs',
+    'portal',
+    'sample',
+# DEPRECATED #    'django.contrib.formtools',
+# DEPRECATED ##    'crispy_forms',
+# DEPRECATED #
+# DEPRECATED #    # User registration
+# DEPRECATED #    'django.contrib.auth',
+# DEPRECATED #    'django.contrib.sites',
+# DEPRECATED #    'registration',
 )
 
+ACCOUNT_ACTIVATION_DAYS = 7 # One-week activation window; you may, of course, use a different value.
+
 # A sample logging configuration. The only tangible logging
 # performed by this configuration is to send an email to
 # the site admins on every HTTP 500 error when DEBUG=False.
@@ -184,7 +231,7 @@ LOGGING = {
     }
 }
 
-AUTHENTICATION_BACKENDS = ( 'auth.backend.MyCustomBackend', 'auth.manifoldbackend.ManifoldBackend', )
+AUTHENTICATION_BACKENDS = ( 'auth.manifoldbackend.ManifoldBackend', )
 
 ### the view to redirect malformed (i.e. with a wrong CSRF) incoming requests
 # without this setting django will return a 403 forbidden error, which is fine
index a2e0695..6d22803 100644 (file)
@@ -1,4 +1,5 @@
 from django.conf.urls import patterns, include, url
+from django.conf      import settings
 
 # Uncomment the next two lines to enable the admin:
 # from django.contrib import admin
@@ -8,10 +9,24 @@ from django.conf.urls import patterns, include, url
 from django.template.loader import add_to_builtins
 add_to_builtins('insert_above.templatetags.insert_tags')
 
+import portal.platformsview
+import portal.dashboardview
+import portal.homeview
+
+home_view=portal.homeview.HomeView.as_view()
+dashboard_view=portal.dashboardview.DashboardView.as_view()
+platforms_view=portal.platformsview.PlatformsView.as_view()
+
+#### high level choices
 # main entry point (set to the / URL)
-default_view='trash.pluginview.test_plugin_view'
+# beware that if this view is broken you end up in an endless cycle...
+# maybe platforms_view would be best on the longer run
+the_default_view=home_view
 # where to be redirected after login
-after_login_view='trash.dashboard.dashboard_view'
+the_after_login_view=home_view #dashboard_view
+# where to redirect when login is required
+# might need another one ?
+the_login_view=home_view
 
 urlpatterns = patterns(
     '',
@@ -25,26 +40,31 @@ urlpatterns = patterns(
     #
     # default / view
     #
-    (r'^/?$', default_view),
+    (r'^/?$', the_default_view),
     #
     # login / logout
     #
-    (r'^login-ok/?$', after_login_view),
+    (r'^login-ok/?$', the_after_login_view, {'state': 'Welcome to MySlice'} ),
     # seems to be what login_required uses to redirect ...
-    (r'^accounts/login/$', 'auth.views.login_user'),
-    (r'^login/?$', 'auth.views.login_user'),
+    (r'^accounts/login/$', the_login_view),
+    (r'^login/?$', the_login_view),
     (r'^logout/?$', 'auth.views.logout_user'),
     #
     # the manifold proxy
     #
     (r'^manifold/proxy/(?P<format>\w+)/?$', 'manifold.manifoldproxy.proxy'),
     #
-    # various trash views
+    # Portal
+    url(r'^portal/', include('portal.urls')),
+    # Portal
+    url(r'^sample/', include('sample.urls')),
+    # Debug
+    url(r'^debug/', include('debug_platform.urls')),
+    # Static files
+    (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),
     #
-    (r'^tab/?$', 'trash.sampleviews.tab_view'),
-    (r'^scroll/?$', 'trash.sampleviews.scroll_view'),
-    (r'^plugin/?$', 'trash.pluginview.test_plugin_view'),
-    (r'^dashboard/?$', 'trash.dashboard.dashboard_view'),
-    (r'^slice/?$', 'trash.sliceview.slice_view'),
-    (r'^slice/(?P<slicename>[\w\.]+)/?$', 'trash.sliceview.slice_view'),
+    # various trash views - bound to go away 
+    #
+    url(r'^trash/', include('trash.urls')),
+
 )
index 37a7d63..eaa2dcb 100644 (file)
@@ -1,66 +1,31 @@
 # a set of utilities to help make the global layout consistent across views
 
-from copy import deepcopy
-
-standard_topmenu_items = [ 
-#    { 'label':'Tab', 'href': '/tab/'},
-#    { 'label':'Scroll', 'href': '/scroll/'},
-    { 'label':'One Plugin', 'href': '/plugin/'},
-    { 'label':'Dashboard', 'href': '/dashboard/'},
-    { 'label':'Slice', 'href': '/slice/'},
-    ]
-
-#login_out_items = { False: { 'label':'Login', 'href':'/login/'},
-#                    True:  { 'label':'Logout', 'href':'/logout/'}}
-
 def topmenu_items (current,request=None):
-    result=deepcopy(standard_topmenu_items)
+    has_user=request.user.is_authenticated()
+    result=[]
+    if has_user:
+        result.append({'label':'Platforms', 'href': '/portal/platforms/'})
+        result.append({ 'label':'Dashboard', 'href': '/portal/dashboard/'})
+        # This should probably go in dashboard at some point
+        result.append({ 'label':'Request a slice', 'href': '/portal/slice_request/'})
+        result.append({'label':'My Account', 'href': '/portal/account/'})
+    else:
+        result.append({'label':'Home', 'href': '/login'})
+        # looks like this is accessible to non-logged users
+        result.append({'label':'Platforms', 'href': '/portal/platforms/'})
+        result.append({ 'label':'Register', 'href': '/portal/register/'})
+    result.append({'label':'Contact Support', 'href': '/portal/contact/'})
     for d in result:
-        if d['label'].lower().find(current)>=0: d['is_active']=True
+        #if d['label'].lower()find(current)>=0: d['is_active']=True
+        if d['label'] == current: d['is_active']=True
     if not request: return result
-    has_user=request.user.is_authenticated()
 #    result.append (login_out_items [ has_user] )
     return result
 
 def the_user (request):
-    "This code below is broken"
+    "retrieves logged in user's email, or empty string"
     if not request.user.is_authenticated (): 
-#        print 'void user!'
         return ''
     else: 
         return request.user.email
 
-# temporary for sample views
-lorem="""
-Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod <code>mazim placerat</code> facer possim assum. Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.
-"""
-
-lorem_p = "<p>"+lorem+"</p>"
-
-hard_wired_slice_names = []
-for site in [ 'inria', 'upmc' , 'ibbt' ]:
-    for slice in [ 'foo', 'bar', 'tutu', 'test', 'omf', 'heartbeat' ]:
-        hard_wired_slice_names.append ("ple.%s.%s"%(site,slice))
-
-# having html tags right here is not a real use case
-hard_wired_list=[]
-hard_wired_list.append("this hard-wired list")
-hard_wired_list.append("is defined")
-hard_wired_list.append("in plugins.simplelist.py")
-hard_wired_list.append("which in turn relies on")
-hard_wired_list.append("template widget-template.html")
-hard_wired_list.append("while it should of course")
-hard_wired_list.append("instead issue a query")
-hard_wired_list.append("and fill the DOM in js from there")
-hard_wired_list.append("it would however maybe make sense")
-hard_wired_list.append("to offer the option to 'datatablify'")
-hard_wired_list.append("the list from the python code")
-hard_wired_list.append("just like a standard plugin can be set as visible or not")
-hard_wired_list.append("")    
-hard_wired_list.append("OTOH and IMHO, there should be two separate and explicit subclasses of SimpleList for slices or testbeds")
-
-quickfilter_criterias = [
-    {'key': 'Slice', 'values': ['slice1','slice2']},
-    {'key': 'Type', 'values': ['type1','type2']},
-    {'key': 'Network', 'values': ['net1','net2']},
-    ]
diff --git a/plugins/active_filters/__init__.py b/plugins/active_filters/__init__.py
new file mode 100644 (file)
index 0000000..c20847a
--- /dev/null
@@ -0,0 +1,61 @@
+from unfold.plugin import Plugin
+from manifold.util.predicate import eq, ne, lt, le, gt, ge, and_, or_, contains, included 
+
+# NOTE: Python should pass templates to javascript for creating new filters
+# - option variable
+# - or, better, hidden div in the page
+# In the meantime, templates are duplicated in the javascript code
+# RECIPES FOR PLUGINS
+
+# NOTE: having classes would help
+
+class ActiveFilters(Plugin):
+
+    def __init__ (self, query=None, **settings):
+        Plugin.__init__ (self, **settings)
+
+        self.query = query
+
+    def template_file (self):
+        return "active_filters.html"
+
+    def template_env (self, request):
+
+        def get_op_str(predicate):
+            map = {
+                eq      : 'eq',
+                ne      : 'ne',
+                lt      : 'lt',
+                le      : 'le',
+                gt      : 'gt',
+                ge      : 'ge',
+                and_    : 'and',
+                or_     : 'or',
+                contains: 'contains',
+                included: 'included'
+            }
+            return map[predicate.get_op()]
+
+        filters = [[f.get_key(), get_op_str(f), f.get_value()] for p in self.query.get_where()]
+        env={}
+        env.update(self.__dict__)
+        env['filters'] = filters
+        return env
+
+    def requirements (self):
+        reqs = {
+            'js_files' : [
+                'js/active_filters.js',
+             ],
+            'css_files': [ 
+                'css/demo_table.css',
+                'css/active_filters.css'
+            ]
+        }
+        return reqs
+
+    def json_settings_list (self):
+        return ['plugin_uuid', 'domid', 'query_uuid']
+
+    def export_json_settings (self):
+        return True
diff --git a/plugins/active_filters/static/active_filters.html b/plugins/active_filters/static/active_filters.html
new file mode 100644 (file)
index 0000000..7fa3883
--- /dev/null
@@ -0,0 +1,25 @@
+{% load staticfiles %}
+<div id='{{domid}}__myActiveFilters' style='clear:both;'>
+
+       <!-- TEMPLATE -->
+       <div id='{{domid}}__template' class='template'>
+                <div id='{% templatetag openvariable %} id {% templatetag closevariable %}' class='filterButton' style='float:left;margin-bottom:10px;'>
+                       <span>{% templatetag openvariable %} span {% templatetag closevariable %}</span>
+            <img src='{% static "img/details_close.png" %}' class='closeButton' style='padding-left:3px;'/>
+               </div>
+       </div>
+
+       {% for filter in filters %}
+       <div id='{{domid}}__filter__{{filter.key}}{{filter.op_str}}{{filter.value}}' class='filterButton' style='float:left;margin-bottom:10px;'>
+               <span>{{filter.key}}__{{filter.op}}__{{filter.value}}</span>
+        <img src='/all-static/img/details_close.png' class='closeButton' style='padding-left:3px;'/>
+       </div>
+       {% endfor %}
+
+</div>
+
+<div id='clearFilters' class='paging_full_numbers' style='clear:both;'>
+    <span class='paginate_button'>Clear</span>
+</div>
+
+<div style='clear:both;'></div>
diff --git a/plugins/active_filters/static/css/active_filters.css b/plugins/active_filters/static/css/active_filters.css
new file mode 100644 (file)
index 0000000..83967d9
--- /dev/null
@@ -0,0 +1,20 @@
+/* 
+    Document   : ActiveFilters
+    Created on : 26 juil. 2012, 11:19:10
+    Author     : loicbaron
+    Description:
+        Purpose of the stylesheet follows.
+*/
+
+.filterButton { 
+    border: 1px solid #AAA;
+    -webkit-border-radius: 5px;
+    -moz-border-radius: 5px;
+    padding: 2px 5px;
+    margin: 0 3px;
+    background-color:#D3D6FF;
+}
+.closeButton{
+    cursor: pointer;
+    vertical-align:middle;    
+}
\ No newline at end of file
diff --git a/plugins/active_filters/static/img/details_close.png b/plugins/active_filters/static/img/details_close.png
new file mode 100644 (file)
index 0000000..fcc23c6
Binary files /dev/null and b/plugins/active_filters/static/img/details_close.png differ
diff --git a/plugins/active_filters/static/img/details_open.png b/plugins/active_filters/static/img/details_open.png
new file mode 100644 (file)
index 0000000..6f034d0
Binary files /dev/null and b/plugins/active_filters/static/img/details_open.png differ
diff --git a/plugins/active_filters/static/js/active_filters.js b/plugins/active_filters/static/js/active_filters.js
new file mode 100644 (file)
index 0000000..89ebef2
--- /dev/null
@@ -0,0 +1,118 @@
+/**
+ * Description: ActiveFilters plugin
+ * Copyright (c) 2012-2013 UPMC Sorbonne Universite
+ * License: GPLv3
+ */
+
+// NOTE: We are not making use of element, but this.el() instead...
+
+(function($){
+
+    var ActiveFilters = Plugin.extend({
+
+        init: function(options, element) {
+            this._super(options, element);
+
+            this.els('closeButton').click(function() {
+                manifold.raise_event(options.query_uuid, FILTER_REMOVED, filter);
+            });
+
+            this.el('clearFilters').click(function () {
+                manifold.raise_event(options.query_uuid, CLEAR_FILTERS);
+            });
+            this.check_and_hide_clear_button();
+
+            this.listen_query(options.query_uuid);
+
+        },
+
+        // This should be provided in the API
+        // make_id_from_filter, etc
+        getOperatorLabel: function(op)
+        {
+            if (op == "=" || op == "==") {
+                return 'eq';
+            } else if (op == "!=") {
+                return "ne";
+            } else if (op == ">") {
+                return "gt";
+            } else if (op == ">=") {
+                return "ge";
+            } else if (op == "<") {
+                return "lt";
+            } else if (op == "<=") {
+                return "le";
+            } else {
+                return false;
+            }
+        },
+
+        show_clear_button: function()
+        {
+            this.el('clearFilters').show();
+        },
+
+        hide_clear_button: function()
+        {
+            this.el('clearFilters').hide();
+        },
+
+        check_and_hide_clear_button: function()
+        {
+            // Count the number of filter _inside_ the current plugin
+            var count = this.els('filterButton').length;
+            if (count == 1) { // Including the template
+                this.el('clearFilters').hide();
+            }
+        },
+
+        clear_filters: function() 
+        {
+            // XXX We need to remove all filter but template
+            this.hide_clear_button();
+        },
+
+        add_filter: function(filter)
+        {
+            var template = this.el('template').html();
+            var ctx = {
+                id:   this.id(this.id_from_filter(filter, false)),
+                span: this.str_from_filter(filter)
+            };
+            var output = Mustache.render(template, ctx);
+
+            this.el('myActiveFilters').append(output);
+
+            // Add an event on click on the close button, call function removeFilter
+            var self = this;
+            this.els('closeButton').last().click(function() {
+                manifold.raise_event(self.options.query_uuid, FILTER_REMOVED, filter);
+            });
+
+            this.show_clear_button();
+        },
+        
+        remove_filter: function(filter)
+        {
+            this.el(this.id_from_filter(filter, false)).remove();
+            this.check_and_hide_clear_button();
+        },
+
+        /* Events */
+
+        on_filter_added: function(filter) {
+            this.add_filter(filter);
+        },
+
+        on_filter_removed: function(filter) {
+            this.remove_filter(filter);
+        },
+
+        on_filter_clear: function(filter) {
+            this.clear_filters();
+        },
+    });
+
+    $.plugin('ActiveFilters', ActiveFilters);
+
+})(jQuery);
diff --git a/plugins/code_editor/__init__.py b/plugins/code_editor/__init__.py
new file mode 100644 (file)
index 0000000..c3f7528
--- /dev/null
@@ -0,0 +1,29 @@
+from unfold.plugin import Plugin
+
+class CodeEditor(Plugin):
+
+    def template_file(self):
+        return "code_editor.html"
+
+    def requirements (self):
+        reqs = {
+            'js_files' : [
+                'js/code_editor.js',
+                'js/moo-clientcide-1.3.js',
+                'js/codemirror.js',
+                'js/sql.js',
+                'js/Actions.js',
+                #'js/EditorCM.js',
+                'js/LayoutCM.js',
+            ] ,
+            'css_files': [
+                'css/codemirror.css',
+            ]
+        }
+        return reqs
+
+    def json_settings_list (self):
+        return ['plugin_uuid', 'domid', 'lineNumbers']
+
+    def export_json_settings (self):
+        return True
diff --git a/plugins/code_editor/static/code_editor.html b/plugins/code_editor/static/code_editor.html
new file mode 100644 (file)
index 0000000..c39802a
--- /dev/null
@@ -0,0 +1 @@
+<textarea id="{{ domid }}-textarea" rows="10" cols="40" name="code_html"></textarea>
diff --git a/plugins/code_editor/static/img/handle-h.png b/plugins/code_editor/static/img/handle-h.png
new file mode 100644 (file)
index 0000000..d743e52
Binary files /dev/null and b/plugins/code_editor/static/img/handle-h.png differ
diff --git a/plugins/code_editor/static/img/handle-v.png b/plugins/code_editor/static/img/handle-v.png
new file mode 100644 (file)
index 0000000..0e1a959
Binary files /dev/null and b/plugins/code_editor/static/img/handle-v.png differ
diff --git a/plugins/code_editor/static/img/initializing.png b/plugins/code_editor/static/img/initializing.png
new file mode 100644 (file)
index 0000000..2eed2a6
Binary files /dev/null and b/plugins/code_editor/static/img/initializing.png differ
diff --git a/plugins/code_editor/static/js/Actions.js b/plugins/code_editor/static/js/Actions.js
new file mode 100644 (file)
index 0000000..08ea0c1
--- /dev/null
@@ -0,0 +1,798 @@
+// TODO: refactor
+// TODO: This code is now legacy code, none of it will make its way into Beta
+window.editorsModified = false;
+
+Request.JSON.implement({
+  initialize: function(options) {
+    this.parent(options);
+    this.setHeader('X-CSRFToken', Cookie.read('csrftoken'));
+  }
+});
+
+Track = {
+  ui: function(action){
+    if (typeof(_gaq) !== 'undefined'){
+      _gaq.push(['_trackEvent', 'UI',  action || null]);
+    }
+  }
+};
+
+/*
+ * Define actions on the run/save/clean buttons
+ */
+var MooShellActions = new Class({
+  Implements: [Options, Events],
+  options: {
+    // onRun: $empty,
+    // onClean: $empty,
+    formId: 'show-result',
+    saveAndReloadId: 'update',
+    saveAsNewId: 'savenew',
+    runId: 'run',
+    draftId: 'mobile',
+    jslintId: 'jslint',
+    tidyId: 'tidy',
+    showJsId: 'showjscode',
+    shareSelector: '#share_link_dropdown, #share_embedded_dropdown, #share_result_dropdown',
+    favId: 'mark_favourite',
+    entriesSelector: 'textarea',
+    resultLabel: 'result_label',
+    resultInput: 'select_link',
+    collaborateId: 'collaborate',
+    example_id: false,
+    exampleURL: '',
+    exampleSaveURL: '',
+    loadDependenciesURL: '',
+    tidy: {
+      'javascript': 'js',
+      'javascript 1.7': 'js',
+      'html': 'html',
+      'css': 'css'
+    },
+    jslint: {
+      evil: true,
+      passfail: false,
+      browser: true,
+      newcap: false
+    },
+    jslintLanguages: ['text/javascript', 'javascript', 'javascript 1.7'],
+    showJSLanguages: ['text/coffeescript', 'coffeescript']
+  },
+  /*
+   * Assign actions
+   */
+  initialize: function(options) {
+    this.setOptions(options);
+    var addBound = function(el, callback, bind) {
+      el = $(el)[0]; // jordan added [0] for jquery
+      if (el){
+        el.addEvent('click', callback.bind(bind));
+      }
+    };
+
+    Layout.addEvent('ready', function() {
+      addBound(this.options.saveAndReloadId, this.saveAndReload, this);
+      addBound(this.options.saveAsNewId, this.saveAsNew, this);
+      addBound(this.options.runId, this.run, this);
+      addBound(this.options.draftId, this.run, this);
+      addBound(this.options.jslintId, this.jsLint, this);
+      addBound(this.options.showJsId, this.showJs, this);
+      addBound(this.options.tidyId, this.prepareAndLaunchTidy, this);
+      addBound(this.options.favId, this.makeFavourite, this);
+      // addBound(this.options.collaborateId, this.launchTowtruck, this);
+
+      // show key shortcuts
+      var keyActions = document.getElements('a.keyActions');
+      keyActions.addEvents({
+        click: function(event){
+          this.showShortcutDialog(event);
+        }.bind(this)
+      });
+      document.id(document.body).addEvents({
+        keydown: function(event){
+          if (event.shift && event.key === '/'){
+            var elType = new Element(event.target);
+            if (elType.get('tag') === 'body'){
+              keyActions[0].fireEvent('click');
+            }
+          }
+        }
+      });
+
+      var share = $$(this.options.shareSelector);
+      if (share.length > 0) {
+        share.addEvent('click', function() {
+          this.select();
+        });
+      }
+
+      // actions run if shell loaded
+      this.form = document.id(this.options.formId);
+
+      if (this.options.exampleURL) {
+        //  this.run();
+        this.displayExampleURL();
+      }
+      // assign change language in panel
+      $$('.panelChoice').addEvent('change', this.switchLanguageAction.bind(this));
+      this.showHideJsLint();
+      this.showHideTidyUp();
+      this.showHideShowJs();
+    }.bind(this));
+  },
+
+  switchLanguageAction: function(e) {
+    if (!e) return;
+    var sel = $(e.target);
+    this.switchLanguage(sel);
+  },
+
+  /*
+   * Change language in panel
+   */
+  switchLanguage: function(sel) {
+    var panel_name = sel.get('data-panel'),
+        editorClass = Layout.editors[panel_name],
+        // Klass = MooShellEditor[panel_name.toUpperCase()],
+        language = sel.getElement('option:selected').get('text'),
+        type = sel.getElement('option:selected').get('data-mime-type');
+
+    editorClass.editor.setOption('mode', type);
+    // editorClass.updateCode();
+
+    // editor.getWindow().getElement('.CodeMirror-wrapping').destroy();
+    // Layout.editors[panel_name] = editor = false;
+    // new Klass($(sel.get('data-panel_id')), {
+    //   language: language.toLowerCase()
+    // });
+
+    Layout.editors[panel_name].setLabelName(language);
+    window['panel_' + panel_name] = language.toLowerCase();
+    this.showHideTidyUp();
+    this.showHideJsLint();
+    this.showHideShowJs();
+
+    Track.ui('Switch language: ' + language);
+  },
+
+  loadAsset: function(check, file, callback, scope) {
+    if (!check()) {
+      if (scope){
+        callback = callback.bind(scope);
+      }
+
+      Asset.javascript(file, {
+        onload: callback
+      });
+      return true;
+    }
+  },
+
+  prepareCoffee: function(callback) {
+    return this.loadAsset(function() {
+      return $defined(window.CoffeeScript);
+    }, '/js/coffeescript/coffeescript.js', callback, this);
+  },
+
+  showJs: function(e) {
+    if (e) e.stop();
+    if (this.prepareCoffee(this.showJs, this)) return;
+    var html = '<div class="modalWrap modal_Coffee">' +
+      '<div class="modalHeading"><h3>JavaScript Code</h3><span class="close">Close window</span></div>'+
+      '<div id="" class="modalBody">',
+      jscode, coffeecode;
+
+    if (panel_js != 'coffeescript') return;
+    coffeecode = Layout.editors.js.editor.getValue();
+    try {
+      jscode = CoffeeScript.compile(coffeecode);
+      html += '<pre>' + jscode + '</pre>';
+    } catch(error) {
+      html += '<p class="error">' + error + '</p>';
+    }
+    html += '</div></div>';
+    new StickyWin({
+      content: html,
+      relativeTo: $(document.body),
+      position: 'center',
+      edge: 'center',
+      closeClassName: 'close',
+      draggable: true,
+      dragHandleSelector: 'h3',
+      closeOnEsc: true,
+      destroyOnClose: true,
+      allowMultiple: false,
+      onDisplay: this.showModalFx
+    }).show();
+
+    Track.ui('Show JS');
+  },
+
+  prepareTidyUp: function(callback, scope) {
+    //return this.loadAsset(function() {
+    //  return $defined(window.Beautifier);
+    //}, '/js/beautifier.js', callback, scope);
+  },
+
+  showHideShowJs: function() {
+    var show = false,
+        showjs = $(this.options.showJsId)[0]; // jordan
+
+    if (showjs){
+      show = (Layout.editors.js.editor.getOption('mode').contains('coffeescript'));
+      if (show) {
+        showjs.getParent('li').show();
+      } else {
+        showjs.getParent('li').hide();
+      }
+    }
+  },
+
+  showHideJsLint: function() {
+
+    var hide = true,
+        lint = $(this.options.jslintId)[0]; // jordan added [0] for jquery
+
+    if (!lint) return;
+    Layout.editors.each(function(w){
+      if (this.options.jslintLanguages.contains(w.editor.getOption('mode'))) {
+        hide = false;
+      }
+    }, this);
+    if (hide) {
+      lint.getParent('li').hide();
+    } else {
+      lint.getParent('li').show();
+    }
+  },
+
+  showHideTidyUp: function() {
+/*
+    if (this.prepareTidyUp(this.showHideTidyUp, this)) return;
+    var hide = true,
+        tidy = $(this.options.tidyId);
+
+    if (!tidy) return;
+    Layout.editors.each(function(w){
+      language = this.options.tidy[w.options.language];
+      if (language && Beautifier[language]) {
+        hide = false;
+      }
+    }, this);
+    if (hide) {
+      tidy.getParent('li').hide();
+    } else {
+      tidy.getParent('li').show();
+    }
+*/
+  },
+
+  prepareAndLaunchTidy: function(e) {
+    e.stop();
+    if (this.prepareTidyUp(this.makeTidy.bind(this))) return;
+    this.makeTidy();
+  },
+
+  makeTidy: function(){
+/*
+    Layout.editors.each(function(editorInstance){
+      var code = editorInstance.editor.getValue(), language;
+      if (code) {
+        language = this.options.tidy[editorInstance.options.language];
+        if (language && Beautifier[language]) {
+          var fixed = Beautifier[language](code);
+          if (fixed) editorInstance.editor.setValue(fixed);
+          else editorInstance.editor.reindent();
+        }
+      }
+    }, this);
+*/
+  },
+
+  jsLint: function(e) {
+    e.stop();
+    if (JSHINT){
+      return this.JSLintValidate();
+      Track.ui('Validate JavaScript');
+    }
+    // if (!window.JSLINT) {
+    //   // never happens as apparently JSLINT needs to be loaded before MooTools
+    //   Asset.javascript('/js/jslint.min.js', {
+    //     onload: this.JSLintValidate.bind(this)
+    //   });
+    // } else {
+    //   return this.JSLintValidate();
+    // }
+  },
+
+  JSLintValidate: function() {
+    var editor = Layout.editors.js.editor;
+    var html = '<div class="modalWrap modal_jslint">' +
+      '<div class="modalHeading"><h3>JSLint {title}</h3><span class="close">Close window</span></div>'+
+      '<div class="modalBody">{content}</div></div>';
+    var sticky = function(subs){
+      return new StickyWin({
+        content: html.substitute(subs),
+        relativeTo: $(document.body),
+        position: 'center',
+        edge: 'center',
+        closeClassName: 'close',
+        draggable: true,
+        dragHandleSelector: 'h3',
+        closeOnEsc: true,
+        destroyOnClose: true,
+        allowMultiple: false,
+        onDisplay: this.showModalFx
+      }).show();
+    };
+
+    if (this.options.jslintLanguages.contains(panel_js)){
+      var editorValue = editor.getValue();
+
+      // clear all markers from the gutter, we'll highlight errors again in the next step
+      for (var line = 0; editor.lineCount() >= line; line++){
+        editor.setGutterMarker(line, 'note-gutter', null);
+      }
+
+      if (editorValue.trim() === ''){
+        sticky.call(this, {
+          title: 'Valid!',
+          content: '<p>Good work! Your JavaScript code is perfectly valid.</p>'
+        });
+      } else {
+        if (JSHINT(editorValue)){
+          sticky.call(this, {
+            title: 'Valid!',
+            content: '<p>Good work! Your JavaScript code is perfectly valid.</p>'
+          });
+        } else {
+          Array.each(JSHINT.errors, function(error, index){
+            errorEl = Element('span', {
+              'class': 'CodeMirror-line-error',
+              'data-title': error.reason,
+              'text': '●'
+            });
+            editor.setGutterMarker(error.line - 1, 'note-gutter', errorEl);
+          }, this);
+        }
+      }
+    } else {
+      sticky.call(this, {
+        title: 'Sorry No JavaScript!',
+        content: '<p>You\'re using ' + panel_js + '</p>'
+      });
+    }
+  },
+
+  // mark shell as favourite
+  makeFavourite: function(e) {
+    e.stop();
+    new Request.JSON({
+      'url': makefavouritepath,
+      'data': {shell_id: this.options.example_id},
+      'onSuccess': function(response) {
+
+        // #TODO: reload page after successful save
+        window.location.href = response.url;
+        //$('mark_favourite').addClass('isFavourite').getElements('span')[0].set('text', 'Base');
+      }
+    }).send();
+    Track.ui('Mark as favourite');
+  },
+
+  launchTowtruck: function(event){
+    if (event){
+      event.stop();
+    }
+    TowTruck(this);
+    Track.ui('Launch TowTruck');
+  },
+
+  // save and create new pastie
+  saveAsNew: function(e) {
+    e.stop();
+
+    // reset change state so the confirmation doesn't appear on saving
+    window.editorsModified = false;
+    Layout.updateFromMirror();
+    $('id_slug').value='';
+    $('id_version').value='0';
+    new Request.JSON({
+      'url': this.options.exampleSaveUrl,
+      'onSuccess': function(json) {
+        Layout.decodeEditors();
+        if (!json.error) {
+
+          // reload page after successful save
+          window.location = json.pastie_url_relative;
+        } else {
+          alert('ERROR: ' + json.error);
+        }
+      }
+    }).send(this.form);
+
+    Track.ui('Save as new fiddle');
+  },
+
+  // update existing (create shell with new version)
+  saveAndReload: function(e) {
+    if (e) e.stop();
+
+    // reset change state so the confirmation doesn't appear on updating
+    window.editorsModified = false;
+    Layout.updateFromMirror();
+    new Request.JSON({
+      'url': this.options.exampleSaveUrl,
+      'onSuccess': function(json) {
+
+        // reload page after successful save
+        Layout.decodeEditors();
+        window.location = json.pastie_url_relative;
+      }
+    }).send(this.form);
+
+    Track.ui('Update fiddle');
+  },
+
+  // run - submit the form (targets to the iframe)
+  run: function(e) {
+    var draftonly = false;
+    if (e) e.stop();
+    if (e && ($(e.target).getParent().get('id') === 'mobile' || $(e.target).get('id') === 'mobile')) {
+      draftonly = new Element('input', {
+        'hidden': true,
+        'name': 'draftonly',
+        'id': 'draftonly',
+        'value': true
+      });
+      draftonly.inject(this.form);
+    }
+    Layout.updateFromMirror();
+    this.form.submit();
+    if (draftonly) {
+      draftonly.destroy();
+    }
+    this.fireEvent('run');
+
+    Track.ui('Run fiddle');
+  },
+
+  loadDraft: function(e) {
+    if (e) e.stop();
+    if (username) {
+      window.open('/draft/', 'jsfiddle_draft');
+    } else {
+      window.location = '/user/login/';
+    }
+
+    Track.ui('Load draft');
+  },
+
+  // This is a method to be called by keyboard shortcut
+  toggleSidebar: function(e) {
+     if (e) e.stop();
+     Layout.sidebar.toggle();
+
+     Track.ui('Toggle sidebar');
+  },
+
+  showShortcutDialog: function(e) {
+    if (e) e.stop();
+    var html = '<div class="modalWrap modal_kbd">' +
+                '<div class="modalHeading"><h3>Keyboard shortcuts</h3><span class="close">Close window</span></div>'+
+                '<div id="kbd" class="modalBody">' +
+                '<ul>' +
+                '<li><kbd>CTRL</kbd> + <kbd>Return</kbd> <span>Run fiddle</span></li>' +
+                '<li><kbd>CTRL</kbd> + <kbd>S</kbd> <span>Save fiddle (Save or Update)</span></li>' +
+                '<li><kbd>CTRL</kbd> + <kbd>Shift</kbd> + <kbd>Return</kbd> <span>Load draft</span></li>' +
+                // '<li><kbd>Control</kbd> + <kbd>&uarr;</kbd> or <kbd>Control</kbd> + <kbd>&darr;</kbd> <span>Switch editor windows</span></li>' +
+                '<li><kbd>CTRL</kbd> + <kbd>Shift</kbd> + <kbd>&uarr;</kbd> <span>Toggle sidebar</span></li>' +
+                '<li><kbd>CTRL</kbd> + <kbd>K</kbd> <span>Collaboration with TowTruck (very Alpha, don\'t rely on it too much)</span></li>' +
+                '</ul>' +
+                '</div></div>';
+
+    new StickyWin({
+      content: html,
+      relativeTo: $(document.body),
+      position: 'center',
+      edge: 'center',
+      closeClassName: 'close',
+      draggable: true,
+      dragHandleSelector: 'h3',
+      closeOnEsc: true,
+      destroyOnClose: true,
+      allowMultiple: false,
+      onDisplay: this.showModalFx
+    }).show();
+
+    Track.ui('Show shortcuts modal');
+  },
+
+  showModalFx: function(){
+      $$('.modalWrap')[0].addClass('show');
+  },
+
+  switchTo: function(index) {
+    Layout.current_editor = Layout.editors_order[index];
+    Layout.editors[Layout.current_editor].editor.focus();
+  },
+
+  switchNext: function() {
+    // find current and switch to the next
+    var index = Layout.editors_order.indexOf(Layout.current_editor);
+    var nextindex = (index + 1) % 3;
+    this.switchTo(nextindex);
+  },
+
+  switchPrev: function() {
+    // find current and switch to previous
+    var index = Layout.editors_order.indexOf(Layout.current_editor);
+    var nextindex = (index - 1) % 3;
+    if (nextindex < 0) nextindex = 2;
+    this.switchTo(nextindex);
+  },
+
+  // rename iframe label to present the current URL
+  displayExampleURL: function() {
+    var resultInput = document.id(this.options.resultInput);
+    if (resultInput) {
+      if (Browser.Engine.gecko) {
+        resultInput.setStyle('padding-top', '4px');
+      }
+      // resultInput.select();
+    }
+  },
+
+  loadLibraryVersions: function(group_id) {
+    if (group_id) {
+      new Request.JSON({
+        url: this.options.loadLibraryVersionsURL.substitute({group_id: group_id}),
+        onSuccess: function(response) {
+          $('js_lib').empty();
+          $('js_dependency').empty();
+          response.libraries.each( function(lib) {
+            new Element('option', {
+              value: lib.id,
+              text: "{group_name} {version}".substitute(lib)
+            }).inject($('js_lib'));
+            if (lib.selected) $('js_lib').set('value',lib.id);
+          });
+          response.dependencies.each(function (dep) {
+            new Element('li', {
+              html: [
+                "<input id='dep_{id}' type='checkbox' name='js_dependency[{id}]' value='{id}'/>",
+                "<label for='dep_{id}'>{name}</label>"
+                ].join('').substitute(dep)
+            }).inject($('js_dependency'));
+            if (dep.selected) $('dep_'+dep.id).set('checked', true);
+          });
+        }
+      }).send();
+    } else {
+      // XXX: would be good to send an error somehow
+    }
+  },
+
+  loadDependencies: function(lib_id) {
+    if (lib_id) {
+      new Request.JSON({
+        url: this.options.loadDependenciesURL.substitute({lib_id: lib_id}),
+        method: 'get',
+        onSuccess: function(response) {
+          $('js_dependency').empty();
+          response.each(function (dep) {
+            new Element('li', {
+              html: [
+                "<input id='dep_{id}' type='checkbox' name='js_dependency[{id}]' value='{id}'/>",
+                "<label for='dep_{id}'>{name}</label>"
+                ].join('').substitute(dep)
+            }).inject($('js_dependency'));
+            if (dep.selected) $('dep_'+dep.id).set('checked', true);
+          });
+        }
+      }).send();
+    } else {
+      // XXX: would be good to send an error somehow
+    }
+  }
+});
+
+/**
+*
+*  Base64 encode / decode
+*  http://www.webtoolkit.info/
+*
+**/
+
+var Base64 = {
+
+  // private property
+  _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
+
+  // public method for encoding
+  encode : function (input) {
+    var output = "";
+    input = input || "";
+    var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
+    var i = 0;
+
+    input = Base64._utf8_encode(input);
+
+    while (i < input.length) {
+
+      chr1 = input.charCodeAt(i++);
+      chr2 = input.charCodeAt(i++);
+      chr3 = input.charCodeAt(i++);
+
+      enc1 = chr1 >> 2;
+      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
+      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
+      enc4 = chr3 & 63;
+
+      if (isNaN(chr2)) {
+        enc3 = enc4 = 64;
+      } else if (isNaN(chr3)) {
+        enc4 = 64;
+      }
+
+      output = output +
+      this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
+      this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
+
+    }
+
+    return output;
+  },
+
+  // public method for decoding
+  decode : function (input) {
+    var output = "";
+    var chr1, chr2, chr3;
+    var enc1, enc2, enc3, enc4;
+    var i = 0;
+
+    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
+
+    while (i < input.length) {
+
+      enc1 = this._keyStr.indexOf(input.charAt(i++));
+      enc2 = this._keyStr.indexOf(input.charAt(i++));
+      enc3 = this._keyStr.indexOf(input.charAt(i++));
+      enc4 = this._keyStr.indexOf(input.charAt(i++));
+
+      chr1 = (enc1 << 2) | (enc2 >> 4);
+      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
+      chr3 = ((enc3 & 3) << 6) | enc4;
+
+      output = output + String.fromCharCode(chr1);
+
+      if (enc3 != 64) {
+        output = output + String.fromCharCode(chr2);
+      }
+      if (enc4 != 64) {
+        output = output + String.fromCharCode(chr3);
+      }
+
+    }
+
+    output = Base64._utf8_decode(output);
+
+    return output;
+
+  },
+
+  // private method for UTF-8 encoding
+  _utf8_encode : function (string) {
+    var utftext = "";
+    string = string.replace(/\r\n/g,"\n");
+
+    for (var n = 0; n < string.length; n++) {
+
+      var c = string.charCodeAt(n);
+
+      if (c < 128) {
+        utftext += String.fromCharCode(c);
+      }
+      else if((c > 127) && (c < 2048)) {
+        utftext += String.fromCharCode((c >> 6) | 192);
+        utftext += String.fromCharCode((c & 63) | 128);
+      }
+      else {
+        utftext += String.fromCharCode((c >> 12) | 224);
+        utftext += String.fromCharCode(((c >> 6) & 63) | 128);
+        utftext += String.fromCharCode((c & 63) | 128);
+      }
+
+    }
+    return utftext;
+  },
+
+  // private method for UTF-8 decoding
+  _utf8_decode : function (utftext) {
+    var string = "";
+    var i = 0;
+    var c = c1 = c2 = 0;
+
+    while ( i < utftext.length ) {
+
+      c = utftext.charCodeAt(i);
+
+      if (c < 128) {
+        string += String.fromCharCode(c);
+        i++;
+      }
+      else if((c > 191) && (c < 224)) {
+        c2 = utftext.charCodeAt(i+1);
+        string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
+        i += 2;
+      }
+      else {
+        c2 = utftext.charCodeAt(i+1);
+        c3 = utftext.charCodeAt(i+2);
+        string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
+        i += 3;
+      }
+
+    }
+
+    return string;
+  }
+
+};
+
+var Dropdown = new Class({
+
+  initialize: function(){
+    this.dropdown = {
+      cont: document.getElements('.dropdownCont'),
+      trigger: document.getElements('.dropdown a.aiButton')
+    };
+
+    this.setDefaults();
+  },
+
+  setDefaults: function(){
+    this.dropdown.cont.fade('hide');
+    this.dropdown.cont.set('tween', {
+      duration: 200
+    });
+
+    this.dropdown.trigger.each(function(trigger){
+      trigger.addEvents({
+        click: this.toggle.bindWithEvent(trigger, this)
+      });
+    }, this);
+
+    $(document.body).addEvents({
+      click: function(e){
+        if (!$(e.target).getParent('.dropdownCont')){
+          this.hide();
+          // this.dropdown.trigger.getElement('span').removeClass('selected')
+        }
+      }.bind(this)
+    });
+  },
+
+  toggle: function(event, parent){
+    var trigger = Element(event.target);
+    event.stop();
+    parent.dropdown.cont.fade('out');
+    // trigger.removeClass('selected')
+
+    if (this.getNext('.dropdownCont').getStyles('opacity')['opacity'] === 0){
+      this.getNext('.dropdownCont').fade('in');
+      // trigger.addClass('selected');
+    }
+  },
+
+  hide: function(){
+    this.dropdown.cont.fade('out');
+  }
+});
+
+// mootools events don't work with beforeunload for some reason
+window.onbeforeunload = function(){
+  if (window.editorsModified){
+    return "You've modified your fiddle, reloading the page will reset all changes."
+  }
+};
diff --git a/plugins/code_editor/static/js/EditorCM.js b/plugins/code_editor/static/js/EditorCM.js
new file mode 100644 (file)
index 0000000..0c5f98e
--- /dev/null
@@ -0,0 +1,345 @@
+/*
+ Class: MooshellEditor
+ Editor using CodeMirror
+ http://codemirror.net
+ */
+
+// jordan
+var codemirrorpath = "";
+// end jorda
+
+var disallowedPlatforms = ['ios', 'android', 'ipod'];
+var default_code_mirror_options = {
+  gutters: ["note-gutter", "CodeMirror-linenumbers"],
+  tabSize: 4,
+  indentUnit: 4,
+  matchBrackets: true,
+  lineNumbers: true,
+  lineWrapping: true,
+  tabMode: 'spaces' // or 'shift'
+};
+
+var MooShellEditor = new Class({
+  Implements: [Options, Events],
+
+  parameter: 'Editor',
+
+  options: {
+    useCodeMirror: true,
+    codeMirrorOptions: default_code_mirror_options,
+    syntaxHighlighting: []
+  },
+
+  window_names: {
+    'javascript': 'JavaScript',
+    'html': 'HTML',
+    'css': 'CSS',
+    'scss': 'SCSS',
+    'coffeescript': 'CoffeeScript',
+    'javascript 1.7': 'JavaScript 1.7'
+  },
+
+  initialize: function(el, options) {
+    this.validationTooltip;
+
+    // switch off CodeMirror for IE
+    //if (Browser.Engine.trident) options.useCodeMirror = false;
+    this.element = $(el)[0]; // jordan added [0] for jquery
+    if (!this.options.syntaxHighlighting.contains(options.language)) {
+      this.forceDefaultCodeMirrorOptions();
+    }
+    this.setOptions(options);
+    var is_disallowed = (disallowedPlatforms.contains(Browser.Platform.name));
+    if (this.options.useCodeMirror && !is_disallowed) {
+      // hide textarea
+      this.element.hide();
+      // prepare settings
+      if (!this.options.codeMirrorOptions.stylesheet && this.options.stylesheet) {
+        this.options.codeMirrorOptions.stylesheet = this.options.stylesheet.map(function(path) {
+          return mediapath + path;
+        });
+      }
+      if (!this.options.codeMirrorOptions.path) {
+        this.options.codeMirrorOptions.path = codemirrorpath + 'js/';
+      }
+      if (!this.options.codeMirrorOptions.content) {
+        this.options.codeMirrorOptions.content = this.element.get('value');
+      }
+
+      var parentNode = this.element.getParent();
+      var options = { value: this.element.value };
+      options = Object.append(options, this.options.codeMirrorOptions);
+      this.editor = CodeMirror(parentNode, options);
+
+      // run this after initialization
+      if (!this.options.codeMirrorOptions.initCallback){
+        if (this.options.codeMirrorOptions.autofocus) {
+          // set current editor
+          Layout.current_editor = this.options.name;
+        }
+      }
+
+      // set editor options that can only be set once the editor is initialized
+      var cur = this.editor.getLineHandle(this.editor.getCursor().line);
+      this.setEditorEvents({
+        focus: function(){
+          Layout.current_editor = this.options.name;
+          // this.editor.removeLineClass(cur, 'background', 'activeline');
+          // this.editor.hlLine = this.editor.addLineClass(0, "background", "activeline");
+        },
+        cursorActivity: function(){
+          // var cur = this.editor.getLineHandle(this.editor.getCursor().line);
+          // if (cur != this.editor.hlLine) {
+          //   this.editor.removeLineClass(this.editor.hlLine, 'background', 'activeline');
+          //   this.editor.hlLine = this.editor.addLineClass(cur, 'background', 'activeline');
+          // }
+        },
+        blur: function(){
+          // this.editor.removeLineClass(this.editor.hlLine, 'background', 'activeline');
+        },
+        change: function(){
+          this.validateEditorInput.call(this, parentNode);
+          window.editorsModified = true;
+        }.bind(this)
+      });
+
+      // disable new line insertion when saving fiddle
+      CodeMirror.keyMap.default['Ctrl-Enter'] = function(){
+        return false;
+      };
+
+      // don't let Emmet capture this
+      delete CodeMirror.keyMap.default['Cmd-L'];
+    }
+
+    this.editorLabelFX = new Fx.Tween(this.getLabel(), {
+      property: 'opacity',
+      link: 'cancel'
+    });
+
+    this.getWindow().addEvents({
+      mouseenter: function() {
+        this.editorLabelFX.start(0);
+      }.bind(this),
+      mouseleave: function() {
+        this.editorLabelFX.start(0.8);
+      }.bind(this)
+    });
+
+// jordan commented
+//    mooshell.addEvents({
+//      'run': this.b64decode.bind(this)
+//    });
+
+    Layout.registerEditor(this);
+    this.setLabelName(this.options.language || this.options.name);
+  },
+
+  validateEditorInput: function(parentNode){
+    var currentValue = this.getCode();
+    var warnings = [];
+
+    // destroy tooltip if it already exists for this editor
+    if (this.validationTooltip){
+      this.validationTooltip.destroy();
+    }
+
+    // create the container
+    this.validationTooltip = Element('ul', {
+      'class': 'warningTooltip'
+    });
+
+    // collect warnings
+    Object.each(this.options.disallowed, function(value, key){
+      if (currentValue.test(key, 'i')){
+        warnings.push('<li>' + value + '</li>');
+      }
+    });
+
+    // inject container
+    this.validationTooltip = this.validationTooltip.inject(parentNode);
+
+    // squash and apply warnings
+    this.validationTooltip.set({
+      html: warnings.join('')
+    });
+  },
+
+  getEditor: function() {
+    return this.editor || this.element;
+  },
+
+  getWindow: function() {
+    if (!this.window) {
+      this.window = this.element.getParent('.window');
+    }
+    return this.window;
+  },
+
+  getLabel: function() {
+    return this.getWindow().getElement('.window_label');
+  },
+
+  b64decode: function() {
+    this.element.set('value', this.before_decode);
+  },
+
+  getCode: function() {
+    return (this.editor) ? this.editor.getValue() : this.element.get('value');
+  },
+
+  updateFromMirror: function() {
+    this.before_decode = this.getCode();
+    this.element.set('value', Base64.encode(this.before_decode));
+  },
+
+  updateCode: function() {
+    this.element.set('value', this.getCode());
+  },
+
+  clean: function() {
+    this.element.set('value', '');
+    this.cleanEditor();
+  },
+
+  cleanEditor: function() {
+    if (this.editor) this.editor.setCode('');
+  },
+
+  hide: function() {
+    this.getWindow().hide();
+  },
+
+  show: function() {
+    this.getWindow().show();
+  },
+
+  setEditorOptions: function(options){
+    Object.each(options, function(fn, key){
+      this.editor.setOption(key, fn.bind(this));
+    }, this);
+  },
+
+  setEditorEvents: function(e){
+    Object.each(e, function(fn, key){
+      this.editor.on(key, fn.bind(this));
+    }, this);
+  },
+
+  setLanguage: function(language) {
+    // Todo: This is hacky
+    this.setLabelName(language);
+  },
+
+  setLabelName: function(language) {
+    this.getLabel().set('text', this.window_names[language] || language);
+  },
+
+  setStyle: function(key, value) {
+    if (this.editor) return $(this.editor.frame).setStyle(key, value);
+    return this.element.setStyle(key, value);
+  },
+
+  setStyles: function(options) {
+    if (this.editor) return $(this.editor.frame).setStyles(options);
+    return this.element.setStyles(options);
+  },
+
+  setWidth: function(width) {
+    this.getWindow().setStyle('width', width);
+  },
+
+  setHeight: function(height) {
+    this.getWindow().setStyle('height', height);
+  },
+
+  getPosition: function() {
+    if (this.editor) return $(this.editor.frame).getPosition();
+    return this.element.getPosition();
+  },
+
+  forceDefaultCodeMirrorOptions: function() {
+    this.options.codeMirrorOptions = default_code_mirror_options;
+  }
+});
+
+
+/*
+ * JS specific settings
+ */
+MooShellEditor.JS = new Class({
+  Extends: MooShellEditor,
+
+  options: {
+    name: 'js',
+    language: 'javascript',
+    useCodeMirror: true,
+    codeMirrorOptions: {
+      autofocus: true,
+      mode: 'javascript'
+    },
+    syntaxHighlighting: ['javascript', 'javascript 1.7'],
+    disallowed: {
+      '<script': "Input plain JavaScript code, no HTML.",
+      'document.write': "<code>document.write</code> is disallowed in JSFiddle envioriment and might break your fiddle."
+    }
+  },
+
+  initialize: function(el, options) {
+    this.setOptions(options);
+    this.parent(el, this.options);
+  }
+});
+
+/*
+ * CSS specific settings
+ */
+MooShellEditor.CSS = new Class({
+  Extends: MooShellEditor,
+
+  options: {
+    name: 'css',
+    language: 'css',
+    useCodeMirror: true,
+    codeMirrorOptions: {
+      mode: 'css'
+    },
+    syntaxHighlighting: ['css', 'scss']
+  },
+
+  initialize: function(el, options) {
+    this.setOptions(options);
+    this.parent(el, this.options);
+  }
+});
+
+/*
+ * HTML specific settings
+ */
+MooShellEditor.HTML = new Class({
+  Extends: MooShellEditor,
+
+  options: {
+    name: 'html',
+    language: 'html',
+    useCodeMirror: true,
+    codeMirrorOptions: {
+      mode: 'xml'
+    },
+    syntaxHighlighting: ['html'],
+    disallowed: {
+      '<html': "No need for the <code>HTML</code> tag, it's already in the output.",
+      '<meta': "No need for the <code>META</code> tags.",
+      '<head*.?>': "No need for the <code>HEAD</code> tag, it's already in the output.",
+      '<doctype': "Select <code>DOCTYPE</code> from the <strong>Info</strong> panel on the left, instead of adding a tag.",
+      '<script/?.*text\/javascript': "For JavaScript use the panel below or the <strong>Resources</strong> panel for external files.",
+      '<link/?.*rel/?.*stylesheet': "For external CSS files use the <strong>Resources</strong> panel on the left.",
+      '<style': "For CSS use the panel on the right.",
+    }
+  },
+
+  initialize: function(el, options) {
+    this.setOptions(options);
+    this.parent(el, this.options);
+  }
+});
diff --git a/plugins/code_editor/static/js/LayoutCM.js b/plugins/code_editor/static/js/LayoutCM.js
new file mode 100644 (file)
index 0000000..8d89aab
--- /dev/null
@@ -0,0 +1,301 @@
+/*
+ Layout using CodeMirror
+ */
+
+Element.implement({
+  getInnerWidth: function() {
+    return this.getSize().x -
+      this.getStyle('padding-left').toInt() -
+      this.getStyle('padding-right').toInt() -
+      this.getStyle('border-left-width').toInt() -
+      this.getStyle('border-right-width').toInt();
+  },
+  getInnerHeight: function() {
+    return this.getSize().y -
+      this.getStyle('padding-top').toInt() -
+      this.getStyle('padding-bottom').toInt() -
+      this.getStyle('border-top-width').toInt() -
+      this.getStyle('border-bottom-width').toInt();
+  }
+});
+
+var keyMods = {
+  'shift': false,
+  'shiftKey': false,
+  'control': false,
+  'ctrlKey': false
+}; // these mods will be checked
+
+var Layout = {
+  editors: $H({}),
+  editors_order: ['html', 'css', 'js'],
+  reservedKeys: [ // list of [modifier,keycode,callbackname]
+    ['ctrlKey', 13, 'run'], ['control', 13, 'run'],   // c+ret+run
+    ['ctrlKey', 38, 'switchPrev'],                    // c+upArrow
+    ['ctrlKey', 40, 'switchNext'],                     // c+dnArrow
+    ['ctrlKey+shiftKey', 13, 'loadDraft'], ['control+shift', 13, 'loadDraft'],
+    ['ctrlKey+shiftKey', 38, 'toggleSidebar'], ['control+shift', 38, 'toggleSidebar'],
+    ['ctrlKey+shiftKey', 76, 'showShortcutDialog'], ['control+shift', 76, 'showShortcutDialog'],
+    ['ctrlKey', 83, 'saveAndReload'], ['control', 83, 'saveAndReload'],
+    ['ctrlKey', 75, 'launchTowtruck'], ['control', 75, 'launchTowtruck']
+    // future
+    // ['ctrlKey', f, 'searchBox'], ['control', f, 'searchBox']
+  ],
+  isMobile: (navigator.userAgent.match(/(iPhone|iPod|iPad)/) ||
+             navigator.userAgent.match(/BlackBerry/) ||
+             navigator.userAgent.match(/Android/)),
+  render: function () {
+    // instantiate sidebar
+//    this.sidebar = new Sidebar({
+//      DOM: 'sidebar'
+//    });
+    window.addEvents({
+      'resize': this.resize.bind(this),
+      'keydown': function(keyEvent) {
+        // console.log(keyEvent)
+        if (this.isReservedKey(false, keyEvent)) {
+          this.routeReservedKey(keyEvent);
+        }
+      }.bind(this)
+    });
+//    this.sidebar.addEvents({
+//      'accordion_resized': this.resize.bind(this)
+//    });
+    // set editor labels
+    var result = document.id('result');
+    $$('.window_label').setStyle('opacity', 0.8);
+    if (result) {
+      result.getElement('.window_label').setStyle('opacity', 0.3);
+      this.result = result.getElement('iframe');
+    }
+    // resize
+    this.resize();
+    this.resize.bind(this).delay(20);
+    // change behaviour for IE
+    if (!Browser.Engine.trident4) {
+      this.createDragInstances();
+    }
+    this.createErrorTooltips();
+    // send an event
+    this.fireEvent('ready');
+    // jordan:
+    this.refreshEditors();
+  },
+
+  createErrorTooltips: function(){
+    var tooltip = Element('span', {
+      'class': 'CodeMirror-error-tooltip'
+    }).inject(document.body);
+    document.id('content').addEvents({
+      'mouseover:relay(.CodeMirror-line-error)': function(el){
+        tooltip.set({
+          html: this.get('data-title'),
+          styles: {
+            display: 'block'
+          }
+        });
+        tooltip.position({
+          relativeTo: this,
+          edge: 'centerBottom',
+          offset: {
+            y: -15
+          }
+        });
+      },
+      'mouseout:relay(.CodeMirror-line-error)': function(){
+        tooltip.set({
+          html: '',
+          styles: {
+            top: 0,
+            left: 0,
+            display: 'none'
+          }
+        });
+      }
+    });
+  },
+
+  routeReservedKey: function(keyEvent) {
+    this.reservedKeys.each(function(keyDef){
+      if (this.matchKey(keyEvent, keyDef)) {
+        mooshell[keyDef.getLast()].bind(mooshell).call();
+      }
+    }, this);
+  },
+
+  matchKey: function(keyEvent, keyDef) {
+    if (!keyEvent) return false;
+    var key = keyEvent.keyCode || keyEvent.code;
+    // check if the right key is pressed
+    if (!keyDef.contains(key)) return false;
+    // check for the modifications
+    var pass = true;
+    if (keyDef.length > 1) {
+      var mods = {};
+      keyDef[0].split('+').each(function(mod) {
+        mods[mod] = true;
+      });
+      // adding other mods
+      $each(keyMods, function(value, mod) {
+        if (!mods[mod]) mods[mod] = false;
+      });
+      // check all possibilities
+      $each(mods, function(required, mod) {
+        if (!!keyEvent[mod] != required) pass = false;
+      });
+    }
+    return pass;
+  },
+
+  isReservedKey: function(keyCode, keyEvent) {
+    return (this.reservedKeys.some(function(keyDef) {
+      return this.matchKey(keyEvent, keyDef);
+    }, this));
+  },
+
+  findLayoutElements: function() {
+    // look up some elements, and cache the findings
+    this.content = document.id('content');
+    this.columns = this.content.getChildren('.column');
+    this.windows = this.content.getElements('.window');
+    this.shims = this.content.getElements('.column .shim');
+    this.handlers = $H({
+      'vertical': this.content.getElementById('handler_vertical'),
+      'left': this.columns[0].getElement('.handler_horizontal'),
+      'right': this.columns[1].getElement('.handler_horizontal')
+    });
+  },
+
+  registerEditor: function(editor) {
+    this.editors[editor.options.name] = editor;
+    this.resize();
+  },
+
+  decodeEditors: function() {
+    this.editors.each(function(ed) {
+      ed.b64decode();
+    });
+  },
+
+  updateFromMirror: function() {
+    this.editors.each(function(ed) {
+      ed.updateFromMirror();
+    });
+  },
+
+  cleanMirrors: function() {
+    this.editors.each(function(ed) {
+      ed.clean();
+    });
+  },
+
+  createDragInstances: function() {
+    var onDrag_horizontal = function(h) {
+      var windows = h.getParent().getElements('.window');
+      var top = (h.getPosition(this.content).y + h.getHeight() / 2) / this.content.getHeight() * 100;
+      windows[0].setStyle('height', top + '%');
+      windows[1].setStyle('height', 100 - top + '%');
+      this.refreshEditors();
+    }.bind(this);
+
+    var onDrag_vertical = function(h) {
+      var left = (h.getPosition(this.content).x + h.getWidth() / 2) / this.content.getWidth() * 100;
+      this.columns[0].setStyle('width', left + '%');
+      this.columns[1].setStyle('width', 100 - left + '%');
+    }.bind(this);
+
+    this.handlers.each(function(h) {
+      var isHorizontal = h.hasClass('handler_horizontal');
+      h.dragInstance = new Drag(h, {
+        'modifiers': isHorizontal ? {'x': null, 'y': 'top'} : {'x': 'left', 'y': null},
+        'limit': {
+          'x': [100, this.content.getWidth() - 100],
+          'y': [100, this.content.getHeight() - 100]
+        },
+        'onBeforeStart': function() { this.shims.show(); }.bind(this),
+        'onDrag': isHorizontal ? onDrag_horizontal : onDrag_vertical,
+        'onCancel': function() { this.shims.hide(); }.bind(this),
+        'onComplete': function() { this.shims.hide(); }.bind(this)
+      });
+    }, this);
+
+    // Save window sizes to cookie onUnload.
+    window.addEvent('unload', function() {
+      var sizes = {
+        'w': [],
+        'h': []
+      };
+      this.columns.each(function(col, i) {
+        var width = col.getStyle('width');
+        sizes.w[i] = width.contains('%') ? width : null;
+      });
+      this.windows.each(function(win, i) {
+        var height = win.getStyle('height');
+        sizes.h[i] = height.contains('%') ? height : null;
+      });
+      Cookie.write('window_sizes', JSON.encode(sizes), {'domain': location.host});
+    }.bind(this));
+
+    // Read window sizes from cookie.
+    this.setWindowSizes();
+  },
+
+  setWindowSizes: function(sizes) {
+    // sizes === undefined --> read from cookie
+    // sizes == null/false --> reset sizes + delete cookie
+    // sizes == true       --> use sizes
+    if (typeof sizes === 'undefined') {
+      sizes = Cookie.read('window_sizes');
+      if (sizes) {
+        sizes = JSON.decode(sizes);
+      }
+    }
+    if (sizes) {
+      if ($type(sizes.w) === 'array') {
+        sizes.w.each(function(width, i) {
+          this.columns[i].setStyle('width', width);
+        }, this);
+      }
+      if ($type(sizes.h) == 'array') {
+        sizes.h.each(function(height, i) {
+          this.windows[i].setStyle('height', height);
+        }, this);
+      }
+    } else {
+      this.columns.setStyle('width', null);
+      this.windows.setStyle('height', null);
+      Cookie.dispose('window_sizes', {'domain': location.host});
+    }
+    this.resize();
+  },
+
+  resize: function(e) {
+    if (!this.content) {
+      this.findLayoutElements();
+    }
+
+    var win_size = window.getSize();
+    var av_height = win_size.y -
+      this.columns[0].getPosition().y +
+      this.windows[0].getStyle('top').toInt() +
+      this.windows[1].getStyle('bottom').toInt();
+
+    this.content.setStyle('height', av_height);
+
+    // set handler positions
+    this.handlers.vertical.setStyle('left', this.windows[0].getCoordinates(this.content).right);
+    this.handlers.left.setStyle('top', this.windows[0].getCoordinates(this.content).bottom);
+    this.handlers.right.setStyle('top', this.windows[2].getCoordinates(this.content).bottom);
+
+    this.fireEvent('resize');
+  },
+
+  refreshEditors: function(){
+    Object.each(this.editors, function(editorInstance){
+      editorInstance.editor.refresh();
+    });
+  }
+};
+
+// add events to Layout object
+$extend(Layout, new Events());
diff --git a/plugins/code_editor/static/js/code_editor.js b/plugins/code_editor/static/js/code_editor.js
new file mode 100644 (file)
index 0000000..664bbdc
--- /dev/null
@@ -0,0 +1,433 @@
+/**
+ * Description: CodeEditor plugin
+ * Copyright (c) 2012 UPMC Sorbonne Universite - INRIA
+ * License: GPLv3
+ */
+
+/*
+ * It's a best practice to pass jQuery to an IIFE (Immediately Invoked Function
+ * Expression) that maps it to the dollar sign so it can't be overwritten by
+ * another library in the scope of its execution.
+ */
+
+(function($){
+
+     var default_code_mirror_options = {
+       gutters: ["note-gutter", "CodeMirror-linenumbers"],
+       tabSize: 4,
+       indentUnit: 4,
+       matchBrackets: true,
+       lineNumbers: true,
+       lineWrapping: true,
+       tabMode: 'spaces' // or 'shift'
+     };
+
+    
+    // routing calls
+    jQuery.fn.CodeEditor = function( method ) {
+               if ( methods[method] ) {
+                       return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
+               } else if ( typeof method === 'object' || ! method ) {
+                       return methods.init.apply( this, arguments );
+               } else {
+                       jQuery.error( 'Method ' +  method + ' does not exist on jQuery.CodeEditor' );
+               }    
+    };
+
+    /***************************************************************************
+     * Public methods
+     ***************************************************************************/
+
+    var methods = {
+
+        /**
+         * @brief Plugin initialization
+         * @param options : an associative array of setting values
+         * @return : a jQuery collection of objects on which the plugin is
+         *     applied, which allows to maintain chainability of calls
+         */
+        init : function ( options ) {
+
+            /* Default settings */
+            var options = $.extend( {
+                useCodeMirror: true,
+                codeMirrorOptions: default_code_mirror_options,
+                syntaxHighlighting: []
+            }, options);
+
+            return this.each(function() {
+
+                var $this = $(this);
+
+                /* An object that will hold private variables and methods */
+                var plugin = new CodeEditor(options);
+                $this.data('Manifold', plugin);
+
+                /* Events */
+                $this.on('show.CodeEditor', methods.show);
+
+            }); // this.each
+        }, // init
+
+        /**
+         * @brief Plugin destruction
+         * @return : a jQuery collection of objects on which the plugin is
+         *     applied, which allows to maintain chainability of calls
+         */
+        destroy : function( ) {
+
+            return this.each(function() {
+                var $this = $(this);
+                var hazelnut = $this.data('Manifold');
+
+                // Unbind all events using namespacing
+                $(window).unbind('Manifold');
+
+                // Remove associated data
+                hazelnut.remove();
+                $this.removeData('Manifold');
+            });
+        }, // destroy
+
+        show : function( ) {
+            var $this=$(this);
+            // xxx wtf. why [1] ? would expect 0...
+            if (debug)
+                messages.debug("Hitting suspicious line in hazelnut.show");
+            var oTable = $($('.dataTable', $this)[1]).dataTable();
+            oTable.fnAdjustColumnSizing()
+
+            /* Refresh dataTabeles if click on the menu to display it : fix dataTables 1.9.x Bug */
+            $(this).each(function(i,elt) {
+                if (jQuery(elt).hasClass('dataTables')) {
+                    var myDiv=jQuery('#hazelnut-' + this.id).parent();
+                    if(myDiv.height()==0) {
+                        var oTable=$('#hazelnut-' + this.id).dataTable();
+                        oTable.fnDraw();
+                    }
+                }
+            });
+        } // show
+
+    }; // var methods;
+
+    /***************************************************************************
+     * Plugin object
+     ***************************************************************************/
+
+    function CodeEditor(options)
+    {
+      
+        this.initialize = function() {
+            this.validationTooltip;
+        
+            // switch off CodeMirror for IE
+            //if (Browser.Engine.trident) options.useCodeMirror = false;
+            this.element = $('#' + this.options.plugin_uuid + '-textarea')[0]; // jordan added [0] for jquery
+            if (!this.options.syntaxHighlighting.contains(this.options.language)) {
+                this.forceDefaultCodeMirrorOptions();
+            }
+            //this.setOptions(this.options);
+            var is_disallowed = (disallowedPlatforms.contains(Browser.Platform.name));
+            if (this.options.useCodeMirror && !is_disallowed) {
+                // hide textarea
+                this.element.hide();
+                // prepare settings
+                if (!this.options.codeMirrorOptions.stylesheet && this.options.stylesheet) {
+                    this.options.codeMirrorOptions.stylesheet = this.options.stylesheet.map(function(path) {
+                        return mediapath + path;
+                    });
+                }
+                if (!this.options.codeMirrorOptions.path) {
+                    var codemirrorpath = ''; // jordan
+                    this.options.codeMirrorOptions.path = codemirrorpath + 'js/';
+                }
+                if (!this.options.codeMirrorOptions.content) {
+                    this.options.codeMirrorOptions.content = this.element.get('value');
+                }
+          
+                var parentNode = this.element.getParent();
+                var options = { value: this.element.value };
+                options = Object.append(options, this.options.codeMirrorOptions);
+                this.editor = CodeMirror(parentNode, options);
+          
+                // run this after initialization
+                if (!this.options.codeMirrorOptions.initCallback){
+                    if (this.options.codeMirrorOptions.autofocus) {
+                        // set current editor
+                        Layout.current_editor = this.options.name;
+                    }
+                }
+          
+                // set editor options that can only be set once the editor is initialized
+                var cur = this.editor.getLineHandle(this.editor.getCursor().line);
+                this.setEditorEvents({
+                    focus: function(){
+                        Layout.current_editor = this.options.name;
+                        // this.editor.removeLineClass(cur, 'background', 'activeline');
+                        // this.editor.hlLine = this.editor.addLineClass(0, "background", "activeline");
+                    },
+                    cursorActivity: function(){
+                        // var cur = this.editor.getLineHandle(this.editor.getCursor().line);
+                        // if (cur != this.editor.hlLine) {
+                        //   this.editor.removeLineClass(this.editor.hlLine, 'background', 'activeline');
+                        //   this.editor.hlLine = this.editor.addLineClass(cur, 'background', 'activeline');
+                        // }
+                    },
+                    blur: function(){
+                        // this.editor.removeLineClass(this.editor.hlLine, 'background', 'activeline');
+                    },
+                    change: function(){
+                        this.validateEditorInput.call(this, parentNode);
+                        window.editorsModified = true;
+                    }.bind(this)
+                });
+          
+                // disable new line insertion when saving fiddle
+                CodeMirror.keyMap.default['Ctrl-Enter'] = function(){
+                    return false;
+                };
+        
+                // don't let Emmet capture this
+                delete CodeMirror.keyMap.default['Cmd-L'];
+            }
+        
+            this.editorLabelFX = new Fx.Tween(this.getLabel(), {
+                property: 'opacity',
+                link: 'cancel'
+            });
+        
+            this.getWindow().addEvents({
+                mouseenter: function() {
+                    this.editorLabelFX.start(0);
+                }.bind(this),
+                mouseleave: function() {
+                    this.editorLabelFX.start(0.8);
+                }.bind(this)
+            });
+        
+            // jordan commented
+            //    mooshell.addEvents({
+            //      'run': this.b64decode.bind(this)
+            //    });
+        
+            Layout.registerEditor(this);
+            this.setLabelName(this.options.language || this.options.name);
+        },
+      
+        /**
+         *
+         */
+        this.validateEditorInput = function(parentNode){
+            var currentValue = this.getCode();
+            var warnings = [];
+      
+            // destroy tooltip if it already exists for this editor
+            if (this.validationTooltip){
+                this.validationTooltip.destroy();
+            }
+      
+            // create the container
+            this.validationTooltip = Element('ul', {
+                'class': 'warningTooltip'
+            });
+      
+            // collect warnings
+            Object.each(this.options.disallowed, function(value, key){
+                if (currentValue.test(key, 'i')){
+                    warnings.push('<li>' + value + '</li>');
+                }
+            });
+      
+            // inject container
+            this.validationTooltip = this.validationTooltip.inject(parentNode);
+      
+            // squash and apply warnings
+            this.validationTooltip.set({
+                html: warnings.join('')
+            });
+        },
+      
+        /**
+         *
+         */
+        this.getEditor = function() {
+            return this.editor || this.element;
+        },
+      
+        /**
+         *
+         */
+        this.getWindow = function() {
+            if (!this.window) {
+                this.window = this.element.getParent('.window');
+            }
+            return this.window;
+        },
+      
+        /**
+         *
+         */
+        this.getLabel = function() {
+            return this.getWindow().getElement('.window_label');
+        },
+      
+        /**
+         *
+         */
+        this.b64decode = function() {
+            this.element.set('value', this.before_decode);
+        },
+      
+        /**
+         *
+         */
+        this.getCode = function() {
+            return (this.editor) ? this.editor.getValue() : this.element.get('value');
+        },
+      
+        /**
+         *
+         */
+        this.updateFromMirror = function() {
+            this.before_decode = this.getCode();
+            this.element.set('value', Base64.encode(this.before_decode));
+        },
+      
+        /**
+         *
+         */
+        this.updateCode = function() {
+            this.element.set('value', this.getCode());
+        },
+      
+        /**
+         *
+         */
+        this.clean = function() {
+            this.element.set('value', '');
+            this.cleanEditor();
+        },
+      
+        /**
+         *
+         */
+        this.cleanEditor = function() {
+            if (this.editor) this.editor.setCode('');
+        },
+      
+        /**
+         *
+         */
+        this.hide = function() {
+            this.getWindow().hide();
+        },
+      
+        this.show = function() {
+            this.getWindow().show();
+        },
+      
+        /**
+         *
+         */
+        this.setEditorOptions = function(options){
+            Object.each(options, function(fn, key){
+                this.editor.setOption(key, fn.bind(this));
+            }, this);
+        },
+      
+        /**
+         *
+         */
+        this.setEditorEvents = function(e){
+            Object.each(e, function(fn, key){
+                this.editor.on(key, fn.bind(this));
+            }, this);
+        },
+      
+        /**
+         *
+         */
+        this.setLanguage = function(language) {
+            // Todo: This is hacky
+            this.setLabelName(language);
+        },
+      
+        /**
+         *
+         */
+        this.setLabelName = function(language) {
+            this.getLabel().set('text', this.window_names[language] || language);
+        },
+      
+        /**
+         *
+         */
+        this.setStyle = function(key, value) {
+            if (this.editor) return $(this.editor.frame).setStyle(key, value);
+            return this.element.setStyle(key, value);
+        },
+      
+        /**
+         *
+         */
+        this.setStyles = function(options) {
+            if (this.editor) return $(this.editor.frame).setStyles(options);
+            return this.element.setStyles(options);
+        },
+      
+        /**
+         *
+         */
+        this.setWidth = function(width) {
+            this.getWindow().setStyle('width', width);
+        },
+      
+        /**
+         *
+         */
+        this.setHeight = function(height) {
+            this.getWindow().setStyle('height', height);
+        },
+      
+        /**
+         *
+         */
+        this.getPosition = function() {
+            if (this.editor) return $(this.editor.frame).getPosition();
+            return this.element.getPosition();
+        },
+      
+        /**
+         *
+         */
+        this.forceDefaultCodeMirrorOptions = function() {
+            this.options.codeMirrorOptions = default_code_mirror_options;
+        }
+
+        // BEGIN CONSTRUCTOR
+
+        /* member variables */
+        this.options = options;
+
+        var object = this;
+
+        // adapted from EditorCM.js from jsfiddle.net
+
+        var disallowedPlatforms = ['ios', 'android', 'ipod'];
+
+        this.window_names = {
+          'javascript': 'JavaScript',
+          'html': 'HTML',
+          'css': 'CSS',
+          'scss': 'SCSS',
+          'coffeescript': 'CoffeeScript',
+          'javascript 1.7': 'JavaScript 1.7'
+        };
+
+        this.initialize();
+        // END CONSTRUCTOR
+    } // function CodeEditor
+
+})( jQuery );
+
diff --git a/plugins/code_editor/static/js/moo-clientcide-1.3.js b/plugins/code_editor/static/js/moo-clientcide-1.3.js
new file mode 100644 (file)
index 0000000..793059b
--- /dev/null
@@ -0,0 +1,15425 @@
+
+//This library: http://dev.clientcide.com/depender/build?download=true&version=Clientcide+3.1.0&require=Core%2FBrowser&require=Core%2FClass.Extras&require=Core%2FClass&require=Core%2FCore&require=Core%2FElement.Delegation&require=Core%2FElement.Dimensions&require=Core%2FElement.Event&require=Core%2FElement.Style&require=Core%2FElement&require=Core%2FFx.CSS&require=Core%2FFx.Morph&require=Core%2FFx.Transitions&require=Core%2FFx.Tween&require=Core%2FFx&require=Core%2FRequest.HTML&require=Core%2FRequest.JSON&require=Core%2FRequest&require=Core%2FSlick.Finder&require=Core%2FSlick.Parser&require=Core%2FArray&require=Core%2FEvent&require=Core%2FFunction&require=Core%2FNumber&require=Core%2FObject&require=Core%2FString&require=Core%2FCookie&require=Core%2FDOMReady&require=Core%2FJSON&require=Core%2FSwiff&require=Clientcide%2FBehavior.StickyWin&require=Clientcide%2FCollapsible&require=Clientcide%2FMultipleOpenAccordion&require=Clientcide%2FTabSwapper&require=Clientcide%2FStickyWin.Ajax&require=Clientcide%2FStickyWin.Alert&require=Clientcide%2FStickyWin.Confirm&require=Clientcide%2FStickyWin.Drag&require=Clientcide%2FStickyWin.Fx&require=Clientcide%2FStickyWin.Modal&require=Clientcide%2FStickyWin.UI&require=More%2FElement.Forms&require=More%2FOverText&require=More%2FFx.Accordion&require=More%2FFx.Move&require=More%2FFx.Reveal&require=More%2FFx.Scroll&require=More%2FFx.Slide&require=More%2FKeyboard.Extras&require=More%2FSpinner&require=More%2FMore&require=More%2FRequest.JSONP&require=More%2FRequest.Periodical&require=More%2FArray.Extras&require=More%2FDate.Extras&require=More%2FNumber.Format&require=More%2FURI.Relative&require=More%2FAssets&require=More%2FColor&require=More%2FHash.Cookie
+//Contents: Core:Source/Core/Core.js, Core:Source/Types/Object.js, Core:Source/Types/Array.js, Core:Source/Types/Function.js, Core:Source/Types/Number.js, Core:Source/Types/String.js, Core:Source/Browser/Browser.js, Core:Source/Slick/Slick.Parser.js, Core:Source/Slick/Slick.Finder.js, Core:Source/Element/Element.js, Core:Source/Class/Class.js, Core:Source/Class/Class.Extras.js, Core:Source/Request/Request.js, Core:Source/Utilities/JSON.js, Core:Source/Request/Request.JSON.js, Core:Source/Types/DOMEvent.js, Core:Source/Element/Element.Event.js, Core:Source/Element/Element.Delegation.js, Core:Source/Fx/Fx.js, Core:Source/Element/Element.Style.js, Core:Source/Fx/Fx.CSS.js, Core:Source/Fx/Fx.Morph.js, Core:Source/Utilities/Swiff.js, Core:Source/Fx/Fx.Transitions.js, More:Source/More/More.js, More:Source/Class/Class.Binds.js, More:Source/Class/Class.Occlude.js, Core:Source/Element/Element.Dimensions.js, More:Source/Element/Element.Measure.js, More:Source/Element/Element.Position.js, More:Source/Element/Element.Shortcuts.js, More:Source/Forms/OverText.js, More:Source/Utilities/IframeShim.js, More:Source/Interface/Mask.js, Core:Source/Utilities/DOMReady.js, More:Source/Element/Element.Pin.js, More:Source/Types/Object.Extras.js, Clientcide:Source/Core/Clientcide.js, Clientcide:Source/Core/dbug.js, Clientcide:Source/UI/StyleWriter.js, Clientcide:Source/UI/StickyWin.js, Clientcide:Source/UI/StickyWin.Modal.js, More:Source/Types/String.Extras.js, Clientcide:Source/UI/StickyWin.UI.js, Clientcide:Source/UI/StickyWin.Alert.js, Clientcide:Source/UI/StickyWin.Confirm.js, More:Source/Fx/Fx.Move.js, More:Source/Fx/Fx.Scroll.js, More:Source/Class/Class.Refactor.js, Core:Source/Fx/Fx.Tween.js, Clientcide:Source/UI/StickyWin.Fx.js, More:Source/Types/Array.Extras.js, Core:Source/Request/Request.HTML.js, Clientcide:Source/Layout/TabSwapper.js, More:Source/Element/Element.Forms.js, More:Source/Fx/Fx.Reveal.js, Clientcide:Source/Layout/Collapsible.js, More:Source/Utilities/Table.js, Behavior:Source/Element.Data.js, Behavior:Source/BehaviorAPI.js, Behavior:Source/Behavior.js, More:Source/Drag/Drag.js, More:Source/Drag/Drag.Move.js, Clientcide:Source/UI/StickyWin.Drag.js, Clientcide:Source/Behaviors/Behavior.StickyWin.js, More:Source/Utilities/Color.js, More:Source/Class/Events.Pseudos.js, More:Source/Element/Element.Event.Pseudos.js, More:Source/Element/Element.Event.Pseudos.Keys.js, More:Source/Interface/Keyboard.js, More:Source/Interface/Keyboard.Extras.js, More:Source/Locale/Locale.js, More:Source/Locale/Locale.en-US.Number.js, More:Source/Types/Number.Format.js, More:Source/Request/Request.Periodical.js, More:Source/Request/Request.JSONP.js, More:Source/Types/String.QueryString.js, More:Source/Types/URI.js, More:Source/Types/URI.Relative.js, Core:Source/Utilities/Cookie.js, More:Source/Locale/Locale.en-US.Date.js, More:Source/Types/Date.js, More:Source/Types/Date.Extras.js, More:Source/Fx/Fx.Elements.js, More:Source/Fx/Fx.Accordion.js, More:Source/Types/Hash.js, More:Source/Utilities/Hash.Cookie.js, More:Source/Utilities/Assets.js, More:Source/Interface/Spinner.js, More:Source/Fx/Fx.Slide.js, Clientcide:Source/UI/StickyWin.UI.Pointy.js, Clientcide:Source/UI/StickyWin.PointyTip.js, Clientcide:Source/UI/StickyWin.Ajax.js, Clientcide:Source/Layout/MultipleOpenAccordion.js
+
+// Begin: Source/Core/Core.js
+/*
+---
+
+name: Core
+
+description: The heart of MooTools.
+
+license: MIT-style license.
+
+copyright: Copyright (c) 2006-2012 [Valerio Proietti](http://mad4milk.net/).
+
+authors: The MooTools production team (http://mootools.net/developers/)
+
+inspiration:
+  - Class implementation inspired by [Base.js](http://dean.edwards.name/weblog/2006/03/base/) Copyright (c) 2006 Dean Edwards, [GNU Lesser General Public License](http://opensource.org/licenses/lgpl-license.php)
+  - Some functionality inspired by [Prototype.js](http://prototypejs.org) Copyright (c) 2005-2007 Sam Stephenson, [MIT License](http://opensource.org/licenses/mit-license.php)
+
+provides: [Core, MooTools, Type, typeOf, instanceOf, Native]
+
+...
+*/
+
+(function(){
+
+this.MooTools = {
+       version: '1.4.5',
+       build: 'ab8ea8824dc3b24b6666867a2c4ed58ebb762cf0'
+};
+
+// typeOf, instanceOf
+
+var typeOf = this.typeOf = function(item){
+       if (item == null) return 'null';
+       if (item.$family != null) return item.$family();
+
+       if (item.nodeName){
+               if (item.nodeType == 1) return 'element';
+               if (item.nodeType == 3) return (/\S/).test(item.nodeValue) ? 'textnode' : 'whitespace';
+       } else if (typeof item.length == 'number'){
+               if (item.callee) return 'arguments';
+               if ('item' in item) return 'collection';
+       }
+
+       return typeof item;
+};
+
+var instanceOf = this.instanceOf = function(item, object){
+       if (item == null) return false;
+       var constructor = item.$constructor || item.constructor;
+       while (constructor){
+               if (constructor === object) return true;
+               constructor = constructor.parent;
+       }
+       /*<ltIE8>*/
+       if (!item.hasOwnProperty) return false;
+       /*</ltIE8>*/
+       return item instanceof object;
+};
+
+// Function overloading
+
+var Function = this.Function;
+
+var enumerables = true;
+for (var i in {toString: 1}) enumerables = null;
+if (enumerables) enumerables = ['hasOwnProperty', 'valueOf', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'constructor'];
+
+Function.prototype.overloadSetter = function(usePlural){
+       var self = this;
+       return function(a, b){
+               if (a == null) return this;
+               if (usePlural || typeof a != 'string'){
+                       for (var k in a) self.call(this, k, a[k]);
+                       if (enumerables) for (var i = enumerables.length; i--;){
+                               k = enumerables[i];
+                               if (a.hasOwnProperty(k)) self.call(this, k, a[k]);
+                       }
+               } else {
+                       self.call(this, a, b);
+               }
+               return this;
+       };
+};
+
+Function.prototype.overloadGetter = function(usePlural){
+       var self = this;
+       return function(a){
+               var args, result;
+               if (typeof a != 'string') args = a;
+               else if (arguments.length > 1) args = arguments;
+               else if (usePlural) args = [a];
+               if (args){
+                       result = {};
+                       for (var i = 0; i < args.length; i++) result[args[i]] = self.call(this, args[i]);
+               } else {
+                       result = self.call(this, a);
+               }
+               return result;
+       };
+};
+
+Function.prototype.extend = function(key, value){
+       this[key] = value;
+}.overloadSetter();
+
+Function.prototype.implement = function(key, value){
+       this.prototype[key] = value;
+}.overloadSetter();
+
+// From
+
+var slice = Array.prototype.slice;
+
+Function.from = function(item){
+       return (typeOf(item) == 'function') ? item : function(){
+               return item;
+       };
+};
+
+Array.from = function(item){
+       if (item == null) return [];
+       return (Type.isEnumerable(item) && typeof item != 'string') ? (typeOf(item) == 'array') ? item : slice.call(item) : [item];
+};
+
+Number.from = function(item){
+       var number = parseFloat(item);
+       return isFinite(number) ? number : null;
+};
+
+String.from = function(item){
+       return item + '';
+};
+
+// hide, protect
+
+Function.implement({
+
+       hide: function(){
+               this.$hidden = true;
+               return this;
+       },
+
+       protect: function(){
+               this.$protected = true;
+               return this;
+       }
+
+});
+
+// Type
+
+var Type = this.Type = function(name, object){
+       if (name){
+               var lower = name.toLowerCase();
+               var typeCheck = function(item){
+                       return (typeOf(item) == lower);
+               };
+
+               Type['is' + name] = typeCheck;
+               if (object != null){
+                       object.prototype.$family = (function(){
+                               return lower;
+                       }).hide();
+                       //<1.2compat>
+                       object.type = typeCheck;
+                       //</1.2compat>
+               }
+       }
+
+       if (object == null) return null;
+
+       object.extend(this);
+       object.$constructor = Type;
+       object.prototype.$constructor = object;
+
+       return object;
+};
+
+var toString = Object.prototype.toString;
+
+Type.isEnumerable = function(item){
+       return (item != null && typeof item.length == 'number' && toString.call(item) != '[object Function]' );
+};
+
+var hooks = {};
+
+var hooksOf = function(object){
+       var type = typeOf(object.prototype);
+       return hooks[type] || (hooks[type] = []);
+};
+
+var implement = function(name, method){
+       if (method && method.$hidden) return;
+
+       var hooks = hooksOf(this);
+
+       for (var i = 0; i < hooks.length; i++){
+               var hook = hooks[i];
+               if (typeOf(hook) == 'type') implement.call(hook, name, method);
+               else hook.call(this, name, method);
+       }
+
+       var previous = this.prototype[name];
+       if (previous == null || !previous.$protected) this.prototype[name] = method;
+
+       if (this[name] == null && typeOf(method) == 'function') extend.call(this, name, function(item){
+               return method.apply(item, slice.call(arguments, 1));
+       });
+};
+
+var extend = function(name, method){
+       if (method && method.$hidden) return;
+       var previous = this[name];
+       if (previous == null || !previous.$protected) this[name] = method;
+};
+
+Type.implement({
+
+       implement: implement.overloadSetter(),
+
+       extend: extend.overloadSetter(),
+
+       alias: function(name, existing){
+               implement.call(this, name, this.prototype[existing]);
+       }.overloadSetter(),
+
+       mirror: function(hook){
+               hooksOf(this).push(hook);
+               return this;
+       }
+
+});
+
+new Type('Type', Type);
+
+// Default Types
+
+var force = function(name, object, methods){
+       var isType = (object != Object),
+               prototype = object.prototype;
+
+       if (isType) object = new Type(name, object);
+
+       for (var i = 0, l = methods.length; i < l; i++){
+               var key = methods[i],
+                       generic = object[key],
+                       proto = prototype[key];
+
+               if (generic) generic.protect();
+               if (isType && proto) object.implement(key, proto.protect());
+       }
+
+       if (isType){
+               var methodsEnumerable = prototype.propertyIsEnumerable(methods[0]);
+               object.forEachMethod = function(fn){
+                       if (!methodsEnumerable) for (var i = 0, l = methods.length; i < l; i++){
+                               fn.call(prototype, prototype[methods[i]], methods[i]);
+                       }
+                       for (var key in prototype) fn.call(prototype, prototype[key], key)
+               };
+       }
+
+       return force;
+};
+
+force('String', String, [
+       'charAt', 'charCodeAt', 'concat', 'indexOf', 'lastIndexOf', 'match', 'quote', 'replace', 'search',
+       'slice', 'split', 'substr', 'substring', 'trim', 'toLowerCase', 'toUpperCase'
+])('Array', Array, [
+       'pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift', 'concat', 'join', 'slice',
+       'indexOf', 'lastIndexOf', 'filter', 'forEach', 'every', 'map', 'some', 'reduce', 'reduceRight'
+])('Number', Number, [
+       'toExponential', 'toFixed', 'toLocaleString', 'toPrecision'
+])('Function', Function, [
+       'apply', 'call', 'bind'
+])('RegExp', RegExp, [
+       'exec', 'test'
+])('Object', Object, [
+       'create', 'defineProperty', 'defineProperties', 'keys',
+       'getPrototypeOf', 'getOwnPropertyDescriptor', 'getOwnPropertyNames',
+       'preventExtensions', 'isExtensible', 'seal', 'isSealed', 'freeze', 'isFrozen'
+])('Date', Date, ['now']);
+
+Object.extend = extend.overloadSetter();
+
+Date.extend('now', function(){
+       return +(new Date);
+});
+
+new Type('Boolean', Boolean);
+
+// fixes NaN returning as Number
+
+Number.prototype.$family = function(){
+       return isFinite(this) ? 'number' : 'null';
+}.hide();
+
+// Number.random
+
+Number.extend('random', function(min, max){
+       return Math.floor(Math.random() * (max - min + 1) + min);
+});
+
+// forEach, each
+
+var hasOwnProperty = Object.prototype.hasOwnProperty;
+Object.extend('forEach', function(object, fn, bind){
+       for (var key in object){
+               if (hasOwnProperty.call(object, key)) fn.call(bind, object[key], key, object);
+       }
+});
+
+Object.each = Object.forEach;
+
+Array.implement({
+
+       forEach: function(fn, bind){
+               for (var i = 0, l = this.length; i < l; i++){
+                       if (i in this) fn.call(bind, this[i], i, this);
+               }
+       },
+
+       each: function(fn, bind){
+               Array.forEach(this, fn, bind);
+               return this;
+       }
+
+});
+
+// Array & Object cloning, Object merging and appending
+
+var cloneOf = function(item){
+       switch (typeOf(item)){
+               case 'array': return item.clone();
+               case 'object': return Object.clone(item);
+               default: return item;
+       }
+};
+
+Array.implement('clone', function(){
+       var i = this.length, clone = new Array(i);
+       while (i--) clone[i] = cloneOf(this[i]);
+       return clone;
+});
+
+var mergeOne = function(source, key, current){
+       switch (typeOf(current)){
+               case 'object':
+                       if (typeOf(source[key]) == 'object') Object.merge(source[key], current);
+                       else source[key] = Object.clone(current);
+               break;
+               case 'array': source[key] = current.clone(); break;
+               default: source[key] = current;
+       }
+       return source;
+};
+
+Object.extend({
+
+       merge: function(source, k, v){
+               if (typeOf(k) == 'string') return mergeOne(source, k, v);
+               for (var i = 1, l = arguments.length; i < l; i++){
+                       var object = arguments[i];
+                       for (var key in object) mergeOne(source, key, object[key]);
+               }
+               return source;
+       },
+
+       clone: function(object){
+               var clone = {};
+               for (var key in object) clone[key] = cloneOf(object[key]);
+               return clone;
+       },
+
+       append: function(original){
+               for (var i = 1, l = arguments.length; i < l; i++){
+                       var extended = arguments[i] || {};
+                       for (var key in extended) original[key] = extended[key];
+               }
+               return original;
+       }
+
+});
+
+// Object-less types
+
+['Object', 'WhiteSpace', 'TextNode', 'Collection', 'Arguments'].each(function(name){
+       new Type(name);
+});
+
+// Unique ID
+
+var UID = Date.now();
+
+String.extend('uniqueID', function(){
+       return (UID++).toString(36);
+});
+
+//<1.2compat>
+
+var Hash = this.Hash = new Type('Hash', function(object){
+       if (typeOf(object) == 'hash') object = Object.clone(object.getClean());
+       for (var key in object) this[key] = object[key];
+       return this;
+});
+
+Hash.implement({
+
+       forEach: function(fn, bind){
+               Object.forEach(this, fn, bind);
+       },
+
+       getClean: function(){
+               var clean = {};
+               for (var key in this){
+                       if (this.hasOwnProperty(key)) clean[key] = this[key];
+               }
+               return clean;
+       },
+
+       getLength: function(){
+               var length = 0;
+               for (var key in this){
+                       if (this.hasOwnProperty(key)) length++;
+               }
+               return length;
+       }
+
+});
+
+Hash.alias('each', 'forEach');
+
+Object.type = Type.isObject;
+
+var Native = this.Native = function(properties){
+       return new Type(properties.name, properties.initialize);
+};
+
+Native.type = Type.type;
+
+Native.implement = function(objects, methods){
+       for (var i = 0; i < objects.length; i++) objects[i].implement(methods);
+       return Native;
+};
+
+var arrayType = Array.type;
+Array.type = function(item){
+       return instanceOf(item, Array) || arrayType(item);
+};
+
+this.$A = function(item){
+       return Array.from(item).slice();
+};
+
+this.$arguments = function(i){
+       return function(){
+               return arguments[i];
+       };
+};
+
+this.$chk = function(obj){
+       return !!(obj || obj === 0);
+};
+
+this.$clear = function(timer){
+       clearTimeout(timer);
+       clearInterval(timer);
+       return null;
+};
+
+this.$defined = function(obj){
+       return (obj != null);
+};
+
+this.$each = function(iterable, fn, bind){
+       var type = typeOf(iterable);
+       ((type == 'arguments' || type == 'collection' || type == 'array' || type == 'elements') ? Array : Object).each(iterable, fn, bind);
+};
+
+this.$empty = function(){};
+
+this.$extend = function(original, extended){
+       return Object.append(original, extended);
+};
+
+this.$H = function(object){
+       return new Hash(object);
+};
+
+this.$merge = function(){
+       var args = Array.slice(arguments);
+       args.unshift({});
+       return Object.merge.apply(null, args);
+};
+
+this.$lambda = Function.from;
+this.$mixin = Object.merge;
+this.$random = Number.random;
+this.$splat = Array.from;
+this.$time = Date.now;
+
+this.$type = function(object){
+       var type = typeOf(object);
+       if (type == 'elements') return 'array';
+       return (type == 'null') ? false : type;
+};
+
+this.$unlink = function(object){
+       switch (typeOf(object)){
+               case 'object': return Object.clone(object);
+               case 'array': return Array.clone(object);
+               case 'hash': return new Hash(object);
+               default: return object;
+       }
+};
+
+//</1.2compat>
+
+})();
+
+
+// Begin: Source/Types/Object.js
+/*
+---
+
+name: Object
+
+description: Object generic methods
+
+license: MIT-style license.
+
+requires: Type
+
+provides: [Object, Hash]
+
+...
+*/
+
+(function(){
+
+var hasOwnProperty = Object.prototype.hasOwnProperty;
+
+Object.extend({
+
+       subset: function(object, keys){
+               var results = {};
+               for (var i = 0, l = keys.length; i < l; i++){
+                       var k = keys[i];
+                       if (k in object) results[k] = object[k];
+               }
+               return results;
+       },
+
+       map: function(object, fn, bind){
+               var results = {};
+               for (var key in object){
+                       if (hasOwnProperty.call(object, key)) results[key] = fn.call(bind, object[key], key, object);
+               }
+               return results;
+       },
+
+       filter: function(object, fn, bind){
+               var results = {};
+               for (var key in object){
+                       var value = object[key];
+                       if (hasOwnProperty.call(object, key) && fn.call(bind, value, key, object)) results[key] = value;
+               }
+               return results;
+       },
+
+       every: function(object, fn, bind){
+               for (var key in object){
+                       if (hasOwnProperty.call(object, key) && !fn.call(bind, object[key], key)) return false;
+               }
+               return true;
+       },
+
+       some: function(object, fn, bind){
+               for (var key in object){
+                       if (hasOwnProperty.call(object, key) && fn.call(bind, object[key], key)) return true;
+               }
+               return false;
+       },
+
+       keys: function(object){
+               var keys = [];
+               for (var key in object){
+                       if (hasOwnProperty.call(object, key)) keys.push(key);
+               }
+               return keys;
+       },
+
+       values: function(object){
+               var values = [];
+               for (var key in object){
+                       if (hasOwnProperty.call(object, key)) values.push(object[key]);
+               }
+               return values;
+       },
+
+       getLength: function(object){
+               return Object.keys(object).length;
+       },
+
+       keyOf: function(object, value){
+               for (var key in object){
+                       if (hasOwnProperty.call(object, key) && object[key] === value) return key;
+               }
+               return null;
+       },
+
+       contains: function(object, value){
+               return Object.keyOf(object, value) != null;
+       },
+
+       toQueryString: function(object, base){
+               var queryString = [];
+
+               Object.each(object, function(value, key){
+                       if (base) key = base + '[' + key + ']';
+                       var result;
+                       switch (typeOf(value)){
+                               case 'object': result = Object.toQueryString(value, key); break;
+                               case 'array':
+                                       var qs = {};
+                                       value.each(function(val, i){
+                                               qs[i] = val;
+                                       });
+                                       result = Object.toQueryString(qs, key);
+                               break;
+                               default: result = key + '=' + encodeURIComponent(value);
+                       }
+                       if (value != null) queryString.push(result);
+               });
+
+               return queryString.join('&');
+       }
+
+});
+
+})();
+
+//<1.2compat>
+
+Hash.implement({
+
+       has: Object.prototype.hasOwnProperty,
+
+       keyOf: function(value){
+               return Object.keyOf(this, value);
+       },
+
+       hasValue: function(value){
+               return Object.contains(this, value);
+       },
+
+       extend: function(properties){
+               Hash.each(properties || {}, function(value, key){
+                       Hash.set(this, key, value);
+               }, this);
+               return this;
+       },
+
+       combine: function(properties){
+               Hash.each(properties || {}, function(value, key){
+                       Hash.include(this, key, value);
+               }, this);
+               return this;
+       },
+
+       erase: function(key){
+               if (this.hasOwnProperty(key)) delete this[key];
+               return this;
+       },
+
+       get: function(key){
+               return (this.hasOwnProperty(key)) ? this[key] : null;
+       },
+
+       set: function(key, value){
+               if (!this[key] || this.hasOwnProperty(key)) this[key] = value;
+               return this;
+       },
+
+       empty: function(){
+               Hash.each(this, function(value, key){
+                       delete this[key];
+               }, this);
+               return this;
+       },
+
+       include: function(key, value){
+               if (this[key] == null) this[key] = value;
+               return this;
+       },
+
+       map: function(fn, bind){
+               return new Hash(Object.map(this, fn, bind));
+       },
+
+       filter: function(fn, bind){
+               return new Hash(Object.filter(this, fn, bind));
+       },
+
+       every: function(fn, bind){
+               return Object.every(this, fn, bind);
+       },
+
+       some: function(fn, bind){
+               return Object.some(this, fn, bind);
+       },
+
+       getKeys: function(){
+               return Object.keys(this);
+       },
+
+       getValues: function(){
+               return Object.values(this);
+       },
+
+       toQueryString: function(base){
+               return Object.toQueryString(this, base);
+       }
+
+});
+
+Hash.extend = Object.append;
+
+Hash.alias({indexOf: 'keyOf', contains: 'hasValue'});
+
+//</1.2compat>
+
+
+// Begin: Source/Types/Array.js
+/*
+---
+
+name: Array
+
+description: Contains Array Prototypes like each, contains, and erase.
+
+license: MIT-style license.
+
+requires: Type
+
+provides: Array
+
+...
+*/
+
+Array.implement({
+
+       /*<!ES5>*/
+       every: function(fn, bind){
+               for (var i = 0, l = this.length >>> 0; i < l; i++){
+                       if ((i in this) && !fn.call(bind, this[i], i, this)) return false;
+               }
+               return true;
+       },
+
+       filter: function(fn, bind){
+               var results = [];
+               for (var value, i = 0, l = this.length >>> 0; i < l; i++) if (i in this){
+                       value = this[i];
+                       if (fn.call(bind, value, i, this)) results.push(value);
+               }
+               return results;
+       },
+
+       indexOf: function(item, from){
+               var length = this.length >>> 0;
+               for (var i = (from < 0) ? Math.max(0, length + from) : from || 0; i < length; i++){
+                       if (this[i] === item) return i;
+               }
+               return -1;
+       },
+
+       map: function(fn, bind){
+               var length = this.length >>> 0, results = Array(length);
+               for (var i = 0; i < length; i++){
+                       if (i in this) results[i] = fn.call(bind, this[i], i, this);
+               }
+               return results;
+       },
+
+       some: function(fn, bind){
+               for (var i = 0, l = this.length >>> 0; i < l; i++){
+                       if ((i in this) && fn.call(bind, this[i], i, this)) return true;
+               }
+               return false;
+       },
+       /*</!ES5>*/
+
+       clean: function(){
+               return this.filter(function(item){
+                       return item != null;
+               });
+       },
+
+       invoke: function(methodName){
+               var args = Array.slice(arguments, 1);
+               return this.map(function(item){
+                       return item[methodName].apply(item, args);
+               });
+       },
+
+       associate: function(keys){
+               var obj = {}, length = Math.min(this.length, keys.length);
+               for (var i = 0; i < length; i++) obj[keys[i]] = this[i];
+               return obj;
+       },
+
+       link: function(object){
+               var result = {};
+               for (var i = 0, l = this.length; i < l; i++){
+                       for (var key in object){
+                               if (object[key](this[i])){
+                                       result[key] = this[i];
+                                       delete object[key];
+                                       break;
+                               }
+                       }
+               }
+               return result;
+       },
+
+       contains: function(item, from){
+               return this.indexOf(item, from) != -1;
+       },
+
+       append: function(array){
+               this.push.apply(this, array);
+               return this;
+       },
+
+       getLast: function(){
+               return (this.length) ? this[this.length - 1] : null;
+       },
+
+       getRandom: function(){
+               return (this.length) ? this[Number.random(0, this.length - 1)] : null;
+       },
+
+       include: function(item){
+               if (!this.contains(item)) this.push(item);
+               return this;
+       },
+
+       combine: function(array){
+               for (var i = 0, l = array.length; i < l; i++) this.include(array[i]);
+               return this;
+       },
+
+       erase: function(item){
+               for (var i = this.length; i--;){
+                       if (this[i] === item) this.splice(i, 1);
+               }
+               return this;
+       },
+
+       empty: function(){
+               this.length = 0;
+               return this;
+       },
+
+       flatten: function(){
+               var array = [];
+               for (var i = 0, l = this.length; i < l; i++){
+                       var type = typeOf(this[i]);
+                       if (type == 'null') continue;
+                       array = array.concat((type == 'array' || type == 'collection' || type == 'arguments' || instanceOf(this[i], Array)) ? Array.flatten(this[i]) : this[i]);
+               }
+               return array;
+       },
+
+       pick: function(){
+               for (var i = 0, l = this.length; i < l; i++){
+                       if (this[i] != null) return this[i];
+               }
+               return null;
+       },
+
+       hexToRgb: function(array){
+               if (this.length != 3) return null;
+               var rgb = this.map(function(value){
+                       if (value.length == 1) value += value;
+                       return value.toInt(16);
+               });
+               return (array) ? rgb : 'rgb(' + rgb + ')';
+       },
+
+       rgbToHex: function(array){
+               if (this.length < 3) return null;
+               if (this.length == 4 && this[3] == 0 && !array) return 'transparent';
+               var hex = [];
+               for (var i = 0; i < 3; i++){
+                       var bit = (this[i] - 0).toString(16);
+                       hex.push((bit.length == 1) ? '0' + bit : bit);
+               }
+               return (array) ? hex : '#' + hex.join('');
+       }
+
+});
+
+//<1.2compat>
+
+Array.alias('extend', 'append');
+
+var $pick = function(){
+       return Array.from(arguments).pick();
+};
+
+//</1.2compat>
+
+
+// Begin: Source/Types/Function.js
+/*
+---
+
+name: Function
+
+description: Contains Function Prototypes like create, bind, pass, and delay.
+
+license: MIT-style license.
+
+requires: Type
+
+provides: Function
+
+...
+*/
+
+Function.extend({
+
+       attempt: function(){
+               for (var i = 0, l = arguments.length; i < l; i++){
+                       try {
+                               return arguments[i]();
+                       } catch (e){}
+               }
+               return null;
+       }
+
+});
+
+Function.implement({
+
+       attempt: function(args, bind){
+               try {
+                       return this.apply(bind, Array.from(args));
+               } catch (e){}
+
+               return null;
+       },
+
+       /*<!ES5-bind>*/
+       bind: function(that){
+               var self = this,
+                       args = arguments.length > 1 ? Array.slice(arguments, 1) : null,
+                       F = function(){};
+
+               var bound = function(){
+                       var context = that, length = arguments.length;
+                       if (this instanceof bound){
+                               F.prototype = self.prototype;
+                               context = new F;
+                       }
+                       var result = (!args && !length)
+                               ? self.call(context)
+                               : self.apply(context, args && length ? args.concat(Array.slice(arguments)) : args || arguments);
+                       return context == that ? result : context;
+               };
+               return bound;
+       },
+       /*</!ES5-bind>*/
+
+       pass: function(args, bind){
+               var self = this;
+               if (args != null) args = Array.from(args);
+               return function(){
+                       return self.apply(bind, args || arguments);
+               };
+       },
+
+       delay: function(delay, bind, args){
+               return setTimeout(this.pass((args == null ? [] : args), bind), delay);
+       },
+
+       periodical: function(periodical, bind, args){
+               return setInterval(this.pass((args == null ? [] : args), bind), periodical);
+       }
+
+});
+
+//<1.2compat>
+
+delete Function.prototype.bind;
+
+Function.implement({
+
+       create: function(options){
+               var self = this;
+               options = options || {};
+               return function(event){
+                       var args = options.arguments;
+                       args = (args != null) ? Array.from(args) : Array.slice(arguments, (options.event) ? 1 : 0);
+                       if (options.event) args = [event || window.event].extend(args);
+                       var returns = function(){
+                               return self.apply(options.bind || null, args);
+                       };
+                       if (options.delay) return setTimeout(returns, options.delay);
+                       if (options.periodical) return setInterval(returns, options.periodical);
+                       if (options.attempt) return Function.attempt(returns);
+                       return returns();
+               };
+       },
+
+       bind: function(bind, args){
+               var self = this;
+               if (args != null) args = Array.from(args);
+               return function(){
+                       return self.apply(bind, args || arguments);
+               };
+       },
+
+       bindWithEvent: function(bind, args){
+               var self = this;
+               if (args != null) args = Array.from(args);
+               return function(event){
+                       return self.apply(bind, (args == null) ? arguments : [event].concat(args));
+               };
+       },
+
+       run: function(args, bind){
+               return this.apply(bind, Array.from(args));
+       }
+
+});
+
+if (Object.create == Function.prototype.create) Object.create = null;
+
+var $try = Function.attempt;
+
+//</1.2compat>
+
+
+// Begin: Source/Types/Number.js
+/*
+---
+
+name: Number
+
+description: Contains Number Prototypes like limit, round, times, and ceil.
+
+license: MIT-style license.
+
+requires: Type
+
+provides: Number
+
+...
+*/
+
+Number.implement({
+
+       limit: function(min, max){
+               return Math.min(max, Math.max(min, this));
+       },
+
+       round: function(precision){
+               precision = Math.pow(10, precision || 0).toFixed(precision < 0 ? -precision : 0);
+               return Math.round(this * precision) / precision;
+       },
+
+       times: function(fn, bind){
+               for (var i = 0; i < this; i++) fn.call(bind, i, this);
+       },
+
+       toFloat: function(){
+               return parseFloat(this);
+       },
+
+       toInt: function(base){
+               return parseInt(this, base || 10);
+       }
+
+});
+
+Number.alias('each', 'times');
+
+(function(math){
+       var methods = {};
+       math.each(function(name){
+               if (!Number[name]) methods[name] = function(){
+                       return Math[name].apply(null, [this].concat(Array.from(arguments)));
+               };
+       });
+       Number.implement(methods);
+})(['abs', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'exp', 'floor', 'log', 'max', 'min', 'pow', 'sin', 'sqrt', 'tan']);
+
+
+// Begin: Source/Types/String.js
+/*
+---
+
+name: String
+
+description: Contains String Prototypes like camelCase, capitalize, test, and toInt.
+
+license: MIT-style license.
+
+requires: Type
+
+provides: String
+
+...
+*/
+
+String.implement({
+
+       test: function(regex, params){
+               return ((typeOf(regex) == 'regexp') ? regex : new RegExp('' + regex, params)).test(this);
+       },
+
+       contains: function(string, separator){
+               return (separator) ? (separator + this + separator).indexOf(separator + string + separator) > -1 : String(this).indexOf(string) > -1;
+       },
+
+       trim: function(){
+               return String(this).replace(/^\s+|\s+$/g, '');
+       },
+
+       clean: function(){
+               return String(this).replace(/\s+/g, ' ').trim();
+       },
+
+       camelCase: function(){
+               return String(this).replace(/-\D/g, function(match){
+                       return match.charAt(1).toUpperCase();
+               });
+       },
+
+       hyphenate: function(){
+               return String(this).replace(/[A-Z]/g, function(match){
+                       return ('-' + match.charAt(0).toLowerCase());
+               });
+       },
+
+       capitalize: function(){
+               return String(this).replace(/\b[a-z]/g, function(match){
+                       return match.toUpperCase();
+               });
+       },
+
+       escapeRegExp: function(){
+               return String(this).replace(/([-.*+?^${}()|[\]\/\\])/g, '\\$1');
+       },
+
+       toInt: function(base){
+               return parseInt(this, base || 10);
+       },
+
+       toFloat: function(){
+               return parseFloat(this);
+       },
+
+       hexToRgb: function(array){
+               var hex = String(this).match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/);
+               return (hex) ? hex.slice(1).hexToRgb(array) : null;
+       },
+
+       rgbToHex: function(array){
+               var rgb = String(this).match(/\d{1,3}/g);
+               return (rgb) ? rgb.rgbToHex(array) : null;
+       },
+
+       substitute: function(object, regexp){
+               return String(this).replace(regexp || (/\\?\{([^{}]+)\}/g), function(match, name){
+                       if (match.charAt(0) == '\\') return match.slice(1);
+                       return (object[name] != null) ? object[name] : '';
+               });
+       }
+
+});
+
+
+// Begin: Source/Browser/Browser.js
+/*
+---
+
+name: Browser
+
+description: The Browser Object. Contains Browser initialization, Window and Document, and the Browser Hash.
+
+license: MIT-style license.
+
+requires: [Array, Function, Number, String]
+
+provides: [Browser, Window, Document]
+
+...
+*/
+
+(function(){
+
+var document = this.document;
+var window = document.window = this;
+
+var ua = navigator.userAgent.toLowerCase(),
+       platform = navigator.platform.toLowerCase(),
+       UA = ua.match(/(opera|ie|firefox|chrome|version)[\s\/:]([\w\d\.]+)?.*?(safari|version[\s\/:]([\w\d\.]+)|$)/) || [null, 'unknown', 0],
+       mode = UA[1] == 'ie' && document.documentMode;
+
+var Browser = this.Browser = {
+
+       extend: Function.prototype.extend,
+
+       name: (UA[1] == 'version') ? UA[3] : UA[1],
+
+       version: mode || parseFloat((UA[1] == 'opera' && UA[4]) ? UA[4] : UA[2]),
+
+       Platform: {
+               name: ua.match(/ip(?:ad|od|hone)/) ? 'ios' : (ua.match(/(?:webos|android)/) || platform.match(/mac|win|linux/) || ['other'])[0]
+       },
+
+       Features: {
+               xpath: !!(document.evaluate),
+               air: !!(window.runtime),
+               query: !!(document.querySelector),
+               json: !!(window.JSON)
+       },
+
+       Plugins: {}
+
+};
+
+Browser[Browser.name] = true;
+Browser[Browser.name + parseInt(Browser.version, 10)] = true;
+Browser.Platform[Browser.Platform.name] = true;
+
+// Request
+
+Browser.Request = (function(){
+
+       var XMLHTTP = function(){
+               return new XMLHttpRequest();
+       };
+
+       var MSXML2 = function(){
+               return new ActiveXObject('MSXML2.XMLHTTP');
+       };
+
+       var MSXML = function(){
+               return new ActiveXObject('Microsoft.XMLHTTP');
+       };
+
+       return Function.attempt(function(){
+               XMLHTTP();
+               return XMLHTTP;
+       }, function(){
+               MSXML2();
+               return MSXML2;
+       }, function(){
+               MSXML();
+               return MSXML;
+       });
+
+})();
+
+Browser.Features.xhr = !!(Browser.Request);
+
+// Flash detection
+
+var version = (Function.attempt(function(){
+       return navigator.plugins['Shockwave Flash'].description;
+}, function(){
+       return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version');
+}) || '0 r0').match(/\d+/g);
+
+Browser.Plugins.Flash = {
+       version: Number(version[0] || '0.' + version[1]) || 0,
+       build: Number(version[2]) || 0
+};
+
+// String scripts
+
+Browser.exec = function(text){
+       if (!text) return text;
+       if (window.execScript){
+               window.execScript(text);
+       } else {
+               var script = document.createElement('script');
+               script.setAttribute('type', 'text/javascript');
+               script.text = text;
+               document.head.appendChild(script);
+               document.head.removeChild(script);
+       }
+       return text;
+};
+
+String.implement('stripScripts', function(exec){
+       var scripts = '';
+       var text = this.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, function(all, code){
+               scripts += code + '\n';
+               return '';
+       });
+       if (exec === true) Browser.exec(scripts);
+       else if (typeOf(exec) == 'function') exec(scripts, text);
+       return text;
+});
+
+// Window, Document
+
+Browser.extend({
+       Document: this.Document,
+       Window: this.Window,
+       Element: this.Element,
+       Event: this.Event
+});
+
+this.Window = this.$constructor = new Type('Window', function(){});
+
+this.$family = Function.from('window').hide();
+
+Window.mirror(function(name, method){
+       window[name] = method;
+});
+
+this.Document = document.$constructor = new Type('Document', function(){});
+
+document.$family = Function.from('document').hide();
+
+Document.mirror(function(name, method){
+       document[name] = method;
+});
+
+document.html = document.documentElement;
+if (!document.head) document.head = document.getElementsByTagName('head')[0];
+
+if (document.execCommand) try {
+       document.execCommand("BackgroundImageCache", false, true);
+} catch (e){}
+
+/*<ltIE9>*/
+if (this.attachEvent && !this.addEventListener){
+       var unloadEvent = function(){
+               this.detachEvent('onunload', unloadEvent);
+               document.head = document.html = document.window = null;
+       };
+       this.attachEvent('onunload', unloadEvent);
+}
+
+// IE fails on collections and <select>.options (refers to <select>)
+var arrayFrom = Array.from;
+try {
+       arrayFrom(document.html.childNodes);
+} catch(e){
+       Array.from = function(item){
+               if (typeof item != 'string' && Type.isEnumerable(item) && typeOf(item) != 'array'){
+                       var i = item.length, array = new Array(i);
+                       while (i--) array[i] = item[i];
+                       return array;
+               }
+               return arrayFrom(item);
+       };
+
+       var prototype = Array.prototype,
+               slice = prototype.slice;
+       ['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift', 'concat', 'join', 'slice'].each(function(name){
+               var method = prototype[name];
+               Array[name] = function(item){
+                       return method.apply(Array.from(item), slice.call(arguments, 1));
+               };
+       });
+}
+/*</ltIE9>*/
+
+//<1.2compat>
+
+if (Browser.Platform.ios) Browser.Platform.ipod = true;
+
+Browser.Engine = {};
+
+var setEngine = function(name, version){
+       Browser.Engine.name = name;
+       Browser.Engine[name + version] = true;
+       Browser.Engine.version = version;
+};
+
+if (Browser.ie){
+       Browser.Engine.trident = true;
+
+       switch (Browser.version){
+               case 6: setEngine('trident', 4); break;
+               case 7: setEngine('trident', 5); break;
+               case 8: setEngine('trident', 6);
+       }
+}
+
+if (Browser.firefox){
+       Browser.Engine.gecko = true;
+
+       if (Browser.version >= 3) setEngine('gecko', 19);
+       else setEngine('gecko', 18);
+}
+
+if (Browser.safari || Browser.chrome){
+       Browser.Engine.webkit = true;
+
+       switch (Browser.version){
+               case 2: setEngine('webkit', 419); break;
+               case 3: setEngine('webkit', 420); break;
+               case 4: setEngine('webkit', 525);
+       }
+}
+
+if (Browser.opera){
+       Browser.Engine.presto = true;
+
+       if (Browser.version >= 9.6) setEngine('presto', 960);
+       else if (Browser.version >= 9.5) setEngine('presto', 950);
+       else setEngine('presto', 925);
+}
+
+if (Browser.name == 'unknown'){
+       switch ((ua.match(/(?:webkit|khtml|gecko)/) || [])[0]){
+               case 'webkit':
+               case 'khtml':
+                       Browser.Engine.webkit = true;
+               break;
+               case 'gecko':
+                       Browser.Engine.gecko = true;
+       }
+}
+
+this.$exec = Browser.exec;
+
+//</1.2compat>
+
+})();
+
+
+// Begin: Source/Slick/Slick.Parser.js
+/*
+---
+name: Slick.Parser
+description: Standalone CSS3 Selector parser
+provides: Slick.Parser
+...
+*/
+
+;(function(){
+
+var parsed,
+       separatorIndex,
+       combinatorIndex,
+       reversed,
+       cache = {},
+       reverseCache = {},
+       reUnescape = /\\/g;
+
+var parse = function(expression, isReversed){
+       if (expression == null) return null;
+       if (expression.Slick === true) return expression;
+       expression = ('' + expression).replace(/^\s+|\s+$/g, '');
+       reversed = !!isReversed;
+       var currentCache = (reversed) ? reverseCache : cache;
+       if (currentCache[expression]) return currentCache[expression];
+       parsed = {
+               Slick: true,
+               expressions: [],
+               raw: expression,
+               reverse: function(){
+                       return parse(this.raw, true);
+               }
+       };
+       separatorIndex = -1;
+       while (expression != (expression = expression.replace(regexp, parser)));
+       parsed.length = parsed.expressions.length;
+       return currentCache[parsed.raw] = (reversed) ? reverse(parsed) : parsed;
+};
+
+var reverseCombinator = function(combinator){
+       if (combinator === '!') return ' ';
+       else if (combinator === ' ') return '!';
+       else if ((/^!/).test(combinator)) return combinator.replace(/^!/, '');
+       else return '!' + combinator;
+};
+
+var reverse = function(expression){
+       var expressions = expression.expressions;
+       for (var i = 0; i < expressions.length; i++){
+               var exp = expressions[i];
+               var last = {parts: [], tag: '*', combinator: reverseCombinator(exp[0].combinator)};
+
+               for (var j = 0; j < exp.length; j++){
+                       var cexp = exp[j];
+                       if (!cexp.reverseCombinator) cexp.reverseCombinator = ' ';
+                       cexp.combinator = cexp.reverseCombinator;
+                       delete cexp.reverseCombinator;
+               }
+
+               exp.reverse().push(last);
+       }
+       return expression;
+};
+
+var escapeRegExp = function(string){// Credit: XRegExp 0.6.1 (c) 2007-2008 Steven Levithan <http://stevenlevithan.com/regex/xregexp/> MIT License
+       return string.replace(/[-[\]{}()*+?.\\^$|,#\s]/g, function(match){
+               return '\\' + match;
+       });
+};
+
+var regexp = new RegExp(
+/*
+#!/usr/bin/env ruby
+puts "\t\t" + DATA.read.gsub(/\(\?x\)|\s+#.*$|\s+|\\$|\\n/,'')
+__END__
+       "(?x)^(?:\
+         \\s* ( , ) \\s*               # Separator          \n\
+       | \\s* ( <combinator>+ ) \\s*   # Combinator         \n\
+       |      ( \\s+ )                 # CombinatorChildren \n\
+       |      ( <unicode>+ | \\* )     # Tag                \n\
+       | \\#  ( <unicode>+       )     # ID                 \n\
+       | \\.  ( <unicode>+       )     # ClassName          \n\
+       |                               # Attribute          \n\
+       \\[  \
+               \\s* (<unicode1>+)  (?:  \
+                       \\s* ([*^$!~|]?=)  (?:  \
+                               \\s* (?:\
+                                       ([\"']?)(.*?)\\9 \
+                               )\
+                       )  \
+               )?  \\s*  \
+       \\](?!\\]) \n\
+       |   :+ ( <unicode>+ )(?:\
+       \\( (?:\
+               (?:([\"'])([^\\12]*)\\12)|((?:\\([^)]+\\)|[^()]*)+)\
+       ) \\)\
+       )?\
+       )"
+*/
+       "^(?:\\s*(,)\\s*|\\s*(<combinator>+)\\s*|(\\s+)|(<unicode>+|\\*)|\\#(<unicode>+)|\\.(<unicode>+)|\\[\\s*(<unicode1>+)(?:\\s*([*^$!~|]?=)(?:\\s*(?:([\"']?)(.*?)\\9)))?\\s*\\](?!\\])|(:+)(<unicode>+)(?:\\((?:(?:([\"'])([^\\13]*)\\13)|((?:\\([^)]+\\)|[^()]*)+))\\))?)"
+       .replace(/<combinator>/, '[' + escapeRegExp(">+~`!@$%^&={}\\;</") + ']')
+       .replace(/<unicode>/g, '(?:[\\w\\u00a1-\\uFFFF-]|\\\\[^\\s0-9a-f])')
+       .replace(/<unicode1>/g, '(?:[:\\w\\u00a1-\\uFFFF-]|\\\\[^\\s0-9a-f])')
+);
+
+function parser(
+       rawMatch,
+
+       separator,
+       combinator,
+       combinatorChildren,
+
+       tagName,
+       id,
+       className,
+
+       attributeKey,
+       attributeOperator,
+       attributeQuote,
+       attributeValue,
+
+       pseudoMarker,
+       pseudoClass,
+       pseudoQuote,
+       pseudoClassQuotedValue,
+       pseudoClassValue
+){
+       if (separator || separatorIndex === -1){
+               parsed.expressions[++separatorIndex] = [];
+               combinatorIndex = -1;
+               if (separator) return '';
+       }
+
+       if (combinator || combinatorChildren || combinatorIndex === -1){
+               combinator = combinator || ' ';
+               var currentSeparator = parsed.expressions[separatorIndex];
+               if (reversed && currentSeparator[combinatorIndex])
+                       currentSeparator[combinatorIndex].reverseCombinator = reverseCombinator(combinator);
+               currentSeparator[++combinatorIndex] = {combinator: combinator, tag: '*'};
+       }
+
+       var currentParsed = parsed.expressions[separatorIndex][combinatorIndex];
+
+       if (tagName){
+               currentParsed.tag = tagName.replace(reUnescape, '');
+
+       } else if (id){
+               currentParsed.id = id.replace(reUnescape, '');
+
+       } else if (className){
+               className = className.replace(reUnescape, '');
+
+               if (!currentParsed.classList) currentParsed.classList = [];
+               if (!currentParsed.classes) currentParsed.classes = [];
+               currentParsed.classList.push(className);
+               currentParsed.classes.push({
+                       value: className,
+                       regexp: new RegExp('(^|\\s)' + escapeRegExp(className) + '(\\s|$)')
+               });
+
+       } else if (pseudoClass){
+               pseudoClassValue = pseudoClassValue || pseudoClassQuotedValue;
+               pseudoClassValue = pseudoClassValue ? pseudoClassValue.replace(reUnescape, '') : null;
+
+               if (!currentParsed.pseudos) currentParsed.pseudos = [];
+               currentParsed.pseudos.push({
+                       key: pseudoClass.replace(reUnescape, ''),
+                       value: pseudoClassValue,
+                       type: pseudoMarker.length == 1 ? 'class' : 'element'
+               });
+
+       } else if (attributeKey){
+               attributeKey = attributeKey.replace(reUnescape, '');
+               attributeValue = (attributeValue || '').replace(reUnescape, '');
+
+               var test, regexp;
+
+               switch (attributeOperator){
+                       case '^=' : regexp = new RegExp(       '^'+ escapeRegExp(attributeValue)            ); break;
+                       case '$=' : regexp = new RegExp(            escapeRegExp(attributeValue) +'$'       ); break;
+                       case '~=' : regexp = new RegExp( '(^|\\s)'+ escapeRegExp(attributeValue) +'(\\s|$)' ); break;
+                       case '|=' : regexp = new RegExp(       '^'+ escapeRegExp(attributeValue) +'(-|$)'   ); break;
+                       case  '=' : test = function(value){
+                               return attributeValue == value;
+                       }; break;
+                       case '*=' : test = function(value){
+                               return value && value.indexOf(attributeValue) > -1;
+                       }; break;
+                       case '!=' : test = function(value){
+                               return attributeValue != value;
+                       }; break;
+                       default   : test = function(value){
+                               return !!value;
+                       };
+               }
+
+               if (attributeValue == '' && (/^[*$^]=$/).test(attributeOperator)) test = function(){
+                       return false;
+               };
+
+               if (!test) test = function(value){
+                       return value && regexp.test(value);
+               };
+
+               if (!currentParsed.attributes) currentParsed.attributes = [];
+               currentParsed.attributes.push({
+                       key: attributeKey,
+                       operator: attributeOperator,
+                       value: attributeValue,
+                       test: test
+               });
+
+       }
+
+       return '';
+};
+
+// Slick NS
+
+var Slick = (this.Slick || {});
+
+Slick.parse = function(expression){
+       return parse(expression);
+};
+
+Slick.escapeRegExp = escapeRegExp;
+
+if (!this.Slick) this.Slick = Slick;
+
+}).apply(/*<CommonJS>*/(typeof exports != 'undefined') ? exports : /*</CommonJS>*/this);
+
+
+// Begin: Source/Slick/Slick.Finder.js
+/*
+---
+name: Slick.Finder
+description: The new, superfast css selector engine.
+provides: Slick.Finder
+requires: Slick.Parser
+...
+*/
+
+;(function(){
+
+var local = {},
+       featuresCache = {},
+       toString = Object.prototype.toString;
+
+// Feature / Bug detection
+
+local.isNativeCode = function(fn){
+       return (/\{\s*\[native code\]\s*\}/).test('' + fn);
+};
+
+local.isXML = function(document){
+       return (!!document.xmlVersion) || (!!document.xml) || (toString.call(document) == '[object XMLDocument]') ||
+       (document.nodeType == 9 && document.documentElement.nodeName != 'HTML');
+};
+
+local.setDocument = function(document){
+
+       // convert elements / window arguments to document. if document cannot be extrapolated, the function returns.
+       var nodeType = document.nodeType;
+       if (nodeType == 9); // document
+       else if (nodeType) document = document.ownerDocument; // node
+       else if (document.navigator) document = document.document; // window
+       else return;
+
+       // check if it's the old document
+
+       if (this.document === document) return;
+       this.document = document;
+
+       // check if we have done feature detection on this document before
+
+       var root = document.documentElement,
+               rootUid = this.getUIDXML(root),
+               features = featuresCache[rootUid],
+               feature;
+
+       if (features){
+               for (feature in features){
+                       this[feature] = features[feature];
+               }
+               return;
+       }
+
+       features = featuresCache[rootUid] = {};
+
+       features.root = root;
+       features.isXMLDocument = this.isXML(document);
+
+       features.brokenStarGEBTN
+       = features.starSelectsClosedQSA
+       = features.idGetsName
+       = features.brokenMixedCaseQSA
+       = features.brokenGEBCN
+       = features.brokenCheckedQSA
+       = features.brokenEmptyAttributeQSA
+       = features.isHTMLDocument
+       = features.nativeMatchesSelector
+       = false;
+
+       var starSelectsClosed, starSelectsComments,
+               brokenSecondClassNameGEBCN, cachedGetElementsByClassName,
+               brokenFormAttributeGetter;
+
+       var selected, id = 'slick_uniqueid';
+       var testNode = document.createElement('div');
+
+       var testRoot = document.body || document.getElementsByTagName('body')[0] || root;
+       testRoot.appendChild(testNode);
+
+       // on non-HTML documents innerHTML and getElementsById doesnt work properly
+       try {
+               testNode.innerHTML = '<a id="'+id+'"></a>';
+               features.isHTMLDocument = !!document.getElementById(id);
+       } catch(e){};
+
+       if (features.isHTMLDocument){
+
+               testNode.style.display = 'none';
+
+               // IE returns comment nodes for getElementsByTagName('*') for some documents
+               testNode.appendChild(document.createComment(''));
+               starSelectsComments = (testNode.getElementsByTagName('*').length > 1);
+
+               // IE returns closed nodes (EG:"</foo>") for getElementsByTagName('*') for some documents
+               try {
+                       testNode.innerHTML = 'foo</foo>';
+                       selected = testNode.getElementsByTagName('*');
+                       starSelectsClosed = (selected && !!selected.length && selected[0].nodeName.charAt(0) == '/');
+               } catch(e){};
+
+               features.brokenStarGEBTN = starSelectsComments || starSelectsClosed;
+
+               // IE returns elements with the name instead of just id for getElementsById for some documents
+               try {
+                       testNode.innerHTML = '<a name="'+ id +'"></a><b id="'+ id +'"></b>';
+                       features.idGetsName = document.getElementById(id) === testNode.firstChild;
+               } catch(e){};
+
+               if (testNode.getElementsByClassName){
+
+                       // Safari 3.2 getElementsByClassName caches results
+                       try {
+                               testNode.innerHTML = '<a class="f"></a><a class="b"></a>';
+                               testNode.getElementsByClassName('b').length;
+                               testNode.firstChild.className = 'b';
+                               cachedGetElementsByClassName = (testNode.getElementsByClassName('b').length != 2);
+                       } catch(e){};
+
+                       // Opera 9.6 getElementsByClassName doesnt detects the class if its not the first one
+                       try {
+                               testNode.innerHTML = '<a class="a"></a><a class="f b a"></a>';
+                               brokenSecondClassNameGEBCN = (testNode.getElementsByClassName('a').length != 2);
+                       } catch(e){};
+
+                       features.brokenGEBCN = cachedGetElementsByClassName || brokenSecondClassNameGEBCN;
+               }
+
+               if (testNode.querySelectorAll){
+                       // IE 8 returns closed nodes (EG:"</foo>") for querySelectorAll('*') for some documents
+                       try {
+                               testNode.innerHTML = 'foo</foo>';
+                               selected = testNode.querySelectorAll('*');
+                               features.starSelectsClosedQSA = (selected && !!selected.length && selected[0].nodeName.charAt(0) == '/');
+                       } catch(e){};
+
+                       // Safari 3.2 querySelectorAll doesnt work with mixedcase on quirksmode
+                       try {
+                               testNode.innerHTML = '<a class="MiX"></a>';
+                               features.brokenMixedCaseQSA = !testNode.querySelectorAll('.MiX').length;
+                       } catch(e){};
+
+                       // Webkit and Opera dont return selected options on querySelectorAll
+                       try {
+                               testNode.innerHTML = '<select><option selected="selected">a</option></select>';
+                               features.brokenCheckedQSA = (testNode.querySelectorAll(':checked').length == 0);
+                       } catch(e){};
+
+                       // IE returns incorrect results for attr[*^$]="" selectors on querySelectorAll
+                       try {
+                               testNode.innerHTML = '<a class=""></a>';
+                               features.brokenEmptyAttributeQSA = (testNode.querySelectorAll('[class*=""]').length != 0);
+                       } catch(e){};
+
+               }
+
+               // IE6-7, if a form has an input of id x, form.getAttribute(x) returns a reference to the input
+               try {
+                       testNode.innerHTML = '<form action="s"><input id="action"/></form>';
+                       brokenFormAttributeGetter = (testNode.firstChild.getAttribute('action') != 's');
+               } catch(e){};
+
+               // native matchesSelector function
+
+               features.nativeMatchesSelector = root.matchesSelector || /*root.msMatchesSelector ||*/ root.mozMatchesSelector || root.webkitMatchesSelector;
+               if (features.nativeMatchesSelector) try {
+                       // if matchesSelector trows errors on incorrect sintaxes we can use it
+                       features.nativeMatchesSelector.call(root, ':slick');
+                       features.nativeMatchesSelector = null;
+               } catch(e){};
+
+       }
+
+       try {
+               root.slick_expando = 1;
+               delete root.slick_expando;
+               features.getUID = this.getUIDHTML;
+       } catch(e) {
+               features.getUID = this.getUIDXML;
+       }
+
+       testRoot.removeChild(testNode);
+       testNode = selected = testRoot = null;
+
+       // getAttribute
+
+       features.getAttribute = (features.isHTMLDocument && brokenFormAttributeGetter) ? function(node, name){
+               var method = this.attributeGetters[name];
+               if (method) return method.call(node);
+               var attributeNode = node.getAttributeNode(name);
+               return (attributeNode) ? attributeNode.nodeValue : null;
+       } : function(node, name){
+               var method = this.attributeGetters[name];
+               return (method) ? method.call(node) : node.getAttribute(name);
+       };
+
+       // hasAttribute
+
+       features.hasAttribute = (root && this.isNativeCode(root.hasAttribute)) ? function(node, attribute) {
+               return node.hasAttribute(attribute);
+       } : function(node, attribute) {
+               node = node.getAttributeNode(attribute);
+               return !!(node && (node.specified || node.nodeValue));
+       };
+
+       // contains
+       // FIXME: Add specs: local.contains should be different for xml and html documents?
+       var nativeRootContains = root && this.isNativeCode(root.contains),
+               nativeDocumentContains = document && this.isNativeCode(document.contains);
+
+       features.contains = (nativeRootContains && nativeDocumentContains) ? function(context, node){
+               return context.contains(node);
+       } : (nativeRootContains && !nativeDocumentContains) ? function(context, node){
+               // IE8 does not have .contains on document.
+               return context === node || ((context === document) ? document.documentElement : context).contains(node);
+       } : (root && root.compareDocumentPosition) ? function(context, node){
+               return context === node || !!(context.compareDocumentPosition(node) & 16);
+       } : function(context, node){
+               if (node) do {
+                       if (node === context) return true;
+               } while ((node = node.parentNode));
+               return false;
+       };
+
+       // document order sorting
+       // credits to Sizzle (http://sizzlejs.com/)
+
+       features.documentSorter = (root.compareDocumentPosition) ? function(a, b){
+               if (!a.compareDocumentPosition || !b.compareDocumentPosition) return 0;
+               return a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1;
+       } : ('sourceIndex' in root) ? function(a, b){
+               if (!a.sourceIndex || !b.sourceIndex) return 0;
+               return a.sourceIndex - b.sourceIndex;
+       } : (document.createRange) ? function(a, b){
+               if (!a.ownerDocument || !b.ownerDocument) return 0;
+               var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange();
+               aRange.setStart(a, 0);
+               aRange.setEnd(a, 0);
+               bRange.setStart(b, 0);
+               bRange.setEnd(b, 0);
+               return aRange.compareBoundaryPoints(Range.START_TO_END, bRange);
+       } : null ;
+
+       root = null;
+
+       for (feature in features){
+               this[feature] = features[feature];
+       }
+};
+
+// Main Method
+
+var reSimpleSelector = /^([#.]?)((?:[\w-]+|\*))$/,
+       reEmptyAttribute = /\[.+[*$^]=(?:""|'')?\]/,
+       qsaFailExpCache = {};
+
+local.search = function(context, expression, append, first){
+
+       var found = this.found = (first) ? null : (append || []);
+
+       if (!context) return found;
+       else if (context.navigator) context = context.document; // Convert the node from a window to a document
+       else if (!context.nodeType) return found;
+
+       // setup
+
+       var parsed, i,
+               uniques = this.uniques = {},
+               hasOthers = !!(append && append.length),
+               contextIsDocument = (context.nodeType == 9);
+
+       if (this.document !== (contextIsDocument ? context : context.ownerDocument)) this.setDocument(context);
+
+       // avoid duplicating items already in the append array
+       if (hasOthers) for (i = found.length; i--;) uniques[this.getUID(found[i])] = true;
+
+       // expression checks
+
+       if (typeof expression == 'string'){ // expression is a string
+
+               /*<simple-selectors-override>*/
+               var simpleSelector = expression.match(reSimpleSelector);
+               simpleSelectors: if (simpleSelector) {
+
+                       var symbol = simpleSelector[1],
+                               name = simpleSelector[2],
+                               node, nodes;
+
+                       if (!symbol){
+
+                               if (name == '*' && this.brokenStarGEBTN) break simpleSelectors;
+                               nodes = context.getElementsByTagName(name);
+                               if (first) return nodes[0] || null;
+                               for (i = 0; node = nodes[i++];){
+                                       if (!(hasOthers && uniques[this.getUID(node)])) found.push(node);
+                               }
+
+                       } else if (symbol == '#'){
+
+                               if (!this.isHTMLDocument || !contextIsDocument) break simpleSelectors;
+                               node = context.getElementById(name);
+                               if (!node) return found;
+                               if (this.idGetsName && node.getAttributeNode('id').nodeValue != name) break simpleSelectors;
+                               if (first) return node || null;
+                               if (!(hasOthers && uniques[this.getUID(node)])) found.push(node);
+
+                       } else if (symbol == '.'){
+
+                               if (!this.isHTMLDocument || ((!context.getElementsByClassName || this.brokenGEBCN) && context.querySelectorAll)) break simpleSelectors;
+                               if (context.getElementsByClassName && !this.brokenGEBCN){
+                                       nodes = context.getElementsByClassName(name);
+                                       if (first) return nodes[0] || null;
+                                       for (i = 0; node = nodes[i++];){
+                                               if (!(hasOthers && uniques[this.getUID(node)])) found.push(node);
+                                       }
+                               } else {
+                                       var matchClass = new RegExp('(^|\\s)'+ Slick.escapeRegExp(name) +'(\\s|$)');
+                                       nodes = context.getElementsByTagName('*');
+                                       for (i = 0; node = nodes[i++];){
+                                               className = node.className;
+                                               if (!(className && matchClass.test(className))) continue;
+                                               if (first) return node;
+                                               if (!(hasOthers && uniques[this.getUID(node)])) found.push(node);
+                                       }
+                               }
+
+                       }
+
+                       if (hasOthers) this.sort(found);
+                       return (first) ? null : found;
+
+               }
+               /*</simple-selectors-override>*/
+
+               /*<query-selector-override>*/
+               querySelector: if (context.querySelectorAll) {
+
+                       if (!this.isHTMLDocument
+                               || qsaFailExpCache[expression]
+                               //TODO: only skip when expression is actually mixed case
+                               || this.brokenMixedCaseQSA
+                               || (this.brokenCheckedQSA && expression.indexOf(':checked') > -1)
+                               || (this.brokenEmptyAttributeQSA && reEmptyAttribute.test(expression))
+                               || (!contextIsDocument //Abort when !contextIsDocument and...
+                                       //  there are multiple expressions in the selector
+                                       //  since we currently only fix non-document rooted QSA for single expression selectors
+                                       && expression.indexOf(',') > -1
+                               )
+                               || Slick.disableQSA
+                       ) break querySelector;
+
+                       var _expression = expression, _context = context;
+                       if (!contextIsDocument){
+                               // non-document rooted QSA
+                               // credits to Andrew Dupont
+                               var currentId = _context.getAttribute('id'), slickid = 'slickid__';
+                               _context.setAttribute('id', slickid);
+                               _expression = '#' + slickid + ' ' + _expression;
+                               context = _context.parentNode;
+                       }
+
+                       try {
+                               if (first) return context.querySelector(_expression) || null;
+                               else nodes = context.querySelectorAll(_expression);
+                       } catch(e) {
+                               qsaFailExpCache[expression] = 1;
+                               break querySelector;
+                       } finally {
+                               if (!contextIsDocument){
+                                       if (currentId) _context.setAttribute('id', currentId);
+                                       else _context.removeAttribute('id');
+                                       context = _context;
+                               }
+                       }
+
+                       if (this.starSelectsClosedQSA) for (i = 0; node = nodes[i++];){
+                               if (node.nodeName > '@' && !(hasOthers && uniques[this.getUID(node)])) found.push(node);
+                       } else for (i = 0; node = nodes[i++];){
+                               if (!(hasOthers && uniques[this.getUID(node)])) found.push(node);
+                       }
+
+                       if (hasOthers) this.sort(found);
+                       return found;
+
+               }
+               /*</query-selector-override>*/
+
+               parsed = this.Slick.parse(expression);
+               if (!parsed.length) return found;
+       } else if (expression == null){ // there is no expression
+               return found;
+       } else if (expression.Slick){ // expression is a parsed Slick object
+               parsed = expression;
+       } else if (this.contains(context.documentElement || context, expression)){ // expression is a node
+               (found) ? found.push(expression) : found = expression;
+               return found;
+       } else { // other junk
+               return found;
+       }
+
+       /*<pseudo-selectors>*//*<nth-pseudo-selectors>*/
+
+       // cache elements for the nth selectors
+
+       this.posNTH = {};
+       this.posNTHLast = {};
+       this.posNTHType = {};
+       this.posNTHTypeLast = {};
+
+       /*</nth-pseudo-selectors>*//*</pseudo-selectors>*/
+
+       // if append is null and there is only a single selector with one expression use pushArray, else use pushUID
+       this.push = (!hasOthers && (first || (parsed.length == 1 && parsed.expressions[0].length == 1))) ? this.pushArray : this.pushUID;
+
+       if (found == null) found = [];
+
+       // default engine
+
+       var j, m, n;
+       var combinator, tag, id, classList, classes, attributes, pseudos;
+       var currentItems, currentExpression, currentBit, lastBit, expressions = parsed.expressions;
+
+       search: for (i = 0; (currentExpression = expressions[i]); i++) for (j = 0; (currentBit = currentExpression[j]); j++){
+
+               combinator = 'combinator:' + currentBit.combinator;
+               if (!this[combinator]) continue search;
+
+               tag        = (this.isXMLDocument) ? currentBit.tag : currentBit.tag.toUpperCase();
+               id         = currentBit.id;
+               classList  = currentBit.classList;
+               classes    = currentBit.classes;
+               attributes = currentBit.attributes;
+               pseudos    = currentBit.pseudos;
+               lastBit    = (j === (currentExpression.length - 1));
+
+               this.bitUniques = {};
+
+               if (lastBit){
+                       this.uniques = uniques;
+                       this.found = found;
+               } else {
+                       this.uniques = {};
+                       this.found = [];
+               }
+
+               if (j === 0){
+                       this[combinator](context, tag, id, classes, attributes, pseudos, classList);
+                       if (first && lastBit && found.length) break search;
+               } else {
+                       if (first && lastBit) for (m = 0, n = currentItems.length; m < n; m++){
+                               this[combinator](currentItems[m], tag, id, classes, attributes, pseudos, classList);
+                               if (found.length) break search;
+                       } else for (m = 0, n = currentItems.length; m < n; m++) this[combinator](currentItems[m], tag, id, classes, attributes, pseudos, classList);
+               }
+
+               currentItems = this.found;
+       }
+
+       // should sort if there are nodes in append and if you pass multiple expressions.
+       if (hasOthers || (parsed.expressions.length > 1)) this.sort(found);
+
+       return (first) ? (found[0] || null) : found;
+};
+
+// Utils
+
+local.uidx = 1;
+local.uidk = 'slick-uniqueid';
+
+local.getUIDXML = function(node){
+       var uid = node.getAttribute(this.uidk);
+       if (!uid){
+               uid = this.uidx++;
+               node.setAttribute(this.uidk, uid);
+       }
+       return uid;
+};
+
+local.getUIDHTML = function(node){
+       return node.uniqueNumber || (node.uniqueNumber = this.uidx++);
+};
+
+// sort based on the setDocument documentSorter method.
+
+local.sort = function(results){
+       if (!this.documentSorter) return results;
+       results.sort(this.documentSorter);
+       return results;
+};
+
+/*<pseudo-selectors>*//*<nth-pseudo-selectors>*/
+
+local.cacheNTH = {};
+
+local.matchNTH = /^([+-]?\d*)?([a-z]+)?([+-]\d+)?$/;
+
+local.parseNTHArgument = function(argument){
+       var parsed = argument.match(this.matchNTH);
+       if (!parsed) return false;
+       var special = parsed[2] || false;
+       var a = parsed[1] || 1;
+       if (a == '-') a = -1;
+       var b = +parsed[3] || 0;
+       parsed =
+               (special == 'n')        ? {a: a, b: b} :
+               (special == 'odd')      ? {a: 2, b: 1} :
+               (special == 'even')     ? {a: 2, b: 0} : {a: 0, b: a};
+
+       return (this.cacheNTH[argument] = parsed);
+};
+
+local.createNTHPseudo = function(child, sibling, positions, ofType){
+       return function(node, argument){
+               var uid = this.getUID(node);
+               if (!this[positions][uid]){
+                       var parent = node.parentNode;
+                       if (!parent) return false;
+                       var el = parent[child], count = 1;
+                       if (ofType){
+                               var nodeName = node.nodeName;
+                               do {
+                                       if (el.nodeName != nodeName) continue;
+                                       this[positions][this.getUID(el)] = count++;
+                               } while ((el = el[sibling]));
+                       } else {
+                               do {
+                                       if (el.nodeType != 1) continue;
+                                       this[positions][this.getUID(el)] = count++;
+                               } while ((el = el[sibling]));
+                       }
+               }
+               argument = argument || 'n';
+               var parsed = this.cacheNTH[argument] || this.parseNTHArgument(argument);
+               if (!parsed) return false;
+               var a = parsed.a, b = parsed.b, pos = this[positions][uid];
+               if (a == 0) return b == pos;
+               if (a > 0){
+                       if (pos < b) return false;
+               } else {
+                       if (b < pos) return false;
+               }
+               return ((pos - b) % a) == 0;
+       };
+};
+
+/*</nth-pseudo-selectors>*//*</pseudo-selectors>*/
+
+local.pushArray = function(node, tag, id, classes, attributes, pseudos){
+       if (this.matchSelector(node, tag, id, classes, attributes, pseudos)) this.found.push(node);
+};
+
+local.pushUID = function(node, tag, id, classes, attributes, pseudos){
+       var uid = this.getUID(node);
+       if (!this.uniques[uid] && this.matchSelector(node, tag, id, classes, attributes, pseudos)){
+               this.uniques[uid] = true;
+               this.found.push(node);
+       }
+};
+
+local.matchNode = function(node, selector){
+       if (this.isHTMLDocument && this.nativeMatchesSelector){
+               try {
+                       return this.nativeMatchesSelector.call(node, selector.replace(/\[([^=]+)=\s*([^'"\]]+?)\s*\]/g, '[$1="$2"]'));
+               } catch(matchError) {}
+       }
+
+       var parsed = this.Slick.parse(selector);
+       if (!parsed) return true;
+
+       // simple (single) selectors
+       var expressions = parsed.expressions, simpleExpCounter = 0, i;
+       for (i = 0; (currentExpression = expressions[i]); i++){
+               if (currentExpression.length == 1){
+                       var exp = currentExpression[0];
+                       if (this.matchSelector(node, (this.isXMLDocument) ? exp.tag : exp.tag.toUpperCase(), exp.id, exp.classes, exp.attributes, exp.pseudos)) return true;
+                       simpleExpCounter++;
+               }
+       }
+
+       if (simpleExpCounter == parsed.length) return false;
+
+       var nodes = this.search(this.document, parsed), item;
+       for (i = 0; item = nodes[i++];){
+               if (item === node) return true;
+       }
+       return false;
+};
+
+local.matchPseudo = function(node, name, argument){
+       var pseudoName = 'pseudo:' + name;
+       if (this[pseudoName]) return this[pseudoName](node, argument);
+       var attribute = this.getAttribute(node, name);
+       return (argument) ? argument == attribute : !!attribute;
+};
+
+local.matchSelector = function(node, tag, id, classes, attributes, pseudos){
+       if (tag){
+               var nodeName = (this.isXMLDocument) ? node.nodeName : node.nodeName.toUpperCase();
+               if (tag == '*'){
+                       if (nodeName < '@') return false; // Fix for comment nodes and closed nodes
+               } else {
+                       if (nodeName != tag) return false;
+               }
+       }
+
+       if (id && node.getAttribute('id') != id) return false;
+
+       var i, part, cls;
+       if (classes) for (i = classes.length; i--;){
+               cls = this.getAttribute(node, 'class');
+               if (!(cls && classes[i].regexp.test(cls))) return false;
+       }
+       if (attributes) for (i = attributes.length; i--;){
+               part = attributes[i];
+               if (part.operator ? !part.test(this.getAttribute(node, part.key)) : !this.hasAttribute(node, part.key)) return false;
+       }
+       if (pseudos) for (i = pseudos.length; i--;){
+               part = pseudos[i];
+               if (!this.matchPseudo(node, part.key, part.value)) return false;
+       }
+       return true;
+};
+
+var combinators = {
+
+       ' ': function(node, tag, id, classes, attributes, pseudos, classList){ // all child nodes, any level
+
+               var i, item, children;
+
+               if (this.isHTMLDocument){
+                       getById: if (id){
+                               item = this.document.getElementById(id);
+                               if ((!item && node.all) || (this.idGetsName && item && item.getAttributeNode('id').nodeValue != id)){
+                                       // all[id] returns all the elements with that name or id inside node
+                                       // if theres just one it will return the element, else it will be a collection
+                                       children = node.all[id];
+                                       if (!children) return;
+                                       if (!children[0]) children = [children];
+                                       for (i = 0; item = children[i++];){
+                                               var idNode = item.getAttributeNode('id');
+                                               if (idNode && idNode.nodeValue == id){
+                                                       this.push(item, tag, null, classes, attributes, pseudos);
+                                                       break;
+                                               }
+                                       }
+                                       return;
+                               }
+                               if (!item){
+                                       // if the context is in the dom we return, else we will try GEBTN, breaking the getById label
+                                       if (this.contains(this.root, node)) return;
+                                       else break getById;
+                               } else if (this.document !== node && !this.contains(node, item)) return;
+                               this.push(item, tag, null, classes, attributes, pseudos);
+                               return;
+                       }
+                       getByClass: if (classes && node.getElementsByClassName && !this.brokenGEBCN){
+                               children = node.getElementsByClassName(classList.join(' '));
+                               if (!(children && children.length)) break getByClass;
+                               for (i = 0; item = children[i++];) this.push(item, tag, id, null, attributes, pseudos);
+                               return;
+                       }
+               }
+               getByTag: {
+                       children = node.getElementsByTagName(tag);
+                       if (!(children && children.length)) break getByTag;
+                       if (!this.brokenStarGEBTN) tag = null;
+                       for (i = 0; item = children[i++];) this.push(item, tag, id, classes, attributes, pseudos);
+               }
+       },
+
+       '>': function(node, tag, id, classes, attributes, pseudos){ // direct children
+               if ((node = node.firstChild)) do {
+                       if (node.nodeType == 1) this.push(node, tag, id, classes, attributes, pseudos);
+               } while ((node = node.nextSibling));
+       },
+
+       '+': function(node, tag, id, classes, attributes, pseudos){ // next sibling
+               while ((node = node.nextSibling)) if (node.nodeType == 1){
+                       this.push(node, tag, id, classes, attributes, pseudos);
+                       break;
+               }
+       },
+
+       '^': function(node, tag, id, classes, attributes, pseudos){ // first child
+               node = node.firstChild;
+               if (node){
+                       if (node.nodeType == 1) this.push(node, tag, id, classes, attributes, pseudos);
+                       else this['combinator:+'](node, tag, id, classes, attributes, pseudos);
+               }
+       },
+
+       '~': function(node, tag, id, classes, attributes, pseudos){ // next siblings
+               while ((node = node.nextSibling)){
+                       if (node.nodeType != 1) continue;
+                       var uid = this.getUID(node);
+                       if (this.bitUniques[uid]) break;
+                       this.bitUniques[uid] = true;
+                       this.push(node, tag, id, classes, attributes, pseudos);
+               }
+       },
+
+       '++': function(node, tag, id, classes, attributes, pseudos){ // next sibling and previous sibling
+               this['combinator:+'](node, tag, id, classes, attributes, pseudos);
+               this['combinator:!+'](node, tag, id, classes, attributes, pseudos);
+       },
+
+       '~~': function(node, tag, id, classes, attributes, pseudos){ // next siblings and previous siblings
+               this['combinator:~'](node, tag, id, classes, attributes, pseudos);
+               this['combinator:!~'](node, tag, id, classes, attributes, pseudos);
+       },
+
+       '!': function(node, tag, id, classes, attributes, pseudos){ // all parent nodes up to document
+               while ((node = node.parentNode)) if (node !== this.document) this.push(node, tag, id, classes, attributes, pseudos);
+       },
+
+       '!>': function(node, tag, id, classes, attributes, pseudos){ // direct parent (one level)
+               node = node.parentNode;
+               if (node !== this.document) this.push(node, tag, id, classes, attributes, pseudos);
+       },
+
+       '!+': function(node, tag, id, classes, attributes, pseudos){ // previous sibling
+               while ((node = node.previousSibling)) if (node.nodeType == 1){
+                       this.push(node, tag, id, classes, attributes, pseudos);
+                       break;
+               }
+       },
+
+       '!^': function(node, tag, id, classes, attributes, pseudos){ // last child
+               node = node.lastChild;
+               if (node){
+                       if (node.nodeType == 1) this.push(node, tag, id, classes, attributes, pseudos);
+                       else this['combinator:!+'](node, tag, id, classes, attributes, pseudos);
+               }
+       },
+
+       '!~': function(node, tag, id, classes, attributes, pseudos){ // previous siblings
+               while ((node = node.previousSibling)){
+                       if (node.nodeType != 1) continue;
+                       var uid = this.getUID(node);
+                       if (this.bitUniques[uid]) break;
+                       this.bitUniques[uid] = true;
+                       this.push(node, tag, id, classes, attributes, pseudos);
+               }
+       }
+
+};
+
+for (var c in combinators) local['combinator:' + c] = combinators[c];
+
+var pseudos = {
+
+       /*<pseudo-selectors>*/
+
+       'empty': function(node){
+               var child = node.firstChild;
+               return !(child && child.nodeType == 1) && !(node.innerText || node.textContent || '').length;
+       },
+
+       'not': function(node, expression){
+               return !this.matchNode(node, expression);
+       },
+
+       'contains': function(node, text){
+               return (node.innerText || node.textContent || '').indexOf(text) > -1;
+       },
+
+       'first-child': function(node){
+               while ((node = node.previousSibling)) if (node.nodeType == 1) return false;
+               return true;
+       },
+
+       'last-child': function(node){
+               while ((node = node.nextSibling)) if (node.nodeType == 1) return false;
+               return true;
+       },
+
+       'only-child': function(node){
+               var prev = node;
+               while ((prev = prev.previousSibling)) if (prev.nodeType == 1) return false;
+               var next = node;
+               while ((next = next.nextSibling)) if (next.nodeType == 1) return false;
+               return true;
+       },
+
+       /*<nth-pseudo-selectors>*/
+
+       'nth-child': local.createNTHPseudo('firstChild', 'nextSibling', 'posNTH'),
+
+       'nth-last-child': local.createNTHPseudo('lastChild', 'previousSibling', 'posNTHLast'),
+
+       'nth-of-type': local.createNTHPseudo('firstChild', 'nextSibling', 'posNTHType', true),
+
+       'nth-last-of-type': local.createNTHPseudo('lastChild', 'previousSibling', 'posNTHTypeLast', true),
+
+       'index': function(node, index){
+               return this['pseudo:nth-child'](node, '' + (index + 1));
+       },
+
+       'even': function(node){
+               return this['pseudo:nth-child'](node, '2n');
+       },
+
+       'odd': function(node){
+               return this['pseudo:nth-child'](node, '2n+1');
+       },
+
+       /*</nth-pseudo-selectors>*/
+
+       /*<of-type-pseudo-selectors>*/
+
+       'first-of-type': function(node){
+               var nodeName = node.nodeName;
+               while ((node = node.previousSibling)) if (node.nodeName == nodeName) return false;
+               return true;
+       },
+
+       'last-of-type': function(node){
+               var nodeName = node.nodeName;
+               while ((node = node.nextSibling)) if (node.nodeName == nodeName) return false;
+               return true;
+       },
+
+       'only-of-type': function(node){
+               var prev = node, nodeName = node.nodeName;
+               while ((prev = prev.previousSibling)) if (prev.nodeName == nodeName) return false;
+               var next = node;
+               while ((next = next.nextSibling)) if (next.nodeName == nodeName) return false;
+               return true;
+       },
+
+       /*</of-type-pseudo-selectors>*/
+
+       // custom pseudos
+
+       'enabled': function(node){
+               return !node.disabled;
+       },
+
+       'disabled': function(node){
+               return node.disabled;
+       },
+
+       'checked': function(node){
+               return node.checked || node.selected;
+       },
+
+       'focus': function(node){
+               return this.isHTMLDocument && this.document.activeElement === node && (node.href || node.type || this.hasAttribute(node, 'tabindex'));
+       },
+
+       'root': function(node){
+               return (node === this.root);
+       },
+
+       'selected': function(node){
+               return node.selected;
+       }
+
+       /*</pseudo-selectors>*/
+};
+
+for (var p in pseudos) local['pseudo:' + p] = pseudos[p];
+
+// attributes methods
+
+var attributeGetters = local.attributeGetters = {
+
+       'for': function(){
+               return ('htmlFor' in this) ? this.htmlFor : this.getAttribute('for');
+       },
+
+       'href': function(){
+               return ('href' in this) ? this.getAttribute('href', 2) : this.getAttribute('href');
+       },
+
+       'style': function(){
+               return (this.style) ? this.style.cssText : this.getAttribute('style');
+       },
+
+       'tabindex': function(){
+               var attributeNode = this.getAttributeNode('tabindex');
+               return (attributeNode && attributeNode.specified) ? attributeNode.nodeValue : null;
+       },
+
+       'type': function(){
+               return this.getAttribute('type');
+       },
+
+       'maxlength': function(){
+               var attributeNode = this.getAttributeNode('maxLength');
+               return (attributeNode && attributeNode.specified) ? attributeNode.nodeValue : null;
+       }
+
+};
+
+attributeGetters.MAXLENGTH = attributeGetters.maxLength = attributeGetters.maxlength;
+
+// Slick
+
+var Slick = local.Slick = (this.Slick || {});
+
+Slick.version = '1.1.7';
+
+// Slick finder
+
+Slick.search = function(context, expression, append){
+       return local.search(context, expression, append);
+};
+
+Slick.find = function(context, expression){
+       return local.search(context, expression, null, true);
+};
+
+// Slick containment checker
+
+Slick.contains = function(container, node){
+       local.setDocument(container);
+       return local.contains(container, node);
+};
+
+// Slick attribute getter
+
+Slick.getAttribute = function(node, name){
+       local.setDocument(node);
+       return local.getAttribute(node, name);
+};
+
+Slick.hasAttribute = function(node, name){
+       local.setDocument(node);
+       return local.hasAttribute(node, name);
+};
+
+// Slick matcher
+
+Slick.match = function(node, selector){
+       if (!(node && selector)) return false;
+       if (!selector || selector === node) return true;
+       local.setDocument(node);
+       return local.matchNode(node, selector);
+};
+
+// Slick attribute accessor
+
+Slick.defineAttributeGetter = function(name, fn){
+       local.attributeGetters[name] = fn;
+       return this;
+};
+
+Slick.lookupAttributeGetter = function(name){
+       return local.attributeGetters[name];
+};
+
+// Slick pseudo accessor
+
+Slick.definePseudo = function(name, fn){
+       local['pseudo:' + name] = function(node, argument){
+               return fn.call(node, argument);
+       };
+       return this;
+};
+
+Slick.lookupPseudo = function(name){
+       var pseudo = local['pseudo:' + name];
+       if (pseudo) return function(argument){
+               return pseudo.call(this, argument);
+       };
+       return null;
+};
+
+// Slick overrides accessor
+
+Slick.override = function(regexp, fn){
+       local.override(regexp, fn);
+       return this;
+};
+
+Slick.isXML = local.isXML;
+
+Slick.uidOf = function(node){
+       return local.getUIDHTML(node);
+};
+
+if (!this.Slick) this.Slick = Slick;
+
+}).apply(/*<CommonJS>*/(typeof exports != 'undefined') ? exports : /*</CommonJS>*/this);
+
+
+// Begin: Source/Element/Element.js
+/*
+---
+
+name: Element
+
+description: One of the most important items in MooTools. Contains the dollar function, the dollars function, and an handful of cross-browser, time-saver methods to let you easily work with HTML Elements.
+
+license: MIT-style license.
+
+requires: [Window, Document, Array, String, Function, Object, Number, Slick.Parser, Slick.Finder]
+
+provides: [Element, Elements, $, $$, Iframe, Selectors]
+
+...
+*/
+
+var Element = function(tag, props){
+       var konstructor = Element.Constructors[tag];
+       if (konstructor) return konstructor(props);
+       if (typeof tag != 'string') return document.id(tag).set(props);
+
+       if (!props) props = {};
+
+       if (!(/^[\w-]+$/).test(tag)){
+               var parsed = Slick.parse(tag).expressions[0][0];
+               tag = (parsed.tag == '*') ? 'div' : parsed.tag;
+               if (parsed.id && props.id == null) props.id = parsed.id;
+
+               var attributes = parsed.attributes;
+               if (attributes) for (var attr, i = 0, l = attributes.length; i < l; i++){
+                       attr = attributes[i];
+                       if (props[attr.key] != null) continue;
+
+                       if (attr.value != null && attr.operator == '=') props[attr.key] = attr.value;
+                       else if (!attr.value && !attr.operator) props[attr.key] = true;
+               }
+
+               if (parsed.classList && props['class'] == null) props['class'] = parsed.classList.join(' ');
+       }
+
+       return document.newElement(tag, props);
+};
+
+
+if (Browser.Element){
+       Element.prototype = Browser.Element.prototype;
+       // IE8 and IE9 require the wrapping.
+       Element.prototype._fireEvent = (function(fireEvent){
+               return function(type, event){
+                       return fireEvent.call(this, type, event);
+               };
+       })(Element.prototype.fireEvent);
+}
+
+new Type('Element', Element).mirror(function(name){
+       if (Array.prototype[name]) return;
+
+       var obj = {};
+       obj[name] = function(){
+               var results = [], args = arguments, elements = true;
+               for (var i = 0, l = this.length; i < l; i++){
+                       var element = this[i], result = results[i] = element[name].apply(element, args);
+                       elements = (elements && typeOf(result) == 'element');
+               }
+               return (elements) ? new Elements(results) : results;
+       };
+
+       Elements.implement(obj);
+});
+
+if (!Browser.Element){
+       Element.parent = Object;
+
+       Element.Prototype = {
+               '$constructor': Element,
+               '$family': Function.from('element').hide()
+       };
+
+       Element.mirror(function(name, method){
+               Element.Prototype[name] = method;
+       });
+}
+
+Element.Constructors = {};
+
+//<1.2compat>
+
+Element.Constructors = new Hash;
+
+//</1.2compat>
+
+var IFrame = new Type('IFrame', function(){
+       var params = Array.link(arguments, {
+               properties: Type.isObject,
+               iframe: function(obj){
+                       return (obj != null);
+               }
+       });
+
+       var props = params.properties || {}, iframe;
+       if (params.iframe) iframe = document.id(params.iframe);
+       var onload = props.onload || function(){};
+       delete props.onload;
+       props.id = props.name = [props.id, props.name, iframe ? (iframe.id || iframe.name) : 'IFrame_' + String.uniqueID()].pick();
+       iframe = new Element(iframe || 'iframe', props);
+
+       var onLoad = function(){
+               onload.call(iframe.contentWindow);
+       };
+
+       if (window.frames[props.id]) onLoad();
+       else iframe.addListener('load', onLoad);
+       return iframe;
+});
+
+var Elements = this.Elements = function(nodes){
+       if (nodes && nodes.length){
+               var uniques = {}, node;
+               for (var i = 0; node = nodes[i++];){
+                       var uid = Slick.uidOf(node);
+                       if (!uniques[uid]){
+                               uniques[uid] = true;
+                               this.push(node);
+                       }
+               }
+       }
+};
+
+Elements.prototype = {length: 0};
+Elements.parent = Array;
+
+new Type('Elements', Elements).implement({
+
+       filter: function(filter, bind){
+               if (!filter) return this;
+               return new Elements(Array.filter(this, (typeOf(filter) == 'string') ? function(item){
+                       return item.match(filter);
+               } : filter, bind));
+       }.protect(),
+
+       push: function(){
+               var length = this.length;
+               for (var i = 0, l = arguments.length; i < l; i++){
+                       var item = document.id(arguments[i]);
+                       if (item) this[length++] = item;
+               }
+               return (this.length = length);
+       }.protect(),
+
+       unshift: function(){
+               var items = [];
+               for (var i = 0, l = arguments.length; i < l; i++){
+                       var item = document.id(arguments[i]);
+                       if (item) items.push(item);
+               }
+               return Array.prototype.unshift.apply(this, items);
+       }.protect(),
+
+       concat: function(){
+               var newElements = new Elements(this);
+               for (var i = 0, l = arguments.length; i < l; i++){
+                       var item = arguments[i];
+                       if (Type.isEnumerable(item)) newElements.append(item);
+                       else newElements.push(item);
+               }
+               return newElements;
+       }.protect(),
+
+       append: function(collection){
+               for (var i = 0, l = collection.length; i < l; i++) this.push(collection[i]);
+               return this;
+       }.protect(),
+
+       empty: function(){
+               while (this.length) delete this[--this.length];
+               return this;
+       }.protect()
+
+});
+
+//<1.2compat>
+
+Elements.alias('extend', 'append');
+
+//</1.2compat>
+
+(function(){
+
+// FF, IE
+var splice = Array.prototype.splice, object = {'0': 0, '1': 1, length: 2};
+
+splice.call(object, 1, 1);
+if (object[1] == 1) Elements.implement('splice', function(){
+       var length = this.length;
+       var result = splice.apply(this, arguments);
+       while (length >= this.length) delete this[length--];
+       return result;
+}.protect());
+
+Array.forEachMethod(function(method, name){
+       Elements.implement(name, method);
+});
+
+Array.mirror(Elements);
+
+/*<ltIE8>*/
+var createElementAcceptsHTML;
+try {
+    createElementAcceptsHTML = (document.createElement('<input name=x>').name == 'x');
+} catch (e){}
+
+var escapeQuotes = function(html){
+       return ('' + html).replace(/&/g, '&amp;').replace(/"/g, '&quot;');
+};
+/*</ltIE8>*/
+
+Document.implement({
+
+       newElement: function(tag, props){
+               if (props && props.checked != null) props.defaultChecked = props.checked;
+               /*<ltIE8>*/// Fix for readonly name and type properties in IE < 8
+               if (createElementAcceptsHTML && props){
+                       tag = '<' + tag;
+                       if (props.name) tag += ' name="' + escapeQuotes(props.name) + '"';
+                       if (props.type) tag += ' type="' + escapeQuotes(props.type) + '"';
+                       tag += '>';
+                       delete props.name;
+                       delete props.type;
+               }
+               /*</ltIE8>*/
+               return this.id(this.createElement(tag)).set(props);
+       }
+
+});
+
+})();
+
+(function(){
+
+Slick.uidOf(window);
+Slick.uidOf(document);
+
+Document.implement({
+
+       newTextNode: function(text){
+               return this.createTextNode(text);
+       },
+
+       getDocument: function(){
+               return this;
+       },
+
+       getWindow: function(){
+               return this.window;
+       },
+
+       id: (function(){
+
+               var types = {
+
+                       string: function(id, nocash, doc){
+                               id = Slick.find(doc, '#' + id.replace(/(\W)/g, '\\$1'));
+                               return (id) ? types.element(id, nocash) : null;
+                       },
+
+                       element: function(el, nocash){
+                               Slick.uidOf(el);
+                               if (!nocash && !el.$family && !(/^(?:object|embed)$/i).test(el.tagName)){
+                                       var fireEvent = el.fireEvent;
+                                       // wrapping needed in IE7, or else crash
+                                       el._fireEvent = function(type, event){
+                                               return fireEvent(type, event);
+                                       };
+                                       Object.append(el, Element.Prototype);
+                               }
+                               return el;
+                       },
+
+                       object: function(obj, nocash, doc){
+                               if (obj.toElement) return types.element(obj.toElement(doc), nocash);
+                               return null;
+                       }
+
+               };
+
+               types.textnode = types.whitespace = types.window = types.document = function(zero){
+                       return zero;
+               };
+
+               return function(el, nocash, doc){
+                       if (el && el.$family && el.uniqueNumber) return el;
+                       var type = typeOf(el);
+                       return (types[type]) ? types[type](el, nocash, doc || document) : null;
+               };
+
+       })()
+
+});
+
+if (window.$ == null) Window.implement('$', function(el, nc){
+       return document.id(el, nc, this.document);
+});
+
+Window.implement({
+
+       getDocument: function(){
+               return this.document;
+       },
+
+       getWindow: function(){
+               return this;
+       }
+
+});
+
+[Document, Element].invoke('implement', {
+
+       getElements: function(expression){
+               return Slick.search(this, expression, new Elements);
+       },
+
+       getElement: function(expression){
+               return document.id(Slick.find(this, expression));
+       }
+
+});
+
+var contains = {contains: function(element){
+       return Slick.contains(this, element);
+}};
+
+if (!document.contains) Document.implement(contains);
+if (!document.createElement('div').contains) Element.implement(contains);
+
+//<1.2compat>
+
+Element.implement('hasChild', function(element){
+       return this !== element && this.contains(element);
+});
+
+(function(search, find, match){
+
+       this.Selectors = {};
+       var pseudos = this.Selectors.Pseudo = new Hash();
+
+       var addSlickPseudos = function(){
+               for (var name in pseudos) if (pseudos.hasOwnProperty(name)){
+                       Slick.definePseudo(name, pseudos[name]);
+                       delete pseudos[name];
+               }
+       };
+
+       Slick.search = function(context, expression, append){
+               addSlickPseudos();
+               return search.call(this, context, expression, append);
+       };
+
+       Slick.find = function(context, expression){
+               addSlickPseudos();
+               return find.call(this, context, expression);
+       };
+
+       Slick.match = function(node, selector){
+               addSlickPseudos();
+               return match.call(this, node, selector);
+       };
+
+})(Slick.search, Slick.find, Slick.match);
+
+//</1.2compat>
+
+// tree walking
+
+var injectCombinator = function(expression, combinator){
+       if (!expression) return combinator;
+
+       expression = Object.clone(Slick.parse(expression));
+
+       var expressions = expression.expressions;
+       for (var i = expressions.length; i--;)
+               expressions[i][0].combinator = combinator;
+
+       return expression;
+};
+
+Object.forEach({
+       getNext: '~',
+       getPrevious: '!~',
+       getParent: '!'
+}, function(combinator, method){
+       Element.implement(method, function(expression){
+               return this.getElement(injectCombinator(expression, combinator));
+       });
+});
+
+Object.forEach({
+       getAllNext: '~',
+       getAllPrevious: '!~',
+       getSiblings: '~~',
+       getChildren: '>',
+       getParents: '!'
+}, function(combinator, method){
+       Element.implement(method, function(expression){
+               return this.getElements(injectCombinator(expression, combinator));
+       });
+});
+
+Element.implement({
+
+       getFirst: function(expression){
+               return document.id(Slick.search(this, injectCombinator(expression, '>'))[0]);
+       },
+
+       getLast: function(expression){
+               return document.id(Slick.search(this, injectCombinator(expression, '>')).getLast());
+       },
+
+       getWindow: function(){
+               return this.ownerDocument.window;
+       },
+
+       getDocument: function(){
+               return this.ownerDocument;
+       },
+
+       getElementById: function(id){
+               return document.id(Slick.find(this, '#' + ('' + id).replace(/(\W)/g, '\\$1')));
+       },
+
+       match: function(expression){
+               return !expression || Slick.match(this, expression);
+       }
+
+});
+
+//<1.2compat>
+
+if (window.$$ == null) Window.implement('$$', function(selector){
+       var elements = new Elements;
+       if (arguments.length == 1 && typeof selector == 'string') return Slick.search(this.document, selector, elements);
+       var args = Array.flatten(arguments);
+       for (var i = 0, l = args.length; i < l; i++){
+               var item = args[i];
+               switch (typeOf(item)){
+                       case 'element': elements.push(item); break;
+                       case 'string': Slick.search(this.document, item, elements);
+               }
+       }
+       return elements;
+});
+
+//</1.2compat>
+
+if (window.$$ == null) Window.implement('$$', function(selector){
+       if (arguments.length == 1){
+               if (typeof selector == 'string') return Slick.search(this.document, selector, new Elements);
+               else if (Type.isEnumerable(selector)) return new Elements(selector);
+       }
+       return new Elements(arguments);
+});
+
+// Inserters
+
+var inserters = {
+
+       before: function(context, element){
+               var parent = element.parentNode;
+               if (parent) parent.insertBefore(context, element);
+       },
+
+       after: function(context, element){
+               var parent = element.parentNode;
+               if (parent) parent.insertBefore(context, element.nextSibling);
+       },
+
+       bottom: function(context, element){
+               element.appendChild(context);
+       },
+
+       top: function(context, element){
+               element.insertBefore(context, element.firstChild);
+       }
+
+};
+
+inserters.inside = inserters.bottom;
+
+//<1.2compat>
+
+Object.each(inserters, function(inserter, where){
+
+       where = where.capitalize();
+
+       var methods = {};
+
+       methods['inject' + where] = function(el){
+               inserter(this, document.id(el, true));
+               return this;
+       };
+
+       methods['grab' + where] = function(el){
+               inserter(document.id(el, true), this);
+               return this;
+       };
+
+       Element.implement(methods);
+
+});
+
+//</1.2compat>
+
+// getProperty / setProperty
+
+var propertyGetters = {}, propertySetters = {};
+
+// properties
+
+var properties = {};
+Array.forEach([
+       'type', 'value', 'defaultValue', 'accessKey', 'cellPadding', 'cellSpacing', 'colSpan',
+       'frameBorder', 'rowSpan', 'tabIndex', 'useMap'
+], function(property){
+       properties[property.toLowerCase()] = property;
+});
+
+properties.html = 'innerHTML';
+properties.text = (document.createElement('div').textContent == null) ? 'innerText': 'textContent';
+
+Object.forEach(properties, function(real, key){
+       propertySetters[key] = function(node, value){
+               node[real] = value;
+       };
+       propertyGetters[key] = function(node){
+               return node[real];
+       };
+});
+
+// Booleans
+
+var bools = [
+       'compact', 'nowrap', 'ismap', 'declare', 'noshade', 'checked',
+       'disabled', 'readOnly', 'multiple', 'selected', 'noresize',
+       'defer', 'defaultChecked', 'autofocus', 'controls', 'autoplay',
+       'loop'
+];
+
+var booleans = {};
+Array.forEach(bools, function(bool){
+       var lower = bool.toLowerCase();
+       booleans[lower] = bool;
+       propertySetters[lower] = function(node, value){
+               node[bool] = !!value;
+       };
+       propertyGetters[lower] = function(node){
+               return !!node[bool];
+       };
+});
+
+// Special cases
+
+Object.append(propertySetters, {
+
+       'class': function(node, value){
+               ('className' in node) ? node.className = (value || '') : node.setAttribute('class', value);
+       },
+
+       'for': function(node, value){
+               ('htmlFor' in node) ? node.htmlFor = value : node.setAttribute('for', value);
+       },
+
+       'style': function(node, value){
+               (node.style) ? node.style.cssText = value : node.setAttribute('style', value);
+       },
+
+       'value': function(node, value){
+               node.value = (value != null) ? value : '';
+       }
+
+});
+
+propertyGetters['class'] = function(node){
+       return ('className' in node) ? node.className || null : node.getAttribute('class');
+};
+
+/* <webkit> */
+var el = document.createElement('button');
+// IE sets type as readonly and throws
+try { el.type = 'button'; } catch(e){}
+if (el.type != 'button') propertySetters.type = function(node, value){
+       node.setAttribute('type', value);
+};
+el = null;
+/* </webkit> */
+
+/*<IE>*/
+var input = document.createElement('input');
+input.value = 't';
+input.type = 'submit';
+if (input.value != 't') propertySetters.type = function(node, type){
+       var value = node.value;
+       node.type = type;
+       node.value = value;
+};
+input = null;
+/*</IE>*/
+
+/* getProperty, setProperty */
+
+/* <ltIE9> */
+var pollutesGetAttribute = (function(div){
+       div.random = 'attribute';
+       return (div.getAttribute('random') == 'attribute');
+})(document.createElement('div'));
+
+/* <ltIE9> */
+
+Element.implement({
+
+       setProperty: function(name, value){
+               var setter = propertySetters[name.toLowerCase()];
+               if (setter){
+                       setter(this, value);
+               } else {
+                       /* <ltIE9> */
+                       if (pollutesGetAttribute) var attributeWhiteList = this.retrieve('$attributeWhiteList', {});
+                       /* </ltIE9> */
+
+                       if (value == null){
+                               this.removeAttribute(name);
+                               /* <ltIE9> */
+                               if (pollutesGetAttribute) delete attributeWhiteList[name];
+                               /* </ltIE9> */
+                       } else {
+                               this.setAttribute(name, '' + value);
+                               /* <ltIE9> */
+                               if (pollutesGetAttribute) attributeWhiteList[name] = true;
+                               /* </ltIE9> */
+                       }
+               }
+               return this;
+       },
+
+       setProperties: function(attributes){
+               for (var attribute in attributes) this.setProperty(attribute, attributes[attribute]);
+               return this;
+       },
+
+       getProperty: function(name){
+               var getter = propertyGetters[name.toLowerCase()];
+               if (getter) return getter(this);
+               /* <ltIE9> */
+               if (pollutesGetAttribute){
+                       var attr = this.getAttributeNode(name), attributeWhiteList = this.retrieve('$attributeWhiteList', {});
+                       if (!attr) return null;
+                       if (attr.expando && !attributeWhiteList[name]){
+                               var outer = this.outerHTML;
+                               // segment by the opening tag and find mention of attribute name
+                               if (outer.substr(0, outer.search(/\/?['"]?>(?![^<]*<['"])/)).indexOf(name) < 0) return null;
+                               attributeWhiteList[name] = true;
+                       }
+               }
+               /* </ltIE9> */
+               var result = Slick.getAttribute(this, name);
+               return (!result && !Slick.hasAttribute(this, name)) ? null : result;
+       },
+
+       getProperties: function(){
+               var args = Array.from(arguments);
+               return args.map(this.getProperty, this).associate(args);
+       },
+
+       removeProperty: function(name){
+               return this.setProperty(name, null);
+       },
+
+       removeProperties: function(){
+               Array.each(arguments, this.removeProperty, this);
+               return this;
+       },
+
+       set: function(prop, value){
+               var property = Element.Properties[prop];
+               (property && property.set) ? property.set.call(this, value) : this.setProperty(prop, value);
+       }.overloadSetter(),
+
+       get: function(prop){
+               var property = Element.Properties[prop];
+               return (property && property.get) ? property.get.apply(this) : this.getProperty(prop);
+       }.overloadGetter(),
+
+       erase: function(prop){
+               var property = Element.Properties[prop];
+               (property && property.erase) ? property.erase.apply(this) : this.removeProperty(prop);
+               return this;
+       },
+
+       hasClass: function(className){
+               return this.className.clean().contains(className, ' ');
+       },
+
+       addClass: function(className){
+               if (!this.hasClass(className)) this.className = (this.className + ' ' + className).clean();
+               return this;
+       },
+
+       removeClass: function(className){
+               this.className = this.className.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)'), '$1');
+               return this;
+       },
+
+       toggleClass: function(className, force){
+               if (force == null) force = !this.hasClass(className);
+               return (force) ? this.addClass(className) : this.removeClass(className);
+       },
+
+       adopt: function(){
+               var parent = this, fragment, elements = Array.flatten(arguments), length = elements.length;
+               if (length > 1) parent = fragment = document.createDocumentFragment();
+
+               for (var i = 0; i < length; i++){
+                       var element = document.id(elements[i], true);
+                       if (element) parent.appendChild(element);
+               }
+
+               if (fragment) this.appendChild(fragment);
+
+               return this;
+       },
+
+       appendText: function(text, where){
+               return this.grab(this.getDocument().newTextNode(text), where);
+       },
+
+       grab: function(el, where){
+               inserters[where || 'bottom'](document.id(el, true), this);
+               return this;
+       },
+
+       inject: function(el, where){
+               inserters[where || 'bottom'](this, document.id(el, true));
+               return this;
+       },
+
+       replaces: function(el){
+               el = document.id(el, true);
+               el.parentNode.replaceChild(this, el);
+               return this;
+       },
+
+       wraps: function(el, where){
+               el = document.id(el, true);
+               return this.replaces(el).grab(el, where);
+       },
+
+       getSelected: function(){
+               this.selectedIndex; // Safari 3.2.1
+               return new Elements(Array.from(this.options).filter(function(option){
+                       return option.selected;
+               }));
+       },
+
+       toQueryString: function(){
+               var queryString = [];
+               this.getElements('input, select, textarea').each(function(el){
+                       var type = el.type;
+                       if (!el.name || el.disabled || type == 'submit' || type == 'reset' || type == 'file' || type == 'image') return;
+
+                       var value = (el.get('tag') == 'select') ? el.getSelected().map(function(opt){
+                               // IE
+                               return document.id(opt).get('value');
+                       }) : ((type == 'radio' || type == 'checkbox') && !el.checked) ? null : el.get('value');
+
+                       Array.from(value).each(function(val){
+                               if (typeof val != 'undefined') queryString.push(encodeURIComponent(el.name) + '=' + encodeURIComponent(val));
+                       });
+               });
+               return queryString.join('&');
+       }
+
+});
+
+var collected = {}, storage = {};
+
+var get = function(uid){
+       return (storage[uid] || (storage[uid] = {}));
+};
+
+var clean = function(item){
+       var uid = item.uniqueNumber;
+       if (item.removeEvents) item.removeEvents();
+       if (item.clearAttributes) item.clearAttributes();
+       if (uid != null){
+               delete collected[uid];
+               delete storage[uid];
+       }
+       return item;
+};
+
+var formProps = {input: 'checked', option: 'selected', textarea: 'value'};
+
+Element.implement({
+
+       destroy: function(){
+               var children = clean(this).getElementsByTagName('*');
+               Array.each(children, clean);
+               Element.dispose(this);
+               return null;
+       },
+
+       empty: function(){
+               Array.from(this.childNodes).each(Element.dispose);
+               return this;
+       },
+
+       dispose: function(){
+               return (this.parentNode) ? this.parentNode.removeChild(this) : this;
+       },
+
+       clone: function(contents, keepid){
+               contents = contents !== false;
+               var clone = this.cloneNode(contents), ce = [clone], te = [this], i;
+
+               if (contents){
+                       ce.append(Array.from(clone.getElementsByTagName('*')));
+                       te.append(Array.from(this.getElementsByTagName('*')));
+               }
+
+               for (i = ce.length; i--;){
+                       var node = ce[i], element = te[i];
+                       if (!keepid) node.removeAttribute('id');
+                       /*<ltIE9>*/
+                       if (node.clearAttributes){
+                               node.clearAttributes();
+                               node.mergeAttributes(element);
+                               node.removeAttribute('uniqueNumber');
+                               if (node.options){
+                                       var no = node.options, eo = element.options;
+                                       for (var j = no.length; j--;) no[j].selected = eo[j].selected;
+                               }
+                       }
+                       /*</ltIE9>*/
+                       var prop = formProps[element.tagName.toLowerCase()];
+                       if (prop && element[prop]) node[prop] = element[prop];
+               }
+
+               /*<ltIE9>*/
+               if (Browser.ie){
+                       var co = clone.getElementsByTagName('object'), to = this.getElementsByTagName('object');
+                       for (i = co.length; i--;) co[i].outerHTML = to[i].outerHTML;
+               }
+               /*</ltIE9>*/
+               return document.id(clone);
+       }
+
+});
+
+[Element, Window, Document].invoke('implement', {
+
+       addListener: function(type, fn){
+               if (type == 'unload'){
+                       var old = fn, self = this;
+                       fn = function(){
+                               self.removeListener('unload', fn);
+                               old();
+                       };
+               } else {
+                       collected[Slick.uidOf(this)] = this;
+               }
+               if (this.addEventListener) this.addEventListener(type, fn, !!arguments[2]);
+               else this.attachEvent('on' + type, fn);
+               return this;
+       },
+
+       removeListener: function(type, fn){
+               if (this.removeEventListener) this.removeEventListener(type, fn, !!arguments[2]);
+               else this.detachEvent('on' + type, fn);
+               return this;
+       },
+
+       retrieve: function(property, dflt){
+               var storage = get(Slick.uidOf(this)), prop = storage[property];
+               if (dflt != null && prop == null) prop = storage[property] = dflt;
+               return prop != null ? prop : null;
+       },
+
+       store: function(property, value){
+               var storage = get(Slick.uidOf(this));
+               storage[property] = value;
+               return this;
+       },
+
+       eliminate: function(property){
+               var storage = get(Slick.uidOf(this));
+               delete storage[property];
+               return this;
+       }
+
+});
+
+/*<ltIE9>*/
+if (window.attachEvent && !window.addEventListener) window.addListener('unload', function(){
+       Object.each(collected, clean);
+       if (window.CollectGarbage) CollectGarbage();
+});
+/*</ltIE9>*/
+
+Element.Properties = {};
+
+//<1.2compat>
+
+Element.Properties = new Hash;
+
+//</1.2compat>
+
+Element.Properties.style = {
+
+       set: function(style){
+               this.style.cssText = style;
+       },
+
+       get: function(){
+               return this.style.cssText;
+       },
+
+       erase: function(){
+               this.style.cssText = '';
+       }
+
+};
+
+Element.Properties.tag = {
+
+       get: function(){
+               return this.tagName.toLowerCase();
+       }
+
+};
+
+Element.Properties.html = {
+
+       set: function(html){
+               if (html == null) html = '';
+               else if (typeOf(html) == 'array') html = html.join('');
+               this.innerHTML = html;
+       },
+
+       erase: function(){
+               this.innerHTML = '';
+       }
+
+};
+
+/*<ltIE9>*/
+// technique by jdbarlett - http://jdbartlett.com/innershiv/
+var div = document.createElement('div');
+div.innerHTML = '<nav></nav>';
+var supportsHTML5Elements = (div.childNodes.length == 1);
+if (!supportsHTML5Elements){
+       var tags = 'abbr article aside audio canvas datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video'.split(' '),
+               fragment = document.createDocumentFragment(), l = tags.length;
+       while (l--) fragment.createElement(tags[l]);
+}
+div = null;
+/*</ltIE9>*/
+
+/*<IE>*/
+var supportsTableInnerHTML = Function.attempt(function(){
+       var table = document.createElement('table');
+       table.innerHTML = '<tr><td></td></tr>';
+       return true;
+});
+
+/*<ltFF4>*/
+var tr = document.createElement('tr'), html = '<td></td>';
+tr.innerHTML = html;
+var supportsTRInnerHTML = (tr.innerHTML == html);
+tr = null;
+/*</ltFF4>*/
+
+if (!supportsTableInnerHTML || !supportsTRInnerHTML || !supportsHTML5Elements){
+
+       Element.Properties.html.set = (function(set){
+
+               var translations = {
+                       table: [1, '<table>', '</table>'],
+                       select: [1, '<select>', '</select>'],
+                       tbody: [2, '<table><tbody>', '</tbody></table>'],
+                       tr: [3, '<table><tbody><tr>', '</tr></tbody></table>']
+               };
+
+               translations.thead = translations.tfoot = translations.tbody;
+
+               return function(html){
+                       var wrap = translations[this.get('tag')];
+                       if (!wrap && !supportsHTML5Elements) wrap = [0, '', ''];
+                       if (!wrap) return set.call(this, html);
+
+                       var level = wrap[0], wrapper = document.createElement('div'), target = wrapper;
+                       if (!supportsHTML5Elements) fragment.appendChild(wrapper);
+                       wrapper.innerHTML = [wrap[1], html, wrap[2]].flatten().join('');
+                       while (level--) target = target.firstChild;
+                       this.empty().adopt(target.childNodes);
+                       if (!supportsHTML5Elements) fragment.removeChild(wrapper);
+                       wrapper = null;
+               };
+
+       })(Element.Properties.html.set);
+}
+/*</IE>*/
+
+/*<ltIE9>*/
+var testForm = document.createElement('form');
+testForm.innerHTML = '<select><option>s</option></select>';
+
+if (testForm.firstChild.value != 's') Element.Properties.value = {
+
+       set: function(value){
+               var tag = this.get('tag');
+               if (tag != 'select') return this.setProperty('value', value);
+               var options = this.getElements('option');
+               for (var i = 0; i < options.length; i++){
+                       var option = options[i],
+                               attr = option.getAttributeNode('value'),
+                               optionValue = (attr && attr.specified) ? option.value : option.get('text');
+                       if (optionValue == value) return option.selected = true;
+               }
+       },
+
+       get: function(){
+               var option = this, tag = option.get('tag');
+
+               if (tag != 'select' && tag != 'option') return this.getProperty('value');
+
+               if (tag == 'select' && !(option = option.getSelected()[0])) return '';
+
+               var attr = option.getAttributeNode('value');
+               return (attr && attr.specified) ? option.value : option.get('text');
+       }
+
+};
+testForm = null;
+/*</ltIE9>*/
+
+/*<IE>*/
+if (document.createElement('div').getAttributeNode('id')) Element.Properties.id = {
+       set: function(id){
+               this.id = this.getAttributeNode('id').value = id;
+       },
+       get: function(){
+               return this.id || null;
+       },
+       erase: function(){
+               this.id = this.getAttributeNode('id').value = '';
+       }
+};
+/*</IE>*/
+
+})();
+
+
+// Begin: Source/Class/Class.js
+/*
+---
+
+name: Class
+
+description: Contains the Class Function for easily creating, extending, and implementing reusable Classes.
+
+license: MIT-style license.
+
+requires: [Array, String, Function, Number]
+
+provides: Class
+
+...
+*/
+
+(function(){
+
+var Class = this.Class = new Type('Class', function(params){
+       if (instanceOf(params, Function)) params = {initialize: params};
+
+       var newClass = function(){
+               reset(this);
+               if (newClass.$prototyping) return this;
+               this.$caller = null;
+               var value = (this.initialize) ? this.initialize.apply(this, arguments) : this;
+               this.$caller = this.caller = null;
+               return value;
+       }.extend(this).implement(params);
+
+       newClass.$constructor = Class;
+       newClass.prototype.$constructor = newClass;
+       newClass.prototype.parent = parent;
+
+       return newClass;
+});
+
+var parent = function(){
+       if (!this.$caller) throw new Error('The method "parent" cannot be called.');
+       var name = this.$caller.$name,
+               parent = this.$caller.$owner.parent,
+               previous = (parent) ? parent.prototype[name] : null;
+       if (!previous) throw new Error('The method "' + name + '" has no parent.');
+       return previous.apply(this, arguments);
+};
+
+var reset = function(object){
+       for (var key in object){
+               var value = object[key];
+               switch (typeOf(value)){
+                       case 'object':
+                               var F = function(){};
+                               F.prototype = value;
+                               object[key] = reset(new F);
+                       break;
+                       case 'array': object[key] = value.clone(); break;
+               }
+       }
+       return object;
+};
+
+var wrap = function(self, key, method){
+       if (method.$origin) method = method.$origin;
+       var wrapper = function(){
+               if (method.$protected && this.$caller == null) throw new Error('The method "' + key + '" cannot be called.');
+               var caller = this.caller, current = this.$caller;
+               this.caller = current; this.$caller = wrapper;
+               var result = method.apply(this, arguments);
+               this.$caller = current; this.caller = caller;
+               return result;
+       }.extend({$owner: self, $origin: method, $name: key});
+       return wrapper;
+};
+
+var implement = function(key, value, retain){
+       if (Class.Mutators.hasOwnProperty(key)){
+               value = Class.Mutators[key].call(this, value);
+               if (value == null) return this;
+       }
+
+       if (typeOf(value) == 'function'){
+               if (value.$hidden) return this;
+               this.prototype[key] = (retain) ? value : wrap(this, key, value);
+       } else {
+               Object.merge(this.prototype, key, value);
+       }
+
+       return this;
+};
+
+var getInstance = function(klass){
+       klass.$prototyping = true;
+       var proto = new klass;
+       delete klass.$prototyping;
+       return proto;
+};
+
+Class.implement('implement', implement.overloadSetter());
+
+Class.Mutators = {
+
+       Extends: function(parent){
+               this.parent = parent;
+               this.prototype = getInstance(parent);
+       },
+
+       Implements: function(items){
+               Array.from(items).each(function(item){
+                       var instance = new item;
+                       for (var key in instance) implement.call(this, key, instance[key], true);
+               }, this);
+       }
+};
+
+})();
+
+
+// Begin: Source/Class/Class.Extras.js
+/*
+---
+
+name: Class.Extras
+
+description: Contains Utility Classes that can be implemented into your own Classes to ease the execution of many common tasks.
+
+license: MIT-style license.
+
+requires: Class
+
+provides: [Class.Extras, Chain, Events, Options]
+
+...
+*/
+
+(function(){
+
+this.Chain = new Class({
+
+       $chain: [],
+
+       chain: function(){
+               this.$chain.append(Array.flatten(arguments));
+               return this;
+       },
+
+       callChain: function(){
+               return (this.$chain.length) ? this.$chain.shift().apply(this, arguments) : false;
+       },
+
+       clearChain: function(){
+               this.$chain.empty();
+               return this;
+       }
+
+});
+
+var removeOn = function(string){
+       return string.replace(/^on([A-Z])/, function(full, first){
+               return first.toLowerCase();
+       });
+};
+
+this.Events = new Class({
+
+       $events: {},
+
+       addEvent: function(type, fn, internal){
+               type = removeOn(type);
+
+               /*<1.2compat>*/
+               if (fn == $empty) return this;
+               /*</1.2compat>*/
+
+               this.$events[type] = (this.$events[type] || []).include(fn);
+               if (internal) fn.internal = true;
+               return this;
+       },
+
+       addEvents: function(events){
+               for (var type in events) this.addEvent(type, events[type]);
+               return this;
+       },
+
+       fireEvent: function(type, args, delay){
+               type = removeOn(type);
+               var events = this.$events[type];
+               if (!events) return this;
+               args = Array.from(args);
+               events.each(function(fn){
+                       if (delay) fn.delay(delay, this, args);
+                       else fn.apply(this, args);
+               }, this);
+               return this;
+       },
+
+       removeEvent: function(type, fn){
+               type = removeOn(type);
+               var events = this.$events[type];
+               if (events && !fn.internal){
+                       var index =  events.indexOf(fn);
+                       if (index != -1) delete events[index];
+               }
+               return this;
+       },
+
+       removeEvents: function(events){
+               var type;
+               if (typeOf(events) == 'object'){
+                       for (type in events) this.removeEvent(type, events[type]);
+                       return this;
+               }
+               if (events) events = removeOn(events);
+               for (type in this.$events){
+                       if (events && events != type) continue;
+                       var fns = this.$events[type];
+                       for (var i = fns.length; i--;) if (i in fns){
+                               this.removeEvent(type, fns[i]);
+                       }
+               }
+               return this;
+       }
+
+});
+
+this.Options = new Class({
+
+       setOptions: function(){
+               var options = this.options = Object.merge.apply(null, [{}, this.options].append(arguments));
+               if (this.addEvent) for (var option in options){
+                       if (typeOf(options[option]) != 'function' || !(/^on[A-Z]/).test(option)) continue;
+                       this.addEvent(option, options[option]);
+                       delete options[option];
+               }
+               return this;
+       }
+
+});
+
+})();
+
+
+// Begin: Source/Request/Request.js
+/*
+---
+
+name: Request
+
+description: Powerful all purpose Request Class. Uses XMLHTTPRequest.
+
+license: MIT-style license.
+
+requires: [Object, Element, Chain, Events, Options, Browser]
+
+provides: Request
+
+...
+*/
+
+(function(){
+
+var empty = function(){},
+       progressSupport = ('onprogress' in new Browser.Request);
+
+var Request = this.Request = new Class({
+
+       Implements: [Chain, Events, Options],
+
+       options: {/*
+               onRequest: function(){},
+               onLoadstart: function(event, xhr){},
+               onProgress: function(event, xhr){},
+               onComplete: function(){},
+               onCancel: function(){},
+               onSuccess: function(responseText, responseXML){},
+               onFailure: function(xhr){},
+               onException: function(headerName, value){},
+               onTimeout: function(){},
+               user: '',
+               password: '',*/
+               url: '',
+               data: '',
+               headers: {
+                       'X-Requested-With': 'XMLHttpRequest',
+                       'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
+               },
+               async: true,
+               format: false,
+               method: 'post',
+               link: 'ignore',
+               isSuccess: null,
+               emulation: true,
+               urlEncoded: true,
+               encoding: 'utf-8',
+               evalScripts: false,
+               evalResponse: false,
+               timeout: 0,
+               noCache: false
+       },
+
+       initialize: function(options){
+               this.xhr = new Browser.Request();
+               this.setOptions(options);
+               this.headers = this.options.headers;
+       },
+
+       onStateChange: function(){
+               var xhr = this.xhr;
+               if (xhr.readyState != 4 || !this.running) return;
+               this.running = false;
+               this.status = 0;
+               Function.attempt(function(){
+                       var status = xhr.status;
+                       this.status = (status == 1223) ? 204 : status;
+               }.bind(this));
+               xhr.onreadystatechange = empty;
+               if (progressSupport) xhr.onprogress = xhr.onloadstart = empty;
+               clearTimeout(this.timer);
+
+               this.response = {text: this.xhr.responseText || '', xml: this.xhr.responseXML};
+               if (this.options.isSuccess.call(this, this.status))
+                       this.success(this.response.text, this.response.xml);
+               else
+                       this.failure();
+       },
+
+       isSuccess: function(){
+               var status = this.status;
+               return (status >= 200 && status < 300);
+       },
+
+       isRunning: function(){
+               return !!this.running;
+       },
+
+       processScripts: function(text){
+               if (this.options.evalResponse || (/(ecma|java)script/).test(this.getHeader('Content-type'))) return Browser.exec(text);
+               return text.stripScripts(this.options.evalScripts);
+       },
+
+       success: function(text, xml){
+               this.onSuccess(this.processScripts(text), xml);
+       },
+
+       onSuccess: function(){
+               this.fireEvent('complete', arguments).fireEvent('success', arguments).callChain();
+       },
+
+       failure: function(){
+               this.onFailure();
+       },
+
+       onFailure: function(){
+               this.fireEvent('complete').fireEvent('failure', this.xhr);
+       },
+
+       loadstart: function(event){
+               this.fireEvent('loadstart', [event, this.xhr]);
+       },
+
+       progress: function(event){
+               this.fireEvent('progress', [event, this.xhr]);
+       },
+
+       timeout: function(){
+               this.fireEvent('timeout', this.xhr);
+       },
+
+       setHeader: function(name, value){
+               this.headers[name] = value;
+               return this;
+       },
+
+       getHeader: function(name){
+               return Function.attempt(function(){
+                       return this.xhr.getResponseHeader(name);
+               }.bind(this));
+       },
+
+       check: function(){
+               if (!this.running) return true;
+               switch (this.options.link){
+                       case 'cancel': this.cancel(); return true;
+                       case 'chain': this.chain(this.caller.pass(arguments, this)); return false;
+               }
+               return false;
+       },
+
+       send: function(options){
+               if (!this.check(options)) return this;
+
+               this.options.isSuccess = this.options.isSuccess || this.isSuccess;
+               this.running = true;
+
+               var type = typeOf(options);
+               if (type == 'string' || type == 'element') options = {data: options};
+
+               var old = this.options;
+               options = Object.append({data: old.data, url: old.url, method: old.method}, options);
+               var data = options.data, url = String(options.url), method = options.method.toLowerCase();
+
+               switch (typeOf(data)){
+                       case 'element': data = document.id(data).toQueryString(); break;
+                       case 'object': case 'hash': data = Object.toQueryString(data);
+               }
+
+               if (this.options.format){
+                       var format = 'format=' + this.options.format;
+                       data = (data) ? format + '&' + data : format;
+               }
+
+               if (this.options.emulation && !['get', 'post'].contains(method)){
+                       var _method = '_method=' + method;
+                       data = (data) ? _method + '&' + data : _method;
+                       method = 'post';
+               }
+
+               if (this.options.urlEncoded && ['post', 'put'].contains(method)){
+                       var encoding = (this.options.encoding) ? '; charset=' + this.options.encoding : '';
+                       this.headers['Content-type'] = 'application/x-www-form-urlencoded' + encoding;
+               }
+
+               if (!url) url = document.location.pathname;
+
+               var trimPosition = url.lastIndexOf('/');
+               if (trimPosition > -1 && (trimPosition = url.indexOf('#')) > -1) url = url.substr(0, trimPosition);
+
+               if (this.options.noCache)
+                       url += (url.contains('?') ? '&' : '?') + String.uniqueID();
+
+               if (data && method == 'get'){
+                       url += (url.contains('?') ? '&' : '?') + data;
+                       data = null;
+               }
+
+               var xhr = this.xhr;
+               if (progressSupport){
+                       xhr.onloadstart = this.loadstart.bind(this);
+                       xhr.onprogress = this.progress.bind(this);
+               }
+
+               xhr.open(method.toUpperCase(), url, this.options.async, this.options.user, this.options.password);
+               if (this.options.user && 'withCredentials' in xhr) xhr.withCredentials = true;
+
+               xhr.onreadystatechange = this.onStateChange.bind(this);
+
+               Object.each(this.headers, function(value, key){
+                       try {
+                               xhr.setRequestHeader(key, value);
+                       } catch (e){
+                               this.fireEvent('exception', [key, value]);
+                       }
+               }, this);
+
+               this.fireEvent('request');
+               xhr.send(data);
+               if (!this.options.async) this.onStateChange();
+               else if (this.options.timeout) this.timer = this.timeout.delay(this.options.timeout, this);
+               return this;
+       },
+
+       cancel: function(){
+               if (!this.running) return this;
+               this.running = false;
+               var xhr = this.xhr;
+               xhr.abort();
+               clearTimeout(this.timer);
+               xhr.onreadystatechange = empty;
+               if (progressSupport) xhr.onprogress = xhr.onloadstart = empty;
+               this.xhr = new Browser.Request();
+               this.fireEvent('cancel');
+               return this;
+       }
+
+});
+
+var methods = {};
+['get', 'post', 'put', 'delete', 'GET', 'POST', 'PUT', 'DELETE'].each(function(method){
+       methods[method] = function(data){
+               var object = {
+                       method: method
+               };
+               if (data != null) object.data = data;
+               return this.send(object);
+       };
+});
+
+Request.implement(methods);
+
+Element.Properties.send = {
+
+       set: function(options){
+               var send = this.get('send').cancel();
+               send.setOptions(options);
+               return this;
+       },
+
+       get: function(){
+               var send = this.retrieve('send');
+               if (!send){
+                       send = new Request({
+                               data: this, link: 'cancel', method: this.get('method') || 'post', url: this.get('action')
+                       });
+                       this.store('send', send);
+               }
+               return send;
+       }
+
+};
+
+Element.implement({
+
+       send: function(url){
+               var sender = this.get('send');
+               sender.send({data: this, url: url || sender.options.url});
+               return this;
+       }
+
+});
+
+})();
+
+
+// Begin: Source/Utilities/JSON.js
+/*
+---
+
+name: JSON
+
+description: JSON encoder and decoder.
+
+license: MIT-style license.
+
+SeeAlso: <http://www.json.org/>
+
+requires: [Array, String, Number, Function]
+
+provides: JSON
+
+...
+*/
+
+if (typeof JSON == 'undefined') this.JSON = {};
+
+//<1.2compat>
+
+JSON = new Hash({
+       stringify: JSON.stringify,
+       parse: JSON.parse
+});
+
+//</1.2compat>
+
+(function(){
+
+var special = {'\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\'};
+
+var escape = function(chr){
+       return special[chr] || '\\u' + ('0000' + chr.charCodeAt(0).toString(16)).slice(-4);
+};
+
+JSON.validate = function(string){
+       string = string.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
+                                       replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
+                                       replace(/(?:^|:|,)(?:\s*\[)+/g, '');
+
+       return (/^[\],:{}\s]*$/).test(string);
+};
+
+JSON.encode = JSON.stringify ? function(obj){
+       return JSON.stringify(obj);
+} : function(obj){
+       if (obj && obj.toJSON) obj = obj.toJSON();
+
+       switch (typeOf(obj)){
+               case 'string':
+                       return '"' + obj.replace(/[\x00-\x1f\\"]/g, escape) + '"';
+               case 'array':
+                       return '[' + obj.map(JSON.encode).clean() + ']';
+               case 'object': case 'hash':
+                       var string = [];
+                       Object.each(obj, function(value, key){
+                               var json = JSON.encode(value);
+                               if (json) string.push(JSON.encode(key) + ':' + json);
+                       });
+                       return '{' + string + '}';
+               case 'number': case 'boolean': return '' + obj;
+               case 'null': return 'null';
+       }
+
+       return null;
+};
+
+JSON.decode = function(string, secure){
+       if (!string || typeOf(string) != 'string') return null;
+
+       if (secure || JSON.secure){
+               if (JSON.parse) return JSON.parse(string);
+               if (!JSON.validate(string)) throw new Error('JSON could not decode the input; security is enabled and the value is not secure.');
+       }
+
+       return eval('(' + string + ')');
+};
+
+})();
+
+
+// Begin: Source/Request/Request.JSON.js
+/*
+---
+
+name: Request.JSON
+
+description: Extends the basic Request Class with additional methods for sending and receiving JSON data.
+
+license: MIT-style license.
+
+requires: [Request, JSON]
+
+provides: Request.JSON
+
+...
+*/
+
+Request.JSON = new Class({
+
+       Extends: Request,
+
+       options: {
+               /*onError: function(text, error){},*/
+               secure: true
+       },
+
+       initialize: function(options){
+               this.parent(options);
+               Object.append(this.headers, {
+                       'Accept': 'application/json',
+                       'X-Request': 'JSON'
+               });
+       },
+
+       success: function(text){
+               var json;
+               try {
+                       json = this.response.json = JSON.decode(text, this.options.secure);
+               } catch (error){
+                       this.fireEvent('error', [text, error]);
+                       return;
+               }
+               if (json == null) this.onFailure();
+               else this.onSuccess(json, text);
+       }
+
+});
+
+
+// Begin: Source/Types/DOMEvent.js
+/*
+---
+
+name: Event
+
+description: Contains the Event Type, to make the event object cross-browser.
+
+license: MIT-style license.
+
+requires: [Window, Document, Array, Function, String, Object]
+
+provides: Event
+
+...
+*/
+
+(function() {
+
+var _keys = {};
+
+var DOMEvent = this.DOMEvent = new Type('DOMEvent', function(event, win){
+       if (!win) win = window;
+       event = event || win.event;
+       if (event.$extended) return event;
+       this.event = event;
+       this.$extended = true;
+       this.shift = event.shiftKey;
+       this.control = event.ctrlKey;
+       this.alt = event.altKey;
+       this.meta = event.metaKey;
+       var type = this.type = event.type;
+       var target = event.target || event.srcElement;
+       while (target && target.nodeType == 3) target = target.parentNode;
+       this.target = document.id(target);
+
+       if (type.indexOf('key') == 0){
+               var code = this.code = (event.which || event.keyCode);
+               this.key = _keys[code]/*<1.3compat>*/ || Object.keyOf(Event.Keys, code)/*</1.3compat>*/;
+               if (type == 'keydown'){
+                       if (code > 111 && code < 124) this.key = 'f' + (code - 111);
+                       else if (code > 95 && code < 106) this.key = code - 96;
+               }
+               if (this.key == null) this.key = String.fromCharCode(code).toLowerCase();
+       } else if (type == 'click' || type == 'dblclick' || type == 'contextmenu' || type == 'DOMMouseScroll' || type.indexOf('mouse') == 0){
+               var doc = win.document;
+               doc = (!doc.compatMode || doc.compatMode == 'CSS1Compat') ? doc.html : doc.body;
+               this.page = {
+                       x: (event.pageX != null) ? event.pageX : event.clientX + doc.scrollLeft,
+                       y: (event.pageY != null) ? event.pageY : event.clientY + doc.scrollTop
+               };
+               this.client = {
+                       x: (event.pageX != null) ? event.pageX - win.pageXOffset : event.clientX,
+                       y: (event.pageY != null) ? event.pageY - win.pageYOffset : event.clientY
+               };
+               if (type == 'DOMMouseScroll' || type == 'mousewheel')
+                       this.wheel = (event.wheelDelta) ? event.wheelDelta / 120 : -(event.detail || 0) / 3;
+
+               this.rightClick = (event.which == 3 || event.button == 2);
+               if (type == 'mouseover' || type == 'mouseout'){
+                       var related = event.relatedTarget || event[(type == 'mouseover' ? 'from' : 'to') + 'Element'];
+                       while (related && related.nodeType == 3) related = related.parentNode;
+                       this.relatedTarget = document.id(related);
+               }
+       } else if (type.indexOf('touch') == 0 || type.indexOf('gesture') == 0){
+               this.rotation = event.rotation;
+               this.scale = event.scale;
+               this.targetTouches = event.targetTouches;
+               this.changedTouches = event.changedTouches;
+               var touches = this.touches = event.touches;
+               if (touches && touches[0]){
+                       var touch = touches[0];
+                       this.page = {x: touch.pageX, y: touch.pageY};
+                       this.client = {x: touch.clientX, y: touch.clientY};
+               }
+       }
+
+       if (!this.client) this.client = {};
+       if (!this.page) this.page = {};
+});
+
+DOMEvent.implement({
+
+       stop: function(){
+               return this.preventDefault().stopPropagation();
+       },
+
+       stopPropagation: function(){
+               if (this.event.stopPropagation) this.event.stopPropagation();
+               else this.event.cancelBubble = true;
+               return this;
+       },
+
+       preventDefault: function(){
+               if (this.event.preventDefault) this.event.preventDefault();
+               else this.event.returnValue = false;
+               return this;
+       }
+
+});
+
+DOMEvent.defineKey = function(code, key){
+       _keys[code] = key;
+       return this;
+};
+
+DOMEvent.defineKeys = DOMEvent.defineKey.overloadSetter(true);
+
+DOMEvent.defineKeys({
+       '38': 'up', '40': 'down', '37': 'left', '39': 'right',
+       '27': 'esc', '32': 'space', '8': 'backspace', '9': 'tab',
+       '46': 'delete', '13': 'enter'
+});
+
+})();
+
+/*<1.3compat>*/
+var Event = DOMEvent;
+Event.Keys = {};
+/*</1.3compat>*/
+
+/*<1.2compat>*/
+
+Event.Keys = new Hash(Event.Keys);
+
+/*</1.2compat>*/
+
+
+// Begin: Source/Element/Element.Event.js
+/*
+---
+
+name: Element.Event
+
+description: Contains Element methods for dealing with events. This file also includes mouseenter and mouseleave custom Element Events, if necessary.
+
+license: MIT-style license.
+
+requires: [Element, Event]
+
+provides: Element.Event
+
+...
+*/
+
+(function(){
+
+Element.Properties.events = {set: function(events){
+       this.addEvents(events);
+}};
+
+[Element, Window, Document].invoke('implement', {
+
+       addEvent: function(type, fn){
+               var events = this.retrieve('events', {});
+               if (!events[type]) events[type] = {keys: [], values: []};
+               if (events[type].keys.contains(fn)) return this;
+               events[type].keys.push(fn);
+               var realType = type,
+                       custom = Element.Events[type],
+                       condition = fn,
+                       self = this;
+               if (custom){
+                       if (custom.onAdd) custom.onAdd.call(this, fn, type);
+                       if (custom.condition){
+                               condition = function(event){
+                                       if (custom.condition.call(this, event, type)) return fn.call(this, event);
+                                       return true;
+                               };
+                       }
+                       if (custom.base) realType = Function.from(custom.base).call(this, type);
+               }
+               var defn = function(){
+                       return fn.call(self);
+               };
+               var nativeEvent = Element.NativeEvents[realType];
+               if (nativeEvent){
+                       if (nativeEvent == 2){
+                               defn = function(event){
+                                       event = new DOMEvent(event, self.getWindow());
+                                       if (condition.call(self, event) === false) event.stop();
+                               };
+                       }
+                       this.addListener(realType, defn, arguments[2]);
+               }
+               events[type].values.push(defn);
+               return this;
+       },
+
+       removeEvent: function(type, fn){
+               var events = this.retrieve('events');
+               if (!events || !events[type]) return this;
+               var list = events[type];
+               var index = list.keys.indexOf(fn);
+               if (index == -1) return this;
+               var value = list.values[index];
+               delete list.keys[index];
+               delete list.values[index];
+               var custom = Element.Events[type];
+               if (custom){
+                       if (custom.onRemove) custom.onRemove.call(this, fn, type);
+                       if (custom.base) type = Function.from(custom.base).call(this, type);
+               }
+               return (Element.NativeEvents[type]) ? this.removeListener(type, value, arguments[2]) : this;
+       },
+
+       addEvents: function(events){
+               for (var event in events) this.addEvent(event, events[event]);
+               return this;
+       },
+
+       removeEvents: function(events){
+               var type;
+               if (typeOf(events) == 'object'){
+                       for (type in events) this.removeEvent(type, events[type]);
+                       return this;
+               }
+               var attached = this.retrieve('events');
+               if (!attached) return this;
+               if (!events){
+                       for (type in attached) this.removeEvents(type);
+                       this.eliminate('events');
+               } else if (attached[events]){
+                       attached[events].keys.each(function(fn){
+                               this.removeEvent(events, fn);
+                       }, this);
+                       delete attached[events];
+               }
+               return this;
+       },
+
+       fireEvent: function(type, args, delay){
+               var events = this.retrieve('events');
+               if (!events || !events[type]) return this;
+               args = Array.from(args);
+
+               events[type].keys.each(function(fn){
+                       if (delay) fn.delay(delay, this, args);
+                       else fn.apply(this, args);
+               }, this);
+               return this;
+       },
+
+       cloneEvents: function(from, type){
+               from = document.id(from);
+               var events = from.retrieve('events');
+               if (!events) return this;
+               if (!type){
+                       for (var eventType in events) this.cloneEvents(from, eventType);
+               } else if (events[type]){
+                       events[type].keys.each(function(fn){
+                               this.addEvent(type, fn);
+                       }, this);
+               }
+               return this;
+       }
+
+});
+
+Element.NativeEvents = {
+       click: 2, dblclick: 2, mouseup: 2, mousedown: 2, contextmenu: 2, //mouse buttons
+       mousewheel: 2, DOMMouseScroll: 2, //mouse wheel
+       mouseover: 2, mouseout: 2, mousemove: 2, selectstart: 2, selectend: 2, //mouse movement
+       keydown: 2, keypress: 2, keyup: 2, //keyboard
+       orientationchange: 2, // mobile
+       touchstart: 2, touchmove: 2, touchend: 2, touchcancel: 2, // touch
+       gesturestart: 2, gesturechange: 2, gestureend: 2, // gesture
+       focus: 2, blur: 2, change: 2, reset: 2, select: 2, submit: 2, paste: 2, input: 2, //form elements
+       load: 2, unload: 1, beforeunload: 2, resize: 1, move: 1, DOMContentLoaded: 1, readystatechange: 1, //window
+       error: 1, abort: 1, scroll: 1 //misc
+};
+
+Element.Events = {mousewheel: {
+       base: (Browser.firefox) ? 'DOMMouseScroll' : 'mousewheel'
+}};
+
+if ('onmouseenter' in document.documentElement){
+       Element.NativeEvents.mouseenter = Element.NativeEvents.mouseleave = 2;
+} else {
+       var check = function(event){
+               var related = event.relatedTarget;
+               if (related == null) return true;
+               if (!related) return false;
+               return (related != this && related.prefix != 'xul' && typeOf(this) != 'document' && !this.contains(related));
+       };
+
+       Element.Events.mouseenter = {
+               base: 'mouseover',
+               condition: check
+       };
+
+       Element.Events.mouseleave = {
+               base: 'mouseout',
+               condition: check
+       };
+}
+
+/*<ltIE9>*/
+if (!window.addEventListener){
+       Element.NativeEvents.propertychange = 2;
+       Element.Events.change = {
+               base: function(){
+                       var type = this.type;
+                       return (this.get('tag') == 'input' && (type == 'radio' || type == 'checkbox')) ? 'propertychange' : 'change'
+               },
+               condition: function(event){
+                       return this.type != 'radio' || (event.event.propertyName == 'checked' && this.checked);
+               }
+       }
+}
+/*</ltIE9>*/
+
+//<1.2compat>
+
+Element.Events = new Hash(Element.Events);
+
+//</1.2compat>
+
+})();
+
+
+// Begin: Source/Element/Element.Delegation.js
+/*
+---
+
+name: Element.Delegation
+
+description: Extends the Element native object to include the delegate method for more efficient event management.
+
+license: MIT-style license.
+
+requires: [Element.Event]
+
+provides: [Element.Delegation]
+
+...
+*/
+
+(function(){
+
+var eventListenerSupport = !!window.addEventListener;
+
+Element.NativeEvents.focusin = Element.NativeEvents.focusout = 2;
+
+var bubbleUp = function(self, match, fn, event, target){
+       while (target && target != self){
+               if (match(target, event)) return fn.call(target, event, target);
+               target = document.id(target.parentNode);
+       }
+};
+
+var map = {
+       mouseenter: {
+               base: 'mouseover'
+       },
+       mouseleave: {
+               base: 'mouseout'
+       },
+       focus: {
+               base: 'focus' + (eventListenerSupport ? '' : 'in'),
+               capture: true
+       },
+       blur: {
+               base: eventListenerSupport ? 'blur' : 'focusout',
+               capture: true
+       }
+};
+
+/*<ltIE9>*/
+var _key = '$delegation:';
+var formObserver = function(type){
+
+       return {
+
+               base: 'focusin',
+
+               remove: function(self, uid){
+                       var list = self.retrieve(_key + type + 'listeners', {})[uid];
+                       if (list && list.forms) for (var i = list.forms.length; i--;){
+                               list.forms[i].removeEvent(type, list.fns[i]);
+                       }
+               },
+
+               listen: function(self, match, fn, event, target, uid){
+                       var form = (target.get('tag') == 'form') ? target : event.target.getParent('form');
+                       if (!form) return;
+
+                       var listeners = self.retrieve(_key + type + 'listeners', {}),
+                               listener = listeners[uid] || {forms: [], fns: []},
+                               forms = listener.forms, fns = listener.fns;
+
+                       if (forms.indexOf(form) != -1) return;
+                       forms.push(form);
+
+                       var _fn = function(event){
+                               bubbleUp(self, match, fn, event, target);
+                       };
+                       form.addEvent(type, _fn);
+                       fns.push(_fn);
+
+                       listeners[uid] = listener;
+                       self.store(_key + type + 'listeners', listeners);
+               }
+       };
+};
+
+var inputObserver = function(type){
+       return {
+               base: 'focusin',
+               listen: function(self, match, fn, event, target){
+                       var events = {blur: function(){
+                               this.removeEvents(events);
+                       }};
+                       events[type] = function(event){
+                               bubbleUp(self, match, fn, event, target);
+                       };
+                       event.target.addEvents(events);
+               }
+       };
+};
+
+if (!eventListenerSupport) Object.append(map, {
+       submit: formObserver('submit'),
+       reset: formObserver('reset'),
+       change: inputObserver('change'),
+       select: inputObserver('select')
+});
+/*</ltIE9>*/
+
+var proto = Element.prototype,
+       addEvent = proto.addEvent,
+       removeEvent = proto.removeEvent;
+
+var relay = function(old, method){
+       return function(type, fn, useCapture){
+               if (type.indexOf(':relay') == -1) return old.call(this, type, fn, useCapture);
+               var parsed = Slick.parse(type).expressions[0][0];
+               if (parsed.pseudos[0].key != 'relay') return old.call(this, type, fn, useCapture);
+               var newType = parsed.tag;
+               parsed.pseudos.slice(1).each(function(pseudo){
+                       newType += ':' + pseudo.key + (pseudo.value ? '(' + pseudo.value + ')' : '');
+               });
+               old.call(this, type, fn);
+               return method.call(this, newType, parsed.pseudos[0].value, fn);
+       };
+};
+
+var delegation = {
+
+       addEvent: function(type, match, fn){
+               var storage = this.retrieve('$delegates', {}), stored = storage[type];
+               if (stored) for (var _uid in stored){
+                       if (stored[_uid].fn == fn && stored[_uid].match == match) return this;
+               }
+
+               var _type = type, _match = match, _fn = fn, _map = map[type] || {};
+               type = _map.base || _type;
+
+               match = function(target){
+                       return Slick.match(target, _match);
+               };
+
+               var elementEvent = Element.Events[_type];
+               if (elementEvent && elementEvent.condition){
+                       var __match = match, condition = elementEvent.condition;
+                       match = function(target, event){
+                               return __match(target, event) && condition.call(target, event, type);
+                       };
+               }
+
+               var self = this, uid = String.uniqueID();
+               var delegator = _map.listen ? function(event, target){
+                       if (!target && event && event.target) target = event.target;
+                       if (target) _map.listen(self, match, fn, event, target, uid);
+               } : function(event, target){
+                       if (!target && event && event.target) target = event.target;
+                       if (target) bubbleUp(self, match, fn, event, target);
+               };
+
+               if (!stored) stored = {};
+               stored[uid] = {
+                       match: _match,
+                       fn: _fn,
+                       delegator: delegator
+               };
+               storage[_type] = stored;
+               return addEvent.call(this, type, delegator, _map.capture);
+       },
+
+       removeEvent: function(type, match, fn, _uid){
+               var storage = this.retrieve('$delegates', {}), stored = storage[type];
+               if (!stored) return this;
+
+               if (_uid){
+                       var _type = type, delegator = stored[_uid].delegator, _map = map[type] || {};
+                       type = _map.base || _type;
+                       if (_map.remove) _map.remove(this, _uid);
+                       delete stored[_uid];
+                       storage[_type] = stored;
+                       return removeEvent.call(this, type, delegator);
+               }
+
+               var __uid, s;
+               if (fn) for (__uid in stored){
+                       s = stored[__uid];
+                       if (s.match == match && s.fn == fn) return delegation.removeEvent.call(this, type, match, fn, __uid);
+               } else for (__uid in stored){
+                       s = stored[__uid];
+                       if (s.match == match) delegation.removeEvent.call(this, type, match, s.fn, __uid);
+               }
+               return this;
+       }
+
+};
+
+[Element, Window, Document].invoke('implement', {
+       addEvent: relay(addEvent, delegation.addEvent),
+       removeEvent: relay(removeEvent, delegation.removeEvent)
+});
+
+})();
+
+
+// Begin: Source/Fx/Fx.js
+/*
+---
+
+name: Fx
+
+description: Contains the basic animation logic to be extended by all other Fx Classes.
+
+license: MIT-style license.
+
+requires: [Chain, Events, Options]
+
+provides: Fx
+
+...
+*/
+
+(function(){
+
+var Fx = this.Fx = new Class({
+
+       Implements: [Chain, Events, Options],
+
+       options: {
+               /*
+               onStart: nil,
+               onCancel: nil,
+               onComplete: nil,
+               */
+               fps: 60,
+               unit: false,
+               duration: 500,
+               frames: null,
+               frameSkip: true,
+               link: 'ignore'
+       },
+
+       initialize: function(options){
+               this.subject = this.subject || this;
+               this.setOptions(options);
+       },
+
+       getTransition: function(){
+               return function(p){
+                       return -(Math.cos(Math.PI * p) - 1) / 2;
+               };
+       },
+
+       step: function(now){
+               if (this.options.frameSkip){
+                       var diff = (this.time != null) ? (now - this.time) : 0, frames = diff / this.frameInterval;
+                       this.time = now;
+                       this.frame += frames;
+               } else {
+                       this.frame++;
+               }
+
+               if (this.frame < this.frames){
+                       var delta = this.transition(this.frame / this.frames);
+                       this.set(this.compute(this.from, this.to, delta));
+               } else {
+                       this.frame = this.frames;
+                       this.set(this.compute(this.from, this.to, 1));
+                       this.stop();
+               }
+       },
+
+       set: function(now){
+               return now;
+       },
+
+       compute: function(from, to, delta){
+               return Fx.compute(from, to, delta);
+       },
+
+       check: function(){
+               if (!this.isRunning()) return true;
+               switch (this.options.link){
+                       case 'cancel': this.cancel(); return true;
+                       case 'chain': this.chain(this.caller.pass(arguments, this)); return false;
+               }
+               return false;
+       },
+
+       start: function(from, to){
+               if (!this.check(from, to)) return this;
+               this.from = from;
+               this.to = to;
+               this.frame = (this.options.frameSkip) ? 0 : -1;
+               this.time = null;
+               this.transition = this.getTransition();
+               var frames = this.options.frames, fps = this.options.fps, duration = this.options.duration;
+               this.duration = Fx.Durations[duration] || duration.toInt();
+               this.frameInterval = 1000 / fps;
+               this.frames = frames || Math.round(this.duration / this.frameInterval);
+               this.fireEvent('start', this.subject);
+               pushInstance.call(this, fps);
+               return this;
+       },
+
+       stop: function(){
+               if (this.isRunning()){
+                       this.time = null;
+                       pullInstance.call(this, this.options.fps);
+                       if (this.frames == this.frame){
+                               this.fireEvent('complete', this.subject);
+                               if (!this.callChain()) this.fireEvent('chainComplete', this.subject);
+                       } else {
+                               this.fireEvent('stop', this.subject);
+                       }
+               }
+               return this;
+       },
+
+       cancel: function(){
+               if (this.isRunning()){
+                       this.time = null;
+                       pullInstance.call(this, this.options.fps);
+                       this.frame = this.frames;
+                       this.fireEvent('cancel', this.subject).clearChain();
+               }
+               return this;
+       },
+
+       pause: function(){
+               if (this.isRunning()){
+                       this.time = null;
+                       pullInstance.call(this, this.options.fps);
+               }
+               return this;
+       },
+
+       resume: function(){
+               if ((this.frame < this.frames) && !this.isRunning()) pushInstance.call(this, this.options.fps);
+               return this;
+       },
+
+       isRunning: function(){
+               var list = instances[this.options.fps];
+               return list && list.contains(this);
+       }
+
+});
+
+Fx.compute = function(from, to, delta){
+       return (to - from) * delta + from;
+};
+
+Fx.Durations = {'short': 250, 'normal': 500, 'long': 1000};
+
+// global timers
+
+var instances = {}, timers = {};
+
+var loop = function(){
+       var now = Date.now();
+       for (var i = this.length; i--;){
+               var instance = this[i];
+               if (instance) instance.step(now);
+       }
+};
+
+var pushInstance = function(fps){
+       var list = instances[fps] || (instances[fps] = []);
+       list.push(this);
+       if (!timers[fps]) timers[fps] = loop.periodical(Math.round(1000 / fps), list);
+};
+
+var pullInstance = function(fps){
+       var list = instances[fps];
+       if (list){
+               list.erase(this);
+               if (!list.length && timers[fps]){
+                       delete instances[fps];
+                       timers[fps] = clearInterval(timers[fps]);
+               }
+       }
+};
+
+})();
+
+
+// Begin: Source/Element/Element.Style.js
+/*
+---
+
+name: Element.Style
+
+description: Contains methods for interacting with the styles of Elements in a fashionable way.
+
+license: MIT-style license.
+
+requires: Element
+
+provides: Element.Style
+
+...
+*/
+
+(function(){
+
+var html = document.html;
+
+//<ltIE9>
+// Check for oldIE, which does not remove styles when they're set to null
+var el = document.createElement('div');
+el.style.color = 'red';
+el.style.color = null;
+var doesNotRemoveStyles = el.style.color == 'red';
+el = null;
+//</ltIE9>
+
+Element.Properties.styles = {set: function(styles){
+       this.setStyles(styles);
+}};
+
+var hasOpacity = (html.style.opacity != null),
+       hasFilter = (html.style.filter != null),
+       reAlpha = /alpha\(opacity=([\d.]+)\)/i;
+
+var setVisibility = function(element, opacity){
+       element.store('$opacity', opacity);
+       element.style.visibility = opacity > 0 || opacity == null ? 'visible' : 'hidden';
+};
+
+var setOpacity = (hasOpacity ? function(element, opacity){
+       element.style.opacity = opacity;
+} : (hasFilter ? function(element, opacity){
+       var style = element.style;
+       if (!element.currentStyle || !element.currentStyle.hasLayout) style.zoom = 1;
+       if (opacity == null || opacity == 1) opacity = '';
+       else opacity = 'alpha(opacity=' + (opacity * 100).limit(0, 100).round() + ')';
+       var filter = style.filter || element.getComputedStyle('filter') || '';
+       style.filter = reAlpha.test(filter) ? filter.replace(reAlpha, opacity) : filter + opacity;
+       if (!style.filter) style.removeAttribute('filter');
+} : setVisibility));
+
+var getOpacity = (hasOpacity ? function(element){
+       var opacity = element.style.opacity || element.getComputedStyle('opacity');
+       return (opacity == '') ? 1 : opacity.toFloat();
+} : (hasFilter ? function(element){
+       var filter = (element.style.filter || element.getComputedStyle('filter')),
+               opacity;
+       if (filter) opacity = filter.match(reAlpha);
+       return (opacity == null || filter == null) ? 1 : (opacity[1] / 100);
+} : function(element){
+       var opacity = element.retrieve('$opacity');
+       if (opacity == null) opacity = (element.style.visibility == 'hidden' ? 0 : 1);
+       return opacity;
+}));
+
+var floatName = (html.style.cssFloat == null) ? 'styleFloat' : 'cssFloat';
+
+Element.implement({
+
+       getComputedStyle: function(property){
+               if (this.currentStyle) return this.currentStyle[property.camelCase()];
+               var defaultView = Element.getDocument(this).defaultView,
+                       computed = defaultView ? defaultView.getComputedStyle(this, null) : null;
+               return (computed) ? computed.getPropertyValue((property == floatName) ? 'float' : property.hyphenate()) : null;
+       },
+
+       setStyle: function(property, value){
+               if (property == 'opacity'){
+                       if (value != null) value = parseFloat(value);
+                       setOpacity(this, value);
+                       return this;
+               }
+               property = (property == 'float' ? floatName : property).camelCase();
+               if (typeOf(value) != 'string'){
+                       var map = (Element.Styles[property] || '@').split(' ');
+                       value = Array.from(value).map(function(val, i){
+                               if (!map[i]) return '';
+                               return (typeOf(val) == 'number') ? map[i].replace('@', Math.round(val)) : val;
+                       }).join(' ');
+               } else if (value == String(Number(value))){
+                       value = Math.round(value);
+               }
+               this.style[property] = value;
+               //<ltIE9>
+               if ((value == '' || value == null) && doesNotRemoveStyles && this.style.removeAttribute){
+                       this.style.removeAttribute(property);
+               }
+               //</ltIE9>
+               return this;
+       },
+
+       getStyle: function(property){
+               if (property == 'opacity') return getOpacity(this);
+               property = (property == 'float' ? floatName : property).camelCase();
+               var result = this.style[property];
+               if (!result || property == 'zIndex'){
+                       result = [];
+                       for (var style in Element.ShortStyles){
+                               if (property != style) continue;
+                               for (var s in Element.ShortStyles[style]) result.push(this.getStyle(s));
+                               return result.join(' ');
+                       }
+                       result = this.getComputedStyle(property);
+               }
+               if (result){
+                       result = String(result);
+                       var color = result.match(/rgba?\([\d\s,]+\)/);
+                       if (color) result = result.replace(color[0], color[0].rgbToHex());
+               }
+               if (Browser.opera || Browser.ie){
+                       if ((/^(height|width)$/).test(property) && !(/px$/.test(result))){
+                               var values = (property == 'width') ? ['left', 'right'] : ['top', 'bottom'], size = 0;
+                               values.each(function(value){
+                                       size += this.getStyle('border-' + value + '-width').toInt() + this.getStyle('padding-' + value).toInt();
+                               }, this);
+                               return this['offset' + property.capitalize()] - size + 'px';
+                       }
+                       if (Browser.ie && (/^border(.+)Width|margin|padding/).test(property) && isNaN(parseFloat(result))){
+                               return '0px';
+                       }
+               }
+               return result;
+       },
+
+       setStyles: function(styles){
+               for (var style in styles) this.setStyle(style, styles[style]);
+               return this;
+       },
+
+       getStyles: function(){
+               var result = {};
+               Array.flatten(arguments).each(function(key){
+                       result[key] = this.getStyle(key);
+               }, this);
+               return result;
+       }
+
+});
+
+Element.Styles = {
+       left: '@px', top: '@px', bottom: '@px', right: '@px',
+       width: '@px', height: '@px', maxWidth: '@px', maxHeight: '@px', minWidth: '@px', minHeight: '@px',
+       backgroundColor: 'rgb(@, @, @)', backgroundPosition: '@px @px', color: 'rgb(@, @, @)',
+       fontSize: '@px', letterSpacing: '@px', lineHeight: '@px', clip: 'rect(@px @px @px @px)',
+       margin: '@px @px @px @px', padding: '@px @px @px @px', border: '@px @ rgb(@, @, @) @px @ rgb(@, @, @) @px @ rgb(@, @, @)',
+       borderWidth: '@px @px @px @px', borderStyle: '@ @ @ @', borderColor: 'rgb(@, @, @) rgb(@, @, @) rgb(@, @, @) rgb(@, @, @)',
+       zIndex: '@', 'zoom': '@', fontWeight: '@', textIndent: '@px', opacity: '@'
+};
+
+//<1.3compat>
+
+Element.implement({
+
+       setOpacity: function(value){
+               setOpacity(this, value);
+               return this;
+       },
+
+       getOpacity: function(){
+               return getOpacity(this);
+       }
+
+});
+
+Element.Properties.opacity = {
+
+       set: function(opacity){
+               setOpacity(this, opacity);
+               setVisibility(this, opacity);
+       },
+
+       get: function(){
+               return getOpacity(this);
+       }
+
+};
+
+//</1.3compat>
+
+//<1.2compat>
+
+Element.Styles = new Hash(Element.Styles);
+
+//</1.2compat>
+
+Element.ShortStyles = {margin: {}, padding: {}, border: {}, borderWidth: {}, borderStyle: {}, borderColor: {}};
+
+['Top', 'Right', 'Bottom', 'Left'].each(function(direction){
+       var Short = Element.ShortStyles;
+       var All = Element.Styles;
+       ['margin', 'padding'].each(function(style){
+               var sd = style + direction;
+               Short[style][sd] = All[sd] = '@px';
+       });
+       var bd = 'border' + direction;
+       Short.border[bd] = All[bd] = '@px @ rgb(@, @, @)';
+       var bdw = bd + 'Width', bds = bd + 'Style', bdc = bd + 'Color';
+       Short[bd] = {};
+       Short.borderWidth[bdw] = Short[bd][bdw] = All[bdw] = '@px';
+       Short.borderStyle[bds] = Short[bd][bds] = All[bds] = '@';
+       Short.borderColor[bdc] = Short[bd][bdc] = All[bdc] = 'rgb(@, @, @)';
+});
+
+})();
+
+
+// Begin: Source/Fx/Fx.CSS.js
+/*
+---
+
+name: Fx.CSS
+
+description: Contains the CSS animation logic. Used by Fx.Tween, Fx.Morph, Fx.Elements.
+
+license: MIT-style license.
+
+requires: [Fx, Element.Style]
+
+provides: Fx.CSS
+
+...
+*/
+
+Fx.CSS = new Class({
+
+       Extends: Fx,
+
+       //prepares the base from/to object
+
+       prepare: function(element, property, values){
+               values = Array.from(values);
+               var from = values[0], to = values[1];
+               if (to == null){
+                       to = from;
+                       from = element.getStyle(property);
+                       var unit = this.options.unit;
+                       // adapted from: https://github.com/ryanmorr/fx/blob/master/fx.js#L299
+                       if (unit && from.slice(-unit.length) != unit && parseFloat(from) != 0){
+                               element.setStyle(property, to + unit);
+                               var value = element.getComputedStyle(property);
+                               // IE and Opera support pixelLeft or pixelWidth
+                               if (!(/px$/.test(value))){
+                                       value = element.style[('pixel-' + property).camelCase()];
+                                       if (value == null){
+                                               // adapted from Dean Edwards' http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
+                                               var left = element.style.left;
+                                               element.style.left = to + unit;
+                                               value = element.style.pixelLeft;
+                                               element.style.left = left;
+                                       }
+                               }
+                               from = (to || 1) / (parseFloat(value) || 1) * (parseFloat(from) || 0);
+                               element.setStyle(property, from + unit);
+                       }
+               }
+               return {from: this.parse(from), to: this.parse(to)};
+       },
+
+       //parses a value into an array
+
+       parse: function(value){
+               value = Function.from(value)();
+               value = (typeof value == 'string') ? value.split(' ') : Array.from(value);
+               return value.map(function(val){
+                       val = String(val);
+                       var found = false;
+                       Object.each(Fx.CSS.Parsers, function(parser, key){
+                               if (found) return;
+                               var parsed = parser.parse(val);
+                               if (parsed || parsed === 0) found = {value: parsed, parser: parser};
+                       });
+                       found = found || {value: val, parser: Fx.CSS.Parsers.String};
+                       return found;
+               });
+       },
+
+       //computes by a from and to prepared objects, using their parsers.
+
+       compute: function(from, to, delta){
+               var computed = [];
+               (Math.min(from.length, to.length)).times(function(i){
+                       computed.push({value: from[i].parser.compute(from[i].value, to[i].value, delta), parser: from[i].parser});
+               });
+               computed.$family = Function.from('fx:css:value');
+               return computed;
+       },
+
+       //serves the value as settable
+
+       serve: function(value, unit){
+               if (typeOf(value) != 'fx:css:value') value = this.parse(value);
+               var returned = [];
+               value.each(function(bit){
+                       returned = returned.concat(bit.parser.serve(bit.value, unit));
+               });
+               return returned;
+       },
+
+       //renders the change to an element
+
+       render: function(element, property, value, unit){
+               element.setStyle(property, this.serve(value, unit));
+       },
+
+       //searches inside the page css to find the values for a selector
+
+       search: function(selector){
+               if (Fx.CSS.Cache[selector]) return Fx.CSS.Cache[selector];
+               var to = {}, selectorTest = new RegExp('^' + selector.escapeRegExp() + '$');
+               Array.each(document.styleSheets, function(sheet, j){
+                       var href = sheet.href;
+                       if (href && href.contains('://') && !href.contains(document.domain)) return;
+                       var rules = sheet.rules || sheet.cssRules;
+                       Array.each(rules, function(rule, i){
+                               if (!rule.style) return;
+                               var selectorText = (rule.selectorText) ? rule.selectorText.replace(/^\w+/, function(m){
+                                       return m.toLowerCase();
+                               }) : null;
+                               if (!selectorText || !selectorTest.test(selectorText)) return;
+                               Object.each(Element.Styles, function(value, style){
+                                       if (!rule.style[style] || Element.ShortStyles[style]) return;
+                                       value = String(rule.style[style]);
+                                       to[style] = ((/^rgb/).test(value)) ? value.rgbToHex() : value;
+                               });
+                       });
+               });
+               return Fx.CSS.Cache[selector] = to;
+       }
+
+});
+
+Fx.CSS.Cache = {};
+
+Fx.CSS.Parsers = {
+
+       Color: {
+               parse: function(value){
+                       if (value.match(/^#[0-9a-f]{3,6}$/i)) return value.hexToRgb(true);
+                       return ((value = value.match(/(\d+),\s*(\d+),\s*(\d+)/))) ? [value[1], value[2], value[3]] : false;
+               },
+               compute: function(from, to, delta){
+                       return from.map(function(value, i){
+                               return Math.round(Fx.compute(from[i], to[i], delta));
+                       });
+               },
+               serve: function(value){
+                       return value.map(Number);
+               }
+       },
+
+       Number: {
+               parse: parseFloat,
+               compute: Fx.compute,
+               serve: function(value, unit){
+                       return (unit) ? value + unit : value;
+               }
+       },
+
+       String: {
+               parse: Function.from(false),
+               compute: function(zero, one){
+                       return one;
+               },
+               serve: function(zero){
+                       return zero;
+               }
+       }
+
+};
+
+//<1.2compat>
+
+Fx.CSS.Parsers = new Hash(Fx.CSS.Parsers);
+
+//</1.2compat>
+
+
+// Begin: Source/Fx/Fx.Morph.js
+/*
+---
+
+name: Fx.Morph
+
+description: Formerly Fx.Styles, effect to transition any number of CSS properties for an element using an object of rules, or CSS based selector rules.
+
+license: MIT-style license.
+
+requires: Fx.CSS
+
+provides: Fx.Morph
+
+...
+*/
+
+Fx.Morph = new Class({
+
+       Extends: Fx.CSS,
+
+       initialize: function(element, options){
+               this.element = this.subject = document.id(element);
+               this.parent(options);
+       },
+
+       set: function(now){
+               if (typeof now == 'string') now = this.search(now);
+               for (var p in now) this.render(this.element, p, now[p], this.options.unit);
+               return this;
+       },
+
+       compute: function(from, to, delta){
+               var now = {};
+               for (var p in from) now[p] = this.parent(from[p], to[p], delta);
+               return now;
+       },
+
+       start: function(properties){
+               if (!this.check(properties)) return this;
+               if (typeof properties == 'string') properties = this.search(properties);
+               var from = {}, to = {};
+               for (var p in properties){
+                       var parsed = this.prepare(this.element, p, properties[p]);
+                       from[p] = parsed.from;
+                       to[p] = parsed.to;
+               }
+               return this.parent(from, to);
+       }
+
+});
+
+Element.Properties.morph = {
+
+       set: function(options){
+               this.get('morph').cancel().setOptions(options);
+               return this;
+       },
+
+       get: function(){
+               var morph = this.retrieve('morph');
+               if (!morph){
+                       morph = new Fx.Morph(this, {link: 'cancel'});
+                       this.store('morph', morph);
+               }
+               return morph;
+       }
+
+};
+
+Element.implement({
+
+       morph: function(props){
+               this.get('morph').start(props);
+               return this;
+       }
+
+});
+
+
+// Begin: Source/Utilities/Swiff.js
+/*
+---
+
+name: Swiff
+
+description: Wrapper for embedding SWF movies. Supports External Interface Communication.
+
+license: MIT-style license.
+
+credits:
+  - Flash detection & Internet Explorer + Flash Player 9 fix inspired by SWFObject.
+
+requires: [Options, Object, Element]
+
+provides: Swiff
+
+...
+*/
+
+(function(){
+
+var Swiff = this.Swiff = new Class({
+
+       Implements: Options,
+
+       options: {
+               id: null,
+               height: 1,
+               width: 1,
+               container: null,
+               properties: {},
+               params: {
+                       quality: 'high',
+                       allowScriptAccess: 'always',
+                       wMode: 'window',
+                       swLiveConnect: true
+               },
+               callBacks: {},
+               vars: {}
+       },
+
+       toElement: function(){
+               return this.object;
+       },
+
+       initialize: function(path, options){
+               this.instance = 'Swiff_' + String.uniqueID();
+
+               this.setOptions(options);
+               options = this.options;
+               var id = this.id = options.id || this.instance;
+               var container = document.id(options.container);
+
+               Swiff.CallBacks[this.instance] = {};
+
+               var params = options.params, vars = options.vars, callBacks = options.callBacks;
+               var properties = Object.append({height: options.height, width: options.width}, options.properties);
+
+               var self = this;
+
+               for (var callBack in callBacks){
+                       Swiff.CallBacks[this.instance][callBack] = (function(option){
+                               return function(){
+                                       return option.apply(self.object, arguments);
+                               };
+                       })(callBacks[callBack]);
+                       vars[callBack] = 'Swiff.CallBacks.' + this.instance + '.' + callBack;
+               }
+
+               params.flashVars = Object.toQueryString(vars);
+               if (Browser.ie){
+                       properties.classid = 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000';
+                       params.movie = path;
+               } else {
+                       properties.type = 'application/x-shockwave-flash';
+               }
+               properties.data = path;
+
+               var build = '<object id="' + id + '"';
+               for (var property in properties) build += ' ' + property + '="' + properties[property] + '"';
+               build += '>';
+               for (var param in params){
+                       if (params[param]) build += '<param name="' + param + '" value="' + params[param] + '" />';
+               }
+               build += '</object>';
+               this.object = ((container) ? container.empty() : new Element('div')).set('html', build).firstChild;
+       },
+
+       replaces: function(element){
+               element = document.id(element, true);
+               element.parentNode.replaceChild(this.toElement(), element);
+               return this;
+       },
+
+       inject: function(element){
+               document.id(element, true).appendChild(this.toElement());
+               return this;
+       },
+
+       remote: function(){
+               return Swiff.remote.apply(Swiff, [this.toElement()].append(arguments));
+       }
+
+});
+
+Swiff.CallBacks = {};
+
+Swiff.remote = function(obj, fn){
+       var rs = obj.CallFunction('<invoke name="' + fn + '" returntype="javascript">' + __flash__argumentsToXML(arguments, 2) + '</invoke>');
+       return eval(rs);
+};
+
+})();
+
+
+// Begin: Source/Fx/Fx.Transitions.js
+/*
+---
+
+name: Fx.Transitions
+
+description: Contains a set of advanced transitions to be used with any of the Fx Classes.
+
+license: MIT-style license.
+
+credits:
+  - Easing Equations by Robert Penner, <http://www.robertpenner.com/easing/>, modified and optimized to be used with MooTools.
+
+requires: Fx
+
+provides: Fx.Transitions
+
+...
+*/
+
+Fx.implement({
+
+       getTransition: function(){
+               var trans = this.options.transition || Fx.Transitions.Sine.easeInOut;
+               if (typeof trans == 'string'){
+                       var data = trans.split(':');
+                       trans = Fx.Transitions;
+                       trans = trans[data[0]] || trans[data[0].capitalize()];
+                       if (data[1]) trans = trans['ease' + data[1].capitalize() + (data[2] ? data[2].capitalize() : '')];
+               }
+               return trans;
+       }
+
+});
+
+Fx.Transition = function(transition, params){
+       params = Array.from(params);
+       var easeIn = function(pos){
+               return transition(pos, params);
+       };
+       return Object.append(easeIn, {
+               easeIn: easeIn,
+               easeOut: function(pos){
+                       return 1 - transition(1 - pos, params);
+               },
+               easeInOut: function(pos){
+                       return (pos <= 0.5 ? transition(2 * pos, params) : (2 - transition(2 * (1 - pos), params))) / 2;
+               }
+       });
+};
+
+Fx.Transitions = {
+
+       linear: function(zero){
+               return zero;
+       }
+
+};
+
+//<1.2compat>
+
+Fx.Transitions = new Hash(Fx.Transitions);
+
+//</1.2compat>
+
+Fx.Transitions.extend = function(transitions){
+       for (var transition in transitions) Fx.Transitions[transition] = new Fx.Transition(transitions[transition]);
+};
+
+Fx.Transitions.extend({
+
+       Pow: function(p, x){
+               return Math.pow(p, x && x[0] || 6);
+       },
+
+       Expo: function(p){
+               return Math.pow(2, 8 * (p - 1));
+       },
+
+       Circ: function(p){
+               return 1 - Math.sin(Math.acos(p));
+       },
+
+       Sine: function(p){
+               return 1 - Math.cos(p * Math.PI / 2);
+       },
+
+       Back: function(p, x){
+               x = x && x[0] || 1.618;
+               return Math.pow(p, 2) * ((x + 1) * p - x);
+       },
+
+       Bounce: function(p){
+               var value;
+               for (var a = 0, b = 1; 1; a += b, b /= 2){
+                       if (p >= (7 - 4 * a) / 11){
+                               value = b * b - Math.pow((11 - 6 * a - 11 * p) / 4, 2);
+                               break;
+                       }
+               }
+               return value;
+       },
+
+       Elastic: function(p, x){
+               return Math.pow(2, 10 * --p) * Math.cos(20 * p * Math.PI * (x && x[0] || 1) / 3);
+       }
+
+});
+
+['Quad', 'Cubic', 'Quart', 'Quint'].each(function(transition, i){
+       Fx.Transitions[transition] = new Fx.Transition(function(p){
+               return Math.pow(p, i + 2);
+       });
+});
+
+
+// Begin: Source/More/More.js
+/*
+---
+
+script: More.js
+
+name: More
+
+description: MooTools More
+
+license: MIT-style license
+
+authors:
+  - Guillermo Rauch
+  - Thomas Aylott
+  - Scott Kyle
+  - Arian Stolwijk
+  - Tim Wienk
+  - Christoph Pojer
+  - Aaron Newton
+  - Jacob Thornton
+
+requires:
+  - Core/MooTools
+
+provides: [MooTools.More]
+
+...
+*/
+
+MooTools.More = {
+       version: '1.4.3.1dev',
+       build: '%build%'
+};
+
+
+// Begin: Source/Class/Class.Binds.js
+/*
+---
+
+script: Class.Binds.js
+
+name: Class.Binds
+
+description: Automagically binds specified methods in a class to the instance of the class.
+
+license: MIT-style license
+
+authors:
+  - Aaron Newton
+
+requires:
+  - Core/Class
+  - /MooTools.More
+
+provides: [Class.Binds]
+
+...
+*/
+
+Class.Mutators.Binds = function(binds){
+       if (!this.prototype.initialize) this.implement('initialize', function(){});
+       return Array.from(binds).concat(this.prototype.Binds || []);
+};
+
+Class.Mutators.initialize = function(initialize){
+       return function(){
+               Array.from(this.Binds).each(function(name){
+                       var original = this[name];
+                       if (original) this[name] = original.bind(this);
+               }, this);
+               return initialize.apply(this, arguments);
+       };
+};
+
+
+// Begin: Source/Class/Class.Occlude.js
+/*
+---
+
+script: Class.Occlude.js
+
+name: Class.Occlude
+
+description: Prevents a class from being applied to a DOM element twice.
+
+license: MIT-style license.
+
+authors:
+  - Aaron Newton
+
+requires:
+  - Core/Class
+  - Core/Element
+  - /MooTools.More
+
+provides: [Class.Occlude]
+
+...
+*/
+
+Class.Occlude = new Class({
+
+       occlude: function(property, element){
+               element = document.id(element || this.element);
+               var instance = element.retrieve(property || this.property);
+               if (instance && !this.occluded)
+                       return (this.occluded = instance);
+
+               this.occluded = false;
+               element.store(property || this.property, this);
+               return this.occluded;
+       }
+
+});
+
+
+// Begin: Source/Element/Element.Dimensions.js
+/*
+---
+
+name: Element.Dimensions
+
+description: Contains methods to work with size, scroll, or positioning of Elements and the window object.
+
+license: MIT-style license.
+
+credits:
+  - Element positioning based on the [qooxdoo](http://qooxdoo.org/) code and smart browser fixes, [LGPL License](http://www.gnu.org/licenses/lgpl.html).
+  - Viewport dimensions based on [YUI](http://developer.yahoo.com/yui/) code, [BSD License](http://developer.yahoo.com/yui/license.html).
+
+requires: [Element, Element.Style]
+
+provides: [Element.Dimensions]
+
+...
+*/
+
+(function(){
+
+var element = document.createElement('div'),
+       child = document.createElement('div');
+element.style.height = '0';
+element.appendChild(child);
+var brokenOffsetParent = (child.offsetParent === element);
+element = child = null;
+
+var isOffset = function(el){
+       return styleString(el, 'position') != 'static' || isBody(el);
+};
+
+var isOffsetStatic = function(el){
+       return isOffset(el) || (/^(?:table|td|th)$/i).test(el.tagName);
+};
+
+Element.implement({
+
+       scrollTo: function(x, y){
+               if (isBody(this)){
+                       this.getWindow().scrollTo(x, y);
+               } else {
+                       this.scrollLeft = x;
+                       this.scrollTop = y;
+               }
+               return this;
+       },
+
+       getSize: function(){
+               if (isBody(this)) return this.getWindow().getSize();
+               return {x: this.offsetWidth, y: this.offsetHeight};
+       },
+
+       getScrollSize: function(){
+               if (isBody(this)) return this.getWindow().getScrollSize();
+               return {x: this.scrollWidth, y: this.scrollHeight};
+       },
+
+       getScroll: function(){
+               if (isBody(this)) return this.getWindow().getScroll();
+               return {x: this.scrollLeft, y: this.scrollTop};
+       },
+
+       getScrolls: function(){
+               var element = this.parentNode, position = {x: 0, y: 0};
+               while (element && !isBody(element)){
+                       position.x += element.scrollLeft;
+                       position.y += element.scrollTop;
+                       element = element.parentNode;
+               }
+               return position;
+       },
+
+       getOffsetParent: brokenOffsetParent ? function(){
+               var element = this;
+               if (isBody(element) || styleString(element, 'position') == 'fixed') return null;
+
+               var isOffsetCheck = (styleString(element, 'position') == 'static') ? isOffsetStatic : isOffset;
+               while ((element = element.parentNode)){
+                       if (isOffsetCheck(element)) return element;
+               }
+               return null;
+       } : function(){
+               var element = this;
+               if (isBody(element) || styleString(element, 'position') == 'fixed') return null;
+
+               try {
+                       return element.offsetParent;
+               } catch(e) {}
+               return null;
+       },
+
+       getOffsets: function(){
+               if (this.getBoundingClientRect && !Browser.Platform.ios){
+                       var bound = this.getBoundingClientRect(),
+                               html = document.id(this.getDocument().documentElement),
+                               htmlScroll = html.getScroll(),
+                               elemScrolls = this.getScrolls(),
+                               isFixed = (styleString(this, 'position') == 'fixed');
+
+                       return {
+                               x: bound.left.toInt() + elemScrolls.x + ((isFixed) ? 0 : htmlScroll.x) - html.clientLeft,
+                               y: bound.top.toInt()  + elemScrolls.y + ((isFixed) ? 0 : htmlScroll.y) - html.clientTop
+                       };
+               }
+
+               var element = this, position = {x: 0, y: 0};
+               if (isBody(this)) return position;
+
+               while (element && !isBody(element)){
+                       position.x += element.offsetLeft;
+                       position.y += element.offsetTop;
+
+                       if (Browser.firefox){
+                               if (!borderBox(element)){
+                                       position.x += leftBorder(element);
+                                       position.y += topBorder(element);
+                               }
+                               var parent = element.parentNode;
+                               if (parent && styleString(parent, 'overflow') != 'visible'){
+                                       position.x += leftBorder(parent);
+                                       position.y += topBorder(parent);
+                               }
+                       } else if (element != this && Browser.safari){
+                               position.x += leftBorder(element);
+                               position.y += topBorder(element);
+                       }
+
+                       element = element.offsetParent;
+               }
+               if (Browser.firefox && !borderBox(this)){
+                       position.x -= leftBorder(this);
+                       position.y -= topBorder(this);
+               }
+               return position;
+       },
+
+       getPosition: function(relative){
+               var offset = this.getOffsets(),
+                       scroll = this.getScrolls();
+               var position = {
+                       x: offset.x - scroll.x,
+                       y: offset.y - scroll.y
+               };
+
+               if (relative && (relative = document.id(relative))){
+                       var relativePosition = relative.getPosition();
+                       return {x: position.x - relativePosition.x - leftBorder(relative), y: position.y - relativePosition.y - topBorder(relative)};
+               }
+               return position;
+       },
+
+       getCoordinates: function(element){
+               if (isBody(this)) return this.getWindow().getCoordinates();
+               var position = this.getPosition(element),
+                       size = this.getSize();
+               var obj = {
+                       left: position.x,
+                       top: position.y,
+                       width: size.x,
+                       height: size.y
+               };
+               obj.right = obj.left + obj.width;
+               obj.bottom = obj.top + obj.height;
+               return obj;
+       },
+
+       computePosition: function(obj){
+               return {
+                       left: obj.x - styleNumber(this, 'margin-left'),
+                       top: obj.y - styleNumber(this, 'margin-top')
+               };
+       },
+
+       setPosition: function(obj){
+               return this.setStyles(this.computePosition(obj));
+       }
+
+});
+
+
+[Document, Window].invoke('implement', {
+
+       getSize: function(){
+               var doc = getCompatElement(this);
+               return {x: doc.clientWidth, y: doc.clientHeight};
+       },
+
+       getScroll: function(){
+               var win = this.getWindow(), doc = getCompatElement(this);
+               return {x: win.pageXOffset || doc.scrollLeft, y: win.pageYOffset || doc.scrollTop};
+       },
+
+       getScrollSize: function(){
+               var doc = getCompatElement(this),
+                       min = this.getSize(),
+                       body = this.getDocument().body;
+
+               return {x: Math.max(doc.scrollWidth, body.scrollWidth, min.x), y: Math.max(doc.scrollHeight, body.scrollHeight, min.y)};
+       },
+
+       getPosition: function(){
+               return {x: 0, y: 0};
+       },
+
+       getCoordinates: function(){
+               var size = this.getSize();
+               return {top: 0, left: 0, bottom: size.y, right: size.x, height: size.y, width: size.x};
+       }
+
+});
+
+// private methods
+
+var styleString = Element.getComputedStyle;
+
+function styleNumber(element, style){
+       return styleString(element, style).toInt() || 0;
+}
+
+function borderBox(element){
+       return styleString(element, '-moz-box-sizing') == 'border-box';
+}
+
+function topBorder(element){
+       return styleNumber(element, 'border-top-width');
+}
+
+function leftBorder(element){
+       return styleNumber(element, 'border-left-width');
+}
+
+function isBody(element){
+       return (/^(?:body|html)$/i).test(element.tagName);
+}
+
+function getCompatElement(element){
+       var doc = element.getDocument();
+       return (!doc.compatMode || doc.compatMode == 'CSS1Compat') ? doc.html : doc.body;
+}
+
+})();
+
+//aliases
+Element.alias({position: 'setPosition'}); //compatability
+
+[Window, Document, Element].invoke('implement', {
+
+       getHeight: function(){
+               return this.getSize().y;
+       },
+
+       getWidth: function(){
+               return this.getSize().x;
+       },
+
+       getScrollTop: function(){
+               return this.getScroll().y;
+       },
+
+       getScrollLeft: function(){
+               return this.getScroll().x;
+       },
+
+       getScrollHeight: function(){
+               return this.getScrollSize().y;
+       },
+
+       getScrollWidth: function(){
+               return this.getScrollSize().x;
+       },
+
+       getTop: function(){
+               return this.getPosition().y;
+       },
+
+       getLeft: function(){
+               return this.getPosition().x;
+       }
+
+});
+
+
+// Begin: Source/Element/Element.Measure.js
+/*
+---
+
+script: Element.Measure.js
+
+name: Element.Measure
+
+description: Extends the Element native object to include methods useful in measuring dimensions.
+
+credits: "Element.measure / .expose methods by Daniel Steigerwald License: MIT-style license. Copyright: Copyright (c) 2008 Daniel Steigerwald, daniel.steigerwald.cz"
+
+license: MIT-style license
+
+authors:
+  - Aaron Newton
+
+requires:
+  - Core/Element.Style
+  - Core/Element.Dimensions
+  - /MooTools.More
+
+provides: [Element.Measure]
+
+...
+*/
+
+(function(){
+
+var getStylesList = function(styles, planes){
+       var list = [];
+       Object.each(planes, function(directions){
+               Object.each(directions, function(edge){
+                       styles.each(function(style){
+                               list.push(style + '-' + edge + (style == 'border' ? '-width' : ''));
+                       });
+               });
+       });
+       return list;
+};
+
+var calculateEdgeSize = function(edge, styles){
+       var total = 0;
+       Object.each(styles, function(value, style){
+               if (style.test(edge)) total = total + value.toInt();
+       });
+       return total;
+};
+
+var isVisible = function(el){
+       return !!(!el || el.offsetHeight || el.offsetWidth);
+};
+
+
+Element.implement({
+
+       measure: function(fn){
+               if (isVisible(this)) return fn.call(this);
+               var parent = this.getParent(),
+                       toMeasure = [];
+               while (!isVisible(parent) && parent != document.body){
+                       toMeasure.push(parent.expose());
+                       parent = parent.getParent();
+               }
+               var restore = this.expose(),
+                       result = fn.call(this);
+               restore();
+               toMeasure.each(function(restore){
+                       restore();
+               });
+               return result;
+       },
+
+       expose: function(){
+               if (this.getStyle('display') != 'none') return function(){};
+               var before = this.style.cssText;
+               this.setStyles({
+                       display: 'block',
+                       position: 'absolute',
+                       visibility: 'hidden'
+               });
+               return function(){
+                       this.style.cssText = before;
+               }.bind(this);
+       },
+
+       getDimensions: function(options){
+               options = Object.merge({computeSize: false}, options);
+               var dim = {x: 0, y: 0};
+
+               var getSize = function(el, options){
+                       return (options.computeSize) ? el.getComputedSize(options) : el.getSize();
+               };
+
+               var parent = this.getParent('body');
+
+               if (parent && this.getStyle('display') == 'none'){
+                       dim = this.measure(function(){
+                               return getSize(this, options);
+                       });
+               } else if (parent){
+                       try { //safari sometimes crashes here, so catch it
+                               dim = getSize(this, options);
+                       }catch(e){}
+               }
+
+               return Object.append(dim, (dim.x || dim.x === 0) ? {
+                               width: dim.x,
+                               height: dim.y
+                       } : {
+                               x: dim.width,
+                               y: dim.height
+                       }
+               );
+       },
+
+       getComputedSize: function(options){
+               //<1.2compat>
+               //legacy support for my stupid spelling error
+               if (options && options.plains) options.planes = options.plains;
+               //</1.2compat>
+
+               options = Object.merge({
+                       styles: ['padding','border'],
+                       planes: {
+                               height: ['top','bottom'],
+                               width: ['left','right']
+                       },
+                       mode: 'both'
+               }, options);
+
+               var styles = {},
+                       size = {width: 0, height: 0},
+                       dimensions;
+
+               if (options.mode == 'vertical'){
+                       delete size.width;
+                       delete options.planes.width;
+               } else if (options.mode == 'horizontal'){
+                       delete size.height;
+                       delete options.planes.height;
+               }
+
+               getStylesList(options.styles, options.planes).each(function(style){
+                       styles[style] = this.getStyle(style).toInt();
+               }, this);
+
+               Object.each(options.planes, function(edges, plane){
+
+                       var capitalized = plane.capitalize(),
+                               style = this.getStyle(plane);
+
+                       if (style == 'auto' && !dimensions) dimensions = this.getDimensions();
+
+                       style = styles[plane] = (style == 'auto') ? dimensions[plane] : style.toInt();
+                       size['total' + capitalized] = style;
+
+                       edges.each(function(edge){
+                               var edgesize = calculateEdgeSize(edge, styles);
+                               size['computed' + edge.capitalize()] = edgesize;
+                               size['total' + capitalized] += edgesize;
+                       });
+
+               }, this);
+
+               return Object.append(size, styles);
+       }
+
+});
+
+})();
+
+
+// Begin: Source/Element/Element.Position.js
+/*
+---
+
+script: Element.Position.js
+
+name: Element.Position
+
+description: Extends the Element native object to include methods useful positioning elements relative to others.
+
+license: MIT-style license
+
+authors:
+  - Aaron Newton
+  - Jacob Thornton
+
+requires:
+  - Core/Options
+  - Core/Element.Dimensions
+  - Element.Measure
+
+provides: [Element.Position]
+
+...
+*/
+
+(function(original){
+
+var local = Element.Position = {
+
+       options: {/*
+               edge: false,
+               returnPos: false,
+               minimum: {x: 0, y: 0},
+               maximum: {x: 0, y: 0},
+               relFixedPosition: false,
+               ignoreMargins: false,
+               ignoreScroll: false,
+               allowNegative: false,*/
+               relativeTo: document.body,
+               position: {
+                       x: 'center', //left, center, right
+                       y: 'center' //top, center, bottom
+               },
+               offset: {x: 0, y: 0}
+       },
+
+       getOptions: function(element, options){
+               options = Object.merge({}, local.options, options);
+               local.setPositionOption(options);
+               local.setEdgeOption(options);
+               local.setOffsetOption(element, options);
+               local.setDimensionsOption(element, options);
+               return options;
+       },
+
+       setPositionOption: function(options){
+               options.position = local.getCoordinateFromValue(options.position);
+       },
+
+       setEdgeOption: function(options){
+               var edgeOption = local.getCoordinateFromValue(options.edge);
+               options.edge = edgeOption ? edgeOption :
+                       (options.position.x == 'center' && options.position.y == 'center') ? {x: 'center', y: 'center'} :
+                       {x: 'left', y: 'top'};
+       },
+
+       setOffsetOption: function(element, options){
+               var parentOffset = {x: 0, y: 0},
+                       offsetParent = element.measure(function(){
+                               return document.id(this.getOffsetParent());
+                       }),
+                       parentScroll = offsetParent.getScroll();
+
+               if (!offsetParent || offsetParent == element.getDocument().body) return;
+               parentOffset = offsetParent.measure(function(){
+                       var position = this.getPosition();
+                       if (this.getStyle('position') == 'fixed'){
+                               var scroll = window.getScroll();
+                               position.x += scroll.x;
+                               position.y += scroll.y;
+                       }
+                       return position;
+               });
+
+               options.offset = {
+                       parentPositioned: offsetParent != document.id(options.relativeTo),
+                       x: options.offset.x - parentOffset.x + parentScroll.x,
+                       y: options.offset.y - parentOffset.y + parentScroll.y
+               };
+       },
+
+       setDimensionsOption: function(element, options){
+               options.dimensions = element.getDimensions({
+                       computeSize: true,
+                       styles: ['padding', 'border', 'margin']
+               });
+       },
+
+       getPosition: function(element, options){
+               var position = {};
+               options = local.getOptions(element, options);
+               var relativeTo = document.id(options.relativeTo) || document.body;
+
+               local.setPositionCoordinates(options, position, relativeTo);
+               if (options.edge) local.toEdge(position, options);
+
+               var offset = options.offset;
+               position.left = ((position.x >= 0 || offset.parentPositioned || options.allowNegative) ? position.x : 0).toInt();
+               position.top = ((position.y >= 0 || offset.parentPositioned || options.allowNegative) ? position.y : 0).toInt();
+
+               local.toMinMax(position, options);
+
+               if (options.relFixedPosition || relativeTo.getStyle('position') == 'fixed') local.toRelFixedPosition(relativeTo, position);
+               if (options.ignoreScroll) local.toIgnoreScroll(relativeTo, position);
+               if (options.ignoreMargins) local.toIgnoreMargins(position, options);
+
+               position.left = Math.ceil(position.left);
+               position.top = Math.ceil(position.top);
+               delete position.x;
+               delete position.y;
+
+               return position;
+       },
+
+       setPositionCoordinates: function(options, position, relativeTo){
+               var offsetY = options.offset.y,
+                       offsetX = options.offset.x,
+                       calc = (relativeTo == document.body) ? window.getScroll() : relativeTo.getPosition(),
+                       top = calc.y,
+                       left = calc.x,
+                       winSize = window.getSize();
+
+               switch(options.position.x){
+                       case 'left': position.x = left + offsetX; break;
+                       case 'right': position.x = left + offsetX + relativeTo.offsetWidth; break;
+                       default: position.x = left + ((relativeTo == document.body ? winSize.x : relativeTo.offsetWidth) / 2) + offsetX; break;
+               }
+
+               switch(options.position.y){
+                       case 'top': position.y = top + offsetY; break;
+                       case 'bottom': position.y = top + offsetY + relativeTo.offsetHeight; break;
+                       default: position.y = top + ((relativeTo == document.body ? winSize.y : relativeTo.offsetHeight) / 2) + offsetY; break;
+               }
+       },
+
+       toMinMax: function(position, options){
+               var xy = {left: 'x', top: 'y'}, value;
+               ['minimum', 'maximum'].each(function(minmax){
+                       ['left', 'top'].each(function(lr){
+                               value = options[minmax] ? options[minmax][xy[lr]] : null;
+                               if (value != null && ((minmax == 'minimum') ? position[lr] < value : position[lr] > value)) position[lr] = value;
+                       });
+               });
+       },
+
+       toRelFixedPosition: function(relativeTo, position){
+               var winScroll = window.getScroll();
+               position.top += winScroll.y;
+               position.left += winScroll.x;
+       },
+
+       toIgnoreScroll: function(relativeTo, position){
+               var relScroll = relativeTo.getScroll();
+               position.top -= relScroll.y;
+               position.left -= relScroll.x;
+       },
+
+       toIgnoreMargins: function(position, options){
+               position.left += options.edge.x == 'right'
+                       ? options.dimensions['margin-right']
+                       : (options.edge.x != 'center'
+                               ? -options.dimensions['margin-left']
+                               : -options.dimensions['margin-left'] + ((options.dimensions['margin-right'] + options.dimensions['margin-left']) / 2));
+
+               position.top += options.edge.y == 'bottom'
+                       ? options.dimensions['margin-bottom']
+                       : (options.edge.y != 'center'
+                               ? -options.dimensions['margin-top']
+                               : -options.dimensions['margin-top'] + ((options.dimensions['margin-bottom'] + options.dimensions['margin-top']) / 2));
+       },
+
+       toEdge: function(position, options){
+               var edgeOffset = {},
+                       dimensions = options.dimensions,
+                       edge = options.edge;
+
+               switch(edge.x){
+                       case 'left': edgeOffset.x = 0; break;
+                       case 'right': edgeOffset.x = -dimensions.x - dimensions.computedRight - dimensions.computedLeft; break;
+                       // center
+                       default: edgeOffset.x = -(Math.round(dimensions.totalWidth / 2)); break;
+               }
+
+               switch(edge.y){
+                       case 'top': edgeOffset.y = 0; break;
+                       case 'bottom': edgeOffset.y = -dimensions.y - dimensions.computedTop - dimensions.computedBottom; break;
+                       // center
+                       default: edgeOffset.y = -(Math.round(dimensions.totalHeight / 2)); break;
+               }
+
+               position.x += edgeOffset.x;
+               position.y += edgeOffset.y;
+       },
+
+       getCoordinateFromValue: function(option){
+               if (typeOf(option) != 'string') return option;
+               option = option.toLowerCase();
+
+               return {
+                       x: option.test('left') ? 'left'
+                               : (option.test('right') ? 'right' : 'center'),
+                       y: option.test(/upper|top/) ? 'top'
+                               : (option.test('bottom') ? 'bottom' : 'center')
+               };
+       }
+
+};
+
+Element.implement({
+
+       position: function(options){
+               if (options && (options.x != null || options.y != null)){
+                       return (original ? original.apply(this, arguments) : this);
+               }
+               var position = this.setStyle('position', 'absolute').calculatePosition(options);
+               return (options && options.returnPos) ? position : this.setStyles(position);
+       },
+
+       calculatePosition: function(options){
+               return local.getPosition(this, options);
+       }
+
+});
+
+})(Element.prototype.position);
+
+
+// Begin: Source/Element/Element.Shortcuts.js
+/*
+---
+
+script: Element.Shortcuts.js
+
+name: Element.Shortcuts
+
+description: Extends the Element native object to include some shortcut methods.
+
+license: MIT-style license
+
+authors:
+  - Aaron Newton
+
+requires:
+  - Core/Element.Style
+  - /MooTools.More
+
+provides: [Element.Shortcuts]
+
+...
+*/
+
+Element.implement({
+
+       isDisplayed: function(){
+               return this.getStyle('display') != 'none';
+       },
+
+       isVisible: function(){
+               var w = this.offsetWidth,
+                       h = this.offsetHeight;
+               return (w == 0 && h == 0) ? false : (w > 0 && h > 0) ? true : this.style.display != 'none';
+       },
+
+       toggle: function(){
+               return this[this.isDisplayed() ? 'hide' : 'show']();
+       },
+
+       hide: function(){
+               var d;
+               try {
+                       //IE fails here if the element is not in the dom
+                       d = this.getStyle('display');
+               } catch(e){}
+               if (d == 'none') return this;
+               return this.store('element:_originalDisplay', d || '').setStyle('display', 'none');
+       },
+
+       show: function(display){
+               if (!display && this.isDisplayed()) return this;
+               display = display || this.retrieve('element:_originalDisplay') || 'block';
+               return this.setStyle('display', (display == 'none') ? 'block' : display);
+       },
+
+       swapClass: function(remove, add){
+               return this.removeClass(remove).addClass(add);
+       }
+
+});
+
+Document.implement({
+
+       clearSelection: function(){
+               if (window.getSelection){
+                       var selection = window.getSelection();
+                       if (selection && selection.removeAllRanges) selection.removeAllRanges();
+               } else if (document.selection && document.selection.empty){
+                       try {
+                               //IE fails here if selected element is not in dom
+                               document.selection.empty();
+                       } catch(e){}
+               }
+       }
+
+});
+
+
+// Begin: Source/Forms/OverText.js
+/*
+---
+
+script: OverText.js
+
+name: OverText
+
+description: Shows text over an input that disappears when the user clicks into it. The text remains hidden if the user adds a value.
+
+license: MIT-style license
+
+authors:
+  - Aaron Newton
+
+requires:
+  - Core/Options
+  - Core/Events
+  - Core/Element.Event
+  - Class.Binds
+  - Class.Occlude
+  - Element.Position
+  - Element.Shortcuts
+
+provides: [OverText]
+
+...
+*/
+
+var OverText = new Class({
+
+       Implements: [Options, Events, Class.Occlude],
+
+       Binds: ['reposition', 'assert', 'focus', 'hide'],
+
+       options: {/*
+               textOverride: null,
+               onFocus: function(){},
+               onTextHide: function(textEl, inputEl){},
+               onTextShow: function(textEl, inputEl){}, */
+               element: 'label',
+               labelClass: 'overTxtLabel',
+               positionOptions: {
+                       position: 'upperLeft',
+                       edge: 'upperLeft',
+                       offset: {
+                               x: 4,
+                               y: 2
+                       }
+               },
+               poll: false,
+               pollInterval: 250,
+               wrap: false
+       },
+
+       property: 'OverText',
+
+       initialize: function(element, options){
+               element = this.element = document.id(element);
+
+               if (this.occlude()) return this.occluded;
+               this.setOptions(options);
+
+               this.attach(element);
+               OverText.instances.push(this);
+
+               if (this.options.poll) this.poll();
+       },
+
+       toElement: function(){
+               return this.element;
+       },
+
+       attach: function(){
+               var element = this.element,
+                       options = this.options,
+                       value = options.textOverride || element.get('alt') || element.get('title');
+
+               if (!value) return this;
+
+               var text = this.text = new Element(options.element, {
+                       'class': options.labelClass,
+                       styles: {
+                               lineHeight: 'normal',
+                               position: 'absolute',
+                               cursor: 'text'
+                       },
+                       html: value,
+                       events: {
+                               click: this.hide.pass(options.element == 'label', this)
+                       }
+               }).inject(element, 'after');
+
+               if (options.element == 'label'){
+                       if (!element.get('id')) element.set('id', 'input_' + String.uniqueID());
+                       text.set('for', element.get('id'));
+               }
+
+               if (options.wrap){
+                       this.textHolder = new Element('div.overTxtWrapper', {
+                               styles: {
+                                       lineHeight: 'normal',
+                                       position: 'relative'
+                               }
+                       }).grab(text).inject(element, 'before');
+               }
+
+               return this.enable();
+       },
+
+       destroy: function(){
+               this.element.eliminate(this.property); // Class.Occlude storage
+               this.disable();
+               if (this.text) this.text.destroy();
+               if (this.textHolder) this.textHolder.destroy();
+               return this;
+       },
+
+       disable: function(){
+               this.element.removeEvents({
+                       focus: this.focus,
+                       blur: this.assert,
+                       change: this.assert
+               });
+               window.removeEvent('resize', this.reposition);
+               this.hide(true, true);
+               return this;
+       },
+
+       enable: function(){
+               this.element.addEvents({
+                       focus: this.focus,
+                       blur: this.assert,
+                       change: this.assert
+               });
+               window.addEvent('resize', this.reposition);
+               this.reposition();
+               return this;
+       },
+
+       wrap: function(){
+               if (this.options.element == 'label'){
+                       if (!this.element.get('id')) this.element.set('id', 'input_' + String.uniqueID());
+                       this.text.set('for', this.element.get('id'));
+               }
+       },
+
+       startPolling: function(){
+               this.pollingPaused = false;
+               return this.poll();
+       },
+
+       poll: function(stop){
+               //start immediately
+               //pause on focus
+               //resumeon blur
+               if (this.poller && !stop) return this;
+               if (stop){
+                       clearInterval(this.poller);
+               } else {
+                       this.poller = (function(){
+                               if (!this.pollingPaused) this.assert(true);
+                       }).periodical(this.options.pollInterval, this);
+               }
+
+               return this;
+       },
+
+       stopPolling: function(){
+               this.pollingPaused = true;
+               return this.poll(true);
+       },
+
+       focus: function(){
+               if (this.text && (!this.text.isDisplayed() || this.element.get('disabled'))) return this;
+               return this.hide();
+       },
+
+       hide: function(suppressFocus, force){
+               if (this.text && (this.text.isDisplayed() && (!this.element.get('disabled') || force))){
+                       this.text.hide();
+                       this.fireEvent('textHide', [this.text, this.element]);
+                       this.pollingPaused = true;
+                       if (!suppressFocus){
+                               try {
+                                       this.element.fireEvent('focus');
+                                       this.element.focus();
+                               } catch(e){} //IE barfs if you call focus on hidden elements
+                       }
+               }
+               return this;
+       },
+
+       show: function(){
+               if (document.id(this.text) && !this.text.isDisplayed()){
+                       this.text.show();
+                       this.reposition();
+                       this.fireEvent('textShow', [this.text, this.element]);
+                       this.pollingPaused = false;
+               }
+               return this;
+       },
+
+       test: function(){
+               return !this.element.get('value');
+       },
+
+       assert: function(suppressFocus){
+               return this[this.test() ? 'show' : 'hide'](suppressFocus);
+       },
+
+       reposition: function(){
+               this.assert(true);
+               if (!this.element.isVisible()) return this.stopPolling().hide();
+               if (this.text && this.test()){
+                       this.text.position(Object.merge(this.options.positionOptions, {
+                               relativeTo: this.element
+                       }));
+               }
+               return this;
+       }
+
+});
+
+OverText.instances = [];
+
+Object.append(OverText, {
+
+       each: function(fn){
+               return OverText.instances.each(function(ot, i){
+                       if (ot.element && ot.text) fn.call(OverText, ot, i);
+               });
+       },
+
+       update: function(){
+
+               return OverText.each(function(ot){
+                       return ot.reposition();
+               });
+
+       },
+
+       hideAll: function(){
+
+               return OverText.each(function(ot){
+                       return ot.hide(true, true);
+               });
+
+       },
+
+       showAll: function(){
+               return OverText.each(function(ot){
+                       return ot.show();
+               });
+       }
+
+});
+
+
+
+// Begin: Source/Utilities/IframeShim.js
+/*
+---
+
+script: IframeShim.js
+
+name: IframeShim
+
+description: Defines IframeShim, a class for obscuring select lists and flash objects in IE.
+
+license: MIT-style license
+
+authors:
+  - Aaron Newton
+
+requires:
+  - Core/Element.Event
+  - Core/Element.Style
+  - Core/Options
+  - Core/Events
+  - /Element.Position
+  - /Class.Occlude
+
+provides: [IframeShim]
+
+...
+*/
+
+var IframeShim = new Class({
+
+       Implements: [Options, Events, Class.Occlude],
+
+       options: {
+               className: 'iframeShim',
+               src: 'javascript:false;document.write("");',
+               display: false,
+               zIndex: null,
+               margin: 0,
+               offset: {x: 0, y: 0},
+               browsers: (Browser.ie6 || (Browser.firefox && Browser.version < 3 && Browser.Platform.mac))
+       },
+
+       property: 'IframeShim',
+
+       initialize: function(element, options){
+               this.element = document.id(element);
+               if (this.occlude()) return this.occluded;
+               this.setOptions(options);
+               this.makeShim();
+               return this;
+       },
+
+       makeShim: function(){
+               if (this.options.browsers){
+                       var zIndex = this.element.getStyle('zIndex').toInt();
+
+                       if (!zIndex){
+                               zIndex = 1;
+                               var pos = this.element.getStyle('position');
+                               if (pos == 'static' || !pos) this.element.setStyle('position', 'relative');
+                               this.element.setStyle('zIndex', zIndex);
+                       }
+                       zIndex = ((this.options.zIndex != null || this.options.zIndex === 0) && zIndex > this.options.zIndex) ? this.options.zIndex : zIndex - 1;
+                       if (zIndex < 0) zIndex = 1;
+                       this.shim = new Element('iframe', {
+                               src: this.options.src,
+                               scrolling: 'no',
+                               frameborder: 0,
+                               styles: {
+                                       zIndex: zIndex,
+                                       position: 'absolute',
+                                       border: 'none',
+                                       filter: 'progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)'
+                               },
+                               'class': this.options.className
+                       }).store('IframeShim', this);
+                       var inject = (function(){
+                               this.shim.inject(this.element, 'after');
+                               this[this.options.display ? 'show' : 'hide']();
+                               this.fireEvent('inject');
+                       }).bind(this);
+                       if (!IframeShim.ready) window.addEvent('load', inject);
+                       else inject();
+               } else {
+                       this.position = this.hide = this.show = this.dispose = Function.from(this);
+               }
+       },
+
+       position: function(){
+               if (!IframeShim.ready || !this.shim) return this;
+               var size = this.element.measure(function(){
+                       return this.getSize();
+               });
+               if (this.options.margin != undefined){
+                       size.x = size.x - (this.options.margin * 2);
+                       size.y = size.y - (this.options.margin * 2);
+                       this.options.offset.x += this.options.margin;
+                       this.options.offset.y += this.options.margin;
+               }
+               this.shim.set({width: size.x, height: size.y}).position({
+                       relativeTo: this.element,
+                       offset: this.options.offset
+               });
+               return this;
+       },
+
+       hide: function(){
+               if (this.shim) this.shim.setStyle('display', 'none');
+               return this;
+       },
+
+       show: function(){
+               if (this.shim) this.shim.setStyle('display', 'block');
+               return this.position();
+       },
+
+       dispose: function(){
+               if (this.shim) this.shim.dispose();
+               return this;
+       },
+
+       destroy: function(){
+               if (this.shim) this.shim.destroy();
+               return this;
+       }
+
+});
+
+window.addEvent('load', function(){
+       IframeShim.ready = true;
+});
+
+
+// Begin: Source/Interface/Mask.js
+/*
+---
+
+script: Mask.js
+
+name: Mask
+
+description: Creates a mask element to cover another.
+
+license: MIT-style license
+
+authors:
+  - Aaron Newton
+
+requires:
+  - Core/Options
+  - Core/Events
+  - Core/Element.Event
+  - /Class.Binds
+  - /Element.Position
+  - /IframeShim
+
+provides: [Mask]
+
+...
+*/
+
+var Mask = new Class({
+
+       Implements: [Options, Events],
+
+       Binds: ['position'],
+
+       options: {/*
+               onShow: function(){},
+               onHide: function(){},
+               onDestroy: function(){},
+               onClick: function(event){},
+               inject: {
+                       where: 'after',
+                       target: null,
+               },
+               hideOnClick: false,
+               id: null,
+               destroyOnHide: false,*/
+               style: {},
+               'class': 'mask',
+               maskMargins: false,
+               useIframeShim: true,
+               iframeShimOptions: {}
+       },
+
+       initialize: function(target, options){
+               this.target = document.id(target) || document.id(document.body);
+               this.target.store('mask', this);
+               this.setOptions(options);
+               this.render();
+               this.inject();
+       },
+
+       render: function(){
+               this.element = new Element('div', {
+                       'class': this.options['class'],
+                       id: this.options.id || 'mask-' + String.uniqueID(),
+                       styles: Object.merge({}, this.options.style, {
+                               display: 'none'
+                       }),
+                       events: {
+                               click: function(event){
+                                       this.fireEvent('click', event);
+                                       if (this.options.hideOnClick) this.hide();
+                               }.bind(this)
+                       }
+               });
+
+               this.hidden = true;
+       },
+
+       toElement: function(){
+               return this.element;
+       },
+
+       inject: function(target, where){
+               where = where || (this.options.inject ? this.options.inject.where : '') || this.target == document.body ? 'inside' : 'after';
+               target = target || (this.options.inject && this.options.inject.target) || this.target;
+
+               this.element.inject(target, where);
+
+               if (this.options.useIframeShim){
+                       this.shim = new IframeShim(this.element, this.options.iframeShimOptions);
+
+                       this.addEvents({
+                               show: this.shim.show.bind(this.shim),
+                               hide: this.shim.hide.bind(this.shim),
+                               destroy: this.shim.destroy.bind(this.shim)
+                       });
+               }
+       },
+
+       position: function(){
+               this.resize(this.options.width, this.options.height);
+
+               this.element.position({
+                       relativeTo: this.target,
+                       position: 'topLeft',
+                       ignoreMargins: !this.options.maskMargins,
+                       ignoreScroll: this.target == document.body
+               });
+
+               return this;
+       },
+
+       resize: function(x, y){
+               var opt = {
+                       styles: ['padding', 'border']
+               };
+               if (this.options.maskMargins) opt.styles.push('margin');
+
+               var dim = this.target.getComputedSize(opt);
+               if (this.target == document.body){
+                       this.element.setStyles({width: 0, height: 0});
+                       var win = window.getScrollSize();
+                       if (dim.totalHeight < win.y) dim.totalHeight = win.y;
+                       if (dim.totalWidth < win.x) dim.totalWidth = win.x;
+               }
+               this.element.setStyles({
+                       width: Array.pick([x, dim.totalWidth, dim.x]),
+                       height: Array.pick([y, dim.totalHeight, dim.y])
+               });
+
+               return this;
+       },
+
+       show: function(){
+               if (!this.hidden) return this;
+
+               window.addEvent('resize', this.position);
+               this.position();
+               this.showMask.apply(this, arguments);
+
+               return this;
+       },
+
+       showMask: function(){
+               this.element.setStyle('display', 'block');
+               this.hidden = false;
+               this.fireEvent('show');
+       },
+
+       hide: function(){
+               if (this.hidden) return this;
+
+               window.removeEvent('resize', this.position);
+               this.hideMask.apply(this, arguments);
+               if (this.options.destroyOnHide) return this.destroy();
+
+               return this;
+       },
+
+       hideMask: function(){
+               this.element.setStyle('display', 'none');
+               this.hidden = true;
+               this.fireEvent('hide');
+       },
+
+       toggle: function(){
+               this[this.hidden ? 'show' : 'hide']();
+       },
+
+       destroy: function(){
+               this.hide();
+               this.element.destroy();
+               this.fireEvent('destroy');
+               this.target.eliminate('mask');
+       }
+
+});
+
+Element.Properties.mask = {
+
+       set: function(options){
+               var mask = this.retrieve('mask');
+               if (mask) mask.destroy();
+               return this.eliminate('mask').store('mask:options', options);
+       },
+
+       get: function(){
+               var mask = this.retrieve('mask');
+               if (!mask){
+                       mask = new Mask(this, this.retrieve('mask:options'));
+                       this.store('mask', mask);
+               }
+               return mask;
+       }
+
+};
+
+Element.implement({
+
+       mask: function(options){
+               if (options) this.set('mask', options);
+               this.get('mask').show();
+               return this;
+       },
+
+       unmask: function(){
+               this.get('mask').hide();
+               return this;
+       }
+
+});
+
+
+// Begin: Source/Utilities/DOMReady.js
+/*
+---
+
+name: DOMReady
+
+description: Contains the custom event domready.
+
+license: MIT-style license.
+
+requires: [Browser, Element, Element.Event]
+
+provides: [DOMReady, DomReady]
+
+...
+*/
+
+(function(window, document){
+
+var ready,
+       loaded,
+       checks = [],
+       shouldPoll,
+       timer,
+       testElement = document.createElement('div');
+
+var domready = function(){
+       clearTimeout(timer);
+       if (ready) return;
+       Browser.loaded = ready = true;
+       document.removeListener('DOMContentLoaded', domready).removeListener('readystatechange', check);
+
+       document.fireEvent('domready');
+       window.fireEvent('domready');
+};
+
+var check = function(){
+       for (var i = checks.length; i--;) if (checks[i]()){
+               domready();
+               return true;
+       }
+       return false;
+};
+
+var poll = function(){
+       clearTimeout(timer);
+       if (!check()) timer = setTimeout(poll, 10);
+};
+
+document.addListener('DOMContentLoaded', domready);
+
+/*<ltIE8>*/
+// doScroll technique by Diego Perini http://javascript.nwbox.com/IEContentLoaded/
+// testElement.doScroll() throws when the DOM is not ready, only in the top window
+var doScrollWorks = function(){
+       try {
+               testElement.doScroll();
+               return true;
+       } catch (e){}
+       return false;
+};
+// If doScroll works already, it can't be used to determine domready
+//   e.g. in an iframe
+if (testElement.doScroll && !doScrollWorks()){
+       checks.push(doScrollWorks);
+       shouldPoll = true;
+}
+/*</ltIE8>*/
+
+if (document.readyState) checks.push(function(){
+       var state = document.readyState;
+       return (state == 'loaded' || state == 'complete');
+});
+
+if ('onreadystatechange' in document) document.addListener('readystatechange', check);
+else shouldPoll = true;
+
+if (shouldPoll) poll();
+
+Element.Events.domready = {
+       onAdd: function(fn){
+               if (ready) fn.call(this);
+       }
+};
+
+// Make sure that domready fires before load
+Element.Events.load = {
+       base: 'load',
+       onAdd: function(fn){
+               if (loaded && this == window) fn.call(this);
+       },
+       condition: function(){
+               if (this == window){
+                       domready();
+                       delete Element.Events.load;
+               }
+               return true;
+       }
+};
+
+// This is based on the custom load event
+window.addEvent('load', function(){
+       loaded = true;
+});
+
+})(window, document);
+
+
+// Begin: Source/Element/Element.Pin.js
+/*
+---
+
+script: Element.Pin.js
+
+name: Element.Pin
+
+description: Extends the Element native object to include the pin method useful for fixed positioning for elements.
+
+license: MIT-style license
+
+authors:
+  - Aaron Newton
+
+requires:
+  - Core/Element.Event
+  - Core/Element.Dimensions
+  - Core/Element.Style
+  - /MooTools.More
+
+provides: [Element.Pin]
+
+...
+*/
+
+(function(){
+       var supportsPositionFixed = false,
+               supportTested = false;
+
+       var testPositionFixed = function(){
+               var test = new Element('div').setStyles({
+                       position: 'fixed',
+                       top: 0,
+                       right: 0
+               }).inject(document.body);
+               supportsPositionFixed = (test.offsetTop === 0);
+               test.dispose();
+               supportTested = true;
+       };
+
+       Element.implement({
+
+               pin: function(enable, forceScroll){
+                       if (!supportTested) testPositionFixed();
+                       if (this.getStyle('display') == 'none') return this;
+
+                       var pinnedPosition,
+                               scroll = window.getScroll(),
+                               parent,
+                               scrollFixer;
+
+                       if (enable !== false){
+                               pinnedPosition = this.getPosition(supportsPositionFixed ? document.body : this.getOffsetParent());
+                               if (!this.retrieve('pin:_pinned')){
+                                       var currentPosition = {
+                                               top: pinnedPosition.y - scroll.y,
+                                               left: pinnedPosition.x - scroll.x
+                                       };
+
+                                       if (supportsPositionFixed && !forceScroll){
+                                               this.setStyle('position', 'fixed').setStyles(currentPosition);
+                                       } else {
+
+                                               parent = this.getOffsetParent();
+                                               var position = this.getPosition(parent),
+                                                       styles = this.getStyles('left', 'top');
+
+                                               if (parent && styles.left == 'auto' || styles.top == 'auto') this.setPosition(position);
+                                               if (this.getStyle('position') == 'static') this.setStyle('position', 'absolute');
+
+                                               position = {
+                                                       x: styles.left.toInt() - scroll.x,
+                                                       y: styles.top.toInt() - scroll.y
+                                               };
+
+                                               scrollFixer = function(){
+                                                       if (!this.retrieve('pin:_pinned')) return;
+                                                       var scroll = window.getScroll();
+                                                       this.setStyles({
+                                                               left: position.x + scroll.x,
+                                                               top: position.y + scroll.y
+                                                       });
+                                               }.bind(this);
+
+                                               this.store('pin:_scrollFixer', scrollFixer);
+                                               window.addEvent('scroll', scrollFixer);
+                                       }
+                                       this.store('pin:_pinned', true);
+                               }
+
+                       } else {
+                               if (!this.retrieve('pin:_pinned')) return this;
+
+                               parent = this.getParent();
+                               var offsetParent = (parent.getComputedStyle('position') != 'static' ? parent : parent.getOffsetParent());
+
+                               pinnedPosition = this.getPosition(offsetParent);
+
+                               this.store('pin:_pinned', false);
+                               scrollFixer = this.retrieve('pin:_scrollFixer');
+                               if (!scrollFixer){
+                                       this.setStyles({
+                                               position: 'absolute',
+                                               top: pinnedPosition.y + scroll.y,
+                                               left: pinnedPosition.x + scroll.x
+                                       });
+                               } else {
+                                       this.store('pin:_scrollFixer', null);
+                                       window.removeEvent('scroll', scrollFixer);
+                               }
+                               this.removeClass('isPinned');
+                       }
+                       return this;
+               },
+
+               unpin: function(){
+                       return this.pin(false);
+               },
+
+               togglePin: function(){
+                       return this.pin(!this.retrieve('pin:_pinned'));
+               }
+
+       });
+
+//<1.2compat>
+Element.alias('togglepin', 'togglePin');
+//</1.2compat>
+
+})();
+
+
+// Begin: Source/Types/Object.Extras.js
+/*
+---
+
+script: Object.Extras.js
+
+name: Object.Extras
+
+description: Extra Object generics, like getFromPath which allows a path notation to child elements.
+
+license: MIT-style license
+
+authors:
+  - Aaron Newton
+
+requires:
+  - Core/Object
+  - /MooTools.More
+
+provides: [Object.Extras]
+
+...
+*/
+
+(function(){
+
+var defined = function(value){
+       return value != null;
+};
+
+var hasOwnProperty = Object.prototype.hasOwnProperty;
+
+Object.extend({
+
+       getFromPath: function(source, parts){
+               if (typeof parts == 'string') parts = parts.split('.');
+               for (var i = 0, l = parts.length; i < l; i++){
+                       if (hasOwnProperty.call(source, parts[i])) source = source[parts[i]];
+                       else return null;
+               }
+               return source;
+       },
+
+       cleanValues: function(object, method){
+               method = method || defined;
+               for (var key in object) if (!method(object[key])){
+                       delete object[key];
+               }
+               return object;
+       },
+
+       erase: function(object, key){
+               if (hasOwnProperty.call(object, key)) delete object[key];
+               return object;
+       },
+
+       run: function(object){
+               var args = Array.slice(arguments, 1);
+               for (var key in object) if (object[key].apply){
+                       object[key].apply(object, args);
+               }
+               return object;
+       }
+
+});
+
+})();
+
+
+// Begin: Source/Core/Clientcide.js
+/*
+---
+
+name: Clientcide
+
+description: The Clientcide namespace.
+
+license: MIT-style license.
+
+provides: Clientcide
+
+...
+*/
+var Clientcide = {
+       version: '3.0.10',
+       assetLocation: "http://github.com/anutron/clientcide/raw/master/Assets",
+       setAssetLocation: function(baseHref) {
+               Clientcide.assetLocation = baseHref;
+               if (Clientcide.preloaded) Clientcide.preLoadCss();
+       },
+       preLoadCss: function(){
+               if (window.StickyWin && StickyWin.ui) StickyWin.ui();
+               if (window.StickyWin && StickyWin.pointy) StickyWin.pointy();
+               Clientcide.preloaded = true;
+               return true;
+       },
+       preloaded: false
+};
+(function(){
+       if (!window.addEvent) return;
+       var preload = function(){
+               if (window.dbug) dbug.log('preloading clientcide css');
+               if (!Clientcide.preloaded) Clientcide.preLoadCss();
+       };
+       window.addEvent('domready', preload);
+       window.addEvent('load', preload);
+})();
+setCNETAssetBaseHref = Clientcide.setAssetLocation;
+
+
+// Begin: Source/Core/dbug.js
+/*
+---
+
+name: dbug
+
+description: A wrapper for Firebug console.* statements.
+
+license: MIT-style license.
+
+authors:
+- Aaron Newton
+
+provides: dbug
+
+...
+*/
+var dbug = {
+       logged: [],
+       timers: {},
+       firebug: false,
+       enabled: false,
+       log: function() {
+               dbug.logged.push(arguments);
+       },
+       nolog: function(msg) {
+               dbug.logged.push(arguments);
+       },
+       time: function(name){
+               dbug.timers[name] = new Date().getTime();
+       },
+       timeEnd: function(name){
+               if (dbug.timers[name]) {
+                       var end = new Date().getTime() - dbug.timers[name];
+                       dbug.timers[name] = false;
+                       dbug.log('%s: %s', name, end);
+               } else dbug.log('no such timer: %s', name);
+       },
+       enable: function(silent) {
+               var con = window.firebug ? firebug.d.console.cmd : window.console;
+
+               if((!!window.console && !!window.console.warn) || window.firebug) {
+                       try {
+                               dbug.enabled = true;
+                               dbug.log = function(){
+                                               try {
+                                                       (con.debug || con.log).apply(con, arguments);
+                                               } catch(e) {
+                                                       console.log(Array.slice(arguments));
+                                               }
+                               };
+                               dbug.time = function(){
+                                       con.time.apply(con, arguments);
+                               };
+                               dbug.timeEnd = function(){
+                                       con.timeEnd.apply(con, arguments);
+                               };
+                               if(!silent) dbug.log('enabling dbug');
+                               for(var i=0;i<dbug.logged.length;i++){ dbug.log.apply(con, dbug.logged[i]); }
+                               dbug.logged=[];
+                       } catch(e) {
+                               dbug.enable.delay(400);
+                       }
+               }
+       },
+       disable: function(){
+               if(dbug.firebug) dbug.enabled = false;
+               dbug.log = dbug.nolog;
+               dbug.time = function(){};
+               dbug.timeEnd = function(){};
+       },
+       cookie: function(set){
+               var value = document.cookie.match('(?:^|;)\\s*jsdebug=([^;]*)');
+               var debugCookie = value ? unescape(value[1]) : false;
+               if((set == null && debugCookie != 'true') || (set != null && set)) {
+                       dbug.enable();
+                       dbug.log('setting debugging cookie');
+                       var date = new Date();
+                       date.setTime(date.getTime()+(24*60*60*1000));
+                       document.cookie = 'jsdebug=true;expires='+date.toGMTString()+';path=/;';
+               } else dbug.disableCookie();
+       },
+       disableCookie: function(){
+               dbug.log('disabling debugging cookie');
+               document.cookie = 'jsdebug=false;path=/;';
+       },
+       conditional: function(fn, fnIfError) {
+               if (dbug.enabled) {
+                       return fn();
+               } else {
+                       try {
+                               return fn();
+                       } catch(e) {
+                               if (fnIfError) fnIfError(e);
+                       }
+               }
+       }
+};
+
+(function(){
+       var fb = !!window.console || !!window.firebug;
+       var con = window.firebug ? window.firebug.d.console.cmd : window.console;
+       var debugMethods = ['debug','info','warn','error','assert','dir','dirxml'];
+       var otherMethods = ['trace','group','groupEnd','profile','profileEnd','count'];
+       function set(methodList, defaultFunction) {
+
+               var getLogger = function(method) {
+                       return function(){
+                               con[method].apply(con, arguments);
+                       };
+               };
+
+               for(var i = 0; i < methodList.length; i++){
+                       var method = methodList[i];
+                       if (fb && con[method]) {
+                               dbug[method] = getLogger(method);
+                       } else {
+                               dbug[method] = defaultFunction;
+                       }
+               }
+       };
+       set(debugMethods, dbug.log);
+       set(otherMethods, function(){});
+})();
+if ((!!window.console && !!window.console.warn) || window.firebug){
+       dbug.firebug = true;
+       var value = document.cookie.match('(?:^|;)\\s*jsdebug=([^;]*)');
+       var debugCookie = value ? unescape(value[1]) : false;
+       if(window.location.href.indexOf("jsdebug=true")>0 || debugCookie=='true') dbug.enable();
+       if(debugCookie=='true')dbug.log('debugging cookie enabled');
+       if(window.location.href.indexOf("jsdebugCookie=true")>0){
+               dbug.cookie();
+               if(!dbug.enabled)dbug.enable();
+       }
+       if(window.location.href.indexOf("jsdebugCookie=false")>0)dbug.disableCookie();
+}
+
+
+// Begin: Source/UI/StyleWriter.js
+/*
+---
+name: StyleWriter
+
+description: Provides a simple method for injecting a css style element into the DOM if it's not already present.
+
+license: MIT-Style License
+
+requires: [Core/Class, Core/DomReady, Core/Element, dbug]
+
+provides: StyleWriter
+
+...
+*/
+
+var StyleWriter = new Class({
+       createStyle: function(css, id) {
+               window.addEvent('domready', function(){
+                       try {
+                               if (document.id(id) && id) return;
+                               var style = new Element('style', {id: id||''}).inject($$('head')[0]);
+                               if (Browser.ie) style.styleSheet.cssText = css;
+                               else style.set('text', css);
+                       }catch(e){dbug.log('error: %s',e);}
+               }.bind(this));
+       }
+});
+
+// Begin: Source/UI/StickyWin.js
+/*
+---
+
+name: StickyWin
+
+description: Creates a div within the page with the specified contents at the location relative to the element you specify; basically an in-page popup maker.
+
+license: MIT-Style License
+
+requires: [
+  Core/DomReady,
+  Core/Slick.Finder,
+  More/Element.Position,
+  More/Class.Binds,
+  More/Element.Shortcuts,
+  More/Element.Pin,
+  More/IframeShim,
+  More/Object.Extras,
+  Clientcide,
+  StyleWriter
+]
+
+provides: [StickyWin, StickyWin.Stacker]
+...
+*/
+
+
+var StickyWin = new Class({
+       Binds: ['destroy', 'hide', 'togglepin', 'esc'],
+       Implements: [Options, Events, StyleWriter],
+       options: {
+//             onDisplay: function(){},
+//             onClose: function(){},
+//             onDestroy: function(){},
+               closeClassName: 'closeSticky',
+               pinClassName: 'pinSticky',
+               content: '',
+               zIndex: 10000,
+               className: '',
+//             id: ... set above in initialize function
+/*     these are the defaults for Element.position anyway
+               ************************************************
+               edge: false, //see Element.position
+               position: 'center', //center, corner == upperLeft, upperRight, bottomLeft, bottomRight
+               offset: {x:0,y:0},
+               relativeTo: document.body, */
+               width: false,
+               height: false,
+               timeout: -1,
+               allowMultipleByClass: true,
+               allowMultiple: true,
+               showNow: true,
+               useIframeShim: true,
+               iframeShimSelector: '',
+               destroyOnClose: false,
+               closeOnClickOut: false,
+               closeOnEsc: false,
+               getWindowManager: function(){ return StickyWin.WM; }
+       },
+
+       css: '.SWclearfix:after {content: "."; display: block; height: 0; clear: both; visibility: hidden;}'+
+                '.SWclearfix {display: inline-table;} * html .SWclearfix {height: 1%;} .SWclearfix {display: block;}',
+
+       initialize: function(options){
+               this.options.inject = this.options.inject || {
+                       target: document.body,
+                       where: 'bottom'
+               };
+               this.setOptions(options);
+               this.windowManager = this.options.getWindowManager();
+               this.id = this.options.id || 'StickyWin_'+new Date().getTime();
+               this.makeWindow();
+               if (this.windowManager) this.windowManager.add(this);
+
+               if (this.options.content) this.setContent(this.options.content);
+               if (this.options.timeout > 0) {
+                       this.addEvent('onDisplay', function(){
+                               this.hide.delay(this.options.timeout, this);
+                       }.bind(this));
+               }
+               //add css for clearfix
+               this.createStyle(this.css, 'StickyWinClearFix');
+               if (this.options.closeOnClickOut || this.options.closeOnEsc) this.attach();
+               if (this.options.destroyOnClose) this.addEvent('close', this.destroy);
+               if (this.options.showNow) this.show();
+       },
+       toElement: function(){
+               return this.element;
+       },
+       attach: function(dettach){
+               var method = dettach ? 'removeEvents' : 'addEvents';
+               var events = {};
+               if (this.options.closeOnClickOut) events.click = this.esc;
+               if (this.options.closeOnEsc) events.keyup = this.esc;
+               document[method](events);
+       },
+       esc: function(e) {
+               if (e.key == "esc") this.hide();
+               if (e.type == "click" && this.element != e.target && !this.element.contains(e.target)) this.hide();
+       },
+       makeWindow: function(){
+               this.destroyOthers();
+               if (!document.id(this.id)) {
+                       this.win = new Element('div', {
+                               id: this.id
+                       }).addClass(this.options.className).addClass('StickyWinInstance').addClass('SWclearfix').setStyles({
+                               display: 'none',
+                               position: 'absolute',
+                               zIndex: this.options.zIndex
+                       }).inject(this.options.inject.target, this.options.inject.where).store('StickyWin', this);
+               } else this.win = document.id(this.id);
+               this.element = this.win;
+               if (this.options.width && typeOf(this.options.width.toInt())=="number") this.win.setStyle('width', this.options.width.toInt());
+               if (this.options.height && typeOf(this.options.height.toInt())=="number") this.win.setStyle('height', this.options.height.toInt());
+               return this;
+       },
+       show: function(suppressEvent){
+               this.showWin();
+               if (!suppressEvent) this.fireEvent('display');
+               if (this.options.useIframeShim) this.showIframeShim();
+               this.visible = true;
+               return this;
+       },
+       showWin: function(){
+               if (this.windowManager) this.windowManager.focus(this);
+               if (!this.positioned) this.position();
+               this.win.show();
+       },
+       hide: function(suppressEvent){
+               if (typeOf(suppressEvent) == "event" || !suppressEvent) this.fireEvent('close');
+               this.hideWin();
+               if (this.options.useIframeShim) this.hideIframeShim();
+               this.visible = false;
+               return this;
+       },
+       hideWin: function(){
+               this.win.setStyle('display','none');
+       },
+       destroyOthers: function() {
+               if (!this.options.allowMultipleByClass || !this.options.allowMultiple) {
+                       $$('div.StickyWinInstance').each(function(sw) {
+                               if (!this.options.allowMultiple || (!this.options.allowMultipleByClass && sw.hasClass(this.options.className)))
+                                       sw.retrieve('StickyWin').destroy();
+                       }, this);
+               }
+       },
+       setContent: function(html) {
+               if (this.win.getChildren().length>0) this.win.empty();
+               if (typeOf(html) == "string") this.win.set('html', html);
+               else if (document.id(html)) this.win.adopt(html);
+               this.win.getElements('.'+this.options.closeClassName).each(function(el){
+                       el.addEvent('click', this.hide);
+               }, this);
+               this.win.getElements('.'+this.options.pinClassName).each(function(el){
+                       el.addEvent('click', this.togglepin);
+               }, this);
+               return this;
+       },
+       position: function(options){
+               this.positioned = true;
+               this.setOptions(options);
+               this.win.position(
+                       Object.cleanValues({
+                               allowNegative: [this.options.allowNegative, this.options.relativeTo != document.body].pick(),
+                               relativeTo: this.options.relativeTo,
+                               position: this.options.position,
+                               offset: this.options.offset,
+                               edge: this.options.edge
+                       })
+               );
+               if (this.shim) this.shim.position();
+               return this;
+       },
+       pin: function(pin) {
+               if (!this.win.pin) {
+                       dbug.log('you must include element.pin.js!');
+                       return this;
+               }
+               this.pinned = pin != null && pin;
+               this.win.pin(pin);
+               return this;
+       },
+       unpin: function(){
+               return this.pin(false);
+       },
+       togglepin: function(){
+               return this.pin(!this.pinned);
+       },
+       makeIframeShim: function(){
+               if (!this.shim){
+                       var el = (this.options.iframeShimSelector)?this.win.getElement(this.options.iframeShimSelector):this.win;
+                       this.shim = new IframeShim(el, {
+                               display: false,
+                               name: 'StickyWinShim'
+                       });
+               }
+       },
+       showIframeShim: function(){
+               if (this.options.useIframeShim) {
+                       this.makeIframeShim();
+                       this.shim.show();
+               }
+       },
+       hideIframeShim: function(){
+               if (this.shim) this.shim.hide();
+       },
+       destroy: function(){
+               this.destroyed = true;
+               this.attach(true);
+               if (this.windowManager) this.windowManager.remove(this);
+               if (this.win) this.win.destroy();
+               if (this.options.useIframeShim && this.shim) this.shim.destroy();
+               if (document.id('modalOverlay')) document.id('modalOverlay').destroy();
+               this.fireEvent('destroy');
+       }
+});
+
+StickyWin.Stacker = new Class({
+       Implements: [Options, Events],
+       Binds: ['click'],
+       instances: [],
+       options: {
+               zIndexBase: 9000
+       },
+       initialize: function(options) {
+               this.setOptions(options);
+       },
+       add: function(sw) {
+               this.instances.include(sw);
+               $(sw).addEvent('mousedown', this.click);
+       },
+       click: function(e) {
+               this.instances.each(function(sw){
+                       var el = $(sw);
+                       if (el == e.target || el.contains($(e.target))) this.focus(sw);
+               }, this);
+       },
+       focus: function(instance){
+               if (this.focused == instance) return;
+               this.focused = instance;
+               if (instance) this.instances.erase(instance).push(instance);
+               this.instances.each(function(current, i){
+                       $(current).setStyle('z-index', this.options.zIndexBase + i);
+               }, this);
+               this.focused = instance;
+       },
+       remove: function(sw) {
+               this.instances.erase(sw);
+               $(sw).removeEvent('click', this.click);
+       }
+});
+StickyWin.WM = new StickyWin.Stacker();
+
+// Begin: Source/UI/StickyWin.Modal.js
+/*
+---
+
+name: StickyWin.Modal
+
+description: This script extends StickyWin and StickyWin.Fx classes to add Mask functionality.
+
+license: MIT-Style License
+
+requires: [More/Mask, StickyWin]
+
+provides: StickyWin.Modal
+...
+*/
+StickyWin.Modal = new Class({
+
+       Extends: StickyWin,
+
+       options: {
+               modalize: true,
+               maskOptions: {
+                       style: {
+                               'background-color':'#333',
+                               opacity:0.8
+                       }
+               },
+               hideOnClick: true,
+               getWindowManager: function(){ return StickyWin.ModalWM; }
+       },
+
+       initialize: function(options) {
+               this.options.maskTarget = this.options.maskTarget || document.body;
+               this.setOptions(options);
+               this.mask = new Mask(this.options.maskTarget, this.options.maskOptions).addEvent('click', function() {
+                       if (this.options.hideOnClick) this.hide();
+               }.bind(this));
+               this.parent(options);
+       },
+
+       show: function(showModal){
+               if ([showModal, this.options.modalize].pick()) this.mask.show();
+               this.parent();
+       },
+
+       hide: function(hideModal){
+               if ([hideModal, true].pick()) this.mask.hide();
+               this.parent();
+       },
+
+       destroy: function(){
+               this.mask.destroy();
+               this.parent.apply(this, arguments);
+       }
+
+});
+
+StickyWin.ModalWM = new StickyWin.Stacker({
+       zIndexBase: 11000
+});
+if (StickyWin.Fx) StickyWin.Fx.Modal = StickyWin.Modal;
+
+// Begin: Source/Types/String.Extras.js
+/*
+---
+
+script: String.Extras.js
+
+name: String.Extras
+
+description: Extends the String native object to include methods useful in managing various kinds of strings (query strings, urls, html, etc).
+
+license: MIT-style license
+
+authors:
+  - Aaron Newton
+  - Guillermo Rauch
+  - Christopher Pitt
+
+requires:
+  - Core/String
+  - Core/Array
+  - MooTools.More
+
+provides: [String.Extras]
+
+...
+*/
+
+(function(){
+
+var special = {
+       'a': /[àáâãäåăą]/g,
+       'A': /[ÀÁÂÃÄÅĂĄ]/g,
+       'c': /[ćčç]/g,
+       'C': /[ĆČÇ]/g,
+       'd': /[ďđ]/g,
+       'D': /[ĎÐ]/g,
+       'e': /[èéêëěę]/g,
+       'E': /[ÈÉÊËĚĘ]/g,
+       'g': /[ğ]/g,
+       'G': /[Ğ]/g,
+       'i': /[ìíîï]/g,
+       'I': /[ÌÍÎÏ]/g,
+       'l': /[ĺľł]/g,
+       'L': /[ĹĽŁ]/g,
+       'n': /[ñňń]/g,
+       'N': /[ÑŇŃ]/g,
+       'o': /[òóôõöøő]/g,
+       'O': /[ÒÓÔÕÖØ]/g,
+       'r': /[řŕ]/g,
+       'R': /[ŘŔ]/g,
+       's': /[ššş]/g,
+       'S': /[ŠŞŚ]/g,
+       't': /[ťţ]/g,
+       'T': /[ŤŢ]/g,
+       'ue': /[ü]/g,
+       'UE': /[Ü]/g,
+       'u': /[ùúûůµ]/g,
+       'U': /[ÙÚÛŮ]/g,
+       'y': /[ÿý]/g,
+       'Y': /[ŸÝ]/g,
+       'z': /[žźż]/g,
+       'Z': /[ŽŹŻ]/g,
+       'th': /[þ]/g,
+       'TH': /[Þ]/g,
+       'dh': /[ð]/g,
+       'DH': /[Ð]/g,
+       'ss': /[ß]/g,
+       'oe': /[œ]/g,
+       'OE': /[Œ]/g,
+       'ae': /[æ]/g,
+       'AE': /[Æ]/g
+},
+
+tidy = {
+       ' ': /[\xa0\u2002\u2003\u2009]/g,
+       '*': /[\xb7]/g,
+       '\'': /[\u2018\u2019]/g,
+       '"': /[\u201c\u201d]/g,
+       '...': /[\u2026]/g,
+       '-': /[\u2013]/g,
+//     '--': /[\u2014]/g,
+       '&raquo;': /[\uFFFD]/g
+},
+
+conversions = {
+       ms: 1,
+       s: 1000,
+       m: 6e4,
+       h: 36e5
+},
+
+findUnits = /(\d*.?\d+)([msh]+)/;
+
+var walk = function(string, replacements){
+       var result = string, key;
+       for (key in replacements) result = result.replace(replacements[key], key);
+       return result;
+};
+
+var getRegexForTag = function(tag, contents){
+       tag = tag || '';
+       var regstr = contents ? "<" + tag + "(?!\\w)[^>]*>([\\s\\S]*?)<\/" + tag + "(?!\\w)>" : "<\/?" + tag + "([^>]+)?>",
+               reg = new RegExp(regstr, "gi");
+       return reg;
+};
+
+String.implement({
+
+       standardize: function(){
+               return walk(this, special);
+       },
+
+       repeat: function(times){
+               return new Array(times + 1).join(this);
+       },
+
+       pad: function(length, str, direction){
+               if (this.length >= length) return this;
+
+               var pad = (str == null ? ' ' : '' + str)
+                       .repeat(length - this.length)
+                       .substr(0, length - this.length);
+
+               if (!direction || direction == 'right') return this + pad;
+               if (direction == 'left') return pad + this;
+
+               return pad.substr(0, (pad.length / 2).floor()) + this + pad.substr(0, (pad.length / 2).ceil());
+       },
+
+       getTags: function(tag, contents){
+               return this.match(getRegexForTag(tag, contents)) || [];
+       },
+
+       stripTags: function(tag, contents){
+               return this.replace(getRegexForTag(tag, contents), '');
+       },
+
+       tidy: function(){
+               return walk(this, tidy);
+       },
+
+       truncate: function(max, trail, atChar){
+               var string = this;
+               if (trail == null && arguments.length == 1) trail = '…';
+               if (string.length > max){
+                       string = string.substring(0, max);
+                       if (atChar){
+                               var index = string.lastIndexOf(atChar);
+                               if (index != -1) string = string.substr(0, index);
+                       }
+                       if (trail) string += trail;
+               }
+               return string;
+       },
+
+       ms: function(){
+         // "Borrowed" from https://gist.github.com/1503944
+               var units = findUnits.exec(this);
+               if (units == null) return Number(this);
+               return Number(units[1]) * conversions[units[2]];
+       }
+
+});
+
+})();
+
+
+// Begin: Source/UI/StickyWin.UI.js
+ /*
+---
+name: StickyWin.UI
+
+description: Creates an html holder for in-page popups using a default style.
+
+license: MIT-Style License
+
+requires: [Core/Element.Style, More/String.Extras, StyleWriter, StickyWin]
+
+provides: StickyWin.UI
+...
+*/
+StickyWin.UI = new Class({
+       Implements: [Options, StyleWriter],
+       options: {
+               width: 300,
+               css: "div.DefaultStickyWin {font-family:verdana; font-size:11px; line-height: 13px;position: relative;}"+
+                       "div.DefaultStickyWin div.top{-moz-user-select: none;-khtml-user-select: none;}"+
+                       "div.DefaultStickyWin div.top_ul{background:url({%baseHref%}full.png) top left no-repeat; height:30px; width:15px; float:left}"+
+                       "div.DefaultStickyWin div.top_ur{position:relative; left:0px !important; left:-4px; background:url({%baseHref%}full.png) top right !important; height:30px; margin:0px 0px 0px 15px !important; margin-right:-4px; padding:0px}"+
+                       "div.DefaultStickyWin h1.caption{clear: none !important; margin:0px !important; overflow: hidden; padding:0 !important; font-weight:bold; color:#555; font-size:14px !important; position:relative; top:8px !important; left:5px !important; float: left; height: 22px !important;}"+
+                       "div.DefaultStickyWin div.middle, div.DefaultStickyWin div.closeBody {background:url({%baseHref%}body.png) top left repeat-y; margin:0px 20px 0px 0px !important;       margin-bottom: -3px; position: relative;        top: 0px !important; top: -3px;}"+
+                       "div.DefaultStickyWin div.body{background:url({%baseHref%}body.png) top right repeat-y; padding:8px 23px 8px 0px !important; margin-left:5px !important; position:relative; right:-20px !important; z-index: 1;}"+
+                       "div.DefaultStickyWin div.bottom{clear:both;}"+
+                       "div.DefaultStickyWin div.bottom_ll{background:url({%baseHref%}full.png) bottom left no-repeat; width:15px; height:15px; float:left}"+
+                       "div.DefaultStickyWin div.bottom_lr{background:url({%baseHref%}full.png) bottom right; position:relative; left:0px !important; left:-4px; margin:0px 0px 0px 15px !important; margin-right:-4px; height:15px}"+
+                       "div.DefaultStickyWin div.closeButtons{text-align: center; background:url({%baseHref%}body.png) top right repeat-y; padding: 4px 30px 8px 0px; margin-left:5px; position:relative; right:-20px}"+
+                       "div.DefaultStickyWin a.button:hover{background:url({%baseHref%}big_button_over.gif) repeat-x}"+
+                       "div.DefaultStickyWin a.button {background:url({%baseHref%}big_button.gif) repeat-x; margin: 2px 8px 2px 8px; padding: 2px 12px; cursor:pointer; border: 1px solid #999 !important; text-decoration:none; color: #000 !important;}"+
+                       "div.DefaultStickyWin div.closeButton{width:13px; height:13px; background:url({%baseHref%}closebtn.gif) no-repeat; position: absolute; right: 0px; margin:10px 15px 0px 0px !important; cursor:pointer;top:0px}"+
+                       "div.DefaultStickyWin div.dragHandle {  width: 11px;    height: 25px;   position: relative;     top: 5px;       left: -3px;     cursor: move;   background: url({%baseHref%}drag_corner.gif); float: left;}",
+               cornerHandle: false,
+               cssClass: '',
+               buttons: [],
+               cssId: 'defaultStickyWinStyle',
+               cssClassName: 'DefaultStickyWin',
+               closeButton: true
+/*     These options are deprecated:
+               closeTxt: false,
+               onClose: function(){},
+               confirmTxt: false,
+               onConfirm: function(){} */
+       },
+       initialize: function() {
+               var args = this.getArgs(arguments);
+               this.setOptions(args.options);
+               this.legacy();
+               var css = this.options.css.substitute({baseHref: this.options.baseHref || Clientcide.assetLocation + '/stickyWinHTML/'}, /\\?\{%([^}]+)%\}/g);
+               if (Browser.ie) css = css.replace(/png/g, 'gif');
+               this.createStyle(css, this.options.cssId);
+               this.build();
+               if (args.caption || args.body) this.setContent(args.caption, args.body);
+       },
+       toElement: function(){
+               return this.element;
+       },
+       getArgs: function(){
+               return StickyWin.UI.getArgs.apply(this, arguments);
+       },
+       legacy: function(){
+               var opt = this.options; //saving bytes
+               //legacy support
+               if (opt.confirmTxt) opt.buttons.push({text: opt.confirmTxt, onClick: opt.onConfirm || function(){}});
+               if (opt.closeTxt) opt.buttons.push({text: opt.closeTxt, onClick: opt.onClose || function(){}});
+       },
+       build: function(){
+               var opt = this.options;
+
+               var container = new Element('div', {
+                       'class': opt.cssClassName
+               });
+               if (opt.width) container.setStyle('width', opt.width);
+               this.element = container;
+               this.element.store('StickyWinUI', this);
+               if (opt.cssClass) container.addClass(opt.cssClass);
+
+
+               var bodyDiv = new Element('div').addClass('body');
+               this.body = bodyDiv;
+
+               var top_ur = new Element('div').addClass('top_ur');
+               this.top_ur = top_ur;
+               this.top = new Element('div').addClass('top').adopt(
+                               new Element('div').addClass('top_ul')
+                       ).adopt(top_ur);
+               container.adopt(this.top);
+
+               if (opt.cornerHandle) new Element('div').addClass('dragHandle').inject(top_ur, 'top');
+
+               //body
+               container.adopt(new Element('div').addClass('middle').adopt(bodyDiv));
+               //close buttons
+               if (opt.buttons.length > 0){
+                       var closeButtons = new Element('div').addClass('closeButtons');
+                       opt.buttons.each(function(button){
+                               if (button.properties && button.properties.className){
+                                       button.properties['class'] = button.properties.className;
+                                       delete button.properties.className;
+                               }
+                               var properties = Object.merge({'class': 'closeSticky'}, button.properties);
+                               new Element('a').addEvent('click', button.onClick || function(){})
+                                       .appendText(button.text).inject(closeButtons).set(properties).addClass('button');
+                       });
+                       container.adopt(new Element('div').addClass('closeBody').adopt(closeButtons));
+               }
+               //footer
+               container.adopt(
+                       new Element('div').addClass('bottom').adopt(
+                                       new Element('div').addClass('bottom_ll')
+                               ).adopt(
+                                       new Element('div').addClass('bottom_lr')
+                       )
+               );
+               if (this.options.closeButton) container.adopt(new Element('div').addClass('closeButton').addClass('closeSticky'));
+               return this;
+       },
+       setCaption: function(caption) {
+               this.caption = caption;
+               if (!this.h1) {
+                       this.makeCaption(caption);
+               } else {
+                       if (document.id(caption)) this.h1.adopt(caption);
+                       else this.h1.set('html', caption);
+               }
+               return this;
+       },
+       makeCaption: function(caption) {
+               if (!caption) return this.destroyCaption();
+               var opt = this.options;
+               this.h1 = new Element('h1').addClass('caption');
+               if (opt.width) this.h1.setStyle('width', (opt.width.toInt()-(opt.cornerHandle?55:40)-(opt.closeButton?10:0)));
+               this.setCaption(caption);
+               this.top_ur.adopt(this.h1);
+               if (!this.options.cornerHandle) this.h1.addClass('dragHandle');
+               return this;
+       },
+       destroyCaption: function(){
+               if (this.h1) {
+                       this.h1.destroy();
+                       this.h1 = null;
+               }
+               return this;
+       },
+       setContent: function(){
+               var args = this.getArgs.apply(this, arguments);
+               var caption = args.caption;
+               var body = args.body;
+               this.setCaption(caption);
+               if (document.id(body)) this.body.empty().adopt(body);
+               else this.body.set('html', body);
+               return this;
+       }
+});
+StickyWin.UI.getArgs = function(){
+       var input = typeOf(arguments[0]) == "arguments"?arguments[0]:arguments;
+       if (Browser.opera && 1 === input.length) input = input[0];
+
+       var cap = input[0], bod = input[1];
+       var args = Array.link(input, {options: Type.isObject});
+       if (input.length == 3 || (!args.options && input.length == 2)) {
+               args.caption = cap;
+               args.body = bod;
+       } else if ((typeOf(bod) == 'object' || !bod) && cap && typeOf(cap) != 'object'){
+               args.body = cap;
+       }
+       return args;
+};
+
+StickyWin.ui = function(caption, body, options){
+       return document.id(new StickyWin.UI(caption, body, options));
+};
+
+
+// Begin: Source/UI/StickyWin.Alert.js
+/*
+---
+
+name: StickyWin.Alert
+
+description: Defines StickyWin.Alert, a simple little alert box with a close button.
+
+license: MIT-Style License
+
+requires: [StickyWin.Modal, StickyWin.UI]
+
+provides: [StickyWin.Alert, StickyWin.Error, StickyWin.alert, StickyWin.error]
+
+...
+*/
+StickyWin.Alert = new Class({
+       Implements: Options,
+       Extends: StickyWin.Modal,
+       options: {
+               destroyOnClose: true,
+               modalOptions: {
+                       modalStyle: {
+                               zIndex: 11000
+                       }
+               },
+               zIndex: 110001,
+               uiOptions: {
+                       width: 250,
+                       buttons: [
+                               {text: 'Ok'}
+                       ]
+               },
+               getWindowManager: function(){}
+       },
+       initialize: function(caption, message, options) {
+               this.message = message;
+               this.caption = caption;
+               this.setOptions(options);
+               this.setOptions({
+                       content: this.build()
+               });
+               this.parent(options);
+       },
+       makeMessage: function() {
+               return new Element('p', {
+                       'class': 'errorMsg SWclearfix',
+                       styles: {
+                               margin: 0,
+                               minHeight: 10
+                       },
+                       html: this.message
+               });
+       },
+       build: function(){
+               return StickyWin.ui(this.caption, this.makeMessage(), this.options.uiOptions);
+       }
+});
+
+StickyWin.Error = new Class({
+       Extends: StickyWin.Alert,
+       makeMessage: function(){
+               var message = this.parent();
+               new Element('img', {
+                       src: (this.options.baseHref || Clientcide.assetLocation + '/simple.error.popup') + '/icon_problems_sm.gif',
+                       'class': 'bang clearfix',
+                       styles: {
+                               'float': 'left',
+                               width: 30,
+                               height: 30,
+                               margin: '3px 5px 5px 0px'
+                       }
+               }).inject(message, 'top');
+               return message;
+       }
+});
+
+StickyWin.alert = function(caption, message, options) {
+       if (typeOf(options) == "string") options = {baseHref: options};
+       return new StickyWin.Alert(caption, message, options);
+};
+
+StickyWin.error = function(caption, message, options) {
+       return new StickyWin.Error(caption, message, options);
+};
+
+// Begin: Source/UI/StickyWin.Confirm.js
+/*
+---
+name: StickyWin.Confirm
+
+description: Defines StickyWin.Conferm, a simple confirmation box with an ok and a close button.
+
+license: MIT-Style License
+
+requires: StickyWin.Alert
+
+provides: [StickyWin.Confirm, StickyWin.confirm]
+
+...
+*/
+StickyWin.Confirm = new Class({
+       Extends: StickyWin.Alert,
+       options: {
+               uiOptions: {
+                       width: 250
+               }
+       },
+       build: function(callback){
+               this.setOptions({
+                       uiOptions: {
+                               buttons: [
+                                       {text: 'Cancel'},
+                                       {
+                                               text: 'Ok',
+                                               onClick: callback || function(){
+                                                       this.fireEvent('confirm');
+                                               }.bind(this)
+                                       }
+                               ]
+                       }
+               });
+               return this.parent();
+       }
+});
+
+StickyWin.confirm = function(caption, message, callback, options) {
+       return new StickyWin.Confirm(caption, message, options).addEvent('confirm', callback);
+};
+
+// Begin: Source/Fx/Fx.Move.js
+/*
+---
+
+script: Fx.Move.js
+
+name: Fx.Move
+
+description: Defines Fx.Move, a class that works with Element.Position.js to transition an element from one location to another.
+
+license: MIT-style license
+
+authors:
+  - Aaron Newton
+
+requires:
+  - Core/Fx.Morph
+  - /Element.Position
+
+provides: [Fx.Move]
+
+...
+*/
+
+Fx.Move = new Class({
+
+       Extends: Fx.Morph,
+
+       options: {
+               relativeTo: document.body,
+               position: 'center',
+               edge: false,
+               offset: {x: 0, y: 0}
+       },
+
+       start: function(destination){
+               var element = this.element,
+                       topLeft = element.getStyles('top', 'left');
+               if (topLeft.top == 'auto' || topLeft.left == 'auto'){
+                       element.setPosition(element.getPosition(element.getOffsetParent()));
+               }
+               return this.parent(element.position(Object.merge({}, this.options, destination, {returnPos: true})));
+       }
+
+});
+
+Element.Properties.move = {
+
+       set: function(options){
+               this.get('move').cancel().setOptions(options);
+               return this;
+       },
+
+       get: function(){
+               var move = this.retrieve('move');
+               if (!move){
+                       move = new Fx.Move(this, {link: 'cancel'});
+                       this.store('move', move);
+               }
+               return move;
+       }
+
+};
+
+Element.implement({
+
+       move: function(options){
+               this.get('move').start(options);
+               return this;
+       }
+
+});
+
+
+// Begin: Source/Fx/Fx.Scroll.js
+/*
+---
+
+script: Fx.Scroll.js
+
+name: Fx.Scroll
+
+description: Effect to smoothly scroll any element, including the window.
+
+license: MIT-style license
+
+authors:
+  - Valerio Proietti
+
+requires:
+  - Core/Fx
+  - Core/Element.Event
+  - Core/Element.Dimensions
+  - /MooTools.More
+
+provides: [Fx.Scroll]
+
+...
+*/
+
+(function(){
+
+Fx.Scroll = new Class({
+
+       Extends: Fx,
+
+       options: {
+               offset: {x: 0, y: 0},
+               wheelStops: true
+       },
+
+       initialize: function(element, options){
+               this.element = this.subject = document.id(element);
+               this.parent(options);
+
+               if (typeOf(this.element) != 'element') this.element = document.id(this.element.getDocument().body);
+
+               if (this.options.wheelStops){
+                       var stopper = this.element,
+                               cancel = this.cancel.pass(false, this);
+                       this.addEvent('start', function(){
+                               stopper.addEvent('mousewheel', cancel);
+                       }, true);
+                       this.addEvent('complete', function(){
+                               stopper.removeEvent('mousewheel', cancel);
+                       }, true);
+               }
+       },
+
+       set: function(){
+               var now = Array.flatten(arguments);
+               if (Browser.firefox) now = [Math.round(now[0]), Math.round(now[1])]; // not needed anymore in newer firefox versions
+               this.element.scrollTo(now[0], now[1]);
+               return this;
+       },
+
+       compute: function(from, to, delta){
+               return [0, 1].map(function(i){
+                       return Fx.compute(from[i], to[i], delta);
+               });
+       },
+
+       start: function(x, y){
+               if (!this.check(x, y)) return this;
+               var scroll = this.element.getScroll();
+               return this.parent([scroll.x, scroll.y], [x, y]);
+       },
+
+       calculateScroll: function(x, y){
+               var element = this.element,
+                       scrollSize = element.getScrollSize(),
+                       scroll = element.getScroll(),
+                       size = element.getSize(),
+                       offset = this.options.offset,
+                       values = {x: x, y: y};
+
+               for (var z in values){
+                       if (!values[z] && values[z] !== 0) values[z] = scroll[z];
+                       if (typeOf(values[z]) != 'number') values[z] = scrollSize[z] - size[z];
+                       values[z] += offset[z];
+               }
+
+               return [values.x, values.y];
+       },
+
+       toTop: function(){
+               return this.start.apply(this, this.calculateScroll(false, 0));
+       },
+
+       toLeft: function(){
+               return this.start.apply(this, this.calculateScroll(0, false));
+       },
+
+       toRight: function(){
+               return this.start.apply(this, this.calculateScroll('right', false));
+       },
+
+       toBottom: function(){
+               return this.start.apply(this, this.calculateScroll(false, 'bottom'));
+       },
+
+       toElement: function(el, axes){
+               axes = axes ? Array.from(axes) : ['x', 'y'];
+               var scroll = isBody(this.element) ? {x: 0, y: 0} : this.element.getScroll();
+               var position = Object.map(document.id(el).getPosition(this.element), function(value, axis){
+                       return axes.contains(axis) ? value + scroll[axis] : false;
+               });
+               return this.start.apply(this, this.calculateScroll(position.x, position.y));
+       },
+
+       toElementEdge: function(el, axes, offset){
+               axes = axes ? Array.from(axes) : ['x', 'y'];
+               el = document.id(el);
+               var to = {},
+                       position = el.getPosition(this.element),
+                       size = el.getSize(),
+                       scroll = this.element.getScroll(),
+                       containerSize = this.element.getSize(),
+                       edge = {
+                               x: position.x + size.x,
+                               y: position.y + size.y
+                       };
+
+               ['x', 'y'].each(function(axis){
+                       if (axes.contains(axis)){
+                               if (edge[axis] > scroll[axis] + containerSize[axis]) to[axis] = edge[axis] - containerSize[axis];
+                               if (position[axis] < scroll[axis]) to[axis] = position[axis];
+                       }
+                       if (to[axis] == null) to[axis] = scroll[axis];
+                       if (offset && offset[axis]) to[axis] = to[axis] + offset[axis];
+               }, this);
+
+               if (to.x != scroll.x || to.y != scroll.y) this.start(to.x, to.y);
+               return this;
+       },
+
+       toElementCenter: function(el, axes, offset){
+               axes = axes ? Array.from(axes) : ['x', 'y'];
+               el = document.id(el);
+               var to = {},
+                       position = el.getPosition(this.element),
+                       size = el.getSize(),
+                       scroll = this.element.getScroll(),
+                       containerSize = this.element.getSize();
+
+               ['x', 'y'].each(function(axis){
+                       if (axes.contains(axis)){
+                               to[axis] = position[axis] - (containerSize[axis] - size[axis]) / 2;
+                       }
+                       if (to[axis] == null) to[axis] = scroll[axis];
+                       if (offset && offset[axis]) to[axis] = to[axis] + offset[axis];
+               }, this);
+
+               if (to.x != scroll.x || to.y != scroll.y) this.start(to.x, to.y);
+               return this;
+       }
+
+});
+
+//<1.2compat>
+Fx.Scroll.implement({
+       scrollToCenter: function(){
+               return this.toElementCenter.apply(this, arguments);
+       },
+       scrollIntoView: function(){
+               return this.toElementEdge.apply(this, arguments);
+       }
+});
+//</1.2compat>
+
+function isBody(element){
+       return (/^(?:body|html)$/i).test(element.tagName);
+}
+
+})();
+
+
+// Begin: Source/Class/Class.Refactor.js
+/*
+---
+
+script: Class.Refactor.js
+
+name: Class.Refactor
+
+description: Extends a class onto itself with new property, preserving any items attached to the class's namespace.
+
+license: MIT-style license
+
+authors:
+  - Aaron Newton
+
+requires:
+  - Core/Class
+  - /MooTools.More
+
+# Some modules declare themselves dependent on Class.Refactor
+provides: [Class.refactor, Class.Refactor]
+
+...
+*/
+
+Class.refactor = function(original, refactors){
+
+       Object.each(refactors, function(item, name){
+               var origin = original.prototype[name];
+               origin = (origin && origin.$origin) || origin || function(){};
+               original.implement(name, (typeof item == 'function') ? function(){
+                       var old = this.previous;
+                       this.previous = origin;
+                       var value = item.apply(this, arguments);
+                       this.previous = old;
+                       return value;
+               } : item);
+       });
+
+       return original;
+
+};
+
+
+// Begin: Source/Fx/Fx.Tween.js
+/*
+---
+
+name: Fx.Tween
+
+description: Formerly Fx.Style, effect to transition any CSS property for an element.
+
+license: MIT-style license.
+
+requires: Fx.CSS
+
+provides: [Fx.Tween, Element.fade, Element.highlight]
+
+...
+*/
+
+Fx.Tween = new Class({
+
+       Extends: Fx.CSS,
+
+       initialize: function(element, options){
+               this.element = this.subject = document.id(element);
+               this.parent(options);
+       },
+
+       set: function(property, now){
+               if (arguments.length == 1){
+                       now = property;
+                       property = this.property || this.options.property;
+               }
+               this.render(this.element, property, now, this.options.unit);
+               return this;
+       },
+
+       start: function(property, from, to){
+               if (!this.check(property, from, to)) return this;
+               var args = Array.flatten(arguments);
+               this.property = this.options.property || args.shift();
+               var parsed = this.prepare(this.element, this.property, args);
+               return this.parent(parsed.from, parsed.to);
+       }
+
+});
+
+Element.Properties.tween = {
+
+       set: function(options){
+               this.get('tween').cancel().setOptions(options);
+               return this;
+       },
+
+       get: function(){
+               var tween = this.retrieve('tween');
+               if (!tween){
+                       tween = new Fx.Tween(this, {link: 'cancel'});
+                       this.store('tween', tween);
+               }
+               return tween;
+       }
+
+};
+
+Element.implement({
+
+       tween: function(property, from, to){
+               this.get('tween').start(property, from, to);
+               return this;
+       },
+
+       fade: function(how){
+               var fade = this.get('tween'), method, args = ['opacity'].append(arguments), toggle;
+               if (args[1] == null) args[1] = 'toggle';
+               switch (args[1]){
+                       case 'in': method = 'start'; args[1] = 1; break;
+                       case 'out': method = 'start'; args[1] = 0; break;
+                       case 'show': method = 'set'; args[1] = 1; break;
+                       case 'hide': method = 'set'; args[1] = 0; break;
+                       case 'toggle':
+                               var flag = this.retrieve('fade:flag', this.getStyle('opacity') == 1);
+                               method = 'start';
+                               args[1] = flag ? 0 : 1;
+                               this.store('fade:flag', !flag);
+                               toggle = true;
+                       break;
+                       default: method = 'start';
+               }
+               if (!toggle) this.eliminate('fade:flag');
+               fade[method].apply(fade, args);
+               var to = args[args.length - 1];
+               if (method == 'set' || to != 0) this.setStyle('visibility', to == 0 ? 'hidden' : 'visible');
+               else fade.chain(function(){
+                       this.element.setStyle('visibility', 'hidden');
+                       this.callChain();
+               });
+               return this;
+       },
+
+       highlight: function(start, end){
+               if (!end){
+                       end = this.retrieve('highlight:original', this.getStyle('background-color'));
+                       end = (end == 'transparent') ? '#fff' : end;
+               }
+               var tween = this.get('tween');
+               tween.start('background-color', start || '#ffff88', end).chain(function(){
+                       this.setStyle('background-color', this.retrieve('highlight:original'));
+                       tween.callChain();
+               }.bind(this));
+               return this;
+       }
+
+});
+
+
+// Begin: Source/UI/StickyWin.Fx.js
+/*
+---
+
+name: StickyWin.Fx
+
+description: Extends StickyWin to create popups that fade in and out.
+
+license: MIT-style license.
+
+requires: [More/Class.Refactor, Core/Fx.Tween, StickyWin]
+
+provides: StickyWin.Fx
+
+...
+*/
+if (!Browser.ie){
+       StickyWin = Class.refactor(StickyWin, {
+               options: {
+                       //fadeTransition: 'sine:in:out',
+                       fade: true,
+                       fadeDuration: 150
+               },
+               hideWin: function(){
+                       if (this.options.fade) this.fade(0);
+                       else this.previous();
+               },
+               showWin: function(){
+                       if (this.options.fade) this.fade(1);
+                       else this.previous();
+               },
+               hide: function(){
+                       this.previous(this.options.fade);
+               },
+               show: function(){
+                       this.previous(this.options.fade);
+               },
+               fade: function(to){
+                       if (!this.fadeFx) {
+                               this.win.setStyles({
+                                       opacity: 0,
+                                       display: 'block'
+                               });
+                               var opts = {
+                                       property: 'opacity',
+                                       duration: this.options.fadeDuration
+                               };
+                               if (this.options.fadeTransition) opts.transition = this.options.fadeTransition;
+                               this.fadeFx = new Fx.Tween(this.win, opts);
+                       }
+                       if (to > 0) {
+                               this.win.setStyle('display','block');
+                               this.position();
+                       }
+                       this.fadeFx.clearChain();
+                       this.fadeFx.start(to).chain(function (){
+                               if (to == 0) {
+                                       this.win.setStyle('display', 'none');
+                                       this.fireEvent('onClose');
+                               } else {
+                                       this.fireEvent('onDisplay');
+                               }
+                       }.bind(this));
+                       return this;
+               }
+       });
+}
+StickyWin.Fx = StickyWin;
+
+
+// Begin: Source/Types/Array.Extras.js
+/*
+---
+
+script: Array.Extras.js
+
+name: Array.Extras
+
+description: Extends the Array native object to include useful methods to work with arrays.
+
+license: MIT-style license
+
+authors:
+  - Christoph Pojer
+  - Sebastian Markbåge
+
+requires:
+  - Core/Array
+  - MooTools.More
+
+provides: [Array.Extras]
+
+...
+*/
+
+(function(nil){
+
+Array.implement({
+
+       min: function(){
+               return Math.min.apply(null, this);
+       },
+
+       max: function(){
+               return Math.max.apply(null, this);
+       },
+
+       average: function(){
+               return this.length ? this.sum() / this.length : 0;
+       },
+
+       sum: function(){
+               var result = 0, l = this.length;
+               if (l){
+                       while (l--) result += this[l];
+               }
+               return result;
+       },
+
+       unique: function(){
+               return [].combine(this);
+       },
+
+       shuffle: function(){
+               for (var i = this.length; i && --i;){
+                       var temp = this[i], r = Math.floor(Math.random() * ( i + 1 ));
+                       this[i] = this[r];
+                       this[r] = temp;
+               }
+               return this;
+       },
+
+       reduce: function(fn, value){
+               for (var i = 0, l = this.length; i < l; i++){
+                       if (i in this) value = value === nil ? this[i] : fn.call(null, value, this[i], i, this);
+               }
+               return value;
+       },
+
+       reduceRight: function(fn, value){
+               var i = this.length;
+               while (i--){
+                       if (i in this) value = value === nil ? this[i] : fn.call(null, value, this[i], i, this);
+               }
+               return value;
+       },
+
+       pluck: function(prop){
+               return this.map(function(item){
+                       return item[prop];
+               });
+       }
+
+});
+
+})();
+
+
+// Begin: Source/Request/Request.HTML.js
+/*
+---
+
+name: Request.HTML
+
+description: Extends the basic Request Class with additional methods for interacting with HTML responses.
+
+license: MIT-style license.
+
+requires: [Element, Request]
+
+provides: Request.HTML
+
+...
+*/
+
+Request.HTML = new Class({
+
+       Extends: Request,
+
+       options: {
+               update: false,
+               append: false,
+               evalScripts: true,
+               filter: false,
+               headers: {
+                       Accept: 'text/html, application/xml, text/xml, */*'
+               }
+       },
+
+       success: function(text){
+               var options = this.options, response = this.response;
+
+               response.html = text.stripScripts(function(script){
+                       response.javascript = script;
+               });
+
+               var match = response.html.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
+               if (match) response.html = match[1];
+               var temp = new Element('div').set('html', response.html);
+
+               response.tree = temp.childNodes;
+               response.elements = temp.getElements(options.filter || '*');
+
+               if (options.filter) response.tree = response.elements;
+               if (options.update){
+                       var update = document.id(options.update).empty();
+                       if (options.filter) update.adopt(response.elements);
+                       else update.set('html', response.html);
+               } else if (options.append){
+                       var append = document.id(options.append);
+                       if (options.filter) response.elements.reverse().inject(append);
+                       else append.adopt(temp.getChildren());
+               }
+               if (options.evalScripts) Browser.exec(response.javascript);
+
+               this.onSuccess(response.tree, response.elements, response.html, response.javascript);
+       }
+
+});
+
+Element.Properties.load = {
+
+       set: function(options){
+               var load = this.get('load').cancel();
+               load.setOptions(options);
+               return this;
+       },
+
+       get: function(){
+               var load = this.retrieve('load');
+               if (!load){
+                       load = new Request.HTML({data: this, link: 'cancel', update: this, method: 'get'});
+                       this.store('load', load);
+               }
+               return load;
+       }
+
+};
+
+Element.implement({
+
+       load: function(){
+               this.get('load').send(Array.link(arguments, {data: Type.isObject, url: Type.isString}));
+               return this;
+       }
+
+});
+
+
+// Begin: Source/Layout/TabSwapper.js
+/*
+---
+
+name: TabSwapper
+
+description: Handles the scripting for a common UI layout; the tabbed box.
+
+license: MIT-Style License
+
+requires: [Core/Element.Event, Core/Fx.Tween, Core/Fx.Morph, Core/Element.Dimensions, More/Element.Shortcuts, More/Element.Measure]
+
+provides: TabSwapper
+
+...
+*/
+var TabSwapper = new Class({
+       Implements: [Options, Events],
+       options: {
+               // initPanel: null,
+               // smooth: false,
+               // smoothSize: false,
+               // maxSize: null,
+               // onActive: function(){},
+               // onActiveAfterFx: function(){},
+               // onBackground: function(){}
+               // cookieName: null,
+               preventDefault: true,
+               selectedClass: 'tabSelected',
+               mouseoverClass: 'tabOver',
+               deselectedClass: '',
+               rearrangeDOM: true,
+               effectOptions: {
+                       duration: 500
+               },
+               cookieDays: 999
+       },
+       tabs: [],
+       sections: [],
+       clickers: [],
+       sectionFx: [],
+       initialize: function(options){
+               this.setOptions(options);
+               var prev = this.setup();
+               if (prev) return prev;
+               if (this.options.initPanel != null) this.show(this.options.initPanel);
+               else if (this.options.cookieName && this.recall()) this.show(this.recall().toInt());
+               else this.show(0);
+
+       },
+       setup: function(){
+               var opt = this.options,
+                   sections = $$(opt.sections),
+                   tabs = $$(opt.tabs);
+               if (tabs[0] && tabs[0].retrieve('tabSwapper')) return tabs[0].retrieve('tabSwapper');
+               var clickers = $$(opt.clickers);
+               tabs.each(function(tab, index){
+                       this.addTab(tab, sections[index], clickers[index], index);
+               }, this);
+       },
+       addTab: function(tab, section, clicker, index){
+               tab = document.id(tab); clicker = document.id(clicker); section = document.id(section);
+               //if the tab is already in the interface, just move it
+               if (this.tabs.indexOf(tab) >= 0 && tab.retrieve('tabbered')
+                        && this.tabs.indexOf(tab) != index && this.options.rearrangeDOM) {
+                       this.moveTab(this.tabs.indexOf(tab), index);
+                       return this;
+               }
+               //if the index isn't specified, put the tab at the end
+               if (index == null) index = this.tabs.length;
+               //if this isn't the first item, and there's a tab
+               //already in the interface at the index 1 less than this
+               //insert this after that one
+               if (index > 0 && this.tabs[index-1] && this.options.rearrangeDOM) {
+                       tab.inject(this.tabs[index-1], 'after');
+                       section.inject(this.tabs[index-1].retrieve('section'), 'after');
+               }
+               this.tabs.splice(index, 0, tab);
+               clicker = clicker || tab;
+
+               tab.addEvents({
+                       mouseout: function(){
+                               tab.removeClass(this.options.mouseoverClass);
+                       }.bind(this),
+                       mouseover: function(){
+                               tab.addClass(this.options.mouseoverClass);
+                       }.bind(this)
+               });
+
+               clicker.addEvent('click', function(e){
+                       if (this.options.preventDefault) e.preventDefault();
+                       this.show(index);
+               }.bind(this));
+
+               tab.store('tabbered', true);
+               tab.store('section', section);
+               tab.store('clicker', clicker);
+               this.hideSection(index);
+               return this;
+       },
+       removeTab: function(index){
+               var now = this.tabs[this.now];
+               if (this.now == index){
+                       if (index > 0) this.show(index - 1);
+                       else if (index < this.tabs.length) this.show(index + 1);
+               }
+               this.now = this.tabs.indexOf(now);
+               return this;
+       },
+       moveTab: function(from, to){
+               var tab = this.tabs[from];
+               var clicker = tab.retrieve('clicker');
+               var section = tab.retrieve('section');
+
+               var toTab = this.tabs[to];
+               var toClicker = toTab.retrieve('clicker');
+               var toSection = toTab.retrieve('section');
+
+               this.tabs.erase(tab).splice(to, 0, tab);
+
+               tab.inject(toTab, 'before');
+               clicker.inject(toClicker, 'before');
+               section.inject(toSection, 'before');
+               return this;
+       },
+       show: function(i){
+               if (this.now == null) {
+                       this.tabs.each(function(tab, idx){
+                               if (i != idx)
+                                       this.hideSection(idx);
+                       }, this);
+               }
+               this.showSection(i).save(i);
+               return this;
+       },
+       save: function(index){
+               if (this.options.cookieName)
+                       Cookie.write(this.options.cookieName, index, {duration:this.options.cookieDays});
+               return this;
+       },
+       recall: function(){
+               return (this.options.cookieName) ? Cookie.read(this.options.cookieName) : false;
+       },
+       hideSection: function(idx) {
+               var tab = this.tabs[idx];
+               if (!tab) return this;
+               var sect = tab.retrieve('section');
+               if (!sect) return this;
+               if (sect.getStyle('display') != 'none') {
+                       this.lastHeight = sect.getSize().y;
+                       sect.setStyle('display', 'none');
+                       tab.swapClass(this.options.selectedClass, this.options.deselectedClass);
+                       this.fireEvent('onBackground', [idx, sect, tab]);
+               }
+               return this;
+       },
+       showSection: function(idx) {
+               var tab = this.tabs[idx];
+               if (!tab) return this;
+               var sect = tab.retrieve('section');
+               if (!sect) return this;
+               var smoothOk = this.options.smooth && !Browser.ie;
+               if (this.now != idx) {
+                       if (!tab.retrieve('tabFx'))
+                               tab.store('tabFx', new Fx.Morph(sect, this.options.effectOptions));
+                       var overflow = sect.getStyle('overflow');
+                       var start = {
+                               display:'block',
+                               overflow: 'hidden'
+                       };
+                       if (smoothOk) start.opacity = 0;
+                       var effect = false;
+                       if (smoothOk) {
+                               effect = {opacity: 1};
+                       } else if (sect.getStyle('opacity').toInt() < 1) {
+                               sect.setStyle('opacity', 1);
+                               if (!this.options.smoothSize) this.fireEvent('onActiveAfterFx', [idx, sect, tab]);
+                       }
+                       if (this.options.smoothSize) {
+                               var size = sect.getDimensions().height;
+                               if (this.options.maxSize != null && this.options.maxSize < size)
+                                       size = this.options.maxSize;
+                               if (!effect) effect = {};
+                               effect.height = size;
+                       }
+                       if (this.now != null) this.hideSection(this.now);
+                       if (this.options.smoothSize && this.lastHeight) start.height = this.lastHeight;
+                       sect.setStyles(start);
+                       var finish = function(){
+                               this.fireEvent('onActiveAfterFx', [idx, sect, tab]);
+                               sect.setStyles({
+                                       height: this.options.maxSize == effect.height ? this.options.maxSize : "auto",
+                                       overflow: overflow
+                               });
+                               sect.getElements('input, textarea').setStyle('opacity', 1);
+                       }.bind(this);
+                       if (effect) {
+                               tab.retrieve('tabFx').start(effect).chain(finish);
+                       } else {
+                               finish();
+                       }
+                       this.now = idx;
+                       this.fireEvent('onActive', [idx, sect, tab]);
+               }
+               tab.swapClass(this.options.deselectedClass, this.options.selectedClass);
+               return this;
+       }
+});
+
+
+// Begin: Source/Element/Element.Forms.js
+/*
+---
+
+script: Element.Forms.js
+
+name: Element.Forms
+
+description: Extends the Element native object to include methods useful in managing inputs.
+
+license: MIT-style license
+
+authors:
+  - Aaron Newton
+
+requires:
+  - Core/Element
+  - /String.Extras
+  - /MooTools.More
+
+provides: [Element.Forms]
+
+...
+*/
+
+Element.implement({
+
+       tidy: function(){
+               this.set('value', this.get('value').tidy());
+       },
+
+       getTextInRange: function(start, end){
+               return this.get('value').substring(start, end);
+       },
+
+       getSelectedText: function(){
+               if (this.setSelectionRange) return this.getTextInRange(this.getSelectionStart(), this.getSelectionEnd());
+               return document.selection.createRange().text;
+       },
+
+       getSelectedRange: function(){
+               if (this.selectionStart != null){
+                       return {
+                               start: this.selectionStart,
+                               end: this.selectionEnd
+                       };
+               }
+
+               var pos = {
+                       start: 0,
+                       end: 0
+               };
+               var range = this.getDocument().selection.createRange();
+               if (!range || range.parentElement() != this) return pos;
+               var duplicate = range.duplicate();
+
+               if (this.type == 'text'){
+                       pos.start = 0 - duplicate.moveStart('character', -100000);
+                       pos.end = pos.start + range.text.length;
+               } else {
+                       var value = this.get('value');
+                       var offset = value.length;
+                       duplicate.moveToElementText(this);
+                       duplicate.setEndPoint('StartToEnd', range);
+                       if (duplicate.text.length) offset -= value.match(/[\n\r]*$/)[0].length;
+                       pos.end = offset - duplicate.text.length;
+                       duplicate.setEndPoint('StartToStart', range);
+                       pos.start = offset - duplicate.text.length;
+               }
+               return pos;
+       },
+
+       getSelectionStart: function(){
+               return this.getSelectedRange().start;
+       },
+
+       getSelectionEnd: function(){
+               return this.getSelectedRange().end;
+       },
+
+       setCaretPosition: function(pos){
+               if (pos == 'end') pos = this.get('value').length;
+               this.selectRange(pos, pos);
+               return this;
+       },
+
+       getCaretPosition: function(){
+               return this.getSelectedRange().start;
+       },
+
+       selectRange: function(start, end){
+               if (this.setSelectionRange){
+                       this.focus();
+                       this.setSelectionRange(start, end);
+               } else {
+                       var value = this.get('value');
+                       var diff = value.substr(start, end - start).replace(/\r/g, '').length;
+                       start = value.substr(0, start).replace(/\r/g, '').length;
+                       var range = this.createTextRange();
+                       range.collapse(true);
+                       range.moveEnd('character', start + diff);
+                       range.moveStart('character', start);
+                       range.select();
+               }
+               return this;
+       },
+
+       insertAtCursor: function(value, select){
+               var pos = this.getSelectedRange();
+               var text = this.get('value');
+               this.set('value', text.substring(0, pos.start) + value + text.substring(pos.end, text.length));
+               if (select !== false) this.selectRange(pos.start, pos.start + value.length);
+               else this.setCaretPosition(pos.start + value.length);
+               return this;
+       },
+
+       insertAroundCursor: function(options, select){
+               options = Object.append({
+                       before: '',
+                       defaultMiddle: '',
+                       after: ''
+               }, options);
+
+               var value = this.getSelectedText() || options.defaultMiddle;
+               var pos = this.getSelectedRange();
+               var text = this.get('value');
+
+               if (pos.start == pos.end){
+                       this.set('value', text.substring(0, pos.start) + options.before + value + options.after + text.substring(pos.end, text.length));
+                       this.selectRange(pos.start + options.before.length, pos.end + options.before.length + value.length);
+               } else {
+                       var current = text.substring(pos.start, pos.end);
+                       this.set('value', text.substring(0, pos.start) + options.before + current + options.after + text.substring(pos.end, text.length));
+                       var selStart = pos.start + options.before.length;
+                       if (select !== false) this.selectRange(selStart, selStart + current.length);
+                       else this.setCaretPosition(selStart + text.length);
+               }
+               return this;
+       }
+
+});
+
+
+// Begin: Source/Fx/Fx.Reveal.js
+/*
+---
+
+script: Fx.Reveal.js
+
+name: Fx.Reveal
+
+description: Defines Fx.Reveal, a class that shows and hides elements with a transition.
+
+license: MIT-style license
+
+authors:
+  - Aaron Newton
+
+requires:
+  - Core/Fx.Morph
+  - /Element.Shortcuts
+  - /Element.Measure
+
+provides: [Fx.Reveal]
+
+...
+*/
+
+(function(){
+
+
+var hideTheseOf = function(object){
+       var hideThese = object.options.hideInputs;
+       if (window.OverText){
+               var otClasses = [null];
+               OverText.each(function(ot){
+                       otClasses.include('.' + ot.options.labelClass);
+               });
+               if (otClasses) hideThese += otClasses.join(', ');
+       }
+       return (hideThese) ? object.element.getElements(hideThese) : null;
+};
+
+
+Fx.Reveal = new Class({
+
+       Extends: Fx.Morph,
+
+       options: {/*
+               onShow: function(thisElement){},
+               onHide: function(thisElement){},
+               onComplete: function(thisElement){},
+               heightOverride: null,
+               widthOverride: null,*/
+               link: 'cancel',
+               styles: ['padding', 'border', 'margin'],
+               transitionOpacity: !Browser.ie6,
+               mode: 'vertical',
+               display: function(){
+                       return this.element.get('tag') != 'tr' ? 'block' : 'table-row';
+               },
+               opacity: 1,
+               hideInputs: Browser.ie ? 'select, input, textarea, object, embed' : null
+       },
+
+       dissolve: function(){
+               if (!this.hiding && !this.showing){
+                       if (this.element.getStyle('display') != 'none'){
+                               this.hiding = true;
+                               this.showing = false;
+                               this.hidden = true;
+                               this.cssText = this.element.style.cssText;
+
+                               var startStyles = this.element.getComputedSize({
+                                       styles: this.options.styles,
+                                       mode: this.options.mode
+                               });
+                               if (this.options.transitionOpacity) startStyles.opacity = this.options.opacity;
+
+                               var zero = {};
+                               Object.each(startStyles, function(style, name){
+                                       zero[name] = [style, 0];
+                               });
+
+                               this.element.setStyles({
+                                       display: Function.from(this.options.display).call(this),
+                                       overflow: 'hidden'
+                               });
+
+                               var hideThese = hideTheseOf(this);
+                               if (hideThese) hideThese.setStyle('visibility', 'hidden');
+
+                               this.$chain.unshift(function(){
+                                       if (this.hidden){
+                                               this.hiding = false;
+                                               this.element.style.cssText = this.cssText;
+                                               this.element.setStyle('display', 'none');
+                                               if (hideThese) hideThese.setStyle('visibility', 'visible');
+                                       }
+                                       this.fireEvent('hide', this.element);
+                                       this.callChain();
+                               }.bind(this));
+
+                               this.start(zero);
+                       } else {
+                               this.callChain.delay(10, this);
+                               this.fireEvent('complete', this.element);
+                               this.fireEvent('hide', this.element);
+                       }
+               } else if (this.options.link == 'chain'){
+                       this.chain(this.dissolve.bind(this));
+               } else if (this.options.link == 'cancel' && !this.hiding){
+                       this.cancel();
+                       this.dissolve();
+               }
+               return this;
+       },
+
+       reveal: function(){
+               if (!this.showing && !this.hiding){
+                       if (this.element.getStyle('display') == 'none'){
+                               this.hiding = false;
+                               this.showing = true;
+                               this.hidden = false;
+                               this.cssText = this.element.style.cssText;
+
+                               var startStyles;
+                               this.element.measure(function(){
+                                       startStyles = this.element.getComputedSize({
+                                               styles: this.options.styles,
+                                               mode: this.options.mode
+                                       });
+                               }.bind(this));
+                               if (this.options.heightOverride != null) startStyles.height = this.options.heightOverride.toInt();
+                               if (this.options.widthOverride != null) startStyles.width = this.options.widthOverride.toInt();
+                               if (this.options.transitionOpacity){
+                                       this.element.setStyle('opacity', 0);
+                                       startStyles.opacity = this.options.opacity;
+                               }
+
+                               var zero = {
+                                       height: 0,
+                                       display: Function.from(this.options.display).call(this)
+                               };
+                               Object.each(startStyles, function(style, name){
+                                       zero[name] = 0;
+                               });
+                               zero.overflow = 'hidden';
+
+                               this.element.setStyles(zero);
+
+                               var hideThese = hideTheseOf(this);
+                               if (hideThese) hideThese.setStyle('visibility', 'hidden');
+
+                               this.$chain.unshift(function(){
+                                       this.element.style.cssText = this.cssText;
+                                       this.element.setStyle('display', Function.from(this.options.display).call(this));
+                                       if (!this.hidden) this.showing = false;
+                                       if (hideThese) hideThese.setStyle('visibility', 'visible');
+                                       this.callChain();
+                                       this.fireEvent('show', this.element);
+                               }.bind(this));
+
+                               this.start(startStyles);
+                       } else {
+                               this.callChain();
+                               this.fireEvent('complete', this.element);
+                               this.fireEvent('show', this.element);
+                       }
+               } else if (this.options.link == 'chain'){
+                       this.chain(this.reveal.bind(this));
+               } else if (this.options.link == 'cancel' && !this.showing){
+                       this.cancel();
+                       this.reveal();
+               }
+               return this;
+       },
+
+       toggle: function(){
+               if (this.element.getStyle('display') == 'none'){
+                       this.reveal();
+               } else {
+                       this.dissolve();
+               }
+               return this;
+       },
+
+       cancel: function(){
+               this.parent.apply(this, arguments);
+               if (this.cssText != null) this.element.style.cssText = this.cssText;
+               this.hiding = false;
+               this.showing = false;
+               return this;
+       }
+
+});
+
+Element.Properties.reveal = {
+
+       set: function(options){
+               this.get('reveal').cancel().setOptions(options);
+               return this;
+       },
+
+       get: function(){
+               var reveal = this.retrieve('reveal');
+               if (!reveal){
+                       reveal = new Fx.Reveal(this);
+                       this.store('reveal', reveal);
+               }
+               return reveal;
+       }
+
+};
+
+Element.Properties.dissolve = Element.Properties.reveal;
+
+Element.implement({
+
+       reveal: function(options){
+               this.get('reveal').setOptions(options).reveal();
+               return this;
+       },
+
+       dissolve: function(options){
+               this.get('reveal').setOptions(options).dissolve();
+               return this;
+       },
+
+       nix: function(options){
+               var params = Array.link(arguments, {destroy: Type.isBoolean, options: Type.isObject});
+               this.get('reveal').setOptions(options).dissolve().chain(function(){
+                       this[params.destroy ? 'destroy' : 'dispose']();
+               }.bind(this));
+               return this;
+       },
+
+       wink: function(){
+               var params = Array.link(arguments, {duration: Type.isNumber, options: Type.isObject});
+               var reveal = this.get('reveal').setOptions(params.options);
+               reveal.reveal().chain(function(){
+                       (function(){
+                               reveal.dissolve();
+                       }).delay(params.duration || 2000);
+               });
+       }
+
+});
+
+})();
+
+
+// Begin: Source/Layout/Collapsible.js
+/*
+---
+name: Collapsible
+
+description: Enables a dom element to, when clicked, hide or show (it toggles) another dom element. Kind of an Accordion for one item.
+
+license: MIT-Style License
+
+requires: [Core/Element.Event, More/Fx.Reveal]
+
+provides: Collapsible
+...
+*/
+var Collapsible = new Class({
+       Extends: Fx.Reveal,
+       initialize: function(clicker, section, options) {
+               this.clicker = document.id(clicker);
+               this.section = document.id(section);
+               this.parent(this.section, options);
+               this.boundtoggle = this.toggle.bind(this);
+               this.attach();
+       },
+       attach: function(){
+               this.clicker.addEvent('click', this.boundtoggle);
+       },
+       detach: function(){
+               this.clicker.removeEvent('click', this.boundtoggle);
+       }
+});
+//legacy, this class originated w/ a typo. nice!
+var Collapsable = Collapsible;
+
+// Begin: Source/Utilities/Table.js
+/*
+---
+name: Table
+description: LUA-Style table implementation.
+license: MIT-style license
+authors:
+  - Valerio Proietti
+requires: [Core/Array]
+provides: [Table]
+...
+*/
+
+(function(){
+
+var Table = this.Table = function(){
+
+       this.length = 0;
+       var keys = [],
+           values = [];
+       
+       this.set = function(key, value){
+               var index = keys.indexOf(key);
+               if (index == -1){
+                       var length = keys.length;
+                       keys[length] = key;
+                       values[length] = value;
+                       this.length++;
+               } else {
+                       values[index] = value;
+               }
+               return this;
+       };
+
+       this.get = function(key){
+               var index = keys.indexOf(key);
+               return (index == -1) ? null : values[index];
+       };
+
+       this.erase = function(key){
+               var index = keys.indexOf(key);
+               if (index != -1){
+                       this.length--;
+                       keys.splice(index, 1);
+                       return values.splice(index, 1)[0];
+               }
+               return null;
+       };
+
+       this.each = this.forEach = function(fn, bind){
+               for (var i = 0, l = this.length; i < l; i++) fn.call(bind, keys[i], values[i], this);
+       };
+       
+};
+
+if (this.Type) new Type('Table', Table);
+
+})();
+
+
+// Begin: Source/Element.Data.js
+/*
+---
+name: Element.Data
+description: Stores data in HTML5 data properties
+provides: [Element.Data]
+requires: [Core/Element, Core/JSON]
+script: Element.Data.js
+
+...
+*/
+(function(){
+
+       JSON.isSecure = function(string){
+               //this verifies that the string is parsable JSON and not malicious (borrowed from JSON.js in MooTools, which in turn borrowed it from Crockford)
+               //this version is a little more permissive, as it allows single quoted attributes because forcing the use of double quotes
+               //is a pain when this stuff is used as HTML properties
+               return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(string.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '').replace(/'[^'\\\n\r]*'/g, ''));
+       };
+
+       Element.implement({
+               /*
+                       sets an HTML5 data property.
+                       arguments:
+                               name - (string) the data name to store; will be automatically prefixed with 'data-'.
+                               value - (string, number) the value to store.
+               */
+               setData: function(name, value){
+                       return this.set('data-' + name.hyphenate(), value);
+               },
+
+               getData: function(name, defaultValue){
+                       var value = this.get('data-' + name.hyphenate());
+                       if (value != undefined){
+                               return value;
+                       } else if (defaultValue != undefined){
+                               this.setData(name, defaultValue);
+                               return defaultValue;
+                       }
+               },
+
+               /* 
+                       arguments:
+                               name - (string) the data name to store; will be automatically prefixed with 'data-'
+                               value - (string, array, or object) if an object or array the object will be JSON encoded; otherwise stored as provided.
+               */
+               setJSONData: function(name, value){
+                       return this.setData(name, JSON.encode(value));
+               },
+
+               /*
+                       retrieves a property from HTML5 data property you specify
+               
+                       arguments:
+                               name - (retrieve) the data name to store; will be automatically prefixed with 'data-'
+                               strict - (boolean) if true, will set the JSON.decode's secure flag to true; otherwise the value is still tested but allows single quoted attributes.
+                               defaultValue - (string, array, or object) the value to set if no value is found (see storeData above)
+               */
+               getJSONData: function(name, strict, defaultValue){
+                       var value = this.get('data-' + name);
+                       if (value != undefined){
+                               if (value && JSON.isSecure(value)) {
+                                       return JSON.decode(value, strict);
+                               } else {
+                                       return value;
+                               }
+                       } else if (defaultValue != undefined){
+                               this.setJSONData(name, defaultValue);
+                               return defaultValue;
+                       }
+               }
+
+       });
+
+})();
+
+// Begin: Source/BehaviorAPI.js
+/*
+---
+name: BehaviorAPI
+description: HTML getters for Behavior's API model.
+requires: [Core/Class, /Element.Data]
+provides: [BehaviorAPI]
+...
+*/
+
+
+(function(){
+       //see Docs/BehaviorAPI.md for documentation of public methods.
+
+       var reggy = /[^a-z0-9\-]/gi;
+
+       window.BehaviorAPI = new Class({
+               element: null,
+               prefix: '',
+               defaults: {},
+
+               initialize: function(element, prefix){
+                       this.element = element;
+                       this.prefix = prefix.toLowerCase().replace('.', '-', 'g').replace(reggy, '');
+               },
+
+               /******************
+                * PUBLIC METHODS
+                ******************/
+
+               get: function(/* name[, name, name, etc] */){
+                       if (arguments.length > 1) return this._getObj(Array.from(arguments));
+                       return this._getValue(arguments[0]);
+               },
+
+               getAs: function(/*returnType, name, defaultValue OR {name: returnType, name: returnType, etc}*/){
+                       if (typeOf(arguments[0]) == 'object') return this._getValuesAs.apply(this, arguments);
+                       return this._getValueAs.apply(this, arguments);
+               },
+
+               require: function(/* name[, name, name, etc] */){
+                       for (var i = 0; i < arguments.length; i++){
+                               if (this._getValue(arguments[i]) == undefined) throw new Error('Could not retrieve ' + this.prefix + '-' + arguments[i] + ' option from element.');
+                       }
+                       return this;
+               },
+
+               requireAs: function(returnType, name /* OR {name: returnType, name: returnType, etc}*/){
+                       var val;
+                       if (typeOf(arguments[0]) == 'object'){
+                               for (var objName in arguments[0]){
+                                       val = this._getValueAs(arguments[0][objName], objName);
+                                       if (val === undefined || val === null) throw new Error("Could not retrieve " + this.prefix + '-' + objName + " option from element.");
+                               }
+                       } else {
+                               val = this._getValueAs(returnType, name);
+                               if (val === undefined || val === null) throw new Error("Could not retrieve " + this.prefix + '-' + name + " option from element.");
+                       }
+                       return this;
+               },
+
+               setDefault: function(name, value /* OR {name: value, name: value, etc }*/){
+                       if (typeOf(arguments[0]) == 'object'){
+                               for (var objName in arguments[0]){
+                                       this.setDefault(objName, arguments[0][objName]);
+                               }
+                               return;
+                       }
+                       name = name.camelCase();
+                       this.defaults[name] = value;
+                       if (this._getValue(name) == null){
+                               var options = this._getOptions();
+                               options[name] = value;
+                       }
+                       return this;
+               },
+
+               refreshAPI: function(){
+                       delete this.options;
+                       this.setDefault(this.defaults);
+                       return;
+               },
+
+               /******************
+                * PRIVATE METHODS
+                ******************/
+
+               //given an array of names, returns an object of key/value pairs for each name
+               _getObj: function(names){
+                       var obj = {};
+                       names.each(function(name){
+                               var value = this._getValue(name);
+                               if (value !== undefined) obj[name] = value;
+                       }, this);
+                       return obj;
+               },
+               //gets the data-behaviorname-options object and parses it as JSON
+               _getOptions: function(){
+                       try {
+                               if (!this.options){
+                                       var options = this.element.getData(this.prefix + '-options', '{}');
+                                       if (options && options.substring(0,1) != '{') options = '{' + options + '}';
+                                       var isSecure = JSON.isSecure(options);
+                                       if (!isSecure) throw new Error('warning, options value for element is not parsable, check your JSON format for quotes, etc.');
+                                       this.options = isSecure ? JSON.decode(options) : {};
+                                       for (option in this.options) {
+                                               this.options[option.camelCase()] = this.options[option];
+                                       }
+                               }
+                       } catch (e){
+                               throw new Error('Could not get options from element; check your syntax. ' + this.prefix + '-options: "' + this.element.getData(this.prefix + '-options', '{}') + '"');
+                       }
+                       return this.options;
+               },
+               //given a name (string) returns the value for it
+               _getValue: function(name){
+                       name = name.camelCase();
+                       var options = this._getOptions();
+                       if (!options.hasOwnProperty(name)){
+                               var inline = this.element.getData(this.prefix + '-' + name.hyphenate());
+                               if (inline) options[name] = inline;
+                       }
+                       return options[name];
+               },
+               //given a Type and a name (string) returns the value for it coerced to that type if possible
+               //else returns the defaultValue or null
+               _getValueAs: function(returnType, name, defaultValue){
+                       var value = this._getValue(name);
+                       if (value == null || value == undefined) return defaultValue;
+                       var coerced = this._coerceFromString(returnType, value);
+                       if (coerced == null) throw new Error("Could not retrieve value '" + name + "' as the specified type. Its value is: " + value);
+                       return coerced;
+               },
+               //given an object of name/Type pairs, returns those as an object of name/value (as specified Type) pairs
+               _getValuesAs: function(obj){
+                       var returnObj = {};
+                       for (var name in obj){
+                               returnObj[name] = this._getValueAs(obj[name], name);
+                       }
+                       return returnObj;
+               },
+               //attempts to run a value through the JSON parser. If the result is not of that type returns null.
+               _coerceFromString: function(toType, value){
+                       if (typeOf(value) == 'string' && toType != String){
+                               if (JSON.isSecure(value)) value = JSON.decode(value);
+                       }
+                       if (instanceOf(value, toType)) return value;
+                       return null;
+               }
+       });
+
+})();
+
+// Begin: Source/Behavior.js
+/*
+---
+name: Behavior
+description: Auto-instantiates widgets/classes based on parsed, declarative HTML.
+requires: [Core/Class.Extras, Core/Element.Event, Core/Selectors, More/Table, /Element.Data, /BehaviorAPI]
+provides: [Behavior]
+...
+*/
+
+(function(){
+
+       var getLog = function(method){
+               return function(){
+                       if (window.console && console[method]){
+                               if(console[method].apply) console[method].apply(console, arguments);
+                               else console[method](Array.from(arguments).join(' '));
+                       }
+               };
+       };
+
+       var PassMethods = new Class({
+               //pass a method pointer through to a filter
+               //by default the methods for add/remove events are passed to the filter
+               //pointed to this instance of behavior. you could use this to pass along
+               //other methods to your filters. For example, a method to close a popup
+               //for filters presented inside popups.
+               passMethod: function(method, fn){
+                       if (this.API.prototype[method]) throw new Error('Cannot overwrite API method ' + method + ' as it already exists');
+                       this.API.implement(method, fn);
+                       return this;
+               },
+
+               passMethods: function(methods){
+                       for (method in methods) this.passMethod(method, methods[method]);
+                       return this;
+               }
+
+       });
+
+       var spaceOrCommaRegex = /\s*,\s*|\s+/g;
+
+       BehaviorAPI.implement({
+               deprecate: function(deprecated, asJSON){
+                       var set,
+                           values = {};
+                       Object.each(deprecated, function(prop, key){
+                               var value = this.element[ asJSON ? 'getJSONData' : 'getData'](prop);
+                               if (value !== undefined){
+                                       set = true;
+                                       values[key] = value;
+                               }
+                       }, this);
+                       this.setDefault(values);
+                       return this;
+               }
+       });
+
+       this.Behavior = new Class({
+
+               Implements: [Options, Events, PassMethods],
+
+               options: {
+                       //by default, errors thrown by filters are caught; the onError event is fired.
+                       //set this to *true* to NOT catch these errors to allow them to be handled by the browser.
+                       // breakOnErrors: false,
+                       // container: document.body,
+
+                       //default error behavior when a filter cannot be applied
+                       onError: getLog('error'),
+                       onWarn: getLog('warn'),
+                       enableDeprecation: true,
+                       selector: '[data-behavior]'
+               },
+
+               initialize: function(options){
+                       this.setOptions(options);
+                       this.API = new Class({ Extends: BehaviorAPI });
+                       this.passMethods({
+                               getDelegator: this.getDelegator.bind(this),
+                               addEvent: this.addEvent.bind(this),
+                               removeEvent: this.removeEvent.bind(this),
+                               addEvents: this.addEvents.bind(this),
+                               removeEvents: this.removeEvents.bind(this),
+                               fireEvent: this.fireEvent.bind(this),
+                               applyFilters: this.apply.bind(this),
+                               applyFilter: this.applyFilter.bind(this),
+                               getContentElement: this.getContentElement.bind(this),
+                               cleanup: this.cleanup.bind(this),
+                               getContainerSize: function(){
+                                       return this.getContentElement().measure(function(){
+                                               return this.getSize();
+                                       });
+                               }.bind(this),
+                               error: function(){ this.fireEvent('error', arguments); }.bind(this),
+                               fail: function(){
+                                       var msg = Array.join(arguments, ' ');
+                                       throw new Error(msg);
+                               },
+                               warn: function(){
+                                       this.fireEvent('warn', arguments);
+                               }.bind(this)
+                       });
+               },
+
+               getDelegator: function(){
+                       return this.delegator;
+               },
+
+               setDelegator: function(delegator){
+                       if (!instanceOf(delegator, Delegator)) throw new Error('Behavior.setDelegator only accepts instances of Delegator.');
+                       this.delegator = delegator;
+                       return this;
+               },
+
+               getContentElement: function(){
+                       return this.options.container || document.body;
+               },
+
+               //Applies all the behavior filters for an element.
+               //container - (element) an element to apply the filters registered with this Behavior instance to.
+               //force - (boolean; optional) passed through to applyFilter (see it for docs)
+               apply: function(container, force){
+                 this._getElements(container).each(function(element){
+                               var plugins = [];
+                               element.getBehaviors().each(function(name){
+                                       var filter = this.getFilter(name);
+                                       if (!filter){
+                                               this.fireEvent('error', ['There is no filter registered with this name: ', name, element]);
+                                       } else {
+                                               var config = filter.config;
+                                               if (config.delay !== undefined){
+                                                       this.applyFilter.delay(filter.config.delay, this, [element, filter, force]);
+                                               } else if(config.delayUntil){
+                                                       this._delayFilterUntil(element, filter, force);
+                                               } else if(config.initializer){
+                                                       this._customInit(element, filter, force);
+                                               } else {
+                                                       plugins.append(this.applyFilter(element, filter, force, true));
+                                               }
+                                       }
+                               }, this);
+                               plugins.each(function(plugin){ plugin(); });
+                       }, this);
+                       return this;
+               },
+
+               _getElements: function(container){
+                       if (typeOf(this.options.selector) == 'function') return this.options.selector(container);
+                       else return document.id(container).getElements(this.options.selector);
+               },
+
+               //delays a filter until the event specified in filter.config.delayUntil is fired on the element
+               _delayFilterUntil: function(element, filter, force){
+                       var events = filter.config.delayUntil.split(','),
+                           attached = {},
+                           inited = false;
+                       var clear = function(){
+                               events.each(function(event){
+                                       element.removeEvent(event, attached[event]);
+                               });
+                               clear = function(){};
+                       };
+                       events.each(function(event){
+                               var init = function(e){
+                                       clear();
+                                       if (inited) return;
+                                       inited = true;
+                                       var setup = filter.setup;
+                                       filter.setup = function(element, api, _pluginResult){
+                                               api.event = e;
+                                               return setup.apply(filter, [element, api, _pluginResult]);
+                                       };
+                                       this.applyFilter(element, filter, force);
+                                       filter.setup = setup;
+                               }.bind(this);
+                               element.addEvent(event, init);
+                               attached[event] = init;
+                       }, this);
+               },
+
+               //runs custom initiliazer defined in filter.config.initializer
+               _customInit: function(element, filter, force){
+                       var api = new this.API(element, filter.name);
+                       api.runSetup = this.applyFilter.pass([element, filter, force], this);
+                       filter.config.initializer(element, api);
+               },
+
+               //Applies a specific behavior to a specific element.
+               //element - the element to which to apply the behavior
+               //filter - (object) a specific behavior filter, typically one registered with this instance or registered globally.
+               //force - (boolean; optional) apply the behavior to each element it matches, even if it was previously applied. Defaults to *false*.
+               //_returnPlugins - (boolean; optional; internal) if true, plugins are not rendered but instead returned as an array of functions
+               //_pluginTargetResult - (obj; optional internal) if this filter is a plugin for another, this is whatever that target filter returned
+               //                      (an instance of a class for example)
+               applyFilter: function(element, filter, force, _returnPlugins, _pluginTargetResult){
+                       var pluginsToReturn = [];
+                       if (this.options.breakOnErrors){
+                               pluginsToReturn = this._applyFilter.apply(this, arguments);
+                       } else {
+                               try {
+                                       pluginsToReturn = this._applyFilter.apply(this, arguments);
+                               } catch (e){
+                                       this.fireEvent('error', ['Could not apply the behavior ' + filter.name, e]);
+                               }
+                       }
+                       return _returnPlugins ? pluginsToReturn : this;
+               },
+
+               //see argument list above for applyFilter
+               _applyFilter: function(element, filter, force, _returnPlugins, _pluginTargetResult){
+                       var pluginsToReturn = [];
+                       element = document.id(element);
+                       //get the filters already applied to this element
+                       var applied = getApplied(element);
+                       //if this filter is not yet applied to the element, or we are forcing the filter
+                       if (!applied[filter.name] || force){
+                               //if it was previously applied, garbage collect it
+                               if (applied[filter.name]) applied[filter.name].cleanup(element);
+                               var api = new this.API(element, filter.name);
+
+                               //deprecated
+                               api.markForCleanup = filter.markForCleanup.bind(filter);
+                               api.onCleanup = function(fn){
+                                       filter.markForCleanup(element, fn);
+                               };
+
+                               if (filter.config.deprecated && this.options.enableDeprecation) api.deprecate(filter.config.deprecated);
+                               if (filter.config.deprecateAsJSON && this.options.enableDeprecation) api.deprecate(filter.config.deprecatedAsJSON, true);
+
+                               //deal with requirements and defaults
+                               if (filter.config.requireAs){
+                                       api.requireAs(filter.config.requireAs);
+                               } else if (filter.config.require){
+                                       api.require.apply(api, Array.from(filter.config.require));
+                               }
+
+                               if (filter.config.defaults) api.setDefault(filter.config.defaults);
+
+                               //apply the filter
+                               var result = filter.setup(element, api, _pluginTargetResult);
+                               if (filter.config.returns && !instanceOf(result, filter.config.returns)){
+                                       throw new Error("Filter " + filter.name + " did not return a valid instance.");
+                               }
+                               element.store('Behavior Filter result:' + filter.name, result);
+                               //and mark it as having been previously applied
+                               applied[filter.name] = filter;
+                               //apply all the plugins for this filter
+                               var plugins = this.getPlugins(filter.name);
+                               if (plugins){
+                                       for (var name in plugins){
+                                               if (_returnPlugins){
+                                                       pluginsToReturn.push(this.applyFilter.pass([element, plugins[name], force, null, result], this));
+                                               } else {
+                                                       this.applyFilter(element, plugins[name], force, null, result);
+                                               }
+                                       }
+                               }
+                       }
+                       return pluginsToReturn;
+               },
+
+               //given a name, returns a registered behavior
+               getFilter: function(name){
+                       return this._registered[name] || Behavior.getFilter(name);
+               },
+
+               getPlugins: function(name){
+                       return this._plugins[name] || Behavior._plugins[name];
+               },
+
+               //Garbage collects all applied filters for an element and its children.
+               //element - (*element*) container to cleanup
+               //ignoreChildren - (*boolean*; optional) if *true* only the element will be cleaned, otherwise the element and all the
+               //        children with filters applied will be cleaned. Defaults to *false*.
+               cleanup: function(element, ignoreChildren){
+                       element = document.id(element);
+                       var applied = getApplied(element);
+                       for (var filter in applied){
+                               applied[filter].cleanup(element);
+                               element.eliminate('Behavior Filter result:' + filter);
+                               delete applied[filter];
+                       }
+                       if (!ignoreChildren) this._getElements(element).each(this.cleanup, this);
+                       return this;
+               }
+
+       });
+
+       //Export these for use elsewhere (notabily: Delegator).
+       Behavior.getLog = getLog;
+       Behavior.PassMethods = PassMethods;
+
+
+       //Returns the applied behaviors for an element.
+       var getApplied = function(el){
+               return el.retrieve('_appliedBehaviors', {});
+       };
+
+       //Registers a behavior filter.
+       //name - the name of the filter
+       //fn - a function that applies the filter to the given element
+       //overwrite - (boolean) if true, will overwrite existing filter if one exists; defaults to false.
+       var addFilter = function(name, fn, overwrite){
+               if (!this._registered[name] || overwrite) this._registered[name] = new Behavior.Filter(name, fn);
+               else throw new Error('Could not add the Behavior filter "' + name  +'" as a previous trigger by that same name exists.');
+       };
+
+       var addFilters = function(obj, overwrite){
+               for (var name in obj){
+                       addFilter.apply(this, [name, obj[name], overwrite]);
+               }
+       };
+
+       //Registers a behavior plugin
+       //filterName - (*string*) the filter (or plugin) this is a plugin for
+       //name - (*string*) the name of this plugin
+       //setup - a function that applies the filter to the given element
+       var addPlugin = function(filterName, name, setup, overwrite){
+               if (!this._plugins[filterName]) this._plugins[filterName] = {};
+               if (!this._plugins[filterName][name] || overwrite) this._plugins[filterName][name] = new Behavior.Filter(name, setup);
+               else throw new Error('Could not add the Behavior filter plugin "' + name  +'" as a previous trigger by that same name exists.');
+       };
+
+       var addPlugins = function(obj, overwrite){
+               for (var name in obj){
+                       addPlugin.apply(this, [obj[name].fitlerName, obj[name].name, obj[name].setup], overwrite);
+               }
+       };
+
+       var setFilterDefaults = function(name, defaults){
+               var filter = this.getFilter(name);
+               if (!filter.config.defaults) filter.config.defaults = {};
+               Object.append(filter.config.defaults, defaults);
+       };
+
+       //Add methods to the Behavior namespace for global registration.
+       Object.append(Behavior, {
+               _registered: {},
+               _plugins: {},
+               addGlobalFilter: addFilter,
+               addGlobalFilters: addFilters,
+               addGlobalPlugin: addPlugin,
+               addGlobalPlugins: addPlugins,
+               setFilterDefaults: setFilterDefaults,
+               getFilter: function(name){
+                       return this._registered[name];
+               }
+       });
+       //Add methods to the Behavior class for instance registration.
+       Behavior.implement({
+               _registered: {},
+               _plugins: {},
+               addFilter: addFilter,
+               addFilters: addFilters,
+               addPlugin: addPlugin,
+               addPlugins: addPlugins,
+               setFilterDefaults: setFilterDefaults
+       });
+
+       //This class is an actual filter that, given an element, alters it with specific behaviors.
+       Behavior.Filter = new Class({
+
+               config: {
+                       /**
+                               returns: Foo,
+                               require: ['req1', 'req2'],
+                               //or
+                               requireAs: {
+                                       req1: Boolean,
+                                       req2: Number,
+                                       req3: String
+                               },
+                               defaults: {
+                                       opt1: false,
+                                       opt2: 2
+                               },
+                               //simple example:
+                               setup: function(element, API){
+                                       var kids = element.getElements(API.get('selector'));
+                                       //some validation still has to occur here
+                                       if (!kids.length) API.fail('there were no child elements found that match ', API.get('selector'));
+                                       if (kids.length < 2) API.warn("there weren't more than 2 kids that match", API.get('selector'));
+                                       var fooInstance = new Foo(kids, API.get('opt1', 'opt2'));
+                                       API.onCleanup(function(){
+                                               fooInstance.destroy();
+                                       });
+                                       return fooInstance;
+                               },
+                               delayUntil: 'mouseover',
+                               //OR
+                               delay: 100,
+                               //OR
+                               initializer: function(element, API){
+                                       element.addEvent('mouseover', API.runSetup); //same as specifying event
+                                       //or
+                                       API.runSetup.delay(100); //same as specifying delay
+                                       //or something completely esoteric
+                                       var timer = (function(){
+                                               if (element.hasClass('foo')){
+                                                       clearInterval(timer);
+                                                       API.runSetup();
+                                               }
+                                       }).periodical(100);
+                                       //or
+                                       API.addEvent('someBehaviorEvent', API.runSetup);
+                               });
+                               */
+               },
+
+               //Pass in an object with the following properties:
+               //name - the name of this filter
+               //setup - a function that applies the filter to the given element
+               initialize: function(name, setup){
+                       this.name = name;
+                       if (typeOf(setup) == "function"){
+                               this.setup = setup;
+                       } else {
+                               Object.append(this.config, setup);
+                               this.setup = this.config.setup;
+                       }
+                       this._cleanupFunctions = new Table();
+               },
+
+               //Stores a garbage collection pointer for a specific element.
+               //Example: if your filter enhances all the inputs in the container
+               //you might have a function that removes that enhancement for garbage collection.
+               //You would mark each input matched with its own cleanup function.
+               //NOTE: this MUST be the element passed to the filter - the element with this filters
+               //      name in its data-behavior property. I.E.:
+               //<form data-behavior="FormValidator">
+               //  <input type="text" name="email"/>
+               //</form>
+               //If this filter is FormValidator, you can mark the form for cleanup, but not, for example
+               //the input. Only elements that match this filter can be marked.
+               markForCleanup: function(element, fn){
+                       var functions = this._cleanupFunctions.get(element);
+                       if (!functions) functions = [];
+                       functions.include(fn);
+                       this._cleanupFunctions.set(element, functions);
+                       return this;
+               },
+
+               //Garbage collect a specific element.
+               //NOTE: this should be an element that has a data-behavior property that matches this filter.
+               cleanup: function(element){
+                       var marks = this._cleanupFunctions.get(element);
+                       if (marks){
+                               marks.each(function(fn){ fn(); });
+                               this._cleanupFunctions.erase(element);
+                       }
+                       return this;
+               }
+
+       });
+
+       Behavior.elementDataProperty = 'behavior';
+
+       Element.implement({
+
+               addBehaviorFilter: function(name){
+                       return this.setData(Behavior.elementDataProperty, this.getBehaviors().include(name).join(' '));
+               },
+
+               removeBehaviorFilter: function(name){
+                       return this.setData(Behavior.elementDataProperty, this.getBehaviors().erase(name).join(' '));
+               },
+
+               getBehaviors: function(){
+                       var filters = this.getData(Behavior.elementDataProperty);
+                       if (!filters) return [];
+                       return filters.trim().split(spaceOrCommaRegex);
+               },
+
+               hasBehavior: function(name){
+                       return this.getBehaviors().contains(name);
+               },
+
+               getBehaviorResult: function(name){
+                       return this.retrieve('Behavior Filter result:' + name);
+               }
+
+       });
+
+
+})();
+
+
+// Begin: Source/Drag/Drag.js
+/*
+---
+
+script: Drag.js
+
+name: Drag
+
+description: The base Drag Class. Can be used to drag and resize Elements using mouse events.
+
+license: MIT-style license
+
+authors:
+  - Valerio Proietti
+  - Tom Occhinno
+  - Jan Kassens
+
+requires:
+  - Core/Events
+  - Core/Options
+  - Core/Element.Event
+  - Core/Element.Style
+  - Core/Element.Dimensions
+  - /MooTools.More
+
+provides: [Drag]
+...
+
+*/
+
+var Drag = new Class({
+
+       Implements: [Events, Options],
+
+       options: {/*
+               onBeforeStart: function(thisElement){},
+               onStart: function(thisElement, event){},
+               onSnap: function(thisElement){},
+               onDrag: function(thisElement, event){},
+               onCancel: function(thisElement){},
+               onComplete: function(thisElement, event){},*/
+               snap: 6,
+               unit: 'px',
+               grid: false,
+               style: true,
+               limit: false,
+               handle: false,
+               invert: false,
+               preventDefault: false,
+               stopPropagation: false,
+               modifiers: {x: 'left', y: 'top'}
+       },
+
+       initialize: function(){
+               var params = Array.link(arguments, {
+                       'options': Type.isObject,
+                       'element': function(obj){
+                               return obj != null;
+                       }
+               });
+
+               this.element = document.id(params.element);
+               this.document = this.element.getDocument();
+               this.setOptions(params.options || {});
+               var htype = typeOf(this.options.handle);
+               this.handles = ((htype == 'array' || htype == 'collection') ? $$(this.options.handle) : document.id(this.options.handle)) || this.element;
+               this.mouse = {'now': {}, 'pos': {}};
+               this.value = {'start': {}, 'now': {}};
+
+               this.selection = (Browser.ie) ? 'selectstart' : 'mousedown';
+
+
+               if (Browser.ie && !Drag.ondragstartFixed){
+                       document.ondragstart = Function.from(false);
+                       Drag.ondragstartFixed = true;
+               }
+
+               this.bound = {
+                       start: this.start.bind(this),
+                       check: this.check.bind(this),
+                       drag: this.drag.bind(this),
+                       stop: this.stop.bind(this),
+                       cancel: this.cancel.bind(this),
+                       eventStop: Function.from(false)
+               };
+               this.attach();
+       },
+
+       attach: function(){
+               this.handles.addEvent('mousedown', this.bound.start);
+               return this;
+       },
+
+       detach: function(){
+               this.handles.removeEvent('mousedown', this.bound.start);
+               return this;
+       },
+
+       start: function(event){
+               var options = this.options;
+
+               if (event.rightClick) return;
+
+               if (options.preventDefault) event.preventDefault();
+               if (options.stopPropagation) event.stopPropagation();
+               this.mouse.start = event.page;
+
+               this.fireEvent('beforeStart', this.element);
+
+               var limit = options.limit;
+               this.limit = {x: [], y: []};
+
+               var z, coordinates;
+               for (z in options.modifiers){
+                       if (!options.modifiers[z]) continue;
+
+                       var style = this.element.getStyle(options.modifiers[z]);
+
+                       // Some browsers (IE and Opera) don't always return pixels.
+                       if (style && !style.match(/px$/)){
+                               if (!coordinates) coordinates = this.element.getCoordinates(this.element.getOffsetParent());
+                               style = coordinates[options.modifiers[z]];
+                       }
+
+                       if (options.style) this.value.now[z] = (style || 0).toInt();
+                       else this.value.now[z] = this.element[options.modifiers[z]];
+
+                       if (options.invert) this.value.now[z] *= -1;
+
+                       this.mouse.pos[z] = event.page[z] - this.value.now[z];
+
+                       if (limit && limit[z]){
+                               var i = 2;
+                               while (i--){
+                                       var limitZI = limit[z][i];
+                                       if (limitZI || limitZI === 0) this.limit[z][i] = (typeof limitZI == 'function') ? limitZI() : limitZI;
+                               }
+                       }
+               }
+
+               if (typeOf(this.options.grid) == 'number') this.options.grid = {
+                       x: this.options.grid,
+                       y: this.options.grid
+               };
+
+               var events = {
+                       mousemove: this.bound.check,
+                       mouseup: this.bound.cancel
+               };
+               events[this.selection] = this.bound.eventStop;
+               this.document.addEvents(events);
+       },
+
+       check: function(event){
+               if (this.options.preventDefault) event.preventDefault();
+               var distance = Math.round(Math.sqrt(Math.pow(event.page.x - this.mouse.start.x, 2) + Math.pow(event.page.y - this.mouse.start.y, 2)));
+               if (distance > this.options.snap){
+                       this.cancel();
+                       this.document.addEvents({
+                               mousemove: this.bound.drag,
+                               mouseup: this.bound.stop
+                       });
+                       this.fireEvent('start', [this.element, event]).fireEvent('snap', this.element);
+               }
+       },
+
+       drag: function(event){
+               var options = this.options;
+
+               if (options.preventDefault) event.preventDefault();
+               this.mouse.now = event.page;
+
+               for (var z in options.modifiers){
+                       if (!options.modifiers[z]) continue;
+                       this.value.now[z] = this.mouse.now[z] - this.mouse.pos[z];
+
+                       if (options.invert) this.value.now[z] *= -1;
+
+                       if (options.limit && this.limit[z]){
+                               if ((this.limit[z][1] || this.limit[z][1] === 0) && (this.value.now[z] > this.limit[z][1])){
+                                       this.value.now[z] = this.limit[z][1];
+                               } else if ((this.limit[z][0] || this.limit[z][0] === 0) && (this.value.now[z] < this.limit[z][0])){
+                                       this.value.now[z] = this.limit[z][0];
+                               }
+                       }
+
+                       if (options.grid[z]) this.value.now[z] -= ((this.value.now[z] - (this.limit[z][0]||0)) % options.grid[z]);
+
+                       if (options.style) this.element.setStyle(options.modifiers[z], this.value.now[z] + options.unit);
+                       else this.element[options.modifiers[z]] = this.value.now[z];
+               }
+
+               this.fireEvent('drag', [this.element, event]);
+       },
+
+       cancel: function(event){
+               this.document.removeEvents({
+                       mousemove: this.bound.check,
+                       mouseup: this.bound.cancel
+               });
+               if (event){
+                       this.document.removeEvent(this.selection, this.bound.eventStop);
+                       this.fireEvent('cancel', this.element);
+               }
+       },
+
+       stop: function(event){
+               var events = {
+                       mousemove: this.bound.drag,
+                       mouseup: this.bound.stop
+               };
+               events[this.selection] = this.bound.eventStop;
+               this.document.removeEvents(events);
+               if (event) this.fireEvent('complete', [this.element, event]);
+       }
+
+});
+
+Element.implement({
+
+       makeResizable: function(options){
+               var drag = new Drag(this, Object.merge({
+                       modifiers: {
+                               x: 'width',
+                               y: 'height'
+                       }
+               }, options));
+
+               this.store('resizer', drag);
+               return drag.addEvent('drag', function(){
+                       this.fireEvent('resize', drag);
+               }.bind(this));
+       }
+
+});
+
+
+// Begin: Source/Drag/Drag.Move.js
+/*
+---
+
+script: Drag.Move.js
+
+name: Drag.Move
+
+description: A Drag extension that provides support for the constraining of draggables to containers and droppables.
+
+license: MIT-style license
+
+authors:
+  - Valerio Proietti
+  - Tom Occhinno
+  - Jan Kassens
+  - Aaron Newton
+  - Scott Kyle
+
+requires:
+  - Core/Element.Dimensions
+  - /Drag
+
+provides: [Drag.Move]
+
+...
+*/
+
+Drag.Move = new Class({
+
+       Extends: Drag,
+
+       options: {/*
+               onEnter: function(thisElement, overed){},
+               onLeave: function(thisElement, overed){},
+               onDrop: function(thisElement, overed, event){},*/
+               droppables: [],
+               container: false,
+               precalculate: false,
+               includeMargins: true,
+               checkDroppables: true
+       },
+
+       initialize: function(element, options){
+               this.parent(element, options);
+               element = this.element;
+
+               this.droppables = $$(this.options.droppables);
+               this.container = document.id(this.options.container);
+
+               if (this.container && typeOf(this.container) != 'element')
+                       this.container = document.id(this.container.getDocument().body);
+
+               if (this.options.style){
+                       if (this.options.modifiers.x == 'left' && this.options.modifiers.y == 'top'){
+                               var parent = element.getOffsetParent(),
+                                       styles = element.getStyles('left', 'top');
+                               if (parent && (styles.left == 'auto' || styles.top == 'auto')){
+                                       element.setPosition(element.getPosition(parent));
+                               }
+                       }
+
+                       if (element.getStyle('position') == 'static') element.setStyle('position', 'absolute');
+               }
+
+               this.addEvent('start', this.checkDroppables, true);
+               this.overed = null;
+       },
+
+       start: function(event){
+               if (this.container) this.options.limit = this.calculateLimit();
+
+               if (this.options.precalculate){
+                       this.positions = this.droppables.map(function(el){
+                               return el.getCoordinates();
+                       });
+               }
+
+               this.parent(event);
+       },
+
+       calculateLimit: function(){
+               var element = this.element,
+                       container = this.container,
+
+                       offsetParent = document.id(element.getOffsetParent()) || document.body,
+                       containerCoordinates = container.getCoordinates(offsetParent),
+                       elementMargin = {},
+                       elementBorder = {},
+                       containerMargin = {},
+                       containerBorder = {},
+                       offsetParentPadding = {};
+
+               ['top', 'right', 'bottom', 'left'].each(function(pad){
+                       elementMargin[pad] = element.getStyle('margin-' + pad).toInt();
+                       elementBorder[pad] = element.getStyle('border-' + pad).toInt();
+                       containerMargin[pad] = container.getStyle('margin-' + pad).toInt();
+                       containerBorder[pad] = container.getStyle('border-' + pad).toInt();
+                       offsetParentPadding[pad] = offsetParent.getStyle('padding-' + pad).toInt();
+               }, this);
+
+               var width = element.offsetWidth + elementMargin.left + elementMargin.right,
+                       height = element.offsetHeight + elementMargin.top + elementMargin.bottom,
+                       left = 0,
+                       top = 0,
+                       right = containerCoordinates.right - containerBorder.right - width,
+                       bottom = containerCoordinates.bottom - containerBorder.bottom - height;
+
+               if (this.options.includeMargins){
+                       left += elementMargin.left;
+                       top += elementMargin.top;
+               } else {
+                       right += elementMargin.right;
+                       bottom += elementMargin.bottom;
+               }
+
+               if (element.getStyle('position') == 'relative'){
+                       var coords = element.getCoordinates(offsetParent);
+                       coords.left -= element.getStyle('left').toInt();
+                       coords.top -= element.getStyle('top').toInt();
+
+                       left -= coords.left;
+                       top -= coords.top;
+                       if (container.getStyle('position') != 'relative'){
+                               left += containerBorder.left;
+                               top += containerBorder.top;
+                       }
+                       right += elementMargin.left - coords.left;
+                       bottom += elementMargin.top - coords.top;
+
+                       if (container != offsetParent){
+                               left += containerMargin.left + offsetParentPadding.left;
+                               top += ((Browser.ie6 || Browser.ie7) ? 0 : containerMargin.top) + offsetParentPadding.top;
+                       }
+               } else {
+                       left -= elementMargin.left;
+                       top -= elementMargin.top;
+                       if (container != offsetParent){
+                               left += containerCoordinates.left + containerBorder.left;
+                               top += containerCoordinates.top + containerBorder.top;
+                       }
+               }
+
+               return {
+                       x: [left, right],
+                       y: [top, bottom]
+               };
+       },
+
+       getDroppableCoordinates: function(element){
+               var position = element.getCoordinates();
+               if (element.getStyle('position') == 'fixed'){
+                       var scroll = window.getScroll();
+                       position.left += scroll.x;
+                       position.right += scroll.x;
+                       position.top += scroll.y;
+                       position.bottom += scroll.y;
+               }
+               return position;
+       },
+
+       checkDroppables: function(){
+               var overed = this.droppables.filter(function(el, i){
+                       el = this.positions ? this.positions[i] : this.getDroppableCoordinates(el);
+                       var now = this.mouse.now;
+                       return (now.x > el.left && now.x < el.right && now.y < el.bottom && now.y > el.top);
+               }, this).getLast();
+
+               if (this.overed != overed){
+                       if (this.overed) this.fireEvent('leave', [this.element, this.overed]);
+                       if (overed) this.fireEvent('enter', [this.element, overed]);
+                       this.overed = overed;
+               }
+       },
+
+       drag: function(event){
+               this.parent(event);
+               if (this.options.checkDroppables && this.droppables.length) this.checkDroppables();
+       },
+
+       stop: function(event){
+               this.checkDroppables();
+               this.fireEvent('drop', [this.element, this.overed, event]);
+               this.overed = null;
+               return this.parent(event);
+       }
+
+});
+
+Element.implement({
+
+       makeDraggable: function(options){
+               var drag = new Drag.Move(this, options);
+               this.store('dragger', drag);
+               return drag;
+       }
+
+});
+
+
+// Begin: Source/UI/StickyWin.Drag.js
+/*
+---
+
+name: StickyWin.Drag
+
+description: Implements drag and resize functionaity into StickyWin.Fx. See StickyWin.Fx for the options.
+
+license: MIT-Style License
+
+requires: [More/Class.Refactor, More/Drag.Move, StickyWin]
+
+provides: StickyWin.Drag
+
+...
+*/
+StickyWin = Class.refactor(StickyWin, {
+       options: {
+               draggable: false,
+               dragOptions: {
+                       onComplete: function(){}
+               },
+               dragHandleSelector: '.dragHandle',
+               resizable: false,
+               resizeOptions: {
+                       onComplete: function(){}
+               },
+               resizeHandleSelector: ''
+       },
+       setContent: function(){
+               this.previous.apply(this, arguments);
+               if (this.options.draggable) this.makeDraggable();
+               if (this.options.resizable) this.makeResizable();
+               return this;
+       },
+       makeDraggable: function(){
+               var toggled = this.toggleVisible(true);
+               if (this.options.useIframeShim) {
+                       this.makeIframeShim();
+                       var onComplete = (this.options.dragOptions.onComplete);
+                       this.options.dragOptions.onComplete = function(){
+                               onComplete();
+                               this.shim.position();
+                       }.bind(this);
+               }
+               if (this.options.dragHandleSelector) {
+                       var handle = this.win.getElement(this.options.dragHandleSelector);
+                       if (handle) {
+                               handle.setStyle('cursor','move');
+                               this.options.dragOptions.handle = handle;
+                       }
+               }
+               this.win.makeDraggable(this.options.dragOptions);
+               if (toggled) this.toggleVisible(false);
+       },
+       makeResizable: function(){
+               var toggled = this.toggleVisible(true);
+               if (this.options.useIframeShim) {
+                       this.makeIframeShim();
+                       var onComplete = (this.options.resizeOptions.onComplete);
+                       this.options.resizeOptions.onComplete = function(){
+                               onComplete();
+                               this.shim.position();
+                       }.bind(this);
+               }
+               if (this.options.resizeHandleSelector) {
+                       var handle = this.win.getElement(this.options.resizeHandleSelector);
+                       if (handle) this.options.resizeOptions.handle = this.win.getElement(this.options.resizeHandleSelector);
+               }
+               this.win.makeResizable(this.options.resizeOptions);
+               if (toggled) this.toggleVisible(false);
+       },
+       toggleVisible: function(show){
+               if (!this.visible && show == null || show) {
+                       this.win.setStyles({
+                               display: 'block',
+                               opacity: 0
+                       });
+                       return true;
+               } else if (show != null && !show){
+                       this.win.setStyles({
+                               display: 'none',
+                               opacity: 1
+                       });
+                       return false;
+               }
+               return false;
+       }
+});
+StickyWin.Fx = StickyWin;
+
+// Begin: Source/Behaviors/Behavior.StickyWin.js
+/*
+---
+name: Behavior.StickyWin
+description: Behaviors for StickyWin instances.
+provides: [Behavior.StickyWin]
+requires: [Behavior/Behavior, /StickyWin, /StickyWin.Modal, /StickyWin.Fx, /StickyWin.Drag, More/Array.Extras, More/Object.Extras]
+script: Behavior.Tabs.js
+
+...
+*/
+
+Behavior.addGlobalFilters({
+
+       'StickyWin.Modal': {
+               defaults: {
+                       destroyOnClose: true,
+                       closeOnClickOut: true,
+                       closeOnEsc: true,
+                       draggable: false,
+                       resizable: false
+               },
+               returns: StickyWin.Modal,
+               setup: function(element, api) {
+                       var flex = element.getElement('.flex'),
+                           height = api.getAs(Number, 'height') || (window.getSize().y * .9);
+
+                       if (flex){
+                               element.measure(function(){
+                                       var tmp = new Element('span', { styles: { display: 'none' }}).replaces(flex),
+                                           remainder = element.getSize().y;
+                                       var padding = ['padding-top', 'padding-bottom', 'margin-top', 'margin-bottom', 'border-top-width', 'border-bottom-width'].map(function(style){
+                                               return flex.getStyle(style).toInt();
+                                       }).sum();
+                                       flex.setStyle('max-height', height - remainder - padding);
+                                       flex.replaces(tmp);
+                               });
+                       }
+
+                       var options = Object.merge({
+                                       content: element
+                               },
+                               Object.cleanValues(
+                                       api.getAs({
+                                               closeClassName: String,
+                                               pinClassName: String,
+                                               className: String,
+                                               edge: String,
+                                               position: String,
+                                               offset: Object,
+                                               relativeTo: String,
+                                               width: Number,
+                                               height: Number,
+                                               timeout: Number,
+                                               destroyOnClose: Boolean,
+                                               closeOnClickOut: Boolean,
+                                               closeOnEsc: Boolean,
+                                               //modal options
+                                               maskOptions: Object,
+                                               //draggable options
+                                               draggable: Boolean,
+                                               dragHandleSelector: String,
+                                               resizable: Boolean,
+                                               resizeHandleSelector: String
+                                       })
+                               )
+                       );
+
+                       if (options.mask) options.closeOnClickOut = false;
+
+                       var sw = new StickyWin.Modal(options);
+                       api.onCleanup(function(){
+                               if (!sw.destroyed) sw.destroy();
+                       });
+                       sw.addEvent('destroy', function(){
+                               api.cleanup(element);
+                       });
+                       return sw;
+               }
+       }
+
+});
+
+
+// Begin: Source/Utilities/Color.js
+/*
+---
+
+script: Color.js
+
+name: Color
+
+description: Class for creating and manipulating colors in JavaScript. Supports HSB -> RGB Conversions and vice versa.
+
+license: MIT-style license
+
+authors:
+  - Valerio Proietti
+
+requires:
+  - Core/Array
+  - Core/String
+  - Core/Number
+  - Core/Hash
+  - Core/Function
+  - MooTools.More
+
+provides: [Color]
+
+...
+*/
+
+(function(){
+
+var Color = this.Color = new Type('Color', function(color, type){
+       if (arguments.length >= 3){
+               type = 'rgb'; color = Array.slice(arguments, 0, 3);
+       } else if (typeof color == 'string'){
+               if (color.match(/rgb/)) color = color.rgbToHex().hexToRgb(true);
+               else if (color.match(/hsb/)) color = color.hsbToRgb();
+               else color = color.hexToRgb(true);
+       }
+       type = type || 'rgb';
+       switch (type){
+               case 'hsb':
+                       var old = color;
+                       color = color.hsbToRgb();
+                       color.hsb = old;
+               break;
+               case 'hex': color = color.hexToRgb(true); break;
+       }
+       color.rgb = color.slice(0, 3);
+       color.hsb = color.hsb || color.rgbToHsb();
+       color.hex = color.rgbToHex();
+       return Object.append(color, this);
+});
+
+Color.implement({
+
+       mix: function(){
+               var colors = Array.slice(arguments);
+               var alpha = (typeOf(colors.getLast()) == 'number') ? colors.pop() : 50;
+               var rgb = this.slice();
+               colors.each(function(color){
+                       color = new Color(color);
+                       for (var i = 0; i < 3; i++) rgb[i] = Math.round((rgb[i] / 100 * (100 - alpha)) + (color[i] / 100 * alpha));
+               });
+               return new Color(rgb, 'rgb');
+       },
+
+       invert: function(){
+               return new Color(this.map(function(value){
+                       return 255 - value;
+               }));
+       },
+
+       setHue: function(value){
+               return new Color([value, this.hsb[1], this.hsb[2]], 'hsb');
+       },
+
+       setSaturation: function(percent){
+               return new Color([this.hsb[0], percent, this.hsb[2]], 'hsb');
+       },
+
+       setBrightness: function(percent){
+               return new Color([this.hsb[0], this.hsb[1], percent], 'hsb');
+       }
+
+});
+
+this.$RGB = function(r, g, b){
+       return new Color([r, g, b], 'rgb');
+};
+
+this.$HSB = function(h, s, b){
+       return new Color([h, s, b], 'hsb');
+};
+
+this.$HEX = function(hex){
+       return new Color(hex, 'hex');
+};
+
+Array.implement({
+
+       rgbToHsb: function(){
+               var red = this[0],
+                               green = this[1],
+                               blue = this[2],
+                               hue = 0;
+               var max = Math.max(red, green, blue),
+                               min = Math.min(red, green, blue);
+               var delta = max - min;
+               var brightness = max / 255,
+                               saturation = (max != 0) ? delta / max : 0;
+               if (saturation != 0){
+                       var rr = (max - red) / delta;
+                       var gr = (max - green) / delta;
+                       var br = (max - blue) / delta;
+                       if (red == max) hue = br - gr;
+                       else if (green == max) hue = 2 + rr - br;
+                       else hue = 4 + gr - rr;
+                       hue /= 6;
+                       if (hue < 0) hue++;
+               }
+               return [Math.round(hue * 360), Math.round(saturation * 100), Math.round(brightness * 100)];
+       },
+
+       hsbToRgb: function(){
+               var br = Math.round(this[2] / 100 * 255);
+               if (this[1] == 0){
+                       return [br, br, br];
+               } else {
+                       var hue = this[0] % 360;
+                       var f = hue % 60;
+                       var p = Math.round((this[2] * (100 - this[1])) / 10000 * 255);
+                       var q = Math.round((this[2] * (6000 - this[1] * f)) / 600000 * 255);
+                       var t = Math.round((this[2] * (6000 - this[1] * (60 - f))) / 600000 * 255);
+                       switch (Math.floor(hue / 60)){
+                               case 0: return [br, t, p];
+                               case 1: return [q, br, p];
+                               case 2: return [p, br, t];
+                               case 3: return [p, q, br];
+                               case 4: return [t, p, br];
+                               case 5: return [br, p, q];
+                       }
+               }
+               return false;
+       }
+
+});
+
+String.implement({
+
+       rgbToHsb: function(){
+               var rgb = this.match(/\d{1,3}/g);
+               return (rgb) ? rgb.rgbToHsb() : null;
+       },
+
+       hsbToRgb: function(){
+               var hsb = this.match(/\d{1,3}/g);
+               return (hsb) ? hsb.hsbToRgb() : null;
+       }
+
+});
+
+})();
+
+
+
+// Begin: Source/Class/Events.Pseudos.js
+/*
+---
+
+name: Events.Pseudos
+
+description: Adds the functionality to add pseudo events
+
+license: MIT-style license
+
+authors:
+  - Arian Stolwijk
+
+requires: [Core/Class.Extras, Core/Slick.Parser, More/MooTools.More]
+
+provides: [Events.Pseudos]
+
+...
+*/
+
+(function(){
+
+Events.Pseudos = function(pseudos, addEvent, removeEvent){
+
+       var storeKey = '_monitorEvents:';
+
+       var storageOf = function(object){
+               return {
+                       store: object.store ? function(key, value){
+                               object.store(storeKey + key, value);
+                       } : function(key, value){
+                               (object._monitorEvents || (object._monitorEvents = {}))[key] = value;
+                       },
+                       retrieve: object.retrieve ? function(key, dflt){
+                               return object.retrieve(storeKey + key, dflt);
+                       } : function(key, dflt){
+                               if (!object._monitorEvents) return dflt;
+                               return object._monitorEvents[key] || dflt;
+                       }
+               };
+       };
+
+       var splitType = function(type){
+               if (type.indexOf(':') == -1 || !pseudos) return null;
+
+               var parsed = Slick.parse(type).expressions[0][0],
+                       parsedPseudos = parsed.pseudos,
+                       l = parsedPseudos.length,
+                       splits = [];
+
+               while (l--){
+                       var pseudo = parsedPseudos[l].key,
+                               listener = pseudos[pseudo];
+                       if (listener != null) splits.push({
+                               event: parsed.tag,
+                               value: parsedPseudos[l].value,
+                               pseudo: pseudo,
+                               original: type,
+                               listener: listener
+                       });
+               }
+               return splits.length ? splits : null;
+       };
+
+       return {
+
+               addEvent: function(type, fn, internal){
+                       var split = splitType(type);
+                       if (!split) return addEvent.call(this, type, fn, internal);
+
+                       var storage = storageOf(this),
+                               events = storage.retrieve(type, []),
+                               eventType = split[0].event,
+                               args = Array.slice(arguments, 2),
+                               stack = fn,
+                               self = this;
+
+                       split.each(function(item){
+                               var listener = item.listener,
+                                       stackFn = stack;
+                               if (listener == false) eventType += ':' + item.pseudo + '(' + item.value + ')';
+                               else stack = function(){
+                                       listener.call(self, item, stackFn, arguments, stack);
+                               };
+                       });
+
+                       events.include({type: eventType, event: fn, monitor: stack});
+                       storage.store(type, events);
+
+                       if (type != eventType) addEvent.apply(this, [type, fn].concat(args));
+                       return addEvent.apply(this, [eventType, stack].concat(args));
+               },
+
+               removeEvent: function(type, fn){
+                       var split = splitType(type);
+                       if (!split) return removeEvent.call(this, type, fn);
+
+                       var storage = storageOf(this),
+                               events = storage.retrieve(type);
+                       if (!events) return this;
+
+                       var args = Array.slice(arguments, 2);
+
+                       removeEvent.apply(this, [type, fn].concat(args));
+                       events.each(function(monitor, i){
+                               if (!fn || monitor.event == fn) removeEvent.apply(this, [monitor.type, monitor.monitor].concat(args));
+                               delete events[i];
+                       }, this);
+
+                       storage.store(type, events);
+                       return this;
+               }
+
+       };
+
+};
+
+var pseudos = {
+
+       once: function(split, fn, args, monitor){
+               fn.apply(this, args);
+               this.removeEvent(split.event, monitor)
+                       .removeEvent(split.original, fn);
+       },
+
+       throttle: function(split, fn, args){
+               if (!fn._throttled){
+                       fn.apply(this, args);
+                       fn._throttled = setTimeout(function(){
+                               fn._throttled = false;
+                       }, split.value || 250);
+               }
+       },
+
+       pause: function(split, fn, args){
+               clearTimeout(fn._pause);
+               fn._pause = fn.delay(split.value || 250, this, args);
+       }
+
+};
+
+Events.definePseudo = function(key, listener){
+       pseudos[key] = listener;
+       return this;
+};
+
+Events.lookupPseudo = function(key){
+       return pseudos[key];
+};
+
+var proto = Events.prototype;
+Events.implement(Events.Pseudos(pseudos, proto.addEvent, proto.removeEvent));
+
+['Request', 'Fx'].each(function(klass){
+       if (this[klass]) this[klass].implement(Events.prototype);
+});
+
+})();
+
+
+// Begin: Source/Element/Element.Event.Pseudos.js
+/*
+---
+
+name: Element.Event.Pseudos
+
+description: Adds the functionality to add pseudo events for Elements
+
+license: MIT-style license
+
+authors:
+  - Arian Stolwijk
+
+requires: [Core/Element.Event, Core/Element.Delegation, Events.Pseudos]
+
+provides: [Element.Event.Pseudos, Element.Delegation]
+
+...
+*/
+
+(function(){
+
+var pseudos = {relay: false},
+       copyFromEvents = ['once', 'throttle', 'pause'],
+       count = copyFromEvents.length;
+
+while (count--) pseudos[copyFromEvents[count]] = Events.lookupPseudo(copyFromEvents[count]);
+
+DOMEvent.definePseudo = function(key, listener){
+       pseudos[key] = listener;
+       return this;
+};
+
+var proto = Element.prototype;
+[Element, Window, Document].invoke('implement', Events.Pseudos(pseudos, proto.addEvent, proto.removeEvent));
+
+})();
+
+
+// Begin: Source/Element/Element.Event.Pseudos.Keys.js
+/*
+---
+
+name: Element.Event.Pseudos.Keys
+
+description: Adds functionality fire events if certain keycombinations are pressed
+
+license: MIT-style license
+
+authors:
+  - Arian Stolwijk
+
+requires: [Element.Event.Pseudos]
+
+provides: [Element.Event.Pseudos.Keys]
+
+...
+*/
+
+(function(){
+
+var keysStoreKey = '$moo:keys-pressed',
+       keysKeyupStoreKey = '$moo:keys-keyup';
+
+
+DOMEvent.definePseudo('keys', function(split, fn, args){
+
+       var event = args[0],
+               keys = [],
+               pressed = this.retrieve(keysStoreKey, []);
+
+       keys.append(split.value.replace('++', function(){
+               keys.push('+'); // shift++ and shift+++a
+               return '';
+       }).split('+'));
+
+       pressed.include(event.key);
+
+       if (keys.every(function(key){
+               return pressed.contains(key);
+       })) fn.apply(this, args);
+
+       this.store(keysStoreKey, pressed);
+
+       if (!this.retrieve(keysKeyupStoreKey)){
+               var keyup = function(event){
+                       (function(){
+                               pressed = this.retrieve(keysStoreKey, []).erase(event.key);
+                               this.store(keysStoreKey, pressed);
+                       }).delay(0, this); // Fix for IE
+               };
+               this.store(keysKeyupStoreKey, keyup).addEvent('keyup', keyup);
+       }
+
+});
+
+DOMEvent.defineKeys({
+       '16': 'shift',
+       '17': 'control',
+       '18': 'alt',
+       '20': 'capslock',
+       '33': 'pageup',
+       '34': 'pagedown',
+       '35': 'end',
+       '36': 'home',
+       '144': 'numlock',
+       '145': 'scrolllock',
+       '186': ';',
+       '187': '=',
+       '188': ',',
+       '190': '.',
+       '191': '/',
+       '192': '`',
+       '219': '[',
+       '220': '\\',
+       '221': ']',
+       '222': "'",
+       '107': '+'
+}).defineKey(Browser.firefox ? 109 : 189, '-');
+
+})();
+
+
+// Begin: Source/Interface/Keyboard.js
+/*
+---
+
+script: Keyboard.js
+
+name: Keyboard
+
+description: KeyboardEvents used to intercept events on a class for keyboard and format modifiers in a specific order so as to make alt+shift+c the same as shift+alt+c.
+
+license: MIT-style license
+
+authors:
+  - Perrin Westrich
+  - Aaron Newton
+  - Scott Kyle
+
+requires:
+  - Core/Events
+  - Core/Options
+  - Core/Element.Event
+  - Element.Event.Pseudos.Keys
+
+provides: [Keyboard]
+
+...
+*/
+
+(function(){
+
+       var Keyboard = this.Keyboard = new Class({
+
+               Extends: Events,
+
+               Implements: [Options],
+
+               options: {/*
+                       onActivate: function(){},
+                       onDeactivate: function(){},*/
+                       defaultEventType: 'keydown',
+                       active: false,
+                       manager: null,
+                       events: {},
+                       nonParsedEvents: ['activate', 'deactivate', 'onactivate', 'ondeactivate', 'changed', 'onchanged']
+               },
+
+               initialize: function(options){
+                       if (options && options.manager){
+                               this._manager = options.manager;
+                               delete options.manager;
+                       }
+                       this.setOptions(options);
+                       this._setup();
+               },
+
+               addEvent: function(type, fn, internal){
+                       return this.parent(Keyboard.parse(type, this.options.defaultEventType, this.options.nonParsedEvents), fn, internal);
+               },
+
+               removeEvent: function(type, fn){
+                       return this.parent(Keyboard.parse(type, this.options.defaultEventType, this.options.nonParsedEvents), fn);
+               },
+
+               toggleActive: function(){
+                       return this[this.isActive() ? 'deactivate' : 'activate']();
+               },
+
+               activate: function(instance){
+                       if (instance){
+                               if (instance.isActive()) return this;
+                               //if we're stealing focus, store the last keyboard to have it so the relinquish command works
+                               if (this._activeKB && instance != this._activeKB){
+                                       this.previous = this._activeKB;
+                                       this.previous.fireEvent('deactivate');
+                               }
+                               //if we're enabling a child, assign it so that events are now passed to it
+                               this._activeKB = instance.fireEvent('activate');
+                               Keyboard.manager.fireEvent('changed');
+                       } else if (this._manager){
+                               //else we're enabling ourselves, we must ask our parent to do it for us
+                               this._manager.activate(this);
+                       }
+                       return this;
+               },
+
+               isActive: function(){
+                       return this._manager ? (this._manager._activeKB == this) : (Keyboard.manager == this);
+               },
+
+               deactivate: function(instance){
+                       if (instance){
+                               if (instance === this._activeKB){
+                                       this._activeKB = null;
+                                       instance.fireEvent('deactivate');
+                                       Keyboard.manager.fireEvent('changed');
+                               }
+                       } else if (this._manager){
+                               this._manager.deactivate(this);
+                       }
+                       return this;
+               },
+
+               relinquish: function(){
+                       if (this.isActive() && this._manager && this._manager.previous) this._manager.activate(this._manager.previous);
+                       else this.deactivate();
+                       return this;
+               },
+
+               //management logic
+               manage: function(instance){
+                       if (instance._manager) instance._manager.drop(instance);
+                       this._instances.push(instance);
+                       instance._manager = this;
+                       if (!this._activeKB) this.activate(instance);
+                       return this;
+               },
+
+               drop: function(instance){
+                       instance.relinquish();
+                       this._instances.erase(instance);
+                       if (this._activeKB == instance){
+                               if (this.previous && this._instances.contains(this.previous)) this.activate(this.previous);
+                               else this._activeKB = this._instances[0];
+                       }
+                       return this;
+               },
+
+               trace: function(){
+                       Keyboard.trace(this);
+               },
+
+               each: function(fn){
+                       Keyboard.each(this, fn);
+               },
+
+               /*
+                       PRIVATE METHODS
+               */
+
+               _instances: [],
+
+               _disable: function(instance){
+                       if (this._activeKB == instance) this._activeKB = null;
+               },
+
+               _setup: function(){
+                       this.addEvents(this.options.events);
+                       //if this is the root manager, nothing manages it
+                       if (Keyboard.manager && !this._manager) Keyboard.manager.manage(this);
+                       if (this.options.active) this.activate();
+                       else this.relinquish();
+               },
+
+               _handle: function(event, type){
+                       //Keyboard.stop(event) prevents key propagation
+                       if (event.preventKeyboardPropagation) return;
+
+                       var bubbles = !!this._manager;
+                       if (bubbles && this._activeKB){
+                               this._activeKB._handle(event, type);
+                               if (event.preventKeyboardPropagation) return;
+                       }
+                       this.fireEvent(type, event);
+
+                       if (!bubbles && this._activeKB) this._activeKB._handle(event, type);
+               }
+
+       });
+
+       var parsed = {};
+       var modifiers = ['shift', 'control', 'alt', 'meta'];
+       var regex = /^(?:shift|control|ctrl|alt|meta)$/;
+
+       Keyboard.parse = function(type, eventType, ignore){
+               if (ignore && ignore.contains(type.toLowerCase())) return type;
+
+               type = type.toLowerCase().replace(/^(keyup|keydown):/, function($0, $1){
+                       eventType = $1;
+                       return '';
+               });
+
+               if (!parsed[type]){
+                       var key, mods = {};
+                       type.split('+').each(function(part){
+                               if (regex.test(part)) mods[part] = true;
+                               else key = part;
+                       });
+
+                       mods.control = mods.control || mods.ctrl; // allow both control and ctrl
+
+                       var keys = [];
+                       modifiers.each(function(mod){
+                               if (mods[mod]) keys.push(mod);
+                       });
+
+                       if (key) keys.push(key);
+                       parsed[type] = keys.join('+');
+               }
+
+               return eventType + ':keys(' + parsed[type] + ')';
+       };
+
+       Keyboard.each = function(keyboard, fn){
+               var current = keyboard || Keyboard.manager;
+               while (current){
+                       fn.run(current);
+                       current = current._activeKB;
+               }
+       };
+
+       Keyboard.stop = function(event){
+               event.preventKeyboardPropagation = true;
+       };
+
+       Keyboard.manager = new Keyboard({
+               active: true
+       });
+
+       Keyboard.trace = function(keyboard){
+               keyboard = keyboard || Keyboard.manager;
+               var hasConsole = window.console && console.log;
+               if (hasConsole) console.log('the following items have focus: ');
+               Keyboard.each(keyboard, function(current){
+                       if (hasConsole) console.log(document.id(current.widget) || current.wiget || current);
+               });
+       };
+
+       var handler = function(event){
+               var keys = [];
+               modifiers.each(function(mod){
+                       if (event[mod]) keys.push(mod);
+               });
+
+               if (!regex.test(event.key)) keys.push(event.key);
+               Keyboard.manager._handle(event, event.type + ':keys(' + keys.join('+') + ')');
+       };
+
+       document.addEvents({
+               'keyup': handler,
+               'keydown': handler
+       });
+
+})();
+
+
+// Begin: Source/Interface/Keyboard.Extras.js
+/*
+---
+
+script: Keyboard.Extras.js
+
+name: Keyboard.Extras
+
+description: Enhances Keyboard by adding the ability to name and describe keyboard shortcuts, and the ability to grab shortcuts by name and bind the shortcut to different keys.
+
+license: MIT-style license
+
+authors:
+  - Perrin Westrich
+
+requires:
+  - /Keyboard
+  - /MooTools.More
+
+provides: [Keyboard.Extras]
+
+...
+*/
+Keyboard.prototype.options.nonParsedEvents.combine(['rebound', 'onrebound']);
+
+Keyboard.implement({
+
+       /*
+               shortcut should be in the format of:
+               {
+                       'keys': 'shift+s', // the default to add as an event.
+                       'description': 'blah blah blah', // a brief description of the functionality.
+                       'handler': function(){} // the event handler to run when keys are pressed.
+               }
+       */
+       addShortcut: function(name, shortcut){
+               this._shortcuts = this._shortcuts || [];
+               this._shortcutIndex = this._shortcutIndex || {};
+
+               shortcut.getKeyboard = Function.from(this);
+               shortcut.name = name;
+               this._shortcutIndex[name] = shortcut;
+               this._shortcuts.push(shortcut);
+               if (shortcut.keys) this.addEvent(shortcut.keys, shortcut.handler);
+               return this;
+       },
+
+       addShortcuts: function(obj){
+               for (var name in obj) this.addShortcut(name, obj[name]);
+               return this;
+       },
+
+       removeShortcut: function(name){
+               var shortcut = this.getShortcut(name);
+               if (shortcut && shortcut.keys){
+                       this.removeEvent(shortcut.keys, shortcut.handler);
+                       delete this._shortcutIndex[name];
+                       this._shortcuts.erase(shortcut);
+               }
+               return this;
+       },
+
+       removeShortcuts: function(names){
+               names.each(this.removeShortcut, this);
+               return this;
+       },
+
+       getShortcuts: function(){
+               return this._shortcuts || [];
+       },
+
+       getShortcut: function(name){
+               return (this._shortcutIndex || {})[name];
+       }
+
+});
+
+Keyboard.rebind = function(newKeys, shortcuts){
+       Array.from(shortcuts).each(function(shortcut){
+               shortcut.getKeyboard().removeEvent(shortcut.keys, shortcut.handler);
+               shortcut.getKeyboard().addEvent(newKeys, shortcut.handler);
+               shortcut.keys = newKeys;
+               shortcut.getKeyboard().fireEvent('rebound');
+       });
+};
+
+
+Keyboard.getActiveShortcuts = function(keyboard){
+       var activeKBS = [], activeSCS = [];
+       Keyboard.each(keyboard, [].push.bind(activeKBS));
+       activeKBS.each(function(kb){ activeSCS.extend(kb.getShortcuts()); });
+       return activeSCS;
+};
+
+Keyboard.getShortcut = function(name, keyboard, opts){
+       opts = opts || {};
+       var shortcuts = opts.many ? [] : null,
+               set = opts.many ? function(kb){
+                               var shortcut = kb.getShortcut(name);
+                               if (shortcut) shortcuts.push(shortcut);
+                       } : function(kb){
+                               if (!shortcuts) shortcuts = kb.getShortcut(name);
+                       };
+       Keyboard.each(keyboard, set);
+       return shortcuts;
+};
+
+Keyboard.getShortcuts = function(name, keyboard){
+       return Keyboard.getShortcut(name, keyboard, { many: true });
+};
+
+
+// Begin: Source/Locale/Locale.js
+/*
+---
+
+script: Locale.js
+
+name: Locale
+
+description: Provides methods for localization.
+
+license: MIT-style license
+
+authors:
+  - Aaron Newton
+  - Arian Stolwijk
+
+requires:
+  - Core/Events
+  - /Object.Extras
+  - /MooTools.More
+
+provides: [Locale, Lang]
+
+...
+*/
+
+(function(){
+
+var current = null,
+       locales = {},
+       inherits = {};
+
+var getSet = function(set){
+       if (instanceOf(set, Locale.Set)) return set;
+       else return locales[set];
+};
+
+var Locale = this.Locale = {
+
+       define: function(locale, set, key, value){
+               var name;
+               if (instanceOf(locale, Locale.Set)){
+                       name = locale.name;
+                       if (name) locales[name] = locale;
+               } else {
+                       name = locale;
+                       if (!locales[name]) locales[name] = new Locale.Set(name);
+                       locale = locales[name];
+               }
+
+               if (set) locale.define(set, key, value);
+
+               /*<1.2compat>*/
+               if (set == 'cascade') return Locale.inherit(name, key);
+               /*</1.2compat>*/
+
+               if (!current) current = locale;
+
+               return locale;
+       },
+
+       use: function(locale){
+               locale = getSet(locale);
+
+               if (locale){
+                       current = locale;
+
+                       this.fireEvent('change', locale);
+
+                       /*<1.2compat>*/
+                       this.fireEvent('langChange', locale.name);
+                       /*</1.2compat>*/
+               }
+
+               return this;
+       },
+
+       getCurrent: function(){
+               return current;
+       },
+
+       get: function(key, args){
+               return (current) ? current.get(key, args) : '';
+       },
+
+       inherit: function(locale, inherits, set){
+               locale = getSet(locale);
+
+               if (locale) locale.inherit(inherits, set);
+               return this;
+       },
+
+       list: function(){
+               return Object.keys(locales);
+       }
+
+};
+
+Object.append(Locale, new Events);
+
+Locale.Set = new Class({
+
+       sets: {},
+
+       inherits: {
+               locales: [],
+               sets: {}
+       },
+
+       initialize: function(name){
+               this.name = name || '';
+       },
+
+       define: function(set, key, value){
+               var defineData = this.sets[set];
+               if (!defineData) defineData = {};
+
+               if (key){
+                       if (typeOf(key) == 'object') defineData = Object.merge(defineData, key);
+                       else defineData[key] = value;
+               }
+               this.sets[set] = defineData;
+
+               return this;
+       },
+
+       get: function(key, args, _base){
+               var value = Object.getFromPath(this.sets, key);
+               if (value != null){
+                       var type = typeOf(value);
+                       if (type == 'function') value = value.apply(null, Array.from(args));
+                       else if (type == 'object') value = Object.clone(value);
+                       return value;
+               }
+
+               // get value of inherited locales
+               var index = key.indexOf('.'),
+                       set = index < 0 ? key : key.substr(0, index),
+                       names = (this.inherits.sets[set] || []).combine(this.inherits.locales).include('en-US');
+               if (!_base) _base = [];
+
+               for (var i = 0, l = names.length; i < l; i++){
+                       if (_base.contains(names[i])) continue;
+                       _base.include(names[i]);
+
+                       var locale = locales[names[i]];
+                       if (!locale) continue;
+
+                       value = locale.get(key, args, _base);
+                       if (value != null) return value;
+               }
+
+               return '';
+       },
+
+       inherit: function(names, set){
+               names = Array.from(names);
+
+               if (set && !this.inherits.sets[set]) this.inherits.sets[set] = [];
+
+               var l = names.length;
+               while (l--) (set ? this.inherits.sets[set] : this.inherits.locales).unshift(names[l]);
+
+               return this;
+       }
+
+});
+
+/*<1.2compat>*/
+var lang = MooTools.lang = {};
+
+Object.append(lang, Locale, {
+       setLanguage: Locale.use,
+       getCurrentLanguage: function(){
+               var current = Locale.getCurrent();
+               return (current) ? current.name : null;
+       },
+       set: function(){
+               Locale.define.apply(this, arguments);
+               return this;
+       },
+       get: function(set, key, args){
+               if (key) set += '.' + key;
+               return Locale.get(set, args);
+       }
+});
+/*</1.2compat>*/
+
+})();
+
+
+// Begin: Source/Locale/Locale.en-US.Number.js
+/*
+---
+
+name: Locale.en-US.Number
+
+description: Number messages for US English.
+
+license: MIT-style license
+
+authors:
+  - Arian Stolwijk
+
+requires:
+  - /Locale
+
+provides: [Locale.en-US.Number]
+
+...
+*/
+
+Locale.define('en-US', 'Number', {
+
+       decimal: '.',
+       group: ',',
+
+/*     Commented properties are the defaults for Number.format
+       decimals: 0,
+       precision: 0,
+       scientific: null,
+
+       prefix: null,
+       suffic: null,
+
+       // Negative/Currency/percentage will mixin Number
+       negative: {
+               prefix: '-'
+       },*/
+
+       currency: {
+//             decimals: 2,
+               prefix: '$ '
+       }/*,
+
+       percentage: {
+               decimals: 2,
+               suffix: '%'
+       }*/
+
+});
+
+
+
+
+// Begin: Source/Types/Number.Format.js
+/*
+---
+name: Number.Format
+description: Extends the Number Type object to include a number formatting method.
+license: MIT-style license
+authors: [Arian Stolwijk]
+requires: [Core/Number, Locale.en-US.Number]
+# Number.Extras is for compatibility
+provides: [Number.Format, Number.Extras]
+...
+*/
+
+
+Number.implement({
+
+       format: function(options){
+               // Thanks dojo and YUI for some inspiration
+               var value = this;
+               options = options ? Object.clone(options) : {};
+               var getOption = function(key){
+                       if (options[key] != null) return options[key];
+                       return Locale.get('Number.' + key);
+               };
+
+               var negative = value < 0,
+                       decimal = getOption('decimal'),
+                       precision = getOption('precision'),
+                       group = getOption('group'),
+                       decimals = getOption('decimals');
+
+               if (negative){
+                       var negativeLocale = getOption('negative') || {};
+                       if (negativeLocale.prefix == null && negativeLocale.suffix == null) negativeLocale.prefix = '-';
+                       ['prefix', 'suffix'].each(function(key){
+                               if (negativeLocale[key]) options[key] = getOption(key) + negativeLocale[key];
+                       });
+
+                       value = -value;
+               }
+
+               var prefix = getOption('prefix'),
+                       suffix = getOption('suffix');
+
+               if (decimals !== '' && decimals >= 0 && decimals <= 20) value = value.toFixed(decimals);
+               if (precision >= 1 && precision <= 21) value = (+value).toPrecision(precision);
+
+               value += '';
+               var index;
+               if (getOption('scientific') === false && value.indexOf('e') > -1){
+                       var match = value.split('e'),
+                               zeros = +match[1];
+                       value = match[0].replace('.', '');
+
+                       if (zeros < 0){
+                               zeros = -zeros - 1;
+                               index = match[0].indexOf('.');
+                               if (index > -1) zeros -= index - 1;
+                               while (zeros--) value = '0' + value;
+                               value = '0.' + value;
+                       } else {
+                               index = match[0].lastIndexOf('.');
+                               if (index > -1) zeros -= match[0].length - index - 1;
+                               while (zeros--) value += '0';
+                       }
+               }
+
+               if (decimal != '.') value = value.replace('.', decimal);
+
+               if (group){
+                       index = value.lastIndexOf(decimal);
+                       index = (index > -1) ? index : value.length;
+                       var newOutput = value.substring(index),
+                               i = index;
+
+                       while (i--){
+                               if ((index - i - 1) % 3 == 0 && i != (index - 1)) newOutput = group + newOutput;
+                               newOutput = value.charAt(i) + newOutput;
+                       }
+
+                       value = newOutput;
+               }
+
+               if (prefix) value = prefix + value;
+               if (suffix) value += suffix;
+
+               return value;
+       },
+
+       formatCurrency: function(decimals){
+               var locale = Locale.get('Number.currency') || {};
+               if (locale.scientific == null) locale.scientific = false;
+               locale.decimals = decimals != null ? decimals
+                       : (locale.decimals == null ? 2 : locale.decimals);
+
+               return this.format(locale);
+       },
+
+       formatPercentage: function(decimals){
+               var locale = Locale.get('Number.percentage') || {};
+               if (locale.suffix == null) locale.suffix = '%';
+               locale.decimals = decimals != null ? decimals
+                       : (locale.decimals == null ? 2 : locale.decimals);
+
+               return this.format(locale);
+       }
+
+});
+
+
+// Begin: Source/Request/Request.Periodical.js
+/*
+---
+
+script: Request.Periodical.js
+
+name: Request.Periodical
+
+description: Requests the same URL to pull data from a server but increases the intervals if no data is returned to reduce the load
+
+license: MIT-style license
+
+authors:
+  - Christoph Pojer
+
+requires:
+  - Core/Request
+  - /MooTools.More
+
+provides: [Request.Periodical]
+
+...
+*/
+
+Request.implement({
+
+       options: {
+               initialDelay: 5000,
+               delay: 5000,
+               limit: 60000
+       },
+
+       startTimer: function(data){
+               var fn = function(){
+                       if (!this.running) this.send({data: data});
+               };
+               this.lastDelay = this.options.initialDelay;
+               this.timer = fn.delay(this.lastDelay, this);
+               this.completeCheck = function(response){
+                       clearTimeout(this.timer);
+                       this.lastDelay = (response) ? this.options.delay : (this.lastDelay + this.options.delay).min(this.options.limit);
+                       this.timer = fn.delay(this.lastDelay, this);
+               };
+               return this.addEvent('complete', this.completeCheck);
+       },
+
+       stopTimer: function(){
+               clearTimeout(this.timer);
+               return this.removeEvent('complete', this.completeCheck);
+       }
+
+});
+
+
+// Begin: Source/Request/Request.JSONP.js
+/*
+---
+
+script: Request.JSONP.js
+
+name: Request.JSONP
+
+description: Defines Request.JSONP, a class for cross domain javascript via script injection.
+
+license: MIT-style license
+
+authors:
+  - Aaron Newton
+  - Guillermo Rauch
+  - Arian Stolwijk
+
+requires:
+  - Core/Element
+  - Core/Request
+  - MooTools.More
+
+provides: [Request.JSONP]
+
+...
+*/
+
+Request.JSONP = new Class({
+
+       Implements: [Chain, Events, Options],
+
+       options: {/*
+               onRequest: function(src, scriptElement){},
+               onComplete: function(data){},
+               onSuccess: function(data){},
+               onCancel: function(){},
+               onTimeout: function(){},
+               onError: function(){}, */
+               onRequest: function(src){
+                       if (this.options.log && window.console && console.log){
+                               console.log('JSONP retrieving script with url:' + src);
+                       }
+               },
+               onError: function(src){
+                       if (this.options.log && window.console && console.warn){
+                               console.warn('JSONP '+ src +' will fail in Internet Explorer, which enforces a 2083 bytes length limit on URIs');
+                       }
+               },
+               url: '',
+               callbackKey: 'callback',
+               injectScript: document.head,
+               data: '',
+               link: 'ignore',
+               timeout: 0,
+               log: false
+       },
+
+       initialize: function(options){
+               this.setOptions(options);
+       },
+
+       send: function(options){
+               if (!Request.prototype.check.call(this, options)) return this;
+               this.running = true;
+
+               var type = typeOf(options);
+               if (type == 'string' || type == 'element') options = {data: options};
+               options = Object.merge(this.options, options || {});
+
+               var data = options.data;
+               switch (typeOf(data)){
+                       case 'element': data = document.id(data).toQueryString(); break;
+                       case 'object': case 'hash': data = Object.toQueryString(data);
+               }
+
+               var index = this.index = Request.JSONP.counter++;
+
+               var src = options.url +
+                       (options.url.test('\\?') ? '&' :'?') +
+                       (options.callbackKey) +
+                       '=Request.JSONP.request_map.request_'+ index +
+                       (data ? '&' + data : '');
+
+               if (src.length > 2083) this.fireEvent('error', src);
+
+               Request.JSONP.request_map['request_' + index] = function(){
+                       this.success(arguments, index);
+               }.bind(this);
+
+               var script = this.getScript(src).inject(options.injectScript);
+               this.fireEvent('request', [src, script]);
+
+               if (options.timeout) this.timeout.delay(options.timeout, this);
+
+               return this;
+       },
+
+       getScript: function(src){
+               if (!this.script) this.script = new Element('script', {
+                       type: 'text/javascript',
+                       async: true,
+                       src: src
+               });
+               return this.script;
+       },
+
+       success: function(args, index){
+               if (!this.running) return;
+               this.clear()
+                       .fireEvent('complete', args).fireEvent('success', args)
+                       .callChain();
+       },
+
+       cancel: function(){
+               if (this.running) this.clear().fireEvent('cancel');
+               return this;
+       },
+
+       isRunning: function(){
+               return !!this.running;
+       },
+
+       clear: function(){
+               this.running = false;
+               if (this.script){
+                       this.script.destroy();
+                       this.script = null;
+               }
+               return this;
+       },
+
+       timeout: function(){
+               if (this.running){
+                       this.running = false;
+                       this.fireEvent('timeout', [this.script.get('src'), this.script]).fireEvent('failure').cancel();
+               }
+               return this;
+       }
+
+});
+
+Request.JSONP.counter = 0;
+Request.JSONP.request_map = {};
+
+
+// Begin: Source/Types/String.QueryString.js
+/*
+---
+
+script: String.QueryString.js
+
+name: String.QueryString
+
+description: Methods for dealing with URI query strings.
+
+license: MIT-style license
+
+authors:
+  - Sebastian Markbåge
+  - Aaron Newton
+  - Lennart Pilon
+  - Valerio Proietti
+
+requires:
+  - Core/Array
+  - Core/String
+  - /MooTools.More
+
+provides: [String.QueryString]
+
+...
+*/
+
+String.implement({
+
+       parseQueryString: function(decodeKeys, decodeValues){
+               if (decodeKeys == null) decodeKeys = true;
+               if (decodeValues == null) decodeValues = true;
+
+               var vars = this.split(/[&;]/),
+                       object = {};
+               if (!vars.length) return object;
+
+               vars.each(function(val){
+                       var index = val.indexOf('=') + 1,
+                               value = index ? val.substr(index) : '',
+                               keys = index ? val.substr(0, index - 1).match(/([^\]\[]+|(\B)(?=\]))/g) : [val],
+                               obj = object;
+                       if (!keys) return;
+                       if (decodeValues) value = decodeURIComponent(value);
+                       keys.each(function(key, i){
+                               if (decodeKeys) key = decodeURIComponent(key);
+                               var current = obj[key];
+
+                               if (i < keys.length - 1) obj = obj[key] = current || {};
+                               else if (typeOf(current) == 'array') current.push(value);
+                               else obj[key] = current != null ? [current, value] : value;
+                       });
+               });
+
+               return object;
+       },
+
+       cleanQueryString: function(method){
+               return this.split('&').filter(function(val){
+                       var index = val.indexOf('='),
+                               key = index < 0 ? '' : val.substr(0, index),
+                               value = val.substr(index + 1);
+
+                       return method ? method.call(null, key, value) : (value || value === 0);
+               }).join('&');
+       }
+
+});
+
+
+// Begin: Source/Types/URI.js
+/*
+---
+
+script: URI.js
+
+name: URI
+
+description: Provides methods useful in managing the window location and uris.
+
+license: MIT-style license
+
+authors:
+  - Sebastian Markbåge
+  - Aaron Newton
+
+requires:
+  - Core/Object
+  - Core/Class
+  - Core/Class.Extras
+  - Core/Element
+  - /String.QueryString
+
+provides: [URI]
+
+...
+*/
+
+(function(){
+
+var toString = function(){
+       return this.get('value');
+};
+
+var URI = this.URI = new Class({
+
+       Implements: Options,
+
+       options: {
+               /*base: false*/
+       },
+
+       regex: /^(?:(\w+):)?(?:\/\/(?:(?:([^:@\/]*):?([^:@\/]*))?@)?([^:\/?#]*)(?::(\d*))?)?(\.\.?$|(?:[^?#\/]*\/)*)([^?#]*)(?:\?([^#]*))?(?:#(.*))?/,
+       parts: ['scheme', 'user', 'password', 'host', 'port', 'directory', 'file', 'query', 'fragment'],
+       schemes: {http: 80, https: 443, ftp: 21, rtsp: 554, mms: 1755, file: 0},
+
+       initialize: function(uri, options){
+               this.setOptions(options);
+               var base = this.options.base || URI.base;
+               if (!uri) uri = base;
+
+               if (uri && uri.parsed) this.parsed = Object.clone(uri.parsed);
+               else this.set('value', uri.href || uri.toString(), base ? new URI(base) : false);
+       },
+
+       parse: function(value, base){
+               var bits = value.match(this.regex);
+               if (!bits) return false;
+               bits.shift();
+               return this.merge(bits.associate(this.parts), base);
+       },
+
+       merge: function(bits, base){
+               if ((!bits || !bits.scheme) && (!base || !base.scheme)) return false;
+               if (base){
+                       this.parts.every(function(part){
+                               if (bits[part]) return false;
+                               bits[part] = base[part] || '';
+                               return true;
+                       });
+               }
+               bits.port = bits.port || this.schemes[bits.scheme.toLowerCase()];
+               bits.directory = bits.directory ? this.parseDirectory(bits.directory, base ? base.directory : '') : '/';
+               return bits;
+       },
+
+       parseDirectory: function(directory, baseDirectory){
+               directory = (directory.substr(0, 1) == '/' ? '' : (baseDirectory || '/')) + directory;
+               if (!directory.test(URI.regs.directoryDot)) return directory;
+               var result = [];
+               directory.replace(URI.regs.endSlash, '').split('/').each(function(dir){
+                       if (dir == '..' && result.length > 0) result.pop();
+                       else if (dir != '.') result.push(dir);
+               });
+               return result.join('/') + '/';
+       },
+
+       combine: function(bits){
+               return bits.value || bits.scheme + '://' +
+                       (bits.user ? bits.user + (bits.password ? ':' + bits.password : '') + '@' : '') +
+                       (bits.host || '') + (bits.port && bits.port != this.schemes[bits.scheme] ? ':' + bits.port : '') +
+                       (bits.directory || '/') + (bits.file || '') +
+                       (bits.query ? '?' + bits.query : '') +
+                       (bits.fragment ? '#' + bits.fragment : '');
+       },
+
+       set: function(part, value, base){
+               if (part == 'value'){
+                       var scheme = value.match(URI.regs.scheme);
+                       if (scheme) scheme = scheme[1];
+                       if (scheme && this.schemes[scheme.toLowerCase()] == null) this.parsed = { scheme: scheme, value: value };
+                       else this.parsed = this.parse(value, (base || this).parsed) || (scheme ? { scheme: scheme, value: value } : { value: value });
+               } else if (part == 'data'){
+                       this.setData(value);
+               } else {
+                       this.parsed[part] = value;
+               }
+               return this;
+       },
+
+       get: function(part, base){
+               switch (part){
+                       case 'value': return this.combine(this.parsed, base ? base.parsed : false);
+                       case 'data' : return this.getData();
+               }
+               return this.parsed[part] || '';
+       },
+
+       go: function(){
+               document.location.href = this.toString();
+       },
+
+       toURI: function(){
+               return this;
+       },
+
+       getData: function(key, part){
+               var qs = this.get(part || 'query');
+               if (!(qs || qs === 0)) return key ? null : {};
+               var obj = qs.parseQueryString();
+               return key ? obj[key] : obj;
+       },
+
+       setData: function(values, merge, part){
+               if (typeof values == 'string'){
+                       var data = this.getData();
+                       data[arguments[0]] = arguments[1];
+                       values = data;
+               } else if (merge){
+                       values = Object.merge(this.getData(), values);
+               }
+               return this.set(part || 'query', Object.toQueryString(values));
+       },
+
+       clearData: function(part){
+               return this.set(part || 'query', '');
+       },
+
+       toString: toString,
+       valueOf: toString
+
+});
+
+URI.regs = {
+       endSlash: /\/$/,
+       scheme: /^(\w+):/,
+       directoryDot: /\.\/|\.$/
+};
+
+URI.base = new URI(Array.from(document.getElements('base[href]', true)).getLast(), {base: document.location});
+
+String.implement({
+
+       toURI: function(options){
+               return new URI(this, options);
+       }
+
+});
+
+})();
+
+
+// Begin: Source/Types/URI.Relative.js
+/*
+---
+
+script: URI.Relative.js
+
+name: URI.Relative
+
+description: Extends the URI class to add methods for computing relative and absolute urls.
+
+license: MIT-style license
+
+authors:
+  - Sebastian Markbåge
+
+
+requires:
+  - /Class.refactor
+  - /URI
+
+provides: [URI.Relative]
+
+...
+*/
+
+URI = Class.refactor(URI, {
+
+       combine: function(bits, base){
+               if (!base || bits.scheme != base.scheme || bits.host != base.host || bits.port != base.port)
+                       return this.previous.apply(this, arguments);
+               var end = bits.file + (bits.query ? '?' + bits.query : '') + (bits.fragment ? '#' + bits.fragment : '');
+
+               if (!base.directory) return (bits.directory || (bits.file ? '' : './')) + end;
+
+               var baseDir = base.directory.split('/'),
+                       relDir = bits.directory.split('/'),
+                       path = '',
+                       offset;
+
+               var i = 0;
+               for (offset = 0; offset < baseDir.length && offset < relDir.length && baseDir[offset] == relDir[offset]; offset++);
+               for (i = 0; i < baseDir.length - offset - 1; i++) path += '../';
+               for (i = offset; i < relDir.length - 1; i++) path += relDir[i] + '/';
+
+               return (path || (bits.file ? '' : './')) + end;
+       },
+
+       toAbsolute: function(base){
+               base = new URI(base);
+               if (base) base.set('directory', '').set('file', '');
+               return this.toRelative(base);
+       },
+
+       toRelative: function(base){
+               return this.get('value', new URI(base));
+       }
+
+});
+
+
+// Begin: Source/Utilities/Cookie.js
+/*
+---
+
+name: Cookie
+
+description: Class for creating, reading, and deleting browser Cookies.
+
+license: MIT-style license.
+
+credits:
+  - Based on the functions by Peter-Paul Koch (http://quirksmode.org).
+
+requires: [Options, Browser]
+
+provides: Cookie
+
+...
+*/
+
+var Cookie = new Class({
+
+       Implements: Options,
+
+       options: {
+               path: '/',
+               domain: false,
+               duration: false,
+               secure: false,
+               document: document,
+               encode: true
+       },
+
+       initialize: function(key, options){
+               this.key = key;
+               this.setOptions(options);
+       },
+
+       write: function(value){
+               if (this.options.encode) value = encodeURIComponent(value);
+               if (this.options.domain) value += '; domain=' + this.options.domain;
+               if (this.options.path) value += '; path=' + this.options.path;
+               if (this.options.duration){
+                       var date = new Date();
+                       date.setTime(date.getTime() + this.options.duration * 24 * 60 * 60 * 1000);
+                       value += '; expires=' + date.toGMTString();
+               }
+               if (this.options.secure) value += '; secure';
+               this.options.document.cookie = this.key + '=' + value;
+               return this;
+       },
+
+       read: function(){
+               var value = this.options.document.cookie.match('(?:^|;)\\s*' + this.key.escapeRegExp() + '=([^;]*)');
+               return (value) ? decodeURIComponent(value[1]) : null;
+       },
+
+       dispose: function(){
+               new Cookie(this.key, Object.merge({}, this.options, {duration: -1})).write('');
+               return this;
+       }
+
+});
+
+Cookie.write = function(key, value, options){
+       return new Cookie(key, options).write(value);
+};
+
+Cookie.read = function(key){
+       return new Cookie(key).read();
+};
+
+Cookie.dispose = function(key, options){
+       return new Cookie(key, options).dispose();
+};
+
+
+// Begin: Source/Locale/Locale.en-US.Date.js
+/*
+---
+
+name: Locale.en-US.Date
+
+description: Date messages for US English.
+
+license: MIT-style license
+
+authors:
+  - Aaron Newton
+
+requires:
+  - /Locale
+
+provides: [Locale.en-US.Date]
+
+...
+*/
+
+Locale.define('en-US', 'Date', {
+
+       months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
+       months_abbr: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
+       days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
+       days_abbr: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
+
+       // Culture's date order: MM/DD/YYYY
+       dateOrder: ['month', 'date', 'year'],
+       shortDate: '%m/%d/%Y',
+       shortTime: '%I:%M%p',
+       AM: 'AM',
+       PM: 'PM',
+       firstDayOfWeek: 0,
+
+       // Date.Extras
+       ordinal: function(dayOfMonth){
+               // 1st, 2nd, 3rd, etc.
+               return (dayOfMonth > 3 && dayOfMonth < 21) ? 'th' : ['th', 'st', 'nd', 'rd', 'th'][Math.min(dayOfMonth % 10, 4)];
+       },
+
+       lessThanMinuteAgo: 'less than a minute ago',
+       minuteAgo: 'about a minute ago',
+       minutesAgo: '{delta} minutes ago',
+       hourAgo: 'about an hour ago',
+       hoursAgo: 'about {delta} hours ago',
+       dayAgo: '1 day ago',
+       daysAgo: '{delta} days ago',
+       weekAgo: '1 week ago',
+       weeksAgo: '{delta} weeks ago',
+       monthAgo: '1 month ago',
+       monthsAgo: '{delta} months ago',
+       yearAgo: '1 year ago',
+       yearsAgo: '{delta} years ago',
+
+       lessThanMinuteUntil: 'less than a minute from now',
+       minuteUntil: 'about a minute from now',
+       minutesUntil: '{delta} minutes from now',
+       hourUntil: 'about an hour from now',
+       hoursUntil: 'about {delta} hours from now',
+       dayUntil: '1 day from now',
+       daysUntil: '{delta} days from now',
+       weekUntil: '1 week from now',
+       weeksUntil: '{delta} weeks from now',
+       monthUntil: '1 month from now',
+       monthsUntil: '{delta} months from now',
+       yearUntil: '1 year from now',
+       yearsUntil: '{delta} years from now'
+
+});
+
+
+// Begin: Source/Types/Date.js
+/*
+---
+
+script: Date.js
+
+name: Date
+
+description: Extends the Date native object to include methods useful in managing dates.
+
+license: MIT-style license
+
+authors:
+  - Aaron Newton
+  - Nicholas Barthelemy - https://svn.nbarthelemy.com/date-js/
+  - Harald Kirshner - mail [at] digitarald.de; http://digitarald.de
+  - Scott Kyle - scott [at] appden.com; http://appden.com
+
+requires:
+  - Core/Array
+  - Core/String
+  - Core/Number
+  - MooTools.More
+  - Locale
+  - Locale.en-US.Date
+
+provides: [Date]
+
+...
+*/
+
+(function(){
+
+var Date = this.Date;
+
+var DateMethods = Date.Methods = {
+       ms: 'Milliseconds',
+       year: 'FullYear',
+       min: 'Minutes',
+       mo: 'Month',
+       sec: 'Seconds',
+       hr: 'Hours'
+};
+
+['Date', 'Day', 'FullYear', 'Hours', 'Milliseconds', 'Minutes', 'Month', 'Seconds', 'Time', 'TimezoneOffset',
+       'Week', 'Timezone', 'GMTOffset', 'DayOfYear', 'LastMonth', 'LastDayOfMonth', 'UTCDate', 'UTCDay', 'UTCFullYear',
+       'AMPM', 'Ordinal', 'UTCHours', 'UTCMilliseconds', 'UTCMinutes', 'UTCMonth', 'UTCSeconds', 'UTCMilliseconds'].each(function(method){
+       Date.Methods[method.toLowerCase()] = method;
+});
+
+var pad = function(n, digits, string){
+       if (digits == 1) return n;
+       return n < Math.pow(10, digits - 1) ? (string || '0') + pad(n, digits - 1, string) : n;
+};
+
+Date.implement({
+
+       set: function(prop, value){
+               prop = prop.toLowerCase();
+               var method = DateMethods[prop] && 'set' + DateMethods[prop];
+               if (method && this[method]) this[method](value);
+               return this;
+       }.overloadSetter(),
+
+       get: function(prop){
+               prop = prop.toLowerCase();
+               var method = DateMethods[prop] && 'get' + DateMethods[prop];
+               if (method && this[method]) return this[method]();
+               return null;
+       }.overloadGetter(),
+
+       clone: function(){
+               return new Date(this.get('time'));
+       },
+
+       increment: function(interval, times){
+               interval = interval || 'day';
+               times = times != null ? times : 1;
+
+               switch (interval){
+                       case 'year':
+                               return this.increment('month', times * 12);
+                       case 'month':
+                               var d = this.get('date');
+                               this.set('date', 1).set('mo', this.get('mo') + times);
+                               return this.set('date', d.min(this.get('lastdayofmonth')));
+                       case 'week':
+                               return this.increment('day', times * 7);
+                       case 'day':
+                               return this.set('date', this.get('date') + times);
+               }
+
+               if (!Date.units[interval]) throw new Error(interval + ' is not a supported interval');
+
+               return this.set('time', this.get('time') + times * Date.units[interval]());
+       },
+
+       decrement: function(interval, times){
+               return this.increment(interval, -1 * (times != null ? times : 1));
+       },
+
+       isLeapYear: function(){
+               return Date.isLeapYear(this.get('year'));
+       },
+
+       clearTime: function(){
+               return this.set({hr: 0, min: 0, sec: 0, ms: 0});
+       },
+
+       diff: function(date, resolution){
+               if (typeOf(date) == 'string') date = Date.parse(date);
+
+               return ((date - this) / Date.units[resolution || 'day'](3, 3)).round(); // non-leap year, 30-day month
+       },
+
+       getLastDayOfMonth: function(){
+               return Date.daysInMonth(this.get('mo'), this.get('year'));
+       },
+
+       getDayOfYear: function(){
+               return (Date.UTC(this.get('year'), this.get('mo'), this.get('date') + 1)
+                       - Date.UTC(this.get('year'), 0, 1)) / Date.units.day();
+       },
+
+       setDay: function(day, firstDayOfWeek){
+               if (firstDayOfWeek == null){
+                       firstDayOfWeek = Date.getMsg('firstDayOfWeek');
+                       if (firstDayOfWeek === '') firstDayOfWeek = 1;
+               }
+
+               day = (7 + Date.parseDay(day, true) - firstDayOfWeek) % 7;
+               var currentDay = (7 + this.get('day') - firstDayOfWeek) % 7;
+
+               return this.increment('day', day - currentDay);
+       },
+
+       getWeek: function(firstDayOfWeek){
+               if (firstDayOfWeek == null){
+                       firstDayOfWeek = Date.getMsg('firstDayOfWeek');
+                       if (firstDayOfWeek === '') firstDayOfWeek = 1;
+               }
+
+               var date = this,
+                       dayOfWeek = (7 + date.get('day') - firstDayOfWeek) % 7,
+                       dividend = 0,
+                       firstDayOfYear;
+
+               if (firstDayOfWeek == 1){
+                       // ISO-8601, week belongs to year that has the most days of the week (i.e. has the thursday of the week)
+                       var month = date.get('month'),
+                               startOfWeek = date.get('date') - dayOfWeek;
+
+                       if (month == 11 && startOfWeek > 28) return 1; // Week 1 of next year
+
+                       if (month == 0 && startOfWeek < -2){
+                               // Use a date from last year to determine the week
+                               date = new Date(date).decrement('day', dayOfWeek);
+                               dayOfWeek = 0;
+                       }
+
+                       firstDayOfYear = new Date(date.get('year'), 0, 1).get('day') || 7;
+                       if (firstDayOfYear > 4) dividend = -7; // First week of the year is not week 1
+               } else {
+                       // In other cultures the first week of the year is always week 1 and the last week always 53 or 54.
+                       // Days in the same week can have a different weeknumber if the week spreads across two years.
+                       firstDayOfYear = new Date(date.get('year'), 0, 1).get('day');
+               }
+
+               dividend += date.get('dayofyear');
+               dividend += 6 - dayOfWeek; // Add days so we calculate the current date's week as a full week
+               dividend += (7 + firstDayOfYear - firstDayOfWeek) % 7; // Make up for first week of the year not being a full week
+
+               return (dividend / 7);
+       },
+
+       getOrdinal: function(day){
+               return Date.getMsg('ordinal', day || this.get('date'));
+       },
+
+       getTimezone: function(){
+               return this.toString()
+                       .replace(/^.*? ([A-Z]{3}).[0-9]{4}.*$/, '$1')
+                       .replace(/^.*?\(([A-Z])[a-z]+ ([A-Z])[a-z]+ ([A-Z])[a-z]+\)$/, '$1$2$3');
+       },
+
+       getGMTOffset: function(){
+               var off = this.get('timezoneOffset');
+               return ((off > 0) ? '-' : '+') + pad((off.abs() / 60).floor(), 2) + pad(off % 60, 2);
+       },
+
+       setAMPM: function(ampm){
+               ampm = ampm.toUpperCase();
+               var hr = this.get('hr');
+               if (hr > 11 && ampm == 'AM') return this.decrement('hour', 12);
+               else if (hr < 12 && ampm == 'PM') return this.increment('hour', 12);
+               return this;
+       },
+
+       getAMPM: function(){
+               return (this.get('hr') < 12) ? 'AM' : 'PM';
+       },
+
+       parse: function(str){
+               this.set('time', Date.parse(str));
+               return this;
+       },
+
+       isValid: function(date){
+               if (!date) date = this;
+               return typeOf(date) == 'date' && !isNaN(date.valueOf());
+       },
+
+       format: function(format){
+               if (!this.isValid()) return 'invalid date';
+
+               if (!format) format = '%x %X';
+               if (typeof format == 'string') format = formats[format.toLowerCase()] || format;
+               if (typeof format == 'function') return format(this);
+
+               var d = this;
+               return format.replace(/%([a-z%])/gi,
+                       function($0, $1){
+                               switch ($1){
+                                       case 'a': return Date.getMsg('days_abbr')[d.get('day')];
+                                       case 'A': return Date.getMsg('days')[d.get('day')];
+                                       case 'b': return Date.getMsg('months_abbr')[d.get('month')];
+                                       case 'B': return Date.getMsg('months')[d.get('month')];
+                                       case 'c': return d.format('%a %b %d %H:%M:%S %Y');
+                                       case 'd': return pad(d.get('date'), 2);
+                                       case 'e': return pad(d.get('date'), 2, ' ');
+                                       case 'H': return pad(d.get('hr'), 2);
+                                       case 'I': return pad((d.get('hr') % 12) || 12, 2);
+                                       case 'j': return pad(d.get('dayofyear'), 3);
+                                       case 'k': return pad(d.get('hr'), 2, ' ');
+                                       case 'l': return pad((d.get('hr') % 12) || 12, 2, ' ');
+                                       case 'L': return pad(d.get('ms'), 3);
+                                       case 'm': return pad((d.get('mo') + 1), 2);
+                                       case 'M': return pad(d.get('min'), 2);
+                                       case 'o': return d.get('ordinal');
+                                       case 'p': return Date.getMsg(d.get('ampm'));
+                                       case 's': return Math.round(d / 1000);
+                                       case 'S': return pad(d.get('seconds'), 2);
+                                       case 'T': return d.format('%H:%M:%S');
+                                       case 'U': return pad(d.get('week'), 2);
+                                       case 'w': return d.get('day');
+                                       case 'x': return d.format(Date.getMsg('shortDate'));
+                                       case 'X': return d.format(Date.getMsg('shortTime'));
+                                       case 'y': return d.get('year').toString().substr(2);
+                                       case 'Y': return d.get('year');
+                                       case 'z': return d.get('GMTOffset');
+                                       case 'Z': return d.get('Timezone');
+                               }
+                               return $1;
+                       }
+               );
+       },
+
+       toISOString: function(){
+               return this.format('iso8601');
+       }
+
+}).alias({
+       toJSON: 'toISOString',
+       compare: 'diff',
+       strftime: 'format'
+});
+
+// The day and month abbreviations are standardized, so we cannot use simply %a and %b because they will get localized
+var rfcDayAbbr = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
+       rfcMonthAbbr = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
+
+var formats = {
+       db: '%Y-%m-%d %H:%M:%S',
+       compact: '%Y%m%dT%H%M%S',
+       'short': '%d %b %H:%M',
+       'long': '%B %d, %Y %H:%M',
+       rfc822: function(date){
+               return rfcDayAbbr[date.get('day')] + date.format(', %d ') + rfcMonthAbbr[date.get('month')] + date.format(' %Y %H:%M:%S %Z');
+       },
+       rfc2822: function(date){
+               return rfcDayAbbr[date.get('day')] + date.format(', %d ') + rfcMonthAbbr[date.get('month')] + date.format(' %Y %H:%M:%S %z');
+       },
+       iso8601: function(date){
+               return (
+                       date.getUTCFullYear() + '-' +
+                       pad(date.getUTCMonth() + 1, 2) + '-' +
+                       pad(date.getUTCDate(), 2) + 'T' +
+                       pad(date.getUTCHours(), 2) + ':' +
+                       pad(date.getUTCMinutes(), 2) + ':' +
+                       pad(date.getUTCSeconds(), 2) + '.' +
+                       pad(date.getUTCMilliseconds(), 3) + 'Z'
+               );
+       }
+};
+
+var parsePatterns = [],
+       nativeParse = Date.parse;
+
+var parseWord = function(type, word, num){
+       var ret = -1,
+               translated = Date.getMsg(type + 's');
+       switch (typeOf(word)){
+               case 'object':
+                       ret = translated[word.get(type)];
+                       break;
+               case 'number':
+                       ret = translated[word];
+                       if (!ret) throw new Error('Invalid ' + type + ' index: ' + word);
+                       break;
+               case 'string':
+                       var match = translated.filter(function(name){
+                               return this.test(name);
+                       }, new RegExp('^' + word, 'i'));
+                       if (!match.length) throw new Error('Invalid ' + type + ' string');
+                       if (match.length > 1) throw new Error('Ambiguous ' + type);
+                       ret = match[0];
+       }
+
+       return (num) ? translated.indexOf(ret) : ret;
+};
+
+var startCentury = 1900,
+       startYear = 70;
+
+Date.extend({
+
+       getMsg: function(key, args){
+               return Locale.get('Date.' + key, args);
+       },
+
+       units: {
+               ms: Function.from(1),
+               second: Function.from(1000),
+               minute: Function.from(60000),
+               hour: Function.from(3600000),
+               day: Function.from(86400000),
+               week: Function.from(608400000),
+               month: function(month, year){
+                       var d = new Date;
+                       return Date.daysInMonth(month != null ? month : d.get('mo'), year != null ? year : d.get('year')) * 86400000;
+               },
+               year: function(year){
+                       year = year || new Date().get('year');
+                       return Date.isLeapYear(year) ? 31622400000 : 31536000000;
+               }
+       },
+
+       daysInMonth: function(month, year){
+               return [31, Date.isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
+       },
+
+       isLeapYear: function(year){
+               return ((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0);
+       },
+
+       parse: function(from){
+               var t = typeOf(from);
+               if (t == 'number') return new Date(from);
+               if (t != 'string') return from;
+               from = from.clean();
+               if (!from.length) return null;
+
+               var parsed;
+               parsePatterns.some(function(pattern){
+                       var bits = pattern.re.exec(from);
+                       return (bits) ? (parsed = pattern.handler(bits)) : false;
+               });
+
+               if (!(parsed && parsed.isValid())){
+                       parsed = new Date(nativeParse(from));
+                       if (!(parsed && parsed.isValid())) parsed = new Date(from.toInt());
+               }
+               return parsed;
+       },
+
+       parseDay: function(day, num){
+               return parseWord('day', day, num);
+       },
+
+       parseMonth: function(month, num){
+               return parseWord('month', month, num);
+       },
+
+       parseUTC: function(value){
+               var localDate = new Date(value);
+               var utcSeconds = Date.UTC(
+                       localDate.get('year'),
+                       localDate.get('mo'),
+                       localDate.get('date'),
+                       localDate.get('hr'),
+                       localDate.get('min'),
+                       localDate.get('sec'),
+                       localDate.get('ms')
+               );
+               return new Date(utcSeconds);
+       },
+
+       orderIndex: function(unit){
+               return Date.getMsg('dateOrder').indexOf(unit) + 1;
+       },
+
+       defineFormat: function(name, format){
+               formats[name] = format;
+               return this;
+       },
+
+       //<1.2compat>
+       parsePatterns: parsePatterns,
+       //</1.2compat>
+
+       defineParser: function(pattern){
+               parsePatterns.push((pattern.re && pattern.handler) ? pattern : build(pattern));
+               return this;
+       },
+
+       defineParsers: function(){
+               Array.flatten(arguments).each(Date.defineParser);
+               return this;
+       },
+
+       define2DigitYearStart: function(year){
+               startYear = year % 100;
+               startCentury = year - startYear;
+               return this;
+       }
+
+}).extend({
+       defineFormats: Date.defineFormat.overloadSetter()
+});
+
+var regexOf = function(type){
+       return new RegExp('(?:' + Date.getMsg(type).map(function(name){
+               return name.substr(0, 3);
+       }).join('|') + ')[a-z]*');
+};
+
+var replacers = function(key){
+       switch (key){
+               case 'T':
+                       return '%H:%M:%S';
+               case 'x': // iso8601 covers yyyy-mm-dd, so just check if month is first
+                       return ((Date.orderIndex('month') == 1) ? '%m[-./]%d' : '%d[-./]%m') + '([-./]%y)?';
+               case 'X':
+                       return '%H([.:]%M)?([.:]%S([.:]%s)?)? ?%p? ?%z?';
+       }
+       return null;
+};
+
+var keys = {
+       d: /[0-2]?[0-9]|3[01]/,
+       H: /[01]?[0-9]|2[0-3]/,
+       I: /0?[1-9]|1[0-2]/,
+       M: /[0-5]?\d/,
+       s: /\d+/,
+       o: /[a-z]*/,
+       p: /[ap]\.?m\.?/,
+       y: /\d{2}|\d{4}/,
+       Y: /\d{4}/,
+       z: /Z|[+-]\d{2}(?::?\d{2})?/
+};
+
+keys.m = keys.I;
+keys.S = keys.M;
+
+var currentLanguage;
+
+var recompile = function(language){
+       currentLanguage = language;
+
+       keys.a = keys.A = regexOf('days');
+       keys.b = keys.B = regexOf('months');
+
+       parsePatterns.each(function(pattern, i){
+               if (pattern.format) parsePatterns[i] = build(pattern.format);
+       });
+};
+
+var build = function(format){
+       if (!currentLanguage) return {format: format};
+
+       var parsed = [];
+       var re = (format.source || format) // allow format to be regex
+        .replace(/%([a-z])/gi,
+               function($0, $1){
+                       return replacers($1) || $0;
+               }
+       ).replace(/\((?!\?)/g, '(?:') // make all groups non-capturing
+        .replace(/ (?!\?|\*)/g, ',? ') // be forgiving with spaces and commas
+        .replace(/%([a-z%])/gi,
+               function($0, $1){
+                       var p = keys[$1];
+                       if (!p) return $1;
+                       parsed.push($1);
+                       return '(' + p.source + ')';
+               }
+       ).replace(/\[a-z\]/gi, '[a-z\\u00c0-\\uffff;\&]'); // handle unicode words
+
+       return {
+               format: format,
+               re: new RegExp('^' + re + '$', 'i'),
+               handler: function(bits){
+                       bits = bits.slice(1).associate(parsed);
+                       var date = new Date().clearTime(),
+                               year = bits.y || bits.Y;
+
+                       if (year != null) handle.call(date, 'y', year); // need to start in the right year
+                       if ('d' in bits) handle.call(date, 'd', 1);
+                       if ('m' in bits || bits.b || bits.B) handle.call(date, 'm', 1);
+
+                       for (var key in bits) handle.call(date, key, bits[key]);
+                       return date;
+               }
+       };
+};
+
+var handle = function(key, value){
+       if (!value) return this;
+
+       switch (key){
+               case 'a': case 'A': return this.set('day', Date.parseDay(value, true));
+               case 'b': case 'B': return this.set('mo', Date.parseMonth(value, true));
+               case 'd': return this.set('date', value);
+               case 'H': case 'I': return this.set('hr', value);
+               case 'm': return this.set('mo', value - 1);
+               case 'M': return this.set('min', value);
+               case 'p': return this.set('ampm', value.replace(/\./g, ''));
+               case 'S': return this.set('sec', value);
+               case 's': return this.set('ms', ('0.' + value) * 1000);
+               case 'w': return this.set('day', value);
+               case 'Y': return this.set('year', value);
+               case 'y':
+                       value = +value;
+                       if (value < 100) value += startCentury + (value < startYear ? 100 : 0);
+                       return this.set('year', value);
+               case 'z':
+                       if (value == 'Z') value = '+00';
+                       var offset = value.match(/([+-])(\d{2}):?(\d{2})?/);
+                       offset = (offset[1] + '1') * (offset[2] * 60 + (+offset[3] || 0)) + this.getTimezoneOffset();
+                       return this.set('time', this - offset * 60000);
+       }
+
+       return this;
+};
+
+Date.defineParsers(
+       '%Y([-./]%m([-./]%d((T| )%X)?)?)?', // "1999-12-31", "1999-12-31 11:59pm", "1999-12-31 23:59:59", ISO8601
+       '%Y%m%d(T%H(%M%S?)?)?', // "19991231", "19991231T1159", compact
+       '%x( %X)?', // "12/31", "12.31.99", "12-31-1999", "12/31/2008 11:59 PM"
+       '%d%o( %b( %Y)?)?( %X)?', // "31st", "31st December", "31 Dec 1999", "31 Dec 1999 11:59pm"
+       '%b( %d%o)?( %Y)?( %X)?', // Same as above with month and day switched
+       '%Y %b( %d%o( %X)?)?', // Same as above with year coming first
+       '%o %b %d %X %z %Y', // "Thu Oct 22 08:11:23 +0000 2009"
+       '%T', // %H:%M:%S
+       '%H:%M( ?%p)?' // "11:05pm", "11:05 am" and "11:05"
+);
+
+Locale.addEvent('change', function(language){
+       if (Locale.get('Date')) recompile(language);
+}).fireEvent('change', Locale.getCurrent());
+
+})();
+
+
+// Begin: Source/Types/Date.Extras.js
+/*
+---
+
+script: Date.Extras.js
+
+name: Date.Extras
+
+description: Extends the Date native object to include extra methods (on top of those in Date.js).
+
+license: MIT-style license
+
+authors:
+  - Aaron Newton
+  - Scott Kyle
+
+requires:
+  - /Date
+
+provides: [Date.Extras]
+
+...
+*/
+
+Date.implement({
+
+       timeDiffInWords: function(to){
+               return Date.distanceOfTimeInWords(this, to || new Date);
+       },
+
+       timeDiff: function(to, separator){
+               if (to == null) to = new Date;
+               var delta = ((to - this) / 1000).floor().abs();
+
+               var vals = [],
+                       durations = [60, 60, 24, 365, 0],
+                       names = ['s', 'm', 'h', 'd', 'y'],
+                       value, duration;
+
+               for (var item = 0; item < durations.length; item++){
+                       if (item && !delta) break;
+                       value = delta;
+                       if ((duration = durations[item])){
+                               value = (delta % duration);
+                               delta = (delta / duration).floor();
+                       }
+                       vals.unshift(value + (names[item] || ''));
+               }
+
+               return vals.join(separator || ':');
+       }
+
+}).extend({
+
+       distanceOfTimeInWords: function(from, to){
+               return Date.getTimePhrase(((to - from) / 1000).toInt());
+       },
+
+       getTimePhrase: function(delta){
+               var suffix = (delta < 0) ? 'Until' : 'Ago';
+               if (delta < 0) delta *= -1;
+
+               var units = {
+                       minute: 60,
+                       hour: 60,
+                       day: 24,
+                       week: 7,
+                       month: 52 / 12,
+                       year: 12,
+                       eon: Infinity
+               };
+
+               var msg = 'lessThanMinute';
+
+               for (var unit in units){
+                       var interval = units[unit];
+                       if (delta < 1.5 * interval){
+                               if (delta > 0.75 * interval) msg = unit;
+                               break;
+                       }
+                       delta /= interval;
+                       msg = unit + 's';
+               }
+
+               delta = delta.round();
+               return Date.getMsg(msg + suffix, delta).substitute({delta: delta});
+       }
+
+}).defineParsers(
+
+       {
+               // "today", "tomorrow", "yesterday"
+               re: /^(?:tod|tom|yes)/i,
+               handler: function(bits){
+                       var d = new Date().clearTime();
+                       switch (bits[0]){
+                               case 'tom': return d.increment();
+                               case 'yes': return d.decrement();
+                               default: return d;
+                       }
+               }
+       },
+
+       {
+               // "next Wednesday", "last Thursday"
+               re: /^(next|last) ([a-z]+)$/i,
+               handler: function(bits){
+                       var d = new Date().clearTime();
+                       var day = d.getDay();
+                       var newDay = Date.parseDay(bits[2], true);
+                       var addDays = newDay - day;
+                       if (newDay <= day) addDays += 7;
+                       if (bits[1] == 'last') addDays -= 7;
+                       return d.set('date', d.getDate() + addDays);
+               }
+       }
+
+).alias('timeAgoInWords', 'timeDiffInWords');
+
+
+// Begin: Source/Fx/Fx.Elements.js
+/*
+---
+
+script: Fx.Elements.js
+
+name: Fx.Elements
+
+description: Effect to change any number of CSS properties of any number of Elements.
+
+license: MIT-style license
+
+authors:
+  - Valerio Proietti
+
+requires:
+  - Core/Fx.CSS
+  - /MooTools.More
+
+provides: [Fx.Elements]
+
+...
+*/
+
+Fx.Elements = new Class({
+
+       Extends: Fx.CSS,
+
+       initialize: function(elements, options){
+               this.elements = this.subject = $$(elements);
+               this.parent(options);
+       },
+
+       compute: function(from, to, delta){
+               var now = {};
+
+               for (var i in from){
+                       var iFrom = from[i], iTo = to[i], iNow = now[i] = {};
+                       for (var p in iFrom) iNow[p] = this.parent(iFrom[p], iTo[p], delta);
+               }
+
+               return now;
+       },
+
+       set: function(now){
+               for (var i in now){
+                       if (!this.elements[i]) continue;
+
+                       var iNow = now[i];
+                       for (var p in iNow) this.render(this.elements[i], p, iNow[p], this.options.unit);
+               }
+
+               return this;
+       },
+
+       start: function(obj){
+               if (!this.check(obj)) return this;
+               var from = {}, to = {};
+
+               for (var i in obj){
+                       if (!this.elements[i]) continue;
+
+                       var iProps = obj[i], iFrom = from[i] = {}, iTo = to[i] = {};
+
+                       for (var p in iProps){
+                               var parsed = this.prepare(this.elements[i], p, iProps[p]);
+                               iFrom[p] = parsed.from;
+                               iTo[p] = parsed.to;
+                       }
+               }
+
+               return this.parent(from, to);
+       }
+
+});
+
+
+// Begin: Source/Fx/Fx.Accordion.js
+/*
+---
+
+script: Fx.Accordion.js
+
+name: Fx.Accordion
+
+description: An Fx.Elements extension which allows you to easily create accordion type controls.
+
+license: MIT-style license
+
+authors:
+  - Valerio Proietti
+
+requires:
+  - Core/Element.Event
+  - /Fx.Elements
+
+provides: [Fx.Accordion]
+
+...
+*/
+
+Fx.Accordion = new Class({
+
+       Extends: Fx.Elements,
+
+       options: {/*
+               onActive: function(toggler, section){},
+               onBackground: function(toggler, section){},*/
+               fixedHeight: false,
+               fixedWidth: false,
+               display: 0,
+               show: false,
+               height: true,
+               width: false,
+               opacity: true,
+               alwaysHide: false,
+               trigger: 'click',
+               initialDisplayFx: true,
+               resetHeight: true
+       },
+
+       initialize: function(){
+               var defined = function(obj){
+                       return obj != null;
+               };
+
+               var params = Array.link(arguments, {
+                       'container': Type.isElement, //deprecated
+                       'options': Type.isObject,
+                       'togglers': defined,
+                       'elements': defined
+               });
+               this.parent(params.elements, params.options);
+
+               var options = this.options,
+                       togglers = this.togglers = $$(params.togglers);
+
+               this.previous = -1;
+               this.internalChain = new Chain();
+
+               if (options.alwaysHide) this.options.link = 'chain';
+
+               if (options.show || this.options.show === 0){
+                       options.display = false;
+                       this.previous = options.show;
+               }
+
+               if (options.start){
+                       options.display = false;
+                       options.show = false;
+               }
+
+               var effects = this.effects = {};
+
+               if (options.opacity) effects.opacity = 'fullOpacity';
+               if (options.width) effects.width = options.fixedWidth ? 'fullWidth' : 'offsetWidth';
+               if (options.height) effects.height = options.fixedHeight ? 'fullHeight' : 'scrollHeight';
+
+               for (var i = 0, l = togglers.length; i < l; i++) this.addSection(togglers[i], this.elements[i]);
+
+               this.elements.each(function(el, i){
+                       if (options.show === i){
+                               this.fireEvent('active', [togglers[i], el]);
+                       } else {
+                               for (var fx in effects) el.setStyle(fx, 0);
+                       }
+               }, this);
+
+               if (options.display || options.display === 0 || options.initialDisplayFx === false){
+                       this.display(options.display, options.initialDisplayFx);
+               }
+
+               if (options.fixedHeight !== false) options.resetHeight = false;
+               this.addEvent('complete', this.internalChain.callChain.bind(this.internalChain));
+       },
+
+       addSection: function(toggler, element){
+               toggler = document.id(toggler);
+               element = document.id(element);
+               this.togglers.include(toggler);
+               this.elements.include(element);
+
+               var togglers = this.togglers,
+                       options = this.options,
+                       test = togglers.contains(toggler),
+                       idx = togglers.indexOf(toggler),
+                       displayer = this.display.pass(idx, this);
+
+               toggler.store('accordion:display', displayer)
+                       .addEvent(options.trigger, displayer);
+
+               if (options.height) element.setStyles({'padding-top': 0, 'border-top': 'none', 'padding-bottom': 0, 'border-bottom': 'none'});
+               if (options.width) element.setStyles({'padding-left': 0, 'border-left': 'none', 'padding-right': 0, 'border-right': 'none'});
+
+               element.fullOpacity = 1;
+               if (options.fixedWidth) element.fullWidth = options.fixedWidth;
+               if (options.fixedHeight) element.fullHeight = options.fixedHeight;
+               element.setStyle('overflow', 'hidden');
+
+               if (!test) for (var fx in this.effects){
+                       element.setStyle(fx, 0);
+               }
+               return this;
+       },
+
+       removeSection: function(toggler, displayIndex){
+               var togglers = this.togglers,
+                       idx = togglers.indexOf(toggler),
+                       element = this.elements[idx];
+
+               var remover = function(){
+                       togglers.erase(toggler);
+                       this.elements.erase(element);
+                       this.detach(toggler);
+               }.bind(this);
+
+               if (this.now == idx || displayIndex != null){
+                       this.display(displayIndex != null ? displayIndex : (idx - 1 >= 0 ? idx - 1 : 0)).chain(remover);
+               } else {
+                       remover();
+               }
+               return this;
+       },
+
+       detach: function(toggler){
+               var remove = function(toggler){
+                       toggler.removeEvent(this.options.trigger, toggler.retrieve('accordion:display'));
+               }.bind(this);
+
+               if (!toggler) this.togglers.each(remove);
+               else remove(toggler);
+               return this;
+       },
+
+       display: function(index, useFx){
+               if (!this.check(index, useFx)) return this;
+
+               var obj = {},
+                       elements = this.elements,
+                       options = this.options,
+                       effects = this.effects;
+
+               if (useFx == null) useFx = true;
+               if (typeOf(index) == 'element') index = elements.indexOf(index);
+               if (index == this.previous && !options.alwaysHide) return this;
+
+               if (options.resetHeight){
+                       var prev = elements[this.previous];
+                       if (prev && !this.selfHidden){
+                               for (var fx in effects) prev.setStyle(fx, prev[effects[fx]]);
+                       }
+               }
+
+               if ((this.timer && options.link == 'chain') || (index === this.previous && !options.alwaysHide)) return this;
+
+               this.previous = index;
+               this.selfHidden = false;
+
+               elements.each(function(el, i){
+                       obj[i] = {};
+                       var hide;
+                       if (i != index){
+                               hide = true;
+                       } else if (options.alwaysHide && ((el.offsetHeight > 0 && options.height) || el.offsetWidth > 0 && options.width)){
+                               hide = true;
+                               this.selfHidden = true;
+                       }
+                       this.fireEvent(hide ? 'background' : 'active', [this.togglers[i], el]);
+                       for (var fx in effects) obj[i][fx] = hide ? 0 : el[effects[fx]];
+                       if (!useFx && !hide && options.resetHeight) obj[i].height = 'auto';
+               }, this);
+
+               this.internalChain.clearChain();
+               this.internalChain.chain(function(){
+                       if (options.resetHeight && !this.selfHidden){
+                               var el = elements[index];
+                               if (el) el.setStyle('height', 'auto');
+                       }
+               }.bind(this));
+
+               return useFx ? this.start(obj) : this.set(obj).internalChain.callChain();
+       }
+
+});
+
+/*<1.2compat>*/
+/*
+       Compatibility with 1.2.0
+*/
+var Accordion = new Class({
+
+       Extends: Fx.Accordion,
+
+       initialize: function(){
+               this.parent.apply(this, arguments);
+               var params = Array.link(arguments, {'container': Type.isElement});
+               this.container = params.container;
+       },
+
+       addSection: function(toggler, element, pos){
+               toggler = document.id(toggler);
+               element = document.id(element);
+
+               var test = this.togglers.contains(toggler);
+               var len = this.togglers.length;
+               if (len && (!test || pos)){
+                       pos = pos != null ? pos : len - 1;
+                       toggler.inject(this.togglers[pos], 'before');
+                       element.inject(toggler, 'after');
+               } else if (this.container && !test){
+                       toggler.inject(this.container);
+                       element.inject(this.container);
+               }
+               return this.parent.apply(this, arguments);
+       }
+
+});
+/*</1.2compat>*/
+
+
+// Begin: Source/Types/Hash.js
+/*
+---
+
+name: Hash
+
+description: Contains Hash Prototypes. Provides a means for overcoming the JavaScript practical impossibility of extending native Objects.
+
+license: MIT-style license.
+
+requires:
+  - Core/Object
+  - /MooTools.More
+
+provides: [Hash]
+
+...
+*/
+
+(function(){
+
+if (this.Hash) return;
+
+var Hash = this.Hash = new Type('Hash', function(object){
+       if (typeOf(object) == 'hash') object = Object.clone(object.getClean());
+       for (var key in object) this[key] = object[key];
+       return this;
+});
+
+this.$H = function(object){
+       return new Hash(object);
+};
+
+Hash.implement({
+
+       forEach: function(fn, bind){
+               Object.forEach(this, fn, bind);
+       },
+
+       getClean: function(){
+               var clean = {};
+               for (var key in this){
+                       if (this.hasOwnProperty(key)) clean[key] = this[key];
+               }
+               return clean;
+       },
+
+       getLength: function(){
+               var length = 0;
+               for (var key in this){
+                       if (this.hasOwnProperty(key)) length++;
+               }
+               return length;
+       }
+
+});
+
+Hash.alias('each', 'forEach');
+
+Hash.implement({
+
+       has: Object.prototype.hasOwnProperty,
+
+       keyOf: function(value){
+               return Object.keyOf(this, value);
+       },
+
+       hasValue: function(value){
+               return Object.contains(this, value);
+       },
+
+       extend: function(properties){
+               Hash.each(properties || {}, function(value, key){
+                       Hash.set(this, key, value);
+               }, this);
+               return this;
+       },
+
+       combine: function(properties){
+               Hash.each(properties || {}, function(value, key){
+                       Hash.include(this, key, value);
+               }, this);
+               return this;
+       },
+
+       erase: function(key){
+               if (this.hasOwnProperty(key)) delete this[key];
+               return this;
+       },
+
+       get: function(key){
+               return (this.hasOwnProperty(key)) ? this[key] : null;
+       },
+
+       set: function(key, value){
+               if (!this[key] || this.hasOwnProperty(key)) this[key] = value;
+               return this;
+       },
+
+       empty: function(){
+               Hash.each(this, function(value, key){
+                       delete this[key];
+               }, this);
+               return this;
+       },
+
+       include: function(key, value){
+               if (this[key] == undefined) this[key] = value;
+               return this;
+       },
+
+       map: function(fn, bind){
+               return new Hash(Object.map(this, fn, bind));
+       },
+
+       filter: function(fn, bind){
+               return new Hash(Object.filter(this, fn, bind));
+       },
+
+       every: function(fn, bind){
+               return Object.every(this, fn, bind);
+       },
+
+       some: function(fn, bind){
+               return Object.some(this, fn, bind);
+       },
+
+       getKeys: function(){
+               return Object.keys(this);
+       },
+
+       getValues: function(){
+               return Object.values(this);
+       },
+
+       toQueryString: function(base){
+               return Object.toQueryString(this, base);
+       }
+
+});
+
+Hash.alias({indexOf: 'keyOf', contains: 'hasValue'});
+
+
+})();
+
+
+
+// Begin: Source/Utilities/Hash.Cookie.js
+/*
+---
+
+script: Hash.Cookie.js
+
+name: Hash.Cookie
+
+description: Class for creating, reading, and deleting Cookies in JSON format.
+
+license: MIT-style license
+
+authors:
+  - Valerio Proietti
+  - Aaron Newton
+
+requires:
+  - Core/Cookie
+  - Core/JSON
+  - /MooTools.More
+  - /Hash
+
+provides: [Hash.Cookie]
+
+...
+*/
+
+Hash.Cookie = new Class({
+
+       Extends: Cookie,
+
+       options: {
+               autoSave: true
+       },
+
+       initialize: function(name, options){
+               this.parent(name, options);
+               this.load();
+       },
+
+       save: function(){
+               var value = JSON.encode(this.hash);
+               if (!value || value.length > 4096) return false; //cookie would be truncated!
+               if (value == '{}') this.dispose();
+               else this.write(value);
+               return true;
+       },
+
+       load: function(){
+               this.hash = new Hash(JSON.decode(this.read(), true));
+               return this;
+       }
+
+});
+
+Hash.each(Hash.prototype, function(method, name){
+       if (typeof method == 'function') Hash.Cookie.implement(name, function(){
+               var value = method.apply(this.hash, arguments);
+               if (this.options.autoSave) this.save();
+               return value;
+       });
+});
+
+
+// Begin: Source/Utilities/Assets.js
+/*
+---
+
+script: Assets.js
+
+name: Assets
+
+description: Provides methods to dynamically load JavaScript, CSS, and Image files into the document.
+
+license: MIT-style license
+
+authors:
+  - Valerio Proietti
+
+requires:
+  - Core/Element.Event
+  - /MooTools.More
+
+provides: [Assets]
+
+...
+*/
+
+var Asset = {
+
+       javascript: function(source, properties){
+               if (!properties) properties = {};
+
+               var script = new Element('script', {src: source, type: 'text/javascript'}),
+                       doc = properties.document || document,
+                       load = properties.onload || properties.onLoad;
+
+               delete properties.onload;
+               delete properties.onLoad;
+               delete properties.document;
+
+               if (load){
+                       if (!script.addEventListener){
+                               script.addEvent('readystatechange', function(){
+                                       if (['loaded', 'complete'].contains(this.readyState)) load.call(this);
+                               });
+                       } else {
+                               script.addEvent('load', load);
+                       }
+               }
+
+               return script.set(properties).inject(doc.head);
+       },
+
+       css: function(source, properties){
+               if (!properties) properties = {};
+
+               var link = new Element('link', {
+                       rel: 'stylesheet',
+                       media: 'screen',
+                       type: 'text/css',
+                       href: source
+               });
+
+               var load = properties.onload || properties.onLoad,
+                       doc = properties.document || document;
+
+               delete properties.onload;
+               delete properties.onLoad;
+               delete properties.document;
+
+               if (load) link.addEvent('load', load);
+               return link.set(properties).inject(doc.head);
+       },
+
+       image: function(source, properties){
+               if (!properties) properties = {};
+
+               var image = new Image(),
+                       element = document.id(image) || new Element('img');
+
+               ['load', 'abort', 'error'].each(function(name){
+                       var type = 'on' + name,
+                               cap = 'on' + name.capitalize(),
+                               event = properties[type] || properties[cap] || function(){};
+
+                       delete properties[cap];
+                       delete properties[type];
+
+                       image[type] = function(){
+                               if (!image) return;
+                               if (!element.parentNode){
+                                       element.width = image.width;
+                                       element.height = image.height;
+                               }
+                               image = image.onload = image.onabort = image.onerror = null;
+                               event.delay(1, element, element);
+                               element.fireEvent(name, element, 1);
+                       };
+               });
+
+               image.src = element.src = source;
+               if (image && image.complete) image.onload.delay(1);
+               return element.set(properties);
+       },
+
+       images: function(sources, options){
+               sources = Array.from(sources);
+
+               var fn = function(){},
+                       counter = 0;
+
+               options = Object.merge({
+                       onComplete: fn,
+                       onProgress: fn,
+                       onError: fn,
+                       properties: {}
+               }, options);
+
+               return new Elements(sources.map(function(source, index){
+                       return Asset.image(source, Object.append(options.properties, {
+                               onload: function(){
+                                       counter++;
+                                       options.onProgress.call(this, counter, index, source);
+                                       if (counter == sources.length) options.onComplete();
+                               },
+                               onerror: function(){
+                                       counter++;
+                                       options.onError.call(this, counter, index, source);
+                                       if (counter == sources.length) options.onComplete();
+                               }
+                       }));
+               }));
+       }
+
+};
+
+
+// Begin: Source/Interface/Spinner.js
+/*
+---
+
+script: Spinner.js
+
+name: Spinner
+
+description: Adds a semi-transparent overlay over a dom element with a spinnin ajax icon.
+
+license: MIT-style license
+
+authors:
+  - Aaron Newton
+
+requires:
+  - Core/Fx.Tween
+  - Core/Request
+  - /Class.refactor
+  - /Mask
+
+provides: [Spinner]
+
+...
+*/
+
+var Spinner = new Class({
+
+       Extends: Mask,
+
+       Implements: Chain,
+
+       options: {/*
+               message: false,*/
+               'class': 'spinner',
+               containerPosition: {},
+               content: {
+                       'class': 'spinner-content'
+               },
+               messageContainer: {
+                       'class': 'spinner-msg'
+               },
+               img: {
+                       'class': 'spinner-img'
+               },
+               fxOptions: {
+                       link: 'chain'
+               }
+       },
+
+       initialize: function(target, options){
+               this.target = document.id(target) || document.id(document.body);
+               this.target.store('spinner', this);
+               this.setOptions(options);
+               this.render();
+               this.inject();
+
+               // Add this to events for when noFx is true; parent methods handle hide/show.
+               var deactivate = function(){ this.active = false; }.bind(this);
+               this.addEvents({
+                       hide: deactivate,
+                       show: deactivate
+               });
+       },
+
+       render: function(){
+               this.parent();
+
+               this.element.set('id', this.options.id || 'spinner-' + String.uniqueID());
+
+               this.content = document.id(this.options.content) || new Element('div', this.options.content);
+               this.content.inject(this.element);
+
+               if (this.options.message){
+                       this.msg = document.id(this.options.message) || new Element('p', this.options.messageContainer).appendText(this.options.message);
+                       this.msg.inject(this.content);
+               }
+
+               if (this.options.img){
+                       this.img = document.id(this.options.img) || new Element('div', this.options.img);
+                       this.img.inject(this.content);
+               }
+
+               this.element.set('tween', this.options.fxOptions);
+       },
+
+       show: function(noFx){
+               if (this.active) return this.chain(this.show.bind(this));
+               if (!this.hidden){
+                       this.callChain.delay(20, this);
+                       return this;
+               }
+
+               this.active = true;
+
+               return this.parent(noFx);
+       },
+
+       showMask: function(noFx){
+               var pos = function(){
+                       this.content.position(Object.merge({
+                               relativeTo: this.element
+                       }, this.options.containerPosition));
+               }.bind(this);
+
+               if (noFx){
+                       this.parent();
+                       pos();
+               } else {
+                       if (!this.options.style.opacity) this.options.style.opacity = this.element.getStyle('opacity').toFloat();
+                       this.element.setStyles({
+                               display: 'block',
+                               opacity: 0
+                       }).tween('opacity', this.options.style.opacity);
+                       pos();
+                       this.hidden = false;
+                       this.fireEvent('show');
+                       this.callChain();
+               }
+       },
+
+       hide: function(noFx){
+               if (this.active) return this.chain(this.hide.bind(this));
+               if (this.hidden){
+                       this.callChain.delay(20, this);
+                       return this;
+               }
+               this.active = true;
+               return this.parent(noFx);
+       },
+
+       hideMask: function(noFx){
+               if (noFx) return this.parent();
+               this.element.tween('opacity', 0).get('tween').chain(function(){
+                       this.element.setStyle('display', 'none');
+                       this.hidden = true;
+                       this.fireEvent('hide');
+                       this.callChain();
+               }.bind(this));
+       },
+
+       destroy: function(){
+               this.content.destroy();
+               this.parent();
+               this.target.eliminate('spinner');
+       }
+
+});
+
+Request = Class.refactor(Request, {
+
+       options: {
+               useSpinner: false,
+               spinnerOptions: {},
+               spinnerTarget: false
+       },
+
+       initialize: function(options){
+               this._send = this.send;
+               this.send = function(options){
+                       var spinner = this.getSpinner();
+                       if (spinner) spinner.chain(this._send.pass(options, this)).show();
+                       else this._send(options);
+                       return this;
+               };
+               this.previous(options);
+       },
+
+       getSpinner: function(){
+               if (!this.spinner){
+                       var update = document.id(this.options.spinnerTarget) || document.id(this.options.update);
+                       if (this.options.useSpinner && update){
+                               update.set('spinner', this.options.spinnerOptions);
+                               var spinner = this.spinner = update.get('spinner');
+                               ['complete', 'exception', 'cancel'].each(function(event){
+                                       this.addEvent(event, spinner.hide.bind(spinner));
+                               }, this);
+                       }
+               }
+               return this.spinner;
+       }
+
+});
+
+Element.Properties.spinner = {
+
+       set: function(options){
+               var spinner = this.retrieve('spinner');
+               if (spinner) spinner.destroy();
+               return this.eliminate('spinner').store('spinner:options', options);
+       },
+
+       get: function(){
+               var spinner = this.retrieve('spinner');
+               if (!spinner){
+                       spinner = new Spinner(this, this.retrieve('spinner:options'));
+                       this.store('spinner', spinner);
+               }
+               return spinner;
+       }
+
+};
+
+Element.implement({
+
+       spin: function(options){
+               if (options) this.set('spinner', options);
+               this.get('spinner').show();
+               return this;
+       },
+
+       unspin: function(){
+               this.get('spinner').hide();
+               return this;
+       }
+
+});
+
+
+// Begin: Source/Fx/Fx.Slide.js
+/*
+---
+
+script: Fx.Slide.js
+
+name: Fx.Slide
+
+description: Effect to slide an element in and out of view.
+
+license: MIT-style license
+
+authors:
+  - Valerio Proietti
+
+requires:
+  - Core/Fx
+  - Core/Element.Style
+  - /MooTools.More
+
+provides: [Fx.Slide]
+
+...
+*/
+
+Fx.Slide = new Class({
+
+       Extends: Fx,
+
+       options: {
+               mode: 'vertical',
+               wrapper: false,
+               hideOverflow: true,
+               resetHeight: false
+       },
+
+       initialize: function(element, options){
+               element = this.element = this.subject = document.id(element);
+               this.parent(options);
+               options = this.options;
+
+               var wrapper = element.retrieve('wrapper'),
+                       styles = element.getStyles('margin', 'position', 'overflow');
+
+               if (options.hideOverflow) styles = Object.append(styles, {overflow: 'hidden'});
+               if (options.wrapper) wrapper = document.id(options.wrapper).setStyles(styles);
+
+               if (!wrapper) wrapper = new Element('div', {
+                       styles: styles
+               }).wraps(element);
+
+               element.store('wrapper', wrapper).setStyle('margin', 0);
+               if (element.getStyle('overflow') == 'visible') element.setStyle('overflow', 'hidden');
+
+               this.now = [];
+               this.open = true;
+               this.wrapper = wrapper;
+
+               this.addEvent('complete', function(){
+                       this.open = (wrapper['offset' + this.layout.capitalize()] != 0);
+                       if (this.open && this.options.resetHeight) wrapper.setStyle('height', '');
+               }, true);
+       },
+
+       vertical: function(){
+               this.margin = 'margin-top';
+               this.layout = 'height';
+               this.offset = this.element.offsetHeight;
+       },
+
+       horizontal: function(){
+               this.margin = 'margin-left';
+               this.layout = 'width';
+               this.offset = this.element.offsetWidth;
+       },
+
+       set: function(now){
+               this.element.setStyle(this.margin, now[0]);
+               this.wrapper.setStyle(this.layout, now[1]);
+               return this;
+       },
+
+       compute: function(from, to, delta){
+               return [0, 1].map(function(i){
+                       return Fx.compute(from[i], to[i], delta);
+               });
+       },
+
+       start: function(how, mode){
+               if (!this.check(how, mode)) return this;
+               this[mode || this.options.mode]();
+
+               var margin = this.element.getStyle(this.margin).toInt(),
+                       layout = this.wrapper.getStyle(this.layout).toInt(),
+                       caseIn = [[margin, layout], [0, this.offset]],
+                       caseOut = [[margin, layout], [-this.offset, 0]],
+                       start;
+
+               switch (how){
+                       case 'in': start = caseIn; break;
+                       case 'out': start = caseOut; break;
+                       case 'toggle': start = (layout == 0) ? caseIn : caseOut;
+               }
+               return this.parent(start[0], start[1]);
+       },
+
+       slideIn: function(mode){
+               return this.start('in', mode);
+       },
+
+       slideOut: function(mode){
+               return this.start('out', mode);
+       },
+
+       hide: function(mode){
+               this[mode || this.options.mode]();
+               this.open = false;
+               return this.set([-this.offset, 0]);
+       },
+
+       show: function(mode){
+               this[mode || this.options.mode]();
+               this.open = true;
+               return this.set([0, this.offset]);
+       },
+
+       toggle: function(mode){
+               return this.start('toggle', mode);
+       }
+
+});
+
+Element.Properties.slide = {
+
+       set: function(options){
+               this.get('slide').cancel().setOptions(options);
+               return this;
+       },
+
+       get: function(){
+               var slide = this.retrieve('slide');
+               if (!slide){
+                       slide = new Fx.Slide(this, {link: 'cancel'});
+                       this.store('slide', slide);
+               }
+               return slide;
+       }
+
+};
+
+Element.implement({
+
+       slide: function(how, mode){
+               how = how || 'toggle';
+               var slide = this.get('slide'), toggle;
+               switch (how){
+                       case 'hide': slide.hide(mode); break;
+                       case 'show': slide.show(mode); break;
+                       case 'toggle':
+                               var flag = this.retrieve('slide:flag', slide.open);
+                               slide[flag ? 'slideOut' : 'slideIn'](mode);
+                               this.store('slide:flag', !flag);
+                               toggle = true;
+                       break;
+                       default: slide.start(how, mode);
+               }
+               if (!toggle) this.eliminate('slide:flag');
+               return this;
+       }
+
+});
+
+
+// Begin: Source/UI/StickyWin.UI.Pointy.js
+/*
+---
+name: StickyWin.UI.Pointy
+
+description: Creates an html holder for in-page popups using a default style - this one including a pointer in the specified direction.
+
+license: MIT-Style License
+
+requires: [More/Element.Shortcuts, More/Element.Position, StickyWin.UI]
+
+provides: [StickyWin.UI.Pointy, StickyWin.UI.pointy]
+...
+*/
+StickyWin.UI.Pointy = new Class({
+       Extends: StickyWin.UI,
+       options: {
+               theme: 'dark',
+               themes: {
+                       dark: {
+                               bgColor: '#333',
+                               fgColor: '#ddd',
+                               imgset: 'dark'
+                       },
+                       light: {
+                               bgColor: '#ccc',
+                               fgColor: '#333',
+                               imgset: 'light'
+                       }
+               },
+               css: "div.DefaultPointyTip {vertical-align: auto; position: relative;}"+
+               "div.DefaultPointyTip * {text-align:left !important}"+
+               "div.DefaultPointyTip .pointyWrapper div.body{background: {%bgColor%}; color: {%fgColor%}; left: 0px; right: 0px !important;padding:  0px 10px !important;margin-left: 0px !important;font-family: verdana;font-size: 11px;line-height: 13px;position: relative;}"+
+               "div.DefaultPointyTip .pointyWrapper div.top {position: relative;height: 25px; overflow: visible;}"+
+               "div.DefaultPointyTip .pointyWrapper div.top_ul{background: url({%baseHref%}{%imgset%}_back.png) top left no-repeat;width: 8px;height: 25px; position: absolute; left: 0px;}"+
+               "div.DefaultPointyTip .pointyWrapper div.top_ur{background: url({%baseHref%}{%imgset%}_back.png) top right !important;margin: 0 0 0 8px !important;height: 25px;position: relative;left: 0px !important;padding: 0;}"+
+               "div.DefaultPointyTip .pointyWrapper h1.caption{color: {%fgColor%};left: 0px !important;top: 4px !important;clear: none !important;overflow: hidden;font-weight: 700;font-size: 12px !important;position: relative;float: left;height: 22px !important;margin: 0 !important;padding: 0 !important;}"+
+               "div.DefaultPointyTip .pointyWrapper div.middle, div.DefaultPointyTip .pointyWrapper div.closeBody{background:  {%bgColor%};margin: 0 0px 0 0 !important;position: relative;top: 0 !important;}"+
+               "div.DefaultPointyTip .pointyWrapper div.middle {min-height: 16px; background:  {%bgColor%};margin: 0 0px 0 0 !important;position: relative;top: 0 !important;}"+
+               "div.DefaultPointyTip .pointyWrapper div.bottom {clear: both; width: 100% !important; background: none; height: 6px} "+
+               "div.DefaultPointyTip .pointyWrapper div.bottom_ll{font-size:1; background: url({%baseHref%}{%imgset%}_back.png) bottom left no-repeat;width: 6px;height: 6px;position: absolute; left: 0px;}"+
+               "div.DefaultPointyTip .pointyWrapper div.bottom_lr{font-size:1; background: url({%baseHref%}{%imgset%}_back.png) bottom right;height: 6px;margin: 0 0 0 6px !important;position: relative;left: 0 !important;}"+
+               "div.DefaultPointyTip .pointyWrapper div.noCaption{ height: 6px; overflow: hidden}"+
+               "div.DefaultPointyTip .pointyWrapper div.closeButton{width:13px; height:13px; background:url({%baseHref%}{%imgset%}_x.png) no-repeat; position: absolute; right: 0px; margin:0px !important; cursor:pointer; z-index: 1; top: 4px;}"+
+               "div.DefaultPointyTip .pointyWrapper div.pointyDivot {background: url({%divot%}) no-repeat;}",
+               divot: '{%baseHref%}{%imgset%}_divot.png',
+               divotSize: 22,
+               direction: 12,
+               cssId: 'defaultPointyTipStyle',
+               cssClassName: 'DefaultPointyTip'
+       },
+       initialize: function() {
+               var args = this.getArgs(arguments);
+               this.setOptions(args.options);
+               Object.append(this.options, this.options.themes[this.options.theme]);
+               this.options.baseHref = this.options.baseHref || Clientcide.assetLocation + '/PointyTip/';
+               this.options.divot = this.options.divot.substitute(this.options, /\\?\{%([^}]+)%\}/g);
+               if (Browser.ie) this.options.divot = this.options.divot.replace(/png/g, 'gif');
+               this.options.css = this.options.css.substitute(this.options, /\\?\{%([^}]+)%\}/g);
+               if (args.options && args.options.theme) {
+                       while (!this.id) {
+                               var id = Number.random(0, 999999999);
+                               if (!StickyWin.UI.Pointy[id]) {
+                                       StickyWin.UI.Pointy[id] = this;
+                                       this.id = id;
+                               }
+                       }
+                       this.options.css = this.options.css.replace(/div\.DefaultPointyTip/g, "div#pointy_"+this.id);
+                       this.options.cssId = "pointyTipStyle_" + this.id;
+               }
+               if (typeOf(this.options.direction) == 'string') {
+                       var map = {
+                               left: 9,
+                               right: 3,
+                               up: 12,
+                               down: 6
+                       };
+                       this.options.direction = map[this.options.direction];
+               }
+
+               this.parent(args.caption, args.body, this.options);
+               if (this.id) document.id(this).set('id', "pointy_"+this.id);
+       },
+       build: function(){
+               this.parent();
+               var opt = this.options;
+               this.pointyWrapper = new Element('div', {
+                       'class': 'pointyWrapper'
+               }).inject(document.id(this));
+               document.id(this).getChildren().each(function(el){
+                       if (el != this.pointyWrapper) this.pointyWrapper.grab(el);
+               }, this);
+
+               var w = opt.divotSize;
+               var h = w;
+               var left = (opt.width.toInt() - opt.divotSize)/2;
+               var orient = function(){
+                       switch(opt.direction) {
+                               case 12: case 1: case 11:
+                                       return {
+                                               height: h/2
+                                       };
+                               case 5: case 6: case 7:
+                                       return {
+                                               height: h/2,
+                                               backgroundPosition: '0 -'+h/2+'px'
+                                       };
+                               case 8: case 9: case 10:
+                                       return {
+                                               width: w/2
+                                       };
+                               case 2: case 3: case 4:
+                                       return {
+                                               width: w/2,
+                                               backgroundPosition: '100%'
+                                       };
+                       };
+               };
+               this.pointer = new Element('div', {
+                       styles: Object.append({
+                               width: w,
+                               height: h,
+                               overflow: 'hidden'
+                       }, orient()),
+                       'class': 'pointyDivot pointy_'+opt.direction
+               }).inject(this.pointyWrapper);
+       },
+       expose: function(){
+               if (document.id(this).getStyle('display') != 'none' &&
+                 document.body != document.id(this) &&
+                 document.id(document.body).contains(document.id(this))) return function(){};
+               document.id(this).setStyles({
+                       visibility: 'hidden',
+                       position: 'absolute'
+               });
+               var dispose;
+               if (document.body != document.id(this) && !document.body.contains(document.id(this))) {
+                       document.id(this).inject(document.body);
+                       dispose = true;
+               }
+               return (function(){
+                       if (dispose) document.id(this).dispose();
+                       document.id(this).setStyles({
+                               visibility: 'visible',
+                               position: 'relative'
+                       });
+               }).bind(this);
+       },
+       positionPointer: function(options){
+               if (!this.pointer) return;
+               var opt = options || this.options;
+               var pos;
+               var d = opt.direction;
+               switch (d){
+                       case 12: case 1: case 11:
+                               pos = {
+                                       edge: {x: 'center', y: 'bottom'},
+                                       position: {
+                                               x: d==12?'center':d==1?'right':'left',
+                                               y: 'top'
+                                       },
+                                       offset: {
+                                               x: (d==12?0:d==1?-1:1)*opt.divotSize,
+                                               y: 1
+                                       }
+                               };
+                               break;
+                       case 2: case 3: case 4:
+                               pos = {
+                                       edge: {x: 'left', y: 'center'},
+                                       position: {
+                                               x: 'right',
+                                               y: d==3?'center':d==2?'top':'bottom'
+                                       },
+                                       offset: {
+                                               x: -1,
+                                               y: (d==3?0:d==4?-1:1)*opt.divotSize
+                                       }
+                               };
+                               break;
+                       case 5: case 6: case 7:
+                               pos = {
+                                       edge: {x: 'center', y: 'top'},
+                                       position: {
+                                               x: d==6?'center':d==5?'right':'left',
+                                               y: 'bottom'
+                                       },
+                                       offset: {
+                                               x: (d==6?0:d==5?-1:1)*opt.divotSize,
+                                               y: -1
+                                       }
+                               };
+                               break;
+                       case 8: case 9: case 10:
+                               pos = {
+                                       edge: {x: 'right', y: 'center'},
+                                       position: {
+                                               x: 'left',
+                                               y: d==9?'center':d==10?'top':'bottom'
+                                       },
+                                       offset: {
+                                               x: 1,
+                                               y: (d==9?0:d==8?-1:1)*opt.divotSize
+                                       }
+                               };
+                               break;
+               };
+               var putItBack = this.expose();
+               this.pointer.position(Object.append({
+                       relativeTo: this.pointyWrapper,
+                       allowNegative: true
+               }, pos, options));
+               putItBack();
+       },
+       setContent: function(a1, a2){
+               this.parent(a1, a2);
+               this.top[this.h1?'removeClass':'addClass']('noCaption');
+               if (Browser.ie) document.id(this).getElements('.bottom_ll, .bottom_lr').setStyle('font-size', 1); //IE6 bullshit
+               if (this.options.closeButton) this.body.setStyle('margin-right', 6);
+               this.positionPointer();
+               return this;
+       },
+       makeCaption: function(caption){
+               this.parent(caption);
+               if (this.options.width && this.h1) this.h1.setStyle('width', (this.options.width.toInt()-(this.options.closeButton?25:15)));
+       }
+});
+
+StickyWin.UI.pointy = function(caption, body, options){
+       return document.id(new StickyWin.UI.Pointy(caption, body, options));
+};
+StickyWin.ui.pointy = StickyWin.UI.pointy;
+
+// Begin: Source/UI/StickyWin.PointyTip.js
+/*
+---
+name: StickyWin.PointyTip
+
+description: Positions a pointy tip relative to the element you specify.
+
+license: MIT-Style License
+
+requires: StickyWin.UI.Pointy
+
+provides: StickyWin.PointyTip
+
+...
+*/
+StickyWin.PointyTip = new Class({
+       Extends: StickyWin,
+       options: {
+               point: "left",
+               pointyOptions: {}
+       },
+       initialize: function(){
+               var args = this.getArgs(arguments);
+               this.setOptions(args.options);
+               var popts = this.options.pointyOptions;
+               var d = popts.direction;
+               if (!d) {
+                       var map = {
+                               left: 9,
+                               right: 3,
+                               up: 12,
+                               down: 6
+                       };
+                       d = map[this.options.point];
+                       if (!d) d = this.options.point;
+                       popts.direction = d;
+               }
+               if (!popts.width) popts.width = this.options.width;
+               this.pointy = new StickyWin.UI.Pointy(args.caption, args.body, popts);
+               this.options.content = null;
+               this.setOptions(args.options, this.getPositionSettings());
+               this.parent(this.options);
+               this.win.empty().adopt(document.id(this.pointy));
+               this.attachHandlers(this.win);
+               if (this.options.showNow) this.position();
+       },
+       getArgs: function(){
+               return StickyWin.UI.getArgs.apply(this, arguments);
+       },
+       getPositionSettings: function(){
+               var s = this.pointy.options.divotSize;
+               var d = this.options.point;
+               var offset = this.options.offset || {};
+               switch(d) {
+                       case "left": case 8: case 9: case 10:
+                               return {
+                                       edge: {
+                                               x: 'left',
+                                               y: d==10?'top':d==8?'bottom':'center'
+                                       },
+                                       position: {x: 'right', y: 'center'},
+                                       offset: {
+                                               x: s + (offset.x || 0),
+                                               y: offset.y || 0
+                                       }
+                               };
+                       case "right": case 2:  case 3: case 4:
+                               return {
+                                       edge: {
+                                               x: 'right',
+                                               y: (d==2?'top':d==4?'bottom':'center') + (offset.y || 0)
+                                       },
+                                       position: {x: 'left', y: 'center'},
+                                       offset: {
+                                               x: -s + (offset.x || 0),
+                                               y: offset.y || 0
+                                       }
+                               };
+                       case "up": case 11: case 12: case 1:
+                               return {
+                                       edge: {
+                                               x: d==11?'left':d==1?'right':'center',
+                                               y: 'top'
+                                       },
+                                       position: {     x: 'center', y: 'bottom' },
+                                       offset: {
+                                               y: s + (offset.y || 0),
+                                               x: (d==11?-s:d==1?s:0) + (offset.x || 0)
+                                       }
+                               };
+                       case "down": case 5: case 6: case 7:
+                               return {
+                                       edge: {
+                                               x: (d==7?'left':d==5?'right':'center') + (offset.x || 0),
+                                               y: 'bottom'
+                                       },
+                                       position: {x: 'center', y: 'top'},
+                                       offset: {
+                                               y: -s + (offset.y || 0),
+                                               x: (d==7?-s:d==5?s:0) + (offset.x || 0)
+                                       }
+                               };
+               };
+       },
+       setContent: function() {
+               var args = this.getArgs(arguments);
+               this.pointy.setContent(args.caption, args.body);
+               [this.pointy.h1, this.pointy.body].each(this.attachHandlers, this);
+               if (this.visible) this.position();
+               return this;
+       },
+       showWin: function(){
+               this.parent();
+               this.pointy.positionPointer();
+       },
+       position: function(options){
+               this.parent(options);
+               this.pointy.positionPointer();
+       },
+       attachHandlers: function(content) {
+               if (!content) return;
+               content.getElements('.'+this.options.closeClassName).addEvent('click', function(){ this.hide(); }.bind(this));
+               content.getElements('.'+this.options.pinClassName).addEvent('click', function(){ this.togglepin(); }.bind(this));
+       }
+});
+
+// Begin: Source/UI/StickyWin.Ajax.js
+/*
+---
+
+name: StickyWin.Ajax
+
+description: Adds ajax functionality to all the StickyWin classes.
+
+license: MIT-Style License
+
+requires: [Core/Request, StickyWin, StickyWin.UI, StickyWin.PointyTip]
+
+provides: [StickyWin.Ajax, StickyWin.Modal.Ajax, StickyWin.PointyTip.Ajax]
+
+...
+*/
+(function(){
+       var SWA = function(extend){
+               return {
+                       Extends: extend,
+                       options: {
+                               //onUpdate: function(){},
+                               url: '',
+                               showNow: false,
+                               cacheRequest: false,
+                               requestOptions: {
+                                       method: 'get',
+                                       evalScripts: true
+                               },
+                               wrapWithUi: false,
+                               caption: '',
+                               uiOptions:{},
+                               cacheRequest: false,
+                               handleResponse: function(response){
+                                       if(this.options.cacheRequest) {
+                                               this.element.store(this.Request.options.url, response);
+                                       }
+                                       var responseScript = "";
+                                       this.Request.response.text.stripScripts(function(script){       responseScript += script; });
+                                       if (this.options.wrapWithUi) response = StickyWin.ui(this.options.caption, response, this.options.uiOptions);
+                                       this.setContent(response);
+                                       this.show();
+                                       if (this.evalScripts) Browser.exec(responseScript);
+                                       this.fireEvent('update');
+                               }
+                       },
+                       initialize: function(options){
+                               var showNow;
+                               if (options && options.showNow) {
+                                       showNow = true;
+                                       options.showNow = false;
+                               }
+                               this.parent(options);
+                               this.evalScripts = this.options.requestOptions.evalScripts;
+                               this.options.requestOptions.evalScripts = false;
+                               this.createRequest();
+                               if (showNow) this.update();
+                       },
+                       createRequest: function(){
+                               this.Request = new Request(this.options.requestOptions).addEvent('onSuccess',
+                                       this.options.handleResponse.bind(this));
+                       },
+                       update: function(url, options){
+                               this.Request.options.url = url || options.url;
+                               var cachedResponse;
+                               if(this.options.cacheRequest) {
+                                       cachedResponse = this.element.retrieve(url);
+                               }
+                               if(!cachedResponse) {
+                                       this.Request.setOptions(options).send({url: url||this.options.url});
+                                       return this;
+                               } else {
+                                       this.Request.fireEvent('onSuccess', cachedResponse);
+                                       return this;
+                               }
+                       }
+               };
+       };
+       try { StickyWin.Ajax = new Class(SWA(StickyWin)); } catch(e){}
+       try { StickyWin.Modal.Ajax = new Class(SWA(StickyWin.Modal)); } catch(e){}
+       try { StickyWin.PointyTip.Ajax = new Class(SWA(StickyWin.PointyTip)); } catch(e){}
+})();
+
+// Begin: Source/Layout/MultipleOpenAccordion.js
+/*
+---
+name: MultipleOpenAccordion
+
+description: Creates a Mootools Fx.Accordion that allows the user to open more than one element.
+
+license: MIT-Style License
+
+requires: [Core/Element.Event, More/Fx.Reveal]
+
+provides: MultipleOpenAccordion
+
+...
+*/
+var MultipleOpenAccordion = new Class({
+       Implements: [Options, Events, Chain],
+       options: {
+               togglers: [],
+               elements: [],
+               openAll: false,
+               firstElementsOpen: [0],
+               fixedHeight: null,
+               fixedWidth: null,
+               height: true,
+               opacity: true,
+               width: false
+               //onActive: function(){},
+               //onBackground: function(){}
+       },
+       togglers: [],
+       elements: [],
+       initialize: function(options){
+               var args = Array.link(arguments, {options: Type.isObject, elements: Type.isElements});
+               this.setOptions(args.options);
+               elements = $$(this.options.elements);
+               $$(this.options.togglers).each(function(toggler, idx){
+                       this.addSection(toggler, elements[idx], idx);
+               }, this);
+               if (this.togglers.length) {
+                       if (this.options.openAll) this.showAll();
+                       else this.toggleSections(this.options.firstElementsOpen, false, true);
+               }
+               this.openSections = this.showSections.bind(this);
+               this.closeSections = this.hideSections.bind(this);
+       },
+       addSection: function(toggler, element){
+               toggler = document.id(toggler);
+               element = document.id(element);
+               var test = this.togglers.contains(toggler);
+               var len = this.togglers.length;
+               this.togglers.include(toggler);
+               this.elements.include(element);
+               var idx = this.togglers.indexOf(toggler);
+               var displayer = this.toggleSection.bind(this, idx);
+               toggler.addEvent('click', displayer).store('multipleOpenAccordion:display', displayer);
+               var mode;
+               if (this.options.height && this.options.width) mode = "both";
+               else mode = (this.options.height)?"vertical":"horizontal";
+               element.store('moa:reveal', new Fx.Reveal(element, {
+                       transitionOpacity: this.options.opacity,
+                       mode: mode,
+                       heightOverride: this.options.fixedHeight,
+                       widthOverride: this.options.fixedWidth
+               }));
+               return this;
+       },
+       removeSection: function(toggler) {
+               var idx = this.togglers.indexOf(toggler);
+               var element = this.elements[idx];
+               element.dissolve();
+               this.togglers.erase(toggler);
+               this.elements.erase(element);
+               this.detach(toggler);
+               return this;
+       },
+       detach: function(toggler){
+               var remove = function(toggler) {
+                       toggler.removeEvent(this.options.trigger, toggler.retrieve('multipleOpenAccordion:display'));
+               }.bind(this);
+               if (!toggler) this.togglers.each(remove);
+               else remove(toggler);
+               return this;
+       },
+       onComplete: function(idx, callChain){
+               this.fireEvent(this.elements[idx].isDisplayed()?'onActive':'onBackground', [this.togglers[idx], this.elements[idx]]);
+               this.callChain();
+               return this;
+       },
+       showSection: function(idx, useFx){
+               this.toggleSection(idx, useFx, true);
+       },
+       hideSection: function(idx, useFx){
+               this.toggleSection(idx, useFx, false);
+       },
+       toggleSection: function(idx, useFx, show, callChain){
+               var method = show?'reveal':show != null?'dissolve':'toggle';
+               callChain = [callChain, true].pick();
+               var el = this.elements[idx];
+               if (useFx != null ? useFx : true) {
+                       el.retrieve('moa:reveal')[method]().chain(
+                               this.onComplete.bind(this, idx, callChain)
+                       );
+               } else {
+                               if (method == "toggle") el.toggle();
+                               else el[method == "reveal"?'show':'hide']();
+                               this.onComplete(idx, callChain);
+               }
+               return this;
+       },
+       toggleAll: function(useFx, show){
+               var method = show?'reveal':(show!=null)?'disolve':'toggle';
+               var last = this.elements.getLast();
+               this.elements.each(function(el, idx){
+                       this.toggleSection(idx, useFx, show, el == last);
+               }, this);
+               return this;
+       },
+       toggleSections: function(sections, useFx, show) {
+               last = sections.getLast();
+               this.elements.each(function(el,idx){
+                       this.toggleSection(idx, useFx, sections.contains(idx)?show:!show, idx == last);
+               }, this);
+               return this;
+       },
+       showSections: function(sections, useFx){
+               sections.each(function(i){
+                       this.showSection(i, useFx);
+               }, this);
+       },
+       hideSections: function(sections, useFx){
+               sections.each(function(i){
+                       this.hideSection(i, useFx);
+               }, this);
+       },
+       showAll: function(useFx){
+               return this.toggleAll(useFx, true);
+       },
+       hideAll: function(useFx){
+               return this.toggleAll(useFx, false);
+       }
+});
+
+
diff --git a/plugins/debug_platform/__init__.py b/plugins/debug_platform/__init__.py
new file mode 100644 (file)
index 0000000..543fa5c
--- /dev/null
@@ -0,0 +1,34 @@
+from unfold.plugin       import Plugin
+from unfold.page         import Page
+from plugins.code_editor import CodeEditor
+from plugins.hazelnut    import Hazelnut
+
+class DebugPlatform(Plugin):
+
+    def template_file(self):
+        return "debug_platform.html"
+
+    def requirements (self):
+        reqs = {
+            'js_files' : [
+                'js/debug_platform.js',
+            ] ,
+            'css_files': [
+                'css/debug_platform.css',
+            ]
+        }
+        return reqs
+
+    def json_settings_list (self):
+        return ['plugin_uuid', 'domid']
+
+    def export_json_settings (self):
+        return True
+
+    def template_env (self, request):
+        # This part should be moved to a Layout
+        env = {}
+        env['topleft'] = CodeEditor(page=self.page, lineNumbers=True).render(request)
+        env['bottomleft'] = Hazelnut(page=self.page, columns=['dummy']).render(request)
+        return env
+
diff --git a/plugins/debug_platform/static/css/debug_platform.css b/plugins/debug_platform/static/css/debug_platform.css
new file mode 100644 (file)
index 0000000..30a6a67
--- /dev/null
@@ -0,0 +1,1017 @@
+*, html, body {
+  -webkit-font-smoothing: antialiased;
+}
+
+html {
+  height: 100%;
+}
+
+/*
+body {
+  font-family: "Helvetica", "Arial", "FreeSans", "Verdana", "Tahoma", "Lucida Sans", "Lucida Sans Unicode", "Luxi Sans", sans-serif;
+  background: #F6F6F6 url(../img/initializing.png) 50% 50% no-repeat;
+  overflow: hidden;
+  padding: 0;
+  margin: 0;
+  position: relative;
+  font-size: 14px;
+}
+
+@media
+(-webkit-min-device-pixel-ratio: 2),
+(min-resolution: 192dpi) {
+  body {
+    background: #F6F6F6 url(../img/initializing@2x.png) 50% 50% no-repeat;
+    background-size: 186px 157px;
+  }
+}
+*/
+
+body .CodeMirror * {
+  -webkit-font-smoothing: subpixel-antialiased;
+}
+
+#show-result #sidebar,
+#show-result #content {
+  transition: opacity .4s;
+  -moz-transition: opacity .4s;
+  -webkit-transition: opacity .4s;
+  -o-transition: opacity .4s;
+  -ms-transition: opacity .4s;
+  -webkit-transform: translateZ(0);
+  /*-moz-transform: translateZ(0);*/
+  opacity: 0;
+}
+
+
+/* content
+ ================================================================ */
+#content {
+  margin: 14px 15px 0 232px;
+  position: relative;
+  background: #F6F6F6;
+  height: 96%;
+}
+
+/* header
+ ================================================================ */
+#header {
+  height: 44px;
+  background: #3D6AA2;
+}
+
+#branding {
+  float: left;
+  width: 200px;
+  padding: 0 7px 0 10px;
+  font-size: 10px;
+  color: #fff;
+}
+
+#home {
+  display: block;
+  width: 200px;
+  height: 44px;
+  line-height: 44px;
+  background: transparent url(../img/logo.png) no-repeat 0 50%;
+  text-indent: 45px;
+  text-transform: uppercase;
+  color: #fff;
+  text-decoration: none;
+  font-size: 17px;
+  text-indent: -900em;
+}
+
+@media
+(-webkit-min-device-pixel-ratio: 2),
+(min-resolution: 192dpi) {
+  #home {
+    background: transparent url(../img/logo@2x.png) no-repeat 0 50%;
+    background-size: 136px 23px;
+  }
+}
+
+/* sidebar
+ ================================================================ */
+#sidebar {
+  padding: 0;
+  margin: 0;
+/*  font-size: 11px;*/
+  width: 217px;
+  position: absolute;
+/*  top: 45px;
+  left: 0;*/
+  background-color: #fff;
+  color: #444;
+  height: 100%;
+}
+
+  #sidebar h3 {
+    clear: both;
+    padding: 0;
+    font-size: 12px;
+    font-weight: bold;
+  }
+
+  #sidebar input[type='text'],
+  #sidebar input[type='password'],
+  #sidebar textarea {
+    width: 186px;
+    padding: 7px 5px;
+    color: #626262;
+    font-family: "Helvetica", "Arial", "FreeSans", "Verdana", "Tahoma", "Lucida Sans", "Lucida Sans Unicode", "Luxi Sans", sans-serif;
+    font-size: 1em;
+    background: #F6F6F6;
+    border: solid 1px #C0C0C0;
+    box-shadow: inset 0 1px 2px #e4e4e4;
+    border-radius: 2px;
+    outline: none;
+  }
+
+  #sidebar input[type='text'].warning {
+    border: solid 1px #e58b85;
+    background: #f6e4e3;
+  }
+
+  #sidebar textarea {
+    height: 40px;
+  }
+
+  #sidebar a {
+    color: #4679BD;
+  }
+
+  #sidebar p {
+    margin: 0 0 7px;
+    line-height: 160%;
+  }
+
+  #sidebar select {
+    width: 100%;
+    margin: 3px 0;
+  }
+
+  #sidebar pre,
+  #sidebar code {
+    padding: 0 2px;
+    font-family: "Monaco", "Andale Mono", "Lucida Console", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace;
+    font-size: .9em;
+    background: #fffadb;
+  }
+
+  #sidebar .element,
+  #sidebar .text {
+    margin: 0;
+  }
+
+/*
+  #sidebar label {
+    font-size: 11px;
+  }
+*/
+  #sidebar .element strong {
+    font-weight: bold;
+  }
+
+  #sidebar .elementBody {
+    padding-top: 0;
+    border-top-style: none;
+    padding-bottom: 0;
+    border-bottom-style: none;
+    overflow: hidden;
+    opacity: 0;
+    height: 0;
+  }
+
+  #sidebar .ebCont {
+    padding: 4px 8px 8px;
+  }
+
+    #sidebar .ebCont h3 {
+      font-size: 1em;
+      padding: 4px 0 2px;
+      color: #888;
+      border-top: 1px solid #EEEFEE;
+    }
+
+#sidebar .selectPanel {
+  position: relative;
+  height: 54px;
+}
+
+  #sidebar .selectPanel .panelChoice,
+  #sidebar .selectPanel .selectFake {
+    width: 92px;
+    position: absolute;
+  }
+
+  #sidebar .selectPanel .selectFake {
+    color: #999;
+    font-size: 1em;
+    line-height: 20px;
+  }
+
+  .panelChoice.html {
+    top: 0;
+    left: 0;
+  }
+
+  .panelChoice.css {
+    top: 0;
+    right: 0;
+  }
+
+  .panelChoice.js {
+    bottom: 0;
+    left: 0;
+  }
+
+  .panelChoice.result {
+    bottom: 0;
+    right: 0;
+  }
+
+#sidebar #id_title {
+}
+
+#sidebar .toggler {
+  color: #333;
+  height: 36px;
+  line-height: 36px;
+  padding: 0 8px;
+  font-size: 13px;
+  font-weight: normal;
+  position: relative;
+}
+
+  #sidebar .toggler em {
+    color: #AEAEAE;
+    font-style: normal;
+    font-size: .8em;
+    position: absolute;
+    top: 10px;
+    right: 10px;
+    background: #f1f1f1;
+    height: 16px;
+    padding: 0 4px;
+    line-height: 16px;
+    border-radius: 2px;
+  }
+
+
+  #sidebar .toggler.active {
+    color: #333;
+    font-weight: bold;
+  }
+
+  #sidebar .toggler.selected {
+  }
+
+  #sidebar .toggler,
+  #sidebar .element a {
+    cursor: pointer;
+    text-decoration: none;
+  }
+
+  #sidebar .element {
+    border-bottom: 1px solid #DFDFDF;
+  }
+
+  #sidebar .element a:hover {
+    text-decoration: underline;
+  }
+
+
+
+#shell_settings li {
+  margin: 5px 0;
+}
+
+#shell_settings li input {
+  margin-right: 3px;
+}
+
+#sidebar-bottom {
+   margin: 10px 0 10px 3px;
+
+}
+
+  #sidebar #share_links label,
+  #share_links_dropdown label {
+    display: block;
+    padding: 0 0 2px;
+    font-family: "Helvetica", "Arial", "FreeSans", "Verdana", "Tahoma", "Lucida Sans", "Lucida Sans Unicode", "Luxi Sans", sans-serif;
+    font-size: 11px;
+  }
+
+  #sidebar #share_links p,
+  #share_links_dropdown p {
+    margin: 0 0 7px;
+  }
+
+  #share_links_dropdown input {
+    width: 190px;
+    padding: 7px 5px;
+    color: #626262;
+    font-family: "Helvetica", "Arial", "FreeSans", "Verdana", "Tahoma", "Lucida Sans", "Lucida Sans Unicode", "Luxi Sans", sans-serif;
+    font-size: 1em;
+    border: solid 1px #C0C0C0;
+    background: #F6F6F6;
+    box-shadow: inset 0 1px 2px #e4e4e4;
+    border-radius: 2px;
+  }
+
+.libraryTagAttributes {
+   padding: 5px 0 0;
+}
+
+/* actions */
+#actions {
+  height: 44px;
+  font-size: 13px;
+}
+
+#actions ul.actionCont {
+  float: left;
+}
+
+  #actions ul.right {
+    float: right;
+  }
+
+  #actions li.actionItem {
+    float: left;
+    position: relative;
+    margin-right: 1px;
+  }
+
+  #actions li.actionItem .aiButton,
+  #actions li.actionItem .aiButton span,
+  #actions ul.dropdown li.actionItem a.aiButton {
+    height: 44px;
+  }
+
+  #actions li.actionItem a.aiButton {
+    display: block;
+    outline: none;
+    text-decoration: none;
+    color: #fff;
+    background: #355E95;
+    padding: 0 10px;
+  }
+
+  #actions li.actionItem a.aiButton span {
+    line-height: 44px;
+    margin-right: 6px;
+    font-size: .85em;
+  }
+
+  #actions li.noIcon a.aiButton span {
+    padding: 0 0 0 6px;
+    margin-right: 0;
+  }
+
+  #actions li.actionItem #mobile.aiButton span {
+    margin-right: 0;
+  }
+
+  #actions li.actionItem a.aiButton span.selected {
+    color: #555;
+    background: #fff;
+  }
+
+
+  #actions ul.dropdown .dropdownCont li {
+    line-height: 26px;
+  }
+
+  #actions ul.dropdown .dcWrapper a {
+    color: #4679BD;
+    text-decoration: none;
+  }
+
+  #actions ul.dropdown .dcWrapper a:hover {
+    text-decoration: underline;
+  }
+
+    #actions ul.dropdown .dropdownCont li a {
+      display: block;
+      text-decoration: none;
+      font-weight: bold;
+    }
+
+      #actions ul.dropdown .dropdownCont li a span {
+        margin: 0 6px;
+      }
+
+    #actions ul.dropdown .dropdownCont li a:hover {
+      background: #eee;
+    }
+
+  #actions ul.collapsed li.actionItem {
+  }
+
+  #actions ul.dropdown li.actionItem a.aiButton {
+  }
+
+    #actions ul.dropdown li.actionItem a.aiButton span {
+      padding: 0 0 0 6px;
+      margin-right: 0;
+    }
+
+  #actions #toggleSidebarUl {
+    position: absolute;
+    top: 0;
+    left: 165px;
+    margin-left: -40px;
+  }
+
+  #actions #toggleSidebar {
+    border-width: 0px;
+    display: none;
+    outline: none;
+    text-decoration: none;
+    text-shadow: 0;
+    color: #ffffff;
+    font-weight: bold;
+    font-size: 12px;
+    background: transparent;
+  }
+
+  #actions #toggleSidebar span {
+    text-indent: -999px;
+    padding: 0 8px;
+    width: 12px;
+  }
+
+  #actions #showjscode {
+    display: none;
+  }
+
+  #actions #collaborate sup {
+    background: rgba(0, 0, 0, 0.5);
+    border-radius: 2px;
+    vertical-align: middle;
+    opacity: 0.4;
+    font-size: .7em;
+    padding: 2px 3px;
+    text-transform: uppercase;
+
+  }
+
+/* select link */
+#select_link {
+  background: transparent url(../img/sprites.png) no-repeat 0 -254px;
+  color: #fdfdfd;
+  float: right;
+  width: 229px;
+  height: 27px;
+  margin: 6px 10px 0;
+  font-size: 13px;
+  padding-left: 15px;
+  line-height: 27px;
+}
+
+/* universal dropdown container
+ ================================================================ */
+div.dropdownCont {
+  position: absolute;
+  top: 44px;
+  right: -30px;
+  z-index: 200;
+  opacity: 0;
+  overflow: hidden;
+  padding: 0 30px 30px;
+}
+
+  div.dropdownCont div.dcWrapper {
+    background-color: #fff;
+    width: 200px;
+    padding: 10px;
+    margin: 0;
+    font-size: 13px;
+    box-shadow: 0 2px 30px rgba(0, 0, 0, 0.4);
+  }
+
+    #actions div.dropdownCont div.dcWrapper ul li a {
+      font-weight: normal;
+      color: #4679BD;
+      padding: 0;
+      line-height: 22px;
+    }
+
+    #actions div.dropdownCont div.dcWrapper ul li a:hover {
+      background: #fff;
+    }
+
+/* editor
+ ================================================================ */
+#content fieldset.column {
+  display: block;
+  height: 100%;
+  width: 50%;
+}
+
+#content .window {
+  width: 100%;
+  border: 1px solid #C0C0C0;
+  box-shadow: inset 0 1px 2px #e4e4e4;
+}
+
+  #content .top {
+    height: 25%;
+    position: absolute;
+    top: -6px;
+  }
+
+  #content .bottom {
+    height: 75%;
+    position: absolute;
+    bottom: -6px;
+  }
+
+  #content .right {
+    position: absolute;
+    right: -5px;
+  }
+
+  #content .left {
+    position: absolute;
+    left: -5px;
+  }
+
+  #handler_vertical {
+    width: 8px;
+    height: 100%;
+    padding: 5px 0;
+    cursor: col-resize;
+    position: absolute;
+    top: -5px;
+    left: 0;
+    background: url(../img/handle-v.png) 3px 50% no-repeat;
+
+  }
+
+  .handler_horizontal {
+    width: 100%;
+    height: 8px;
+    padding: 0 1px;
+    cursor: row-resize;
+    position: absolute;
+    top: 0;
+    left: 0;
+    background: url(../img/handle-h.png) 50% 3px no-repeat;
+  }
+
+  #content textarea,
+  #result iframe,
+  body.editbox {
+    min-width: 100px;
+    width: 100%;
+    height: 100%;
+    line-height: 15px;
+    font-family: "Monaco", "Andale Mono", "Lucida Console", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace;
+    font-size: 12px;
+  }
+
+  /* editors */
+  #content textarea,
+  #content iframe {
+    background: #fff;
+    box-shadow: inset 0 1px 3px #E4E4E4;
+    border: 0 !important;
+  }
+
+  /* resizing sets display to inline, this overrides */
+  #content textarea {
+    display: block;
+  }
+
+  .heyoffline_overlay {
+    z-index: 100;
+  }
+
+  /* editor labels */
+  .window_label {
+    border: solid 1px #F1F1F1;
+    background: #fff;
+    display: inline-block;
+    height: 22px;
+    padding: 0 6px;
+    line-height: 22px;
+    position: absolute;
+    top: 7px;
+    right: 6px;
+    text-align: center;
+    font-size: 12px;
+    color: #777;
+    border-radius: 1px;
+    z-index: 30;
+  }
+
+  /* fullscreen */
+  .fullscreen {
+    background: transparent url(../img/sprites.png) no-repeat -301px -320px;
+    display: block;
+    width: 31px;
+    height: 31px;
+    text-indent: -9999px;
+    z-index: 100;
+    position: absolute;
+    bottom: 6px;
+    right: 14px;
+    cursor: pointer;
+  }
+
+  /* we want editors to fill up all the space available */
+  .CodeMirror-wrapping {
+    width: 100%;
+    height: 100%;
+  }
+
+  /* shim to cover iframes when dragging */
+  .shim {
+    display: none;
+    width: 100%;
+    height: 100%;
+    z-index: 1;
+    position: absolute;
+    top: 0;
+    left: 0;
+  }
+
+/* external resources
+ ================================================================ */
+#sidebar #external-resources-form {
+  height: 30px;
+}
+
+  /* place resource button next to input */
+  #sidebar #external-resources-form #external_resource {
+    padding-right: 0px;
+    width: 160px;
+    float: left;
+    height: 14px;
+  }
+
+    /* custom style inputs/buttons */
+    #sidebar #external-resources-form .submit,
+    #sidebar .submit {
+      border: none;
+      border: solid 1px #EDEDED;
+      float: right;
+      height: 28px;
+      width: 28px;
+      padding: 0;
+      line-height: 31px;
+      text-align: center;
+      outline: none;
+      color: #333;
+    }
+
+    #sidebar #external-resources-form .submit:hover,
+    #sidebar .submit:hover {
+      text-decoration: none;
+    }
+
+    #sidebar .commonButton {
+      width: 70%;
+      float: none;
+      display: block;
+      line-height: 28px;
+      text-align: center;
+      color: #555;
+      font-size: 12px;
+      margin-top: 5px;
+    }
+
+
+/* share socially
+ ================================================================ */
+#share-social {
+
+}
+
+  #share-social li {
+  }
+
+  #actions .actionCont .dropdownCont #share-social a {
+    text-decoration: none;
+    margin-left: 5px;
+    display: inline;
+  }
+
+  #actions .actionCont .dropdownCont #share-social a:hover {
+    text-decoration: underline;
+  }
+
+  #share-social span {
+    color: #ccc;
+  }
+
+/* license text
+ ================================================================ */
+#documentation-info {
+  margin: 20px 8px 0;
+  color: #9A9A9A;
+}
+
+  #documentation-info p {
+    font-size: 1em;
+  }
+
+  #documentation-info a {
+    text-decoration: none;
+  }
+
+  #documentation-info a:hover {
+    text-decoration: underline;
+  }
+
+
+/* style the external resources list
+ ================================================================ */
+#sidebar #external_resources_list {
+}
+
+  #sidebar #external_resources_list li {
+    padding: 5px 0 3px;
+    position: relative;
+  }
+
+  #sidebar #external_resources_list li .filename {
+  }
+
+  #sidebar #external_resources_list li .remove {
+    position: absolute;
+    top: 7px;
+    right: 0;
+    display: block;
+    text-indent: -9000em;
+    width: 10px;
+    height: 10px;
+    background: url(../img/remove-resources.png) -10px 50% no-repeat;
+  }
+
+  #sidebar #external_resources_list li a.remove:hover {
+    background: url(../img/remove-resources.png) 0 50% no-repeat;
+  }
+
+  #add_external_resource {
+  }
+
+/* info box
+ ================================================================ */
+#info {
+  background: #FEFFE5;
+  padding: 7px;
+  border: 1px solid #EBBA95;
+  font-size: 11px;
+  color: #C98657;
+  margin: 7px 8px 10px;
+  line-height: 130%;
+  text-shadow: 0 1px 0 #FFF7F4;
+  position: relative;
+  display: none;
+
+  -moz-border-radius: 2px;
+  -webkit-border-radius: 2px;
+}
+
+  #info #info-close {
+    width: 10px;
+    height: 10px;
+    position: absolute;
+    top: 4px;
+    right: 4px;
+    text-indent: -900em;
+    display: block;
+    background: url(../img/info-close.png);
+    overflow: hidden;
+  }
+
+  #info a {
+    font-weight: bold;
+    color: #C98657;
+  }
+
+/* modal window
+ ================================================================ */
+#modal {
+  display: none;
+}
+
+.disqus_thread {
+  width: 600px;
+}
+
+  .disqus_thread .modalBody {
+    max-height: 500px;
+    min-height: 250px;
+    overflow: auto;
+    margin-bottom: 0 !important;
+  }
+
+.modal_jslint {
+  width: 500px;
+}
+
+.modal_kbd {
+  width: 500px;
+}
+
+.modal_confirmation {
+  width: 400px;
+}
+
+  .modal_jslint code,
+  .modal_Coffee .error,
+  .modal_jslint .evidence {
+    padding: 0 2px;
+    font-family: "Monaco", "Andale Mono", "Lucida Console", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace;
+    font-size: .9em;
+    background: #fffadb;
+  }
+
+    .modal_Coffee .error {
+        padding: 5px 10px;
+    }
+
+  .modal_jslint #errors {
+
+  }
+
+    .modal_jslint #errors p {
+      margin: 2px 0;
+    }
+
+  .modal_jslint p.evidence {
+    display: block;
+    margin-bottom: 10px !important;
+  }
+
+
+.modalWrap {
+  padding: 10px;
+  background: #fff;
+  z-index: 300;
+  font-size: 1em;
+  transition-duration: 0.2s;
+  transition-property: webkit-transform opacity;
+  transform: scale(0.94);
+
+  -webkit-transition-duration: 0.2s;
+  -webkit-transition-property: webkit-transform opacity;
+  -webkit-transform: scale(0.94);
+
+  -moz-transition-duration: 0.2s;
+  -moz-transition-property: moz-transform opacity;
+  -moz-transform: scale(0.94);
+
+  -o-transition-duration: 0.2s;
+  -o-transition-property: o-transform opacity;
+  -o-transform: scale(0.94);
+
+  -ms-transition-duration: 0.2s;
+  -ms-transition-property: ms-transform opacity;
+  -ms-transform: scale(0.94);
+
+  -webkit-transform: translateZ(0);
+  /*-moz-transform: translateZ(0);*/
+
+  opacity: 0;
+  box-shadow: 0 5px 50px rgba(0, 0, 0, 0.3);
+  border: solid 1px #ACB3B9;
+}
+
+.modalWrap.show {
+  opacity: 1;
+  transform: scale(1.0);
+  -webkit-transform: scale(1.0);
+  -moz-transform: scale(1.0);
+  -o-transform: scale(1.0);
+  -ms-transform: scale(1.0);
+}
+
+  .modalWrap .modalHeading {
+    position: relative;
+    height: 50px;
+  }
+
+    .modalWrap .modalHeading .close {
+      background: url(../img/modal/close.png) 0 0 no-repeat;
+      width: 15px;
+      height: 15px;
+      display: block;
+      position: absolute;
+      top: 8px;
+      right: 0;
+      text-indent: -9000em;
+      cursor: pointer;
+    }
+
+    .modalWrap .modalHeading h3 {
+      font-size: 1.6em;
+      padding: 6px 0;
+      cursor: default;
+    }
+
+  .modalWrap .modalBody {
+    position: relative;
+  }
+
+    .modalWrap .modalBody strong {
+      font-weight: bold;
+    }
+
+legend {
+  display: none;
+}
+
+.keyActions {
+  position: absolute;
+  bottom: 40px;
+  left: 8px;
+  display: block;
+  padding: 0 0 0 30px;
+  text-decoration: none;
+}
+
+  .keyActions:before {
+    content: '?';
+    position: absolute;
+    top: -1px;
+    left: 0;
+    display: block;
+    border: solid 1px #ABABAB;
+    padding: 0 8px;
+    border-radius: 2px;
+    font-family: 'Lucida Grande';
+    font-size: 10px;
+    color: #999;
+  }
+
+.keyActions:hover {
+  text-decoration: underline;
+}
+
+#kbd {
+}
+
+  #kbd li {
+    padding: 10px 0;
+    border-bottom: solid 1px #E6E6E6;
+  }
+
+  #kbd li:last-child {
+    padding: 10px 0 0;
+    border-bottom: none;
+  }
+
+  #kbd kbd {
+    border: solid 1px #ABABAB;
+    font-size: 10px;
+    font-family: 'Lucida Grande';
+    padding: 2px 3px;
+    border-radius: 3px;
+    color: #999;
+  }
+
+  #kbd span {
+    padding-left: 10px;
+  }
+
+.warningTooltip {
+  position: absolute;
+  bottom: 0;
+  left: 0;
+  background: rgba(255, 234, 147, 0.9);
+  font-size: .85em;
+  line-height: 1.5em;
+  color: #6c5517;
+  width: 100%;
+  z-index: 100;
+}
+
+  .warningTooltip code,
+  .warningTooltip strong {
+    font-weight: bold;
+  }
+
+  .warningTooltip li {
+    border-top: solid 1px #eddf97;
+    padding: 5px 8px;
+  }
+
+.gittip {
+  margin: 10px;
+  color: #949494;
+}
+
+.gittip iframe {
+  border: 0;
+  margin: 0 0 0 5px;
+  padding: 0;
+  opacity: 0.6;
+  vertical-align: middle;
+}
diff --git a/plugins/debug_platform/static/debug_platform.html b/plugins/debug_platform/static/debug_platform.html
new file mode 100644 (file)
index 0000000..7562ffe
--- /dev/null
@@ -0,0 +1,49 @@
+<div id='sidebar'>
+       <label>Platform:</label>
+       <select name='platform_name' id='platform_name'>
+               <optgroup label='SFA'>
+                       <option value='ple'>PLE</option>
+                       <option value='omf'>NITOS</option>
+                       <option value='senslab'>SENSLAB</option>
+               </optgroup>
+       </select>
+
+       <label>Authentication:</label>
+       <input type="radio" name="auth" value="myslice" checked>Use MANIFOLD default<br/>
+       <input type="radio" name="auth" value="myslice" disabled>Enter manually<br/>
+
+       <input id="" type="button" name="execute" value="Execute MANIFOLD query"/>
+       <input id="" type="button" name="execute" value="Execute platform query"/>
+</div>
+
+<div id='content'>
+       <fieldset class='column left'>
+               <div class='window top' id="panel_html" data-panel_type="html">
+                       <!-- <textarea id="id_code_html" rows="10" cols="40" name="code_html"></textarea>-->
+                       {{ topleft }}
+                       <span class='window_label'>HTML</span>
+               </div>
+               <div class='handler handler_horizontal'></div>
+               <div class='window bottom' id="panel_js" data-panel_type="js">
+                       <!--<textarea id="id_code_js" rows="10" cols="40" name="code_js"></textarea>-->
+                       {{ bottomleft }}
+                       <span class='window_label'>JavaScript</span>
+               </div>
+               <div class="shim"></div>
+       </fieldset>
+
+       <div class='handler' id='handler_vertical'></div>
+
+       <fieldset class='column right'>
+               <div class='window top' id="panel_css" data-panel_type="css">
+                       <textarea id="id_code_css" rows="10" cols="40" name="code_css"></textarea>
+                       <span class='window_label'>CSS</span>
+               </div>
+               <div class='handler handler_horizontal'></div>
+               <div id='result' class='window bottom'>
+                 <iframe name='result' frameBorder='0'></iframe>
+                       <span class='window_label'>Result</span>
+               </div>
+               <div class="shim"></div>
+       </fieldset>
+</div>
diff --git a/plugins/debug_platform/static/js/debug_platform.js b/plugins/debug_platform/static/js/debug_platform.js
new file mode 100644 (file)
index 0000000..cbbd0b7
--- /dev/null
@@ -0,0 +1,109 @@
+/**
+ * Description: DebugPlatform plugin
+ * Copyright (c) 2012 UPMC Sorbonne Universite - INRIA
+ * License: GPLv3
+ */
+
+/*
+ * It's a best practice to pass jQuery to an IIFE (Immediately Invoked Function
+ * Expression) that maps it to the dollar sign so it can't be overwritten by
+ * another library in the scope of its execution.
+ */
+
+(function($){
+
+    
+    // routing calls
+    jQuery.fn.DebugPlatform = function( method ) {
+               if ( methods[method] ) {
+                       return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
+               } else if ( typeof method === 'object' || ! method ) {
+                       return methods.init.apply( this, arguments );
+               } else {
+                       jQuery.error( 'Method ' +  method + ' does not exist on jQuery.DebugPlatform' );
+               }    
+    };
+
+    /***************************************************************************
+     * Public methods
+     ***************************************************************************/
+
+    var methods = {
+
+        /**
+         * @brief Plugin initialization
+         * @param options : an associative array of setting values
+         * @return : a jQuery collection of objects on which the plugin is
+         *     applied, which allows to maintain chainability of calls
+         */
+        init : function ( options ) {
+
+            var default_code_mirror_options = {
+              gutters: ["note-gutter", "CodeMirror-linenumbers"],
+              tabSize: 4,
+              indentUnit: 4,
+              matchBrackets: true,
+              lineNumbers: true,
+              lineWrapping: true,
+              tabMode: 'spaces' // or 'shift'
+            };
+
+            /* Default settings */
+            var options = $.extend( {
+                useCodeMirror: true,
+                codeMirrorOptions: default_code_mirror_options,
+                syntaxHighlighting: []
+            }, options);
+
+            return this.each(function() {
+
+                var $this = $(this);
+
+                /* An object that will hold private variables and methods */
+                var plugin = new DebugPlatform(options);
+                $this.data('Manifold', plugin);
+
+                /* Events */
+                $this.on('show.DebugPlatform', methods.show);
+
+                // This is the new plugin API meant to replace the weird publish_subscribe mechanism
+            }); // this.each
+        }, // init
+
+        /**
+         * @brief Plugin destruction
+         * @return : a jQuery collection of objects on which the plugin is
+         *     applied, which allows to maintain chainability of calls
+         */
+        destroy : function( ) {
+
+            return this.each(function() {
+                var $this = $(this);
+                var hazelnut = $this.data('Manifold');
+
+                // Unbind all events using namespacing
+                $(window).unbind('Manifold');
+
+                // Remove associated data
+                hazelnut.remove();
+                $this.removeData('Manifold');
+            });
+        }, // destroy
+
+    }; // var methods;
+
+    /***************************************************************************
+     * Plugin object
+     ***************************************************************************/
+
+    function DebugPlatform(options)
+    {
+        /* member variables */
+        this.options = options;
+
+        var object = this;
+
+    } // function DebugPlatform
+
+})( jQuery );
+
diff --git a/plugins/form/__init__.py b/plugins/form/__init__.py
new file mode 100644 (file)
index 0000000..ff569d5
--- /dev/null
@@ -0,0 +1,52 @@
+from unfold.composite import Composite
+from unfold.plugin    import Plugin
+
+class CreateForm (Plugin):
+
+    def __init__ (self, **settings):
+        Plugin.__init__(self, **settings)
+        print "SETTINGS", settings
+        assert 'page'   in settings, "You should specify page"
+        assert 'object' in settings, "You should specify object"
+
+        if 'object' in settings:
+            self.object = settings['object']
+
+        if 'fields' in settings:
+            self.fields = []
+            for field in settings['fields']:
+                c = {
+                    'name'          : field.get('name', ''),
+                    'field'         : field.get('field', ''),
+                    'type'          : field.get('type', 'input'),
+                    'description'   : field.get('description', ''),
+                    'validate_rx'   : field.get('validate_rx', ''),
+                    'validate_err'  : field.get('validate_err', ''),
+                    'old_value'     : 'POST',
+                }
+                self.fields.append(c)
+        else:
+            # Attempt to retrieve object fields from metadata
+            metadata = settings['page'].get_metadata()
+            md_o = metadata.details_by_object(settings['object'])
+            self.fields = md_o['column']
+    
+    def requirements (self):
+        # Some should be included by default by manifold
+        return { 'js_files'     : ['js/manifold.js', 'js/spin.presets.js', 'js/spin.min.js', 'js/jquery.spin.js',
+                                   'js/form.js', 'js/jquery.validate.js', ],
+                 'css_files'    : ['css/form.css'] 
+                 }
+    def export_json_settings(self):
+        # We need initialization, even though we are not associated with a query
+        return True
+
+    def template_env (self, request):
+        env={}
+        env.update(self.__dict__)
+        return env
+
+    def template_file (self):
+        return "form.html"
+
+    def json_settings_list (self): return ['plugin_uuid', 'object', 'fields']
diff --git a/plugins/form/static/css/form.css b/plugins/form/static/css/form.css
new file mode 100644 (file)
index 0000000..89fd941
--- /dev/null
@@ -0,0 +1,82 @@
+#commentForm {
+    margin:0 auto;
+    width:800px;
+    padding:10px;
+    font-size:12pt;
+    overflow:auto;
+    }    
+input {
+    border:2px solid #456879;
+    height: 22px;
+    width: 200px;
+    font-size: 10px;
+    }    
+label { 
+    float: left;
+    font-weight: bold;
+    text-align: right;
+    margin-right: 20px;
+    width: 200px;
+    display: inline-block;
+        
+}
+label.error { 
+    float: none;
+    color: red;
+    padding-left: .5em;
+    vertical-align: top;
+    font-size: 12px; 
+}
+p {
+    /*border-bottom:1px solid #B7DDF2;*/
+    color:#666666;
+    font-size:10px;
+    margin-bottom:20px;
+    padding-bottom:10px;
+}
+
+legend {
+    position: relative;
+    top: -2px;
+    background: cornsilk;
+    padding: 10px 100px;
+    border: 2px groove threedface;
+    border-top: none;
+    box-shadow: inset 0 -5px 5px rgba(0,0,0,.2);
+    text-shadow: 1px 1px 2px rgba(0,0,0,.3);
+    font-weight: bold;
+    font-size: 25px;
+    margin-left: 90px;
+}
+
+textarea:focus, input:focus {
+    border: 2px solid #900;
+}
+
+.required{
+    font-size:12pt;
+}
+.submit {
+    /* float:right; */
+    text-align: center;
+    margin-top: 15px;
+    margin-left: 180px;
+}
+.field {
+    padding:2px;
+}
+.hint{
+    display:none;
+    }
+.field:hover .hint {
+    position: absolute;
+    display: block;
+    margin: -30px 0 0 455px;
+    color: #FFFFFF;
+    padding: 7px 10px;
+    background: rgba(0, 0, 0, 0.6);
+    -moz-border-radius: 7px;
+    -webkit-border-radius: 7px;
+    border-radius: 7px;
+    }
diff --git a/plugins/form/static/form.html b/plugins/form/static/form.html
new file mode 100644 (file)
index 0000000..9fd413c
--- /dev/null
@@ -0,0 +1,19 @@
+<div id="form_plugin_{{domid}}">
+  <form class="cmxform" id="form_{{domid}}" method="post" action="#" enctype="multipart/form-data" onsubmit="return validate_form_{{domid}}(this)">
+    <fieldset>
+
+      {% for f in fields %}
+      <div class="field">
+        <label for="lname">{{f.name}}</label>
+        <input type="{{f.type}}" id="{{domid}}-{{f.field}}" name="{{f.field}}" size="25" class="required" minlength="2" value="{{f.old_value}}"/>
+        <p class="hint">{{f.description}}</p>
+        <span id='err-{{domid}}-{{f.field}}'><font color='red'>{{f.validation_err}}</font></span>
+      </div>
+      {% endfor %}
+
+    </fieldset>
+  </form>
+
+</div>
+
+
diff --git a/plugins/form/static/js/form.js b/plugins/form/static/js/form.js
new file mode 100644 (file)
index 0000000..b9d30d3
--- /dev/null
@@ -0,0 +1,135 @@
+/**
+ * Description: implements a form
+ * Copyright (c) 2013 UPMC Sorbonne Universite
+ * License: GPLv3
+ */
+
+/*
+ * It's a best practice to pass jQuery to an IIFE (Immediately Invoked Function
+ * Expression) that maps it to the dollar sign so it can't be overwritten by
+ * another library in the scope of its execution.
+ */
+(function($){
+
+    /***************************************************************************
+     * Method calling logic
+     ***************************************************************************/
+
+    $.fn.CreateForm = function( method ) {
+        if ( methods[method] ) {
+            return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
+        } else if ( typeof method === 'object' || ! method ) {
+            return methods.init.apply( this, arguments );
+        } else {
+            return undefined;
+            //$.error( 'Method ' +  method + ' does not exist on jQuery.CreateForm' );
+        }    
+    };
+
+    /***************************************************************************
+     * Public methods
+     ***************************************************************************/
+
+    var methods = {
+
+        /**
+         * @brief Plugin initialization
+         * @param options : an associative array of setting values
+         * @return : a jQuery collection of objects on which the plugin is
+         *     applied, which allows to maintain chainability of calls
+         */
+        init : function ( options ) {
+            return this.each(function() {
+                var $this = $(this);
+
+                /* An object that will hold private variables and methods */
+                var form = new CreateForm(options);
+                $this.data('plugin', form);
+
+            }); // this.each
+        }, // init
+
+    };
+
+    /***************************************************************************
+     * CreateForm object
+     ***************************************************************************/
+
+    function CreateForm(options) {
+
+        /* save a reference to this */
+        var $this = this;
+        var $obj  = $('#' + options.plugin_uuid);
+
+        /* member variables */
+        this.options = options;
+
+        /* methods */
+
+        /**
+         * \brief Validate the form
+         * \param validate_callback (function) a callback to be triggered when validation is done
+         * \return True if all fields match validation regex
+         */
+        this.validate = function(validate_callback) {
+            var frm = document.forms['form_'+options.plugin_uuid]
+
+            // $this = $('#' + options.plugin_uuid); // useless
+
+            // Loop on the fields and test regexp if present
+            var err = false;
+            var params = {}
+            $.each(options.fields, function(i, field) {
+                var value = frm.elements[field['field']].value;
+                var rx    = field['validate_rx'];
+                var str   = '';
+                if (rx && !value.match(rx)) {
+                    str = field['validate_err'];
+                    err = true;
+                }
+                params[field['field']] = value;
+                $('#err-' + options.plugin_uuid + '-' + field['field']).html(str);
+            });
+
+            /* If the form correctly validates, we issue a create query */
+            if (!err) {
+                var query = {
+                    'action': 'create',
+                    'object': options.object,
+                    'params': params,
+                };
+
+                /* Inform user about ongoing query: spinner */
+                this.enable(false);
+                manifold.spin($obj);
+
+                /* Issue json query and wait for callback */
+                manifold.forward(query, function(data) {
+                    manifold.spin($obj, false);
+                    if (data.code != 0) { // ERROR OR WARNING, which we don't expect
+                        alert("ERROR IN CALLING THE API");
+                        validate_callback(false);
+                        return;
+                    }
+                    validate_callback(true);
+                });
+            }
+
+            /* Note, if the create has already been done (or fails, or ... ?)
+             * shall we proceed to an update ? */
+
+            /* We always return false. Only the query callback is in charge of
+             * advancing to next step */
+            return false;
+        }
+
+        /**
+         * \brief Disable the form entirely, during a create query for example
+         */
+        this.enable = function(is_enabled) {
+
+        }
+
+    }
+
+})( jQuery );
diff --git a/plugins/form/static/js/jquery.validate.js b/plugins/form/static/js/jquery.validate.js
new file mode 100644 (file)
index 0000000..2a12cb3
--- /dev/null
@@ -0,0 +1,1220 @@
+/**
+ * jQuery Validation Plugin 1.11.0pre
+ *
+ * http://bassistance.de/jquery-plugins/jquery-plugin-validation/
+ * http://docs.jquery.com/Plugins/Validation
+ *
+ * Copyright 2013 Jörn Zaefferer
+ * Released under the MIT license:
+ *   http://www.opensource.org/licenses/mit-license.php
+ */
+
+(function($) {
+
+$.extend($.fn, {
+       // http://docs.jquery.com/Plugins/Validation/validate
+       validate: function( options ) {
+
+               // if nothing is selected, return nothing; can't chain anyway
+               if ( !this.length ) {
+                       if ( options && options.debug && window.console ) {
+                               console.warn( "Nothing selected, can't validate, returning nothing." );
+                       }
+                       return;
+               }
+
+               // check if a validator for this form was already created
+               var validator = $.data( this[0], "validator" );
+               if ( validator ) {
+                       return validator;
+               }
+
+               // Add novalidate tag if HTML5.
+               this.attr( "novalidate", "novalidate" );
+
+               validator = new $.validator( options, this[0] );
+               $.data( this[0], "validator", validator );
+
+               if ( validator.settings.onsubmit ) {
+
+                       this.validateDelegate( ":submit", "click", function( event ) {
+                               if ( validator.settings.submitHandler ) {
+                                       validator.submitButton = event.target;
+                               }
+                               // allow suppressing validation by adding a cancel class to the submit button
+                               if ( $(event.target).hasClass("cancel") ) {
+                                       validator.cancelSubmit = true;
+                               }
+                       });
+
+                       // validate the form on submit
+                       this.submit( function( event ) {
+                               if ( validator.settings.debug ) {
+                                       // prevent form submit to be able to see console output
+                                       event.preventDefault();
+                               }
+                               function handle() {
+                                       var hidden;
+                                       if ( validator.settings.submitHandler ) {
+                                               if ( validator.submitButton ) {
+                                                       // insert a hidden input as a replacement for the missing submit button
+                                                       hidden = $("<input type='hidden'/>").attr("name", validator.submitButton.name).val(validator.submitButton.value).appendTo(validator.currentForm);
+                                               }
+                                               validator.settings.submitHandler.call( validator, validator.currentForm, event );
+                                               if ( validator.submitButton ) {
+                                                       // and clean up afterwards; thanks to no-block-scope, hidden can be referenced
+                                                       hidden.remove();
+                                               }
+                                               return false;
+                                       }
+                                       return true;
+                               }
+
+                               // prevent submit for invalid forms or custom submit handlers
+                               if ( validator.cancelSubmit ) {
+                                       validator.cancelSubmit = false;
+                                       return handle();
+                               }
+                               if ( validator.form() ) {
+                                       if ( validator.pendingRequest ) {
+                                               validator.formSubmitted = true;
+                                               return false;
+                                       }
+                                       return handle();
+                               } else {
+                                       validator.focusInvalid();
+                                       return false;
+                               }
+                       });
+               }
+
+               return validator;
+       },
+       // http://docs.jquery.com/Plugins/Validation/valid
+       valid: function() {
+               if ( $(this[0]).is("form")) {
+                       return this.validate().form();
+               } else {
+                       var valid = true;
+                       var validator = $(this[0].form).validate();
+                       this.each(function() {
+                               valid &= validator.element(this);
+                       });
+                       return valid;
+               }
+       },
+       // attributes: space seperated list of attributes to retrieve and remove
+       removeAttrs: function( attributes ) {
+               var result = {},
+                       $element = this;
+               $.each(attributes.split(/\s/), function( index, value ) {
+                       result[value] = $element.attr(value);
+                       $element.removeAttr(value);
+               });
+               return result;
+       },
+       // http://docs.jquery.com/Plugins/Validation/rules
+       rules: function( command, argument ) {
+               var element = this[0];
+
+               if ( command ) {
+                       var settings = $.data(element.form, "validator").settings;
+                       var staticRules = settings.rules;
+                       var existingRules = $.validator.staticRules(element);
+                       switch(command) {
+                       case "add":
+                               $.extend(existingRules, $.validator.normalizeRule(argument));
+                               staticRules[element.name] = existingRules;
+                               if ( argument.messages ) {
+                                       settings.messages[element.name] = $.extend( settings.messages[element.name], argument.messages );
+                               }
+                               break;
+                       case "remove":
+                               if ( !argument ) {
+                                       delete staticRules[element.name];
+                                       return existingRules;
+                               }
+                               var filtered = {};
+                               $.each(argument.split(/\s/), function( index, method ) {
+                                       filtered[method] = existingRules[method];
+                                       delete existingRules[method];
+                               });
+                               return filtered;
+                       }
+               }
+
+               var data = $.validator.normalizeRules(
+               $.extend(
+                       {},
+                       $.validator.classRules(element),
+                       $.validator.attributeRules(element),
+                       $.validator.dataRules(element),
+                       $.validator.staticRules(element)
+               ), element);
+
+               // make sure required is at front
+               if ( data.required ) {
+                       var param = data.required;
+                       delete data.required;
+                       data = $.extend({required: param}, data);
+               }
+
+               return data;
+       }
+});
+
+// Custom selectors
+$.extend($.expr[":"], {
+       // http://docs.jquery.com/Plugins/Validation/blank
+       blank: function( a ) { return !$.trim("" + a.value); },
+       // http://docs.jquery.com/Plugins/Validation/filled
+       filled: function( a ) { return !!$.trim("" + a.value); },
+       // http://docs.jquery.com/Plugins/Validation/unchecked
+       unchecked: function( a ) { return !a.checked; }
+});
+
+// constructor for validator
+$.validator = function( options, form ) {
+       this.settings = $.extend( true, {}, $.validator.defaults, options );
+       this.currentForm = form;
+       this.init();
+};
+
+$.validator.format = function( source, params ) {
+       if ( arguments.length === 1 ) {
+               return function() {
+                       var args = $.makeArray(arguments);
+                       args.unshift(source);
+                       return $.validator.format.apply( this, args );
+               };
+       }
+       if ( arguments.length > 2 && params.constructor !== Array  ) {
+               params = $.makeArray(arguments).slice(1);
+       }
+       if ( params.constructor !== Array ) {
+               params = [ params ];
+       }
+       $.each(params, function( i, n ) {
+               source = source.replace( new RegExp("\\{" + i + "\\}", "g"), function() {
+                       return n;
+               });
+       });
+       return source;
+};
+
+$.extend($.validator, {
+
+       defaults: {
+               messages: {},
+               groups: {},
+               rules: {},
+               errorClass: "error",
+               validClass: "valid",
+               errorElement: "label",
+               focusInvalid: true,
+               errorContainer: $([]),
+               errorLabelContainer: $([]),
+               onsubmit: true,
+               ignore: ":hidden",
+               ignoreTitle: false,
+               onfocusin: function( element, event ) {
+                       this.lastActive = element;
+
+                       // hide error label and remove error class on focus if enabled
+                       if ( this.settings.focusCleanup && !this.blockFocusCleanup ) {
+                               if ( this.settings.unhighlight ) {
+                                       this.settings.unhighlight.call( this, element, this.settings.errorClass, this.settings.validClass );
+                               }
+                               this.addWrapper(this.errorsFor(element)).hide();
+                       }
+               },
+               onfocusout: function( element, event ) {
+                       if ( !this.checkable(element) && (element.name in this.submitted || !this.optional(element)) ) {
+                               this.element(element);
+                       }
+               },
+               onkeyup: function( element, event ) {
+                       if ( event.which === 9 && this.elementValue(element) === "" ) {
+                               return;
+                       } else if ( element.name in this.submitted || element === this.lastElement ) {
+                               this.element(element);
+                       }
+               },
+               onclick: function( element, event ) {
+                       // click on selects, radiobuttons and checkboxes
+                       if ( element.name in this.submitted ) {
+                               this.element(element);
+                       }
+                       // or option elements, check parent select in that case
+                       else if ( element.parentNode.name in this.submitted ) {
+                               this.element(element.parentNode);
+                       }
+               },
+               highlight: function( element, errorClass, validClass ) {
+                       if ( element.type === "radio" ) {
+                               this.findByName(element.name).addClass(errorClass).removeClass(validClass);
+                       } else {
+                               $(element).addClass(errorClass).removeClass(validClass);
+                       }
+               },
+               unhighlight: function( element, errorClass, validClass ) {
+                       if ( element.type === "radio" ) {
+                               this.findByName(element.name).removeClass(errorClass).addClass(validClass);
+                       } else {
+                               $(element).removeClass(errorClass).addClass(validClass);
+                       }
+               }
+       },
+
+       // http://docs.jquery.com/Plugins/Validation/Validator/setDefaults
+       setDefaults: function( settings ) {
+               $.extend( $.validator.defaults, settings );
+       },
+
+       messages: {
+               required: "This field is required.",
+               remote: "Please fix this field.",
+               email: "Please enter a valid email address.",
+               url: "Please enter a valid URL.",
+               date: "Please enter a valid date.",
+               dateISO: "Please enter a valid date (ISO).",
+               number: "Please enter a valid number.",
+               digits: "Please enter only digits.",
+               creditcard: "Please enter a valid credit card number.",
+               equalTo: "Please enter the same value again.",
+               maxlength: $.validator.format("Please enter no more than {0} characters."),
+               minlength: $.validator.format("Please enter at least {0} characters."),
+               rangelength: $.validator.format("Please enter a value between {0} and {1} characters long."),
+               range: $.validator.format("Please enter a value between {0} and {1}."),
+               max: $.validator.format("Please enter a value less than or equal to {0}."),
+               min: $.validator.format("Please enter a value greater than or equal to {0}.")
+       },
+
+       autoCreateRanges: false,
+
+       prototype: {
+
+               init: function() {
+                       this.labelContainer = $(this.settings.errorLabelContainer);
+                       this.errorContext = this.labelContainer.length && this.labelContainer || $(this.currentForm);
+                       this.containers = $(this.settings.errorContainer).add( this.settings.errorLabelContainer );
+                       this.submitted = {};
+                       this.valueCache = {};
+                       this.pendingRequest = 0;
+                       this.pending = {};
+                       this.invalid = {};
+                       this.reset();
+
+                       var groups = (this.groups = {});
+                       $.each(this.settings.groups, function( key, value ) {
+                               if ( typeof value === "string" ) {
+                                       value = value.split(/\s/);
+                               }
+                               $.each(value, function( index, name ) {
+                                       groups[name] = key;
+                               });
+                       });
+                       var rules = this.settings.rules;
+                       $.each(rules, function( key, value ) {
+                               rules[key] = $.validator.normalizeRule(value);
+                       });
+
+                       function delegate(event) {
+                               var validator = $.data(this[0].form, "validator"),
+                                       eventType = "on" + event.type.replace(/^validate/, "");
+                               if ( validator.settings[eventType] ) {
+                                       validator.settings[eventType].call(validator, this[0], event);
+                               }
+                       }
+                       $(this.currentForm)
+                               .validateDelegate(":text, [type='password'], [type='file'], select, textarea, " +
+                                       "[type='number'], [type='search'] ,[type='tel'], [type='url'], " +
+                                       "[type='email'], [type='datetime'], [type='date'], [type='month'], " +
+                                       "[type='week'], [type='time'], [type='datetime-local'], " +
+                                       "[type='range'], [type='color'] ",
+                                       "focusin focusout keyup", delegate)
+                               .validateDelegate("[type='radio'], [type='checkbox'], select, option", "click", delegate);
+
+                       if ( this.settings.invalidHandler ) {
+                               $(this.currentForm).bind("invalid-form.validate", this.settings.invalidHandler);
+                       }
+               },
+
+               // http://docs.jquery.com/Plugins/Validation/Validator/form
+               form: function() {
+                       this.checkForm();
+                       $.extend(this.submitted, this.errorMap);
+                       this.invalid = $.extend({}, this.errorMap);
+                       if ( !this.valid() ) {
+                               $(this.currentForm).triggerHandler("invalid-form", [this]);
+                       }
+                       this.showErrors();
+                       return this.valid();
+               },
+
+               checkForm: function() {
+                       this.prepareForm();
+                       for ( var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++ ) {
+                               this.check( elements[i] );
+                       }
+                       return this.valid();
+               },
+
+               // http://docs.jquery.com/Plugins/Validation/Validator/element
+               element: function( element ) {
+                       element = this.validationTargetFor( this.clean( element ) );
+                       this.lastElement = element;
+                       this.prepareElement( element );
+                       this.currentElements = $(element);
+                       var result = this.check( element ) !== false;
+                       if ( result ) {
+                               delete this.invalid[element.name];
+                       } else {
+                               this.invalid[element.name] = true;
+                       }
+                       if ( !this.numberOfInvalids() ) {
+                               // Hide error containers on last error
+                               this.toHide = this.toHide.add( this.containers );
+                       }
+                       this.showErrors();
+                       return result;
+               },
+
+               // http://docs.jquery.com/Plugins/Validation/Validator/showErrors
+               showErrors: function( errors ) {
+                       if ( errors ) {
+                               // add items to error list and map
+                               $.extend( this.errorMap, errors );
+                               this.errorList = [];
+                               for ( var name in errors ) {
+                                       this.errorList.push({
+                                               message: errors[name],
+                                               element: this.findByName(name)[0]
+                                       });
+                               }
+                               // remove items from success list
+                               this.successList = $.grep( this.successList, function( element ) {
+                                       return !(element.name in errors);
+                               });
+                       }
+                       if ( this.settings.showErrors ) {
+                               this.settings.showErrors.call( this, this.errorMap, this.errorList );
+                       } else {
+                               this.defaultShowErrors();
+                       }
+               },
+
+               // http://docs.jquery.com/Plugins/Validation/Validator/resetForm
+               resetForm: function() {
+                       if ( $.fn.resetForm ) {
+                               $(this.currentForm).resetForm();
+                       }
+                       this.submitted = {};
+                       this.lastElement = null;
+                       this.prepareForm();
+                       this.hideErrors();
+                       this.elements().removeClass( this.settings.errorClass ).removeData( "previousValue" );
+               },
+
+               numberOfInvalids: function() {
+                       return this.objectLength(this.invalid);
+               },
+
+               objectLength: function( obj ) {
+                       var count = 0;
+                       for ( var i in obj ) {
+                               count++;
+                       }
+                       return count;
+               },
+
+               hideErrors: function() {
+                       this.addWrapper( this.toHide ).hide();
+               },
+
+               valid: function() {
+                       return this.size() === 0;
+               },
+
+               size: function() {
+                       return this.errorList.length;
+               },
+
+               focusInvalid: function() {
+                       if ( this.settings.focusInvalid ) {
+                               try {
+                                       $(this.findLastActive() || this.errorList.length && this.errorList[0].element || [])
+                                       .filter(":visible")
+                                       .focus()
+                                       // manually trigger focusin event; without it, focusin handler isn't called, findLastActive won't have anything to find
+                                       .trigger("focusin");
+                               } catch(e) {
+                                       // ignore IE throwing errors when focusing hidden elements
+                               }
+                       }
+               },
+
+               findLastActive: function() {
+                       var lastActive = this.lastActive;
+                       return lastActive && $.grep(this.errorList, function( n ) {
+                               return n.element.name === lastActive.name;
+                       }).length === 1 && lastActive;
+               },
+
+               elements: function() {
+                       var validator = this,
+                               rulesCache = {};
+
+                       // select all valid inputs inside the form (no submit or reset buttons)
+                       return $(this.currentForm)
+                       .find("input, select, textarea")
+                       .not(":submit, :reset, :image, [disabled]")
+                       .not( this.settings.ignore )
+                       .filter(function() {
+                               if ( !this.name ) {
+                                       if ( window.console ) {
+                                               console.error( "%o has no name assigned", this );
+                                       }
+                                       throw new Error( "Failed to validate, found an element with no name assigned. See console for element reference." );
+                               }
+
+                               // select only the first element for each name, and only those with rules specified
+                               if ( this.name in rulesCache || !validator.objectLength($(this).rules()) ) {
+                                       return false;
+                               }
+
+                               rulesCache[this.name] = true;
+                               return true;
+                       });
+               },
+
+               clean: function( selector ) {
+                       return $(selector)[0];
+               },
+
+               errors: function() {
+                       var errorClass = this.settings.errorClass.replace(" ", ".");
+                       return $(this.settings.errorElement + "." + errorClass, this.errorContext);
+               },
+
+               reset: function() {
+                       this.successList = [];
+                       this.errorList = [];
+                       this.errorMap = {};
+                       this.toShow = $([]);
+                       this.toHide = $([]);
+                       this.currentElements = $([]);
+               },
+
+               prepareForm: function() {
+                       this.reset();
+                       this.toHide = this.errors().add( this.containers );
+               },
+
+               prepareElement: function( element ) {
+                       this.reset();
+                       this.toHide = this.errorsFor(element);
+               },
+
+               elementValue: function( element ) {
+                       var type = $(element).attr("type"),
+                               val = $(element).val();
+
+                       if ( type === "radio" || type === "checkbox" ) {
+                               return $("input[name='" + $(element).attr("name") + "']:checked").val();
+                       }
+
+                       if ( typeof val === "string" ) {
+                               return val.replace(/\r/g, "");
+                       }
+                       return val;
+               },
+
+               check: function( element ) {
+                       element = this.validationTargetFor( this.clean( element ) );
+
+                       var rules = $(element).rules();
+                       var dependencyMismatch = false;
+                       var val = this.elementValue(element);
+                       var result;
+
+                       for (var method in rules ) {
+                               var rule = { method: method, parameters: rules[method] };
+                               try {
+
+                                       result = $.validator.methods[method].call( this, val, element, rule.parameters );
+
+                                       // if a method indicates that the field is optional and therefore valid,
+                                       // don't mark it as valid when there are no other rules
+                                       if ( result === "dependency-mismatch" ) {
+                                               dependencyMismatch = true;
+                                               continue;
+                                       }
+                                       dependencyMismatch = false;
+
+                                       if ( result === "pending" ) {
+                                               this.toHide = this.toHide.not( this.errorsFor(element) );
+                                               return;
+                                       }
+
+                                       if ( !result ) {
+                                               this.formatAndAdd( element, rule );
+                                               return false;
+                                       }
+                               } catch(e) {
+                                       if ( this.settings.debug && window.console ) {
+                                               console.log( "Exception occured when checking element " + element.id + ", check the '" + rule.method + "' method.", e );
+                                       }
+                                       throw e;
+                               }
+                       }
+                       if ( dependencyMismatch ) {
+                               return;
+                       }
+                       if ( this.objectLength(rules) ) {
+                               this.successList.push(element);
+                       }
+                       return true;
+               },
+
+               // return the custom message for the given element and validation method
+               // specified in the element's HTML5 data attribute
+               customDataMessage: function( element, method ) {
+                       return $(element).data("msg-" + method.toLowerCase()) || (element.attributes && $(element).attr("data-msg-" + method.toLowerCase()));
+               },
+
+               // return the custom message for the given element name and validation method
+               customMessage: function( name, method ) {
+                       var m = this.settings.messages[name];
+                       return m && (m.constructor === String ? m : m[method]);
+               },
+
+               // return the first defined argument, allowing empty strings
+               findDefined: function() {
+                       for(var i = 0; i < arguments.length; i++) {
+                               if ( arguments[i] !== undefined ) {
+                                       return arguments[i];
+                               }
+                       }
+                       return undefined;
+               },
+
+               defaultMessage: function( element, method ) {
+                       return this.findDefined(
+                               this.customMessage( element.name, method ),
+                               this.customDataMessage( element, method ),
+                               // title is never undefined, so handle empty string as undefined
+                               !this.settings.ignoreTitle && element.title || undefined,
+                               $.validator.messages[method],
+                               "<strong>Warning: No message defined for " + element.name + "</strong>"
+                       );
+               },
+
+               formatAndAdd: function( element, rule ) {
+                       var message = this.defaultMessage( element, rule.method ),
+                               theregex = /\$?\{(\d+)\}/g;
+                       if ( typeof message === "function" ) {
+                               message = message.call(this, rule.parameters, element);
+                       } else if (theregex.test(message)) {
+                               message = $.validator.format(message.replace(theregex, "{$1}"), rule.parameters);
+                       }
+                       this.errorList.push({
+                               message: message,
+                               element: element
+                       });
+
+                       this.errorMap[element.name] = message;
+                       this.submitted[element.name] = message;
+               },
+
+               addWrapper: function( toToggle ) {
+                       if ( this.settings.wrapper ) {
+                               toToggle = toToggle.add( toToggle.parent( this.settings.wrapper ) );
+                       }
+                       return toToggle;
+               },
+
+               defaultShowErrors: function() {
+                       var i, elements;
+                       for ( i = 0; this.errorList[i]; i++ ) {
+                               var error = this.errorList[i];
+                               if ( this.settings.highlight ) {
+                                       this.settings.highlight.call( this, error.element, this.settings.errorClass, this.settings.validClass );
+                               }
+                               this.showLabel( error.element, error.message );
+                       }
+                       if ( this.errorList.length ) {
+                               this.toShow = this.toShow.add( this.containers );
+                       }
+                       if ( this.settings.success ) {
+                               for ( i = 0; this.successList[i]; i++ ) {
+                                       this.showLabel( this.successList[i] );
+                               }
+                       }
+                       if ( this.settings.unhighlight ) {
+                               for ( i = 0, elements = this.validElements(); elements[i]; i++ ) {
+                                       this.settings.unhighlight.call( this, elements[i], this.settings.errorClass, this.settings.validClass );
+                               }
+                       }
+                       this.toHide = this.toHide.not( this.toShow );
+                       this.hideErrors();
+                       this.addWrapper( this.toShow ).show();
+               },
+
+               validElements: function() {
+                       return this.currentElements.not(this.invalidElements());
+               },
+
+               invalidElements: function() {
+                       return $(this.errorList).map(function() {
+                               return this.element;
+                       });
+               },
+
+               showLabel: function( element, message ) {
+                       var label = this.errorsFor( element );
+                       if ( label.length ) {
+                               // refresh error/success class
+                               label.removeClass( this.settings.validClass ).addClass( this.settings.errorClass );
+
+                               // check if we have a generated label, replace the message then
+                               if ( label.attr("generated") ) {
+                                       label.html(message);
+                               }
+                       } else {
+                               // create label
+                               label = $("<" + this.settings.errorElement + "/>")
+                                       .attr({"for":  this.idOrName(element), generated: true})
+                                       .addClass(this.settings.errorClass)
+                                       .html(message || "");
+                               if ( this.settings.wrapper ) {
+                                       // make sure the element is visible, even in IE
+                                       // actually showing the wrapped element is handled elsewhere
+                                       label = label.hide().show().wrap("<" + this.settings.wrapper + "/>").parent();
+                               }
+                               if ( !this.labelContainer.append(label).length ) {
+                                       if ( this.settings.errorPlacement ) {
+                                               this.settings.errorPlacement(label, $(element) );
+                                       } else {
+                                               label.insertAfter(element);
+                                       }
+                               }
+                       }
+                       if ( !message && this.settings.success ) {
+                               label.text("");
+                               if ( typeof this.settings.success === "string" ) {
+                                       label.addClass( this.settings.success );
+                               } else {
+                                       this.settings.success( label, element );
+                               }
+                       }
+                       this.toShow = this.toShow.add(label);
+               },
+
+               errorsFor: function( element ) {
+                       var name = this.idOrName(element);
+                       return this.errors().filter(function() {
+                               return $(this).attr("for") === name;
+                       });
+               },
+
+               idOrName: function( element ) {
+                       return this.groups[element.name] || (this.checkable(element) ? element.name : element.id || element.name);
+               },
+
+               validationTargetFor: function( element ) {
+                       // if radio/checkbox, validate first element in group instead
+                       if ( this.checkable(element) ) {
+                               element = this.findByName( element.name ).not(this.settings.ignore)[0];
+                       }
+                       return element;
+               },
+
+               checkable: function( element ) {
+                       return (/radio|checkbox/i).test(element.type);
+               },
+
+               findByName: function( name ) {
+                       return $(this.currentForm).find("[name='" + name + "']");
+               },
+
+               getLength: function( value, element ) {
+                       switch( element.nodeName.toLowerCase() ) {
+                       case "select":
+                               return $("option:selected", element).length;
+                       case "input":
+                               if ( this.checkable( element) ) {
+                                       return this.findByName(element.name).filter(":checked").length;
+                               }
+                       }
+                       return value.length;
+               },
+
+               depend: function( param, element ) {
+                       return this.dependTypes[typeof param] ? this.dependTypes[typeof param](param, element) : true;
+               },
+
+               dependTypes: {
+                       "boolean": function( param, element ) {
+                               return param;
+                       },
+                       "string": function( param, element ) {
+                               return !!$(param, element.form).length;
+                       },
+                       "function": function( param, element ) {
+                               return param(element);
+                       }
+               },
+
+               optional: function( element ) {
+                       var val = this.elementValue(element);
+                       return !$.validator.methods.required.call(this, val, element) && "dependency-mismatch";
+               },
+
+               startRequest: function( element ) {
+                       if ( !this.pending[element.name] ) {
+                               this.pendingRequest++;
+                               this.pending[element.name] = true;
+                       }
+               },
+
+               stopRequest: function( element, valid ) {
+                       this.pendingRequest--;
+                       // sometimes synchronization fails, make sure pendingRequest is never < 0
+                       if ( this.pendingRequest < 0 ) {
+                               this.pendingRequest = 0;
+                       }
+                       delete this.pending[element.name];
+                       if ( valid && this.pendingRequest === 0 && this.formSubmitted && this.form() ) {
+                               $(this.currentForm).submit();
+                               this.formSubmitted = false;
+                       } else if (!valid && this.pendingRequest === 0 && this.formSubmitted) {
+                               $(this.currentForm).triggerHandler("invalid-form", [this]);
+                               this.formSubmitted = false;
+                       }
+               },
+
+               previousValue: function( element ) {
+                       return $.data(element, "previousValue") || $.data(element, "previousValue", {
+                               old: null,
+                               valid: true,
+                               message: this.defaultMessage( element, "remote" )
+                       });
+               }
+
+       },
+
+       classRuleSettings: {
+               required: {required: true},
+               email: {email: true},
+               url: {url: true},
+               date: {date: true},
+               dateISO: {dateISO: true},
+               number: {number: true},
+               digits: {digits: true},
+               creditcard: {creditcard: true}
+       },
+
+       addClassRules: function( className, rules ) {
+               if ( className.constructor === String ) {
+                       this.classRuleSettings[className] = rules;
+               } else {
+                       $.extend(this.classRuleSettings, className);
+               }
+       },
+
+       classRules: function( element ) {
+               var rules = {};
+               var classes = $(element).attr("class");
+               if ( classes ) {
+                       $.each(classes.split(" "), function() {
+                               if ( this in $.validator.classRuleSettings ) {
+                                       $.extend(rules, $.validator.classRuleSettings[this]);
+                               }
+                       });
+               }
+               return rules;
+       },
+
+       attributeRules: function( element ) {
+               var rules = {};
+               var $element = $(element);
+
+               for (var method in $.validator.methods) {
+                       var value;
+
+                       // support for <input required> in both html5 and older browsers
+                       if ( method === "required" ) {
+                               value = $element.get(0).getAttribute(method);
+                               // Some browsers return an empty string for the required attribute
+                               // and non-HTML5 browsers might have required="" markup
+                               if ( value === "" ) {
+                                       value = true;
+                               }
+                               // force non-HTML5 browsers to return bool
+                               value = !!value;
+                       } else {
+                               value = $element.attr(method);
+                       }
+
+                       if ( value ) {
+                               rules[method] = value;
+                       } else if ( $element[0].getAttribute("type") === method ) {
+                               rules[method] = true;
+                       }
+               }
+
+               // maxlength may be returned as -1, 2147483647 (IE) and 524288 (safari) for text inputs
+               if ( rules.maxlength && /-1|2147483647|524288/.test(rules.maxlength) ) {
+                       delete rules.maxlength;
+               }
+
+               return rules;
+       },
+
+       dataRules: function( element ) {
+               var method, value,
+                       rules = {}, $element = $(element);
+               for (method in $.validator.methods) {
+                       value = $element.data("rule-" + method.toLowerCase());
+                       if ( value !== undefined ) {
+                               rules[method] = value;
+                       }
+               }
+               return rules;
+       },
+
+       staticRules: function( element ) {
+               var rules = {};
+               var validator = $.data(element.form, "validator");
+               if ( validator.settings.rules ) {
+                       rules = $.validator.normalizeRule(validator.settings.rules[element.name]) || {};
+               }
+               return rules;
+       },
+
+       normalizeRules: function( rules, element ) {
+               // handle dependency check
+               $.each(rules, function( prop, val ) {
+                       // ignore rule when param is explicitly false, eg. required:false
+                       if ( val === false ) {
+                               delete rules[prop];
+                               return;
+                       }
+                       if ( val.param || val.depends ) {
+                               var keepRule = true;
+                               switch (typeof val.depends) {
+                               case "string":
+                                       keepRule = !!$(val.depends, element.form).length;
+                                       break;
+                               case "function":
+                                       keepRule = val.depends.call(element, element);
+                                       break;
+                               }
+                               if ( keepRule ) {
+                                       rules[prop] = val.param !== undefined ? val.param : true;
+                               } else {
+                                       delete rules[prop];
+                               }
+                       }
+               });
+
+               // evaluate parameters
+               $.each(rules, function( rule, parameter ) {
+                       rules[rule] = $.isFunction(parameter) ? parameter(element) : parameter;
+               });
+
+               // clean number parameters
+               $.each(["minlength", "maxlength", "min", "max"], function() {
+                       if ( rules[this] ) {
+                               rules[this] = Number(rules[this]);
+                       }
+               });
+               $.each(["rangelength", "range"], function() {
+                       var parts;
+                       if ( rules[this] ) {
+                               if ( $.isArray(rules[this]) ) {
+                                       rules[this] = [Number(rules[this][0]), Number(rules[this][1])];
+                               } else if ( typeof rules[this] === "string" ) {
+                                       parts = rules[this].split(/[\s,]+/);
+                                       rules[this] = [Number(parts[0]), Number(parts[1])];
+                               }
+                       }
+               });
+
+               if ( $.validator.autoCreateRanges ) {
+                       // auto-create ranges
+                       if ( rules.min && rules.max ) {
+                               rules.range = [rules.min, rules.max];
+                               delete rules.min;
+                               delete rules.max;
+                       }
+                       if ( rules.minlength && rules.maxlength ) {
+                               rules.rangelength = [rules.minlength, rules.maxlength];
+                               delete rules.minlength;
+                               delete rules.maxlength;
+                       }
+               }
+
+               return rules;
+       },
+
+       // Converts a simple string to a {string: true} rule, e.g., "required" to {required:true}
+       normalizeRule: function( data ) {
+               if ( typeof data === "string" ) {
+                       var transformed = {};
+                       $.each(data.split(/\s/), function() {
+                               transformed[this] = true;
+                       });
+                       data = transformed;
+               }
+               return data;
+       },
+
+       // http://docs.jquery.com/Plugins/Validation/Validator/addMethod
+       addMethod: function( name, method, message ) {
+               $.validator.methods[name] = method;
+               $.validator.messages[name] = message !== undefined ? message : $.validator.messages[name];
+               if ( method.length < 3 ) {
+                       $.validator.addClassRules(name, $.validator.normalizeRule(name));
+               }
+       },
+
+       methods: {
+
+               // http://docs.jquery.com/Plugins/Validation/Methods/required
+               required: function( value, element, param ) {
+                       // check if dependency is met
+                       if ( !this.depend(param, element) ) {
+                               return "dependency-mismatch";
+                       }
+                       if ( element.nodeName.toLowerCase() === "select" ) {
+                               // could be an array for select-multiple or a string, both are fine this way
+                               var val = $(element).val();
+                               return val && val.length > 0;
+                       }
+                       if ( this.checkable(element) ) {
+                               return this.getLength(value, element) > 0;
+                       }
+                       return $.trim(value).length > 0;
+               },
+
+               // http://docs.jquery.com/Plugins/Validation/Methods/remote
+               remote: function( value, element, param ) {
+                       if ( this.optional(element) ) {
+                               return "dependency-mismatch";
+                       }
+
+                       var previous = this.previousValue(element);
+                       if (!this.settings.messages[element.name] ) {
+                               this.settings.messages[element.name] = {};
+                       }
+                       previous.originalMessage = this.settings.messages[element.name].remote;
+                       this.settings.messages[element.name].remote = previous.message;
+
+                       param = typeof param === "string" && {url:param} || param;
+
+                       if ( previous.old === value ) {
+                               return previous.valid;
+                       }
+
+                       previous.old = value;
+                       var validator = this;
+                       this.startRequest(element);
+                       var data = {};
+                       data[element.name] = value;
+                       $.ajax($.extend(true, {
+                               url: param,
+                               mode: "abort",
+                               port: "validate" + element.name,
+                               dataType: "json",
+                               data: data,
+                               success: function( response ) {
+                                       validator.settings.messages[element.name].remote = previous.originalMessage;
+                                       var valid = response === true || response === "true";
+                                       if ( valid ) {
+                                               var submitted = validator.formSubmitted;
+                                               validator.prepareElement(element);
+                                               validator.formSubmitted = submitted;
+                                               validator.successList.push(element);
+                                               delete validator.invalid[element.name];
+                                               validator.showErrors();
+                                       } else {
+                                               var errors = {};
+                                               var message = response || validator.defaultMessage( element, "remote" );
+                                               errors[element.name] = previous.message = $.isFunction(message) ? message(value) : message;
+                                               validator.invalid[element.name] = true;
+                                               validator.showErrors(errors);
+                                       }
+                                       previous.valid = valid;
+                                       validator.stopRequest(element, valid);
+                               }
+                       }, param));
+                       return "pending";
+               },
+
+               // http://docs.jquery.com/Plugins/Validation/Methods/minlength
+               minlength: function( value, element, param ) {
+                       var length = $.isArray( value ) ? value.length : this.getLength($.trim(value), element);
+                       return this.optional(element) || length >= param;
+               },
+
+               // http://docs.jquery.com/Plugins/Validation/Methods/maxlength
+               maxlength: function( value, element, param ) {
+                       var length = $.isArray( value ) ? value.length : this.getLength($.trim(value), element);
+                       return this.optional(element) || length <= param;
+               },
+
+               // http://docs.jquery.com/Plugins/Validation/Methods/rangelength
+               rangelength: function( value, element, param ) {
+                       var length = $.isArray( value ) ? value.length : this.getLength($.trim(value), element);
+                       return this.optional(element) || ( length >= param[0] && length <= param[1] );
+               },
+
+               // http://docs.jquery.com/Plugins/Validation/Methods/min
+               min: function( value, element, param ) {
+                       return this.optional(element) || value >= param;
+               },
+
+               // http://docs.jquery.com/Plugins/Validation/Methods/max
+               max: function( value, element, param ) {
+                       return this.optional(element) || value <= param;
+               },
+
+               // http://docs.jquery.com/Plugins/Validation/Methods/range
+               range: function( value, element, param ) {
+                       return this.optional(element) || ( value >= param[0] && value <= param[1] );
+               },
+
+               // http://docs.jquery.com/Plugins/Validation/Methods/email
+               email: function( value, element ) {
+                       // contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
+                       return this.optional(element) || /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(value);
+               },
+
+               // http://docs.jquery.com/Plugins/Validation/Methods/url
+               url: function( value, element ) {
+                       // contributed by Scott Gonzalez: http://projects.scottsplayground.com/iri/
+                       return this.optional(element) || /^(https?|s?ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value);
+               },
+
+               // http://docs.jquery.com/Plugins/Validation/Methods/date
+               date: function( value, element ) {
+                       return this.optional(element) || !/Invalid|NaN/.test(new Date(value).toString());
+               },
+
+               // http://docs.jquery.com/Plugins/Validation/Methods/dateISO
+               dateISO: function( value, element ) {
+                       return this.optional(element) || /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/.test(value);
+               },
+
+               // http://docs.jquery.com/Plugins/Validation/Methods/number
+               number: function( value, element ) {
+                       return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(value);
+               },
+
+               // http://docs.jquery.com/Plugins/Validation/Methods/digits
+               digits: function( value, element ) {
+                       return this.optional(element) || /^\d+$/.test(value);
+               },
+
+               // http://docs.jquery.com/Plugins/Validation/Methods/creditcard
+               // based on http://en.wikipedia.org/wiki/Luhn
+               creditcard: function( value, element ) {
+                       if ( this.optional(element) ) {
+                               return "dependency-mismatch";
+                       }
+                       // accept only spaces, digits and dashes
+                       if ( /[^0-9 \-]+/.test(value) ) {
+                               return false;
+                       }
+                       var nCheck = 0,
+                               nDigit = 0,
+                               bEven = false;
+
+                       value = value.replace(/\D/g, "");
+
+                       for (var n = value.length - 1; n >= 0; n--) {
+                               var cDigit = value.charAt(n);
+                               nDigit = parseInt(cDigit, 10);
+                               if ( bEven ) {
+                                       if ( (nDigit *= 2) > 9 ) {
+                                               nDigit -= 9;
+                                       }
+                               }
+                               nCheck += nDigit;
+                               bEven = !bEven;
+                       }
+
+                       return (nCheck % 10) === 0;
+               },
+
+               // http://docs.jquery.com/Plugins/Validation/Methods/equalTo
+               equalTo: function( value, element, param ) {
+                       // bind to the blur event of the target in order to revalidate whenever the target field is updated
+                       // TODO find a way to bind the event just once, avoiding the unbind-rebind overhead
+                       var target = $(param);
+                       if ( this.settings.onfocusout ) {
+                               target.unbind(".validate-equalTo").bind("blur.validate-equalTo", function() {
+                                       $(element).valid();
+                               });
+                       }
+                       return value === target.val();
+               }
+
+       }
+
+});
+
+// deprecated, use $.validator.format instead
+$.format = $.validator.format;
+
+}(jQuery));
+
+// ajax mode: abort
+// usage: $.ajax({ mode: "abort"[, port: "uniqueport"]});
+// if mode:"abort" is used, the previous request on that port (port can be undefined) is aborted via XMLHttpRequest.abort()
+(function($) {
+       var pendingRequests = {};
+       // Use a prefilter if available (1.5+)
+       if ( $.ajaxPrefilter ) {
+               $.ajaxPrefilter(function( settings, _, xhr ) {
+                       var port = settings.port;
+                       if ( settings.mode === "abort" ) {
+                               if ( pendingRequests[port] ) {
+                                       pendingRequests[port].abort();
+                               }
+                               pendingRequests[port] = xhr;
+                       }
+               });
+       } else {
+               // Proxy ajax
+               var ajax = $.ajax;
+               $.ajax = function( settings ) {
+                       var mode = ( "mode" in settings ? settings : $.ajaxSettings ).mode,
+                               port = ( "port" in settings ? settings : $.ajaxSettings ).port;
+                       if ( mode === "abort" ) {
+                               if ( pendingRequests[port] ) {
+                                       pendingRequests[port].abort();
+                               }
+                               return (pendingRequests[port] = ajax.apply(this, arguments));
+                       }
+                       return ajax.apply(this, arguments);
+               };
+       }
+}(jQuery));
+
+// provides delegate(type: String, delegate: Selector, handler: Callback) plugin for easier event delegation
+// handler is only called when $(event.target).is(delegate), in the scope of the jquery-object for event.target
+(function($) {
+       $.extend($.fn, {
+               validateDelegate: function( delegate, type, handler ) {
+                       return this.bind(type, function( event ) {
+                               var target = $(event.target);
+                               if ( target.is(delegate) ) {
+                                       return handler.apply(target, arguments);
+                               }
+                       });
+               }
+       });
+}(jQuery));
\ No newline at end of file
diff --git a/plugins/googlemap/googlemap.html b/plugins/googlemap/googlemap.html
deleted file mode 100644 (file)
index d0bb5d6..0000000
+++ /dev/null
@@ -1,2 +0,0 @@
-{# keep the original skeleton but this probably won't support several instances in the same page #}
-<div id='map-container'><div id='map'></div></div>
diff --git a/plugins/googlemap/googlemap.js b/plugins/googlemap/googlemap.js
deleted file mode 100644 (file)
index 62e1d6f..0000000
+++ /dev/null
@@ -1,277 +0,0 @@
-/**
- * Description: display a query result in a googlemap
- * Copyright (c) 2012 UPMC Sorbonne Universite - INRIA
- * License: GPLv3
- */
-
-// xxx TODO -- this one could use a bit of cleaning like what was done for the first plugins
-// especially wrt using 'instance' and 'data' in such a confusing way
-
-(function( jQuery ){
-
-  var methods = {
-     init : function( options ) {
-
-       return this.each(function(){
-         
-         var $this = jQuery(this),
-             data = $this.data('GoogleMap'), GoogleMap = jQuery('<div />', {text : $this.attr('title')});
-         
-         // If the plugin hasn't been initialized yet
-         if ( ! data ) {
-         
-           /* Plugin initialization */
-
-            //google.load('maps', '3', { other_params: 'sensor=false' });
-            //google.setOnLoadCallback(initialize);
-
-            $this.data('map', null);
-            $this.data('markerCluster', null);
-            $this.data('markers', []);
-
-            var myLatlng = new google.maps.LatLng(options.latitude, options.longitude);
-            var myOptions = {
-              zoom: options.zoom,
-              center: myLatlng,
-              mapTypeId: google.maps.MapTypeId.ROADMAP
-            }
-      
-            var map = new google.maps.Map(document.getElementById("map"), myOptions);
-            $this.data('map', map);
-
-            /* End of plugin initialization */
-
-            jQuery(this).data('GoogleMap', {
-                               plugin_uuid: options.plugin_uuid,
-                               query_uuid: options.query_uuid,
-                target : $this,
-                current_resources: Array(),
-                GoogleMap : GoogleMap
-            });
-
-            /* Subscribe to query updates */
-            jQuery.subscribe('/results/' + options.query_uuid + '/changed', {instance: $this}, update_map);
-            jQuery.subscribe('/update-set/' + options.query_uuid, {instance: $this}, on_resource_changed);
-            jQuery.subscribe('/query/' + options.query_uuid + '/changed', {instance: $this}, query_changed);
-            
-            //data = jQuery(this).data();
-            
-            // TODO: Change the status of a node based on the actions in GoogleMap plugin or in other plugins (e.g. DataTables)
-            // Can we publish a value in results row['sliver'] ???
-            // Today, the value is attached or undefined
-            // But can we think about a added/removed status ???
-            // This plugin would update the map based on the results published
-
-         }
-       });
-     },
-    destroy : function( ) {
-
-        return this.each(function(){
-            var $this = jQuery(this), data = $this.data('GoogleMap');
-                       jQuery(window).unbind('GoogleMap');
-                       data.GoogleMap.remove();
-                       $this.removeData('GoogleMap');
-               })
-
-    },
-/*
-    reposition : function( ) { // ... },
-    update : function( ) { // ... },
-    hide : function( ) { // ... },
-*/
-    show : function( content ) {
-        google.maps.event.trigger(map, 'resize');
-    }
-  };
-
-    jQuery.fn.GoogleMap = function( method ) {
-               /* Method calling logic */
-               if ( methods[method] ) {
-                       return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
-               } else if ( typeof method === 'object' || ! method ) {
-                       return methods.init.apply( this, arguments );
-               } else {
-                       jQuery.error( 'Method ' +  method + ' does not exist on jQuery.GoogleMap' );
-               }    
-
-    };
-
-    /* Private methods */
-        function query_changed(e,query){
-            var data = e.data.instance.data();
-            /* Compare current and advertised query to get added and removed fields */
-            previous_query=data.current_query;
-            /* Save the query as the current query */
-            data.current_query=query;
-            
-            var rows=[];
-            if(typeof(data.results)!="undefined" && data.results.length>0){
-                jQuery.each(data.results, function(i, row){
-                    jQuery.each(query.filter, function (idx, filter){
-                        if(get_value(row[filter[0]])==filter[2]){
-                            rows.push(row);
-                        }
-                    });
-                });
-                data.markerCluster=[];
-                data.markers=[];
-                var myLatlng = new google.maps.LatLng(34.397, 150.644);
-                var myOptions = {
-                    zoom: 2,
-                    center: myLatlng,
-                    mapTypeId: google.maps.MapTypeId.ROADMAP
-                }
-                map = new google.maps.Map(jQuery('#map')[0],myOptions);
-                data.map=map;
-                //map.clearMarkers();
-                update_map(e, rows);
-            }
-        }
-       function update_map(e, rows) {            
-            var data = e.data.instance.data();
-            var instance_ = e.data.instance;
-           //$plugindiv.closest('.need-spin').spin(false);
-           instance_.closest('.need-spin').spin(false);
-
-
-            if (rows === undefined || !rows || rows.length==0) {
-               messages.warning ("Empty result in googlemap.update_map - nothing to show");
-                return;
-            }
-
-            if(rows.length==0) {
-                rows=data.results;
-            }
-
-            if(typeof(data.results)=="undefined" || data.results==null){
-                data.results=rows;
-            }
-            var map = data.map;
-            var markerCluster = data.markerCluster;            
-            var markers = data.markers;
-            var coords = new Array();
-            var infowindow = new google.maps.InfoWindow();
-            /*
-            if(typeof(markers)!="undefined" && markers.length>0){
-                map.clearMarkers();
-            }*/
-
-            data.current_resources = Array();
-
-            jQuery.each(data.results, function(i, result){
-                // get the coordinates
-                var latitude=get_value(result['latitude']);
-                var longitude=get_value(result['longitude']);
-                var hash = latitude + longitude;
-
-                // check to see if we've seen this hash before
-                if(coords[hash] == null) {
-                    // get coordinate object
-                    var myLatlng = new google.maps.LatLng(latitude, longitude);
-                    // store an indicator that we've seen this point before
-                    coords[hash] = 1;
-                } else {
-                    // add some randomness to this point 1500 = 100 meters, 15000 = 10 meters
-                    var lat = latitude + (Math.random() -.5) / 1500; 
-                    var lng = longitude + (Math.random() -.5) / 1500; 
-
-                    // get the coordinate object
-                    var myLatlng = new google.maps.LatLng(lat, lng);
-                }
-                // If the node is attached to the slice, action will be Remove; else action will be add to slice
-                if (typeof(result['sliver']) != 'undefined') {
-                    data.current_resources.push(result['urn']);
-                    action="del";
-                    action_class="ui-icon-circle-minus";
-                    action_message="Remove from slice";
-                }else{
-                    action="add";
-                    action_class="ui-icon-circle-plus";
-                    action_message="Add to slice";
-                }
-                // XXX not working
-                if (!(result['latitude'])) {
-                    return true;
-                }
-
-                //jQuery(".map-button").click(button_click);
-                if(jQuery.inArray(result,rows)>-1){
-                    var marker = new google.maps.Marker({
-                        position: myLatlng,
-                        title: get_value(result['ip']),
-                        // This should be done by the rendering
-                        content: '<p>Agent: ' + get_value(result['ip']) + ' (' + get_value(result['urn']) + ')<br/>Platform: ' + get_value(result['platform'])+'</p>' +
-                                '<div class="map-button" id="'+action+'/'+get_value(result['urn'])+'" style="cursor:pointer;">'+
-                                '<span class="ui-icon '+action_class+'" style="clear:both;float:left;"></span>'+action_message+
-                                '</div>'
-                    }); 
-
-                    google.maps.event.addListener(marker, 'click', function() {
-                            infowindow.content = this.content;
-                            infowindow.open(map, this);
-                            // onload of the infowindow on the map, bind a click on a button
-                            google.maps.event.addListener(infowindow, 'domready', function() {
-                                jQuery('.map-button').unbind('click');
-                                jQuery(".map-button").click({instance: instance_}, button_click);
-                            });
-                    });
-                    markers.push(marker);
-                }
-            });
-            markerCluster = new MarkerClusterer(map, markers, {zoomOnClick: false});
-            google.maps.event.addListener(markerCluster, "clusterclick", function (cluster) {
-                var markers = cluster.getMarkers();
-                var bounds  = new google.maps.LatLngBounds();
-              /* 
-              * date: 24/05/2012
-              * author: lbaron
-              * Firefox JS Error - replaced $.each by JQuery.each
-              */                  
-                jQuery.each(markers, function(i, marker){
-                    bounds.extend(marker.getPosition()); 
-                    });
-                //map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
-                map.fitBounds(bounds);
-            });
-            data.markerCluster=markerCluster;
-        }
-        function button_click(e){
-            var data = e.data.instance.data().GoogleMap;
-            var op_value=this.id.split("/");
-            if(op_value.length>0){
-                jQuery.publish('selected', op_value[0]+'/'+op_value[1]);
-                var value = op_value[1];
-
-                if (op_value[0] == 'add') {
-                    data.current_resources.push(value);
-                } else {
-                    tmp = jQuery.grep(data.current_resources, function(x) { return x != value; });
-                    data.current_resources = tmp;
-                }
-
-                /* inform slice that our selected resources have changed */
-                jQuery.publish('/update-set/' + data.query_uuid, [data.current_resources, true, e.data.instance]);
-            }
-        }
-
-    function on_resource_changed(e, resources, instance)
-    {
-        /* TODO OPENLAB : this query determines which checkboxes must be checked */
-        if (instance == e.data.instance)
-            return;
-        data = e.data.instance.data().GoogleMap;
-
-        previous_resources = data.current_resources;
-        data.current_resources = resources;
-
-        /* TODO We uncheck all checkboxes ... */
-        //jQuery('datatables-checkbox-' + data.options.plugin_uuid).attr('checked', false);
-        /* ... and check the ones specified in the resource list */
-        //jQuery.each(data.current_resources, function(index, urn) {
-        //    jQuery('#datatables-checkbox-' + data.options.plugin_uuid + "-" + urn).attr('checked', true)
-        //});
-        
-    }
-
-})( jQuery );
similarity index 72%
rename from plugins/googlemap/googlemap.py
rename to plugins/googlemaps/__init__.py
index d6ea883..38c6564 100644 (file)
@@ -1,20 +1,22 @@
 from unfold.plugin import Plugin
 
-class GoogleMap (Plugin):
+class GoogleMaps (Plugin):
 
     # set checkboxes if a final column with checkboxes is desired
     # pass columns as the initial set of columns
     #   if None then this is taken from the query's fields
     # latitude,longitude, zoom : the starting point
-    def __init__ (self, query, latitude=43., longitude=7., zoom=4, **settings):
+    def __init__ (self, query, query_all = None, latitude=43., longitude=7., zoom=4, **settings):
         Plugin.__init__ (self, **settings)
         self.query=query
+        self.query_all = query_all
+        self.query_all_uuid = query_all.query_uuid if query_all else None
         self.latitude=latitude
         self.longitude=longitude
         self.zoom=zoom
 
     def template_file (self):
-        return "googlemap.html"
+        return "googlemaps.html"
 
     def template_env (self, request):
         env={}
@@ -23,16 +25,16 @@ class GoogleMap (Plugin):
     def requirements (self):
         reqs = {
             'js_files' : [ "https://maps.googleapis.com/maps/api/js?sensor=false", 
-                           "/js/googlemap.js",
+                           "/js/googlemaps.js",
                            "/js/markerclusterer.js",
                             "js/manifold.js", "js/manifold-query.js", 
                             "js/spin.presets.js", "js/spin.min.js", "js/jquery.spin.js", 
                             "js/unfold-helper.js",
                            ],
-            'css_files' : [ "css/googlemap.css",
+            'css_files' : [ "css/googlemaps.css",
                             ],
             }
         return reqs
 
     # the list of things passed to the js plugin
-    def json_settings_list (self): return ['plugin_uuid','query_uuid', 'latitude', 'longitude', 'zoom', ]
+    def json_settings_list (self): return ['plugin_uuid','query_uuid', 'query_all_uuid', 'latitude', 'longitude', 'zoom', ]
similarity index 97%
rename from plugins/googlemap/googlemap.css
rename to plugins/googlemaps/static/css/googlemaps.css
index 6a82854..4399c1e 100644 (file)
@@ -9,7 +9,7 @@
   /*width: 800px;*/
 }
 
-#map {
+.map {
   /*width: 800px;*/
   height: 500px;
 }
diff --git a/plugins/googlemaps/static/googlemaps.html b/plugins/googlemaps/static/googlemaps.html
new file mode 100644 (file)
index 0000000..4aee23b
--- /dev/null
@@ -0,0 +1,11 @@
+<div id='{{domid}}__map-container'>
+    <div class='map' id='{{domid}}__map'></div>
+
+    <!-- TEMPLATE -->
+    <div id='{{domid}}__template' class='template'>
+        <div class="map-button" style="cursor:pointer;">
+            <span class='ui-icon {% templatetag openvariable %} action_class {% templatetag closevariable%}' style="clear:both; float:left;"></span>
+            {% templatetag openvariable %} action_message {% templatetag closevariable %}
+        </div>';
+    </div>
+</div>
diff --git a/plugins/googlemaps/static/js/googlemaps.js b/plugins/googlemaps/static/js/googlemaps.js
new file mode 100644 (file)
index 0000000..d985017
--- /dev/null
@@ -0,0 +1,341 @@
+/**
+ * Description: display a query result in a Google map
+ * Copyright (c) 2012-2013 UPMC Sorbonne Universite - INRIA
+ * License: GPLv3
+ */
+
+/* BUGS:
+ * - infowindow is not properly reopened when the maps has not the focus
+ */
+
+(function($){
+
+   var GoogleMaps = Plugin.extend({
+
+        init: function(options, element)
+        {
+            this._super(options, element);
+
+            /* Member variables */
+            // query status
+            this.received_all = false;
+            this.received_set = false;
+            this.in_set_buffer = Array();
+
+            // key -> { marker, checked }
+            this.map_markers = {}
+
+            /* XXX Events XXX */
+            this.el().on('show', this, this.on_show);
+            // TODO in destructor
+            // $(window).unbind('Hazelnut');
+
+            var query = manifold.query_store.find_analyzed_query(this.options.query_uuid);
+            this.method = query.object;
+
+            var keys = manifold.metadata.get_key(this.method);
+            this.key = (keys && keys.length == 1) ? keys[0] : null;
+
+            /* Setup query and record handlers */
+            this.listen_query(options.query_uuid);
+            this.listen_query(options.query_all_uuid, 'all');
+
+            /* GUI setup and event binding */
+            this.initialize_map();
+        }, // init
+
+        /* PLUGIN EVENTS */
+
+        on_show: function(e)
+        {
+            var self = e.data;
+            google.maps.event.trigger(self.map, 'resize');
+        }, // on_show
+
+        /* GUI EVENTS */
+
+        /* GUI MANIPULATION */
+
+        /**
+         */
+        initialize_map: function()
+        {
+            this.markerCluster = null;
+            this.coords = new Array();
+
+            var myLatlng = new google.maps.LatLng(this.options.latitude, this.options.longitude);
+            var myOptions = {
+                zoom: this.options.zoom,
+                center: myLatlng,
+                mapTypeId: google.maps.MapTypeId.ROADMAP
+            }
+      
+            var id = this.options.plugin_uuid + manifold.separator + 'map';
+            this.map = new google.maps.Map(document.getElementById(id), myOptions);
+            this.infowindow = new google.maps.InfoWindow();
+        }, // initialize_map
+
+        set_checkbox: function(record, checked)
+        {
+            /* Default: checked = true */
+            if (typeof checked === 'undefined')
+                checked = true;
+
+            var key_value;
+            /* The function accepts both records and their key */
+            switch (manifold.get_type(record)) {
+                case TYPE_VALUE:
+                    key_value = record;
+                    break;
+                case TYPE_RECORD:
+                    /* XXX Test the key before ? */
+                    key_value = record[this.key];
+                    break;
+                default:
+                    throw "Not implemented";
+                    break;
+            }
+
+            // we cannot directly edit html, since nothing but marker is displayed
+            //var checkbox_id = this.id('checkbox', this.id_from_key(this.key, key_value));
+            //checkbox_id = '#' + checkbox_id.replace(/\./g, '\\.');
+            //$(checkbox_id, this.table.fnGetNodes()).attr('checked', checked);
+
+            var dict_info = this.map_markers[unfold.escape_id(key_value).replace(/\\/g, '')];
+
+
+            // Update the marker content
+            dict_info.in_set = checked;
+            dict_info.marker.content = this.get_marker_content(dict_info.record, checked);
+
+            // Update opened infowindow
+            // XXX Factor this code
+            this.infowindow.close();
+            this.infowindow.open(this.map, dict_info.marker);
+            this.infowindow.setContent(dict_info.marker.content);
+            this.els('map-button').unbind('click').click(this, this._button_click);
+
+            //var button = this.checkbox(record, checked);
+            //this.el('checkbox', this.id_from_record(method, record)).html(button);
+        }, 
+
+        checkbox: function(record, checked) 
+        {
+            if (typeof checked === 'undefined')
+                checked = false;
+
+            var method  = manifold.query_store.find_analyzed_query(this.options.query_uuid).object;
+            var action = checked ? 'checked' : 'del';
+            var ctx = {
+                action_class  : checked ? 'ui-icon-circle-minus' : 'ui-icon-circle-plus',
+                action_message: checked ? 'Remove from slice' : 'Add to slice',
+            };
+            var button = this.load_template('template', ctx);
+
+            var id_record = this.id_from_record(method, record);
+            if (!id_record)
+                return 'ERROR';
+            var id = this.id('checkbox', this.id_from_record(method, record));
+            return "<div id='" + id + "'>" + button + "</div>";
+        },
+        
+        get_marker_content: function(record, checked)
+        {
+            return '<p><b>' + this.method + '</b>: ' + get_value(record['resource_hrn']) + '<br/><b>network</b>: ' + get_value(record['network'])+'</p>' + this.checkbox(record, checked);
+        },
+
+        /**
+         */
+        new_record: function(record)
+        {
+            // get the coordinates
+            var latitude=get_value(record['latitude']);
+            var longitude=get_value(record['longitude']);
+            var hash = latitude + longitude;
+
+            // check to see if we've seen this hash before
+            if(this.coords[hash] == null) {
+                // get coordinate object
+                var myLatlng = new google.maps.LatLng(latitude, longitude);
+                // store an indicator that we've seen this point before
+                this.coords[hash] = 1;
+            } else {
+                // add some randomness to this point 1500 = 100 meters, 15000 = 10 meters
+                var lat = latitude + (Math.random() -.5) / 1500; 
+                var lng = longitude + (Math.random() -.5) / 1500; 
+
+                // get the coordinate object
+                var myLatlng = new google.maps.LatLng(lat, lng);
+            }
+            // XXX not working
+            if (!(record['latitude'])) {
+                return true;
+            }
+
+            //jQuery(".map-button").click(button_click);
+            //if(jQuery.inArray(record, rows)>-1){
+                var marker = new google.maps.Marker({
+                    position: myLatlng,
+                    title: get_value(record['hostname']),
+                    // This should be done by the rendering
+                    content: this.get_marker_content(record, false),
+                }); 
+
+                this.addInfoWindow(marker, this.map);
+                var key_value = (this.key in record) ? record[this.key] : null;
+                if (!key_value)
+                    return;
+                this.map_markers[unfold.escape_id(key_value).replace(/\\/g, '')] = {
+                    marker: marker,
+                    in_set: false,
+                    record: record,
+                    value: key_value
+                }
+            //}
+
+        }, // new_record
+
+        addInfoWindow: function(marker, map)
+        {
+            var self = this;
+            google.maps.event.addListener(marker, 'click', function () {     
+                if(self.infowindow){
+                    self.infowindow.close();
+                }
+                self.infowindow.setContent(marker.content);// = new google.maps.InfoWindow({ content: marker.content });
+                self.infowindow.open(map, marker);
+                // onload of the infowindow on the map, bind a click on a button
+                google.maps.event.addListener(self.infowindow, 'domready', function() {
+                    self.els('map-button').unbind('click').click(self, self._button_click);
+//                    jQuery(".map-button").click({instance: instance_, infoWindow: object.infowindow}, button_click);                     
+                });
+            });
+        }, // addInfoWindow
+
+
+        /*************************** QUERY HANDLER ****************************/
+
+        /*************************** RECORD HANDLER ***************************/
+
+        on_new_record: function(record)
+        {
+            if (this.received_all)
+                // update checkbox for record
+                this.set_checkbox(record);
+            else
+                // store for later update of checkboxes
+                this.in_set_buffer.push(record);
+        },
+
+        on_clear_records: function(record)
+        {
+
+        },
+
+        // Could be the default in parent
+        on_query_in_progress: function()
+        {
+            this.spin();
+        },
+
+        on_query_done: function()
+        {
+            if (this.received_all)
+                this.unspin();
+            this.received_set = true;
+        },
+
+        on_field_state_changed: function(data)
+        {
+            switch(data.request) {
+                case FIELD_REQUEST_ADD:
+                case FIELD_REQUEST_ADD_RESET:
+                    this.set_checkbox(data.value, true);
+                    break;
+                case FIELD_REQUEST_REMOVE:
+                case FIELD_REQUEST_REMOVE_RESET:
+                    this.set_checkbox(data.value, false);
+                    break;
+                default:
+                    break;
+            }
+        },
+
+
+        // all
+
+        on_all_new_record: function(record)
+        {
+            this.new_record(record);
+        },
+
+        on_all_clear_records: function()
+        {
+        },
+
+        on_all_query_in_progress: function()
+        {
+            // XXX parent
+            this.spin();
+        },
+
+        on_all_query_done: function()
+        {
+
+            // MarkerClusterer
+            var markers = [];
+            $.each(this.map_markers, function (k, v) { markers.push(v.marker); });
+
+            this.markerCluster = new MarkerClusterer(this.map, markers, {zoomOnClick: false});
+            google.maps.event.addListener(this.markerCluster, "clusterclick", function (cluster) {
+                var cluster_markers = cluster.getMarkers();
+                var bounds  = new google.maps.LatLngBounds();
+                /* 
+                * date: 24/05/2012
+                * author: lbaron
+                * Firefox JS Error - replaced $.each by JQuery.each
+                */                  
+                jQuery.each(cluster_markers, function(i, marker){
+                    bounds.extend(marker.getPosition()); 
+                });
+
+                //map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
+                this.map.fitBounds(bounds);
+            });
+
+            var self = this;
+            if (this.received_set) {
+                /* XXX needed ? XXX We uncheck all checkboxes ... */
+                //$("[id^='datatables-checkbox-" + this.options.plugin_uuid +"']").attr('checked', false);
+
+                /* ... and check the ones specified in the resource list */
+                $.each(this.in_set_buffer, function(i, record) {
+                    self.set_checkbox(record, true);
+                });
+
+                this.unspin();
+            }
+            this.received_all = true;
+
+        }, // on_all_query_done
+
+        /************************** PRIVATE METHODS ***************************/
+
+        _button_click: function(e)
+        {
+            var self   = e.data;
+
+            var escaped_key = self.key_from_id($(this).parent().attr('id'), 'checkbox');
+            var info_dict = self.map_markers[escaped_key];
+            var in_set = info_dict.in_set;
+            var value = info_dict.value;
+
+            var escaped_key = self.map_markers[self.key_from_id($(this).parent().attr('id'), 'checkbox')]
+            manifold.raise_event(self.options.query_uuid, (in_set) ? SET_REMOVED : SET_ADD, value);
+        } // _button_click
+
+    });
+
+    $.plugin('GoogleMaps', GoogleMaps);
+
+})(jQuery);
diff --git a/plugins/hazelnut/DataTables.php b/plugins/hazelnut/DataTables.php
deleted file mode 100644 (file)
index 67a8985..0000000
+++ /dev/null
@@ -1,116 +0,0 @@
-<?php
-
-
-class DataTables extends Plugin
-{
-
-       /* Knowing the uuid of a query, we could get the results with Plugins */
-       /* Same for async */
-    public function render_content()
-    //$plugin_uuid, $options)
-    {
-
-        //Plugins::add_js('/DataTables/jquery.dataTables.js');
-        Plugins::add_js('//ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.3/jquery.dataTables.js');
-        Plugins::add_js('/DataTables/DataTables.js');
-        //Plugins::add_css('/DataTables/DataTables.css');
-        //Plugins::add_css('/DataTables/demo_table.css');
-        Plugins::add_css('/DataTables/demo_table_jui.css');
-
-        $uuid = $this->uuid;
-
-               $results = Array();
-               $async = 1;
-
-
-        /* XXX required field in options : query_uuid */
-         
-        
-        $query = Plugins::get_query_by_uuid($this->params['query_uuid']);
-        $is_unique = Plugins::get_key_filter($query);
-           $method_keys = Plugins::get_default_fields($query->method, $is_unique);
-          //$method_keys = Plugins::query_get_default_keys($options['query_uuid']);
-          //$fields = Plugins::query_get_fields($options['query_uuid']);
-        //$all_headers = $_SESSION['metadata']['nodes']['columns'];        
-        //$fields = $all_headers;
-
-       $fields = Plugins::metadata_get_fields($query->method);
-
-       /*
-        * @author: lbaron
-        * date: 2012-05-29
-        * debug columns QueryEditor to DataTables
-        *
-        */
-        // Problem: field names are differents between 
-        // $_SESSION['metadata']['nodes']['columns'] 
-        // JSON values
-        //$fields[]="arch"; // architecture in Session metadata
-        //$fields[]="astype"; // as_type in Session metadata
-        $fields['platform'] = Array('column' => 'platform');
-        $fields['platform_longname'] = Array('column' => 'platform_longname');
-
-        //----------------------------------
-        
-        $out = Array();
-        $out[] = "<table class='display' id='table-$uuid'>";
-        $out[] = "<thead><tr>";
-
-        foreach ($method_keys as $f) {
-            $out[] = "<th>$f</th>";
-        }
-
-        /* We put defaults fields (should be keys) at the beginning, and don't repeat them afterwards */
-        foreach ($fields as $key=>$f) {
-            if((array_search($f['column'], $method_keys)) === false)
-                $out[] = "<th>".$f['column']."</th>";
-        }
-
-        if (array_key_exists('checkboxes', $this->params) && ($this->params['checkboxes'])) {
-            $out[] = "<th>+/-</th>";            
-        }
-        $out[] = "</tr></thead>";
-        $out[] = "<tbody>";        
-        
-        /* This might be done asynchronously */
-        if (!$async) {
-            $query = Plugins::get_query_by_uuid($this->params['query_uuid']);
-            foreach ($results as $r) {
-                $out[] = "<tr>";
-                foreach ($fields as $f) {
-                    $out[] = "<td>";
-                    $out[] = Plugins::render_element($query, $r[$f], $f); // XXX was query->method
-                    $out[] = "</td>";
-                }
-                if (array_key_exists('checkboxes', $this->params) && ($this->params['checkboxes'])) {
-                    $out[] = "<td>[X]</td>";
-                }
-                $out[] = "</tr>";
-            }
-        }
-
-
-        if ($async) {
-            /* setup datatables */
-            /* TODO:
-             * - fixed row for key columns
-             * - uniform row height
-             * - how to make some columns disappear
-             * - how to udpate some columns based on keys
-             */
-        }
-        $out[] = "</tbody>";
-        $out[] = "</table>";
-        return implode($out);
-    }
-}
-
-Plugins::register_plugin(
-    'DataTables',   /* plugin name */
-    'DataTables',   /* class name */
-    Array(
-        'method' => '*',
-        'fields' => Array()
-    )
-    /* XXX dependencies */
-);
index e69de29..9509dc0 100644 (file)
@@ -0,0 +1,56 @@
+from unfold.plugin import Plugin
+
+class Hazelnut (Plugin):
+
+    # set checkboxes if a final column with checkboxes is desired
+    # pass columns as the initial set of columns
+    #   if None then this is taken from the query's fields
+    def __init__ (self, query=None, query_all=None, checkboxes=False, columns=None, datatables_options={}, **settings):
+        Plugin.__init__ (self, **settings)
+        self.query          = query
+        # Until we have a proper way to access queries in Python
+        self.query_all      = query_all
+        self.query_all_uuid = query_all.query_uuid if query_all else None
+        self.checkboxes=checkboxes
+        # XXX We need to have some hidden columns until we properly handle dynamic queries
+        if columns is not None:
+            self.columns=columns
+            self.hidden_columns = []
+        elif self.query:
+            self.columns = self.query.fields
+            if query_all:
+                # We need a list because sets are not JSON-serilizable
+                self.hidden_columns = list(self.query_all.fields - self.query.fields)
+            else:
+                self.hidden_columns = []
+        else:
+            self.columns = []
+            self.hidden_columns = []
+        self.datatables_options=datatables_options
+
+    def template_file (self):
+        return "hazelnut.html"
+
+    def template_env (self, request):
+        env={}
+        env.update(self.__dict__)
+        env['columns']=self.columns
+        return env
+
+    def requirements (self):
+        reqs = {
+            'js_files' : [ "js/hazelnut.js", 
+                           "js/manifold.js", "js/manifold-query.js", 
+                           "js/dataTables.js", "js/dataTables.bootstrap.js", "js/with-datatables.js",
+                           "js/spin.presets.js", "js/spin.min.js", "js/jquery.spin.js", 
+                           "js/unfold-helper.js",
+                           ] ,
+            'css_files': [ "css/hazelnut.css" , 
+                           "css/dataTables.bootstrap.css",
+                           ],
+            }
+        return reqs
+
+    # the list of things passed to the js plugin
+    def json_settings_list (self):
+        return ['plugin_uuid', 'domid', 'query_uuid', 'query_all_uuid', 'checkboxes', 'datatables_options', 'hidden_columns']
diff --git a/plugins/hazelnut/hazelnut.html b/plugins/hazelnut/hazelnut.html
deleted file mode 100644 (file)
index 84f2e18..0000000
+++ /dev/null
@@ -1,13 +0,0 @@
-<div id='main-{{ domid }}'>
-<table class='table table-striped table-bordered dataTable' id='hazelnut-{{ domid }}'>
-<thead><tr> {% for column in columns %}
-<th>{{ column }}</th>{% endfor %} {% if checkboxes %}<th>+/-</th>{% endif %}
-</tr></thead> 
-<tbody>
-</tbody>
-<tfoot><tr> {% for column in columns %}
-<th>{{ column }}</th>{% endfor %} {% if checkboxes %}<th>+/-</th>{% endif %}
-</tr></tfoot> 
-</table>
-</div>
-<div class="hazelnut-spacer"></div>
diff --git a/plugins/hazelnut/hazelnut.js b/plugins/hazelnut/hazelnut.js
deleted file mode 100644 (file)
index bbaf11e..0000000
+++ /dev/null
@@ -1,494 +0,0 @@
-/**
- * Description: display a query result in a datatables-powered <table>
- * Copyright (c) 2012 UPMC Sorbonne Universite - INRIA
- * License: GPLv3
- */
-
-/*
- * It's a best practice to pass jQuery to an IIFE (Immediately Invoked Function
- * Expression) that maps it to the dollar sign so it can't be overwritten by
- * another library in the scope of its execution.
- */
-(function($){
-
-    var debug=false;
-    debug=true
-
-    // routing calls
-    $.fn.Hazelnut = function( method ) {
-        if ( methods[method] ) {
-            return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
-        } else if ( typeof method === 'object' || ! method ) {
-            return methods.init.apply( this, arguments );
-        } else {
-            $.error( 'Method ' +  method + ' does not exist on jQuery.Hazelnut' );
-        }    
-    };
-
-    /***************************************************************************
-     * Public methods
-     ***************************************************************************/
-
-    var methods = {
-
-        init : function ( options ) {
-            /* Default settings */
-            var options = $.extend( {
-                'checkboxes': false
-            }, options);
-
-            return this.each(function() {
-                var $this = $(this);
-                /* Events */
-                $this.on('show.Datatables', methods.show);
-
-                /* An object that will hold private variables and methods */
-               var hazelnut = new Hazelnut (options);
-                $this.data('Hazelnut', hazelnut);
-
-                var query_channel   = '/query/' + options.query_uuid + '/changed';
-                var update_channel  = '/update-set/' + options.query_uuid;
-                var results_channel = '/results/' + options.query_uuid + '/changed';
-
-               // xxx not tested yet
-                $.subscribe(query_channel,  function(e, query) { hazelnut.set_query(query); });
-               // xxx not tested yet
-                $.subscribe(update_channel, function(e, resources, instance) { hazelnut.set_resources(resources, instance); });
-               // expected to work
-                $.subscribe(results_channel, $this, function(e, rows) { hazelnut.update_plugin(e,rows); });
-               if (debug) messages.debug("hazelnut '" + this.id + "' subscribed to e.g." + results_channel);
-
-            }); // this.each
-        }, // init
-
-        destroy : function( ) {
-            return this.each(function() {
-                var $this = $(this);
-                var hazelnut = $this.data('Hazelnut');
-
-                // Unbind all events using namespacing
-                $(window).unbind('Hazelnut');
-
-                // Remove associated data
-                hazelnut.remove();
-                $this.removeData('Hazelnut');
-            });
-        }, // destroy
-
-        show : function( ) {
-           var $this=$(this);
-           // xxx wtf. why [1] ? would expect 0...
-           if (debug) messages.debug("Hitting suspicious line in hazelnut.show");
-            var oTable = $($('.dataTable', $this)[1]).dataTable();
-            oTable.fnAdjustColumnSizing()
-    
-            /* Refresh dataTabeles if click on the menu to display it : fix dataTables 1.9.x Bug */        
-            $(this).each(function(i,elt) {
-                if (jQuery(elt).hasClass('dataTables')) {
-                    var myDiv=jQuery('#hazelnut-' + this.id).parent();
-                    if(myDiv.height()==0) {
-                        var oTable=$('#hazelnut-' + this.id).dataTable();            
-                        oTable.fnDraw();
-                    }
-                }
-            });
-        } // show
-
-    }; // var methods;
-
-
-    /***************************************************************************
-     * Hazelnut object
-     ***************************************************************************/
-    function Hazelnut(options) {
-        /* member variables */
-        this.options = options;
-       // xxx thierry : initialize this here - it was not, I expect this relied on set_query somehow..
-        //this.current_query = null;
-       this.current_query=manifold.find_query(this.options.query_uuid);
-//     if (debug) messages.debug("Hazelnut constructor: have set current_query -> " + this.current_query.__repr());
-       this.query_update = null;
-        this.current_resources = Array();
-
-        var object = this;
-
-        /* Transforms the table into DataTable, and keep a pointer to it */
-       actual_options = {
-            // Customize the position of Datatables elements (length,filter,button,...)
-           // we use a fluid row on top and another on the bottom, making sure we take 12 grid elt's each time
-           sDom: "<'row-fluid'<'span5'l><'span1'r><'span6'f>>t<'row-fluid'<'span5'i><'span7'p>>",
-            sPaginationType: 'bootstrap',
-            // Handle the null values & the error : Datatables warning Requested unknown parameter
-            // http://datatables.net/forums/discussion/5331/datatables-warning-...-requested-unknown-parameter/p2
-            aoColumnDefs: [{sDefaultContent: '',aTargets: [ '_all' ]}],
-           // WARNING: this one causes tables in a 'tabs' that are not exposed at the time this is run to show up empty
-            // sScrollX: '100%',       /* Horizontal scrolling */
-            bProcessing: true,      /* Loading */
-            fnDrawCallback: function() { hazelnut_draw_callback.call(object, options); }
-        };
-       // the intention here is that options.datatables_options as coming from the python object take precedence
-       $.extend(actual_options, options.datatables_options );
-        this.table = $('#hazelnut-' + options.plugin_uuid).dataTable(actual_options);
-
-        /* Setup the SelectAll button in the dataTable header */
-       /* xxx not sure this is still working */
-        var oSelectAll = $('#datatableSelectAll-'+ options.plugin_uuid);
-        oSelectAll.html("<span class='ui-icon ui-icon-check' style='float:right;display:inline-block;'></span>Select All");
-        oSelectAll.button();
-        oSelectAll.css('font-size','11px');
-        oSelectAll.css('float','right');
-        oSelectAll.css('margin-right','15px');
-        oSelectAll.css('margin-bottom','5px');
-        oSelectAll.unbind('click');
-        oSelectAll.click(selectAll);
-
-        /* Add a filtering function to the current table 
-         * Note: we use closure to get access to the 'options'
-         */
-        $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) { 
-            /* No filtering if the table does not match */
-            if (oSettings.nTable.id != "hazelnut-" + options.plugin_uuid)
-                return true;
-            return hazelnut_filter.call(object, oSettings, aData, iDataIndex);
-        });
-
-        /* methods */
-
-        this.set_query = function(query) {
-           messages.info('hazelnut.set_query');
-            var options = this.options;
-            /* Compare current and advertised query to get added and removed fields */
-            previous_query = this.current_query;
-            /* Save the query as the current query */
-            this.current_query = query;
-           if (debug) messages.debug("hazelnut.set_query, current_query is now -> " + this.current_query);
-            /* We check all necessary fields : in column editor I presume XXX */
-            // XXX ID naming has no plugin_uuid
-            if (typeof(query.fields) != 'undefined') {        
-                $.each (query.fields, function(index, value) { 
-                    if (!$('#hazelnut-checkbox-' + options.plugin_uuid + "-" + value).attr('checked'))
-                        $('#hazelnut-checkbox-' + options.plugin_uuid + "-" + value).attr('checked', true);
-                });
-            }
-            /*Process updates in filters / current_query must be updated before this call for filtering ! */
-            this.table.fnDraw();
-
-            /*
-             * Process updates in fields
-             */
-            if (typeof(query.fields) != 'undefined') {     
-                /* DataTable Settings */
-                var oSettings = this.table.dataTable().fnSettings();
-                var cols = oSettings.aoColumns;
-                var colnames = cols.map(function(x) {return x.sTitle});
-                colnames = $.grep(colnames, function(value) {return value != "+/-";});
-
-                if (previous_query == null) {
-                    var added_fields = query.fields;
-                    var removed_fields = colnames;            
-                    removed_fields = $.grep(colnames, function(x) { return $.inArray(x, added_fields) == -1});
-                } else {
-                    var tmp = previous_query.diff_fields(query);
-                    var added_fields = tmp.added;
-                    var removed_fields = tmp.removed;
-                }
-
-                /* Hide/unhide columns to match added/removed fields */
-                var object = this;
-                $.each(added_fields, function (index, field) {            
-                    var index = object.getColIndex(field,cols);
-                    if(index != -1)
-                        object.table.fnSetColumnVis(index, true);
-                });
-                $.each(removed_fields, function (index, field) {
-                    var index = object.getColIndex(field,cols);
-                    if(index != -1)
-                        object.table.fnSetColumnVis(index, false);
-                });            
-            }
-        }
-
-        this.set_resources = function(resources, instance) {
-           if (debug) messages.debug("entering hazelnut.set_resources");
-            var options = this.options;
-            var previous_resources = this.current_resources;
-            this.current_resources = resources;
-    
-            /* We uncheck all checkboxes ... */
-            $('hazelnut-checkbox-' + options.plugin_uuid).attr('checked', false);
-            /* ... and check the ones specified in the resource list */
-            $.each(this.current_resources, function(index, urn) {
-                $('#hazelnut-checkbox-' + options.plugin_uuid + "-" + urn).attr('checked', true)
-            });
-            
-        }
-
-        /**
-         * @brief Determine index of key in the table columns 
-         * @param key
-         * @param cols
-         */
-        this.getColIndex = function(key, cols) {
-            var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
-            return (tabIndex.length > 0) ? tabIndex[0] : -1;
-        }
-    
-        /**
-         * @brief
-         * XXX will be removed/replaced
-         */
-        this.selected_changed = function(e, change) {
-           if (debug) messages.debug("entering hazelnut.selected_changed");
-            var actions = change.split("/");
-            if (actions.length > 1) {
-                var oNodes = this.table.fnGetNodes();
-                var myNode = $.grep(oNodes, function(value) {
-                    if (value.id == actions[1]) { return value; }
-                });                
-                if( myNode.length>0 ) {
-                    if ((actions[2]=="add" && actions[0]=="cancel") || actions[0]=="del")
-                        checked='';
-                    else
-                        checked="checked='checked' ";
-                    var newValue = this.checkbox(actions[1], 'node', checked, false);
-                    var columnPos = this.table.fnSettings().aoColumns.length - 1;
-                    this.table.fnUpdate(newValue, myNode[0], columnPos);
-                    this.table.fnDraw();
-                }
-            }
-        }
-    
-        this.update_plugin = function(e, rows) {
-           // e.data is what we passed in second argument to subscribe
-           // so here it is the jquery object attached to the plugin <div>
-           var $plugindiv=e.data;
-           if (debug) messages.debug("entering hazelnut.update_plugin on id '" + $plugindiv.attr('id') + "'");
-           // clear the spinning wheel: look up an ancestor that has the need-spin class
-           // do this before we might return
-           $plugindiv.closest('.need-spin').spin(false);
-
-            var options = this.options;
-            var hazelnut = this;
-    
-           /* if we get no result, or an error, try to make that clear, and exit */
-            if (rows.length==0) {
-               if (debug) messages.debug("Empty result on hazelnut " + domid);
-               var placeholder=$(this.table).find("td.dataTables_empty");
-               console.log("placeholder "+placeholder);
-               if (placeholder.length==1) placeholder.html(unfold.warning("Empty result"));
-               else                       this.table.html(unfold.warning("Empty result"));
-                return;
-            } else if (typeof(rows[0].error) != 'undefined') {
-               // we now should have another means to report errors that this inline/embedded hack
-               if (debug) messages.error ("undefined result on " + domid + " - should not happen anymore");
-                this.table.html(unfold.error(rows[0].error));
-                return;
-            }
-
-           /* 
-            * fill the dataTables object
-            * we cannot set html content directly here, need to use fnAddData
-            */
-            var lines = new Array();
-    
-            this.current_resources = Array();
-    
-            $.each(rows, function(index, row) {
-               // this models a line in dataTables, each element in the line describes a cell
-                line = new Array();
-     
-                // go through table headers to get column names we want
-                // in order (we have temporarily hack some adjustments in names)
-                var cols = hazelnut.table.fnSettings().aoColumns;
-                var colnames = cols.map(function(x) {return x.sTitle})
-                var nb_col = cols.length;
-               /* if we've requested checkboxes, then forget about the checkbox column for now */
-                if (options.checkboxes) nb_col -= 1;
-
-               /* fill in stuff depending on the column name */
-                for (var j = 0; j < nb_col; j++) {
-                    if (typeof colnames[j] == 'undefined') {
-                        line.push('...');
-                    } else if (colnames[j] == 'hostname') {
-                        if (row['type'] == 'resource,link')
-                            //TODO: we need to add source/destination for links
-                            line.push('');
-                        else
-                            line.push(row['hostname']);
-                    } else {
-                        if (row[colnames[j]])
-                            line.push(row[colnames[j]]);
-                        else
-                            line.push('');
-                    }
-                }
-    
-               /* catch up with the last column if checkboxes were requested */
-                if (options.checkboxes) {
-                    var checked = '';
-                   // xxx problem is, we don't get this 'sliver' thing set apparently
-                    if (typeof(row['sliver']) != 'undefined') { /* It is equal to null when <sliver/> is present */
-                        checked = 'checked ';
-                        hazelnut.current_resources.push(row['urn']);
-                    }
-                    // Use a key instead of hostname (hard coded...)
-                    line.push(hazelnut.checkbox(options.plugin_uuid, row['urn'], row['type'], checked, false));
-                }
-    
-                lines.push(line);
-    
-            });
-    
-           this.table.fnClearTable();
-           if (debug) messages.debug("hazelnut.update_plugin: total of " + lines.length + " rows");
-            this.table.fnAddData(lines);
-    
-        };
-
-        this.checkbox = function (plugin_uuid, header, field, selected_str, disabled_str) {
-           var result="";
-            // Preafix id with plugin_uuid
-           result += "<input";
-           result += " class='hazelnut-checkbox-" + plugin_uuid + "'";
-           result += " id='hazelnut-checkbox-" + plugin_uuid + "-" + unfold.get_value(header) + "'";
-           result += " name='" + unfold.get_value(field) + "'";
-           result += " type='checkbox'";
-           result += selected_str;
-           result += disabled_str;
-           result += " autocomplete='off'";
-           result += " value='" + unfold.get_value(header) + "'";
-           result += "></input>";
-           return result;
-        };
-    } // constructor
-
-    /***************************************************************************
-     * Private methods
-     * xxx I'm not sure why this should not be methods in the Hazelnut class above
-     ***************************************************************************/
-
-    /** 
-     * @brief Hazelnut filtering function
-     */
-    function hazelnut_filter (oSettings, aData, iDataIndex) {
-        var cur_query = this.current_query;
-        var ret = true;
-
-        /* We have an array of filters : a filter is an array (key op val) 
-         * field names (unless shortcut)    : oSettings.aoColumns  = [ sTitle ]
-         *     can we exploit the data property somewhere ?
-         * field values (unless formatting) : aData
-         *     formatting should leave original data available in a hidden field
-         *
-         * The current line should validate all filters
-         */
-        $.each (cur_query.filters, function(index, filter) { 
-            /* XXX How to manage checkbox ? */
-            var key = filter[0]; 
-            var op = filter[1];
-            var value = filter[2];
-
-            /* Determine index of key in the table columns */
-            var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
-
-            /* Unknown key: no filtering */
-            if (typeof(col) == 'undefined')
-                return;
-
-            col_value=unfold.get_value(aData[col]);
-            /* Test whether current filter is compatible with the column */
-            if (op == '=' || op == '==') {
-                if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
-                    ret = false;
-            }else if (op == '!=') {
-                if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
-                    ret = false;
-            } else if(op=='<') {
-                if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
-                    ret = false;
-            } else if(op=='>') {
-                if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
-                    ret = false;
-            } else if(op=='<=' || op=='≤') {
-                if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
-                    ret = false;
-            } else if(op=='>=' || op=='≥') {
-                if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
-                    ret = false;
-            }else{
-                // How to break out of a loop ?
-                alert("filter not supported");
-                return false;
-            }
-
-        });
-        return ret;
-    }
-
-    function hazelnut_draw_callback() {
-        var options = this.options;
-        /* 
-         * Handle clicks on checkboxes: reassociate checkbox click every time
-         * the table is redrawn 
-         */
-        $('.hazelnut-checkbox-' + options.plugin_uuid).unbind('click');
-        $('.hazelnut-checkbox-' + options.plugin_uuid).click({instance: this}, check_click);
-
-        if (!this.table)
-            return;
-
-        /* Remove pagination if we show only a few results */
-        var wrapper = this.table; //.parent().parent().parent();
-        var rowsPerPage = this.table.fnSettings()._iDisplayLength;
-        var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
-        var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
-
-        if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
-            $('.hazelnut_paginate', wrapper).css('visibility', 'hidden');
-        } else {
-            $('.hazelnut_paginate', wrapper).css('visibility', 'visible');
-        }
-
-        if ( rowsToShow <= minRowsPerPage ) {
-            $('.hazelnut_length', wrapper).css('visibility', 'hidden');
-        } else {
-            $('.hazelnut_length', wrapper).css('visibility', 'visible');
-        }
-    }
-
-    function check_click (e) {
-        var object = e.data.instance;
-        var value = this.value;
-
-        if (this.checked) {
-            object.current_resources.push(value);
-        } else {
-            tmp = $.grep(object.current_resources, function(x) { return x != value; });
-            object.current_resources = tmp;
-        }
-
-        /* inform slice that our selected resources have changed */
-        $.publish('/update-set/' + object.options.query_uuid, [object.current_resources, true]);
-
-    }
-
-    function selectAll() {
-        // requires jQuery id
-        var uuid=this.id.split("-");
-        var oTable=$("#hazelnut-"+uuid[1]).dataTable();
-        // Function available in Hazelnut 1.9.x
-        // Filter : displayed data only
-        var filterData = oTable._('tr', {"filter":"applied"});   
-        /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */        
-        if(filterData.length<=100){
-            $.each(filterData, function(index, obj) {
-                var last=$(obj).last();
-                var key_value=unfold.get_value(last[0]);
-                if(typeof($(last[0]).attr('checked'))=="undefined"){
-                    $.publish('selected', 'add/'+key_value);
-                }
-            });
-        }
-    }
-    
-})( jQuery );
diff --git a/plugins/hazelnut/hazelnut.py b/plugins/hazelnut/hazelnut.py
deleted file mode 100644 (file)
index e2b3a7c..0000000
+++ /dev/null
@@ -1,42 +0,0 @@
-from unfold.plugin import Plugin
-
-class Hazelnut (Plugin):
-
-    # set checkboxes if a final column with checkboxes is desired
-    # pass columns as the initial set of columns
-    #   if None then this is taken from the query's fields
-    def __init__ (self, query, checkboxes=False, columns=None, datatables_options={}, **settings):
-        Plugin.__init__ (self, **settings)
-        self.query=query
-        self.checkboxes=checkboxes
-        if columns is not None:
-            self.columns=columns
-        else:
-            self.columns=self.query.fields
-        self.datatables_options=datatables_options
-
-    def template_file (self):
-        return "hazelnut.html"
-
-    def template_env (self, request):
-        env={}
-        env.update(self.__dict__)
-        env['columns']=self.columns
-        return env
-
-    def requirements (self):
-        reqs = {
-            'js_files' : [ "js/hazelnut.js", 
-                           "js/manifold.js", "js/manifold-query.js", 
-                           "js/dataTables.js", "js/dataTables.bootstrap.js", "js/with-datatables.js",
-                           "js/spin.presets.js", "js/spin.min.js", "js/jquery.spin.js", 
-                           "js/unfold-helper.js",
-                           ] ,
-            'css_files': [ "css/hazelnut.css" , 
-                           "css/dataTables.bootstrap.css",
-                           ],
-            }
-        return reqs
-
-    # the list of things passed to the js plugin
-    def json_settings_list (self): return ['plugin_uuid','query_uuid','checkboxes','datatables_options']
diff --git a/plugins/hazelnut/static/hazelnut.html b/plugins/hazelnut/static/hazelnut.html
new file mode 100644 (file)
index 0000000..b49161b
--- /dev/null
@@ -0,0 +1,33 @@
+<div id='main-{{ domid }}'>
+  <table class='table table-striped table-bordered dataTable' id='{{domid}}__table'>
+    <thead>
+      <tr>
+        {% for column in columns %}
+        <th>{{ column }}</th>
+        {% endfor %} 
+        {% for column in hidden_columns %}
+        <th>{{ column }}</th>
+        {% endfor %} 
+        {% if checkboxes %}
+               <th>+/-</th>
+               {% endif %}
+         </tr>
+       </thead> 
+    <tbody>
+    </tbody>
+    <tfoot>
+      <tr>
+        {% for column in columns %}
+           <th>{{ column }}</th>
+        {% endfor %} 
+        {% for column in hidden_columns %}
+           <th>{{ column }}</th>
+        {% endfor %} 
+        {% if checkboxes %}
+               <th>+/-</th>
+               {% endif %}
+         </tr>
+    </tfoot> 
+  </table>
+</div>
+<div class="hazelnut-spacer"></div>
diff --git a/plugins/hazelnut/static/js/hazelnut.js b/plugins/hazelnut/static/js/hazelnut.js
new file mode 100644 (file)
index 0000000..ca63e1e
--- /dev/null
@@ -0,0 +1,591 @@
+/**
+ * Description: display a query result in a datatables-powered <table>
+ * Copyright (c) 2012-2013 UPMC Sorbonne Universite - INRIA
+ * License: GPLv3
+ */
+
+(function($){
+
+    // TEMP
+    var debug=false;
+    debug=true
+
+    var Hazelnut = Plugin.extend({
+
+        init: function(options, element) 
+        {
+            this._super(options, element);
+
+            /* Member variables */
+            // query status
+            this.received_all = false;
+            this.received_set = false;
+            this.in_set_buffer = Array();
+
+            /* XXX Events XXX */
+            // this.$element.on('show.Datatables', this.on_show);
+            this.el().on('show', this, this.on_show);
+            // Unbind all events using namespacing
+            // TODO in destructor
+            // $(window).unbind('Hazelnut');
+
+            var query = manifold.query_store.find_analyzed_query(this.options.query_uuid);
+            this.method = query.object;
+
+            var keys = manifold.metadata.get_key(this.method);
+            this.key = (keys && keys.length == 1) ? keys[0] : null;
+
+            /* Setup query and record handlers */
+            this.listen_query(options.query_uuid);
+            this.listen_query(options.query_all_uuid, 'all');
+
+            /* GUI setup and event binding */
+            this.initialize_table();
+        },
+
+        default_options: {
+            'checkboxes': false
+        },
+
+        /* PLUGIN EVENTS */
+
+        on_show: function(e)
+        {
+            var self = e.data;
+
+            self.table.fnAdjustColumnSizing()
+        
+            /* Refresh dataTabeles if click on the menu to display it : fix dataTables 1.9.x Bug */        
+            /* temp disabled... useful ? -- jordan
+            $(this).each(function(i,elt) {
+                if (jQuery(elt).hasClass('dataTables')) {
+                    var myDiv=jQuery('#hazelnut-' + this.id).parent();
+                    if(myDiv.height()==0) {
+                        var oTable=$('#hazelnut-' + this.id).dataTable();            
+                        oTable.fnDraw();
+                    }
+                }
+            });
+            */
+        }, // on_show
+
+        /* GUI EVENTS */
+
+        /* GUI MANIPULATION */
+
+        initialize_table: function() 
+        {
+            /* Transforms the table into DataTable, and keep a pointer to it */
+            var self = this;
+            actual_options = {
+                // Customize the position of Datatables elements (length,filter,button,...)
+                // we use a fluid row on top and another on the bottom, making sure we take 12 grid elt's each time
+                sDom: "<'row-fluid'<'span5'l><'span1'r><'span6'f>>t<'row-fluid'<'span5'i><'span7'p>>",
+                sPaginationType: 'bootstrap',
+                // Handle the null values & the error : Datatables warning Requested unknown parameter
+                // http://datatables.net/forums/discussion/5331/datatables-warning-...-requested-unknown-parameter/p2
+                aoColumnDefs: [{sDefaultContent: '',aTargets: [ '_all' ]}],
+                // WARNING: this one causes tables in a 'tabs' that are not exposed at the time this is run to show up empty
+                // sScrollX: '100%',       /* Horizontal scrolling */
+                bProcessing: true,      /* Loading */
+                fnDrawCallback: function() { self._hazelnut_draw_callback.call(self); }
+                // XXX use $.proxy here !
+            };
+            // the intention here is that options.datatables_options as coming from the python object take precedence
+            //  XXX DISABLED by jordan: was causing errors in datatables.js     $.extend(actual_options, options.datatables_options );
+            this.table = this.el('table').dataTable(actual_options);
+
+            /* Setup the SelectAll button in the dataTable header */
+            /* xxx not sure this is still working */
+            var oSelectAll = $('#datatableSelectAll-'+ this.options.plugin_uuid);
+            oSelectAll.html("<span class='ui-icon ui-icon-check' style='float:right;display:inline-block;'></span>Select All");
+            oSelectAll.button();
+            oSelectAll.css('font-size','11px');
+            oSelectAll.css('float','right');
+            oSelectAll.css('margin-right','15px');
+            oSelectAll.css('margin-bottom','5px');
+            oSelectAll.unbind('click');
+            oSelectAll.click(this._selectAll);
+
+            /* Add a filtering function to the current table 
+             * Note: we use closure to get access to the 'options'
+             */
+            $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) { 
+                /* No filtering if the table does not match */
+                if (oSettings.nTable.id != "hazelnut-" + self.options.plugin_uuid)
+                    return true;
+                return this._hazelnut_filter.call(self, oSettings, aData, iDataIndex);
+            });
+
+            /* Processing hidden_columns */
+            $.each(this.options.hidden_columns, function(i, field) {
+                self.hide_column(field);
+            });
+        }, // initialize_table
+
+        /**
+         * @brief Determine index of key in the table columns 
+         * @param key
+         * @param cols
+         */
+        getColIndex: function(key, cols) {
+            var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
+            return (tabIndex.length > 0) ? tabIndex[0] : -1;
+        }, // getColIndex
+
+ // UNUSED ? //         this.update_plugin = function(e, rows) {
+ // UNUSED ? //             // e.data is what we passed in second argument to subscribe
+ // UNUSED ? //             // so here it is the jquery object attached to the plugin <div>
+ // UNUSED ? //             var $plugindiv=e.data;
+ // UNUSED ? //             if (debug)
+ // UNUSED ? //                 messages.debug("entering hazelnut.update_plugin on id '" + $plugindiv.attr('id') + "'");
+ // UNUSED ? //             // clear the spinning wheel: look up an ancestor that has the need-spin class
+ // UNUSED ? //             // do this before we might return
+ // UNUSED ? //             $plugindiv.closest('.need-spin').spin(false);
+ // UNUSED ? // 
+ // UNUSED ? //             var options = this.options;
+ // UNUSED ? //             var hazelnut = this;
+ // UNUSED ? //     
+ // UNUSED ? //             /* if we get no result, or an error, try to make that clear, and exit */
+ // UNUSED ? //             if (rows.length==0) {
+ // UNUSED ? //                 if (debug) 
+ // UNUSED ? //                     messages.debug("Empty result on hazelnut " + this.options.domid);
+ // UNUSED ? //                 var placeholder=$(this.table).find("td.dataTables_empty");
+ // UNUSED ? //                 console.log("placeholder "+placeholder);
+ // UNUSED ? //                 if (placeholder.length==1) 
+ // UNUSED ? //                     placeholder.html(unfold.warning("Empty result"));
+ // UNUSED ? //                 else
+ // UNUSED ? //                     this.table.html(unfold.warning("Empty result"));
+ // UNUSED ? //                     return;
+ // UNUSED ? //             } else if (typeof(rows[0].error) != 'undefined') {
+ // UNUSED ? //                 // we now should have another means to report errors that this inline/embedded hack
+ // UNUSED ? //                 if (debug) 
+ // UNUSED ? //                     messages.error ("undefined result on " + this.options.domid + " - should not happen anymore");
+ // UNUSED ? //                 this.table.html(unfold.error(rows[0].error));
+ // UNUSED ? //                 return;
+ // UNUSED ? //             }
+ // UNUSED ? // 
+ // UNUSED ? //             /* 
+ // UNUSED ? //              * fill the dataTables object
+ // UNUSED ? //              * we cannot set html content directly here, need to use fnAddData
+ // UNUSED ? //              */
+ // UNUSED ? //             var lines = new Array();
+ // UNUSED ? //     
+ // UNUSED ? //             this.current_resources = Array();
+ // UNUSED ? //     
+ // UNUSED ? //             $.each(rows, function(index, row) {
+ // UNUSED ? //                 // this models a line in dataTables, each element in the line describes a cell
+ // UNUSED ? //                 line = new Array();
+ // UNUSED ? //      
+ // UNUSED ? //                 // go through table headers to get column names we want
+ // UNUSED ? //                 // in order (we have temporarily hack some adjustments in names)
+ // UNUSED ? //                 var cols = object.table.fnSettings().aoColumns;
+ // UNUSED ? //                 var colnames = cols.map(function(x) {return x.sTitle})
+ // UNUSED ? //                 var nb_col = cols.length;
+ // UNUSED ? //                 /* if we've requested checkboxes, then forget about the checkbox column for now */
+ // UNUSED ? //                 if (options.checkboxes) nb_col -= 1;
+ // UNUSED ? // 
+ // UNUSED ? //                 /* fill in stuff depending on the column name */
+ // UNUSED ? //                 for (var j = 0; j < nb_col; j++) {
+ // UNUSED ? //                     if (typeof colnames[j] == 'undefined') {
+ // UNUSED ? //                         line.push('...');
+ // UNUSED ? //                     } else if (colnames[j] == 'hostname') {
+ // UNUSED ? //                         if (row['type'] == 'resource,link')
+ // UNUSED ? //                             //TODO: we need to add source/destination for links
+ // UNUSED ? //                             line.push('');
+ // UNUSED ? //                         else
+ // UNUSED ? //                             line.push(row['hostname']);
+ // UNUSED ? //                     } else {
+ // UNUSED ? //                         if (row[colnames[j]])
+ // UNUSED ? //                             line.push(row[colnames[j]]);
+ // UNUSED ? //                         else
+ // UNUSED ? //                             line.push('');
+ // UNUSED ? //                     }
+ // UNUSED ? //                 }
+ // UNUSED ? //     
+ // UNUSED ? //                 /* catch up with the last column if checkboxes were requested */
+ // UNUSED ? //                 if (options.checkboxes) {
+ // UNUSED ? //                     var checked = '';
+ // UNUSED ? //                     // xxx problem is, we don't get this 'sliver' thing set apparently
+ // UNUSED ? //                     if (typeof(row['sliver']) != 'undefined') { /* It is equal to null when <sliver/> is present */
+ // UNUSED ? //                         checked = 'checked ';
+ // UNUSED ? //                         hazelnut.current_resources.push(row[ELEMENT_KEY]);
+ // UNUSED ? //                     }
+ // UNUSED ? //                     // Use a key instead of hostname (hard coded...)
+ // UNUSED ? //                     line.push(hazelnut.checkbox(options.plugin_uuid, row[ELEMENT_KEY], row['type'], checked, false));
+ // UNUSED ? //                 }
+ // UNUSED ? //     
+ // UNUSED ? //                 lines.push(line);
+ // UNUSED ? //     
+ // UNUSED ? //             });
+ // UNUSED ? //     
+ // UNUSED ? //             this.table.fnClearTable();
+ // UNUSED ? //             if (debug)
+ // UNUSED ? //                 messages.debug("hazelnut.update_plugin: total of " + lines.length + " rows");
+ // UNUSED ? //             this.table.fnAddData(lines);
+ // UNUSED ? //         
+ // UNUSED ? //         }, // update_plugin
+
+        checkbox: function (key, value)
+        {
+            var result="";
+            // Prefix id with plugin_uuid
+            result += "<input";
+            result += " class='hazelnut-checkbox'";
+            result += " id='" + this.id('checkbox', this.id_from_key(key, value)) + "'";
+            result += " name='" + key + "'";
+            result += " type='checkbox'";
+            result += " autocomplete='off'";
+            result += " value='" + value + "'";
+            result += "></input>";
+            return result;
+        }, // checkbox
+
+
+        new_record: function(record)
+        {
+            // this models a line in dataTables, each element in the line describes a cell
+            line = new Array();
+     
+            // go through table headers to get column names we want
+            // in order (we have temporarily hack some adjustments in names)
+            var cols = this.table.fnSettings().aoColumns;
+            var colnames = cols.map(function(x) {return x.sTitle})
+            var nb_col = cols.length;
+            /* if we've requested checkboxes, then forget about the checkbox column for now */
+            if (this.options.checkboxes) nb_col -= 1;
+
+            /* fill in stuff depending on the column name */
+            for (var j = 0; j < nb_col; j++) {
+                if (typeof colnames[j] == 'undefined') {
+                    line.push('...');
+                } else if (colnames[j] == 'hostname') {
+                    if (record['type'] == 'resource,link')
+                        //TODO: we need to add source/destination for links
+                        line.push('');
+                    else
+                        line.push(record['hostname']);
+                } else {
+                    if (record[colnames[j]])
+                        line.push(record[colnames[j]]);
+                    else
+                        line.push('');
+                }
+            }
+    
+            /* catch up with the last column if checkboxes were requested */
+            if (this.options.checkboxes)
+                // Use a key instead of hostname (hard coded...)
+                // XXX remove the empty checked attribute
+                line.push(this.checkbox(this.key, record[this.key]));
+    
+            // XXX Is adding an array of lines more efficient ?
+            this.table.fnAddData(line);
+
+        },
+
+        clear_table: function()
+        {
+            this.table.fnClearTable();
+        },
+
+        redraw_table: function()
+        {
+            this.table.fnDraw();
+        },
+
+        show_column: function(field)
+        {
+            var oSettings = this.table.fnSettings();
+            var cols = oSettings.aoColumns;
+            var index = this.getColIndex(field,cols);
+            if (index != -1)
+                this.table.fnSetColumnVis(index, true);
+        },
+
+        hide_column: function(field)
+        {
+            var oSettings = this.table.fnSettings();
+            var cols = oSettings.aoColumns;
+            var index = this.getColIndex(field,cols);
+            if (index != -1)
+                this.table.fnSetColumnVis(index, false);
+        },
+
+        set_checkbox: function(record, checked)
+        {
+            /* Default: checked = true */
+            if (typeof checked === 'undefined')
+                checked = true;
+
+            var key_value;
+            /* The function accepts both records and their key */
+            switch (manifold.get_type(record)) {
+                case TYPE_VALUE:
+                    key_value = record;
+                    break;
+                case TYPE_RECORD:
+                    /* XXX Test the key before ? */
+                    key_value = record[this.key];
+                    break;
+                default:
+                    throw "Not implemented";
+                    break;
+            }
+
+
+            var checkbox_id = this.id('checkbox', this.id_from_key(this.key, key_value));
+            checkbox_id = '#' + checkbox_id.replace(/\./g, '\\.');
+
+            var element = $(checkbox_id, this.table.fnGetNodes());
+
+            element.attr('checked', checked);
+        },
+
+        /*************************** QUERY HANDLER ****************************/
+
+        on_filter_added: function(filter)
+        {
+            // XXX
+            this.redraw_table();
+        },
+
+        on_filter_removed: function(filter)
+        {
+            // XXX
+            this.redraw_table();
+        },
+        
+        on_filter_clear: function()
+        {
+            // XXX
+            this.redraw_table();
+        },
+
+        on_field_added: function(field)
+        {
+            this.show_column(field);
+        },
+
+        on_field_removed: function(field)
+        {
+            this.hide_column(field);
+        },
+
+        on_field_clear: function()
+        {
+            alert('Hazelnut::clear_fields() not implemented');
+        },
+
+        /*************************** RECORD HANDLER ***************************/
+
+        on_new_record: function(record)
+        {
+            /* NOTE in fact we are doing a join here */
+            if (this.received_all)
+                // update checkbox for record
+                this.set_checkbox(record, true);
+            else
+                // store for later update of checkboxes
+                this.in_set_buffer.push(record);
+        },
+
+        on_clear_records: function()
+        {
+        },
+
+        // Could be the default in parent
+        on_query_in_progress: function()
+        {
+            this.spin();
+        },
+
+        on_query_done: function()
+        {
+            if (this.received_all)
+                this.unspin();
+            this.received_set = true;
+        },
+        
+        on_field_state_changed: function(data)
+        {
+            switch(data.request) {
+                case FIELD_REQUEST_ADD:
+                case FIELD_REQUEST_ADD_RESET:
+                    this.set_checkbox(data.value, true);
+                    break;
+                case FIELD_REQUEST_REMOVE:
+                case FIELD_REQUEST_REMOVE_RESET:
+                    this.set_checkbox(data.value, false);
+                    break;
+                default:
+                    break;
+            }
+        },
+
+        // all
+
+        on_all_new_record: function(record)
+        {
+            this.new_record(record);
+        },
+
+        on_all_clear_records: function()
+        {
+            this.clear_table();
+
+        },
+
+        on_all_query_in_progress: function()
+        {
+            // XXX parent
+            this.spin();
+        }, // on_all_query_in_progress
+
+        on_all_query_done: function()
+        {
+            var self = this;
+            if (this.received_set) {
+                /* XXX needed ? XXX We uncheck all checkboxes ... */
+                $("[id^='datatables-checkbox-" + this.options.plugin_uuid +"']").attr('checked', false);
+
+                /* ... and check the ones specified in the resource list */
+                $.each(this.in_set_buffer, function(i, record) {
+                    self.set_checkbox(record, true);
+                });
+
+                this.unspin();
+            }
+            this.received_all = true;
+
+        }, // on_all_query_done
+
+        /************************** PRIVATE METHODS ***************************/
+
+        /** 
+         * @brief Hazelnut filtering function
+         */
+        _hazelnut_filter: function(oSettings, aData, iDataIndex)
+        {
+            var cur_query = this.current_query;
+            if (!cur_query) return true;
+            var ret = true;
+
+            /* We have an array of filters : a filter is an array (key op val) 
+             * field names (unless shortcut)    : oSettings.aoColumns  = [ sTitle ]
+             *     can we exploit the data property somewhere ?
+             * field values (unless formatting) : aData
+             *     formatting should leave original data available in a hidden field
+             *
+             * The current line should validate all filters
+             */
+            $.each (cur_query.filters, function(index, filter) { 
+                /* XXX How to manage checkbox ? */
+                var key = filter[0]; 
+                var op = filter[1];
+                var value = filter[2];
+
+                /* Determine index of key in the table columns */
+                var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
+
+                /* Unknown key: no filtering */
+                if (typeof(col) == 'undefined')
+                    return;
+
+                col_value=unfold.get_value(aData[col]);
+                /* Test whether current filter is compatible with the column */
+                if (op == '=' || op == '==') {
+                    if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
+                        ret = false;
+                }else if (op == '!=') {
+                    if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
+                        ret = false;
+                } else if(op=='<') {
+                    if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
+                        ret = false;
+                } else if(op=='>') {
+                    if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
+                        ret = false;
+                } else if(op=='<=' || op=='≤') {
+                    if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
+                        ret = false;
+                } else if(op=='>=' || op=='≥') {
+                    if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
+                        ret = false;
+                }else{
+                    // How to break out of a loop ?
+                    alert("filter not supported");
+                    return false;
+                }
+
+            });
+            return ret;
+        },
+
+        _hazelnut_draw_callback: function()
+        {
+            /* 
+             * Handle clicks on checkboxes: reassociate checkbox click every time
+             * the table is redrawn 
+             */
+            this.els('hazelnut-checkbox').unbind('click').click(this, this._check_click);
+
+            if (!this.table)
+                return;
+
+            /* Remove pagination if we show only a few results */
+            var wrapper = this.table; //.parent().parent().parent();
+            var rowsPerPage = this.table.fnSettings()._iDisplayLength;
+            var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
+            var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
+
+            if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
+                $('.hazelnut_paginate', wrapper).css('visibility', 'hidden');
+            } else {
+                $('.hazelnut_paginate', wrapper).css('visibility', 'visible');
+            }
+
+            if ( rowsToShow <= minRowsPerPage ) {
+                $('.hazelnut_length', wrapper).css('visibility', 'hidden');
+            } else {
+                $('.hazelnut_length', wrapper).css('visibility', 'visible');
+            }
+        },
+
+        _check_click: function(e) 
+        {
+            e.stopPropagation();
+
+            var self = e.data;
+
+            // XXX this.value = key of object to be added... what about multiple keys ?
+            manifold.raise_event(self.options.query_uuid, this.checked?SET_ADD:SET_REMOVED, this.value);
+            //return false; // prevent checkbox to be checked, waiting response from manifold plugin api
+            
+        },
+
+        _selectAll: function() 
+        {
+            // requires jQuery id
+            var uuid=this.id.split("-");
+            var oTable=$("#hazelnut-"+uuid[1]).dataTable();
+            // Function available in Hazelnut 1.9.x
+            // Filter : displayed data only
+            var filterData = oTable._('tr', {"filter":"applied"});   
+            /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */        
+            if(filterData.length<=100){
+                $.each(filterData, function(index, obj) {
+                    var last=$(obj).last();
+                    var key_value=unfold.get_value(last[0]);
+                    if(typeof($(last[0]).attr('checked'))=="undefined"){
+                        $.publish('selected', 'add/'+key_value);
+                    }
+                });
+            }
+        },
+
+    });
+
+    $.plugin('Hazelnut', Hazelnut);
+
+})(jQuery);
similarity index 55%
rename from plugins/lists/simplelist.js
rename to plugins/lists/static/js/simplelist.js
index 11f812b..545c04c 100644 (file)
     // complexity here is mostly because a datatables-enabled table cannot
     // be updated in a "normal" way using .html()
     function update_plugin(e, rows) {
-       // e.data is what we passed in second argument to subscribe
-       // so here it is the jquery object attached to the plugin <div>
-       var $plugindiv=e.data;
-       // locate the <table> element; with datatables in the way,
-       // this might not be a direct son of the div-plugin
-       var $table=$plugindiv.find("table.simplelist").first();
-       // also we may or may not have a header
-       var $tbody=$table.find("tbody.simplelist").first();
-       var use_datatables = $table.hasClass("with-datatables");
-       if (debug) messages.debug($plugindiv.attr('id') + " udt= " + use_datatables);
+        // e.data is what we passed in second argument to subscribe
+        // so here it is the jquery object attached to the plugin <div>
+        var $plugindiv = e.data;
+        // locate the <table> element; with datatables in the way,
+        // this might not be a direct son of the div-plugin
+        var $table = $plugindiv.find("table.simplelist").first();
+        // also we may or may not have a header
+        var $tbody = $table.find("tbody.simplelist").first();
+        var use_datatables = $table.hasClass("with-datatables");
+        if (debug) 
+            messages.debug($plugindiv.attr('id') + " udt= " + use_datatables);
        
        // clear the spinning wheel: look up an ancestor that has the need-spin class
        // do this before we might return
-       $plugindiv.closest('.need-spin').spin(false);
+           $plugindiv.closest('.need-spin').spin(false);
 
         if (rows.length == 0) {
-           if (use_datatables) datatables_set_message ($table, $tbody, unfold.warning("No result"));
-           else                regular_set_message ($table, $tbody, unfold.warning("No result"));
+               if (use_datatables)
+                 datatables_set_message ($table, $tbody, unfold.warning("No result"));
+               else
+                       regular_set_message ($table, $tbody, unfold.warning("No result"));
             return;
         }
+
         if (typeof rows[0].error != 'undefined') {
-           var error="ERROR: " + rows[0].error;
-           if (use_datatables) datatables_set_message ($table, $tbody, unfold.error(error));
-           else                regular_set_message ($table, $tbody, unfold.error(error));
+               var error="ERROR: " + rows[0].error;
+               if (use_datatables) 
+                datatables_set_message ($table, $tbody, unfold.error(error));
+               else
+                       regular_set_message ($table, $tbody, unfold.error(error));
             return;
         }
+
         var options = $plugindiv.data().SimpleList;
-       if (use_datatables)     datatables_update_table ($table,$tbody,rows,options.key);
-       else                    regular_update_table ($table,$tbody,rows,options.key);
+           if (use_datatables) 
+            datatables_update_table($table, $tbody, rows, options.key);
+           else
+                       regular_update_table($table, $tbody, rows, options.key);
 
-    }
+        }
 
     // hard-wire a separate presentation depending on the key being used....
     function cell(key, value) {
-        if (key == 'slice_hrn') {
-            return "<i class='icon-play-circle'></i><a href='/slice/" + value + "'>" + value + "</a>";
+        if (key == 'slice.slice_hrn') {
+            return "<i class='icon-play-circle'></i><a href='/portal/slice/" + value + "'>" + value + "</a>";
         } else if (key == 'network_hrn') {
-            return "<i class='icon-play-circle'></i>" + value ;
+            return "<i class='icon-play-circle'></i><a href='/portal/platform/" + value + "'>" + value + "</a>";
         } else {
             return value;
         }
     }
 
     function regular_update_table ($table, $tbody, rows, key) {
-       if (debug) messages.debug('regular_update_table ' + rows.length + " rows");
-       var html=$.map(rows, function (row) { return html_row ( cell (key, row[key])); }).join();
-       $tbody.html(html);
+        if (debug)
+            messages.debug('regular_update_table ' + rows.length + " rows");
+           var html=$.map(rows, function (row) {
+            value = row;
+            $.each(key.split('.'), function(i, k) {
+                if ($.isArray(value)) {
+                    value = $.map(value, function(val, i) { return val[k]});
+                } else {
+                    value = value[k];
+                }
+            });
+            if ($.isArray(value)) {
+                x = $.map(value, function(val, i) { return html_row ( cell (key, val)); });
+                return x;
+            } else {
+                return html_row ( cell (key, value));
+            }
+        }).join();
+       $tbody.html(html);
     }
     
     function datatables_set_message ($table, $tbody, message) {
-       $table.dataTable().fnClearTable();
-       $table.dataTable().fnAddData( [ message ] );
-       $table.dataTable().fnDraw();
+        $table.dataTable().fnClearTable();
+        $table.dataTable().fnAddData( [ message ] );
+        $table.dataTable().fnDraw();
     }
 
     function datatables_update_table ($table, $tbody, rows, key) {
        $table.dataTable().fnDraw();
     }  
     
-    function html_row (cell) { return "<tr><td class='simplelist'>"+cell+"</td></tr>"; }
+    function html_row (cell) { 
+        return "<tr><td class='simplelist'>"+cell+"</td></tr>"; 
+    }
     
 })( jQuery );
diff --git a/plugins/myplugin/__init__.py b/plugins/myplugin/__init__.py
new file mode 100644 (file)
index 0000000..ce8e939
--- /dev/null
@@ -0,0 +1,23 @@
+from unfold.plugin import Plugin
+
+class MyPlugin(Plugin):
+
+    def template_file (self):
+        return "myplugin.html"
+
+    def requirements (self):
+        reqs = {
+            'js_files' : [
+                'js/myplugin.js'
+            ],
+            'css_files': [
+                'css/myplugin.css',
+            ]
+        }
+        return reqs
+
+    def json_settings_list (self):
+        return ['plugin_uuid', 'domid']
+
+    def export_json_settings (self):
+        return True
diff --git a/plugins/myplugin/static/css/myplugin.css b/plugins/myplugin/static/css/myplugin.css
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/plugins/myplugin/static/js/myplugin.js b/plugins/myplugin/static/js/myplugin.js
new file mode 100644 (file)
index 0000000..1801115
--- /dev/null
@@ -0,0 +1,107 @@
+/**
+ * MyPlugin:    demonstration plugin
+ * Version:     0.1
+ * Description: Template for writing new plugins and illustrating the different
+ *              possibilities of the plugin API.
+ *              This file is part of the Manifold project 
+ * Requires:    js/plugin.js
+ * URL:         http://www.myslice.info
+ * Author:      Jordan Augé <jordan.auge@lip6.fr>
+ * Copyright:   Copyright 2012-2013 UPMC Sorbonne Universités
+ * License:     GPLv3
+ */
+
+(function($){
+
+    var MyPlugin = Plugin.extend({
+
+        /** XXX to check
+         * @brief Plugin constructor
+         * @param options : an associative array of setting values
+         * @param element : 
+         * @return : a jQuery collection of objects on which the plugin is
+         *     applied, which allows to maintain chainability of calls
+         */
+        init: function(options, element) {
+            // Call the parent constructor, see FAQ when forgotten
+            this._super(options, element);
+
+            /* Member variables */
+
+            /* Plugin events */
+
+            /* Setup query and record handlers */
+
+            // Explain this will allow query events to be handled
+            // What happens when we don't define some events ?
+            // Some can be less efficient
+            this.listen_query(options.query_uuid);
+            this.listen_query(options.query_uuid, 'all');
+
+            /* GUI setup and event binding */
+            // call function
+
+        },
+
+        /* PLUGIN EVENTS */
+        // on_show like in hazelnut
+
+
+        /* GUI EVENTS */
+
+        // a function to bind events here: click change
+        // how to raise manifold events
+
+
+        /* GUI MANIPULATION */
+
+        // We advise you to write function to change behaviour of the GUI
+        // Will use naming helpers to access content _inside_ the plugin
+        // always refer to these functions in the remaining of the code
+
+        show_hide_button: function() 
+        {
+            // this.id, this.el, this.cl, this.els
+            // same output as a jquery selector with some guarantees
+        },
+
+        /* TEMPLATES */
+
+        // see in the html template
+        // How to load a template, use of mustache
+
+        /* QUERY HANDLERS */
+
+        // How to make sure the plugin is not desynchronized
+        // He should manifest its interest in filters, fields or records
+        // functions triggered only if the proper listen is done
+
+        // no prefix
+
+        on_filter_added: function(filter)
+        {
+
+        },
+
+        // ... be sure to list all events here
+
+        /* RECORD HANDLERS */
+        
+        on_record_received: function(record)
+        {
+            //
+        },
+
+        /* INTERNAL FUNCTIONS */
+        _dummy: function() {
+            // only convention, not strictly enforced at the moment
+        },
+
+    });
+
+    /* Plugin registration */
+    $.plugin('MyPlugin', MyPlugin);
+
+    // TODO Here use cases for instanciating plugins in different ways like in the pastie.
+
+})(jQuery);
diff --git a/plugins/myplugin/static/myplugin.html b/plugins/myplugin/static/myplugin.html
new file mode 100644 (file)
index 0000000..aa17633
--- /dev/null
@@ -0,0 +1,3 @@
+<div id={{ domid }}>
+<p>MyPlugin</p>
+</div>
diff --git a/plugins/pres_view/__init__.py b/plugins/pres_view/__init__.py
new file mode 100644 (file)
index 0000000..7df263c
--- /dev/null
@@ -0,0 +1,36 @@
+from unfold.plugin import Plugin
+
+class PresView(Plugin):
+
+    def template_file (self):
+        return "pres_view.html"
+
+    def requirements (self):
+        reqs = {
+            'js_files' : [
+                'js/pres_view.js',
+                'js/mootools-core.js',
+                'js/MooTools.js',
+                'js/dynamic.js',
+                'js/jquery.min.js',
+                'js/jquery-ui.min.js',
+                'http://maps.google.com/maps/api/js?sensor=false',
+                'js/initmap.js',
+                'js/recup_tout_sites.js',
+                'js/recup_data.js',
+                'js/recup_direct.js',
+                'js/recup_liste.js',
+                'js/visible.js',
+                'js/afficher_par_id.js',           ],
+            'css_files': [
+                'css/pres_view.css',
+                'css/jquery-ui.css'
+            ]
+        }
+        return reqs
+
+    def json_settings_list (self):
+        return ['plugin_uuid', 'domid']
+
+    def export_json_settings (self):
+        return True
diff --git a/plugins/pres_view/config_method_animation b/plugins/pres_view/config_method_animation
new file mode 100644 (file)
index 0000000..50256c2
--- /dev/null
@@ -0,0 +1,4 @@
+#Nom;id;contrainte;adresse_serveur;nom_method_a_utiliser;attributs;type_affichage;options_affichage;
+Noeud;2000;descriptif noeud animation;{};xmlrpc;{"server":"https://www.planet-lab.eu/PLCAPI/"};GetNodes;'site_id','name','date_created';;;
+Sites;2001;descriptif site animation;[{"ens":[{"type":"date","variable":"date_created","op":"]"}]}];xmlrpc;{"server":"https://www.planet-lab.eu/PLCAPI/"};GetSites;'site_id','name','date_created';marker;{"icon":"green"};
+CPU;2002;descriptif cpu animation;{};xmlrpc;{"server":"https://www.planet-lab.eu/PLCAPI/"};getCPU;'site_id','name','date_created';;;
\ No newline at end of file
diff --git a/plugins/pres_view/config_method_dynamic b/plugins/pres_view/config_method_dynamic
new file mode 100644 (file)
index 0000000..1d68b76
--- /dev/null
@@ -0,0 +1 @@
+getSite;1001;descriptif blabla;postmsg;xmlrpc;{"server":"https://www.planet-lab.eu/PLCAPI/","authType":"anonymous"};marker;{"alpha":"1","beta":"2"};GetSites;{">date_created":0};'site_id','name','date_created';>date_created;
\ No newline at end of file
diff --git a/plugins/pres_view/config_method_static b/plugins/pres_view/config_method_static
new file mode 100644 (file)
index 0000000..6b98f58
--- /dev/null
@@ -0,0 +1 @@
+Sites last created;3;descriptif infobulle;[{"ens":[{"type":"date","variable":"date_created","op":"]"}]}];xmlrpc;{"server":"https://www.planet-lab.eu/PLCAPI/"};GetSites;'site_id','name','date_created';line;{"color":"green"};
\ No newline at end of file
diff --git a/plugins/pres_view/config_method_static.bk b/plugins/pres_view/config_method_static.bk
new file mode 100644 (file)
index 0000000..822b101
--- /dev/null
@@ -0,0 +1,3 @@
+#Nom;id;contrainte;adresse_serveur;nom_method_a_utiliser;attributs;type_affichage;options_affichage;
+Sites;2;descriptif sites;[{"ens":[{"type":"date","variable":"date_created","op":"]"}]}];xmlrpc;{"server":"https://www.planet-lab.eu/PLCAPI/"};GetSites;'site_id','name','date_created';marker;{"icon":"green"};
+Sites-cercles;3;descriptif sites;[{"ens":[{"type":"date","variable":"date_created","op":"]"}]}];xmlrpc;{"server":"https://www.planet-lab.eu/PLCAPI/"};GetSites;'site_id','name','date_created';circle;{"visible":"true","color":"#00FF00","circle_radius_arg":"date_created","size":{"tiny":10,"small":50,"avg":100,"big":1000,"giant":5000}};
diff --git a/plugins/pres_view/daemon-todo/daemon.py b/plugins/pres_view/daemon-todo/daemon.py
new file mode 100644 (file)
index 0000000..43d690e
--- /dev/null
@@ -0,0 +1,129 @@
+#!/usr/bin/env python
+
+import sys, os, time, atexit
+from signal import SIGTERM 
+
+class Daemon:
+    """
+    A generic daemon class.
+    
+    Usage: subclass the Daemon class and override the run() method
+    """
+    def __init__(self, pidfile, stdin='/dev/null', stdout='/tmp/plab', stderr='/tmp/plab.err'):
+        self.stdin = stdin
+        self.stdout = stdout
+        self.stderr = stderr
+        self.pidfile = pidfile
+    
+    def daemonize(self):
+        """
+        do the UNIX double-fork magic, see Stevens' "Advanced 
+        Programming in the UNIX Environment" for details (ISBN 0201563177)
+        http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
+        """
+        try: 
+            pid = os.fork() 
+            if pid > 0:
+                # exit first parent
+                sys.exit(0) 
+        except OSError, e: 
+            sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno, e.strerror))
+            sys.exit(1)
+    
+        # decouple from parent environment
+        os.chdir("/var/www/lib/cgi/") 
+        os.setsid() 
+        os.umask(0) 
+    
+        # do second fork
+        try: 
+            pid = os.fork() 
+            if pid > 0:
+                # exit from second parent
+                sys.exit(0) 
+        except OSError, e: 
+            sys.stderr.write("fork #2 failed: %d (%s)\n" % (e.errno, e.strerror))
+            sys.exit(1) 
+    
+        # redirect standard file descriptors
+        sys.stdout.flush()
+        sys.stderr.flush()
+        si = file(self.stdin, 'r')
+        so = file(self.stdout, 'a+')
+        se = file(self.stderr, 'a+', 0)
+        os.dup2(si.fileno(), sys.stdin.fileno())
+        os.dup2(so.fileno(), sys.stdout.fileno())
+        os.dup2(se.fileno(), sys.stderr.fileno())
+    
+        # write pidfile
+        atexit.register(self.delpid)
+        pid = str(os.getpid())
+        file(self.pidfile,'w+').write("%s\n" % pid)
+    
+    def delpid(self):
+        os.remove(self.pidfile)
+
+    def start(self):
+        """
+        Start the daemon
+        """
+        # Check for a pidfile to see if the daemon already runs
+        try:
+            pf = file(self.pidfile,'r')
+            pid = int(pf.read().strip())
+            pf.close()
+        except IOError:
+            pid = None
+    
+        if pid:
+            message = "pidfile %s already exist. Daemon already running?\n"
+            sys.stderr.write(message % self.pidfile)
+            sys.exit(1)
+        
+        # Start the daemon
+        self.daemonize()
+        self.run()
+
+    def stop(self):
+        """
+        Stop the daemon
+        """
+        # Get the pid from the pidfile
+        try:
+            pf = file(self.pidfile,'r')
+            pid = int(pf.read().strip())
+            pf.close()
+        except IOError:
+            pid = None
+    
+        if not pid:
+            message = "pidfile %s does not exist. Daemon not running?\n"
+            sys.stderr.write(message % self.pidfile)
+            return # not an error in a restart
+
+        # Try killing the daemon process    
+        try:
+            while 1:
+                os.kill(pid, SIGTERM)
+                time.sleep(0.1)
+        except OSError, err:
+            err = str(err)
+            if err.find("No such process") > 0:
+                if os.path.exists(self.pidfile):
+                    os.remove(self.pidfile)
+            else:
+                print str(err)
+                sys.exit(1)
+
+    def restart(self):
+        """
+        Restart the daemon
+        """
+        self.stop()
+        self.start()
+
+    def run(self):
+        """
+        You should override this method when you subclass Daemon. It will be called after the process has been
+        daemonized by start() or restart().
+        """
diff --git a/plugins/pres_view/daemon-todo/event2.py b/plugins/pres_view/daemon-todo/event2.py
new file mode 100644 (file)
index 0000000..8913bbe
--- /dev/null
@@ -0,0 +1,129 @@
+# !/usr/bin/python
+# -*-coding: utf-8-*-
+
+import pickle
+import os.path
+import xmlrpclib
+import ast
+import time
+import simplejson
+
+class Event2:
+    def __init__(self, structure):
+        ##Definition des variables##
+        self.data_access_methode    =   ""
+        self.data_access_options    =   ""
+        
+        self.structure              =   structure
+        self.methode                =   ""
+        self.parameters             =   {}
+        self.return_fields          =   []
+        self.print_method           =   ""
+        self.print_options          =   ""
+        self.geo_methode            =   ""
+        self.id                     =   ""
+        self.timestamp              =   ""
+        #on paramètre timestamp, si c'est un dynamique, il sera fournit, sinon, on le met à 0
+        timestamp=0;
+        
+        ##APE###
+        self.raw                    =   ""
+        self.channel                =   ""
+        #######
+        
+        ## On creer l'objet ##
+        self.data = self.make_data(timestamp)
+        
+        
+    def split(self):
+        args = self.structure.split(";");
+        self.channel                =   args[1]  
+        self.raw                    =   args[3]
+        self.data_access_methode    =   args[4]
+        self.data_access_options    =   ast.literal_eval(args[5])
+        self.print_method           =   args[6]
+        self.print_options          =   ast.literal_eval(args[7])
+        self.methode                =   args[8]
+        self.parameters             =   ast.literal_eval(args[9])
+        self.return_fields          =   eval(args[10])
+        self.timestamp              =   args[11]
+
+    def get_event_list_from_xmlrpc(self,timestamp):
+        
+        ## on test pour voir si on est en dynamique, si c'est le cas, on met à jour la valeur du timestamp
+        if timestamp!=0:
+            self.parameters[self.timestamp]         =   int(timestamp)
+            
+            
+        ####on cree l'identification
+        auth = {}
+        if self.data_access_options["authType"]     ==  "anonymous":
+            auth["AuthMethod"]  =   "anonymous"
+            
+        elif self.data_access_options["authType"]   ==  "password":
+            auth["AuthMethod"]  =   "password"
+            auth["Username"]    =   self.data_access_options["Username"]
+            auth["AuthString"]  =   self.data_access_options["AuthString"]
+            
+        elif self.data_access_options["authType"]   ==  "session":
+            auth["AuthMethod"]  =   "session"
+            auth["session"]     =   self.data_access_options["session"]
+            
+        elif self.data_access_options["authType"]   ==  "gpg":
+            auth["AuthMethod"]  =   "gpg"
+            auth["name"]        =   self.data_access_options["name"]
+            auth["signature"]   =   self.data_access_options["signature"]
+        
+         
+        srv = xmlrpclib.Server(self.data_access_options["server"], allow_none = 1)
+        
+        
+        ##On gère en fonction des methodes
+        
+        if self.methode=="GetSites":
+            self.geo_methode="site_id";
+            try :
+                if len(self.return_fields)==0:
+                    data =  srv.GetSites(auth, self.parameters) 
+                else :
+                    data = srv.GetSites(auth, self.parameters, self.return_fields)
+            except:
+                    return self.parameters
+        else:
+            return 2
+        
+        ###on recupère la liste des localisation
+        
+        ##si il y a moins de 8 resultats, on recupère seulement la localisation de ceux-ci
+        list=[]
+        try:
+            sites_id = srv.GetSites(auth,{},["site_id","latitude","longitude"])
+        except :
+            return 3
+        try:
+            for i in data:
+                for j in sites_id:
+                    if i["site_id"]==j["site_id"]:
+                        try:
+                            pos=[{"latitude": j["latitude"], "longitude": j["longitude"]}]
+                        except:
+                            return 4
+                        i["ape_position"] = pos
+                        list.append(i)
+        except:
+            return 5    
+        return list
+        
+
+    
+    def make_data(self,timestamp):
+        try :
+            self.split()
+        except:
+            return 43
+        try :
+            if self.data_access_methode=="xmlrpc":
+                return self.get_event_list_from_xmlrpc(timestamp)
+        except: 
+            return 67
+        
diff --git a/plugins/pres_view/daemon-todo/eventc.py b/plugins/pres_view/daemon-todo/eventc.py
new file mode 100644 (file)
index 0000000..961c33f
--- /dev/null
@@ -0,0 +1,79 @@
+#!/usr/bin/env python
+
+import sys, time
+from event import Event
+import pprint
+
+
+##TEMP / DEBUG##
+import pickle
+import os.path
+import xmlrpclib
+###
+
+if __name__ == "__main__":
+    
+    liste=[]
+    
+    #event = Event("anonymous;https://www.planet-lab.eu/PLCAPI/;GetSites;{"name": "University of Colombo School of Computing"};["name","date_created"];")
+    #event2 = Event("anonymous;https://www.planet-lab.eu/PLCAPI/;GetSites;{"name": "University of Colombo School of Computing"};["name","date_created"];")
+    #event.split()
+    #event.makeAuth()
+    #liste.append(event)
+    #print event.split()
+    #event2 = Event("toto")
+    #event2.split()
+    #event2.makeAuth()
+    #liste.append(event2)
+
+   # print liste[0].data
+    #print liste[1].get_event_list_from_xmlrpc()
+    config = open("config_event", "r")
+    #for ligne in config:
+    #    print ligne.rstrip("\n\r")
+    #config.close()
+    
+    for event in liste:
+        pass#print event.data
+    
+    config = open("config_event", "r")
+    events=[]
+        #initialisation de la liste des instance d"objet event:
+    for ligne in config:
+            #on creer l"objet
+        #print ligne.rstrip("\n\r")
+        event = Event(ligne.rstrip("\n\r"))
+        events.append(event)
+    config.close()
+
+    #fichier = open("leNomDuFichier2.txt", "w")
+    for event in events:
+        
+        data = event.data
+        print data
+        #print str("-")
+        #print type(event.return_fields)
+        #print str("-")
+        #a=0
+        #for d in data:
+            #print a
+            #a=a+1
+            #print event.get_geoposition("toto")
+            #print d
+           # pass
+        #print "\n"
+        #fichier.write(data)
+        #fichier.write("pwet")
+        passs
+    #fichier.close()
+    server="https://www.planet-lab.eu/PLCAPI/"
+    auth = {}
+    auth["AuthMethod"] = "anonymous"
+    srv = xmlrpclib.Server(server, allow_none = 1)
+    sites_id = srv.GetSites(auth, {}, ["latitude","longitude"])
+    #print sites_id
+    for i in sites_id:
+        #print i
+        #print "\n"
+        #print i["longitude"],i["longitude"]
+        pass
diff --git a/plugins/pres_view/daemon-todo/eventd.py b/plugins/pres_view/daemon-todo/eventd.py
new file mode 100644 (file)
index 0000000..5f3de86
--- /dev/null
@@ -0,0 +1,69 @@
+#!/usr/bin/env python
+
+import sys, time
+from daemon import Daemon
+from event2 import Event2
+import cgi
+import urllib2
+import simplejson
+
+class MyDaemon(Daemon):    
+    def run(self):
+        self.server = 'http://0.ape.planet-lab.eu:443/?'
+        self.ape_pwd = 'testpasswd'
+        self.ape_cmd = 'inlinepush'
+        ## Ouverture et traitement du fichier de conf
+        #ouverture du fichier
+        config = open("config_method_dynamic", "r")
+        events=[]
+        #initialisation de la liste des instance d'objet event:
+        for ligne in config:
+            #on creer l'objet
+            event = Event2(ligne.rstrip('\n\r'))
+            
+            events.append(event)
+        config.close()
+        ## creation des objets et ajout dans une liste
+        timestamp=time.time()-800000
+        #timestamp_new=time.time()
+        while True:
+            for event in events:
+                event.data = event.make_data(timestamp);
+                cmd = [{"cmd": self.ape_cmd,
+                        "params": {
+                           "password": self.ape_pwd,
+                           "raw": event.raw,
+                           "channel": event.channel,
+                           "data": {
+                                "print_options": event.print_options,
+                                "print_method": event.print_method,
+                                "message": event.data
+                           }
+                       }
+                }]
+                print cmd
+                url = self.server + urllib2.quote(simplejson.dumps(cmd))
+                urllib2.urlopen(url)
+            ##pour chaque objet de la liste on regarde les data 
+            ## => il faut instancier un tableau de temps
+            ## on instancie un temps en debut de boucle ex temps=time.now()
+            time.sleep(15)
+            #timestamp=timestamp_new
+            #timestamp_new=time.time()
+
+if __name__ == "__main__":
+    daemon = MyDaemon('/tmp/daemon-example.pid')
+    if len(sys.argv) == 2:
+        if 'start' == sys.argv[1]:
+            daemon.start()
+        elif 'stop' == sys.argv[1]:
+            daemon.stop()
+        elif 'restart' == sys.argv[1]:
+            daemon.restart()
+        else:
+            print "Unknown command"
+            sys.exit(2)
+        sys.exit(0)
+    else:
+        print "usage: %s start|stop|restart" % sys.argv[0]
+        sys.exit(2)
diff --git a/plugins/pres_view/static/css/jquery-ui.css b/plugins/pres_view/static/css/jquery-ui.css
new file mode 100644 (file)
index 0000000..4cfb50a
--- /dev/null
@@ -0,0 +1,565 @@
+/*
+ * jQuery UI CSS Framework 1.8.18
+ *
+ * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ * http://jquery.org/license
+ *
+ * http://docs.jquery.com/UI/Theming/API
+ */
+
+/* Layout helpers
+----------------------------------*/
+.ui-helper-hidden { display: none; }
+.ui-helper-hidden-accessible { position: absolute !important; clip: rect(1px 1px 1px 1px); clip: rect(1px,1px,1px,1px); }
+.ui-helper-reset { margin: 0; padding: 0; border: 0; outline: 0; line-height: 1.3; text-decoration: none; font-size: 100%; list-style: none; }
+.ui-helper-clearfix:before, .ui-helper-clearfix:after { content: ""; display: table; }
+.ui-helper-clearfix:after { clear: both; }
+.ui-helper-clearfix { zoom: 1; }
+.ui-helper-zfix { width: 100%; height: 100%; top: 0; left: 0; position: absolute; opacity: 0; filter:Alpha(Opacity=0); }
+
+
+/* Interaction Cues
+----------------------------------*/
+.ui-state-disabled { cursor: default !important; }
+
+
+/* Icons
+----------------------------------*/
+
+/* states and images */
+.ui-icon { display: block; text-indent: -99999px; overflow: hidden; background-repeat: no-repeat; }
+
+
+/* Misc visuals
+----------------------------------*/
+
+/* Overlays */
+.ui-widget-overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
+
+
+/*
+ * jQuery UI CSS Framework 1.8.18
+ *
+ * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ * http://jquery.org/license
+ *
+ * http://docs.jquery.com/UI/Theming/API
+ *
+ * To view and modify this theme, visit http://jqueryui.com/themeroller/?ffDefault=Verdana,Arial,sans-serif&fwDefault=normal&fsDefault=1.1em&cornerRadius=4px&bgColorHeader=cccccc&bgTextureHeader=03_highlight_soft.png&bgImgOpacityHeader=75&borderColorHeader=aaaaaa&fcHeader=222222&iconColorHeader=222222&bgColorContent=ffffff&bgTextureContent=01_flat.png&bgImgOpacityContent=75&borderColorContent=aaaaaa&fcContent=222222&iconColorContent=222222&bgColorDefault=e6e6e6&bgTextureDefault=02_glass.png&bgImgOpacityDefault=75&borderColorDefault=d3d3d3&fcDefault=555555&iconColorDefault=888888&bgColorHover=dadada&bgTextureHover=02_glass.png&bgImgOpacityHover=75&borderColorHover=999999&fcHover=212121&iconColorHover=454545&bgColorActive=ffffff&bgTextureActive=02_glass.png&bgImgOpacityActive=65&borderColorActive=aaaaaa&fcActive=212121&iconColorActive=454545&bgColorHighlight=fbf9ee&bgTextureHighlight=02_glass.png&bgImgOpacityHighlight=55&borderColorHighlight=fcefa1&fcHighlight=363636&iconColorHighlight=2e83ff&bgColorError=fef1ec&bgTextureError=02_glass.png&bgImgOpacityError=95&borderColorError=cd0a0a&fcError=cd0a0a&iconColorError=cd0a0a&bgColorOverlay=aaaaaa&bgTextureOverlay=01_flat.png&bgImgOpacityOverlay=0&opacityOverlay=30&bgColorShadow=aaaaaa&bgTextureShadow=01_flat.png&bgImgOpacityShadow=0&opacityShadow=30&thicknessShadow=8px&offsetTopShadow=-8px&offsetLeftShadow=-8px&cornerRadiusShadow=8px
+ */
+
+
+/* Component containers
+----------------------------------*/
+.ui-widget { font-family: Verdana,Arial,sans-serif; font-size: 1.1em; }
+.ui-widget .ui-widget { font-size: 1em; }
+.ui-widget input, .ui-widget select, .ui-widget textarea, .ui-widget button { font-family: Verdana,Arial,sans-serif; font-size: 1em; }
+.ui-widget-content { border: 1px solid #aaaaaa; background: #ffffff url(images/ui-bg_flat_75_ffffff_40x100.png) 50% 50% repeat-x; color: #222222; }
+.ui-widget-content a { color: #222222; }
+.ui-widget-header { border: 1px solid #aaaaaa; background: #cccccc url(images/ui-bg_highlight-soft_75_cccccc_1x100.png) 50% 50% repeat-x; color: #222222; font-weight: bold; }
+.ui-widget-header a { color: #222222; }
+
+/* Interaction states
+----------------------------------*/
+.ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default { border: 1px solid #d3d3d3; background: #e6e6e6 url(images/ui-bg_glass_75_e6e6e6_1x400.png) 50% 50% repeat-x; font-weight: normal; color: #555555; }
+.ui-state-default a, .ui-state-default a:link, .ui-state-default a:visited { color: #555555; text-decoration: none; }
+.ui-state-hover, .ui-widget-content .ui-state-hover, .ui-widget-header .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus { border: 1px solid #999999; background: #dadada url(images/ui-bg_glass_75_dadada_1x400.png) 50% 50% repeat-x; font-weight: normal; color: #212121; }
+.ui-state-hover a, .ui-state-hover a:hover { color: #212121; text-decoration: none; }
+.ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active { border: 1px solid #aaaaaa; background: #ffffff url(images/ui-bg_glass_65_ffffff_1x400.png) 50% 50% repeat-x; font-weight: normal; color: #212121; }
+.ui-state-active a, .ui-state-active a:link, .ui-state-active a:visited { color: #212121; text-decoration: none; }
+.ui-widget :active { outline: none; }
+
+/* Interaction Cues
+----------------------------------*/
+.ui-state-highlight, .ui-widget-content .ui-state-highlight, .ui-widget-header .ui-state-highlight  {border: 1px solid #fcefa1; background: #fbf9ee url(images/ui-bg_glass_55_fbf9ee_1x400.png) 50% 50% repeat-x; color: #363636; }
+.ui-state-highlight a, .ui-widget-content .ui-state-highlight a,.ui-widget-header .ui-state-highlight a { color: #363636; }
+.ui-state-error, .ui-widget-content .ui-state-error, .ui-widget-header .ui-state-error {border: 1px solid #cd0a0a; background: #fef1ec url(images/ui-bg_glass_95_fef1ec_1x400.png) 50% 50% repeat-x; color: #cd0a0a; }
+.ui-state-error a, .ui-widget-content .ui-state-error a, .ui-widget-header .ui-state-error a { color: #cd0a0a; }
+.ui-state-error-text, .ui-widget-content .ui-state-error-text, .ui-widget-header .ui-state-error-text { color: #cd0a0a; }
+.ui-priority-primary, .ui-widget-content .ui-priority-primary, .ui-widget-header .ui-priority-primary { font-weight: bold; }
+.ui-priority-secondary, .ui-widget-content .ui-priority-secondary,  .ui-widget-header .ui-priority-secondary { opacity: .7; filter:Alpha(Opacity=70); font-weight: normal; }
+.ui-state-disabled, .ui-widget-content .ui-state-disabled, .ui-widget-header .ui-state-disabled { opacity: .35; filter:Alpha(Opacity=35); background-image: none; }
+
+/* Icons
+----------------------------------*/
+
+/* states and images */
+.ui-icon { width: 16px; height: 16px; background-image: url(images/ui-icons_222222_256x240.png); }
+.ui-widget-content .ui-icon {background-image: url(images/ui-icons_222222_256x240.png); }
+.ui-widget-header .ui-icon {background-image: url(images/ui-icons_222222_256x240.png); }
+.ui-state-default .ui-icon { background-image: url(images/ui-icons_888888_256x240.png); }
+.ui-state-hover .ui-icon, .ui-state-focus .ui-icon {background-image: url(images/ui-icons_454545_256x240.png); }
+.ui-state-active .ui-icon {background-image: url(images/ui-icons_454545_256x240.png); }
+.ui-state-highlight .ui-icon {background-image: url(images/ui-icons_2e83ff_256x240.png); }
+.ui-state-error .ui-icon, .ui-state-error-text .ui-icon {background-image: url(images/ui-icons_cd0a0a_256x240.png); }
+
+/* positioning */
+.ui-icon-carat-1-n { background-position: 0 0; }
+.ui-icon-carat-1-ne { background-position: -16px 0; }
+.ui-icon-carat-1-e { background-position: -32px 0; }
+.ui-icon-carat-1-se { background-position: -48px 0; }
+.ui-icon-carat-1-s { background-position: -64px 0; }
+.ui-icon-carat-1-sw { background-position: -80px 0; }
+.ui-icon-carat-1-w { background-position: -96px 0; }
+.ui-icon-carat-1-nw { background-position: -112px 0; }
+.ui-icon-carat-2-n-s { background-position: -128px 0; }
+.ui-icon-carat-2-e-w { background-position: -144px 0; }
+.ui-icon-triangle-1-n { background-position: 0 -16px; }
+.ui-icon-triangle-1-ne { background-position: -16px -16px; }
+.ui-icon-triangle-1-e { background-position: -32px -16px; }
+.ui-icon-triangle-1-se { background-position: -48px -16px; }
+.ui-icon-triangle-1-s { background-position: -64px -16px; }
+.ui-icon-triangle-1-sw { background-position: -80px -16px; }
+.ui-icon-triangle-1-w { background-position: -96px -16px; }
+.ui-icon-triangle-1-nw { background-position: -112px -16px; }
+.ui-icon-triangle-2-n-s { background-position: -128px -16px; }
+.ui-icon-triangle-2-e-w { background-position: -144px -16px; }
+.ui-icon-arrow-1-n { background-position: 0 -32px; }
+.ui-icon-arrow-1-ne { background-position: -16px -32px; }
+.ui-icon-arrow-1-e { background-position: -32px -32px; }
+.ui-icon-arrow-1-se { background-position: -48px -32px; }
+.ui-icon-arrow-1-s { background-position: -64px -32px; }
+.ui-icon-arrow-1-sw { background-position: -80px -32px; }
+.ui-icon-arrow-1-w { background-position: -96px -32px; }
+.ui-icon-arrow-1-nw { background-position: -112px -32px; }
+.ui-icon-arrow-2-n-s { background-position: -128px -32px; }
+.ui-icon-arrow-2-ne-sw { background-position: -144px -32px; }
+.ui-icon-arrow-2-e-w { background-position: -160px -32px; }
+.ui-icon-arrow-2-se-nw { background-position: -176px -32px; }
+.ui-icon-arrowstop-1-n { background-position: -192px -32px; }
+.ui-icon-arrowstop-1-e { background-position: -208px -32px; }
+.ui-icon-arrowstop-1-s { background-position: -224px -32px; }
+.ui-icon-arrowstop-1-w { background-position: -240px -32px; }
+.ui-icon-arrowthick-1-n { background-position: 0 -48px; }
+.ui-icon-arrowthick-1-ne { background-position: -16px -48px; }
+.ui-icon-arrowthick-1-e { background-position: -32px -48px; }
+.ui-icon-arrowthick-1-se { background-position: -48px -48px; }
+.ui-icon-arrowthick-1-s { background-position: -64px -48px; }
+.ui-icon-arrowthick-1-sw { background-position: -80px -48px; }
+.ui-icon-arrowthick-1-w { background-position: -96px -48px; }
+.ui-icon-arrowthick-1-nw { background-position: -112px -48px; }
+.ui-icon-arrowthick-2-n-s { background-position: -128px -48px; }
+.ui-icon-arrowthick-2-ne-sw { background-position: -144px -48px; }
+.ui-icon-arrowthick-2-e-w { background-position: -160px -48px; }
+.ui-icon-arrowthick-2-se-nw { background-position: -176px -48px; }
+.ui-icon-arrowthickstop-1-n { background-position: -192px -48px; }
+.ui-icon-arrowthickstop-1-e { background-position: -208px -48px; }
+.ui-icon-arrowthickstop-1-s { background-position: -224px -48px; }
+.ui-icon-arrowthickstop-1-w { background-position: -240px -48px; }
+.ui-icon-arrowreturnthick-1-w { background-position: 0 -64px; }
+.ui-icon-arrowreturnthick-1-n { background-position: -16px -64px; }
+.ui-icon-arrowreturnthick-1-e { background-position: -32px -64px; }
+.ui-icon-arrowreturnthick-1-s { background-position: -48px -64px; }
+.ui-icon-arrowreturn-1-w { background-position: -64px -64px; }
+.ui-icon-arrowreturn-1-n { background-position: -80px -64px; }
+.ui-icon-arrowreturn-1-e { background-position: -96px -64px; }
+.ui-icon-arrowreturn-1-s { background-position: -112px -64px; }
+.ui-icon-arrowrefresh-1-w { background-position: -128px -64px; }
+.ui-icon-arrowrefresh-1-n { background-position: -144px -64px; }
+.ui-icon-arrowrefresh-1-e { background-position: -160px -64px; }
+.ui-icon-arrowrefresh-1-s { background-position: -176px -64px; }
+.ui-icon-arrow-4 { background-position: 0 -80px; }
+.ui-icon-arrow-4-diag { background-position: -16px -80px; }
+.ui-icon-extlink { background-position: -32px -80px; }
+.ui-icon-newwin { background-position: -48px -80px; }
+.ui-icon-refresh { background-position: -64px -80px; }
+.ui-icon-shuffle { background-position: -80px -80px; }
+.ui-icon-transfer-e-w { background-position: -96px -80px; }
+.ui-icon-transferthick-e-w { background-position: -112px -80px; }
+.ui-icon-folder-collapsed { background-position: 0 -96px; }
+.ui-icon-folder-open { background-position: -16px -96px; }
+.ui-icon-document { background-position: -32px -96px; }
+.ui-icon-document-b { background-position: -48px -96px; }
+.ui-icon-note { background-position: -64px -96px; }
+.ui-icon-mail-closed { background-position: -80px -96px; }
+.ui-icon-mail-open { background-position: -96px -96px; }
+.ui-icon-suitcase { background-position: -112px -96px; }
+.ui-icon-comment { background-position: -128px -96px; }
+.ui-icon-person { background-position: -144px -96px; }
+.ui-icon-print { background-position: -160px -96px; }
+.ui-icon-trash { background-position: -176px -96px; }
+.ui-icon-locked { background-position: -192px -96px; }
+.ui-icon-unlocked { background-position: -208px -96px; }
+.ui-icon-bookmark { background-position: -224px -96px; }
+.ui-icon-tag { background-position: -240px -96px; }
+.ui-icon-home { background-position: 0 -112px; }
+.ui-icon-flag { background-position: -16px -112px; }
+.ui-icon-calendar { background-position: -32px -112px; }
+.ui-icon-cart { background-position: -48px -112px; }
+.ui-icon-pencil { background-position: -64px -112px; }
+.ui-icon-clock { background-position: -80px -112px; }
+.ui-icon-disk { background-position: -96px -112px; }
+.ui-icon-calculator { background-position: -112px -112px; }
+.ui-icon-zoomin { background-position: -128px -112px; }
+.ui-icon-zoomout { background-position: -144px -112px; }
+.ui-icon-search { background-position: -160px -112px; }
+.ui-icon-wrench { background-position: -176px -112px; }
+.ui-icon-gear { background-position: -192px -112px; }
+.ui-icon-heart { background-position: -208px -112px; }
+.ui-icon-star { background-position: -224px -112px; }
+.ui-icon-link { background-position: -240px -112px; }
+.ui-icon-cancel { background-position: 0 -128px; }
+.ui-icon-plus { background-position: -16px -128px; }
+.ui-icon-plusthick { background-position: -32px -128px; }
+.ui-icon-minus { background-position: -48px -128px; }
+.ui-icon-minusthick { background-position: -64px -128px; }
+.ui-icon-close { background-position: -80px -128px; }
+.ui-icon-closethick { background-position: -96px -128px; }
+.ui-icon-key { background-position: -112px -128px; }
+.ui-icon-lightbulb { background-position: -128px -128px; }
+.ui-icon-scissors { background-position: -144px -128px; }
+.ui-icon-clipboard { background-position: -160px -128px; }
+.ui-icon-copy { background-position: -176px -128px; }
+.ui-icon-contact { background-position: -192px -128px; }
+.ui-icon-image { background-position: -208px -128px; }
+.ui-icon-video { background-position: -224px -128px; }
+.ui-icon-script { background-position: -240px -128px; }
+.ui-icon-alert { background-position: 0 -144px; }
+.ui-icon-info { background-position: -16px -144px; }
+.ui-icon-notice { background-position: -32px -144px; }
+.ui-icon-help { background-position: -48px -144px; }
+.ui-icon-check { background-position: -64px -144px; }
+.ui-icon-bullet { background-position: -80px -144px; }
+.ui-icon-radio-off { background-position: -96px -144px; }
+.ui-icon-radio-on { background-position: -112px -144px; }
+.ui-icon-pin-w { background-position: -128px -144px; }
+.ui-icon-pin-s { background-position: -144px -144px; }
+.ui-icon-play { background-position: 0 -160px; }
+.ui-icon-pause { background-position: -16px -160px; }
+.ui-icon-seek-next { background-position: -32px -160px; }
+.ui-icon-seek-prev { background-position: -48px -160px; }
+.ui-icon-seek-end { background-position: -64px -160px; }
+.ui-icon-seek-start { background-position: -80px -160px; }
+/* ui-icon-seek-first is deprecated, use ui-icon-seek-start instead */
+.ui-icon-seek-first { background-position: -80px -160px; }
+.ui-icon-stop { background-position: -96px -160px; }
+.ui-icon-eject { background-position: -112px -160px; }
+.ui-icon-volume-off { background-position: -128px -160px; }
+.ui-icon-volume-on { background-position: -144px -160px; }
+.ui-icon-power { background-position: 0 -176px; }
+.ui-icon-signal-diag { background-position: -16px -176px; }
+.ui-icon-signal { background-position: -32px -176px; }
+.ui-icon-battery-0 { background-position: -48px -176px; }
+.ui-icon-battery-1 { background-position: -64px -176px; }
+.ui-icon-battery-2 { background-position: -80px -176px; }
+.ui-icon-battery-3 { background-position: -96px -176px; }
+.ui-icon-circle-plus { background-position: 0 -192px; }
+.ui-icon-circle-minus { background-position: -16px -192px; }
+.ui-icon-circle-close { background-position: -32px -192px; }
+.ui-icon-circle-triangle-e { background-position: -48px -192px; }
+.ui-icon-circle-triangle-s { background-position: -64px -192px; }
+.ui-icon-circle-triangle-w { background-position: -80px -192px; }
+.ui-icon-circle-triangle-n { background-position: -96px -192px; }
+.ui-icon-circle-arrow-e { background-position: -112px -192px; }
+.ui-icon-circle-arrow-s { background-position: -128px -192px; }
+.ui-icon-circle-arrow-w { background-position: -144px -192px; }
+.ui-icon-circle-arrow-n { background-position: -160px -192px; }
+.ui-icon-circle-zoomin { background-position: -176px -192px; }
+.ui-icon-circle-zoomout { background-position: -192px -192px; }
+.ui-icon-circle-check { background-position: -208px -192px; }
+.ui-icon-circlesmall-plus { background-position: 0 -208px; }
+.ui-icon-circlesmall-minus { background-position: -16px -208px; }
+.ui-icon-circlesmall-close { background-position: -32px -208px; }
+.ui-icon-squaresmall-plus { background-position: -48px -208px; }
+.ui-icon-squaresmall-minus { background-position: -64px -208px; }
+.ui-icon-squaresmall-close { background-position: -80px -208px; }
+.ui-icon-grip-dotted-vertical { background-position: 0 -224px; }
+.ui-icon-grip-dotted-horizontal { background-position: -16px -224px; }
+.ui-icon-grip-solid-vertical { background-position: -32px -224px; }
+.ui-icon-grip-solid-horizontal { background-position: -48px -224px; }
+.ui-icon-gripsmall-diagonal-se { background-position: -64px -224px; }
+.ui-icon-grip-diagonal-se { background-position: -80px -224px; }
+
+
+/* Misc visuals
+----------------------------------*/
+
+/* Corner radius */
+.ui-corner-all, .ui-corner-top, .ui-corner-left, .ui-corner-tl { -moz-border-radius-topleft: 4px; -webkit-border-top-left-radius: 4px; -khtml-border-top-left-radius: 4px; border-top-left-radius: 4px; }
+.ui-corner-all, .ui-corner-top, .ui-corner-right, .ui-corner-tr { -moz-border-radius-topright: 4px; -webkit-border-top-right-radius: 4px; -khtml-border-top-right-radius: 4px; border-top-right-radius: 4px; }
+.ui-corner-all, .ui-corner-bottom, .ui-corner-left, .ui-corner-bl { -moz-border-radius-bottomleft: 4px; -webkit-border-bottom-left-radius: 4px; -khtml-border-bottom-left-radius: 4px; border-bottom-left-radius: 4px; }
+.ui-corner-all, .ui-corner-bottom, .ui-corner-right, .ui-corner-br { -moz-border-radius-bottomright: 4px; -webkit-border-bottom-right-radius: 4px; -khtml-border-bottom-right-radius: 4px; border-bottom-right-radius: 4px; }
+
+/* Overlays */
+.ui-widget-overlay { background: #aaaaaa url(images/ui-bg_flat_0_aaaaaa_40x100.png) 50% 50% repeat-x; opacity: .30;filter:Alpha(Opacity=30); }
+.ui-widget-shadow { margin: -8px 0 0 -8px; padding: 8px; background: #aaaaaa url(images/ui-bg_flat_0_aaaaaa_40x100.png) 50% 50% repeat-x; opacity: .30;filter:Alpha(Opacity=30); -moz-border-radius: 8px; -khtml-border-radius: 8px; -webkit-border-radius: 8px; border-radius: 8px; }/*
+ * jQuery UI Resizable 1.8.18
+ *
+ * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ * http://jquery.org/license
+ *
+ * http://docs.jquery.com/UI/Resizable#theming
+ */
+.ui-resizable { position: relative;}
+.ui-resizable-handle { position: absolute;font-size: 0.1px;z-index: 99999; display: block; }
+.ui-resizable-disabled .ui-resizable-handle, .ui-resizable-autohide .ui-resizable-handle { display: none; }
+.ui-resizable-n { cursor: n-resize; height: 7px; width: 100%; top: -5px; left: 0; }
+.ui-resizable-s { cursor: s-resize; height: 7px; width: 100%; bottom: -5px; left: 0; }
+.ui-resizable-e { cursor: e-resize; width: 7px; right: -5px; top: 0; height: 100%; }
+.ui-resizable-w { cursor: w-resize; width: 7px; left: -5px; top: 0; height: 100%; }
+.ui-resizable-se { cursor: se-resize; width: 12px; height: 12px; right: 1px; bottom: 1px; }
+.ui-resizable-sw { cursor: sw-resize; width: 9px; height: 9px; left: -5px; bottom: -5px; }
+.ui-resizable-nw { cursor: nw-resize; width: 9px; height: 9px; left: -5px; top: -5px; }
+.ui-resizable-ne { cursor: ne-resize; width: 9px; height: 9px; right: -5px; top: -5px;}/*
+ * jQuery UI Selectable 1.8.18
+ *
+ * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ * http://jquery.org/license
+ *
+ * http://docs.jquery.com/UI/Selectable#theming
+ */
+.ui-selectable-helper { position: absolute; z-index: 100; border:1px dotted black; }
+/*
+ * jQuery UI Accordion 1.8.18
+ *
+ * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ * http://jquery.org/license
+ *
+ * http://docs.jquery.com/UI/Accordion#theming
+ */
+/* IE/Win - Fix animation bug - #4615 */
+.ui-accordion { width: 100%; }
+.ui-accordion .ui-accordion-header { cursor: pointer; position: relative; margin-top: 1px; zoom: 1; }
+.ui-accordion .ui-accordion-li-fix { display: inline; }
+.ui-accordion .ui-accordion-header-active { border-bottom: 0 !important; }
+.ui-accordion .ui-accordion-header a { display: block; font-size: 1em; padding: .5em .5em .5em .7em; }
+.ui-accordion-icons .ui-accordion-header a { padding-left: 2.2em; }
+.ui-accordion .ui-accordion-header .ui-icon { position: absolute; left: .5em; top: 50%; margin-top: -8px; }
+.ui-accordion .ui-accordion-content { padding: 1em 2.2em; border-top: 0; margin-top: -2px; position: relative; top: 1px; margin-bottom: 2px; overflow: auto; display: none; zoom: 1; }
+.ui-accordion .ui-accordion-content-active { display: block; }
+/*
+ * jQuery UI Autocomplete 1.8.18
+ *
+ * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ * http://jquery.org/license
+ *
+ * http://docs.jquery.com/UI/Autocomplete#theming
+ */
+.ui-autocomplete { position: absolute; cursor: default; }      
+
+/* workarounds */
+* html .ui-autocomplete { width:1px; } /* without this, the menu expands to 100% in IE6 */
+
+/*
+ * jQuery UI Menu 1.8.18
+ *
+ * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ * http://jquery.org/license
+ *
+ * http://docs.jquery.com/UI/Menu#theming
+ */
+.ui-menu {
+       list-style:none;
+       padding: 2px;
+       margin: 0;
+       display:block;
+       float: left;
+}
+.ui-menu .ui-menu {
+       margin-top: -3px;
+}
+.ui-menu .ui-menu-item {
+       margin:0;
+       padding: 0;
+       zoom: 1;
+       float: left;
+       clear: left;
+       width: 100%;
+}
+.ui-menu .ui-menu-item a {
+       text-decoration:none;
+       display:block;
+       padding:.2em .4em;
+       line-height:1.5;
+       zoom:1;
+}
+.ui-menu .ui-menu-item a.ui-state-hover,
+.ui-menu .ui-menu-item a.ui-state-active {
+       font-weight: normal;
+       margin: -1px;
+}
+/*
+ * jQuery UI Button 1.8.18
+ *
+ * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ * http://jquery.org/license
+ *
+ * http://docs.jquery.com/UI/Button#theming
+ */
+.ui-button { display: inline-block; position: relative; padding: 0; margin-right: .1em; text-decoration: none !important; cursor: pointer; text-align: center; zoom: 1; overflow: hidden; *overflow: visible; } /* the overflow property removes extra width in IE */
+.ui-button-icon-only { width: 2.2em; } /* to make room for the icon, a width needs to be set here */
+button.ui-button-icon-only { width: 2.4em; } /* button elements seem to need a little more width */
+.ui-button-icons-only { width: 3.4em; } 
+button.ui-button-icons-only { width: 3.7em; } 
+
+/*button text element */
+.ui-button .ui-button-text { display: block; line-height: 1.4;  }
+.ui-button-text-only .ui-button-text { padding: .4em 1em; }
+.ui-button-icon-only .ui-button-text, .ui-button-icons-only .ui-button-text { padding: .4em; text-indent: -9999999px; }
+.ui-button-text-icon-primary .ui-button-text, .ui-button-text-icons .ui-button-text { padding: .4em 1em .4em 2.1em; }
+.ui-button-text-icon-secondary .ui-button-text, .ui-button-text-icons .ui-button-text { padding: .4em 2.1em .4em 1em; }
+.ui-button-text-icons .ui-button-text { padding-left: 2.1em; padding-right: 2.1em; }
+/* no icon support for input elements, provide padding by default */
+input.ui-button { padding: .4em 1em; }
+
+/*button icon element(s) */
+.ui-button-icon-only .ui-icon, .ui-button-text-icon-primary .ui-icon, .ui-button-text-icon-secondary .ui-icon, .ui-button-text-icons .ui-icon, .ui-button-icons-only .ui-icon { position: absolute; top: 50%; margin-top: -8px; }
+.ui-button-icon-only .ui-icon { left: 50%; margin-left: -8px; }
+.ui-button-text-icon-primary .ui-button-icon-primary, .ui-button-text-icons .ui-button-icon-primary, .ui-button-icons-only .ui-button-icon-primary { left: .5em; }
+.ui-button-text-icon-secondary .ui-button-icon-secondary, .ui-button-text-icons .ui-button-icon-secondary, .ui-button-icons-only .ui-button-icon-secondary { right: .5em; }
+.ui-button-text-icons .ui-button-icon-secondary, .ui-button-icons-only .ui-button-icon-secondary { right: .5em; }
+
+/*button sets*/
+.ui-buttonset { margin-right: 7px; }
+.ui-buttonset .ui-button { margin-left: 0; margin-right: -.3em; }
+
+/* workarounds */
+button.ui-button::-moz-focus-inner { border: 0; padding: 0; } /* reset extra padding in Firefox */
+/*
+ * jQuery UI Dialog 1.8.18
+ *
+ * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ * http://jquery.org/license
+ *
+ * http://docs.jquery.com/UI/Dialog#theming
+ */
+.ui-dialog { position: absolute; padding: .2em; width: 300px; overflow: hidden; }
+.ui-dialog .ui-dialog-titlebar { padding: .4em 1em; position: relative;  }
+.ui-dialog .ui-dialog-title { float: left; margin: .1em 16px .1em 0; } 
+.ui-dialog .ui-dialog-titlebar-close { position: absolute; right: .3em; top: 50%; width: 19px; margin: -10px 0 0 0; padding: 1px; height: 18px; }
+.ui-dialog .ui-dialog-titlebar-close span { display: block; margin: 1px; }
+.ui-dialog .ui-dialog-titlebar-close:hover, .ui-dialog .ui-dialog-titlebar-close:focus { padding: 0; }
+.ui-dialog .ui-dialog-content { position: relative; border: 0; padding: .5em 1em; background: none; overflow: auto; zoom: 1; }
+.ui-dialog .ui-dialog-buttonpane { text-align: left; border-width: 1px 0 0 0; background-image: none; margin: .5em 0 0 0; padding: .3em 1em .5em .4em; }
+.ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset { float: right; }
+.ui-dialog .ui-dialog-buttonpane button { margin: .5em .4em .5em 0; cursor: pointer; }
+.ui-dialog .ui-resizable-se { width: 14px; height: 14px; right: 3px; bottom: 3px; }
+.ui-draggable .ui-dialog-titlebar { cursor: move; }
+/*
+ * jQuery UI Slider 1.8.18
+ *
+ * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ * http://jquery.org/license
+ *
+ * http://docs.jquery.com/UI/Slider#theming
+ */
+.ui-slider { position: relative; text-align: left; }
+.ui-slider .ui-slider-handle { position: absolute; z-index: 2; width: 1.2em; height: 1.2em; cursor: default; }
+.ui-slider .ui-slider-range { position: absolute; z-index: 1; font-size: .7em; display: block; border: 0; background-position: 0 0; }
+
+.ui-slider-horizontal { height: .8em; }
+.ui-slider-horizontal .ui-slider-handle { top: -.3em; margin-left: -.6em; }
+.ui-slider-horizontal .ui-slider-range { top: 0; height: 100%; }
+.ui-slider-horizontal .ui-slider-range-min { left: 0; }
+.ui-slider-horizontal .ui-slider-range-max { right: 0; }
+
+.ui-slider-vertical { width: .8em; height: 100px; }
+.ui-slider-vertical .ui-slider-handle { left: -.3em; margin-left: 0; margin-bottom: -.6em; }
+.ui-slider-vertical .ui-slider-range { left: 0; width: 100%; }
+.ui-slider-vertical .ui-slider-range-min { bottom: 0; }
+.ui-slider-vertical .ui-slider-range-max { top: 0; }/*
+ * jQuery UI Tabs 1.8.18
+ *
+ * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ * http://jquery.org/license
+ *
+ * http://docs.jquery.com/UI/Tabs#theming
+ */
+.ui-tabs { position: relative; padding: .2em; zoom: 1; } /* position: relative prevents IE scroll bug (element with position: relative inside container with overflow: auto appear as "fixed") */
+.ui-tabs .ui-tabs-nav { margin: 0; padding: .2em .2em 0; }
+.ui-tabs .ui-tabs-nav li { list-style: none; float: left; position: relative; top: 1px; margin: 0 .2em 1px 0; border-bottom: 0 !important; padding: 0; white-space: nowrap; }
+.ui-tabs .ui-tabs-nav li a { float: left; padding: .5em 1em; text-decoration: none; }
+.ui-tabs .ui-tabs-nav li.ui-tabs-selected { margin-bottom: 0; padding-bottom: 1px; }
+.ui-tabs .ui-tabs-nav li.ui-tabs-selected a, .ui-tabs .ui-tabs-nav li.ui-state-disabled a, .ui-tabs .ui-tabs-nav li.ui-state-processing a { cursor: text; }
+.ui-tabs .ui-tabs-nav li a, .ui-tabs.ui-tabs-collapsible .ui-tabs-nav li.ui-tabs-selected a { cursor: pointer; } /* first selector in group seems obsolete, but required to overcome bug in Opera applying cursor: text overall if defined elsewhere... */
+.ui-tabs .ui-tabs-panel { display: block; border-width: 0; padding: 1em 1.4em; background: none; }
+.ui-tabs .ui-tabs-hide { display: none !important; }
+/*
+ * jQuery UI Datepicker 1.8.18
+ *
+ * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ * http://jquery.org/license
+ *
+ * http://docs.jquery.com/UI/Datepicker#theming
+ */
+.ui-datepicker { width: 17em; padding: .2em .2em 0; display: none; }
+.ui-datepicker .ui-datepicker-header { position:relative; padding:.2em 0; }
+.ui-datepicker .ui-datepicker-prev, .ui-datepicker .ui-datepicker-next { position:absolute; top: 2px; width: 1.8em; height: 1.8em; }
+.ui-datepicker .ui-datepicker-prev-hover, .ui-datepicker .ui-datepicker-next-hover { top: 1px; }
+.ui-datepicker .ui-datepicker-prev { left:2px; }
+.ui-datepicker .ui-datepicker-next { right:2px; }
+.ui-datepicker .ui-datepicker-prev-hover { left:1px; }
+.ui-datepicker .ui-datepicker-next-hover { right:1px; }
+.ui-datepicker .ui-datepicker-prev span, .ui-datepicker .ui-datepicker-next span { display: block; position: absolute; left: 50%; margin-left: -8px; top: 50%; margin-top: -8px;  }
+.ui-datepicker .ui-datepicker-title { margin: 0 2.3em; line-height: 1.8em; text-align: center; }
+.ui-datepicker .ui-datepicker-title select { font-size:1em; margin:1px 0; }
+.ui-datepicker select.ui-datepicker-month-year {width: 100%;}
+.ui-datepicker select.ui-datepicker-month, 
+.ui-datepicker select.ui-datepicker-year { width: 49%;}
+.ui-datepicker table {width: 100%; font-size: .9em; border-collapse: collapse; margin:0 0 .4em; }
+.ui-datepicker th { padding: .7em .3em; text-align: center; font-weight: bold; border: 0;  }
+.ui-datepicker td { border: 0; padding: 1px; }
+.ui-datepicker td span, .ui-datepicker td a { display: block; padding: .2em; text-align: right; text-decoration: none; }
+.ui-datepicker .ui-datepicker-buttonpane { background-image: none; margin: .7em 0 0 0; padding:0 .2em; border-left: 0; border-right: 0; border-bottom: 0; }
+.ui-datepicker .ui-datepicker-buttonpane button { float: right; margin: .5em .2em .4em; cursor: pointer; padding: .2em .6em .3em .6em; width:auto; overflow:visible; }
+.ui-datepicker .ui-datepicker-buttonpane button.ui-datepicker-current { float:left; }
+
+/* with multiple calendars */
+.ui-datepicker.ui-datepicker-multi { width:auto; }
+.ui-datepicker-multi .ui-datepicker-group { float:left; }
+.ui-datepicker-multi .ui-datepicker-group table { width:95%; margin:0 auto .4em; }
+.ui-datepicker-multi-2 .ui-datepicker-group { width:50%; }
+.ui-datepicker-multi-3 .ui-datepicker-group { width:33.3%; }
+.ui-datepicker-multi-4 .ui-datepicker-group { width:25%; }
+.ui-datepicker-multi .ui-datepicker-group-last .ui-datepicker-header { border-left-width:0; }
+.ui-datepicker-multi .ui-datepicker-group-middle .ui-datepicker-header { border-left-width:0; }
+.ui-datepicker-multi .ui-datepicker-buttonpane { clear:left; }
+.ui-datepicker-row-break { clear:both; width:100%; font-size:0em; }
+
+/* RTL support */
+.ui-datepicker-rtl { direction: rtl; }
+.ui-datepicker-rtl .ui-datepicker-prev { right: 2px; left: auto; }
+.ui-datepicker-rtl .ui-datepicker-next { left: 2px; right: auto; }
+.ui-datepicker-rtl .ui-datepicker-prev:hover { right: 1px; left: auto; }
+.ui-datepicker-rtl .ui-datepicker-next:hover { left: 1px; right: auto; }
+.ui-datepicker-rtl .ui-datepicker-buttonpane { clear:right; }
+.ui-datepicker-rtl .ui-datepicker-buttonpane button { float: left; }
+.ui-datepicker-rtl .ui-datepicker-buttonpane button.ui-datepicker-current { float:right; }
+.ui-datepicker-rtl .ui-datepicker-group { float:right; }
+.ui-datepicker-rtl .ui-datepicker-group-last .ui-datepicker-header { border-right-width:0; border-left-width:1px; }
+.ui-datepicker-rtl .ui-datepicker-group-middle .ui-datepicker-header { border-right-width:0; border-left-width:1px; }
+
+/* IE6 IFRAME FIX (taken from datepicker 1.5.3 */
+.ui-datepicker-cover {
+    display: none; /*sorry for IE5*/
+    display/**/: block; /*sorry for IE5*/
+    position: absolute; /*must have*/
+    z-index: -1; /*must have*/
+    filter: mask(); /*must have*/
+    top: -4px; /*must have*/
+    left: -4px; /*must have*/
+    width: 200px; /*must have*/
+    height: 200px; /*must have*/
+}/*
+ * jQuery UI Progressbar 1.8.18
+ *
+ * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ * http://jquery.org/license
+ *
+ * http://docs.jquery.com/UI/Progressbar#theming
+ */
+.ui-progressbar { height:2em; text-align: left; overflow: hidden; }
+.ui-progressbar .ui-progressbar-value {margin: -1px; height:100%; }
\ No newline at end of file
diff --git a/plugins/pres_view/static/css/pres_view.css b/plugins/pres_view/static/css/pres_view.css
new file mode 100644 (file)
index 0000000..3de6090
--- /dev/null
@@ -0,0 +1,99 @@
+html {
+       height: 100%;
+}
+
+body {
+       /*margin: 15px;*/
+       text-align: center;
+       background-color: #FFFFFF;/*E3E1DD;*/
+       height: 100%;
+       overflow-y: hidden;
+}
+/*
+body, th, td {
+       font-size: 11px;
+       font-family: Arial, Helvetica, Sans-Serif;
+}
+*/
+h2 {
+       color: #A04641;
+}
+h3 {
+       color: #666666;
+       text-transform: uppercase;
+       border-bottom: 1px solid;
+}
+h4 {
+       margin: 0px;
+}
+#sbar #accordion h3, #sbar .accordionfix h3 {
+       text-transform: capitalize;
+       color: inherit;
+       padding: 5px;
+       padding-left: 25px;
+       cursor: pointer;
+}
+#sbar .accordionfix h3 {
+       border-bottom: 0px;
+       cursor: default;
+}
+#sbar #accordion div.sbar_cont, #sbar .accordionfix div.sbar_cont {
+       padding: 10px;
+}
+#sbar .accordionfix div.sbar_cont {
+       border-top: 0px;
+}
+b, strong {
+       color: #396A92;
+}
+img {
+       border: 0px;
+}
+.clear {
+       clear: both;
+}
+
+#wrapper {
+       margin: 0px auto;
+       /*width: 90%;*/
+       min-width: 910px;
+       background-color: #FFFFFF;
+       /*height: 90%;*/
+}
+#wrapper #gmaps {
+       width: 70%;
+       min-width: 600px;
+       float: left;
+       min-height: 100%;
+       height: auto !important;
+       height: 100%;
+}
+#wrapper #sbar {
+       width: 28.7%;
+       float: right;
+       text-align: left;
+       padding: 5px;
+}
+#statusbar {
+       text-align: left;
+       color: #333;
+       font-size: 10px;
+       padding: 2px 10px;
+       border-top: 1px #CCC solid;
+       min-height: 15px;
+       background-color: #FFFFFF;
+}
+#interval_animation {
+       margin: 5px;
+}
+.tooltip {
+       display: none;
+       position: absolute;
+       border: 1px solid #333;
+       background-color: #161616;
+       border-radius: 5px;
+       padding: 10px;
+       color: #fff;
+       font-size: 10px;
+       font-family: Arial, Helvetica, sans-serif;
+}
diff --git a/plugins/pres_view/static/js/MooTools.js b/plugins/pres_view/static/js/MooTools.js
new file mode 100644 (file)
index 0000000..573d9f7
--- /dev/null
@@ -0,0 +1,114 @@
+var APE = {
+       Config: {
+               identifier: 'ape',
+               init: true,
+               frequency: 0,
+               scripts: []
+       }
+};
+
+APE.Client = new Class({
+       
+       eventProxy: [],
+
+       fireEvent: function(type, args, delay){
+               return this.core.fireEvent(type, args, delay);
+       },
+
+       addEvent: function(type, fn, internal){
+               var newFn = fn.bind(this), ret = this;
+               if(!$defined(this.core)) this.eventProxy.push([type, fn, internal]);
+               else {
+                       ret = this.core.addEvent(type, newFn, internal);
+                       this.core.$originalEvents[type] = this.core.$originalEvents[type] || [];
+                       this.core.$originalEvents[type][fn] = newFn;
+               }
+               return ret;
+       },
+
+       onRaw: function(type, fn, internal) {
+               return this.addEvent('raw_' + type.toLowerCase(), fn, internal); 
+       },
+
+       removeEvent: function(type, fn) {
+               return this.core.removeEvent(type, fn);
+       },
+
+       onCmd: function(type, fn, internal) {
+               return this.addEvent('cmd_' + type.toLowerCase(), fn, internal); 
+       },
+
+       onError: function(type, fn, internal) {
+               return this.addEvent('error_' + type, fn, internal); 
+       },
+
+       load: function(config){ 
+               config = $merge({}, APE.Config, config);
+
+               // Init function called by core to init core variable
+               config.init = function(core){
+                       this.core = core;
+                       for(var i = 0; i < this.eventProxy.length; i++){
+                               this.addEvent.apply(this, this.eventProxy[i]);
+                       }
+               }.bind(this);
+
+               //set document.domain
+               if (config.transport != 2) {
+                       if (config.domain != 'auto') document.domain = config.domain;
+                       if (config.domain == 'auto') document.domain = document.domain;
+               }
+               
+               var tmp = JSON.decode(Cookie.read('APE_Cookie'), {'domain': document.domain});
+
+               if(tmp) {
+                       config.frequency = tmp.frequency.toInt();
+               } else {
+                       tmp = {'frequency': 0};
+               }
+
+               tmp.frequency = config.frequency + 1;
+
+               Cookie.write('APE_Cookie', JSON.encode(tmp), {'domain': document.domain});
+               
+               var iframe = new Element('iframe', {
+                       id: 'ape_' + config.identifier,
+                       styles: {
+                               display: 'none',
+                               position: 'absolute',
+                               left: -300,
+                               top: -300
+                       }
+               }).inject(document.body);
+
+               iframe.addEvent('load',  function() { 
+                       if (!iframe.contentWindow.APE) setTimeout(iframe.onload, 100);//Sometimes IE fire the onload event, but the iframe is not loaded -_-
+                       else iframe.contentWindow.APE.init(config);
+               });
+
+               if (config.transport == 2) {//Special case for JSONP
+                       var doc = iframe.contentDocument;
+                       if (!doc) doc = iframe.contentWindow.document;
+
+                       //If the content of the iframe is created in DOM, the status bar will always load...
+                       //using document.write() is the only way to avoid status bar loading with JSONP
+                       doc.open();
+                       var theHtml = '<html><head>';
+                       for (var i = 0; i < config.scripts.length; i++) {
+                               theHtml += '<script src="' + config.scripts[i] + '"></script>';
+                       }
+                       theHtml += '</head><body></body></html>';
+                       doc.write(theHtml);
+                       doc.close();
+               } else { 
+                       iframe.set('src', (config.secure ? 'https' : 'http') + '://' + config.frequency + '.' + config.server + '/?[{"cmd":"script","params":{"domain":"' + document.domain + '","scripts":["' + config.scripts.join('","') + '"]}}]');
+                       if (Browser.Engine.gecko) { 
+                               // Firefox fix, see bug  #356558 
+                               // https://bugzilla.mozilla.org/show_bug.cgi?id=356558
+                               iframe.contentWindow.location.href = iframe.get('src');
+                       }
+               }       
+
+       }
+       
+});
diff --git a/plugins/pres_view/static/js/afficher_par_id.js b/plugins/pres_view/static/js/afficher_par_id.js
new file mode 100644 (file)
index 0000000..013d4e4
--- /dev/null
@@ -0,0 +1,112 @@
+/* 
+
+       Gére les affichages static, dynamiques ( le static est utiliser pour afficher un marker a la fois ) 
+       sinon affiche une erreur
+
+*/
+
+var animation = [];
+var temps ;
+var toto = 0;
+var save_long ;
+function afficher_par_id (id,method)
+{
+       toto = 0 ;
+       animation[id] = [];
+       switch ( method )
+               {
+                       case 'static':
+                               switch ( ref[id] ) 
+                                       {
+                                               case 'marker' :
+                                                       for ( var i = 0; i < opt_marker[id].length ; i++ ) 
+                                                       {
+                                                               marker[id][i] = new google.maps.Marker(opt_marker[id][i]);
+                                                               marker[id][i].setVisible ( true );
+                                                       }
+                                               break;
+                                               
+                                               case 'line' :
+                                                       for ( var i = 0; i < opt_line[id].length ; i++ ) 
+                                                       {
+                                                               line[id][i] = new google.maps.Polyline(opt_line[id][i]);
+                                                               line[id][i].setVisible ( true );
+                                                       }
+                                               break;
+                                               case 'circle' :
+                                                       for ( var i = 0; i < opt_circle[id].length ; i++ ) 
+                                                       {
+                                                               circle[id][i] = new google.maps.Circle(opt_circle[id][i]);
+                                                               circle[id][i].setVisible ( true );
+                                                       }
+                                               break;
+                                               default :
+                                                       { alert ( " mauvaise referance" ); }
+                                               break;
+                                       }
+                                       
+                       break;
+                       
+                       case 'animation':
+                               document.getElementById("statusbar").innerHTML = "ANIMATION EN COURS " ;
+                               switch ( ref[id] ) 
+                                       {
+                                               case 'marker':
+                                               save_long = opt_marker[id].length;
+                                               
+                                               for ( var i = 0; i < opt_marker[id].length ; i++ )
+                                               {
+                                                       temps =(10.5 - j( "#interval_animation" ).slider( "option", "value" )) * 1000 *(i+1) ;
+                                                       animation [id][i] = setTimeout ( function()
+                                                       {       
+                                                               marker[id][toto] = new google.maps.Marker(opt_marker[id][toto]);
+                                                               marker[id][toto].setVisible ( true );
+                                                               map.panTo ( pos_marker[id][toto]);
+                                                               toto++;
+                                                               if ( toto == save_long)  document.getElementById("statusbar").innerHTML = "ANIMATION TERMINEE " ;
+                                                       }, temps );
+                                               }
+                                               break;
+                                               case 'line' :
+                                               save_long = opt_line[id].length;
+                                               for ( var i = 0; i < opt_line[id].length ; i++ )
+                                               {
+                                                       temps =(10.5 - j( "#interval_animation" ).slider( "option", "value" )) * 1000 *(i+1) ;
+                                                       animation [id][i] = setTimeout ( function()
+                                                       {       
+                                                               
+                                                               line[id][toto] = new google.maps.Polyline(opt_line[id][toto]);
+                                                               line[id][toto].setVisible ( true );
+                                                               map.panTo ( pos_line[id][toto][0]);
+                                                               toto++;
+                                                               if ( toto == save_long)  document.getElementById("statusbar").innerHTML = "ANIMATION TERMINEE " ;
+                                                       }, temps );
+                                               }
+                                               break;
+                                               case 'circle' :
+                                               save_long = opt_circle[id].length;
+                                               for ( var i = 0; i < opt_circle[id].length ; i++ )
+                                               {
+                                                       temps =(10.5 - j( "#interval_animation" ).slider( "option", "value" )) * 1000 *(i+1) ;
+                                                       setTimeout ( function()
+                                                       {       
+                                                               
+                                                               circke[id][toto] = new google.maps.Circle(opt_circle[id][toto]);
+                                                               circle[id][toto].setVisible ( true );
+                                                               map.panTo ( pos_circle[id][toto][0]);
+                                                               toto++;
+                                                               if ( toto == save_long)  document.getElementById("statusbar").innerHTML = "ANIMATION TERMINEE " ;
+                                                       }, temps );
+                                               }
+                                               default :
+                                                       {}
+                                               break;
+                                       }
+                               ;
+                       break ;
+                       
+                       default:
+                               alert ( "afficher_par_id : Erreur dans la method" );
+                       break;
+               }
+}
diff --git a/plugins/pres_view/static/js/config.js b/plugins/pres_view/static/js/config.js
new file mode 100644 (file)
index 0000000..a4a3ded
--- /dev/null
@@ -0,0 +1,12 @@
+/***
+ * APE JSF Setup
+ */
+
+APE.Config.baseUrl = 'http://ape.planet-lab.eu/lib'; //APE JSF 
+APE.Config.domain = 'ape.planet-lab.eu'; 
+APE.Config.server = 'ape.planet-lab.eu:443'; //APE server URL
+
+(function(){
+       for (var i = 0; i < arguments.length; i++)
+               APE.Config.scripts.push(APE.Config.baseUrl + '/Source/' + arguments[i] + '.js');
+})('mootools-core', 'Core/APE', 'Core/Events', 'Core/Core', 'Pipe/Pipe', 'Pipe/PipeProxy', 'Pipe/PipeMulti', 'Pipe/PipeSingle', 'Request/Request','Request/Request.Stack', 'Request/Request.CycledStack', 'Transport/Transport.longPolling','Transport/Transport.SSE', 'Transport/Transport.XHRStreaming', 'Transport/Transport.JSONP', 'Transport/Transport.WebSocket', 'Core/Utility', 'Core/JSON');
diff --git a/plugins/pres_view/static/js/dynamic.js b/plugins/pres_view/static/js/dynamic.js
new file mode 100644 (file)
index 0000000..50ff343
--- /dev/null
@@ -0,0 +1,89 @@
+function ape_initialize(){
+       client = new APE.Controller();
+};
+               
+function ape_load(){
+       client.load({
+               identifier: 'action'
+       })
+}
+
+
+APE.Controller = new Class({
+       Extends: APE.Client,    
+       Implements: Options,    
+       options: {
+               container: null
+       },      
+       initialize: function(options){
+               var j = jQuery.noConflict();
+               this.setOptions(options);
+               this.addEvent('load',this.start);
+               this.onRaw('postmsg', this.onMsg);
+               this.addEvent('ape_join',this.ape_join);
+               this.addEvent('ape_leave',this.ape_leave);
+               this.addEvent('ape_quit',this.ape_quit);
+               this.addEvent('multiPipeCreate', function( pipe,options) {
+               console.log(pipe.getPubid());
+               console.log(options.pipe.properties.name);
+                       var myCookie = Cookie.write(options.pipe.properties.name,pipe.getPubid());
+                       });
+       },
+       
+       start: function(core){
+               this.core.start({'name': $time().toString()});
+               channel_name = [];
+               channel_id = [];
+       },
+       
+
+       
+       ape_join: function(channel_id){
+               // il faut aussi initialier le tableau du canal
+               // TODO 
+               this.core.join(channel_id);             
+       },
+       
+       ape_leave: function(channel_id){
+               var myCookie = Cookie.read(channel_id);
+               this.core.left(myCookie);
+               Cookie.dispose(channel_id);             
+       },
+       
+       ape_quit: function(){
+               this.core.quit();               
+       },
+       
+       
+       onMsg: function(raw){
+               /**console.log(raw);
+               console.log(raw.data.message);
+               console.log(raw.data.message['ape_position']);
+               console.log(raw.data.message[0].ape_position[0].latitude);**/
+               recup_direct(raw,channel_id,"dynamic")
+               /**switch(raw.data.print_method)
+               {
+                       case 'line':
+                               j("#test").append("line");
+                               g_map_printLine(raw);
+                               break;
+                       case 'circle':
+                                j("#test").append("circle");
+                               //g_map_printCircle(data.item[i]);
+                               break;
+                       case 'marker':
+                               j("#test").append("marker");
+                               g_map_printMarker(raw);
+                               break;
+               }**/
+       
+               
+               
+               
+               
+       }
+       
+       
+       
+       
+});
diff --git a/plugins/pres_view/static/js/initmap.js b/plugins/pres_view/static/js/initmap.js
new file mode 100644 (file)
index 0000000..abd8bf1
--- /dev/null
@@ -0,0 +1,55 @@
+       //initialisation no conflict et de la config APE
+       
+       j = jQuery.noConflict();
+       j.getScript('/all-static/js/config.js');
+       
+       //fin
+       
+                       var direct = 0;
+                       var map;
+                       var ref = [];
+                       var chargement = 1 ;
+                       var requete = 0;
+                       // sauvegarde des position en LatLng
+                       
+                       var pos_marker = [];
+                       var pos_line = [];
+                       var pos_circle = [];
+                       
+                       //Sauvegarde des options ( timestamp + options s'il y a )
+                       
+                       var opt_line = [];
+                       var opt_marker = [];
+                       var opt_circle = [];
+                       
+                       // sauvegarde des structures
+                       
+                       var marker= [];
+                       var circle = [];
+                       var line = [];
+                       
+                       //sauvegarde option du fichier conf 
+                       
+                       opt_conf = [];
+                       
+                       var visible = true ;
+                       
+function initialiser() {
+       var latlng = new google.maps.LatLng(49.35, 21.97);
+       //objet contenant des propri�t�s avec des identificateurs pr�d�finis dans Google Maps permettant
+       //de d�finir des options d'affichage de notre carte
+       var options = {
+       center: latlng,
+               zoom: 2,
+               mapTypeId: google.maps.MapTypeId.ROADMAP,
+               streetViewControl: false,
+               panControl : false,
+               maxzoom: 4
+               
+       };
+
+       //constructeur de la carte qui prend en param�tre le conteneur HTML
+       //dans lequel la carte doit s'afficher et les options
+
+       map = new google.maps.Map(document.getElementById("gmaps"), options);
+}
diff --git a/plugins/pres_view/static/js/jquery-ui.min.js b/plugins/pres_view/static/js/jquery-ui.min.js
new file mode 100644 (file)
index 0000000..59d4a5e
--- /dev/null
@@ -0,0 +1,15 @@
+/*!
+ * jQuery UI 1.8.18
+ *
+ * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ * http://jquery.org/license
+ *
+ * http://docs.jquery.com/UI
+ */(function(a,b){function d(b){return!a(b).parents().andSelf().filter(function(){return a.curCSS(this,"visibility")==="hidden"||a.expr.filters.hidden(this)}).length}function c(b,c){var e=b.nodeName.toLowerCase();if("area"===e){var f=b.parentNode,g=f.name,h;if(!b.href||!g||f.nodeName.toLowerCase()!=="map")return!1;h=a("img[usemap=#"+g+"]")[0];return!!h&&d(h)}return(/input|select|textarea|button|object/.test(e)?!b.disabled:"a"==e?b.href||c:c)&&d(b)}a.ui=a.ui||{};a.ui.version||(a.extend(a.ui,{version:"1.8.18",keyCode:{ALT:18,BACKSPACE:8,CAPS_LOCK:20,COMMA:188,COMMAND:91,COMMAND_LEFT:91,COMMAND_RIGHT:93,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,MENU:93,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38,WINDOWS:91}}),a.fn.extend({propAttr:a.fn.prop||a.fn.attr,_focus:a.fn.focus,focus:function(b,c){return typeof b=="number"?this.each(function(){var d=this;setTimeout(function(){a(d).focus(),c&&c.call(d)},b)}):this._focus.apply(this,arguments)},scrollParent:function(){var b;a.browser.msie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?b=this.parents().filter(function(){return/(relative|absolute|fixed)/.test(a.curCSS(this,"position",1))&&/(auto|scroll)/.test(a.curCSS(this,"overflow",1)+a.curCSS(this,"overflow-y",1)+a.curCSS(this,"overflow-x",1))}).eq(0):b=this.parents().filter(function(){return/(auto|scroll)/.test(a.curCSS(this,"overflow",1)+a.curCSS(this,"overflow-y",1)+a.curCSS(this,"overflow-x",1))}).eq(0);return/fixed/.test(this.css("position"))||!b.length?a(document):b},zIndex:function(c){if(c!==b)return this.css("zIndex",c);if(this.length){var d=a(this[0]),e,f;while(d.length&&d[0]!==document){e=d.css("position");if(e==="absolute"||e==="relative"||e==="fixed"){f=parseInt(d.css("zIndex"),10);if(!isNaN(f)&&f!==0)return f}d=d.parent()}}return 0},disableSelection:function(){return this.bind((a.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(a){a.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}}),a.each(["Width","Height"],function(c,d){function h(b,c,d,f){a.each(e,function(){c-=parseFloat(a.curCSS(b,"padding"+this,!0))||0,d&&(c-=parseFloat(a.curCSS(b,"border"+this+"Width",!0))||0),f&&(c-=parseFloat(a.curCSS(b,"margin"+this,!0))||0)});return c}var e=d==="Width"?["Left","Right"]:["Top","Bottom"],f=d.toLowerCase(),g={innerWidth:a.fn.innerWidth,innerHeight:a.fn.innerHeight,outerWidth:a.fn.outerWidth,outerHeight:a.fn.outerHeight};a.fn["inner"+d]=function(c){if(c===b)return g["inner"+d].call(this);return this.each(function(){a(this).css(f,h(this,c)+"px")})},a.fn["outer"+d]=function(b,c){if(typeof b!="number")return g["outer"+d].call(this,b);return this.each(function(){a(this).css(f,h(this,b,!0,c)+"px")})}}),a.extend(a.expr[":"],{data:function(b,c,d){return!!a.data(b,d[3])},focusable:function(b){return c(b,!isNaN(a.attr(b,"tabindex")))},tabbable:function(b){var d=a.attr(b,"tabindex"),e=isNaN(d);return(e||d>=0)&&c(b,!e)}}),a(function(){var b=document.body,c=b.appendChild(c=document.createElement("div"));c.offsetHeight,a.extend(c.style,{minHeight:"100px",height:"auto",padding:0,borderWidth:0}),a.support.minHeight=c.offsetHeight===100,a.support.selectstart="onselectstart"in c,b.removeChild(c).style.display="none"}),a.extend(a.ui,{plugin:{add:function(b,c,d){var e=a.ui[b].prototype;for(var f in d)e.plugins[f]=e.plugins[f]||[],e.plugins[f].push([c,d[f]])},call:function(a,b,c){var d=a.plugins[b];if(!!d&&!!a.element[0].parentNode)for(var e=0;e<d.length;e++)a.options[d[e][0]]&&d[e][1].apply(a.element,c)}},contains:function(a,b){return document.compareDocumentPosition?a.compareDocumentPosition(b)&16:a!==b&&a.contains(b)},hasScroll:function(b,c){if(a(b).css("overflow")==="hidden")return!1;var d=c&&c==="left"?"scrollLeft":"scrollTop",e=!1;if(b[d]>0)return!0;b[d]=1,e=b[d]>0,b[d]=0;return e},isOverAxis:function(a,b,c){return a>b&&a<b+c},isOver:function(b,c,d,e,f,g){return a.ui.isOverAxis(b,d,f)&&a.ui.isOverAxis(c,e,g)}}))})(jQuery),function(a,b){if(a.cleanData){var c=a.cleanData;a.cleanData=function(b){for(var d=0,e;(e=b[d])!=null;d++)try{a(e).triggerHandler("remove")}catch(f){}c(b)}}else{var d=a.fn.remove;a.fn.remove=function(b,c){return this.each(function(){c||(!b||a.filter(b,[this]).length)&&a("*",this).add([this]).each(function(){try{a(this).triggerHandler("remove")}catch(b){}});return d.call(a(this),b,c)})}}a.widget=function(b,c,d){var e=b.split(".")[0],f;b=b.split(".")[1],f=e+"-"+b,d||(d=c,c=a.Widget),a.expr[":"][f]=function(c){return!!a.data(c,b)},a[e]=a[e]||{},a[e][b]=function(a,b){arguments.length&&this._createWidget(a,b)};var g=new c;g.options=a.extend(!0,{},g.options),a[e][b].prototype=a.extend(!0,g,{namespace:e,widgetName:b,widgetEventPrefix:a[e][b].prototype.widgetEventPrefix||b,widgetBaseClass:f},d),a.widget.bridge(b,a[e][b])},a.widget.bridge=function(c,d){a.fn[c]=function(e){var f=typeof e=="string",g=Array.prototype.slice.call(arguments,1),h=this;e=!f&&g.length?a.extend.apply(null,[!0,e].concat(g)):e;if(f&&e.charAt(0)==="_")return h;f?this.each(function(){var d=a.data(this,c),f=d&&a.isFunction(d[e])?d[e].apply(d,g):d;if(f!==d&&f!==b){h=f;return!1}}):this.each(function(){var b=a.data(this,c);b?b.option(e||{})._init():a.data(this,c,new d(e,this))});return h}},a.Widget=function(a,b){arguments.length&&this._createWidget(a,b)},a.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",options:{disabled:!1},_createWidget:function(b,c){a.data(c,this.widgetName,this),this.element=a(c),this.options=a.extend(!0,{},this.options,this._getCreateOptions(),b);var d=this;this.element.bind("remove."+this.widgetName,function(){d.destroy()}),this._create(),this._trigger("create"),this._init()},_getCreateOptions:function(){return a.metadata&&a.metadata.get(this.element[0])[this.widgetName]},_create:function(){},_init:function(){},destroy:function(){this.element.unbind("."+this.widgetName).removeData(this.widgetName),this.widget().unbind("."+this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass+"-disabled "+"ui-state-disabled")},widget:function(){return this.element},option:function(c,d){var e=c;if(arguments.length===0)return a.extend({},this.options);if(typeof c=="string"){if(d===b)return this.options[c];e={},e[c]=d}this._setOptions(e);return this},_setOptions:function(b){var c=this;a.each(b,function(a,b){c._setOption(a,b)});return this},_setOption:function(a,b){this.options[a]=b,a==="disabled"&&this.widget()[b?"addClass":"removeClass"](this.widgetBaseClass+"-disabled"+" "+"ui-state-disabled").attr("aria-disabled",b);return this},enable:function(){return this._setOption("disabled",!1)},disable:function(){return this._setOption("disabled",!0)},_trigger:function(b,c,d){var e,f,g=this.options[b];d=d||{},c=a.Event(c),c.type=(b===this.widgetEventPrefix?b:this.widgetEventPrefix+b).toLowerCase(),c.target=this.element[0],f=c.originalEvent;if(f)for(e in f)e in c||(c[e]=f[e]);this.element.trigger(c,d);return!(a.isFunction(g)&&g.call(this.element[0],c,d)===!1||c.isDefaultPrevented())}}}(jQuery),function(a,b){var c=!1;a(document).mouseup(function(a){c=!1}),a.widget("ui.mouse",{options:{cancel:":input,option",distance:1,delay:0},_mouseInit:function(){var b=this;this.element.bind("mousedown."+this.widgetName,function(a){return b._mouseDown(a)}).bind("click."+this.widgetName,function(c){if(!0===a.data(c.target,b.widgetName+".preventClickEvent")){a.removeData(c.target,b.widgetName+".preventClickEvent"),c.stopImmediatePropagation();return!1}}),this.started=!1},_mouseDestroy:function(){this.element.unbind("."+this.widgetName)},_mouseDown:function(b){if(!c){this._mouseStarted&&this._mouseUp(b),this._mouseDownEvent=b;var d=this,e=b.which==1,f=typeof this.options.cancel=="string"&&b.target.nodeName?a(b.target).closest(this.options.cancel).length:!1;if(!e||f||!this._mouseCapture(b))return!0;this.mouseDelayMet=!this.options.delay,this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){d.mouseDelayMet=!0},this.options.delay));if(this._mouseDistanceMet(b)&&this._mouseDelayMet(b)){this._mouseStarted=this._mouseStart(b)!==!1;if(!this._mouseStarted){b.preventDefault();return!0}}!0===a.data(b.target,this.widgetName+".preventClickEvent")&&a.removeData(b.target,this.widgetName+".preventClickEvent"),this._mouseMoveDelegate=function(a){return d._mouseMove(a)},this._mouseUpDelegate=function(a){return d._mouseUp(a)},a(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate),b.preventDefault(),c=!0;return!0}},_mouseMove:function(b){if(a.browser.msie&&!(document.documentMode>=9)&&!b.button)return this._mouseUp(b);if(this._mouseStarted){this._mouseDrag(b);return b.preventDefault()}this._mouseDistanceMet(b)&&this._mouseDelayMet(b)&&(this._mouseStarted=this._mouseStart(this._mouseDownEvent,b)!==!1,this._mouseStarted?this._mouseDrag(b):this._mouseUp(b));return!this._mouseStarted},_mouseUp:function(b){a(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate),this._mouseStarted&&(this._mouseStarted=!1,b.target==this._mouseDownEvent.target&&a.data(b.target,this.widgetName+".preventClickEvent",!0),this._mouseStop(b));return!1},_mouseDistanceMet:function(a){return Math.max(Math.abs(this._mouseDownEvent.pageX-a.pageX),Math.abs(this._mouseDownEvent.pageY-a.pageY))>=this.options.distance},_mouseDelayMet:function(a){return this.mouseDelayMet},_mouseStart:function(a){},_mouseDrag:function(a){},_mouseStop:function(a){},_mouseCapture:function(a){return!0}})}(jQuery),function(a,b){a.widget("ui.draggable",a.ui.mouse,{widgetEventPrefix:"drag",options:{addClasses:!0,appendTo:"parent",axis:!1,connectToSortable:!1,containment:!1,cursor:"auto",cursorAt:!1,grid:!1,handle:!1,helper:"original",iframeFix:!1,opacity:!1,refreshPositions:!1,revert:!1,revertDuration:500,scope:"default",scroll:!0,scrollSensitivity:20,scrollSpeed:20,snap:!1,snapMode:"both",snapTolerance:20,stack:!1,zIndex:!1},_create:function(){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")){this.element.removeData("draggable").unbind(".draggable").removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled"),this._mouseDestroy();return this}},_mouseCapture:function(b){var c=this.options;if(this.helper||c.disabled||a(b.target).is(".ui-resizable-handle"))return!1;this.handle=this._getHandle(b);if(!this.handle)return!1;c.iframeFix&&a(c.iframeFix===!0?"iframe":c.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:1e3}).css(a(this).offset()).appendTo("body")});return!0},_mouseStart:function(b){var c=this.options;this.helper=this._createHelper(b),this._cacheHelperProportions(),a.ui.ddmanager&&(a.ui.ddmanager.current=this),this._cacheMargins(),this.cssPosition=this.helper.css("position"),this.scrollParent=this.helper.scrollParent(),this.offset=this.positionAbs=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.position=this._generatePosition(b),this.originalPageX=b.pageX,this.originalPageY=b.pageY,c.cursorAt&&this._adjustOffsetFromHelper(c.cursorAt),c.containment&&this._setContainment();if(this._trigger("start",b)===!1){this._clear();return!1}this._cacheHelperProportions(),a.ui.ddmanager&&!c.dropBehaviour&&a.ui.ddmanager.prepareOffsets(this,b),this.helper.addClass("ui-draggable-dragging"),this._mouseDrag(b,!0),a.ui.ddmanager&&a.ui.ddmanager.dragStart(this,b);return!0},_mouseDrag:function(b,c){this.position=this._generatePosition(b),this.positionAbs=this._convertPositionTo("absolute");if(!c){var d=this._uiHash();if(this._trigger("drag",b,d)===!1){this._mouseUp({});return!1}this.position=d.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";a.ui.ddmanager&&a.ui.ddmanager.drag(this,b);return!1},_mouseStop:function(b){var c=!1;a.ui.ddmanager&&!this.options.dropBehaviour&&(c=a.ui.ddmanager.drop(this,b)),this.dropped&&(c=this.dropped,this.dropped=!1);if((!this.element[0]||!this.element[0].parentNode)&&this.options.helper=="original")return!1;if(this.options.revert=="invalid"&&!c||this.options.revert=="valid"&&c||this.options.revert===!0||a.isFunction(this.options.revert)&&this.options.revert.call(this.element,c)){var d=this;a(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){d._trigger("stop",b)!==!1&&d._clear()})}else this._trigger("stop",b)!==!1&&this._clear();return!1},_mouseUp:function(b){this.options.iframeFix===!0&&a("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this)}),a.ui.ddmanager&&a.ui.ddmanager.dragStop(this,b);return a.ui.mouse.prototype._mouseUp.call(this,b)},cancel:function(){this.helper.is(".ui-draggable-dragging")?this._mouseUp({}):this._clear();return this},_getHandle:function(b){var c=!this.options.handle||!a(this.options.handle,this.element).length?!0:!1;a(this.options.handle,this.element).find("*").andSelf().each(function(){this==b.target&&(c=!0)});return c},_createHelper:function(b){var c=this.options,d=a.isFunction(c.helper)?a(c.helper.apply(this.element[0],[b])):c.helper=="clone"?this.element.clone().removeAttr("id"):this.element;d.parents("body").length||d.appendTo(c.appendTo=="parent"?this.element[0].parentNode:c.appendTo),d[0]!=this.element[0]&&!/(fixed|absolute)/.test(d.css("position"))&&d.css("position","absolute");return d},_adjustOffsetFromHelper:function(b){typeof b=="string"&&(b=b.split(" ")),a.isArray(b)&&(b={left:+b[0],top:+b[1]||0}),"left"in b&&(this.offset.click.left=b.left+this.margins.left),"right"in b&&(this.offset.click.left=this.helperProportions.width-b.right+this.margins.left),"top"in b&&(this.offset.click.top=b.top+this.margins.top),"bottom"in b&&(this.offset.click.top=this.helperProportions.height-b.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var b=this.offsetParent.offset();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 a=this.element.position();return{top:a.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:a.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}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,right:parseInt(this.element.css("marginRight"),10)||0,bottom:parseInt(this.element.css("marginBottom"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var b=this.options;b.containment=="parent"&&(b.containment=this.helper[0].parentNode);if(b.containment=="document"||b.containment=="window")this.containment=[b.containment=="document"?0:a(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,b.containment=="document"?0:a(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,(b.containment=="document"?0:a(window).scrollLeft())+a(b.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(b.containment=="document"?0:a(window).scrollTop())+(a(b.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!/^(document|window|parent)$/.test(b.containment)&&b.containment.constructor!=Array){var c=a(b.containment),d=c[0];if(!d)return;var e=c.offset(),f=a(d).css("overflow")!="hidden";this.containment=[(parseInt(a(d).css("borderLeftWidth"),10)||0)+(parseInt(a(d).css("paddingLeft"),10)||0),(parseInt(a(d).css("borderTopWidth"),10)||0)+(parseInt(a(d).css("paddingTop"),10)||0),(f?Math.max(d.scrollWidth,d.offsetWidth):d.offsetWidth)-(parseInt(a(d).css("borderLeftWidth"),10)||0)-(parseInt(a(d).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(f?Math.max(d.scrollHeight,d.offsetHeight):d.offsetHeight)-(parseInt(a(d).css("borderTopWidth"),10)||0)-(parseInt(a(d).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom],this.relative_container=c}else b.containment.constructor==Array&&(this.containment=b.containment)},_convertPositionTo:function(b,c){c||(c=this.position);var d=b=="absolute"?1:-1,e=this.options,f=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(f[0].tagName);return{top:c.top+this.offset.relative.top*d+this.offset.parent.top*d-(a.browser.safari&&a.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():g?0:f.scrollTop())*d),left:c.left+this.offset.relative.left*d+this.offset.parent.left*d-(a.browser.safari&&a.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():g?0:f.scrollLeft())*d)}},_generatePosition:function(b){var c=this.options,d=this.cssPosition=="absolute"&&(this.scrollParent[0]==document||!a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,e=/(html|body)/i.test(d[0].tagName),f=b.pageX,g=b.pageY;if(this.originalPosition){var h;if(this.containment){if(this.relative_container){var i=this.relative_container.offset();h=[this.containment[0]+i.left,this.containment[1]+i.top,this.containment[2]+i.left,this.containment[3]+i.top]}else h=this.containment;b.pageX-this.offset.click.left<h[0]&&(f=h[0]+this.offset.click.left),b.pageY-this.offset.click.top<h[1]&&(g=h[1]+this.offset.click.top),b.pageX-this.offset.click.left>h[2]&&(f=h[2]+this.offset.click.left),b.pageY-this.offset.click.top>h[3]&&(g=h[3]+this.offset.click.top)}if(c.grid){var j=c.grid[1]?this.originalPageY+Math.round((g-this.originalPageY)/c.grid[1])*c.grid[1]:this.originalPageY;g=h?j-this.offset.click.top<h[1]||j-this.offset.click.top>h[3]?j-this.offset.click.top<h[1]?j+c.grid[1]:j-c.grid[1]:j:j;var k=c.grid[0]?this.originalPageX+Math.round((f-this.originalPageX)/c.grid[0])*c.grid[0]:this.originalPageX;f=h?k-this.offset.click.left<h[0]||k-this.offset.click.left>h[2]?k-this.offset.click.left<h[0]?k+c.grid[0]:k-c.grid[0]:k:k}}return{top:g-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(a.browser.safari&&a.browser.version<526&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollTop():e?0:d.scrollTop()),left:f-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(a.browser.safari&&a.browser.version<526&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():e?0:d.scrollLeft())}},_clear:function(){this.helper.removeClass("ui-draggable-dragging"),this.helper[0]!=this.element[0]&&!this.cancelHelperRemoval&&this.helper.remove(),this.helper=null,this.cancelHelperRemoval=!1},_trigger:function(b,c,d){d=d||this._uiHash(),a.ui.plugin.call(this,b,[c,d]),b=="drag"&&(this.positionAbs=this._convertPositionTo("absolute"));return a.Widget.prototype._trigger.call(this,b,c,d)},plugins:{},_uiHash:function(a){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),a.extend(a.ui.draggable,{version:"1.8.18"}),a.ui.plugin.add("draggable","connectToSortable",{start:function(b,c){var d=a(this).data("draggable"),e=d.options,f=a.extend({},c,{item:d.element});d.sortables=[],a(e.connectToSortable).each(function(){var c=a.data(this,"sortable");c&&!c.options.disabled&&(d.sortables.push({instance:c,shouldRevert:c.options.revert}),c.refreshPositions(),c._trigger("activate",b,f))})},stop:function(b,c){var d=a(this).data("draggable"),e=a.extend({},c,{item:d.element});a.each(d.sortables,function(){this.instance.isOver?(this.instance.isOver=0,d.cancelHelperRemoval=!0,this.instance.cancelHelperRemoval=!1,this.shouldRevert&&(this.instance.options.revert=!0),this.instance._mouseStop(b),this.instance.options.helper=this.instance.options._helper,d.options.helper=="original"&&this.instance.currentItem.css({top:"auto",left:"auto"})):(this.instance.cancelHelperRemoval=!1,this.instance._trigger("deactivate",b,e))})},drag:function(b,c){var d=a(this).data("draggable"),e=this,f=function(b){var c=this.offset.click.top,d=this.offset.click.left,e=this.positionAbs.top,f=this.positionAbs.left,g=b.height,h=b.width,i=b.top,j=b.left;return a.ui.isOver(e+c,f+d,i,j,g,h)};a.each(d.sortables,function(f){this.instance.positionAbs=d.positionAbs,this.instance.helperProportions=d.helperProportions,this.instance.offset.click=d.offset.click,this.instance._intersectsWith(this.instance.containerCache)?(this.instance.isOver||(this.instance.isOver=1,this.instance.currentItem=a(e).clone().removeAttr("id").appendTo(this.instance.element).data("sortable-item",!0),this.instance.options._helper=this.instance.options.helper,this.instance.options.helper=function(){return c.helper[0]},b.target=this.instance.currentItem[0],this.instance._mouseCapture(b,!0),this.instance._mouseStart(b,!0,!0),this.instance.offset.click.top=d.offset.click.top,this.instance.offset.click.left=d.offset.click.left,this.instance.offset.parent.left-=d.offset.parent.left-this.instance.offset.parent.left,this.instance.offset.parent.top-=d.offset.parent.top-this.instance.offset.parent.top,d._trigger("toSortable",b),d.dropped=this.instance.element,d.currentItem=d.element,this.instance.fromOutside=d),this.instance.currentItem&&this.instance._mouseDrag(b)):this.instance.isOver&&(this.instance.isOver=0,this.instance.cancelHelperRemoval=!0,this.instance.options.revert=!1,this.instance._trigger("out",b,this.instance._uiHash(this.instance)),this.instance._mouseStop(b,!0),this.instance.options.helper=this.instance.options._helper,this.instance.currentItem.remove(),this.instance.placeholder&&this.instance.placeholder.remove(),d._trigger("fromSortable",b),d.dropped=!1)})}}),a.ui.plugin.add("draggable","cursor",{start:function(b,c){var d=a("body"),e=a(this).data("draggable").options;d.css("cursor")&&(e._cursor=d.css("cursor")),d.css("cursor",e.cursor)},stop:function(b,c){var d=a(this).data("draggable").options;d._cursor&&a("body").css("cursor",d._cursor)}}),a.ui.plugin.add("draggable","opacity",{start:function(b,c){var d=a(c.helper),e=a(this).data("draggable").options;d.css("opacity")&&(e._opacity=d.css("opacity")),d.css("opacity",e.opacity)},stop:function(b,c){var d=a(this).data("draggable").options;d._opacity&&a(c.helper).css("opacity",d._opacity)}}),a.ui.plugin.add("draggable","scroll",{start:function(b,c){var d=a(this).data("draggable");d.scrollParent[0]!=document&&d.scrollParent[0].tagName!="HTML"&&(d.overflowOffset=d.scrollParent.offset())},drag:function(b,c){var d=a(this).data("draggable"),e=d.options,f=!1;if(d.scrollParent[0]!=document&&d.scrollParent[0].tagName!="HTML"){if(!e.axis||e.axis!="x")d.overflowOffset.top+d.scrollParent[0].offsetHeight-b.pageY<e.scrollSensitivity?d.scrollParent[0].scrollTop=f=d.scrollParent[0].scrollTop+e.scrollSpeed:b.pageY-d.overflowOffset.top<e.scrollSensitivity&&(d.scrollParent[0].scrollTop=f=d.scrollParent[0].scrollTop-e.scrollSpeed);if(!e.axis||e.axis!="y")d.overflowOffset.left+d.scrollParent[0].offsetWidth-b.pageX<e.scrollSensitivity?d.scrollParent[0].scrollLeft=f=d.scrollParent[0].scrollLeft+e.scrollSpeed:b.pageX-d.overflowOffset.left<e.scrollSensitivity&&(d.scrollParent[0].scrollLeft=f=d.scrollParent[0].scrollLeft-e.scrollSpeed)}else{if(!e.axis||e.axis!="x")b.pageY-a(document).scrollTop()<e.scrollSensitivity?f=a(document).scrollTop(a(document).scrollTop()-e.scrollSpeed):a(window).height()-(b.pageY-a(document).scrollTop())<e.scrollSensitivity&&(f=a(document).scrollTop(a(document).scrollTop()+e.scrollSpeed));if(!e.axis||e.axis!="y")b.pageX-a(document).scrollLeft()<e.scrollSensitivity?f=a(document).scrollLeft(a(document).scrollLeft()-e.scrollSpeed):a(window).width()-(b.pageX-a(document).scrollLeft())<e.scrollSensitivity&&(f=a(document).scrollLeft(a(document).scrollLeft()+e.scrollSpeed))}f!==!1&&a.ui.ddmanager&&!e.dropBehaviour&&a.ui.ddmanager.prepareOffsets(d,b)}}),a.ui.plugin.add("draggable","snap",{start:function(b,c){var d=a(this).data("draggable"),e=d.options;d.snapElements=[],a(e.snap.constructor!=String?e.snap.items||":data(draggable)":e.snap).each(function(){var b=a(this),c=b.offset();this!=d.element[0]&&d.snapElements.push({item:this,width:b.outerWidth(),height:b.outerHeight(),top:c.top,left:c.left})})},drag:function(b,c){var d=a(this).data("draggable"),e=d.options,f=e.snapTolerance,g=c.offset.left,h=g+d.helperProportions.width,i=c.offset.top,j=i+d.helperProportions.height;for(var k=d.snapElements.length-1;k>=0;k--){var l=d.snapElements[k].left,m=l+d.snapElements[k].width,n=d.snapElements[k].top,o=n+d.snapElements[k].height;if(!(l-f<g&&g<m+f&&n-f<i&&i<o+f||l-f<g&&g<m+f&&n-f<j&&j<o+f||l-f<h&&h<m+f&&n-f<i&&i<o+f||l-f<h&&h<m+f&&n-f<j&&j<o+f)){d.snapElements[k].snapping&&d.options.snap.release&&d.options.snap.release.call(d.element,b,a.extend(d._uiHash(),{snapItem:d.snapElements[k].item})),d.snapElements[k].snapping=!1;continue}if(e.snapMode!="inner"){var p=Math.abs(n-j)<=f,q=Math.abs(o-i)<=f,r=Math.abs(l-h)<=f,s=Math.abs(m-g)<=f;p&&(c.position.top=d._convertPositionTo("relative",{top:n-d.helperProportions.height,left:0}).top-d.margins.top),q&&(c.position.top=d._convertPositionTo("relative",{top:o,left:0}).top-d.margins.top),r&&(c.position.left=d._convertPositionTo("relative",{top:0,left:l-d.helperProportions.width}).left-d.margins.left),s&&(c.position.left=d._convertPositionTo("relative",{top:0,left:m}).left-d.margins.left)}var t=p||q||r||s;if(e.snapMode!="outer"){var p=Math.abs(n-i)<=f,q=Math.abs(o-j)<=f,r=Math.abs(l-g)<=f,s=Math.abs(m-h)<=f;p&&(c.position.top=d._convertPositionTo("relative",{top:n,left:0}).top-d.margins.top),q&&(c.position.top=d._convertPositionTo("relative",{top:o-d.helperProportions.height,left:0}).top-d.margins.top),r&&(c.position.left=d._convertPositionTo("relative",{top:0,left:l}).left-d.margins.left),s&&(c.position.left=d._convertPositionTo("relative",{top:0,left:m-d.helperProportions.width}).left-d.margins.left)}!d.snapElements[k].snapping&&(p||q||r||s||t)&&d.options.snap.snap&&d.options.snap.snap.call(d.element,b,a.extend(d._uiHash(),{snapItem:d.snapElements[k].item})),d.snapElements[k].snapping=p||q||r||s||t}}}),a.ui.plugin.add("draggable","stack",{start:function(b,c){var d=a(this).data("draggable").options,e=a.makeArray(a(d.stack)).sort(function(b,c){return(parseInt(a(b).css("zIndex"),10)||0)-(parseInt(a(c).css("zIndex"),10)||0)});if(!!e.length){var f=parseInt(e[0].style.zIndex)||0;a(e).each(function(a){this.style.zIndex=f+a}),this[0].style.zIndex=f+e.length}}}),a.ui.plugin.add("draggable","zIndex",{start:function(b,c){var d=a(c.helper),e=a(this).data("draggable").options;d.css("zIndex")&&(e._zIndex=d.css("zIndex")),d.css("zIndex",e.zIndex)},stop:function(b,c){var d=a(this).data("draggable").options;d._zIndex&&a(c.helper).css("zIndex",d._zIndex)}})}(jQuery),function(a,b){a.widget("ui.droppable",{widgetEventPrefix:"drop",options:{accept:"*",activeClass:!1,addClasses:!0,greedy:!1,hoverClass:!1,scope:"default",tolerance:"intersect"},_create:function(){var b=this.options,c=b.accept;this.isover=0,this.isout=1,this.accept=a.isFunction(c)?c:function(a){return a.is(c)},this.proportions={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight},a.ui.ddmanager.droppables[b.scope]=a.ui.ddmanager.droppables[b.scope]||[],a.ui.ddmanager.droppables[b.scope].push(this),b.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++)b[c]==this&&b.splice(c,1);this.element.removeClass("ui-droppable ui-droppable-disabled").removeData("droppable").unbind(".droppable");return this},_setOption:function(b,c){b=="accept"&&(this.accept=a.isFunction(c)?c:function(a){return a.is(c)}),a.Widget.prototype._setOption.apply(this,arguments)},_activate:function(b){var c=a.ui.ddmanager.current;this.options.activeClass&&this.element.addClass(this.options.activeClass),c&&this._trigger("activate",b,this.ui(c))},_deactivate:function(b){var c=a.ui.ddmanager.current;this.options.activeClass&&this.element.removeClass(this.options.activeClass),c&&this._trigger("deactivate",b,this.ui(c))},_over:function(b){var c=a.ui.ddmanager.current;!!c&&(c.currentItem||c.element)[0]!=this.element[0]&&this.accept.call(this.element[0],c.currentItem||c.element)&&(this.options.hoverClass&&this.element.addClass(this.options.hoverClass),this._trigger("over",b,this.ui(c)))},_out:function(b){var c=a.ui.ddmanager.current;!!c&&(c.currentItem||c.element)[0]!=this.element[0]&&this.accept.call(this.element[0],c.currentItem||c.element)&&(this.options.hoverClass&&this.element.removeClass(this.options.hoverClass),this._trigger("out",b,this.ui(c)))},_drop:function(b,c){var d=c||a.ui.ddmanager.current;if(!d||(d.currentItem||d.element)[0]==this.element[0])return!1;var e=!1;this.element.find(":data(droppable)").not(".ui-draggable-dragging").each(function(){var b=a.data(this,"droppable");if(b.options.greedy&&!b.options.disabled&&b.options.scope==d.options.scope&&b.accept.call(b.element[0],d.currentItem||d.element)&&a.ui.intersect(d,a.extend(b,{offset:b.element.offset()}),b.options.tolerance)){e=!0;return!1}});if(e)return!1;if(this.accept.call(this.element[0],d.currentItem||d.element)){this.options.activeClass&&this.element.removeClass(this.options.activeClass),this.options.hoverClass&&this.element.removeClass(this.options.hoverClass),this._trigger("drop",b,this.ui(d));return this.element}return!1},ui:function(a){return{draggable:a.currentItem||a.element,helper:a.helper,position:a.position,offset:a.positionAbs}}}),a.extend(a.ui.droppable,{version:"1.8.18"}),a.ui.intersect=function(b,c,d){if(!c.offset)return!1;var e=(b.positionAbs||b.position.absolute).left,f=e+b.helperProportions.width,g=(b.positionAbs||b.position.absolute).top,h=g+b.helperProportions.height,i=c.offset.left,j=i+c.proportions.width,k=c.offset.top,l=k+c.proportions.height;switch(d){case"fit":return i<=e&&f<=j&&k<=g&&h<=l;case"intersect":return i<e+b.helperProportions.width/2&&f-b.helperProportions.width/2<j&&k<g+b.helperProportions.height/2&&h-b.helperProportions.height/2<l;case"pointer":var m=(b.positionAbs||b.position.absolute).left+(b.clickOffset||b.offset.click).left,n=(b.positionAbs||b.position.absolute).top+(b.clickOffset||b.offset.click).top,o=a.ui.isOver(n,m,k,i,c.proportions.height,c.proportions.width);return o;case"touch":return(g>=k&&g<=l||h>=k&&h<=l||g<k&&h>l)&&(e>=i&&e<=j||f>=i&&f<=j||e<i&&f>j);default:return!1}},a.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(b,c){var d=a.ui.ddmanager.droppables[b.options.scope]||[],e=c?c.type:null,f=(b.currentItem||b.element).find(":data(droppable)").andSelf();droppablesLoop:for(var g=0;g<d.length;g++){if(d[g].options.disabled||b&&!d[g].accept.call(d[g].element[0],b.currentItem||b.element))continue;for(var h=0;h<f.length;h++)if(f[h]==d[g].element[0]){d[g].proportions.height=0;continue droppablesLoop}d[g].visible=d[g].element.css("display")!="none";if(!d[g].visible)continue;e=="mousedown"&&d[g]._activate.call(d[g],c),d[g].offset=d[g].element.offset(),d[g].proportions={width:d[g].element[0].offsetWidth,
+height:d[g].element[0].offsetHeight}}},drop:function(b,c){var d=!1;a.each(a.ui.ddmanager.droppables[b.options.scope]||[],function(){!this.options||(!this.options.disabled&&this.visible&&a.ui.intersect(b,this,this.options.tolerance)&&(d=this._drop.call(this,c)||d),!this.options.disabled&&this.visible&&this.accept.call(this.element[0],b.currentItem||b.element)&&(this.isout=1,this.isover=0,this._deactivate.call(this,c)))});return d},dragStart:function(b,c){b.element.parents(":not(body,html)").bind("scroll.droppable",function(){b.options.refreshPositions||a.ui.ddmanager.prepareOffsets(b,c)})},drag:function(b,c){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)){var d=a.ui.intersect(b,this,this.options.tolerance),e=!d&&this.isover==1?"isout":d&&this.isover==0?"isover":null;if(!e)return;var f;if(this.options.greedy){var g=this.element.parents(":data(droppable):eq(0)");g.length&&(f=a.data(g[0],"droppable"),f.greedyChild=e=="isover"?1:0)}f&&e=="isover"&&(f.isover=0,f.isout=1,f._out.call(f,c)),this[e]=1,this[e=="isout"?"isover":"isout"]=0,this[e=="isover"?"_over":"_out"].call(this,c),f&&e=="isout"&&(f.isout=0,f.isover=1,f._over.call(f,c))}})},dragStop:function(b,c){b.element.parents(":not(body,html)").unbind("scroll.droppable"),b.options.refreshPositions||a.ui.ddmanager.prepareOffsets(b,c)}}}(jQuery),function(a,b){a.widget("ui.resizable",a.ui.mouse,{widgetEventPrefix:"resize",options:{alsoResize:!1,animate:!1,animateDuration:"slow",animateEasing:"swing",aspectRatio:!1,autoHide:!1,containment:!1,ghost:!1,grid:!1,handles:"e,s,se",helper:!1,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:1e3},_create:function(){var b=this,c=this.options;this.element.addClass("ui-resizable"),a.extend(this,{_aspectRatio:!!c.aspectRatio,aspectRatio:c.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:c.helper||c.ghost||c.animate?c.helper||"ui-resizable-helper":null}),this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)&&(this.element.wrap(a('<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=!0,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=c.handles||(a(".ui-resizable-handle",this.element).length?{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"}:"e,s,se");if(this.handles.constructor==String){this.handles=="all"&&(this.handles="n,e,s,w,se,sw,ne,nw");var d=this.handles.split(",");this.handles={};for(var e=0;e<d.length;e++){var f=a.trim(d[e]),g="ui-resizable-"+f,h=a('<div class="ui-resizable-handle '+g+'"></div>');/sw|se|ne|nw/.test(f)&&h.css({zIndex:++c.zIndex}),"se"==f&&h.addClass("ui-icon ui-icon-gripsmall-diagonal-se"),this.handles[f]=".ui-resizable-"+f,this.element.append(h)}}this._renderAxis=function(b){b=b||this.element;for(var c in this.handles){this.handles[c].constructor==String&&(this.handles[c]=a(this.handles[c],this.element).show());if(this.elementIsWrapper&&this.originalElement[0].nodeName.match(/textarea|input|select|button/i)){var d=a(this.handles[c],this.element),e=0;e=/sw|ne|nw|se|n|s/.test(c)?d.outerHeight():d.outerWidth();var f=["padding",/ne|nw|n/.test(c)?"Top":/se|sw|s/.test(c)?"Bottom":/^e$/.test(c)?"Right":"Left"].join("");b.css(f,e),this._proportionallyResize()}if(!a(this.handles[c]).length)continue}},this._renderAxis(this.element),this._handles=a(".ui-resizable-handle",this.element).disableSelection(),this._handles.mouseover(function(){if(!b.resizing){if(this.className)var a=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i);b.axis=a&&a[1]?a[1]:"se"}}),c.autoHide&&(this._handles.hide(),a(this.element).addClass("ui-resizable-autohide").hover(function(){c.disabled||(a(this).removeClass("ui-resizable-autohide"),b._handles.show())},function(){c.disabled||b.resizing||(a(this).addClass("ui-resizable-autohide"),b._handles.hide())})),this._mouseInit()},destroy:function(){this._mouseDestroy();var b=function(b){a(b).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing").removeData("resizable").unbind(".resizable").find(".ui-resizable-handle").remove()};if(this.elementIsWrapper){b(this.element);var c=this.element;c.after(this.originalElement.css({position:c.css("position"),width:c.outerWidth(),height:c.outerHeight(),top:c.css("top"),left:c.css("left")})).remove()}this.originalElement.css("resize",this.originalResizeStyle),b(this.originalElement);return this},_mouseCapture:function(b){var c=!1;for(var d in this.handles)a(this.handles[d])[0]==b.target&&(c=!0);return!this.options.disabled&&c},_mouseStart:function(b){var d=this.options,e=this.element.position(),f=this.element;this.resizing=!0,this.documentScroll={top:a(document).scrollTop(),left:a(document).scrollLeft()},(f.is(".ui-draggable")||/absolute/.test(f.css("position")))&&f.css({position:"absolute",top:e.top,left:e.left}),this._renderProxy();var g=c(this.helper.css("left")),h=c(this.helper.css("top"));d.containment&&(g+=a(d.containment).scrollLeft()||0,h+=a(d.containment).scrollTop()||0),this.offset=this.helper.offset(),this.position={left:g,top:h},this.size=this._helper?{width:f.outerWidth(),height:f.outerHeight()}:{width:f.width(),height:f.height()},this.originalSize=this._helper?{width:f.outerWidth(),height:f.outerHeight()}:{width:f.width(),height:f.height()},this.originalPosition={left:g,top:h},this.sizeDiff={width:f.outerWidth()-f.width(),height:f.outerHeight()-f.height()},this.originalMousePosition={left:b.pageX,top:b.pageY},this.aspectRatio=typeof d.aspectRatio=="number"?d.aspectRatio:this.originalSize.width/this.originalSize.height||1;var i=a(".ui-resizable-"+this.axis).css("cursor");a("body").css("cursor",i=="auto"?this.axis+"-resize":i),f.addClass("ui-resizable-resizing"),this._propagate("start",b);return!0},_mouseDrag:function(b){var c=this.helper,d=this.options,e={},f=this,g=this.originalMousePosition,h=this.axis,i=b.pageX-g.left||0,j=b.pageY-g.top||0,k=this._change[h];if(!k)return!1;var l=k.apply(this,[b,i,j]),m=a.browser.msie&&a.browser.version<7,n=this.sizeDiff;this._updateVirtualBoundaries(b.shiftKey);if(this._aspectRatio||b.shiftKey)l=this._updateRatio(l,b);l=this._respectSize(l,b),this._propagate("resize",b),c.css({top:this.position.top+"px",left:this.position.left+"px",width:this.size.width+"px",height:this.size.height+"px"}),!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize(),this._updateCache(l),this._trigger("resize",b,this.ui());return!1},_mouseStop:function(b){this.resizing=!1;var c=this.options,d=this;if(this._helper){var e=this._proportionallyResizeElements,f=e.length&&/textarea/i.test(e[0].nodeName),g=f&&a.ui.hasScroll(e[0],"left")?0:d.sizeDiff.height,h=f?0:d.sizeDiff.width,i={width:d.helper.width()-h,height:d.helper.height()-g},j=parseInt(d.element.css("left"),10)+(d.position.left-d.originalPosition.left)||null,k=parseInt(d.element.css("top"),10)+(d.position.top-d.originalPosition.top)||null;c.animate||this.element.css(a.extend(i,{top:k,left:j})),d.helper.height(d.size.height),d.helper.width(d.size.width),this._helper&&!c.animate&&this._proportionallyResize()}a("body").css("cursor","auto"),this.element.removeClass("ui-resizable-resizing"),this._propagate("stop",b),this._helper&&this.helper.remove();return!1},_updateVirtualBoundaries:function(a){var b=this.options,c,e,f,g,h;h={minWidth:d(b.minWidth)?b.minWidth:0,maxWidth:d(b.maxWidth)?b.maxWidth:Infinity,minHeight:d(b.minHeight)?b.minHeight:0,maxHeight:d(b.maxHeight)?b.maxHeight:Infinity};if(this._aspectRatio||a)c=h.minHeight*this.aspectRatio,f=h.minWidth/this.aspectRatio,e=h.maxHeight*this.aspectRatio,g=h.maxWidth/this.aspectRatio,c>h.minWidth&&(h.minWidth=c),f>h.minHeight&&(h.minHeight=f),e<h.maxWidth&&(h.maxWidth=e),g<h.maxHeight&&(h.maxHeight=g);this._vBoundaries=h},_updateCache:function(a){var b=this.options;this.offset=this.helper.offset(),d(a.left)&&(this.position.left=a.left),d(a.top)&&(this.position.top=a.top),d(a.height)&&(this.size.height=a.height),d(a.width)&&(this.size.width=a.width)},_updateRatio:function(a,b){var c=this.options,e=this.position,f=this.size,g=this.axis;d(a.height)?a.width=a.height*this.aspectRatio:d(a.width)&&(a.height=a.width/this.aspectRatio),g=="sw"&&(a.left=e.left+(f.width-a.width),a.top=null),g=="nw"&&(a.top=e.top+(f.height-a.height),a.left=e.left+(f.width-a.width));return a},_respectSize:function(a,b){var c=this.helper,e=this._vBoundaries,f=this._aspectRatio||b.shiftKey,g=this.axis,h=d(a.width)&&e.maxWidth&&e.maxWidth<a.width,i=d(a.height)&&e.maxHeight&&e.maxHeight<a.height,j=d(a.width)&&e.minWidth&&e.minWidth>a.width,k=d(a.height)&&e.minHeight&&e.minHeight>a.height;j&&(a.width=e.minWidth),k&&(a.height=e.minHeight),h&&(a.width=e.maxWidth),i&&(a.height=e.maxHeight);var l=this.originalPosition.left+this.originalSize.width,m=this.position.top+this.size.height,n=/sw|nw|w/.test(g),o=/nw|ne|n/.test(g);j&&n&&(a.left=l-e.minWidth),h&&n&&(a.left=l-e.maxWidth),k&&o&&(a.top=m-e.minHeight),i&&o&&(a.top=m-e.maxHeight);var p=!a.width&&!a.height;p&&!a.left&&a.top?a.top=null:p&&!a.top&&a.left&&(a.left=null);return a},_proportionallyResize:function(){var b=this.options;if(!!this._proportionallyResizeElements.length){var c=this.helper||this.element;for(var d=0;d<this._proportionallyResizeElements.length;d++){var e=this._proportionallyResizeElements[d];if(!this.borderDif){var f=[e.css("borderTopWidth"),e.css("borderRightWidth"),e.css("borderBottomWidth"),e.css("borderLeftWidth")],g=[e.css("paddingTop"),e.css("paddingRight"),e.css("paddingBottom"),e.css("paddingLeft")];this.borderDif=a.map(f,function(a,b){var c=parseInt(a,10)||0,d=parseInt(g[b],10)||0;return c+d})}if(a.browser.msie&&(!!a(c).is(":hidden")||!!a(c).parents(":hidden").length))continue;e.css({height:c.height()-this.borderDif[0]-this.borderDif[2]||0,width:c.width()-this.borderDif[1]-this.borderDif[3]||0})}}},_renderProxy:function(){var b=this.element,c=this.options;this.elementOffset=b.offset();if(this._helper){this.helper=this.helper||a('<div style="overflow:hidden;"></div>');var d=a.browser.msie&&a.browser.version<7,e=d?1:0,f=d?2:-1;this.helper.addClass(this._helper).css({width:this.element.outerWidth()+f,height:this.element.outerHeight()+f,position:"absolute",left:this.elementOffset.left-e+"px",top:this.elementOffset.top-e+"px",zIndex:++c.zIndex}),this.helper.appendTo("body").disableSelection()}else this.helper=this.element},_change:{e:function(a,b,c){return{width:this.originalSize.width+b}},w:function(a,b,c){var d=this.options,e=this.originalSize,f=this.originalPosition;return{left:f.left+b,width:e.width-b}},n:function(a,b,c){var d=this.options,e=this.originalSize,f=this.originalPosition;return{top:f.top+c,height:e.height-c}},s:function(a,b,c){return{height:this.originalSize.height+c}},se:function(b,c,d){return a.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[b,c,d]))},sw:function(b,c,d){return a.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[b,c,d]))},ne:function(b,c,d){return a.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[b,c,d]))},nw:function(b,c,d){return a.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[b,c,d]))}},_propagate:function(b,c){a.ui.plugin.call(this,b,[c,this.ui()]),b!="resize"&&this._trigger(b,c,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}}}),a.extend(a.ui.resizable,{version:"1.8.18"}),a.ui.plugin.add("resizable","alsoResize",{start:function(b,c){var d=a(this).data("resizable"),e=d.options,f=function(b){a(b).each(function(){var b=a(this);b.data("resizable-alsoresize",{width:parseInt(b.width(),10),height:parseInt(b.height(),10),left:parseInt(b.css("left"),10),top:parseInt(b.css("top"),10)})})};typeof e.alsoResize=="object"&&!e.alsoResize.parentNode?e.alsoResize.length?(e.alsoResize=e.alsoResize[0],f(e.alsoResize)):a.each(e.alsoResize,function(a){f(a)}):f(e.alsoResize)},resize:function(b,c){var d=a(this).data("resizable"),e=d.options,f=d.originalSize,g=d.originalPosition,h={height:d.size.height-f.height||0,width:d.size.width-f.width||0,top:d.position.top-g.top||0,left:d.position.left-g.left||0},i=function(b,d){a(b).each(function(){var b=a(this),e=a(this).data("resizable-alsoresize"),f={},g=d&&d.length?d:b.parents(c.originalElement[0]).length?["width","height"]:["width","height","top","left"];a.each(g,function(a,b){var c=(e[b]||0)+(h[b]||0);c&&c>=0&&(f[b]=c||null)}),b.css(f)})};typeof e.alsoResize=="object"&&!e.alsoResize.nodeType?a.each(e.alsoResize,function(a,b){i(a,b)}):i(e.alsoResize)},stop:function(b,c){a(this).removeData("resizable-alsoresize")}}),a.ui.plugin.add("resizable","animate",{stop:function(b,c){var d=a(this).data("resizable"),e=d.options,f=d._proportionallyResizeElements,g=f.length&&/textarea/i.test(f[0].nodeName),h=g&&a.ui.hasScroll(f[0],"left")?0:d.sizeDiff.height,i=g?0:d.sizeDiff.width,j={width:d.size.width-i,height:d.size.height-h},k=parseInt(d.element.css("left"),10)+(d.position.left-d.originalPosition.left)||null,l=parseInt(d.element.css("top"),10)+(d.position.top-d.originalPosition.top)||null;d.element.animate(a.extend(j,l&&k?{top:l,left:k}:{}),{duration:e.animateDuration,easing:e.animateEasing,step:function(){var c={width:parseInt(d.element.css("width"),10),height:parseInt(d.element.css("height"),10),top:parseInt(d.element.css("top"),10),left:parseInt(d.element.css("left"),10)};f&&f.length&&a(f[0]).css({width:c.width,height:c.height}),d._updateCache(c),d._propagate("resize",b)}})}}),a.ui.plugin.add("resizable","containment",{start:function(b,d){var e=a(this).data("resizable"),f=e.options,g=e.element,h=f.containment,i=h instanceof a?h.get(0):/parent/.test(h)?g.parent().get(0):h;if(!!i){e.containerElement=a(i);if(/document/.test(h)||h==document)e.containerOffset={left:0,top:0},e.containerPosition={left:0,top:0},e.parentData={element:a(document),left:0,top:0,width:a(document).width(),height:a(document).height()||document.body.parentNode.scrollHeight};else{var j=a(i),k=[];a(["Top","Right","Left","Bottom"]).each(function(a,b){k[a]=c(j.css("padding"+b))}),e.containerOffset=j.offset(),e.containerPosition=j.position(),e.containerSize={height:j.innerHeight()-k[3],width:j.innerWidth()-k[1]};var l=e.containerOffset,m=e.containerSize.height,n=e.containerSize.width,o=a.ui.hasScroll(i,"left")?i.scrollWidth:n,p=a.ui.hasScroll(i)?i.scrollHeight:m;e.parentData={element:i,left:l.left,top:l.top,width:o,height:p}}}},resize:function(b,c){var d=a(this).data("resizable"),e=d.options,f=d.containerSize,g=d.containerOffset,h=d.size,i=d.position,j=d._aspectRatio||b.shiftKey,k={top:0,left:0},l=d.containerElement;l[0]!=document&&/static/.test(l.css("position"))&&(k=g),i.left<(d._helper?g.left:0)&&(d.size.width=d.size.width+(d._helper?d.position.left-g.left:d.position.left-k.left),j&&(d.size.height=d.size.width/e.aspectRatio),d.position.left=e.helper?g.left:0),i.top<(d._helper?g.top:0)&&(d.size.height=d.size.height+(d._helper?d.position.top-g.top:d.position.top),j&&(d.size.width=d.size.height*e.aspectRatio),d.position.top=d._helper?g.top:0),d.offset.left=d.parentData.left+d.position.left,d.offset.top=d.parentData.top+d.position.top;var m=Math.abs((d._helper?d.offset.left-k.left:d.offset.left-k.left)+d.sizeDiff.width),n=Math.abs((d._helper?d.offset.top-k.top:d.offset.top-g.top)+d.sizeDiff.height),o=d.containerElement.get(0)==d.element.parent().get(0),p=/relative|absolute/.test(d.containerElement.css("position"));o&&p&&(m-=d.parentData.left),m+d.size.width>=d.parentData.width&&(d.size.width=d.parentData.width-m,j&&(d.size.height=d.size.width/d.aspectRatio)),n+d.size.height>=d.parentData.height&&(d.size.height=d.parentData.height-n,j&&(d.size.width=d.size.height*d.aspectRatio))},stop:function(b,c){var d=a(this).data("resizable"),e=d.options,f=d.position,g=d.containerOffset,h=d.containerPosition,i=d.containerElement,j=a(d.helper),k=j.offset(),l=j.outerWidth()-d.sizeDiff.width,m=j.outerHeight()-d.sizeDiff.height;d._helper&&!e.animate&&/relative/.test(i.css("position"))&&a(this).css({left:k.left-h.left-g.left,width:l,height:m}),d._helper&&!e.animate&&/static/.test(i.css("position"))&&a(this).css({left:k.left-h.left-g.left,width:l,height:m})}}),a.ui.plugin.add("resizable","ghost",{start:function(b,c){var d=a(this).data("resizable"),e=d.options,f=d.size;d.ghost=d.originalElement.clone(),d.ghost.css({opacity:.25,display:"block",position:"relative",height:f.height,width:f.width,margin:0,left:0,top:0}).addClass("ui-resizable-ghost").addClass(typeof e.ghost=="string"?e.ghost:""),d.ghost.appendTo(d.helper)},resize:function(b,c){var d=a(this).data("resizable"),e=d.options;d.ghost&&d.ghost.css({position:"relative",height:d.size.height,width:d.size.width})},stop:function(b,c){var d=a(this).data("resizable"),e=d.options;d.ghost&&d.helper&&d.helper.get(0).removeChild(d.ghost.get(0))}}),a.ui.plugin.add("resizable","grid",{resize:function(b,c){var d=a(this).data("resizable"),e=d.options,f=d.size,g=d.originalSize,h=d.originalPosition,i=d.axis,j=e._aspectRatio||b.shiftKey;e.grid=typeof e.grid=="number"?[e.grid,e.grid]:e.grid;var k=Math.round((f.width-g.width)/(e.grid[0]||1))*(e.grid[0]||1),l=Math.round((f.height-g.height)/(e.grid[1]||1))*(e.grid[1]||1);/^(se|s|e)$/.test(i)?(d.size.width=g.width+k,d.size.height=g.height+l):/^(ne)$/.test(i)?(d.size.width=g.width+k,d.size.height=g.height+l,d.position.top=h.top-l):/^(sw)$/.test(i)?(d.size.width=g.width+k,d.size.height=g.height+l,d.position.left=h.left-k):(d.size.width=g.width+k,d.size.height=g.height+l,d.position.top=h.top-l,d.position.left=h.left-k)}});var c=function(a){return parseInt(a,10)||0},d=function(a){return!isNaN(parseInt(a,10))}}(jQuery),function(a,b){a.widget("ui.selectable",a.ui.mouse,{options:{appendTo:"body",autoRefresh:!0,distance:0,filter:"*",tolerance:"touch"},_create:function(){var b=this;this.element.addClass("ui-selectable"),this.dragged=!1;var c;this.refresh=function(){c=a(b.options.filter,b.element[0]),c.addClass("ui-selectee"),c.each(function(){var b=a(this),c=b.offset();a.data(this,"selectable-item",{element:this,$element:b,left:c.left,top:c.top,right:c.left+b.outerWidth(),bottom:c.top+b.outerHeight(),startselected:!1,selected:b.hasClass("ui-selected"),selecting:b.hasClass("ui-selecting"),unselecting:b.hasClass("ui-unselecting")})})},this.refresh(),this.selectees=c.addClass("ui-selectee"),this._mouseInit(),this.helper=a("<div class='ui-selectable-helper'></div>")},destroy:function(){this.selectees.removeClass("ui-selectee").removeData("selectable-item"),this.element.removeClass("ui-selectable ui-selectable-disabled").removeData("selectable").unbind(".selectable"),this._mouseDestroy();return this},_mouseStart:function(b){var c=this;this.opos=[b.pageX,b.pageY];if(!this.options.disabled){var d=this.options;this.selectees=a(d.filter,this.element[0]),this._trigger("start",b),a(d.appendTo).append(this.helper),this.helper.css({left:b.clientX,top:b.clientY,width:0,height:0}),d.autoRefresh&&this.refresh(),this.selectees.filter(".ui-selected").each(function(){var d=a.data(this,"selectable-item");d.startselected=!0,!b.metaKey&&!b.ctrlKey&&(d.$element.removeClass("ui-selected"),d.selected=!1,d.$element.addClass("ui-unselecting"),d.unselecting=!0,c._trigger("unselecting",b,{unselecting:d.element}))}),a(b.target).parents().andSelf().each(function(){var d=a.data(this,"selectable-item");if(d){var e=!b.metaKey&&!b.ctrlKey||!d.$element.hasClass("ui-selected");d.$element.removeClass(e?"ui-unselecting":"ui-selected").addClass(e?"ui-selecting":"ui-unselecting"),d.unselecting=!e,d.selecting=e,d.selected=e,e?c._trigger("selecting",b,{selecting:d.element}):c._trigger("unselecting",b,{unselecting:d.element});return!1}})}},_mouseDrag:function(b){var c=this;this.dragged=!0;if(!this.options.disabled){var d=this.options,e=this.opos[0],f=this.opos[1],g=b.pageX,h=b.pageY;if(e>g){var i=g;g=e,e=i}if(f>h){var i=h;h=f,f=i}this.helper.css({left:e,top:f,width:g-e,height:h-f}),this.selectees.each(function(){var i=a.data(this,"selectable-item");if(!!i&&i.element!=c.element[0]){var j=!1;d.tolerance=="touch"?j=!(i.left>g||i.right<e||i.top>h||i.bottom<f):d.tolerance=="fit"&&(j=i.left>e&&i.right<g&&i.top>f&&i.bottom<h),j?(i.selected&&(i.$element.removeClass("ui-selected"),i.selected=!1),i.unselecting&&(i.$element.removeClass("ui-unselecting"),i.unselecting=!1),i.selecting||(i.$element.addClass("ui-selecting"),i.selecting=!0,c._trigger("selecting",b,{selecting:i.element}))):(i.selecting&&((b.metaKey||b.ctrlKey)&&i.startselected?(i.$element.removeClass("ui-selecting"),i.selecting=!1,i.$element.addClass("ui-selected"),i.selected=!0):(i.$element.removeClass("ui-selecting"),i.selecting=!1,i.startselected&&(i.$element.addClass("ui-unselecting"),i.unselecting=!0),c._trigger("unselecting",b,{unselecting:i.element}))),i.selected&&!b.metaKey&&!b.ctrlKey&&!i.startselected&&(i.$element.removeClass("ui-selected"),i.selected=!1,i.$element.addClass("ui-unselecting"),i.unselecting=!0,c._trigger("unselecting",b,{unselecting:i.element})))}});return!1}},_mouseStop:function(b){var c=this;this.dragged=!1;var d=this.options;a(".ui-unselecting",this.element[0]).each(function(){var d=a.data(this,"selectable-item");d.$element.removeClass("ui-unselecting"),d.unselecting=!1,d.startselected=!1,c._trigger("unselected",b,{unselected:d.element})}),a(".ui-selecting",this.element[0]).each(function(){var d=a.data(this,"selectable-item");d.$element.removeClass("ui-selecting").addClass("ui-selected"),d.selecting=!1,d.selected=!0,d.startselected=!0,c._trigger("selected",b,{selected:d.element})}),this._trigger("stop",b),this.helper.remove();return!1}}),a.extend(a.ui.selectable,{version:"1.8.18"})}(jQuery),function(a,b){a.widget("ui.sortable",a.ui.mouse,{widgetEventPrefix:"sort",ready:!1,options:{appendTo:"parent",axis:!1,connectWith:!1,containment:!1,cursor:"auto",cursorAt:!1,dropOnEmpty:!0,forcePlaceholderSize:!1,forceHelperSize:!1,grid:!1,handle:!1,helper:"original",items:"> *",opacity:!1,placeholder:!1,revert:!1,scroll:!0,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1e3},_create:function(){var a=this.options;this.containerCache={},this.element.addClass("ui-sortable"),this.refresh(),this.floating=this.items.length?a.axis==="x"||/left|right/.test(this.items[0].item.css("float"))||/inline|table-cell/.test(this.items[0].item.css("display")):!1,this.offset=this.element.offset(),this._mouseInit(),this.ready=!0},destroy:function(){a.Widget.prototype.destroy.call(this),this.element.removeClass("ui-sortable ui-sortable-disabled"),this._mouseDestroy();for(var b=this.items.length-1;b>=0;b--)this.items[b].item.removeData(this.widgetName+"-item");return this},_setOption:function(b,c){b==="disabled"?(this.options[b]=c,this.widget()[c?"addClass":"removeClass"]("ui-sortable-disabled")):a.Widget.prototype._setOption.apply(this,arguments)},_mouseCapture:function(b,c){var d=this;if(this.reverting)return!1;if(this.options.disabled||this.options.type=="static")return!1;this._refreshItems(b);var e=null,f=this,g=a(b.target).parents().each(function(){if(a.data(this,d.widgetName+"-item")==f){e=a(this);return!1}});a.data(b.target,d.widgetName+"-item")==f&&(e=a(b.target));if(!e)return!1;if(this.options.handle&&!c){var h=!1;a(this.options.handle,e).find("*").andSelf().each(function(){this==b.target&&(h=!0)});if(!h)return!1}this.currentItem=e,this._removeCurrentsFromItems();return!0},_mouseStart:function(b,c,d){var e=this.options,f=this;this.currentContainer=this,this.refreshPositions(),this.helper=this._createHelper(b),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: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,e.cursorAt&&this._adjustOffsetFromHelper(e.cursorAt),this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]},this.helper[0]!=this.currentItem[0]&&this.currentItem.hide(),this._createPlaceholder(),e.containment&&this._setContainment(),e.cursor&&(a("body").css("cursor")&&(this._storedCursor=a("body").css("cursor")),a("body").css("cursor",e.cursor)),e.opacity&&(this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity")),this.helper.css("opacity",e.opacity)),e.zIndex&&(this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex")),this.helper.css("zIndex",e.zIndex)),this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"&&(this.overflowOffset=this.scrollParent.offset()),this._trigger("start",b,this._uiHash()),this._preserveHelperProportions||this._cacheHelperProportions();if(!d)for(var g=this.containers.length-1;g>=0;g--)this.containers[g]._trigger("activate",b,f._uiHash(this));a.ui.ddmanager&&(a.ui.ddmanager.current=this),a.ui.ddmanager&&!e.dropBehaviour&&a.ui.ddmanager.prepareOffsets(this,b),this.dragging=!0,this.helper.addClass("ui-sortable-helper"),this._mouseDrag(b);return!0},_mouseDrag:function(b){this.position=this._generatePosition(b),this.positionAbs=this._convertPositionTo("absolute"),this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs);if(this.options.scroll){var c=this.options,d=!1;this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"?(this.overflowOffset.top+this.scrollParent[0].offsetHeight-b.pageY<c.scrollSensitivity?this.scrollParent[0].scrollTop=d=this.scrollParent[0].scrollTop+c.scrollSpeed:b.pageY-this.overflowOffset.top<c.scrollSensitivity&&(this.scrollParent[0].scrollTop=d=this.scrollParent[0].scrollTop-c.scrollSpeed),this.overflowOffset.left+this.scrollParent[0].offsetWidth-b.pageX<c.scrollSensitivity?this.scrollParent[0].scrollLeft=d=this.scrollParent[0].scrollLeft+c.scrollSpeed:b.pageX-this.overflowOffset.left<c.scrollSensitivity&&(this.scrollParent[0].scrollLeft=d=this.scrollParent[0].scrollLeft-c.scrollSpeed)):(b.pageY-a(document).scrollTop()<c.scrollSensitivity?d=a(document).scrollTop(a(document).scrollTop()-c.scrollSpeed):a(window).height()-(b.pageY-a(document).scrollTop())<c.scrollSensitivity&&(d=a(document).scrollTop(a(document).scrollTop()+c.scrollSpeed)),b.pageX-a(document).scrollLeft()<c.scrollSensitivity?d=a(document).scrollLeft(a(document).scrollLeft()-c.scrollSpeed):a(window).width()-(b.pageX-a(document).scrollLeft())<c.scrollSensitivity&&(d=a(document).scrollLeft(a(document).scrollLeft()+c.scrollSpeed))),d!==!1&&a.ui.ddmanager&&!c.dropBehaviour&&a.ui.ddmanager.prepareOffsets(this,b)}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 e=this.items.length-1;e>=0;e--){var f=this.items[e],g=f.item[0],h=this._intersectsWithPointer(f);if(!h)continue;if(g!=this.currentItem[0]&&this.placeholder[h==1?"next":"prev"]()[0]!=g&&!a.ui.contains(this.placeholder[0],g)&&(this.options.type=="semi-dynamic"?!a.ui.contains(this.element[0],g):!0)){this.direction=h==1?"down":"up";if(this.options.tolerance=="pointer"||this._intersectsWithSides(f))this._rearrange(b,f);else break;this._trigger("change",b,this._uiHash());break}}this._contactContainers(b),a.ui.ddmanager&&a.ui.ddmanager.drag(this,b),this._trigger("sort",b,this._uiHash()),this.lastPositionAbs=this.positionAbs;return!1},_mouseStop:function(b,c){if(!!b){a.ui.ddmanager&&!this.options.dropBehaviour&&a.ui.ddmanager.drop(this,b);if(this.options.revert){var d=this,e=d.placeholder.offset();d.reverting=!0,a(this.helper).animate({left:e.left-this.offset.parent.left-d.margins.left+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollLeft),top:e.top-this.offset.parent.top-d.margins.top+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollTop)},parseInt(this.options.revert,10)||500,function(){d._clear(b)})}else this._clear(b,c);return!1}},cancel:function(){var b=this;if(this.dragging){this._mouseUp({target:null}),this.options.helper=="original"?this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"):this.currentItem.show();for(var c=this.containers.length-1;c>=0;c--)this.containers[c]._trigger("deactivate",null,b._uiHash(this)),this.containers[c].containerCache.over&&(this.containers[c]._trigger("out",null,b._uiHash(this)),this.containers[c].containerCache.over=0)}this.placeholder&&(this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.options.helper!="original"&&this.helper&&this.helper[0].parentNode&&this.helper.remove(),a.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null}),this.domPosition.prev?a(this.domPosition.prev).after(this.currentItem):a(this.domPosition.parent).prepend(this.currentItem));return this},serialize:function(b){var c=this._getItemsAsjQuery(b&&b.connected),d=[];b=b||{},a(c).each(function(){var c=(a(b.item||this).attr(b.attribute||"id")||"").match(b.expression||/(.+)[-=_](.+)/);c&&d.push((b.key||c[1]+"[]")+"="+(b.key&&b.expression?c[1]:c[2]))}),!d.length&&b.key&&d.push(b.key+"=");return d.join("&")},toArray:function(b){var c=this._getItemsAsjQuery(b&&b.connected),d=[];b=b||{},c.each(function(){d.push(a(b.item||this).attr(b.attribute||"id")||"")});return d},_intersectsWith:function(a){var b=this.positionAbs.left,c=b+this.helperProportions.width,d=this.positionAbs.top,e=d+this.helperProportions.height,f=a.left,g=f+a.width,h=a.top,i=h+a.height,j=this.offset.click.top,k=this.offset.click.left,l=d+j>h&&d+j<i&&b+k>f&&b+k<g;return this.options.tolerance=="pointer"||this.options.forcePointerForContainers||this.options.tolerance!="pointer"&&this.helperProportions[this.floating?"width":"height"]>a[this.floating?"width":"height"]?l:f<b+this.helperProportions.width/2&&c-this.helperProportions.width/2<g&&h<d+this.helperProportions.height/2&&e-this.helperProportions.height/2<i},_intersectsWithPointer:function(b){var c=a.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,b.top,b.height),d=a.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,b.left,b.width),e=c&&d,f=this._getDragVerticalDirection(),g=this._getDragHorizontalDirection();if(!e)return!1;return this.floating?g&&g=="right"||f=="down"?2:1:f&&(f=="down"?2:1)},_intersectsWithSides:function(b){var c=a.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,b.top+b.height/2,b.height),d=a.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,b.left+b.width/2,b.width),e=this._getDragVerticalDirection(),f=this._getDragHorizontalDirection();return this.floating&&f?f=="right"&&d||f=="left"&&!d:e&&(e=="down"&&c||e=="up"&&!c)},_getDragVerticalDirection:function(){var a=this.positionAbs.top-this.lastPositionAbs.top;return a!=0&&(a>0?"down":"up")},_getDragHorizontalDirection:function(){var a=this.positionAbs.left-this.lastPositionAbs.left;return a!=0&&(a>0?"right":"left")},refresh:function(a){this._refreshItems(a),this.refreshPositions();return this},_connectWith:function(){var a=this.options;return a.connectWith.constructor==String?[a.connectWith]:a.connectWith},_getItemsAsjQuery:function(b){var c=this,d=[],e=[],f=this._connectWith();if(f&&b)for(var g=f.length-1;g>=0;g--){var h=a(f[g]);for(var i=h.length-1;i>=0;i--){var j=a.data(h[i],this.widgetName);j&&j!=this&&!j.options.disabled&&e.push([a.isFunction(j.options.items)?j.options.items.call(j.element):a(j.options.items,j.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),j])}}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").not(".ui-sortable-placeholder"),this]);for(var g=e.length-1;g>=0;g--)e[g][0].each(function(){d.push(this)});return a(d)},_removeCurrentsFromItems:function(){var a=this.currentItem.find(":data("+this.widgetName+"-item)");for(var b=0;b<this.items.length;b++)for(var c=0;c<a.length;c++)a[c]==this.items[b].item[0]&&this.items.splice(b,1)},_refreshItems:function(b){this.items=[],this.containers=[this];var c=this.items,d=this,e=[[a.isFunction(this.options.items)?this.options.items.call(this.element[0],b,{item:this.currentItem}):a(this.options.items,this.element),this]],f=this._connectWith();if(f&&this.ready)for(var g=f.length-1;g>=0;g--){var h=a(f[g]);for(var i=h.length-1;i>=0;i--){var j=a.data(h[i],this.widgetName);j&&j!=this&&!j.options.disabled&&(e.push([a.isFunction(j.options.items)?j.options.items.call(j.element[0],b,{item:this.currentItem}):a(j.options.items,j.element),j]),this.containers.push(j))}}for(var g=e.length-1;g>=0;g--){var k=e[g][1],l=e[g][0];for(var i=0,m=l.length;i<m;i++){var n=a(l[i]);n.data(this.widgetName+"-item",k),c.push({item:n,instance:k,width:0,height:0,left:0,top:0})}}},refreshPositions:function(b){this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset());for(var c=this.items.length-1;c>=0;c--){var d=this.items[c];if(d.instance!=this.currentContainer&&this.currentContainer&&d.item[0]!=this.currentItem[0])continue;var e=this.options.toleranceElement?a(this.options.toleranceElement,d.item):d.item;b||(d.width=e.outerWidth(),d.height=e.outerHeight());var f=e.offset();d.left=f.left,d.top=f.top}if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(var c=this.containers.length-1;c>=0;c--){var f=this.containers[c].element.offset();this.containers[c].containerCache.left=f.left,this.containers[c].containerCache.top=f.top,this.containers[c].containerCache.width=this.containers[c].element.outerWidth(),this.containers[c].containerCache.height=this.containers[c].element.outerHeight()}return this},_createPlaceholder:function(b){var c=b||this,d=c.options;if(!d.placeholder||d.placeholder.constructor==String){var e=d.placeholder;d.placeholder={element:function(){var b=a(document.createElement(c.currentItem[0].nodeName)).addClass(e||c.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper")[0];e||(b.style.visibility="hidden");return b},update:function(a,b){if(!e||!!d.forcePlaceholderSize)b.height()||b.height(c.currentItem.innerHeight()-parseInt(c.currentItem.css("paddingTop")||0,10)-parseInt(c.currentItem.css("paddingBottom")||0,10)),b.width()||b.width(c.currentItem.innerWidth()-parseInt(c.currentItem.css("paddingLeft")||0,10)-parseInt(c.currentItem.css("paddingRight")||0,10))}}}c.placeholder=a(d.placeholder.element.call(c.element,c.currentItem)),c.currentItem.after(c.placeholder),d.placeholder.update(c,c.placeholder)},_contactContainers:function(b){var c=null,d=null;for(var e=this.containers.length-1;e>=0;e--){if(a.ui.contains(this.currentItem[0],this.containers[e].element[0]))continue;if(this._intersectsWith(this.containers[e].containerCache)){if(c&&a.ui.contains(this.containers[e].element[0],c.element[0]))continue;c=this.containers[e],d=e}else this.containers[e].containerCache.over&&(this.containers[e]._trigger("out",b,this._uiHash(this)),this.containers[e].containerCache.over=0)}if(!!c)if(this.containers.length===1)this.containers[d]._trigger("over",b,this._uiHash(this)),this.containers[d].containerCache.over=1;else if(this.currentContainer!=this.containers[d]){var f=1e4,g=null,h=this.positionAbs[this.containers[d].floating?"left":"top"];for(var i=this.items.length-1;i>=0;i--){if(!a.ui.contains(this.containers[d].element[0],this.items[i].item[0]))continue;var j=this.items[i][this.containers[d].floating?"left":"top"];Math.abs(j-h)<f&&(f=Math.abs(j-h),g=this.items[i])}if(!g&&!this.options.dropOnEmpty)return;this.currentContainer=this.containers[d],g?this._rearrange(b,g,null,!0):this._rearrange(b,null,this.containers[d].element,!0),this._trigger("change",b,this._uiHash()),this.containers[d]._trigger("change",b,this._uiHash(this)),this.options.placeholder.update(this.currentContainer,this.placeholder),this.containers[d]._trigger("over",b,this._uiHash(this)),this.containers[d].containerCache.over=1}},_createHelper:function(b){var c=this.options,d=a.isFunction(c.helper)?a(c.helper.apply(this.element[0],[b,this.currentItem])):c.helper=="clone"?this.currentItem.clone():this.currentItem;d.parents("body").length||a(c.appendTo!="parent"?c.appendTo:this.currentItem[0].parentNode)[0].appendChild(d[0]),d[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")}),(d[0].style.width==""||c.forceHelperSize)&&d.width(this.currentItem.width()),(d[0].style.height==""||c.forceHelperSize)&&d.height(this.currentItem.height());return d},_adjustOffsetFromHelper:function(b){typeof b=="string"&&(b=b.split(" ")),a.isArray(b)&&(b={left:+b[0],top:+b[1]||0}),"left"in b&&(this.offset.click.left=b.left+this.margins.left),"right"in b&&(this.offset.click.left=this.helperProportions.width-b.right+this.margins.left),"top"in b&&(this.offset.click.top=b.top+this.margins.top),"bottom"in b&&(this.offset.click.top=this.helperProportions.height-b.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var b=this.offsetParent.offset();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 a=this.currentItem.position();return{top:a.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:a.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}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 b=this.options;b.containment=="parent"&&(b.containment=this.helper[0].parentNode);if(b.containment=="document"||b.containment=="window")this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,a(b.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(a(b.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!/^(document|window|parent)$/.test(b.containment)){var c=a(b.containment)[0],d=a(b.containment).offset(),e=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+(e?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+(e?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(b,c){c||(c=this.position);var d=b=="absolute"?1:-1,e=this.options,f=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(f[0].tagName);return{top:c.top+this.offset.relative.top*d+this.offset.parent.top*d-(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():g?0:f.scrollTop())*d),left:c.left+this.offset.relative.left*d+this.offset.parent.left*d-(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():g?0:f.scrollLeft())*d)}},_generatePosition:function(b){var c=this.options,d=this.cssPosition=="absolute"&&(this.scrollParent[0]==document||!a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,e=/(html|body)/i.test(d[0].tagName);this.cssPosition=="relative"&&(this.scrollParent[0]==document||this.scrollParent[0]==this.offsetParent[0])&&(this.offset.relative=this._getRelativeOffset());var f=b.pageX,g=b.pageY;if(this.originalPosition){this.containment&&(b.pageX-this.offset.click.left<this.containment[0]&&(f=this.containment[0]+this.offset.click.left),b.pageY-this.offset.click.top<this.containment[1]&&(g=this.containment[1]+this.offset.click.top),b.pageX-this.offset.click.left>this.containment[2]&&(f=this.containment[2]+this.offset.click.left),b.pageY-this.offset.click.top>this.containment[3]&&(g=this.containment[3]+this.offset.click.top));if(c.grid){var h=this.originalPageY+Math.round((g-this.originalPageY)/c.grid[1])*c.grid[1];g=this.containment?h-this.offset.click.top<this.containment[1]||h-this.offset.click.top>this.containment[3]?h-this.offset.click.top<this.containment[1]?h+c.grid[1]:h-c.grid[1]:h:h;var i=this.originalPageX+Math.round((f-this.originalPageX)/c.grid[0])*c.grid[0];f=this.containment?i-this.offset.click.left<this.containment[0]||i-this.offset.click.left>this.containment[2]?i-this.offset.click.left<this.containment[0]?i+c.grid[0]:i-c.grid[0]:i:i}}return{top:g-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():e?0:d.scrollTop()),left:f-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():e?0:d.scrollLeft())}},_rearrange:function(a,b,c,d){c?c[0].appendChild(this.placeholder[0]):b.item[0].parentNode.insertBefore(this.placeholder[0],this.direction=="down"?b.item[0]:b.item[0].nextSibling),this.counter=this.counter?++this.counter:1;var e=this,f=this.counter;window.setTimeout(function(){f==e.counter&&e.refreshPositions(!d)},0)},_clear:function(b,c){this.reverting=!1;var d=[],e=this;!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null;if(this.helper[0]==this.currentItem[0]){for(var f in this._storedCSS)if(this._storedCSS[f]=="auto"||this._storedCSS[f]=="static")this._storedCSS[f]="";this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else this.currentItem.show();this.fromOutside&&!c&&d.push(function(a){this._trigger("receive",a,this._uiHash(this.fromOutside))}),(this.fromOutside||this.domPosition.prev!=this.currentItem.prev().not(".ui-sortable-helper")[0]||this.domPosition.parent!=this.currentItem.parent()[0])&&!c&&d.push(function(a){this._trigger("update",a,this._uiHash())});if(!a.ui.contains(this.element[0],this.currentItem[0])){c||d.push(function(a){this._trigger("remove",a,this._uiHash())});for(var f=this.containers.length-1;f>=0;f--)a.ui.contains(this.containers[f].element[0],this.currentItem[0])&&!c&&(d.push(function(a){return function(b){a._trigger("receive",b,this._uiHash(this))}}.call(this,this.containers[f])),d.push(function(a){return function(b){a._trigger("update",b,this._uiHash(this))}}.call(this,this.containers[f])))}for(var f=this.containers.length-1;f>=0;f--)c||d.push(function(a){return function(b){a._trigger("deactivate",b,this._uiHash(this))}}.call(this,this.containers[f])),this.containers[f].containerCache.over&&(d.push(function(a){return function(b){a._trigger("out",b,this._uiHash(this))}}.call(this,this.containers[f])),this.containers[f].containerCache.over=0);this._storedCursor&&a("body").css("cursor",this._storedCursor),this._storedOpacity&&this.helper.css("opacity",this._storedOpacity),this._storedZIndex&&this.helper.css("zIndex",this._storedZIndex=="auto"?"":this._storedZIndex),this.dragging=!1;if(this.cancelHelperRemoval){if(!c){this._trigger("beforeStop",b,this._uiHash());for(var f=0;f<d.length;f++)d[f].call(this,b);this._trigger("stop",b,this._uiHash())}return!1}c||this._trigger("beforeStop",b,this._uiHash()),this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.helper[0]!=this.currentItem[0]&&this.helper.remove(),this.helper=null;if(!c){for(var f=0;f<d.length;f++)d[f].call(this,b);this._trigger("stop",b,this._uiHash())}this.fromOutside=!1;return!0},_trigger:function(){a.Widget.prototype._trigger.apply(this,arguments)===!1&&this.cancel()},_uiHash:function(b){var c=b||this;return{helper:c.helper,placeholder:c.placeholder||a([]),position:c.position,originalPosition:c.originalPosition,offset:c.positionAbs,item:c.currentItem,sender:b?b.element:null}}}),a.extend(a.ui.sortable,{version:"1.8.18"})}(jQuery),jQuery.effects||function(a,b){function l(b){if(!b||typeof b=="number"||a.fx.speeds[b])return!0;if(typeof b=="string"&&!a.effects[b])return!0;return!1}function k(b,c,d,e){typeof b=="object"&&(e=c,d=null,c=b,b=c.effect),a.isFunction(c)&&(e=c,d=null,c={});if(typeof c=="number"||a.fx.speeds[c])e=d,d=c,c={};a.isFunction(d)&&(e=d,d=null),c=c||{},d=d||c.duration,d=a.fx.off?0:typeof d=="number"?d:d in a.fx.speeds?a.fx.speeds[d]:a.fx.speeds._default,e=e||c.complete;return[b,c,d,e]}function j(a,b){var c={_:0},d;for(d in b)a[d]!=b[d]&&(c[d]=b[d]);return c}function i(b){var c,d;for(c in b)d=b[c],(d==null||a.isFunction(d)||c in g||/scrollbar/.test(c)||!/color/i.test(c)&&isNaN(parseFloat(d)))&&delete b[c];return b}function h(){var a=document.defaultView?document.defaultView.getComputedStyle(this,null):this.currentStyle,b={},c,d;if(a&&a.length&&a[0]&&a[a[0]]){var e=a.length;while(e--)c=a[e],typeof a[c]=="string"&&(d=c.replace(/\-(\w)/g,function(a,b){return b.toUpperCase()}),b[d]=a[c])}else for(c in a)typeof a[c]=="string"&&(b[c]=a[c]);return b}function d(b,d){var e;do{e=a.curCSS(b,d);if(e!=""&&e!="transparent"||a.nodeName(b,"body"))break;d="backgroundColor"}while(b=b.parentNode);return c(e)}function c(b){var c;if(b&&b.constructor==Array&&b.length==3)return b;if(c=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(b))return[parseInt(c[1],10),parseInt(c[2],10),parseInt(c[3],10)];if(c=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(b))return[parseFloat(c[1])*2.55,parseFloat(c[2])*2.55,parseFloat(c[3])*2.55];if(c=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(b))return[parseInt(c[1],16),parseInt(c[2],16),parseInt(c[3],16)];if(c=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(b))return[parseInt(c[1]+c[1],16),parseInt(c[2]+c[2],16),parseInt(c[3]+c[3],16)];if(c=/rgba\(0, 0, 0, 0\)/.exec(b))return e.transparent;return e[a.trim(b).toLowerCase()]}a.effects={},a.each(["backgroundColor","borderBottomColor","borderLeftColor","borderRightColor","borderTopColor","borderColor","color","outlineColor"],function(b,e){a.fx.step[e]=function(a){a.colorInit||(a.start=d(a.elem,e),a.end=c(a.end),a.colorInit=!0),a.elem.style[e]="rgb("+Math.max(Math.min(parseInt(a.pos*(a.end[0]-a.start[0])+a.start[0],10),255),0)+","+Math.max(Math.min(parseInt(a.pos*(a.end[1]-a.start[1])+a.start[1],10),255),0)+","+Math.max(Math.min(parseInt(a.pos*(a.end[2]-a.start[2])+a.start[2],10),255),0)+")"}});var e={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0],transparent:[255,255,255]},f=["add","remove","toggle"],g={border:1,borderBottom:1,borderColor:1,borderLeft:1,borderRight:1,borderTop:1,borderWidth:1,margin:1,padding:1};a.effects.animateClass=function(b,c,d,e){a.isFunction(d)&&(e=d,d=null);return this.queue(function(){var g=a(this),k=g.attr("style")||" ",l=i(h.call(this)),m,n=g.attr("class");a.each(f,function(a,c){b[c]&&g[c+"Class"](b[c])}),m=i(h.call(this)),g.attr("class",n),g.animate(j(l,m),{queue:!1,duration:c,easing:d,complete:function(){a.each(f,function(a,c){b[c]&&g[c+"Class"](b[c])}),typeof g.attr("style")=="object"?(g.attr("style").cssText="",g.attr("style").cssText=k):g.attr("style",k),e&&e.apply(this,arguments),a.dequeue(this)}})})},a.fn.extend({_addClass:a.fn.addClass,addClass:function(b,c,d,e){return c?a.effects.animateClass.apply(this,[{add:b},c,d,e]):this._addClass(b)},_removeClass:a.fn.removeClass,removeClass:function(b,c,d,e){return c?a.effects.animateClass.apply(this,[{remove:b},c,d,e]):this._removeClass(b)},_toggleClass:a.fn.toggleClass,toggleClass:function(c,d,e,f,g){return typeof d=="boolean"||d===b?e?a.effects.animateClass.apply(this,[d?{add:c}:{remove:c},e,f,g]):this._toggleClass(c,d):a.effects.animateClass.apply(this,[{toggle:c},d,e,f])},switchClass:function(b,c,d,e,f){return a.effects.animateClass.apply(this,[{add:c,remove:b},d,e,f])}}),a.extend(a.effects,{version:"1.8.18",save:function(a,b){for(var c=0;c<b.length;c++)b[c]!==null&&a.data("ec.storage."+b[c],a[0].style[b[c]])},restore:function(a,b){for(var c=0;c<b.length;c++)b[c]!==null&&a.css(b[c],a.data("ec.storage."+b[c]))},setMode:function(a,b){b=="toggle"&&(b=a.is(":hidden")?"show":"hide");return b},getBaseline:function(a,b){var c,d;switch(a[0]){case"top":c=0;break;case"middle":c=.5;break;case"bottom":c=1;break;default:c=a[0]/b.height}switch(a[1]){case"left":d=0;break;case"center":d=.5;break;case"right":d=1;break;default:d=a[1]/b.width}return{x:d,y:c}},createWrapper:function(b){if(b.parent().is(".ui-effects-wrapper"))return b.parent();var c={width:b.outerWidth(!0),height:b.outerHeight(!0),"float":b.css("float")},d=a("<div></div>").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0}),e=document.activeElement;b.wrap(d),(b[0]===e||a.contains(b[0],e))&&a(e).focus(),d=b.parent(),b.css("position")=="static"?(d.css({position:"relative"}),b.css({position:"relative"})):(a.extend(c,{position:b.css("position"),zIndex:b.css("z-index")}),a.each(["top","left","bottom","right"],function(a,d){c[d]=b.css(d),isNaN(parseInt(c[d],10))&&(c[d]="auto")}),b.css({position:"relative",top:0,left:0,right:"auto",bottom:"auto"}));return d.css(c).show()},removeWrapper:function(b){var c,d=document.activeElement;if(b.parent().is(".ui-effects-wrapper")){c=b.parent().replaceWith(b),(b[0]===d||a.contains(b[0],d))&&a(d).focus();return c}return b},setTransition:function(b,c,d,e){e=e||{},a.each(c,function(a,c){unit=b.cssUnit(c),unit[0]>0&&(e[c]=unit[0]*d+unit[1])});return e}}),a.fn.extend({effect:function(b,c,d,e){var f=k.apply(this,arguments),g={options:f[1],duration:f[2],callback:f[3]},h=g.options.mode,i=a.effects[b];if(a.fx.off||!i)return h?this[h](g.duration,g.callback):this.each(function(){g.callback&&g.callback.call(this)});return i.call(this,g)},_show:a.fn.show,show:function(a){if(l(a))return this._show.apply(this,arguments);var b=k.apply(this,arguments);b[1].mode="show";return this.effect.apply(this,b)},_hide:a.fn.hide,hide:function(a){if(l(a))return this._hide.apply(this,arguments);var b=k.apply(this,arguments);b[1].mode="hide";return this.effect.apply(this,b)},__toggle:a.fn.toggle,toggle:function(b){if(l(b)||typeof b=="boolean"||a.isFunction(b))return this.__toggle.apply(this,arguments);var c=k.apply(this,arguments);c[1].mode="toggle";return this.effect.apply(this,c)},cssUnit:function(b){var c=this.css(b),d=[];a.each(["em","px","%","pt"],function(a,b){c.indexOf(b)>0&&(d=[parseFloat(c),b])});return d}}),a.easing.jswing=a.easing.swing,a.extend(a.easing,{def:"easeOutQuad",swing:function(b,c,d,e,f){return a.easing[a.easing.def](b,c,d,e,f)},easeInQuad:function(a,b,c,d,e){return d*(b/=e)*b+c},easeOutQuad:function(a,b,c,d,e){return-d*(b/=e)*(b-2)+c},easeInOutQuad:function(a,b,c,d,e){if((b/=e/2)<1)return d/2*b*b+c;return-d/2*(--b*(b-2)-1)+c},easeInCubic:function(a,b,c,d,e){return d*(b/=e)*b*b+c},easeOutCubic:function(a,b,c,d,e){return d*((b=b/e-1)*b*b+1)+c},easeInOutCubic:function(a,b,c,d,e){if((b/=e/2)<1)return d/2*b*b*b+c;return d/2*((b-=2)*b*b+2)+c},easeInQuart:function(a,b,c,d,e){return d*(b/=e)*b*b*b+c},easeOutQuart:function(a,b,c,d,e){return-d*((b=b/e-1)*b*b*b-1)+c},easeInOutQuart:function(a,b,c,d,e){if((b/=e/2)<1)return d/2*b*b*b*b+c;return-d/2*((b-=2)*b*b*b-2)+c},easeInQuint:function(a,b,c,d,e){return d*(b/=e)*b*b*b*b+c},easeOutQuint:function(a,b,c,d,e){return d*((b=b/e-1)*b*b*b*b+1)+c},easeInOutQuint:function(a,b,c,d,e){if((b/=e/2)<1)return d/2*b*b*b*b*b+c;return d/2*((b-=2)*b*b*b*b+2)+c},easeInSine:function(a,b,c,d,e){return-d*Math.cos(b/e*(Math.PI/2))+d+c},easeOutSine:function(a,b,c,d,e){return d*Math.sin(b/e*(Math.PI/2))+c},easeInOutSine:function(a,b,c,d,e){return-d/2*(Math.cos(Math.PI*b/e)-1)+c},easeInExpo:function(a,b,c,d,e){return b==0?c:d*Math.pow(2,10*(b/e-1))+c},easeOutExpo:function(a,b,c,d,e){return b==e?c+d:d*(-Math.pow(2,-10*b/e)+1)+c},easeInOutExpo:function(a,b,c,d,e){if(b==0)return c;if(b==e)return c+d;if((b/=e/2)<1)return d/2*Math.pow(2,10*(b-1))+c;return d/2*(-Math.pow(2,-10*--b)+2)+c},easeInCirc:function(a,b,c,d,e){return-d*(Math.sqrt(1-(b/=e)*b)-1)+c},easeOutCirc:function(a,b,c,d,e){return d*Math.sqrt(1-(b=b/e-1)*b)+c},easeInOutCirc:function(a,b,c,d,e){if((b/=e/2)<1)return-d/2*(Math.sqrt(1-b*b)-1)+c;return d/2*(Math.sqrt(1-(b-=2)*b)+1)+c},easeInElastic:function(a,b,c,d,e){var f=1.70158,g=0,h=d;if(b==0)return c;if((b/=e)==1)return c+d;g||(g=e*.3);if(h<Math.abs(d)){h=d;var f=g/4}else var f=g/(2*Math.PI)*Math.asin(d/h);return-(h*Math.pow(2,10*(b-=1))*Math.sin((b*e-f)*2*Math.PI/g))+c},easeOutElastic:function(a,b,c,d,e){var f=1.70158,g=0,h=d;if(b==0)return c;if((b/=e)==1)return c+d;g||(g=e*.3);if(h<Math.abs(d)){h=d;var f=g/4}else var f=g/(2*Math.PI)*Math.asin(d/h);return h*Math.pow(2,-10*b)*Math.sin((b*e-f)*2*Math.PI/g)+d+c},easeInOutElastic:function(a,b,c,d,e){var f=1.70158,g=0,h=d;if(b==0)return c;if((b/=e/2)==2)return c+d;g||(g=e*.3*1.5);if(h<Math.abs(d)){h=d;var f=g/4}else var f=g/(2*Math.PI)*Math.asin(d/h);if(b<1)return-0.5*h*Math.pow(2,10*(b-=1))*Math.sin((b*e-f)*2*Math.PI/g)+c;return h*Math.pow(2,-10*(b-=1))*Math.sin((b*e-f)*2*Math.PI/g)*.5+d+c},easeInBack:function(a,c,d,e,f,g){g==b&&(g=1.70158);return e*(c/=f)*c*((g+1)*c-g)+d},easeOutBack:function(a,c,d,e,f,g){g==b&&(g=1.70158);return e*((c=c/f-1)*c*((g+1)*c+g)+1)+d},easeInOutBack:function(a,c,d,e,f,g){g==b&&(g=1.70158);if((c/=f/2)<1)return e/2*c*c*(((g*=1.525)+1)*c-g)+d;return e/2*((c-=2)*c*(((g*=1.525)+1)*c+g)+2)+d},easeInBounce:function(b,c,d,e,f){return e-a.easing.easeOutBounce(b,f-c,0,e,f)+d},easeOutBounce:function(a,b,c,d,e){return(b/=e)<1/2.75?d*7.5625*b*b+c:b<2/2.75?d*(7.5625*(b-=1.5/2.75)*b+.75)+c:b<2.5/2.75?d*(7.5625*(b-=2.25/2.75)*b+.9375)+c:d*(7.5625*(b-=2.625/2.75)*b+.984375)+c},easeInOutBounce:function(b,c,d,e,f){if(c<f/2)return a.easing.easeInBounce(b,c*2,0,e,f)*.5+d;return a.easing.easeOutBounce(b,c*2-f,0,e,f)*.5+e*.5+d}})}(jQuery),function(a,b){a.effects.blind=function(b){return this.queue(function(){var c=a(this),d=["position","top","bottom","left","right"],e=a.effects.setMode(c,b.options.mode||"hide"),f=b.options.direction||"vertical";a.effects.save(c,d),c.show();var g=a.effects.createWrapper(c).css({overflow:"hidden"}),h=f=="vertical"?"height":"width",i=f=="vertical"?g.height():g.width();e=="show"&&g.css(h,0);var j={};j[h]=e=="show"?i:0,g.animate(j,b.duration,b.options.easing,function(){e=="hide"&&c.hide(),a.effects.restore(c,d),a.effects.removeWrapper(c),b.callback&&b.callback.apply(c[0],arguments),c.dequeue()})})}}(jQuery),function(a,b){a.effects.bounce=function(b){return this.queue(function(){var c=a(this),d=["position","top","bottom","left","right"],e=a.effects.setMode(c,b.options.mode||"effect"),f=b.options.direction||"up",g=b.options.distance||20,h=b.options.times||5,i=b.duration||250;/show|hide/.test(e)&&d.push("opacity"),a.effects.save(c,d),c.show(),a.effects.createWrapper(c);var j=f=="up"||f=="down"?"top":"left",k=f=="up"||f=="left"?"pos":"neg",g=b.options.distance||(j=="top"?c.outerHeight({margin:!0})/3:c.outerWidth({margin:!0})/3);e=="show"&&c.css("opacity",0).css(j,k=="pos"?-g:g),e=="hide"&&(g=g/(h*2)),e!="hide"&&h--;if(e=="show"){var l={opacity:1};l[j]=(k=="pos"?"+=":"-=")+g,c.animate(l,i/2,b.options.easing),g=g/2,h--}for(var m=0;m<h;m++){var n={},p={};n[j]=(k=="pos"?"-=":"+=")+g,p[j]=(k=="pos"?"+=":"-=")+g,c.animate(n,i/2,b.options.easing).animate(p,i/2,b.options.easing),g=e=="hide"?g*2:g/2}if(e=="hide"){var l={opacity:0};l[j]=(k=="pos"?"-=":"+=")+g,c.animate(l,i/2,b.options.easing,function(){c.hide(),a.effects.restore(c,d),a.effects.removeWrapper(c),b.callback&&b.callback.apply(this,arguments)})}else{var n={},p={};n[j]=(k=="pos"?"-=":"+=")+g,p[j]=(k=="pos"?"+=":"-=")+g,c.animate(n,i/2,b.options.easing).animate(p,i/2,b.options.easing,function(){a.effects.restore(c,d),a.effects.removeWrapper(c),b.callback&&b.callback.apply(this,arguments)})}c.queue("fx",function(){c.dequeue()}),c.dequeue()})}}(jQuery),function(a,b){a.effects.clip=function(b){return this.queue(function(){var c=a(this),d=["position","top","bottom","left","right","height","width"],e=a.effects.setMode(c,b.options.mode||"hide"),f=b.options.direction||"vertical";a.effects.save(c,d),c.show();var g=a.effects.createWrapper(c).css({overflow:"hidden"}),h=c[0].tagName=="IMG"?g:c,i={size:f=="vertical"?"height":"width",position:f=="vertical"?"top":"left"},j=f=="vertical"?h.height():h.width();e=="show"&&(h.css(i.size,0),h.css(i.position,j/2));var k={};k[i.size]=e=="show"?j:0,k[i.position]=e=="show"?0:j/2,h.animate(k,{queue:!1,duration:b.duration,easing:b.options.easing,complete:function(){e=="hide"&&c.hide(),a.effects.restore(c,d),a.effects.removeWrapper(c),b.callback&&b.callback.apply(c[0],arguments),c.dequeue()}})})}}(jQuery),function(a,b){a.effects.drop=function(b){return this.queue(function(){var c=a(this),d=["position","top","bottom","left","right","opacity"],e=a.effects.setMode(c,b.options.mode||"hide"),f=b.options.direction||"left";a.effects.save(c,d),c.show(),a.effects.createWrapper(c);var g=f=="up"||f=="down"?"top":"left",h=f=="up"||f=="left"?"pos":"neg",i=b.options.distance||(g=="top"?c.outerHeight({margin:!0})/2:c.outerWidth({margin:!0})/2);e=="show"&&c.css("opacity",0).css(g,h=="pos"?-i:i);var j={opacity:e=="show"?1:0};j[g]=(e=="show"?h=="pos"?"+=":"-=":h=="pos"?"-=":"+=")+i,c.animate(j,{queue:!1,duration:b.duration,easing:b.options.easing,complete:function(){e=="hide"&&c.hide(),a.effects.restore(c,d),a.effects.removeWrapper(c),b.callback&&b.callback.apply(this,arguments),c.dequeue()}})})}}(jQuery),function(a,b){a.effects.explode=function(b){return this.queue(function(){var c=b.options.pieces?Math.round(Math.sqrt(b.options.pieces)):3,d=b.options.pieces?Math.round(Math.sqrt(b.options.pieces)):3;b.options.mode=b.options.mode=="toggle"?a(this).is(":visible")?"hide":"show":b.options.mode;var e=a(this).show().css("visibility","hidden"),f=e.offset();f.top-=parseInt(e.css("marginTop"),10)||0,f.left-=parseInt(e.css("marginLeft"),10)||0;var g=e.outerWidth(!0),h=e.outerHeight(!0);for(var i=0;i<c;i++)for(var j=0;j<d;j++)e.clone().appendTo("body").wrap("<div></div>").css({position:"absolute",visibility:"visible",left:-j*(g/d),top:-i*(h/c)}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:g/d,height:h/c,left:f.left+j*(g/d)+(b.options.mode=="show"?(j-Math.floor(d/2))*(g/d):0),top:f.top+i*(h/c)+(b.options.mode=="show"?(i-Math.floor(c/2))*(h/c):0),opacity:b.options.mode=="show"?0:1}).animate({left:f.left+j*(g/d)+(b.options.mode=="show"?0:(j-Math.floor(d/2))*(g/d)),top:f.top+i*(h/c)+(b.options.mode=="show"?0:(i-Math.floor(c/2))*(h/c)),opacity:b.options.mode=="show"?1:0},b.duration||500);setTimeout(function(){b.options.mode=="show"?e.css({visibility:"visible"}):e.css({visibility:"visible"}).hide(),b.callback&&b.callback.apply(e[0]),e.dequeue(),a("div.ui-effects-explode").remove()},b.duration||500)})}}(jQuery),function(a,b){a.effects.fade=function(b){return this.queue(function(){var c=a(this),d=a.effects.setMode(c,b.options.mode||"hide");c.animate({opacity:d},{queue:!1,duration:b.duration,easing:b.options.easing,complete:function(){b.callback&&b.callback.apply(this,arguments),c.dequeue()}})})}}(jQuery),function(a,b){a.effects.fold=function(b){return this.queue(function(){var c=a(this),d=["position","top","bottom","left","right"],e=a.effects.setMode(c,b.options.mode||"hide"),f=b.options.size||15,g=!!b.options.horizFirst,h=b.duration?b.duration/2:a.fx.speeds._default/2;a.effects.save(c,d),c.show();var i=a.effects.createWrapper(c).css({overflow:"hidden"}),j=e=="show"!=g,k=j?["width","height"]:["height","width"],l=j?[i.width(),i.height()]:[i.height(),i.width()],m=/([0-9]+)%/.exec(f);m&&(f=parseInt(m[1],10)/100*l[e=="hide"?0:1]),e=="show"&&i.css(g?{height:0,width:f}:{height:f,width:0});var n={},p={};n[k[0]]=e=="show"?l[0]:f,p[k[1]]=e=="show"?l[1]:0,i.animate(n,h,b.options.easing).animate(p,h,b.options.easing,function(){e=="hide"&&c.hide(),a.effects.restore(c,d),a.effects.removeWrapper(c),b.callback&&b.callback.apply(c[0],arguments),c.dequeue()})})}}(jQuery),function(a,b){a.effects.highlight=function(b){return this.queue(function(){var c=a(this),d=["backgroundImage","backgroundColor","opacity"],e=a.effects.setMode(c,b.options.mode||"show"),f={backgroundColor:c.css("backgroundColor")};e=="hide"&&(f.opacity=0),a.effects.save(c,d),c.show().css({backgroundImage:"none",backgroundColor:b.options.color||"#ffff99"}).animate(f,{queue:!1,duration:b.duration,easing:b.options.easing,complete:function(){e=="hide"&&c.hide(),a.effects.restore(c,d),e=="show"&&!a.support.opacity&&this.style.removeAttribute("filter"),b.callback&&b.callback.apply(this,arguments),c.dequeue()}})})}}(jQuery),function(a,b){a.effects.pulsate=function(b){return this.queue(function(){var c=a(this),d=a.effects.setMode(c,b.options.mode||"show");times=(b.options.times||5)*2-1,duration=b.duration?b.duration/2:a.fx.speeds._default/2,isVisible=c.is(":visible"),animateTo=0,isVisible||(c.css("opacity",0).show(),animateTo=1),(d=="hide"&&isVisible||d=="show"&&!isVisible)&&times--;for(var e=0;e<times;e++)c.animate({opacity:animateTo},duration,b.options.easing),animateTo=(animateTo+1)%2;c.animate({opacity:animateTo},duration,b.options.easing,function(){animateTo==0&&c.hide(),b.callback&&b.callback.apply(this,arguments)}),c.queue("fx",function(){c.dequeue()}).dequeue()})}}(jQuery),function(a,b){a.effects.puff=function(b){return this.queue(function(){var c=a(this),d=a.effects.setMode(c,b.options.mode||"hide"),e=parseInt(b.options.percent,10)||150,f=e/100,g={height:c.height(),width:c.width()};a.extend(b.options,{fade:!0,mode:d,percent:d=="hide"?e:100,from:d=="hide"?g:{height:g.height*f,width:g.width*f}}),c.effect("scale",b.options,b.duration,b.callback),c.dequeue()})},a.effects.scale=function(b){return this.queue(function(){var c=a(this),d=a.extend(!0,{},b.options),e=a.effects.setMode(c,b.options.mode||"effect"),f=parseInt(b.options.percent,10)||(parseInt(b.options.percent,10)==0?0:e=="hide"?0:100),g=b.options.direction||"both",h=b.options.origin;e!="effect"&&(d.origin=h||["middle","center"],d.restore=!0);var i={height:c.height(),width:c.width()};c.from=b.options.from||(e=="show"?{height:0,width:0}:i);var j={y:g!="horizontal"?f/100:1,x:g!="vertical"?f/100:1};c.to={height:i.height*j.y,width:i.width*j.x},b.options.fade&&(e=="show"&&(c.from.opacity=0,c.to.opacity=1),e=="hide"&&(c.from.opacity=1,c.to.opacity=0)),d.from=c.from,d.to=c.to,d.mode=e,c.effect("size",d,b.duration,b.callback),c.
+dequeue()})},a.effects.size=function(b){return this.queue(function(){var c=a(this),d=["position","top","bottom","left","right","width","height","overflow","opacity"],e=["position","top","bottom","left","right","overflow","opacity"],f=["width","height","overflow"],g=["fontSize"],h=["borderTopWidth","borderBottomWidth","paddingTop","paddingBottom"],i=["borderLeftWidth","borderRightWidth","paddingLeft","paddingRight"],j=a.effects.setMode(c,b.options.mode||"effect"),k=b.options.restore||!1,l=b.options.scale||"both",m=b.options.origin,n={height:c.height(),width:c.width()};c.from=b.options.from||n,c.to=b.options.to||n;if(m){var p=a.effects.getBaseline(m,n);c.from.top=(n.height-c.from.height)*p.y,c.from.left=(n.width-c.from.width)*p.x,c.to.top=(n.height-c.to.height)*p.y,c.to.left=(n.width-c.to.width)*p.x}var q={from:{y:c.from.height/n.height,x:c.from.width/n.width},to:{y:c.to.height/n.height,x:c.to.width/n.width}};if(l=="box"||l=="both")q.from.y!=q.to.y&&(d=d.concat(h),c.from=a.effects.setTransition(c,h,q.from.y,c.from),c.to=a.effects.setTransition(c,h,q.to.y,c.to)),q.from.x!=q.to.x&&(d=d.concat(i),c.from=a.effects.setTransition(c,i,q.from.x,c.from),c.to=a.effects.setTransition(c,i,q.to.x,c.to));(l=="content"||l=="both")&&q.from.y!=q.to.y&&(d=d.concat(g),c.from=a.effects.setTransition(c,g,q.from.y,c.from),c.to=a.effects.setTransition(c,g,q.to.y,c.to)),a.effects.save(c,k?d:e),c.show(),a.effects.createWrapper(c),c.css("overflow","hidden").css(c.from);if(l=="content"||l=="both")h=h.concat(["marginTop","marginBottom"]).concat(g),i=i.concat(["marginLeft","marginRight"]),f=d.concat(h).concat(i),c.find("*[width]").each(function(){child=a(this),k&&a.effects.save(child,f);var c={height:child.height(),width:child.width()};child.from={height:c.height*q.from.y,width:c.width*q.from.x},child.to={height:c.height*q.to.y,width:c.width*q.to.x},q.from.y!=q.to.y&&(child.from=a.effects.setTransition(child,h,q.from.y,child.from),child.to=a.effects.setTransition(child,h,q.to.y,child.to)),q.from.x!=q.to.x&&(child.from=a.effects.setTransition(child,i,q.from.x,child.from),child.to=a.effects.setTransition(child,i,q.to.x,child.to)),child.css(child.from),child.animate(child.to,b.duration,b.options.easing,function(){k&&a.effects.restore(child,f)})});c.animate(c.to,{queue:!1,duration:b.duration,easing:b.options.easing,complete:function(){c.to.opacity===0&&c.css("opacity",c.from.opacity),j=="hide"&&c.hide(),a.effects.restore(c,k?d:e),a.effects.removeWrapper(c),b.callback&&b.callback.apply(this,arguments),c.dequeue()}})})}}(jQuery),function(a,b){a.effects.shake=function(b){return this.queue(function(){var c=a(this),d=["position","top","bottom","left","right"],e=a.effects.setMode(c,b.options.mode||"effect"),f=b.options.direction||"left",g=b.options.distance||20,h=b.options.times||3,i=b.duration||b.options.duration||140;a.effects.save(c,d),c.show(),a.effects.createWrapper(c);var j=f=="up"||f=="down"?"top":"left",k=f=="up"||f=="left"?"pos":"neg",l={},m={},n={};l[j]=(k=="pos"?"-=":"+=")+g,m[j]=(k=="pos"?"+=":"-=")+g*2,n[j]=(k=="pos"?"-=":"+=")+g*2,c.animate(l,i,b.options.easing);for(var p=1;p<h;p++)c.animate(m,i,b.options.easing).animate(n,i,b.options.easing);c.animate(m,i,b.options.easing).animate(l,i/2,b.options.easing,function(){a.effects.restore(c,d),a.effects.removeWrapper(c),b.callback&&b.callback.apply(this,arguments)}),c.queue("fx",function(){c.dequeue()}),c.dequeue()})}}(jQuery),function(a,b){a.effects.slide=function(b){return this.queue(function(){var c=a(this),d=["position","top","bottom","left","right"],e=a.effects.setMode(c,b.options.mode||"show"),f=b.options.direction||"left";a.effects.save(c,d),c.show(),a.effects.createWrapper(c).css({overflow:"hidden"});var g=f=="up"||f=="down"?"top":"left",h=f=="up"||f=="left"?"pos":"neg",i=b.options.distance||(g=="top"?c.outerHeight({margin:!0}):c.outerWidth({margin:!0}));e=="show"&&c.css(g,h=="pos"?isNaN(i)?"-"+i:-i:i);var j={};j[g]=(e=="show"?h=="pos"?"+=":"-=":h=="pos"?"-=":"+=")+i,c.animate(j,{queue:!1,duration:b.duration,easing:b.options.easing,complete:function(){e=="hide"&&c.hide(),a.effects.restore(c,d),a.effects.removeWrapper(c),b.callback&&b.callback.apply(this,arguments),c.dequeue()}})})}}(jQuery),function(a,b){a.effects.transfer=function(b){return this.queue(function(){var c=a(this),d=a(b.options.to),e=d.offset(),f={top:e.top,left:e.left,height:d.innerHeight(),width:d.innerWidth()},g=c.offset(),h=a('<div class="ui-effects-transfer"></div>').appendTo(document.body).addClass(b.options.className).css({top:g.top,left:g.left,height:c.innerHeight(),width:c.innerWidth(),position:"absolute"}).animate(f,b.duration,b.options.easing,function(){h.remove(),b.callback&&b.callback.apply(c[0],arguments),c.dequeue()})})}}(jQuery),function(a,b){a.widget("ui.accordion",{options:{active:0,animated:"slide",autoHeight:!0,clearStyle:!1,collapsible:!1,event:"click",fillSpace:!1,header:"> li > :first-child,> :not(li):even",icons:{header:"ui-icon-triangle-1-e",headerSelected:"ui-icon-triangle-1-s"},navigation:!1,navigationFilter:function(){return this.href.toLowerCase()===location.href.toLowerCase()}},_create:function(){var b=this,c=b.options;b.running=0,b.element.addClass("ui-accordion ui-widget ui-helper-reset").children("li").addClass("ui-accordion-li-fix"),b.headers=b.element.find(c.header).addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all").bind("mouseenter.accordion",function(){c.disabled||a(this).addClass("ui-state-hover")}).bind("mouseleave.accordion",function(){c.disabled||a(this).removeClass("ui-state-hover")}).bind("focus.accordion",function(){c.disabled||a(this).addClass("ui-state-focus")}).bind("blur.accordion",function(){c.disabled||a(this).removeClass("ui-state-focus")}),b.headers.next().addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom");if(c.navigation){var d=b.element.find("a").filter(c.navigationFilter).eq(0);if(d.length){var e=d.closest(".ui-accordion-header");e.length?b.active=e:b.active=d.closest(".ui-accordion-content").prev()}}b.active=b._findActive(b.active||c.active).addClass("ui-state-default ui-state-active").toggleClass("ui-corner-all").toggleClass("ui-corner-top"),b.active.next().addClass("ui-accordion-content-active"),b._createIcons(),b.resize(),b.element.attr("role","tablist"),b.headers.attr("role","tab").bind("keydown.accordion",function(a){return b._keydown(a)}).next().attr("role","tabpanel"),b.headers.not(b.active||"").attr({"aria-expanded":"false","aria-selected":"false",tabIndex:-1}).next().hide(),b.active.length?b.active.attr({"aria-expanded":"true","aria-selected":"true",tabIndex:0}):b.headers.eq(0).attr("tabIndex",0),a.browser.safari||b.headers.find("a").attr("tabIndex",-1),c.event&&b.headers.bind(c.event.split(" ").join(".accordion ")+".accordion",function(a){b._clickHandler.call(b,a,this),a.preventDefault()})},_createIcons:function(){var b=this.options;b.icons&&(a("<span></span>").addClass("ui-icon "+b.icons.header).prependTo(this.headers),this.active.children(".ui-icon").toggleClass(b.icons.header).toggleClass(b.icons.headerSelected),this.element.addClass("ui-accordion-icons"))},_destroyIcons:function(){this.headers.children(".ui-icon").remove(),this.element.removeClass("ui-accordion-icons")},destroy:function(){var b=this.options;this.element.removeClass("ui-accordion ui-widget ui-helper-reset").removeAttr("role"),this.headers.unbind(".accordion").removeClass("ui-accordion-header ui-accordion-disabled ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top").removeAttr("role").removeAttr("aria-expanded").removeAttr("aria-selected").removeAttr("tabIndex"),this.headers.find("a").removeAttr("tabIndex"),this._destroyIcons();var c=this.headers.next().css("display","").removeAttr("role").removeClass("ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active ui-accordion-disabled ui-state-disabled");(b.autoHeight||b.fillHeight)&&c.css("height","");return a.Widget.prototype.destroy.call(this)},_setOption:function(b,c){a.Widget.prototype._setOption.apply(this,arguments),b=="active"&&this.activate(c),b=="icons"&&(this._destroyIcons(),c&&this._createIcons()),b=="disabled"&&this.headers.add(this.headers.next())[c?"addClass":"removeClass"]("ui-accordion-disabled ui-state-disabled")},_keydown:function(b){if(!(this.options.disabled||b.altKey||b.ctrlKey)){var c=a.ui.keyCode,d=this.headers.length,e=this.headers.index(b.target),f=!1;switch(b.keyCode){case c.RIGHT:case c.DOWN:f=this.headers[(e+1)%d];break;case c.LEFT:case c.UP:f=this.headers[(e-1+d)%d];break;case c.SPACE:case c.ENTER:this._clickHandler({target:b.target},b.target),b.preventDefault()}if(f){a(b.target).attr("tabIndex",-1),a(f).attr("tabIndex",0),f.focus();return!1}return!0}},resize:function(){var b=this.options,c;if(b.fillSpace){if(a.browser.msie){var d=this.element.parent().css("overflow");this.element.parent().css("overflow","hidden")}c=this.element.parent().height(),a.browser.msie&&this.element.parent().css("overflow",d),this.headers.each(function(){c-=a(this).outerHeight(!0)}),this.headers.next().each(function(){a(this).height(Math.max(0,c-a(this).innerHeight()+a(this).height()))}).css("overflow","auto")}else b.autoHeight&&(c=0,this.headers.next().each(function(){c=Math.max(c,a(this).height("").height())}).height(c));return this},activate:function(a){this.options.active=a;var b=this._findActive(a)[0];this._clickHandler({target:b},b);return this},_findActive:function(b){return b?typeof b=="number"?this.headers.filter(":eq("+b+")"):this.headers.not(this.headers.not(b)):b===!1?a([]):this.headers.filter(":eq(0)")},_clickHandler:function(b,c){var d=this.options;if(!d.disabled){if(!b.target){if(!d.collapsible)return;this.active.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all").children(".ui-icon").removeClass(d.icons.headerSelected).addClass(d.icons.header),this.active.next().addClass("ui-accordion-content-active");var e=this.active.next(),f={options:d,newHeader:a([]),oldHeader:d.active,newContent:a([]),oldContent:e},g=this.active=a([]);this._toggle(g,e,f);return}var h=a(b.currentTarget||c),i=h[0]===this.active[0];d.active=d.collapsible&&i?!1:this.headers.index(h);if(this.running||!d.collapsible&&i)return;var j=this.active,g=h.next(),e=this.active.next(),f={options:d,newHeader:i&&d.collapsible?a([]):h,oldHeader:this.active,newContent:i&&d.collapsible?a([]):g,oldContent:e},k=this.headers.index(this.active[0])>this.headers.index(h[0]);this.active=i?a([]):h,this._toggle(g,e,f,i,k),j.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all").children(".ui-icon").removeClass(d.icons.headerSelected).addClass(d.icons.header),i||(h.removeClass("ui-state-default ui-corner-all").addClass("ui-state-active ui-corner-top").children(".ui-icon").removeClass(d.icons.header).addClass(d.icons.headerSelected),h.next().addClass("ui-accordion-content-active"));return}},_toggle:function(b,c,d,e,f){var g=this,h=g.options;g.toShow=b,g.toHide=c,g.data=d;var i=function(){if(!!g)return g._completed.apply(g,arguments)};g._trigger("changestart",null,g.data),g.running=c.size()===0?b.size():c.size();if(h.animated){var j={};h.collapsible&&e?j={toShow:a([]),toHide:c,complete:i,down:f,autoHeight:h.autoHeight||h.fillSpace}:j={toShow:b,toHide:c,complete:i,down:f,autoHeight:h.autoHeight||h.fillSpace},h.proxied||(h.proxied=h.animated),h.proxiedDuration||(h.proxiedDuration=h.duration),h.animated=a.isFunction(h.proxied)?h.proxied(j):h.proxied,h.duration=a.isFunction(h.proxiedDuration)?h.proxiedDuration(j):h.proxiedDuration;var k=a.ui.accordion.animations,l=h.duration,m=h.animated;m&&!k[m]&&!a.easing[m]&&(m="slide"),k[m]||(k[m]=function(a){this.slide(a,{easing:m,duration:l||700})}),k[m](j)}else h.collapsible&&e?b.toggle():(c.hide(),b.show()),i(!0);c.prev().attr({"aria-expanded":"false","aria-selected":"false",tabIndex:-1}).blur(),b.prev().attr({"aria-expanded":"true","aria-selected":"true",tabIndex:0}).focus()},_completed:function(a){this.running=a?0:--this.running;this.running||(this.options.clearStyle&&this.toShow.add(this.toHide).css({height:"",overflow:""}),this.toHide.removeClass("ui-accordion-content-active"),this.toHide.length&&(this.toHide.parent()[0].className=this.toHide.parent()[0].className),this._trigger("change",null,this.data))}}),a.extend(a.ui.accordion,{version:"1.8.18",animations:{slide:function(b,c){b=a.extend({easing:"swing",duration:300},b,c);if(!b.toHide.size())b.toShow.animate({height:"show",paddingTop:"show",paddingBottom:"show"},b);else{if(!b.toShow.size()){b.toHide.animate({height:"hide",paddingTop:"hide",paddingBottom:"hide"},b);return}var d=b.toShow.css("overflow"),e=0,f={},g={},h=["height","paddingTop","paddingBottom"],i,j=b.toShow;i=j[0].style.width,j.width(j.parent().width()-parseFloat(j.css("paddingLeft"))-parseFloat(j.css("paddingRight"))-(parseFloat(j.css("borderLeftWidth"))||0)-(parseFloat(j.css("borderRightWidth"))||0)),a.each(h,function(c,d){g[d]="hide";var e=(""+a.css(b.toShow[0],d)).match(/^([\d+-.]+)(.*)$/);f[d]={value:e[1],unit:e[2]||"px"}}),b.toShow.css({height:0,overflow:"hidden"}).show(),b.toHide.filter(":hidden").each(b.complete).end().filter(":visible").animate(g,{step:function(a,c){c.prop=="height"&&(e=c.end-c.start===0?0:(c.now-c.start)/(c.end-c.start)),b.toShow[0].style[c.prop]=e*f[c.prop].value+f[c.prop].unit},duration:b.duration,easing:b.easing,complete:function(){b.autoHeight||b.toShow.css("height",""),b.toShow.css({width:i,overflow:d}),b.complete()}})}},bounceslide:function(a){this.slide(a,{easing:a.down?"easeOutBounce":"swing",duration:a.down?1e3:200})}}})}(jQuery),function(a,b){var c=0;a.widget("ui.autocomplete",{options:{appendTo:"body",autoFocus:!1,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null},pending:0,_create:function(){var b=this,c=this.element[0].ownerDocument,d;this.element.addClass("ui-autocomplete-input").attr("autocomplete","off").attr({role:"textbox","aria-autocomplete":"list","aria-haspopup":"true"}).bind("keydown.autocomplete",function(c){if(!b.options.disabled&&!b.element.propAttr("readOnly")){d=!1;var e=a.ui.keyCode;switch(c.keyCode){case e.PAGE_UP:b._move("previousPage",c);break;case e.PAGE_DOWN:b._move("nextPage",c);break;case e.UP:b._move("previous",c),c.preventDefault();break;case e.DOWN:b._move("next",c),c.preventDefault();break;case e.ENTER:case e.NUMPAD_ENTER:b.menu.active&&(d=!0,c.preventDefault());case e.TAB:if(!b.menu.active)return;b.menu.select(c);break;case e.ESCAPE:b.element.val(b.term),b.close(c);break;default:clearTimeout(b.searching),b.searching=setTimeout(function(){b.term!=b.element.val()&&(b.selectedItem=null,b.search(null,c))},b.options.delay)}}}).bind("keypress.autocomplete",function(a){d&&(d=!1,a.preventDefault())}).bind("focus.autocomplete",function(){b.options.disabled||(b.selectedItem=null,b.previous=b.element.val())}).bind("blur.autocomplete",function(a){b.options.disabled||(clearTimeout(b.searching),b.closing=setTimeout(function(){b.close(a),b._change(a)},150))}),this._initSource(),this.response=function(){return b._response.apply(b,arguments)},this.menu=a("<ul></ul>").addClass("ui-autocomplete").appendTo(a(this.options.appendTo||"body",c)[0]).mousedown(function(c){var d=b.menu.element[0];a(c.target).closest(".ui-menu-item").length||setTimeout(function(){a(document).one("mousedown",function(c){c.target!==b.element[0]&&c.target!==d&&!a.ui.contains(d,c.target)&&b.close()})},1),setTimeout(function(){clearTimeout(b.closing)},13)}).menu({focus:function(a,c){var d=c.item.data("item.autocomplete");!1!==b._trigger("focus",a,{item:d})&&/^key/.test(a.originalEvent.type)&&b.element.val(d.value)},selected:function(a,d){var e=d.item.data("item.autocomplete"),f=b.previous;b.element[0]!==c.activeElement&&(b.element.focus(),b.previous=f,setTimeout(function(){b.previous=f,b.selectedItem=e},1)),!1!==b._trigger("select",a,{item:e})&&b.element.val(e.value),b.term=b.element.val(),b.close(a),b.selectedItem=e},blur:function(a,c){b.menu.element.is(":visible")&&b.element.val()!==b.term&&b.element.val(b.term)}}).zIndex(this.element.zIndex()+1).css({top:0,left:0}).hide().data("menu"),a.fn.bgiframe&&this.menu.element.bgiframe(),b.beforeunloadHandler=function(){b.element.removeAttr("autocomplete")},a(window).bind("beforeunload",b.beforeunloadHandler)},destroy:function(){this.element.removeClass("ui-autocomplete-input").removeAttr("autocomplete").removeAttr("role").removeAttr("aria-autocomplete").removeAttr("aria-haspopup"),this.menu.element.remove(),a(window).unbind("beforeunload",this.beforeunloadHandler),a.Widget.prototype.destroy.call(this)},_setOption:function(b,c){a.Widget.prototype._setOption.apply(this,arguments),b==="source"&&this._initSource(),b==="appendTo"&&this.menu.element.appendTo(a(c||"body",this.element[0].ownerDocument)[0]),b==="disabled"&&c&&this.xhr&&this.xhr.abort()},_initSource:function(){var b=this,d,e;a.isArray(this.options.source)?(d=this.options.source,this.source=function(b,c){c(a.ui.autocomplete.filter(d,b.term))}):typeof this.options.source=="string"?(e=this.options.source,this.source=function(d,f){b.xhr&&b.xhr.abort(),b.xhr=a.ajax({url:e,data:d,dataType:"json",context:{autocompleteRequest:++c},success:function(a,b){this.autocompleteRequest===c&&f(a)},error:function(){this.autocompleteRequest===c&&f([])}})}):this.source=this.options.source},search:function(a,b){a=a!=null?a:this.element.val(),this.term=this.element.val();if(a.length<this.options.minLength)return this.close(b);clearTimeout(this.closing);if(this._trigger("search",b)!==!1)return this._search(a)},_search:function(a){this.pending++,this.element.addClass("ui-autocomplete-loading"),this.source({term:a},this.response)},_response:function(a){!this.options.disabled&&a&&a.length?(a=this._normalize(a),this._suggest(a),this._trigger("open")):this.close(),this.pending--,this.pending||this.element.removeClass("ui-autocomplete-loading")},close:function(a){clearTimeout(this.closing),this.menu.element.is(":visible")&&(this.menu.element.hide(),this.menu.deactivate(),this._trigger("close",a))},_change:function(a){this.previous!==this.element.val()&&this._trigger("change",a,{item:this.selectedItem})},_normalize:function(b){if(b.length&&b[0].label&&b[0].value)return b;return a.map(b,function(b){if(typeof b=="string")return{label:b,value:b};return a.extend({label:b.label||b.value,value:b.value||b.label},b)})},_suggest:function(b){var c=this.menu.element.empty().zIndex(this.element.zIndex()+1);this._renderMenu(c,b),this.menu.deactivate(),this.menu.refresh(),c.show(),this._resizeMenu(),c.position(a.extend({of:this.element},this.options.position)),this.options.autoFocus&&this.menu.next(new a.Event("mouseover"))},_resizeMenu:function(){var a=this.menu.element;a.outerWidth(Math.max(a.width("").outerWidth()+1,this.element.outerWidth()))},_renderMenu:function(b,c){var d=this;a.each(c,function(a,c){d._renderItem(b,c)})},_renderItem:function(b,c){return a("<li></li>").data("item.autocomplete",c).append(a("<a></a>").text(c.label)).appendTo(b)},_move:function(a,b){if(!this.menu.element.is(":visible"))this.search(null,b);else{if(this.menu.first()&&/^previous/.test(a)||this.menu.last()&&/^next/.test(a)){this.element.val(this.term),this.menu.deactivate();return}this.menu[a](b)}},widget:function(){return this.menu.element}}),a.extend(a.ui.autocomplete,{escapeRegex:function(a){return a.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")},filter:function(b,c){var d=new RegExp(a.ui.autocomplete.escapeRegex(c),"i");return a.grep(b,function(a){return d.test(a.label||a.value||a)})}})}(jQuery),function(a){a.widget("ui.menu",{_create:function(){var b=this;this.element.addClass("ui-menu ui-widget ui-widget-content ui-corner-all").attr({role:"listbox","aria-activedescendant":"ui-active-menuitem"}).click(function(c){!a(c.target).closest(".ui-menu-item a").length||(c.preventDefault(),b.select(c))}),this.refresh()},refresh:function(){var b=this,c=this.element.children("li:not(.ui-menu-item):has(a)").addClass("ui-menu-item").attr("role","menuitem");c.children("a").addClass("ui-corner-all").attr("tabindex",-1).mouseenter(function(c){b.activate(c,a(this).parent())}).mouseleave(function(){b.deactivate()})},activate:function(a,b){this.deactivate();if(this.hasScroll()){var c=b.offset().top-this.element.offset().top,d=this.element.scrollTop(),e=this.element.height();c<0?this.element.scrollTop(d+c):c>=e&&this.element.scrollTop(d+c-e+b.height())}this.active=b.eq(0).children("a").addClass("ui-state-hover").attr("id","ui-active-menuitem").end(),this._trigger("focus",a,{item:b})},deactivate:function(){!this.active||(this.active.children("a").removeClass("ui-state-hover").removeAttr("id"),this._trigger("blur"),this.active=null)},next:function(a){this.move("next",".ui-menu-item:first",a)},previous:function(a){this.move("prev",".ui-menu-item:last",a)},first:function(){return this.active&&!this.active.prevAll(".ui-menu-item").length},last:function(){return this.active&&!this.active.nextAll(".ui-menu-item").length},move:function(a,b,c){if(!this.active)this.activate(c,this.element.children(b));else{var d=this.active[a+"All"](".ui-menu-item").eq(0);d.length?this.activate(c,d):this.activate(c,this.element.children(b))}},nextPage:function(b){if(this.hasScroll()){if(!this.active||this.last()){this.activate(b,this.element.children(".ui-menu-item:first"));return}var c=this.active.offset().top,d=this.element.height(),e=this.element.children(".ui-menu-item").filter(function(){var b=a(this).offset().top-c-d+a(this).height();return b<10&&b>-10});e.length||(e=this.element.children(".ui-menu-item:last")),this.activate(b,e)}else this.activate(b,this.element.children(".ui-menu-item").filter(!this.active||this.last()?":first":":last"))},previousPage:function(b){if(this.hasScroll()){if(!this.active||this.first()){this.activate(b,this.element.children(".ui-menu-item:last"));return}var c=this.active.offset().top,d=this.element.height();result=this.element.children(".ui-menu-item").filter(function(){var b=a(this).offset().top-c+d-a(this).height();return b<10&&b>-10}),result.length||(result=this.element.children(".ui-menu-item:first")),this.activate(b,result)}else this.activate(b,this.element.children(".ui-menu-item").filter(!this.active||this.first()?":last":":first"))},hasScroll:function(){return this.element.height()<this.element[a.fn.prop?"prop":"attr"]("scrollHeight")},select:function(a){this._trigger("selected",a,{item:this.active})}})}(jQuery),function(a,b){var c,d,e,f,g="ui-button ui-widget ui-state-default ui-corner-all",h="ui-state-hover ui-state-active ",i="ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only",j=function(){var b=a(this).find(":ui-button");setTimeout(function(){b.button("refresh")},1)},k=function(b){var c=b.name,d=b.form,e=a([]);c&&(d?e=a(d).find("[name='"+c+"']"):e=a("[name='"+c+"']",b.ownerDocument).filter(function(){return!this.form}));return e};a.widget("ui.button",{options:{disabled:null,text:!0,label:null,icons:{primary:null,secondary:null}},_create:function(){this.element.closest("form").unbind("reset.button").bind("reset.button",j),typeof this.options.disabled!="boolean"?this.options.disabled=!!this.element.propAttr("disabled"):this.element.propAttr("disabled",this.options.disabled),this._determineButtonType(),this.hasTitle=!!this.buttonElement.attr("title");var b=this,h=this.options,i=this.type==="checkbox"||this.type==="radio",l="ui-state-hover"+(i?"":" ui-state-active"),m="ui-state-focus";h.label===null&&(h.label=this.buttonElement.html()),this.buttonElement.addClass(g).attr("role","button").bind("mouseenter.button",function(){h.disabled||(a(this).addClass("ui-state-hover"),this===c&&a(this).addClass("ui-state-active"))}).bind("mouseleave.button",function(){h.disabled||a(this).removeClass(l)}).bind("click.button",function(a){h.disabled&&(a.preventDefault(),a.stopImmediatePropagation())}),this.element.bind("focus.button",function(){b.buttonElement.addClass(m)}).bind("blur.button",function(){b.buttonElement.removeClass(m)}),i&&(this.element.bind("change.button",function(){f||b.refresh()}),this.buttonElement.bind("mousedown.button",function(a){h.disabled||(f=!1,d=a.pageX,e=a.pageY)}).bind("mouseup.button",function(a){!h.disabled&&(d!==a.pageX||e!==a.pageY)&&(f=!0)})),this.type==="checkbox"?this.buttonElement.bind("click.button",function(){if(h.disabled||f)return!1;a(this).toggleClass("ui-state-active"),b.buttonElement.attr("aria-pressed",b.element[0].checked)}):this.type==="radio"?this.buttonElement.bind("click.button",function(){if(h.disabled||f)return!1;a(this).addClass("ui-state-active"),b.buttonElement.attr("aria-pressed","true");var c=b.element[0];k(c).not(c).map(function(){return a(this).button("widget")[0]}).removeClass("ui-state-active").attr("aria-pressed","false")}):(this.buttonElement.bind("mousedown.button",function(){if(h.disabled)return!1;a(this).addClass("ui-state-active"),c=this,a(document).one("mouseup",function(){c=null})}).bind("mouseup.button",function(){if(h.disabled)return!1;a(this).removeClass("ui-state-active")}).bind("keydown.button",function(b){if(h.disabled)return!1;(b.keyCode==a.ui.keyCode.SPACE||b.keyCode==a.ui.keyCode.ENTER)&&a(this).addClass("ui-state-active")}).bind("keyup.button",function(){a(this).removeClass("ui-state-active")}),this.buttonElement.is("a")&&this.buttonElement.keyup(function(b){b.keyCode===a.ui.keyCode.SPACE&&a(this).click()})),this._setOption("disabled",h.disabled),this._resetButton()},_determineButtonType:function(){this.element.is(":checkbox")?this.type="checkbox":this.element.is(":radio")?this.type="radio":this.element.is("input")?this.type="input":this.type="button";if(this.type==="checkbox"||this.type==="radio"){var a=this.element.parents().filter(":last"),b="label[for='"+this.element.attr("id")+"']";this.buttonElement=a.find(b),this.buttonElement.length||(a=a.length?a.siblings():this.element.siblings(),this.buttonElement=a.filter(b),this.buttonElement.length||(this.buttonElement=a.find(b))),this.element.addClass("ui-helper-hidden-accessible");var c=this.element.is(":checked");c&&this.buttonElement.addClass("ui-state-active"),this.buttonElement.attr("aria-pressed",c)}else this.buttonElement=this.element},widget:function(){return this.buttonElement},destroy:function(){this.element.removeClass("ui-helper-hidden-accessible"),this.buttonElement.removeClass(g+" "+h+" "+i).removeAttr("role").removeAttr("aria-pressed").html(this.buttonElement.find(".ui-button-text").html()),this.hasTitle||this.buttonElement.removeAttr("title"),a.Widget.prototype.destroy.call(this)},_setOption:function(b,c){a.Widget.prototype._setOption.apply(this,arguments);b==="disabled"?c?this.element.propAttr("disabled",!0):this.element.propAttr("disabled",!1):this._resetButton()},refresh:function(){var b=this.element.is(":disabled");b!==this.options.disabled&&this._setOption("disabled",b),this.type==="radio"?k(this.element[0]).each(function(){a(this).is(":checked")?a(this).button("widget").addClass("ui-state-active").attr("aria-pressed","true"):a(this).button("widget").removeClass("ui-state-active").attr("aria-pressed","false")}):this.type==="checkbox"&&(this.element.is(":checked")?this.buttonElement.addClass("ui-state-active").attr("aria-pressed","true"):this.buttonElement.removeClass("ui-state-active").attr("aria-pressed","false"))},_resetButton:function(){if(this.type==="input")this.options.label&&this.element.val(this.options.label);else{var b=this.buttonElement.removeClass(i),c=a("<span></span>",this.element[0].ownerDocument).addClass("ui-button-text").html(this.options.label).appendTo(b.empty()).text(),d=this.options.icons,e=d.primary&&d.secondary,f=[];d.primary||d.secondary?(this.options.text&&f.push("ui-button-text-icon"+(e?"s":d.primary?"-primary":"-secondary")),d.primary&&b.prepend("<span class='ui-button-icon-primary ui-icon "+d.primary+"'></span>"),d.secondary&&b.append("<span class='ui-button-icon-secondary ui-icon "+d.secondary+"'></span>"),this.options.text||(f.push(e?"ui-button-icons-only":"ui-button-icon-only"),this.hasTitle||b.attr("title",c))):f.push("ui-button-text-only"),b.addClass(f.join(" "))}}}),a.widget("ui.buttonset",{options:{items:":button, :submit, :reset, :checkbox, :radio, a, :data(button)"},_create:function(){this.element.addClass("ui-buttonset")},_init:function(){this.refresh()},_setOption:function(b,c){b==="disabled"&&this.buttons.button("option",b,c),a.Widget.prototype._setOption.apply(this,arguments)},refresh:function(){var b=this.element.css("direction")==="rtl";this.buttons=this.element.find(this.options.items).filter(":ui-button").button("refresh").end().not(":ui-button").button().end().map(function(){return a(this).button("widget")[0]}).removeClass("ui-corner-all ui-corner-left ui-corner-right").filter(":first").addClass(b?"ui-corner-right":"ui-corner-left").end().filter(":last").addClass(b?"ui-corner-left":"ui-corner-right").end().end()},destroy:function(){this.element.removeClass("ui-buttonset"),this.buttons.map(function(){return a(this).button("widget")[0]}).removeClass("ui-corner-left ui-corner-right").end().button("destroy"),a.Widget.prototype.destroy.call(this)}})}(jQuery),function($,undefined){function isArray(a){return a&&($.browser.safari&&typeof a=="object"&&a.length||a.constructor&&a.constructor.toString().match(/\Array\(\)/))}function extendRemove(a,b){$.extend(a,b);for(var c in b)if(b[c]==null||b[c]==undefined)a[c]=b[c];return a}function bindHover(a){var b="button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";return a.bind("mouseout",function(a){var c=$(a.target).closest(b);!c.length||c.removeClass("ui-state-hover ui-datepicker-prev-hover ui-datepicker-next-hover")}).bind("mouseover",function(c){var d=$(c.target).closest(b);!$.datepicker._isDisabledDatepicker(instActive.inline?a.parent()[0]:instActive.input[0])&&!!d.length&&(d.parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"),d.addClass("ui-state-hover"),d.hasClass("ui-datepicker-prev")&&d.addClass("ui-datepicker-prev-hover"),d.hasClass("ui-datepicker-next")&&d.addClass("ui-datepicker-next-hover"))})}function Datepicker(){this.debug=!1,this._curInst=null,this._keyEvent=!1,this._disabledInputs=[],this._datepickerShowing=!1,this._inDialog=!1,this._mainDivId="ui-datepicker-div",this._inlineClass="ui-datepicker-inline",this._appendClass="ui-datepicker-append",this._triggerClass="ui-datepicker-trigger",this._dialogClass="ui-datepicker-dialog",this._disableClass="ui-datepicker-disabled",this._unselectableClass="ui-datepicker-unselectable",this._currentClass="ui-datepicker-current-day",this._dayOverClass="ui-datepicker-days-cell-over",this.regional=[],this.regional[""]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"mm/dd/yy",firstDay:0,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},this._defaults={showOn:"focus",showAnim:"fadeIn",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:!1,hideIfNoPrevNext:!1,navigationAsDateFormat:!1,gotoCurrent:!1,changeMonth:!1,changeYear:!1,yearRange:"c-10:c+10",showOtherMonths:!1,selectOtherMonths:!1,showWeek:!1,calculateWeek:this.iso8601Week,shortYearCutoff:"+10",minDate:null,maxDate:null,duration:"fast",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:!0,showButtonPanel:!1,autoSize:!1,disabled:!1},$.extend(this._defaults,this.regional[""]),this.dpDiv=bindHover($('<div id="'+this._mainDivId+'" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>'))}$.extend($.ui,{datepicker:{version:"1.8.18"}});var PROP_NAME="datepicker",dpuuid=(new Date).getTime(),instActive;$.extend(Datepicker.prototype,{markerClassName:"hasDatepicker",maxRows:4,log:function(){this.debug&&console.log.apply("",arguments)},_widgetDatepicker:function(){return this.dpDiv},setDefaults:function(a){extendRemove(this._defaults,a||{});return this},_attachDatepicker:function(target,settings){var inlineSettings=null;for(var attrName in this._defaults){var attrValue=target.getAttribute("date:"+attrName);if(attrValue){inlineSettings=inlineSettings||{};try{inlineSettings[attrName]=eval(attrValue)}catch(err){inlineSettings[attrName]=attrValue}
+}}var nodeName=target.nodeName.toLowerCase(),inline=nodeName=="div"||nodeName=="span";target.id||(this.uuid+=1,target.id="dp"+this.uuid);var inst=this._newInst($(target),inline);inst.settings=$.extend({},settings||{},inlineSettings||{}),nodeName=="input"?this._connectDatepicker(target,inst):inline&&this._inlineDatepicker(target,inst)},_newInst:function(a,b){var c=a[0].id.replace(/([^A-Za-z0-9_-])/g,"\\\\$1");return{id:c,input:a,selectedDay:0,selectedMonth:0,selectedYear:0,drawMonth:0,drawYear:0,inline:b,dpDiv:b?bindHover($('<div class="'+this._inlineClass+' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>')):this.dpDiv}},_connectDatepicker:function(a,b){var c=$(a);b.append=$([]),b.trigger=$([]);c.hasClass(this.markerClassName)||(this._attachments(c,b),c.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).keyup(this._doKeyUp).bind("setData.datepicker",function(a,c,d){b.settings[c]=d}).bind("getData.datepicker",function(a,c){return this._get(b,c)}),this._autoSize(b),$.data(a,PROP_NAME,b),b.settings.disabled&&this._disableDatepicker(a))},_attachments:function(a,b){var c=this._get(b,"appendText"),d=this._get(b,"isRTL");b.append&&b.append.remove(),c&&(b.append=$('<span class="'+this._appendClass+'">'+c+"</span>"),a[d?"before":"after"](b.append)),a.unbind("focus",this._showDatepicker),b.trigger&&b.trigger.remove();var e=this._get(b,"showOn");(e=="focus"||e=="both")&&a.focus(this._showDatepicker);if(e=="button"||e=="both"){var f=this._get(b,"buttonText"),g=this._get(b,"buttonImage");b.trigger=$(this._get(b,"buttonImageOnly")?$("<img/>").addClass(this._triggerClass).attr({src:g,alt:f,title:f}):$('<button type="button"></button>').addClass(this._triggerClass).html(g==""?f:$("<img/>").attr({src:g,alt:f,title:f}))),a[d?"before":"after"](b.trigger),b.trigger.click(function(){$.datepicker._datepickerShowing&&$.datepicker._lastInput==a[0]?$.datepicker._hideDatepicker():$.datepicker._datepickerShowing&&$.datepicker._lastInput!=a[0]?($.datepicker._hideDatepicker(),$.datepicker._showDatepicker(a[0])):$.datepicker._showDatepicker(a[0]);return!1})}},_autoSize:function(a){if(this._get(a,"autoSize")&&!a.inline){var b=new Date(2009,11,20),c=this._get(a,"dateFormat");if(c.match(/[DM]/)){var d=function(a){var b=0,c=0;for(var d=0;d<a.length;d++)a[d].length>b&&(b=a[d].length,c=d);return c};b.setMonth(d(this._get(a,c.match(/MM/)?"monthNames":"monthNamesShort"))),b.setDate(d(this._get(a,c.match(/DD/)?"dayNames":"dayNamesShort"))+20-b.getDay())}a.input.attr("size",this._formatDate(a,b).length)}},_inlineDatepicker:function(a,b){var c=$(a);c.hasClass(this.markerClassName)||(c.addClass(this.markerClassName).append(b.dpDiv).bind("setData.datepicker",function(a,c,d){b.settings[c]=d}).bind("getData.datepicker",function(a,c){return this._get(b,c)}),$.data(a,PROP_NAME,b),this._setDate(b,this._getDefaultDate(b),!0),this._updateDatepicker(b),this._updateAlternate(b),b.settings.disabled&&this._disableDatepicker(a),b.dpDiv.css("display","block"))},_dialogDatepicker:function(a,b,c,d,e){var f=this._dialogInst;if(!f){this.uuid+=1;var g="dp"+this.uuid;this._dialogInput=$('<input type="text" id="'+g+'" style="position: absolute; top: -100px; width: 0px; z-index: -10;"/>'),this._dialogInput.keydown(this._doKeyDown),$("body").append(this._dialogInput),f=this._dialogInst=this._newInst(this._dialogInput,!1),f.settings={},$.data(this._dialogInput[0],PROP_NAME,f)}extendRemove(f.settings,d||{}),b=b&&b.constructor==Date?this._formatDate(f,b):b,this._dialogInput.val(b),this._pos=e?e.length?e:[e.pageX,e.pageY]:null;if(!this._pos){var h=document.documentElement.clientWidth,i=document.documentElement.clientHeight,j=document.documentElement.scrollLeft||document.body.scrollLeft,k=document.documentElement.scrollTop||document.body.scrollTop;this._pos=[h/2-100+j,i/2-150+k]}this._dialogInput.css("left",this._pos[0]+20+"px").css("top",this._pos[1]+"px"),f.settings.onSelect=c,this._inDialog=!0,this.dpDiv.addClass(this._dialogClass),this._showDatepicker(this._dialogInput[0]),$.blockUI&&$.blockUI(this.dpDiv),$.data(this._dialogInput[0],PROP_NAME,f);return this},_destroyDatepicker:function(a){var b=$(a),c=$.data(a,PROP_NAME);if(!!b.hasClass(this.markerClassName)){var d=a.nodeName.toLowerCase();$.removeData(a,PROP_NAME),d=="input"?(c.append.remove(),c.trigger.remove(),b.removeClass(this.markerClassName).unbind("focus",this._showDatepicker).unbind("keydown",this._doKeyDown).unbind("keypress",this._doKeyPress).unbind("keyup",this._doKeyUp)):(d=="div"||d=="span")&&b.removeClass(this.markerClassName).empty()}},_enableDatepicker:function(a){var b=$(a),c=$.data(a,PROP_NAME);if(!!b.hasClass(this.markerClassName)){var d=a.nodeName.toLowerCase();if(d=="input")a.disabled=!1,c.trigger.filter("button").each(function(){this.disabled=!1}).end().filter("img").css({opacity:"1.0",cursor:""});else if(d=="div"||d=="span"){var e=b.children("."+this._inlineClass);e.children().removeClass("ui-state-disabled"),e.find("select.ui-datepicker-month, select.ui-datepicker-year").removeAttr("disabled")}this._disabledInputs=$.map(this._disabledInputs,function(b){return b==a?null:b})}},_disableDatepicker:function(a){var b=$(a),c=$.data(a,PROP_NAME);if(!!b.hasClass(this.markerClassName)){var d=a.nodeName.toLowerCase();if(d=="input")a.disabled=!0,c.trigger.filter("button").each(function(){this.disabled=!0}).end().filter("img").css({opacity:"0.5",cursor:"default"});else if(d=="div"||d=="span"){var e=b.children("."+this._inlineClass);e.children().addClass("ui-state-disabled"),e.find("select.ui-datepicker-month, select.ui-datepicker-year").attr("disabled","disabled")}this._disabledInputs=$.map(this._disabledInputs,function(b){return b==a?null:b}),this._disabledInputs[this._disabledInputs.length]=a}},_isDisabledDatepicker:function(a){if(!a)return!1;for(var b=0;b<this._disabledInputs.length;b++)if(this._disabledInputs[b]==a)return!0;return!1},_getInst:function(a){try{return $.data(a,PROP_NAME)}catch(b){throw"Missing instance data for this datepicker"}},_optionDatepicker:function(a,b,c){var d=this._getInst(a);if(arguments.length==2&&typeof b=="string")return b=="defaults"?$.extend({},$.datepicker._defaults):d?b=="all"?$.extend({},d.settings):this._get(d,b):null;var e=b||{};typeof b=="string"&&(e={},e[b]=c);if(d){this._curInst==d&&this._hideDatepicker();var f=this._getDateDatepicker(a,!0),g=this._getMinMaxDate(d,"min"),h=this._getMinMaxDate(d,"max");extendRemove(d.settings,e),g!==null&&e.dateFormat!==undefined&&e.minDate===undefined&&(d.settings.minDate=this._formatDate(d,g)),h!==null&&e.dateFormat!==undefined&&e.maxDate===undefined&&(d.settings.maxDate=this._formatDate(d,h)),this._attachments($(a),d),this._autoSize(d),this._setDate(d,f),this._updateAlternate(d),this._updateDatepicker(d)}},_changeDatepicker:function(a,b,c){this._optionDatepicker(a,b,c)},_refreshDatepicker:function(a){var b=this._getInst(a);b&&this._updateDatepicker(b)},_setDateDatepicker:function(a,b){var c=this._getInst(a);c&&(this._setDate(c,b),this._updateDatepicker(c),this._updateAlternate(c))},_getDateDatepicker:function(a,b){var c=this._getInst(a);c&&!c.inline&&this._setDateFromField(c,b);return c?this._getDate(c):null},_doKeyDown:function(a){var b=$.datepicker._getInst(a.target),c=!0,d=b.dpDiv.is(".ui-datepicker-rtl");b._keyEvent=!0;if($.datepicker._datepickerShowing)switch(a.keyCode){case 9:$.datepicker._hideDatepicker(),c=!1;break;case 13:var e=$("td."+$.datepicker._dayOverClass+":not(."+$.datepicker._currentClass+")",b.dpDiv);e[0]&&$.datepicker._selectDay(a.target,b.selectedMonth,b.selectedYear,e[0]);var f=$.datepicker._get(b,"onSelect");if(f){var g=$.datepicker._formatDate(b);f.apply(b.input?b.input[0]:null,[g,b])}else $.datepicker._hideDatepicker();return!1;case 27:$.datepicker._hideDatepicker();break;case 33:$.datepicker._adjustDate(a.target,a.ctrlKey?-$.datepicker._get(b,"stepBigMonths"):-$.datepicker._get(b,"stepMonths"),"M");break;case 34:$.datepicker._adjustDate(a.target,a.ctrlKey?+$.datepicker._get(b,"stepBigMonths"):+$.datepicker._get(b,"stepMonths"),"M");break;case 35:(a.ctrlKey||a.metaKey)&&$.datepicker._clearDate(a.target),c=a.ctrlKey||a.metaKey;break;case 36:(a.ctrlKey||a.metaKey)&&$.datepicker._gotoToday(a.target),c=a.ctrlKey||a.metaKey;break;case 37:(a.ctrlKey||a.metaKey)&&$.datepicker._adjustDate(a.target,d?1:-1,"D"),c=a.ctrlKey||a.metaKey,a.originalEvent.altKey&&$.datepicker._adjustDate(a.target,a.ctrlKey?-$.datepicker._get(b,"stepBigMonths"):-$.datepicker._get(b,"stepMonths"),"M");break;case 38:(a.ctrlKey||a.metaKey)&&$.datepicker._adjustDate(a.target,-7,"D"),c=a.ctrlKey||a.metaKey;break;case 39:(a.ctrlKey||a.metaKey)&&$.datepicker._adjustDate(a.target,d?-1:1,"D"),c=a.ctrlKey||a.metaKey,a.originalEvent.altKey&&$.datepicker._adjustDate(a.target,a.ctrlKey?+$.datepicker._get(b,"stepBigMonths"):+$.datepicker._get(b,"stepMonths"),"M");break;case 40:(a.ctrlKey||a.metaKey)&&$.datepicker._adjustDate(a.target,7,"D"),c=a.ctrlKey||a.metaKey;break;default:c=!1}else a.keyCode==36&&a.ctrlKey?$.datepicker._showDatepicker(this):c=!1;c&&(a.preventDefault(),a.stopPropagation())},_doKeyPress:function(a){var b=$.datepicker._getInst(a.target);if($.datepicker._get(b,"constrainInput")){var c=$.datepicker._possibleChars($.datepicker._get(b,"dateFormat")),d=String.fromCharCode(a.charCode==undefined?a.keyCode:a.charCode);return a.ctrlKey||a.metaKey||d<" "||!c||c.indexOf(d)>-1}},_doKeyUp:function(a){var b=$.datepicker._getInst(a.target);if(b.input.val()!=b.lastVal)try{var c=$.datepicker.parseDate($.datepicker._get(b,"dateFormat"),b.input?b.input.val():null,$.datepicker._getFormatConfig(b));c&&($.datepicker._setDateFromField(b),$.datepicker._updateAlternate(b),$.datepicker._updateDatepicker(b))}catch(a){$.datepicker.log(a)}return!0},_showDatepicker:function(a){a=a.target||a,a.nodeName.toLowerCase()!="input"&&(a=$("input",a.parentNode)[0]);if(!$.datepicker._isDisabledDatepicker(a)&&$.datepicker._lastInput!=a){var b=$.datepicker._getInst(a);$.datepicker._curInst&&$.datepicker._curInst!=b&&($.datepicker._curInst.dpDiv.stop(!0,!0),b&&$.datepicker._datepickerShowing&&$.datepicker._hideDatepicker($.datepicker._curInst.input[0]));var c=$.datepicker._get(b,"beforeShow"),d=c?c.apply(a,[a,b]):{};if(d===!1)return;extendRemove(b.settings,d),b.lastVal=null,$.datepicker._lastInput=a,$.datepicker._setDateFromField(b),$.datepicker._inDialog&&(a.value=""),$.datepicker._pos||($.datepicker._pos=$.datepicker._findPos(a),$.datepicker._pos[1]+=a.offsetHeight);var e=!1;$(a).parents().each(function(){e|=$(this).css("position")=="fixed";return!e}),e&&$.browser.opera&&($.datepicker._pos[0]-=document.documentElement.scrollLeft,$.datepicker._pos[1]-=document.documentElement.scrollTop);var f={left:$.datepicker._pos[0],top:$.datepicker._pos[1]};$.datepicker._pos=null,b.dpDiv.empty(),b.dpDiv.css({position:"absolute",display:"block",top:"-1000px"}),$.datepicker._updateDatepicker(b),f=$.datepicker._checkOffset(b,f,e),b.dpDiv.css({position:$.datepicker._inDialog&&$.blockUI?"static":e?"fixed":"absolute",display:"none",left:f.left+"px",top:f.top+"px"});if(!b.inline){var g=$.datepicker._get(b,"showAnim"),h=$.datepicker._get(b,"duration"),i=function(){var a=b.dpDiv.find("iframe.ui-datepicker-cover");if(!!a.length){var c=$.datepicker._getBorders(b.dpDiv);a.css({left:-c[0],top:-c[1],width:b.dpDiv.outerWidth(),height:b.dpDiv.outerHeight()})}};b.dpDiv.zIndex($(a).zIndex()+1),$.datepicker._datepickerShowing=!0,$.effects&&$.effects[g]?b.dpDiv.show(g,$.datepicker._get(b,"showOptions"),h,i):b.dpDiv[g||"show"](g?h:null,i),(!g||!h)&&i(),b.input.is(":visible")&&!b.input.is(":disabled")&&b.input.focus(),$.datepicker._curInst=b}}},_updateDatepicker:function(a){var b=this;b.maxRows=4;var c=$.datepicker._getBorders(a.dpDiv);instActive=a,a.dpDiv.empty().append(this._generateHTML(a));var d=a.dpDiv.find("iframe.ui-datepicker-cover");!d.length||d.css({left:-c[0],top:-c[1],width:a.dpDiv.outerWidth(),height:a.dpDiv.outerHeight()}),a.dpDiv.find("."+this._dayOverClass+" a").mouseover();var e=this._getNumberOfMonths(a),f=e[1],g=17;a.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""),f>1&&a.dpDiv.addClass("ui-datepicker-multi-"+f).css("width",g*f+"em"),a.dpDiv[(e[0]!=1||e[1]!=1?"add":"remove")+"Class"]("ui-datepicker-multi"),a.dpDiv[(this._get(a,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl"),a==$.datepicker._curInst&&$.datepicker._datepickerShowing&&a.input&&a.input.is(":visible")&&!a.input.is(":disabled")&&a.input[0]!=document.activeElement&&a.input.focus();if(a.yearshtml){var h=a.yearshtml;setTimeout(function(){h===a.yearshtml&&a.yearshtml&&a.dpDiv.find("select.ui-datepicker-year:first").replaceWith(a.yearshtml),h=a.yearshtml=null},0)}},_getBorders:function(a){var b=function(a){return{thin:1,medium:2,thick:3}[a]||a};return[parseFloat(b(a.css("border-left-width"))),parseFloat(b(a.css("border-top-width")))]},_checkOffset:function(a,b,c){var d=a.dpDiv.outerWidth(),e=a.dpDiv.outerHeight(),f=a.input?a.input.outerWidth():0,g=a.input?a.input.outerHeight():0,h=document.documentElement.clientWidth+$(document).scrollLeft(),i=document.documentElement.clientHeight+$(document).scrollTop();b.left-=this._get(a,"isRTL")?d-f:0,b.left-=c&&b.left==a.input.offset().left?$(document).scrollLeft():0,b.top-=c&&b.top==a.input.offset().top+g?$(document).scrollTop():0,b.left-=Math.min(b.left,b.left+d>h&&h>d?Math.abs(b.left+d-h):0),b.top-=Math.min(b.top,b.top+e>i&&i>e?Math.abs(e+g):0);return b},_findPos:function(a){var b=this._getInst(a),c=this._get(b,"isRTL");while(a&&(a.type=="hidden"||a.nodeType!=1||$.expr.filters.hidden(a)))a=a[c?"previousSibling":"nextSibling"];var d=$(a).offset();return[d.left,d.top]},_hideDatepicker:function(a){var b=this._curInst;if(!(!b||a&&b!=$.data(a,PROP_NAME))&&this._datepickerShowing){var c=this._get(b,"showAnim"),d=this._get(b,"duration"),e=this,f=function(){$.datepicker._tidyDialog(b),e._curInst=null};$.effects&&$.effects[c]?b.dpDiv.hide(c,$.datepicker._get(b,"showOptions"),d,f):b.dpDiv[c=="slideDown"?"slideUp":c=="fadeIn"?"fadeOut":"hide"](c?d:null,f),c||f(),this._datepickerShowing=!1;var g=this._get(b,"onClose");g&&g.apply(b.input?b.input[0]:null,[b.input?b.input.val():"",b]),this._lastInput=null,this._inDialog&&(this._dialogInput.css({position:"absolute",left:"0",top:"-100px"}),$.blockUI&&($.unblockUI(),$("body").append(this.dpDiv))),this._inDialog=!1}},_tidyDialog:function(a){a.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar")},_checkExternalClick:function(a){if(!!$.datepicker._curInst){var b=$(a.target),c=$.datepicker._getInst(b[0]);(b[0].id!=$.datepicker._mainDivId&&b.parents("#"+$.datepicker._mainDivId).length==0&&!b.hasClass($.datepicker.markerClassName)&&!b.closest("."+$.datepicker._triggerClass).length&&$.datepicker._datepickerShowing&&(!$.datepicker._inDialog||!$.blockUI)||b.hasClass($.datepicker.markerClassName)&&$.datepicker._curInst!=c)&&$.datepicker._hideDatepicker()}},_adjustDate:function(a,b,c){var d=$(a),e=this._getInst(d[0]);this._isDisabledDatepicker(d[0])||(this._adjustInstDate(e,b+(c=="M"?this._get(e,"showCurrentAtPos"):0),c),this._updateDatepicker(e))},_gotoToday:function(a){var b=$(a),c=this._getInst(b[0]);if(this._get(c,"gotoCurrent")&&c.currentDay)c.selectedDay=c.currentDay,c.drawMonth=c.selectedMonth=c.currentMonth,c.drawYear=c.selectedYear=c.currentYear;else{var d=new Date;c.selectedDay=d.getDate(),c.drawMonth=c.selectedMonth=d.getMonth(),c.drawYear=c.selectedYear=d.getFullYear()}this._notifyChange(c),this._adjustDate(b)},_selectMonthYear:function(a,b,c){var d=$(a),e=this._getInst(d[0]);e["selected"+(c=="M"?"Month":"Year")]=e["draw"+(c=="M"?"Month":"Year")]=parseInt(b.options[b.selectedIndex].value,10),this._notifyChange(e),this._adjustDate(d)},_selectDay:function(a,b,c,d){var e=$(a);if(!$(d).hasClass(this._unselectableClass)&&!this._isDisabledDatepicker(e[0])){var f=this._getInst(e[0]);f.selectedDay=f.currentDay=$("a",d).html(),f.selectedMonth=f.currentMonth=b,f.selectedYear=f.currentYear=c,this._selectDate(a,this._formatDate(f,f.currentDay,f.currentMonth,f.currentYear))}},_clearDate:function(a){var b=$(a),c=this._getInst(b[0]);this._selectDate(b,"")},_selectDate:function(a,b){var c=$(a),d=this._getInst(c[0]);b=b!=null?b:this._formatDate(d),d.input&&d.input.val(b),this._updateAlternate(d);var e=this._get(d,"onSelect");e?e.apply(d.input?d.input[0]:null,[b,d]):d.input&&d.input.trigger("change"),d.inline?this._updateDatepicker(d):(this._hideDatepicker(),this._lastInput=d.input[0],typeof d.input[0]!="object"&&d.input.focus(),this._lastInput=null)},_updateAlternate:function(a){var b=this._get(a,"altField");if(b){var c=this._get(a,"altFormat")||this._get(a,"dateFormat"),d=this._getDate(a),e=this.formatDate(c,d,this._getFormatConfig(a));$(b).each(function(){$(this).val(e)})}},noWeekends:function(a){var b=a.getDay();return[b>0&&b<6,""]},iso8601Week:function(a){var b=new Date(a.getTime());b.setDate(b.getDate()+4-(b.getDay()||7));var c=b.getTime();b.setMonth(0),b.setDate(1);return Math.floor(Math.round((c-b)/864e5)/7)+1},parseDate:function(a,b,c){if(a==null||b==null)throw"Invalid arguments";b=typeof b=="object"?b.toString():b+"";if(b=="")return null;var d=(c?c.shortYearCutoff:null)||this._defaults.shortYearCutoff;d=typeof d!="string"?d:(new Date).getFullYear()%100+parseInt(d,10);var e=(c?c.dayNamesShort:null)||this._defaults.dayNamesShort,f=(c?c.dayNames:null)||this._defaults.dayNames,g=(c?c.monthNamesShort:null)||this._defaults.monthNamesShort,h=(c?c.monthNames:null)||this._defaults.monthNames,i=-1,j=-1,k=-1,l=-1,m=!1,n=function(b){var c=s+1<a.length&&a.charAt(s+1)==b;c&&s++;return c},o=function(a){var c=n(a),d=a=="@"?14:a=="!"?20:a=="y"&&c?4:a=="o"?3:2,e=new RegExp("^\\d{1,"+d+"}"),f=b.substring(r).match(e);if(!f)throw"Missing number at position "+r;r+=f[0].length;return parseInt(f[0],10)},p=function(a,c,d){var e=$.map(n(a)?d:c,function(a,b){return[[b,a]]}).sort(function(a,b){return-(a[1].length-b[1].length)}),f=-1;$.each(e,function(a,c){var d=c[1];if(b.substr(r,d.length).toLowerCase()==d.toLowerCase()){f=c[0],r+=d.length;return!1}});if(f!=-1)return f+1;throw"Unknown name at position "+r},q=function(){if(b.charAt(r)!=a.charAt(s))throw"Unexpected literal at position "+r;r++},r=0;for(var s=0;s<a.length;s++)if(m)a.charAt(s)=="'"&&!n("'")?m=!1:q();else switch(a.charAt(s)){case"d":k=o("d");break;case"D":p("D",e,f);break;case"o":l=o("o");break;case"m":j=o("m");break;case"M":j=p("M",g,h);break;case"y":i=o("y");break;case"@":var t=new Date(o("@"));i=t.getFullYear(),j=t.getMonth()+1,k=t.getDate();break;case"!":var t=new Date((o("!")-this._ticksTo1970)/1e4);i=t.getFullYear(),j=t.getMonth()+1,k=t.getDate();break;case"'":n("'")?q():m=!0;break;default:q()}if(r<b.length)throw"Extra/unparsed characters found in date: "+b.substring(r);i==-1?i=(new Date).getFullYear():i<100&&(i+=(new Date).getFullYear()-(new Date).getFullYear()%100+(i<=d?0:-100));if(l>-1){j=1,k=l;for(;;){var u=this._getDaysInMonth(i,j-1);if(k<=u)break;j++,k-=u}}var t=this._daylightSavingAdjust(new Date(i,j-1,k));if(t.getFullYear()!=i||t.getMonth()+1!=j||t.getDate()!=k)throw"Invalid date";return t},ATOM:"yy-mm-dd",COOKIE:"D, dd M yy",ISO_8601:"yy-mm-dd",RFC_822:"D, d M y",RFC_850:"DD, dd-M-y",RFC_1036:"D, d M y",RFC_1123:"D, d M yy",RFC_2822:"D, d M yy",RSS:"D, d M y",TICKS:"!",TIMESTAMP:"@",W3C:"yy-mm-dd",_ticksTo1970:(718685+Math.floor(492.5)-Math.floor(19.7)+Math.floor(4.925))*24*60*60*1e7,formatDate:function(a,b,c){if(!b)return"";var d=(c?c.dayNamesShort:null)||this._defaults.dayNamesShort,e=(c?c.dayNames:null)||this._defaults.dayNames,f=(c?c.monthNamesShort:null)||this._defaults.monthNamesShort,g=(c?c.monthNames:null)||this._defaults.monthNames,h=function(b){var c=m+1<a.length&&a.charAt(m+1)==b;c&&m++;return c},i=function(a,b,c){var d=""+b;if(h(a))while(d.length<c)d="0"+d;return d},j=function(a,b,c,d){return h(a)?d[b]:c[b]},k="",l=!1;if(b)for(var m=0;m<a.length;m++)if(l)a.charAt(m)=="'"&&!h("'")?l=!1:k+=a.charAt(m);else switch(a.charAt(m)){case"d":k+=i("d",b.getDate(),2);break;case"D":k+=j("D",b.getDay(),d,e);break;case"o":k+=i("o",Math.round(((new Date(b.getFullYear(),b.getMonth(),b.getDate())).getTime()-(new Date(b.getFullYear(),0,0)).getTime())/864e5),3);break;case"m":k+=i("m",b.getMonth()+1,2);break;case"M":k+=j("M",b.getMonth(),f,g);break;case"y":k+=h("y")?b.getFullYear():(b.getYear()%100<10?"0":"")+b.getYear()%100;break;case"@":k+=b.getTime();break;case"!":k+=b.getTime()*1e4+this._ticksTo1970;break;case"'":h("'")?k+="'":l=!0;break;default:k+=a.charAt(m)}return k},_possibleChars:function(a){var b="",c=!1,d=function(b){var c=e+1<a.length&&a.charAt(e+1)==b;c&&e++;return c};for(var e=0;e<a.length;e++)if(c)a.charAt(e)=="'"&&!d("'")?c=!1:b+=a.charAt(e);else switch(a.charAt(e)){case"d":case"m":case"y":case"@":b+="0123456789";break;case"D":case"M":return null;case"'":d("'")?b+="'":c=!0;break;default:b+=a.charAt(e)}return b},_get:function(a,b){return a.settings[b]!==undefined?a.settings[b]:this._defaults[b]},_setDateFromField:function(a,b){if(a.input.val()!=a.lastVal){var c=this._get(a,"dateFormat"),d=a.lastVal=a.input?a.input.val():null,e,f;e=f=this._getDefaultDate(a);var g=this._getFormatConfig(a);try{e=this.parseDate(c,d,g)||f}catch(h){this.log(h),d=b?"":d}a.selectedDay=e.getDate(),a.drawMonth=a.selectedMonth=e.getMonth(),a.drawYear=a.selectedYear=e.getFullYear(),a.currentDay=d?e.getDate():0,a.currentMonth=d?e.getMonth():0,a.currentYear=d?e.getFullYear():0,this._adjustInstDate(a)}},_getDefaultDate:function(a){return this._restrictMinMax(a,this._determineDate(a,this._get(a,"defaultDate"),new Date))},_determineDate:function(a,b,c){var d=function(a){var b=new Date;b.setDate(b.getDate()+a);return b},e=function(b){try{return $.datepicker.parseDate($.datepicker._get(a,"dateFormat"),b,$.datepicker._getFormatConfig(a))}catch(c){}var d=(b.toLowerCase().match(/^c/)?$.datepicker._getDate(a):null)||new Date,e=d.getFullYear(),f=d.getMonth(),g=d.getDate(),h=/([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,i=h.exec(b);while(i){switch(i[2]||"d"){case"d":case"D":g+=parseInt(i[1],10);break;case"w":case"W":g+=parseInt(i[1],10)*7;break;case"m":case"M":f+=parseInt(i[1],10),g=Math.min(g,$.datepicker._getDaysInMonth(e,f));break;case"y":case"Y":e+=parseInt(i[1],10),g=Math.min(g,$.datepicker._getDaysInMonth(e,f))}i=h.exec(b)}return new Date(e,f,g)},f=b==null||b===""?c:typeof b=="string"?e(b):typeof b=="number"?isNaN(b)?c:d(b):new Date(b.getTime());f=f&&f.toString()=="Invalid Date"?c:f,f&&(f.setHours(0),f.setMinutes(0),f.setSeconds(0),f.setMilliseconds(0));return this._daylightSavingAdjust(f)},_daylightSavingAdjust:function(a){if(!a)return null;a.setHours(a.getHours()>12?a.getHours()+2:0);return a},_setDate:function(a,b,c){var d=!b,e=a.selectedMonth,f=a.selectedYear,g=this._restrictMinMax(a,this._determineDate(a,b,new Date));a.selectedDay=a.currentDay=g.getDate(),a.drawMonth=a.selectedMonth=a.currentMonth=g.getMonth(),a.drawYear=a.selectedYear=a.currentYear=g.getFullYear(),(e!=a.selectedMonth||f!=a.selectedYear)&&!c&&this._notifyChange(a),this._adjustInstDate(a),a.input&&a.input.val(d?"":this._formatDate(a))},_getDate:function(a){var b=!a.currentYear||a.input&&a.input.val()==""?null:this._daylightSavingAdjust(new Date(a.currentYear,a.currentMonth,a.currentDay));return b},_generateHTML:function(a){var b=new Date;b=this._daylightSavingAdjust(new Date(b.getFullYear(),b.getMonth(),b.getDate()));var c=this._get(a,"isRTL"),d=this._get(a,"showButtonPanel"),e=this._get(a,"hideIfNoPrevNext"),f=this._get(a,"navigationAsDateFormat"),g=this._getNumberOfMonths(a),h=this._get(a,"showCurrentAtPos"),i=this._get(a,"stepMonths"),j=g[0]!=1||g[1]!=1,k=this._daylightSavingAdjust(a.currentDay?new Date(a.currentYear,a.currentMonth,a.currentDay):new Date(9999,9,9)),l=this._getMinMaxDate(a,"min"),m=this._getMinMaxDate(a,"max"),n=a.drawMonth-h,o=a.drawYear;n<0&&(n+=12,o--);if(m){var p=this._daylightSavingAdjust(new Date(m.getFullYear(),m.getMonth()-g[0]*g[1]+1,m.getDate()));p=l&&p<l?l:p;while(this._daylightSavingAdjust(new Date(o,n,1))>p)n--,n<0&&(n=11,o--)}a.drawMonth=n,a.drawYear=o;var q=this._get(a,"prevText");q=f?this.formatDate(q,this._daylightSavingAdjust(new Date(o,n-i,1)),this._getFormatConfig(a)):q;var r=this._canAdjustMonth(a,-1,o,n)?'<a class="ui-datepicker-prev ui-corner-all" onclick="DP_jQuery_'+dpuuid+".datepicker._adjustDate('#"+a.id+"', -"+i+", 'M');\""+' title="'+q+'"><span class="ui-icon ui-icon-circle-triangle-'+(c?"e":"w")+'">'+q+"</span></a>":e?"":'<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="'+q+'"><span class="ui-icon ui-icon-circle-triangle-'+(c?"e":"w")+'">'+q+"</span></a>",s=this._get(a,"nextText");s=f?this.formatDate(s,this._daylightSavingAdjust(new Date(o,n+i,1)),this._getFormatConfig(a)):s;var t=this._canAdjustMonth(a,1,o,n)?'<a class="ui-datepicker-next ui-corner-all" onclick="DP_jQuery_'+dpuuid+".datepicker._adjustDate('#"+a.id+"', +"+i+", 'M');\""+' title="'+s+'"><span class="ui-icon ui-icon-circle-triangle-'+(c?"w":"e")+'">'+s+"</span></a>":e?"":'<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="'+s+'"><span class="ui-icon ui-icon-circle-triangle-'+(c?"w":"e")+'">'+s+"</span></a>",u=this._get(a,"currentText"),v=this._get(a,"gotoCurrent")&&a.currentDay?k:b;u=f?this.formatDate(u,v,this._getFormatConfig(a)):u;var w=a.inline?"":'<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" onclick="DP_jQuery_'+dpuuid+'.datepicker._hideDatepicker();">'+this._get(a,"closeText")+"</button>",x=d?'<div class="ui-datepicker-buttonpane ui-widget-content">'+(c?w:"")+(this._isInRange(a,v)?'<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" onclick="DP_jQuery_'+dpuuid+".datepicker._gotoToday('#"+a.id+"');\""+">"+u+"</button>":"")+(c?"":w)+"</div>":"",y=parseInt(this._get(a,"firstDay"),10);y=isNaN(y)?0:y;var z=this._get(a,"showWeek"),A=this._get(a,"dayNames"),B=this._get(a,"dayNamesShort"),C=this._get(a,"dayNamesMin"),D=this._get(a,"monthNames"),E=this._get(a,"monthNamesShort"),F=this._get(a,"beforeShowDay"),G=this._get(a,"showOtherMonths"),H=this._get(a,"selectOtherMonths"),I=this._get(a,"calculateWeek")||this.iso8601Week,J=this._getDefaultDate(a),K="";for(var L=0;L<g[0];L++){var M="";this.maxRows=4;for(var N=0;N<g[1];N++){var O=this._daylightSavingAdjust(new Date(o,n,a.selectedDay)),P=" ui-corner-all",Q="";if(j){Q+='<div class="ui-datepicker-group';if(g[1]>1)switch(N){case 0:Q+=" ui-datepicker-group-first",P=" ui-corner-"+(c?"right":"left");break;case g[1]-1:Q+=" ui-datepicker-group-last",P=" ui-corner-"+(c?"left":"right");break;default:Q+=" ui-datepicker-group-middle",P=""}Q+='">'}Q+='<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix'+P+'">'+(/all|left/.test(P)&&L==0?c?t:r:"")+(/all|right/.test(P)&&L==0?c?r:t:"")+this._generateMonthYearHeader(a,n,o,l,m,L>0||N>0,D,E)+'</div><table class="ui-datepicker-calendar"><thead>'+"<tr>";var R=z?'<th class="ui-datepicker-week-col">'+this._get(a,"weekHeader")+"</th>":"";for(var S=0;S<7;S++){var T=(S+y)%7;R+="<th"+((S+y+6)%7>=5?' class="ui-datepicker-week-end"':"")+">"+'<span title="'+A[T]+'">'+C[T]+"</span></th>"}Q+=R+"</tr></thead><tbody>";var U=this._getDaysInMonth(o,n);o==a.selectedYear&&n==a.selectedMonth&&(a.selectedDay=Math.min(a.selectedDay,U));var V=(this._getFirstDayOfMonth(o,n)-y+7)%7,W=Math.ceil((V+U)/7),X=j?this.maxRows>W?this.maxRows:W:W;this.maxRows=X;var Y=this._daylightSavingAdjust(new Date(o,n,1-V));for(var Z=0;Z<X;Z++){Q+="<tr>";var _=z?'<td class="ui-datepicker-week-col">'+this._get(a,"calculateWeek")(Y)+"</td>":"";for(var S=0;S<7;S++){var ba=F?F.apply(a.input?a.input[0]:null,[Y]):[!0,""],bb=Y.getMonth()!=n,bc=bb&&!H||!ba[0]||l&&Y<l||m&&Y>m;_+='<td class="'+((S+y+6)%7>=5?" ui-datepicker-week-end":"")+(bb?" ui-datepicker-other-month":"")+(Y.getTime()==O.getTime()&&n==a.selectedMonth&&a._keyEvent||J.getTime()==Y.getTime()&&J.getTime()==O.getTime()?" "+this._dayOverClass:"")+(bc?" "+this._unselectableClass+" ui-state-disabled":"")+(bb&&!G?"":" "+ba[1]+(Y.getTime()==k.getTime()?" "+this._currentClass:"")+(Y.getTime()==b.getTime()?" ui-datepicker-today":""))+'"'+((!bb||G)&&ba[2]?' title="'+ba[2]+'"':"")+(bc?"":' onclick="DP_jQuery_'+dpuuid+".datepicker._selectDay('#"+a.id+"',"+Y.getMonth()+","+Y.getFullYear()+', this);return false;"')+">"+(bb&&!G?"&#xa0;":bc?'<span class="ui-state-default">'+Y.getDate()+"</span>":'<a class="ui-state-default'+(Y.getTime()==b.getTime()?" ui-state-highlight":"")+(Y.getTime()==k.getTime()?" ui-state-active":"")+(bb?" ui-priority-secondary":"")+'" href="#">'+Y.getDate()+"</a>")+"</td>",Y.setDate(Y.getDate()+1),Y=this._daylightSavingAdjust(Y)}Q+=_+"</tr>"}n++,n>11&&(n=0,o++),Q+="</tbody></table>"+(j?"</div>"+(g[0]>0&&N==g[1]-1?'<div class="ui-datepicker-row-break"></div>':""):""),M+=Q}K+=M}K+=x+($.browser.msie&&parseInt($.browser.version,10)<7&&!a.inline?'<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>':""),a._keyEvent=!1;return K},_generateMonthYearHeader:function(a,b,c,d,e,f,g,h){var i=this._get(a,"changeMonth"),j=this._get(a,"changeYear"),k=this._get(a,"showMonthAfterYear"),l='<div class="ui-datepicker-title">',m="";if(f||!i)m+='<span class="ui-datepicker-month">'+g[b]+"</span>";else{var n=d&&d.getFullYear()==c,o=e&&e.getFullYear()==c;m+='<select class="ui-datepicker-month" onchange="DP_jQuery_'+dpuuid+".datepicker._selectMonthYear('#"+a.id+"', this, 'M');\" "+">";for(var p=0;p<12;p++)(!n||p>=d.getMonth())&&(!o||p<=e.getMonth())&&(m+='<option value="'+p+'"'+(p==b?' selected="selected"':"")+">"+h[p]+"</option>");m+="</select>"}k||(l+=m+(f||!i||!j?"&#xa0;":""));if(!a.yearshtml){a.yearshtml="";if(f||!j)l+='<span class="ui-datepicker-year">'+c+"</span>";else{var q=this._get(a,"yearRange").split(":"),r=(new Date).getFullYear(),s=function(a){var b=a.match(/c[+-].*/)?c+parseInt(a.substring(1),10):a.match(/[+-].*/)?r+parseInt(a,10):parseInt(a,10);return isNaN(b)?r:b},t=s(q[0]),u=Math.max(t,s(q[1]||""));t=d?Math.max(t,d.getFullYear()):t,u=e?Math.min(u,e.getFullYear()):u,a.yearshtml+='<select class="ui-datepicker-year" onchange="DP_jQuery_'+dpuuid+".datepicker._selectMonthYear('#"+a.id+"', this, 'Y');\" "+">";for(;t<=u;t++)a.yearshtml+='<option value="'+t+'"'+(t==c?' selected="selected"':"")+">"+t+"</option>";a.yearshtml+="</select>",l+=a.yearshtml,a.yearshtml=null}}l+=this._get(a,"yearSuffix"),k&&(l+=(f||!i||!j?"&#xa0;":"")+m),l+="</div>";return l},_adjustInstDate:function(a,b,c){var d=a.drawYear+(c=="Y"?b:0),e=a.drawMonth+(c=="M"?b:0),f=Math.min(a.selectedDay,this._getDaysInMonth(d,e))+(c=="D"?b:0),g=this._restrictMinMax(a,this._daylightSavingAdjust(new Date(d,e,f)));a.selectedDay=g.getDate(),a.drawMonth=a.selectedMonth=g.getMonth(),a.drawYear=a.selectedYear=g.getFullYear(),(c=="M"||c=="Y")&&this._notifyChange(a)},_restrictMinMax:function(a,b){var c=this._getMinMaxDate(a,"min"),d=this._getMinMaxDate(a,"max"),e=c&&b<c?c:b;e=d&&e>d?d:e;return e},_notifyChange:function(a){var b=this._get(a,"onChangeMonthYear");b&&b.apply(a.input?a.input[0]:null,[a.selectedYear,a.selectedMonth+1,a])},_getNumberOfMonths:function(a){var b=this._get(a,"numberOfMonths");return b==null?[1,1]:typeof b=="number"?[1,b]:b},_getMinMaxDate:function(a,b){return this._determineDate(a,this._get(a,b+"Date"),null)},_getDaysInMonth:function(a,b){return 32-this._daylightSavingAdjust(new Date(a,b,32)).getDate()},_getFirstDayOfMonth:function(a,b){return(new Date(a,b,1)).getDay()},_canAdjustMonth:function(a,b,c,d){var e=this._getNumberOfMonths(a),f=this._daylightSavingAdjust(new Date(c,d+(b<0?b:e[0]*e[1]),1));b<0&&f.setDate(this._getDaysInMonth(f.getFullYear(),f.getMonth()));return this._isInRange(a,f)},_isInRange:function(a,b){var c=this._getMinMaxDate(a,"min"),d=this._getMinMaxDate(a,"max");return(!c||b.getTime()>=c.getTime())&&(!d||b.getTime()<=d.getTime())},_getFormatConfig:function(a){var b=this._get(a,"shortYearCutoff");b=typeof b!="string"?b:(new Date).getFullYear()%100+parseInt(b,10);return{shortYearCutoff:b,dayNamesShort:this._get(a,"dayNamesShort"),dayNames:this._get(a,"dayNames"),monthNamesShort:this._get(a,"monthNamesShort"),monthNames:this._get(a,"monthNames")}},_formatDate:function(a,b,c,d){b||(a.currentDay=a.selectedDay,a.currentMonth=a.selectedMonth,a.currentYear=a.selectedYear);var e=b?typeof b=="object"?b:this._daylightSavingAdjust(new Date(d,c,b)):this._daylightSavingAdjust(new Date(a.currentYear,a.currentMonth,a.currentDay));return this.formatDate(this._get(a,"dateFormat"),e,this._getFormatConfig(a))}}),$.fn.datepicker=function(a){if(!this.length)return this;$.datepicker.initialized||($(document).mousedown($.datepicker._checkExternalClick).find("body").append($.datepicker.dpDiv),$.datepicker.initialized=!0);var b=Array.prototype.slice.call(arguments,1);if(typeof a=="string"&&(a=="isDisabled"||a=="getDate"||a=="widget"
+))return $.datepicker["_"+a+"Datepicker"].apply($.datepicker,[this[0]].concat(b));if(a=="option"&&arguments.length==2&&typeof arguments[1]=="string")return $.datepicker["_"+a+"Datepicker"].apply($.datepicker,[this[0]].concat(b));return this.each(function(){typeof a=="string"?$.datepicker["_"+a+"Datepicker"].apply($.datepicker,[this].concat(b)):$.datepicker._attachDatepicker(this,a)})},$.datepicker=new Datepicker,$.datepicker.initialized=!1,$.datepicker.uuid=(new Date).getTime(),$.datepicker.version="1.8.18",window["DP_jQuery_"+dpuuid]=$}(jQuery),function(a,b){var c="ui-dialog ui-widget ui-widget-content ui-corner-all ",d={buttons:!0,height:!0,maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0,width:!0},e={maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0},f=a.attrFn||{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0,click:!0};a.widget("ui.dialog",{options:{autoOpen:!0,buttons:{},closeOnEscape:!0,closeText:"close",dialogClass:"",draggable:!0,hide:null,height:"auto",maxHeight:!1,maxWidth:!1,minHeight:150,minWidth:150,modal:!1,position:{my:"center",at:"center",collision:"fit",using:function(b){var c=a(this).css(b).offset().top;c<0&&a(this).css("top",b.top-c)}},resizable:!0,show:null,stack:!0,title:"",width:300,zIndex:1e3},_create:function(){this.originalTitle=this.element.attr("title"),typeof this.originalTitle!="string"&&(this.originalTitle=""),this.options.title=this.options.title||this.originalTitle;var b=this,d=b.options,e=d.title||"&#160;",f=a.ui.dialog.getTitleId(b.element),g=(b.uiDialog=a("<div></div>")).appendTo(document.body).hide().addClass(c+d.dialogClass).css({zIndex:d.zIndex}).attr("tabIndex",-1).css("outline",0).keydown(function(c){d.closeOnEscape&&!c.isDefaultPrevented()&&c.keyCode&&c.keyCode===a.ui.keyCode.ESCAPE&&(b.close(c),c.preventDefault())}).attr({role:"dialog","aria-labelledby":f}).mousedown(function(a){b.moveToTop(!1,a)}),h=b.element.show().removeAttr("title").addClass("ui-dialog-content ui-widget-content").appendTo(g),i=(b.uiDialogTitlebar=a("<div></div>")).addClass("ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix").prependTo(g),j=a('<a href="#"></a>').addClass("ui-dialog-titlebar-close ui-corner-all").attr("role","button").hover(function(){j.addClass("ui-state-hover")},function(){j.removeClass("ui-state-hover")}).focus(function(){j.addClass("ui-state-focus")}).blur(function(){j.removeClass("ui-state-focus")}).click(function(a){b.close(a);return!1}).appendTo(i),k=(b.uiDialogTitlebarCloseText=a("<span></span>")).addClass("ui-icon ui-icon-closethick").text(d.closeText).appendTo(j),l=a("<span></span>").addClass("ui-dialog-title").attr("id",f).html(e).prependTo(i);a.isFunction(d.beforeclose)&&!a.isFunction(d.beforeClose)&&(d.beforeClose=d.beforeclose),i.find("*").add(i).disableSelection(),d.draggable&&a.fn.draggable&&b._makeDraggable(),d.resizable&&a.fn.resizable&&b._makeResizable(),b._createButtons(d.buttons),b._isOpen=!1,a.fn.bgiframe&&g.bgiframe()},_init:function(){this.options.autoOpen&&this.open()},destroy:function(){var a=this;a.overlay&&a.overlay.destroy(),a.uiDialog.hide(),a.element.unbind(".dialog").removeData("dialog").removeClass("ui-dialog-content ui-widget-content").hide().appendTo("body"),a.uiDialog.remove(),a.originalTitle&&a.element.attr("title",a.originalTitle);return a},widget:function(){return this.uiDialog},close:function(b){var c=this,d,e;if(!1!==c._trigger("beforeClose",b)){c.overlay&&c.overlay.destroy(),c.uiDialog.unbind("keypress.ui-dialog"),c._isOpen=!1,c.options.hide?c.uiDialog.hide(c.options.hide,function(){c._trigger("close",b)}):(c.uiDialog.hide(),c._trigger("close",b)),a.ui.dialog.overlay.resize(),c.options.modal&&(d=0,a(".ui-dialog").each(function(){this!==c.uiDialog[0]&&(e=a(this).css("z-index"),isNaN(e)||(d=Math.max(d,e)))}),a.ui.dialog.maxZ=d);return c}},isOpen:function(){return this._isOpen},moveToTop:function(b,c){var d=this,e=d.options,f;if(e.modal&&!b||!e.stack&&!e.modal)return d._trigger("focus",c);e.zIndex>a.ui.dialog.maxZ&&(a.ui.dialog.maxZ=e.zIndex),d.overlay&&(a.ui.dialog.maxZ+=1,d.overlay.$el.css("z-index",a.ui.dialog.overlay.maxZ=a.ui.dialog.maxZ)),f={scrollTop:d.element.scrollTop(),scrollLeft:d.element.scrollLeft()},a.ui.dialog.maxZ+=1,d.uiDialog.css("z-index",a.ui.dialog.maxZ),d.element.attr(f),d._trigger("focus",c);return d},open:function(){if(!this._isOpen){var b=this,c=b.options,d=b.uiDialog;b.overlay=c.modal?new a.ui.dialog.overlay(b):null,b._size(),b._position(c.position),d.show(c.show),b.moveToTop(!0),c.modal&&d.bind("keydown.ui-dialog",function(b){if(b.keyCode===a.ui.keyCode.TAB){var c=a(":tabbable",this),d=c.filter(":first"),e=c.filter(":last");if(b.target===e[0]&&!b.shiftKey){d.focus(1);return!1}if(b.target===d[0]&&b.shiftKey){e.focus(1);return!1}}}),a(b.element.find(":tabbable").get().concat(d.find(".ui-dialog-buttonpane :tabbable").get().concat(d.get()))).eq(0).focus(),b._isOpen=!0,b._trigger("open");return b}},_createButtons:function(b){var c=this,d=!1,e=a("<div></div>").addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix"),g=a("<div></div>").addClass("ui-dialog-buttonset").appendTo(e);c.uiDialog.find(".ui-dialog-buttonpane").remove(),typeof b=="object"&&b!==null&&a.each(b,function(){return!(d=!0)}),d&&(a.each(b,function(b,d){d=a.isFunction(d)?{click:d,text:b}:d;var e=a('<button type="button"></button>').click(function(){d.click.apply(c.element[0],arguments)}).appendTo(g);a.each(d,function(a,b){a!=="click"&&(a in f?e[a](b):e.attr(a,b))}),a.fn.button&&e.button()}),e.appendTo(c.uiDialog))},_makeDraggable:function(){function f(a){return{position:a.position,offset:a.offset}}var b=this,c=b.options,d=a(document),e;b.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",handle:".ui-dialog-titlebar",containment:"document",start:function(d,g){e=c.height==="auto"?"auto":a(this).height(),a(this).height(a(this).height()).addClass("ui-dialog-dragging"),b._trigger("dragStart",d,f(g))},drag:function(a,c){b._trigger("drag",a,f(c))},stop:function(g,h){c.position=[h.position.left-d.scrollLeft(),h.position.top-d.scrollTop()],a(this).removeClass("ui-dialog-dragging").height(e),b._trigger("dragStop",g,f(h)),a.ui.dialog.overlay.resize()}})},_makeResizable:function(c){function h(a){return{originalPosition:a.originalPosition,originalSize:a.originalSize,position:a.position,size:a.size}}c=c===b?this.options.resizable:c;var d=this,e=d.options,f=d.uiDialog.css("position"),g=typeof c=="string"?c:"n,e,s,w,se,sw,ne,nw";d.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:d.element,maxWidth:e.maxWidth,maxHeight:e.maxHeight,minWidth:e.minWidth,minHeight:d._minHeight(),handles:g,start:function(b,c){a(this).addClass("ui-dialog-resizing"),d._trigger("resizeStart",b,h(c))},resize:function(a,b){d._trigger("resize",a,h(b))},stop:function(b,c){a(this).removeClass("ui-dialog-resizing"),e.height=a(this).height(),e.width=a(this).width(),d._trigger("resizeStop",b,h(c)),a.ui.dialog.overlay.resize()}}).css("position",f).find(".ui-resizable-se").addClass("ui-icon ui-icon-grip-diagonal-se")},_minHeight:function(){var a=this.options;return a.height==="auto"?a.minHeight:Math.min(a.minHeight,a.height)},_position:function(b){var c=[],d=[0,0],e;if(b){if(typeof b=="string"||typeof b=="object"&&"0"in b)c=b.split?b.split(" "):[b[0],b[1]],c.length===1&&(c[1]=c[0]),a.each(["left","top"],function(a,b){+c[a]===c[a]&&(d[a]=c[a],c[a]=b)}),b={my:c.join(" "),at:c.join(" "),offset:d.join(" ")};b=a.extend({},a.ui.dialog.prototype.options.position,b)}else b=a.ui.dialog.prototype.options.position;e=this.uiDialog.is(":visible"),e||this.uiDialog.show(),this.uiDialog.css({top:0,left:0}).position(a.extend({of:window},b)),e||this.uiDialog.hide()},_setOptions:function(b){var c=this,f={},g=!1;a.each(b,function(a,b){c._setOption(a,b),a in d&&(g=!0),a in e&&(f[a]=b)}),g&&this._size(),this.uiDialog.is(":data(resizable)")&&this.uiDialog.resizable("option",f)},_setOption:function(b,d){var e=this,f=e.uiDialog;switch(b){case"beforeclose":b="beforeClose";break;case"buttons":e._createButtons(d);break;case"closeText":e.uiDialogTitlebarCloseText.text(""+d);break;case"dialogClass":f.removeClass(e.options.dialogClass).addClass(c+d);break;case"disabled":d?f.addClass("ui-dialog-disabled"):f.removeClass("ui-dialog-disabled");break;case"draggable":var g=f.is(":data(draggable)");g&&!d&&f.draggable("destroy"),!g&&d&&e._makeDraggable();break;case"position":e._position(d);break;case"resizable":var h=f.is(":data(resizable)");h&&!d&&f.resizable("destroy"),h&&typeof d=="string"&&f.resizable("option","handles",d),!h&&d!==!1&&e._makeResizable(d);break;case"title":a(".ui-dialog-title",e.uiDialogTitlebar).html(""+(d||"&#160;"))}a.Widget.prototype._setOption.apply(e,arguments)},_size:function(){var b=this.options,c,d,e=this.uiDialog.is(":visible");this.element.show().css({width:"auto",minHeight:0,height:0}),b.minWidth>b.width&&(b.width=b.minWidth),c=this.uiDialog.css({height:"auto",width:b.width}).height(),d=Math.max(0,b.minHeight-c);if(b.height==="auto")if(a.support.minHeight)this.element.css({minHeight:d,height:"auto"});else{this.uiDialog.show();var f=this.element.css("height","auto").height();e||this.uiDialog.hide(),this.element.height(Math.max(f,d))}else this.element.height(Math.max(b.height-c,0));this.uiDialog.is(":data(resizable)")&&this.uiDialog.resizable("option","minHeight",this._minHeight())}}),a.extend(a.ui.dialog,{version:"1.8.18",uuid:0,maxZ:0,getTitleId:function(a){var b=a.attr("id");b||(this.uuid+=1,b=this.uuid);return"ui-dialog-title-"+b},overlay:function(b){this.$el=a.ui.dialog.overlay.create(b)}}),a.extend(a.ui.dialog.overlay,{instances:[],oldInstances:[],maxZ:0,events:a.map("focus,mousedown,mouseup,keydown,keypress,click".split(","),function(a){return a+".dialog-overlay"}).join(" "),create:function(b){this.instances.length===0&&(setTimeout(function(){a.ui.dialog.overlay.instances.length&&a(document).bind(a.ui.dialog.overlay.events,function(b){if(a(b.target).zIndex()<a.ui.dialog.overlay.maxZ)return!1})},1),a(document).bind("keydown.dialog-overlay",function(c){b.options.closeOnEscape&&!c.isDefaultPrevented()&&c.keyCode&&c.keyCode===a.ui.keyCode.ESCAPE&&(b.close(c),c.preventDefault())}),a(window).bind("resize.dialog-overlay",a.ui.dialog.overlay.resize));var c=(this.oldInstances.pop()||a("<div></div>").addClass("ui-widget-overlay")).appendTo(document.body).css({width:this.width(),height:this.height()});a.fn.bgiframe&&c.bgiframe(),this.instances.push(c);return c},destroy:function(b){var c=a.inArray(b,this.instances);c!=-1&&this.oldInstances.push(this.instances.splice(c,1)[0]),this.instances.length===0&&a([document,window]).unbind(".dialog-overlay"),b.remove();var d=0;a.each(this.instances,function(){d=Math.max(d,this.css("z-index"))}),this.maxZ=d},height:function(){var b,c;if(a.browser.msie&&a.browser.version<7){b=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight),c=Math.max(document.documentElement.offsetHeight,document.body.offsetHeight);return b<c?a(window).height()+"px":b+"px"}return a(document).height()+"px"},width:function(){var b,c;if(a.browser.msie){b=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth),c=Math.max(document.documentElement.offsetWidth,document.body.offsetWidth);return b<c?a(window).width()+"px":b+"px"}return a(document).width()+"px"},resize:function(){var b=a([]);a.each(a.ui.dialog.overlay.instances,function(){b=b.add(this)}),b.css({width:0,height:0}).css({width:a.ui.dialog.overlay.width(),height:a.ui.dialog.overlay.height()})}}),a.extend(a.ui.dialog.overlay.prototype,{destroy:function(){a.ui.dialog.overlay.destroy(this.$el)}})}(jQuery),function(a,b){a.ui=a.ui||{};var c=/left|center|right/,d=/top|center|bottom/,e="center",f={},g=a.fn.position,h=a.fn.offset;a.fn.position=function(b){if(!b||!b.of)return g.apply(this,arguments);b=a.extend({},b);var h=a(b.of),i=h[0],j=(b.collision||"flip").split(" "),k=b.offset?b.offset.split(" "):[0,0],l,m,n;i.nodeType===9?(l=h.width(),m=h.height(),n={top:0,left:0}):i.setTimeout?(l=h.width(),m=h.height(),n={top:h.scrollTop(),left:h.scrollLeft()}):i.preventDefault?(b.at="left top",l=m=0,n={top:b.of.pageY,left:b.of.pageX}):(l=h.outerWidth(),m=h.outerHeight(),n=h.offset()),a.each(["my","at"],function(){var a=(b[this]||"").split(" ");a.length===1&&(a=c.test(a[0])?a.concat([e]):d.test(a[0])?[e].concat(a):[e,e]),a[0]=c.test(a[0])?a[0]:e,a[1]=d.test(a[1])?a[1]:e,b[this]=a}),j.length===1&&(j[1]=j[0]),k[0]=parseInt(k[0],10)||0,k.length===1&&(k[1]=k[0]),k[1]=parseInt(k[1],10)||0,b.at[0]==="right"?n.left+=l:b.at[0]===e&&(n.left+=l/2),b.at[1]==="bottom"?n.top+=m:b.at[1]===e&&(n.top+=m/2),n.left+=k[0],n.top+=k[1];return this.each(function(){var c=a(this),d=c.outerWidth(),g=c.outerHeight(),h=parseInt(a.curCSS(this,"marginLeft",!0))||0,i=parseInt(a.curCSS(this,"marginTop",!0))||0,o=d+h+(parseInt(a.curCSS(this,"marginRight",!0))||0),p=g+i+(parseInt(a.curCSS(this,"marginBottom",!0))||0),q=a.extend({},n),r;b.my[0]==="right"?q.left-=d:b.my[0]===e&&(q.left-=d/2),b.my[1]==="bottom"?q.top-=g:b.my[1]===e&&(q.top-=g/2),f.fractions||(q.left=Math.round(q.left),q.top=Math.round(q.top)),r={left:q.left-h,top:q.top-i},a.each(["left","top"],function(c,e){a.ui.position[j[c]]&&a.ui.position[j[c]][e](q,{targetWidth:l,targetHeight:m,elemWidth:d,elemHeight:g,collisionPosition:r,collisionWidth:o,collisionHeight:p,offset:k,my:b.my,at:b.at})}),a.fn.bgiframe&&c.bgiframe(),c.offset(a.extend(q,{using:b.using}))})},a.ui.position={fit:{left:function(b,c){var d=a(window),e=c.collisionPosition.left+c.collisionWidth-d.width()-d.scrollLeft();b.left=e>0?b.left-e:Math.max(b.left-c.collisionPosition.left,b.left)},top:function(b,c){var d=a(window),e=c.collisionPosition.top+c.collisionHeight-d.height()-d.scrollTop();b.top=e>0?b.top-e:Math.max(b.top-c.collisionPosition.top,b.top)}},flip:{left:function(b,c){if(c.at[0]!==e){var d=a(window),f=c.collisionPosition.left+c.collisionWidth-d.width()-d.scrollLeft(),g=c.my[0]==="left"?-c.elemWidth:c.my[0]==="right"?c.elemWidth:0,h=c.at[0]==="left"?c.targetWidth:-c.targetWidth,i=-2*c.offset[0];b.left+=c.collisionPosition.left<0?g+h+i:f>0?g+h+i:0}},top:function(b,c){if(c.at[1]!==e){var d=a(window),f=c.collisionPosition.top+c.collisionHeight-d.height()-d.scrollTop(),g=c.my[1]==="top"?-c.elemHeight:c.my[1]==="bottom"?c.elemHeight:0,h=c.at[1]==="top"?c.targetHeight:-c.targetHeight,i=-2*c.offset[1];b.top+=c.collisionPosition.top<0?g+h+i:f>0?g+h+i:0}}}},a.offset.setOffset||(a.offset.setOffset=function(b,c){/static/.test(a.curCSS(b,"position"))&&(b.style.position="relative");var d=a(b),e=d.offset(),f=parseInt(a.curCSS(b,"top",!0),10)||0,g=parseInt(a.curCSS(b,"left",!0),10)||0,h={top:c.top-e.top+f,left:c.left-e.left+g};"using"in c?c.using.call(b,h):d.css(h)},a.fn.offset=function(b){var c=this[0];if(!c||!c.ownerDocument)return null;if(b)return this.each(function(){a.offset.setOffset(this,b)});return h.call(this)}),function(){var b=document.getElementsByTagName("body")[0],c=document.createElement("div"),d,e,g,h,i;d=document.createElement(b?"div":"body"),g={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"},b&&a.extend(g,{position:"absolute",left:"-1000px",top:"-1000px"});for(var j in g)d.style[j]=g[j];d.appendChild(c),e=b||document.documentElement,e.insertBefore(d,e.firstChild),c.style.cssText="position: absolute; left: 10.7432222px; top: 10.432325px; height: 30px; width: 201px;",h=a(c).offset(function(a,b){return b}).offset(),d.innerHTML="",e.removeChild(d),i=h.top+h.left+(b?2e3:0),f.fractions=i>21&&i<22}()}(jQuery),function(a,b){a.widget("ui.progressbar",{options:{value:0,max:100},min:0,_create:function(){this.element.addClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").attr({role:"progressbar","aria-valuemin":this.min,"aria-valuemax":this.options.max,"aria-valuenow":this._value()}),this.valueDiv=a("<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>").appendTo(this.element),this.oldValue=this._value(),this._refreshValue()},destroy:function(){this.element.removeClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").removeAttr("role").removeAttr("aria-valuemin").removeAttr("aria-valuemax").removeAttr("aria-valuenow"),this.valueDiv.remove(),a.Widget.prototype.destroy.apply(this,arguments)},value:function(a){if(a===b)return this._value();this._setOption("value",a);return this},_setOption:function(b,c){b==="value"&&(this.options.value=c,this._refreshValue(),this._value()===this.options.max&&this._trigger("complete")),a.Widget.prototype._setOption.apply(this,arguments)},_value:function(){var a=this.options.value;typeof a!="number"&&(a=0);return Math.min(this.options.max,Math.max(this.min,a))},_percentage:function(){return 100*this._value()/this.options.max},_refreshValue:function(){var a=this.value(),b=this._percentage();this.oldValue!==a&&(this.oldValue=a,this._trigger("change")),this.valueDiv.toggle(a>this.min).toggleClass("ui-corner-right",a===this.options.max).width(b.toFixed(0)+"%"),this.element.attr("aria-valuenow",a)}}),a.extend(a.ui.progressbar,{version:"1.8.18"})}(jQuery),function(a,b){var c=5;a.widget("ui.slider",a.ui.mouse,{widgetEventPrefix:"slide",options:{animate:!1,distance:0,max:100,min:0,orientation:"horizontal",range:!1,step:1,value:0,values:null},_create:function(){var b=this,d=this.options,e=this.element.find(".ui-slider-handle").addClass("ui-state-default ui-corner-all"),f="<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>",g=d.values&&d.values.length||1,h=[];this._keySliding=!1,this._mouseSliding=!1,this._animateOff=!0,this._handleIndex=null,this._detectOrientation(),this._mouseInit(),this.element.addClass("ui-slider ui-slider-"+this.orientation+" ui-widget"+" ui-widget-content"+" ui-corner-all"+(d.disabled?" ui-slider-disabled ui-disabled":"")),this.range=a([]),d.range&&(d.range===!0&&(d.values||(d.values=[this._valueMin(),this._valueMin()]),d.values.length&&d.values.length!==2&&(d.values=[d.values[0],d.values[0]])),this.range=a("<div></div>").appendTo(this.element).addClass("ui-slider-range ui-widget-header"+(d.range==="min"||d.range==="max"?" ui-slider-range-"+d.range:"")));for(var i=e.length;i<g;i+=1)h.push(f);this.handles=e.add(a(h.join("")).appendTo(b.element)),this.handle=this.handles.eq(0),this.handles.add(this.range).filter("a").click(function(a){a.preventDefault()}).hover(function(){d.disabled||a(this).addClass("ui-state-hover")},function(){a(this).removeClass("ui-state-hover")}).focus(function(){d.disabled?a(this).blur():(a(".ui-slider .ui-state-focus").removeClass("ui-state-focus"),a(this).addClass("ui-state-focus"))}).blur(function(){a(this).removeClass("ui-state-focus")}),this.handles.each(function(b){a(this).data("index.ui-slider-handle",b)}),this.handles.keydown(function(d){var e=a(this).data("index.ui-slider-handle"),f,g,h,i;if(!b.options.disabled){switch(d.keyCode){case a.ui.keyCode.HOME:case a.ui.keyCode.END:case a.ui.keyCode.PAGE_UP:case a.ui.keyCode.PAGE_DOWN:case a.ui.keyCode.UP:case a.ui.keyCode.RIGHT:case a.ui.keyCode.DOWN:case a.ui.keyCode.LEFT:d.preventDefault();if(!b._keySliding){b._keySliding=!0,a(this).addClass("ui-state-active"),f=b._start(d,e);if(f===!1)return}}i=b.options.step,b.options.values&&b.options.values.length?g=h=b.values(e):g=h=b.value();switch(d.keyCode){case a.ui.keyCode.HOME:h=b._valueMin();break;case a.ui.keyCode.END:h=b._valueMax();break;case a.ui.keyCode.PAGE_UP:h=b._trimAlignValue(g+(b._valueMax()-b._valueMin())/c);break;case a.ui.keyCode.PAGE_DOWN:h=b._trimAlignValue(g-(b._valueMax()-b._valueMin())/c);break;case a.ui.keyCode.UP:case a.ui.keyCode.RIGHT:if(g===b._valueMax())return;h=b._trimAlignValue(g+i);break;case a.ui.keyCode.DOWN:case a.ui.keyCode.LEFT:if(g===b._valueMin())return;h=b._trimAlignValue(g-i)}b._slide(d,e,h)}}).keyup(function(c){var d=a(this).data("index.ui-slider-handle");b._keySliding&&(b._keySliding=!1,b._stop(c,d),b._change(c,d),a(this).removeClass("ui-state-active"))}),this._refreshValue(),this._animateOff=!1},destroy:function(){this.handles.remove(),this.range.remove(),this.element.removeClass("ui-slider ui-slider-horizontal ui-slider-vertical ui-slider-disabled ui-widget ui-widget-content ui-corner-all").removeData("slider").unbind(".slider"),this._mouseDestroy();return this},_mouseCapture:function(b){var c=this.options,d,e,f,g,h,i,j,k,l;if(c.disabled)return!1;this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()},this.elementOffset=this.element.offset(),d={x:b.pageX,y:b.pageY},e=this._normValueFromMouse(d),f=this._valueMax()-this._valueMin()+1,h=this,this.handles.each(function(b){var c=Math.abs(e-h.values(b));f>c&&(f=c,g=a(this),i=b)}),c.range===!0&&this.values(1)===c.min&&(i+=1,g=a(this.handles[i])),j=this._start(b,i);if(j===!1)return!1;this._mouseSliding=!0,h._handleIndex=i,g.addClass("ui-state-active").focus(),k=g.offset(),l=!a(b.target).parents().andSelf().is(".ui-slider-handle"),this._clickOffset=l?{left:0,top:0}:{left:b.pageX-k.left-g.width()/2,top:b.pageY-k.top-g.height()/2-(parseInt(g.css("borderTopWidth"),10)||0)-(parseInt(g.css("borderBottomWidth"),10)||0)+(parseInt(g.css("marginTop"),10)||0)},this.handles.hasClass("ui-state-hover")||this._slide(b,i,e),this._animateOff=!0;return!0},_mouseStart:function(a){return!0},_mouseDrag:function(a){var b={x:a.pageX,y:a.pageY},c=this._normValueFromMouse(b);this._slide(a,this._handleIndex,c);return!1},_mouseStop:function(a){this.handles.removeClass("ui-state-active"),this._mouseSliding=!1,this._stop(a,this._handleIndex),this._change(a,this._handleIndex),this._handleIndex=null,this._clickOffset=null,this._animateOff=!1;return!1},_detectOrientation:function(){this.orientation=this.options.orientation==="vertical"?"vertical":"horizontal"},_normValueFromMouse:function(a){var b,c,d,e,f;this.orientation==="horizontal"?(b=this.elementSize.width,c=a.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)):(b=this.elementSize.height,c=a.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)),d=c/b,d>1&&(d=1),d<0&&(d=0),this.orientation==="vertical"&&(d=1-d),e=this._valueMax()-this._valueMin(),f=this._valueMin()+d*e;return this._trimAlignValue(f)},_start:function(a,b){var c={handle:this.handles[b],value:this.value()};this.options.values&&this.options.values.length&&(c.value=this.values(b),c.values=this.values());return this._trigger("start",a,c)},_slide:function(a,b,c){var d,e,f;this.options.values&&this.options.values.length?(d=this.values(b?0:1),this.options.values.length===2&&this.options.range===!0&&(b===0&&c>d||b===1&&c<d)&&(c=d),c!==this.values(b)&&(e=this.values(),e[b]=c,f=this._trigger("slide",a,{handle:this.handles[b],value:c,values:e}),d=this.values(b?0:1),f!==!1&&this.values(b,c,!0))):c!==this.value()&&(f=this._trigger("slide",a,{handle:this.handles[b],value:c}),f!==!1&&this.value(c))},_stop:function(a,b){var c={handle:this.handles[b],value:this.value()};this.options.values&&this.options.values.length&&(c.value=this.values(b),c.values=this.values()),this._trigger("stop",a,c)},_change:function(a,b){if(!this._keySliding&&!this._mouseSliding){var c={handle:this.handles[b],value:this.value()};this.options.values&&this.options.values.length&&(c.value=this.values(b),c.values=this.values()),this._trigger("change",a,c)}},value:function(a){if(arguments.length)this.options.value=this._trimAlignValue(a),this._refreshValue(),this._change(null,0);else return this._value()},values:function(b,c){var d,e,f;if(arguments.length>1)this.options.values[b]=this._trimAlignValue(c),this._refreshValue(),this._change(null,b);else{if(!arguments.length)return this._values();if(!a.isArray(arguments[0]))return this.options.values&&this.options.values.length?this._values(b):this.value();d=this.options.values,e=arguments[0];for(f=0;f<d.length;f+=1)d[f]=this._trimAlignValue(e[f]),this._change(null,f);this._refreshValue()}},_setOption:function(b,c){var d,e=0;a.isArray(this.options.values)&&(e=this.options.values.length),a.Widget.prototype._setOption.apply(this,arguments);switch(b){case"disabled":c?(this.handles.filter(".ui-state-focus").blur(),this.handles.removeClass("ui-state-hover"),this.handles.propAttr("disabled",!0),this.element.addClass("ui-disabled")):(this.handles.propAttr("disabled",!1),this.element.removeClass("ui-disabled"));break;case"orientation":this._detectOrientation(),this.element.removeClass("ui-slider-horizontal ui-slider-vertical").addClass("ui-slider-"+this.orientation),this._refreshValue();break;case"value":this._animateOff=!0,this._refreshValue(),this._change(null,0),this._animateOff=!1;break;case"values":this._animateOff=!0,this._refreshValue();for(d=0;d<e;d+=1)this._change(null,d);this._animateOff=!1}},_value:function(){var a=this.options.value;a=this._trimAlignValue(a);return a},_values:function(a){var b,c,d;if(arguments.length){b=this.options.values[a],b=this._trimAlignValue(b);return b}c=this.options.values.slice();for(d=0;d<c.length;d+=1)c[d]=this._trimAlignValue(c[d]);return c},_trimAlignValue:function(a){if(a<=this._valueMin())return this._valueMin();if(a>=this._valueMax())return this._valueMax();var b=this.options.step>0?this.options.step:1,c=(a-this._valueMin())%b,d=a-c;Math.abs(c)*2>=b&&(d+=c>0?b:-b);return parseFloat(d.toFixed(5))},_valueMin:function(){return this.options.min},_valueMax:function(){return this.options.max},_refreshValue:function(){var b=this.options.range,c=this.options,d=this,e=this._animateOff?!1:c.animate,f,g={},h,i,j,k;this.options.values&&this.options.values.length?this.handles.each(function(b,i){f=(d.values(b)-d._valueMin())/(d._valueMax()-d._valueMin())*100,g[d.orientation==="horizontal"?"left":"bottom"]=f+"%",a(this).stop(1,1)[e?"animate":"css"](g,c.animate),d.options.range===!0&&(d.orientation==="horizontal"?(b===0&&d.range.stop(1,1)[e?"animate":"css"]({left:f+"%"},c.animate),b===1&&d.range[e?"animate":"css"]({width:f-h+"%"},{queue:!1,duration:c.animate})):(b===0&&d.range.stop(1,1)[e?"animate":"css"]({bottom:f+"%"},c.animate),b===1&&d.range[e?"animate":"css"]({height:f-h+"%"},{queue:!1,duration:c.animate}))),h=f}):(i=this.value(),j=this._valueMin(),k=this._valueMax(),f=k!==j?(i-j)/(k-j)*100:0,g[d.orientation==="horizontal"?"left":"bottom"]=f+"%",this.handle.stop(1,1)[e?"animate":"css"](g,c.animate),b==="min"&&this.orientation==="horizontal"&&this.range.stop(1,1)[e?"animate":"css"]({width:f+"%"},c.animate),b==="max"&&this.orientation==="horizontal"&&this.range[e?"animate":"css"]({width:100-f+"%"},{queue:!1,duration:c.animate}),b==="min"&&this.orientation==="vertical"&&this.range.stop(1,1)[e?"animate":"css"]({height:f+"%"},c.animate),b==="max"&&this.orientation==="vertical"&&this.range[e?"animate":"css"]({height:100-f+"%"},{queue:!1,duration:c.animate}))}}),a.extend(a.ui.slider,{version:"1.8.18"})}(jQuery),function(a,b){function f(){return++d}function e(){return++c}var c=0,d=0;a.widget("ui.tabs",{options:{add:null,ajaxOptions:null,cache:!1,cookie:null,collapsible:!1,disable:null,disabled:[],enable:null,event:"click",fx:null,idPrefix:"ui-tabs-",load:null,panelTemplate:"<div></div>",remove:null,select:null,show:null,spinner:"<em>Loading&#8230;</em>",tabTemplate:"<li><a href='#{href}'><span>#{label}</span></a></li>"},_create:function(){this._tabify(!0)},_setOption:function(a,b){if(a=="selected"){if(this.options.collapsible&&b==this.options.selected)return;this.select(b)}else this.options[a]=b,this._tabify()},_tabId:function(a){return a.title&&a.title.replace(/\s/g,"_").replace(/[^\w\u00c0-\uFFFF-]/g,"")||this.options.idPrefix+e()},_sanitizeSelector:function(a){return a.replace(/:/g,"\\:")},_cookie:function(){var b=this.cookie||(this.cookie=this.options.cookie.name||"ui-tabs-"+f());return a.cookie.apply(null,[b].concat(a.makeArray(arguments)))},_ui:function(a,b){return{tab:a,panel:b,index:this.anchors.index(a)}},_cleanup:function(){this.lis.filter(".ui-state-processing").removeClass("ui-state-processing").find("span:data(label.tabs)").each(function(){var b=a(this);b.html(b.data("label.tabs")).removeData("label.tabs")})},_tabify:function(c){function m(b,c){b.css("display",""),!a.support.opacity&&c.opacity&&b[0].style.removeAttribute("filter")}var d=this,e=this.options,f=/^#.+/;this.list=this.element.find("ol,ul").eq(0),this.lis=a(" > li:has(a[href])",this.list),this.anchors=this.lis.map(function(){return a("a",this)[0]}),this.panels=a([]),this.anchors.each(function(b,c){var g=a(c).attr("href"),h=g.split("#")[0],i;h&&(h===location.toString().split("#")[0]||(i=a("base")[0])&&h===i.href)&&(g=c.hash,c.href=g);if(f.test(g))d.panels=d.panels.add(d.element.find(d._sanitizeSelector(g)));else if(g&&g!=="#"){a.data(c,"href.tabs",g),a.data(c,"load.tabs",g.replace(/#.*$/,""));var j=d._tabId(c);c.href="#"+j;var k=d.element.find("#"+j);k.length||(k=a(e.panelTemplate).attr("id",j).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").insertAfter(d.panels[b-1]||d.list),k.data("destroy.tabs",!0)),d.panels=d.panels.add(k)}else e.disabled.push(b)}),c?(this.element.addClass("ui-tabs ui-widget ui-widget-content ui-corner-all"),this.list.addClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all"),this.lis.addClass("ui-state-default ui-corner-top"),this.panels.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom"),e.selected===b?(location.hash&&this.anchors.each(function(a,b){if(b.hash==location.hash){e.selected=a;return!1}}),typeof e.selected!="number"&&e.cookie&&(e.selected=parseInt(d._cookie(),10)),typeof e.selected!="number"&&this.lis.filter(".ui-tabs-selected").length&&(e.selected=this.lis.index(this.lis.filter(".ui-tabs-selected"))),e.selected=e.selected||(this.lis.length?0:-1)):e.selected===null&&(e.selected=-1),e.selected=e.selected>=0&&this.anchors[e.selected]||e.selected<0?e.selected:0,e.disabled=a.unique(e.disabled.concat(a.map(this.lis.filter(".ui-state-disabled"),function(a,b){return d.lis.index(a)}))).sort(),a.inArray(e.selected,e.disabled)!=-1&&e.disabled.splice(a.inArray(e.selected,e.disabled),1),this.panels.addClass("ui-tabs-hide"),this.lis.removeClass("ui-tabs-selected ui-state-active"),e.selected>=0&&this.anchors.length&&(d.element.find(d._sanitizeSelector(d.anchors[e.selected].hash)).removeClass("ui-tabs-hide"),this.lis.eq(e.selected).addClass("ui-tabs-selected ui-state-active"),d.element.queue("tabs",function(){d._trigger("show",null,d._ui(d.anchors[e.selected],d.element.find(d._sanitizeSelector(d.anchors[e.selected].hash))[0]))}),this.load(e.selected)),a(window).bind("unload",function(){d.lis.add(d.anchors).unbind(".tabs"),d.lis=d.anchors=d.panels=null})):e.selected=this.lis.index(this.lis.filter(".ui-tabs-selected")),this.element[e.collapsible?"addClass":"removeClass"]("ui-tabs-collapsible"),e.cookie&&this._cookie(e.selected,e.cookie);for(var g=0,h;h=this.lis[g];g++)a(h)[a.inArray(g,e.disabled)!=-1&&!a(h).hasClass("ui-tabs-selected")?"addClass":"removeClass"]("ui-state-disabled");e.cache===!1&&this.anchors.removeData("cache.tabs"),this.lis.add(this.anchors).unbind(".tabs");if(e.event!=="mouseover"){var i=function(a,b){b.is(":not(.ui-state-disabled)")&&b.addClass("ui-state-"+a)},j=function(a,b){b.removeClass("ui-state-"+a)};this.lis.bind("mouseover.tabs",function(){i("hover",a(this))}),this.lis.bind("mouseout.tabs",function(){j("hover",a(this))}),this.anchors.bind("focus.tabs",function(){i("focus",a(this).closest("li"))}),this.anchors.bind("blur.tabs",function(){j("focus",a(this).closest("li"))})}var k,l;e.fx&&(a.isArray(e.fx)?(k=e.fx[0],l=e.fx[1]):k=l=e.fx);var n=l?function(b,c){a(b).closest("li").addClass("ui-tabs-selected ui-state-active"),c.hide().removeClass("ui-tabs-hide").animate(l,l.duration||"normal",function(){m(c,l),d._trigger("show",null,d._ui(b,c[0]))})}:function(b,c){a(b).closest("li").addClass("ui-tabs-selected ui-state-active"),c.removeClass("ui-tabs-hide"),d._trigger("show",null,d._ui(b,c[0]))},o=k?function(a,b){b.animate(k,k.duration||"normal",function(){d.lis.removeClass("ui-tabs-selected ui-state-active"),b.addClass("ui-tabs-hide"),m(b,k),d.element.dequeue("tabs")})}:function(a,b,c){d.lis.removeClass("ui-tabs-selected ui-state-active"),b.addClass("ui-tabs-hide"),d.element.dequeue("tabs")};this.anchors.bind(e.event+".tabs",function(){var b=this,c=a(b).closest("li"),f=d.panels.filter(":not(.ui-tabs-hide)"),g=d.element.find(d._sanitizeSelector(b.hash));if(c.hasClass("ui-tabs-selected")&&!e.collapsible||c.hasClass("ui-state-disabled")||c.hasClass("ui-state-processing")||d.panels.filter(":animated").length||d._trigger("select",null,d._ui(this,g[0]))===!1){this.blur();return!1}e.selected=d.anchors.index(this),d.abort();if(e.collapsible){if(c.hasClass("ui-tabs-selected")){e.selected=-1,e.cookie&&d._cookie(e.selected,e.cookie),d.element.queue("tabs",function(){o(b,f)}).dequeue("tabs"),this.blur();return!1}if(!f.length){e.cookie&&d._cookie(e.selected,e.cookie),d.element.queue("tabs",function(){n(b,g)}
+),d.load(d.anchors.index(this)),this.blur();return!1}}e.cookie&&d._cookie(e.selected,e.cookie);if(g.length)f.length&&d.element.queue("tabs",function(){o(b,f)}),d.element.queue("tabs",function(){n(b,g)}),d.load(d.anchors.index(this));else throw"jQuery UI Tabs: Mismatching fragment identifier.";a.browser.msie&&this.blur()}),this.anchors.bind("click.tabs",function(){return!1})},_getIndex:function(a){typeof a=="string"&&(a=this.anchors.index(this.anchors.filter("[href$="+a+"]")));return a},destroy:function(){var b=this.options;this.abort(),this.element.unbind(".tabs").removeClass("ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible").removeData("tabs"),this.list.removeClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all"),this.anchors.each(function(){var b=a.data(this,"href.tabs");b&&(this.href=b);var c=a(this).unbind(".tabs");a.each(["href","load","cache"],function(a,b){c.removeData(b+".tabs")})}),this.lis.unbind(".tabs").add(this.panels).each(function(){a.data(this,"destroy.tabs")?a(this).remove():a(this).removeClass(["ui-state-default","ui-corner-top","ui-tabs-selected","ui-state-active","ui-state-hover","ui-state-focus","ui-state-disabled","ui-tabs-panel","ui-widget-content","ui-corner-bottom","ui-tabs-hide"].join(" "))}),b.cookie&&this._cookie(null,b.cookie);return this},add:function(c,d,e){e===b&&(e=this.anchors.length);var f=this,g=this.options,h=a(g.tabTemplate.replace(/#\{href\}/g,c).replace(/#\{label\}/g,d)),i=c.indexOf("#")?this._tabId(a("a",h)[0]):c.replace("#","");h.addClass("ui-state-default ui-corner-top").data("destroy.tabs",!0);var j=f.element.find("#"+i);j.length||(j=a(g.panelTemplate).attr("id",i).data("destroy.tabs",!0)),j.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide"),e>=this.lis.length?(h.appendTo(this.list),j.appendTo(this.list[0].parentNode)):(h.insertBefore(this.lis[e]),j.insertBefore(this.panels[e])),g.disabled=a.map(g.disabled,function(a,b){return a>=e?++a:a}),this._tabify(),this.anchors.length==1&&(g.selected=0,h.addClass("ui-tabs-selected ui-state-active"),j.removeClass("ui-tabs-hide"),this.element.queue("tabs",function(){f._trigger("show",null,f._ui(f.anchors[0],f.panels[0]))}),this.load(0)),this._trigger("add",null,this._ui(this.anchors[e],this.panels[e]));return this},remove:function(b){b=this._getIndex(b);var c=this.options,d=this.lis.eq(b).remove(),e=this.panels.eq(b).remove();d.hasClass("ui-tabs-selected")&&this.anchors.length>1&&this.select(b+(b+1<this.anchors.length?1:-1)),c.disabled=a.map(a.grep(c.disabled,function(a,c){return a!=b}),function(a,c){return a>=b?--a:a}),this._tabify(),this._trigger("remove",null,this._ui(d.find("a")[0],e[0]));return this},enable:function(b){b=this._getIndex(b);var c=this.options;if(a.inArray(b,c.disabled)!=-1){this.lis.eq(b).removeClass("ui-state-disabled"),c.disabled=a.grep(c.disabled,function(a,c){return a!=b}),this._trigger("enable",null,this._ui(this.anchors[b],this.panels[b]));return this}},disable:function(a){a=this._getIndex(a);var b=this,c=this.options;a!=c.selected&&(this.lis.eq(a).addClass("ui-state-disabled"),c.disabled.push(a),c.disabled.sort(),this._trigger("disable",null,this._ui(this.anchors[a],this.panels[a])));return this},select:function(a){a=this._getIndex(a);if(a==-1)if(this.options.collapsible&&this.options.selected!=-1)a=this.options.selected;else return this;this.anchors.eq(a).trigger(this.options.event+".tabs");return this},load:function(b){b=this._getIndex(b);var c=this,d=this.options,e=this.anchors.eq(b)[0],f=a.data(e,"load.tabs");this.abort();if(!f||this.element.queue("tabs").length!==0&&a.data(e,"cache.tabs"))this.element.dequeue("tabs");else{this.lis.eq(b).addClass("ui-state-processing");if(d.spinner){var g=a("span",e);g.data("label.tabs",g.html()).html(d.spinner)}this.xhr=a.ajax(a.extend({},d.ajaxOptions,{url:f,success:function(f,g){c.element.find(c._sanitizeSelector(e.hash)).html(f),c._cleanup(),d.cache&&a.data(e,"cache.tabs",!0),c._trigger("load",null,c._ui(c.anchors[b],c.panels[b]));try{d.ajaxOptions.success(f,g)}catch(h){}},error:function(a,f,g){c._cleanup(),c._trigger("load",null,c._ui(c.anchors[b],c.panels[b]));try{d.ajaxOptions.error(a,f,b,e)}catch(g){}}})),c.element.dequeue("tabs");return this}},abort:function(){this.element.queue([]),this.panels.stop(!1,!0),this.element.queue("tabs",this.element.queue("tabs").splice(-2,2)),this.xhr&&(this.xhr.abort(),delete this.xhr),this._cleanup();return this},url:function(a,b){this.anchors.eq(a).removeData("cache.tabs").data("load.tabs",b);return this},length:function(){return this.anchors.length}}),a.extend(a.ui.tabs,{version:"1.8.18"}),a.extend(a.ui.tabs.prototype,{rotation:null,rotate:function(a,b){var c=this,d=this.options,e=c._rotate||(c._rotate=function(b){clearTimeout(c.rotation),c.rotation=setTimeout(function(){var a=d.selected;c.select(++a<c.anchors.length?a:0)},a),b&&b.stopPropagation()}),f=c._unrotate||(c._unrotate=b?function(a){t=d.selected,e()}:function(a){a.clientX&&c.rotate(null)});a?(this.element.bind("tabsshow",e),this.anchors.bind(d.event+".tabs",f),e()):(clearTimeout(c.rotation),this.element.unbind("tabsshow",e),this.anchors.unbind(d.event+".tabs",f),delete this._rotate,delete this._unrotate);return this}})}(jQuery)
\ No newline at end of file
diff --git a/plugins/pres_view/static/js/jquery.min.js b/plugins/pres_view/static/js/jquery.min.js
new file mode 100644 (file)
index 0000000..16ad06c
--- /dev/null
@@ -0,0 +1,4 @@
+/*! jQuery v1.7.2 jquery.com | jquery.org/license */
+(function(a,b){function cy(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cu(a){if(!cj[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){ck||(ck=c.createElement("iframe"),ck.frameBorder=ck.width=ck.height=0),b.appendChild(ck);if(!cl||!ck.createElement)cl=(ck.contentWindow||ck.contentDocument).document,cl.write((f.support.boxModel?"<!doctype html>":"")+"<html><body>"),cl.close();d=cl.createElement(a),cl.body.appendChild(d),e=f.css(d,"display"),b.removeChild(ck)}cj[a]=e}return cj[a]}function ct(a,b){var c={};f.each(cp.concat.apply([],cp.slice(0,b)),function(){c[this]=a});return c}function cs(){cq=b}function cr(){setTimeout(cs,0);return cq=f.now()}function ci(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ch(){try{return new a.XMLHttpRequest}catch(b){}}function cb(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g<i;g++){if(g===1)for(h in a.converters)typeof h=="string"&&(e[h.toLowerCase()]=a.converters[h]);l=k,k=d[g];if(k==="*")k=l;else if(l!=="*"&&l!==k){m=l+" "+k,n=e[m]||e["* "+k];if(!n){p=b;for(o in e){j=o.split(" ");if(j[0]===l||j[0]==="*"){p=e[j[1]+" "+k];if(p){o=e[o],o===!0?n=p:p===!0&&(n=o);break}}}}!n&&!p&&f.error("No conversion from "+m.replace(" "," to ")),n!==!0&&(c=n?n(c):p(o(c)))}}return c}function ca(a,c,d){var e=a.contents,f=a.dataTypes,g=a.responseFields,h,i,j,k;for(i in g)i in d&&(c[g[i]]=d[i]);while(f[0]==="*")f.shift(),h===b&&(h=a.mimeType||c.getResponseHeader("content-type"));if(h)for(i in e)if(e[i]&&e[i].test(h)){f.unshift(i);break}if(f[0]in d)j=f[0];else{for(i in d){if(!f[0]||a.converters[i+" "+f[0]]){j=i;break}k||(k=i)}j=j||k}if(j){j!==f[0]&&f.unshift(j);return d[j]}}function b_(a,b,c,d){if(f.isArray(b))f.each(b,function(b,e){c||bD.test(a)?d(a,e):b_(a+"["+(typeof e=="object"?b:"")+"]",e,c,d)});else if(!c&&f.type(b)==="object")for(var e in b)b_(a+"["+e+"]",b[e],c,d);else d(a,b)}function b$(a,c){var d,e,g=f.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((g[d]?a:e||(e={}))[d]=c[d]);e&&f.extend(!0,a,e)}function bZ(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h=a[f],i=0,j=h?h.length:0,k=a===bS,l;for(;i<j&&(k||!l);i++)l=h[i](c,d,e),typeof l=="string"&&(!k||g[l]?l=b:(c.dataTypes.unshift(l),l=bZ(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=bZ(a,c,d,e,"*",g));return l}function bY(a){return function(b,c){typeof b!="string"&&(c=b,b="*");if(f.isFunction(c)){var d=b.toLowerCase().split(bO),e=0,g=d.length,h,i,j;for(;e<g;e++)h=d[e],j=/^\+/.test(h),j&&(h=h.substr(1)||"*"),i=a[h]=a[h]||[],i[j?"unshift":"push"](c)}}}function bB(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=b==="width"?1:0,g=4;if(d>0){if(c!=="border")for(;e<g;e+=2)c||(d-=parseFloat(f.css(a,"padding"+bx[e]))||0),c==="margin"?d+=parseFloat(f.css(a,c+bx[e]))||0:d-=parseFloat(f.css(a,"border"+bx[e]+"Width"))||0;return d+"px"}d=by(a,b);if(d<0||d==null)d=a.style[b];if(bt.test(d))return d;d=parseFloat(d)||0;if(c)for(;e<g;e+=2)d+=parseFloat(f.css(a,"padding"+bx[e]))||0,c!=="padding"&&(d+=parseFloat(f.css(a,"border"+bx[e]+"Width"))||0),c==="margin"&&(d+=parseFloat(f.css(a,c+bx[e]))||0);return d+"px"}function bo(a){var b=c.createElement("div");bh.appendChild(b),b.innerHTML=a.outerHTML;return b.firstChild}function bn(a){var b=(a.nodeName||"").toLowerCase();b==="input"?bm(a):b!=="script"&&typeof a.getElementsByTagName!="undefined"&&f.grep(a.getElementsByTagName("input"),bm)}function bm(a){if(a.type==="checkbox"||a.type==="radio")a.defaultChecked=a.checked}function bl(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bk(a,b){var c;b.nodeType===1&&(b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase(),c==="object"?b.outerHTML=a.outerHTML:c!=="input"||a.type!=="checkbox"&&a.type!=="radio"?c==="option"?b.selected=a.defaultSelected:c==="input"||c==="textarea"?b.defaultValue=a.defaultValue:c==="script"&&b.text!==a.text&&(b.text=a.text):(a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value)),b.removeAttribute(f.expando),b.removeAttribute("_submit_attached"),b.removeAttribute("_change_attached"))}function bj(a,b){if(b.nodeType===1&&!!f.hasData(a)){var c,d,e,g=f._data(a),h=f._data(b,g),i=g.events;if(i){delete h.handle,h.events={};for(c in i)for(d=0,e=i[c].length;d<e;d++)f.event.add(b,c,i[c][d])}h.data&&(h.data=f.extend({},h.data))}}function bi(a,b){return f.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function U(a){var b=V.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function T(a,b,c){b=b||0;if(f.isFunction(b))return f.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return f.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=f.grep(a,function(a){return a.nodeType===1});if(O.test(b))return f.filter(b,d,!c);b=f.filter(b,d)}return f.grep(a,function(a,d){return f.inArray(a,b)>=0===c})}function S(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function K(){return!0}function J(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?+d:j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c<d;c++)b[a[c]]=!0;return b}var c=a.document,d=a.navigator,e=a.location,f=function(){function J(){if(!e.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(J,1);return}e.ready()}}var e=function(a,b){return new e.fn.init(a,b,h)},f=a.jQuery,g=a.$,h,i=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=/-([a-z]|[0-9])/ig,w=/^-ms-/,x=function(a,b){return(b+"").toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=m.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7.2",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.add(a);return this},eq:function(a){a=+a;return a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j<k;j++)if((a=arguments[j])!=null)for(c in a){d=i[c],f=a[c];if(i===f)continue;l&&f&&(e.isPlainObject(f)||(g=e.isArray(f)))?(g?(g=!1,h=d&&e.isArray(d)?d:[]):h=d&&e.isPlainObject(d)?d:{},i[c]=e.extend(l,h,f)):f!==b&&(i[c]=f)}return i},e.extend({noConflict:function(b){a.$===e&&(a.$=g),b&&a.jQuery===e&&(a.jQuery=f);return e},isReady:!1,readyWait:1,holdReady:function(a){a?e.readyWait++:e.ready(!0)},ready:function(a){if(a===!0&&!--e.readyWait||a!==!0&&!e.isReady){if(!c.body)return setTimeout(e.ready,1);e.isReady=!0;if(a!==!0&&--e.readyWait>0)return;A.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").off("ready")}},bindReady:function(){if(!A){A=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a!=null&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):I[C.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||D.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw new Error(a)},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){if(typeof c!="string"||!c)return null;var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,"ms-").replace(v,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g<h;)if(c.apply(a[g++],d)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(;g<h;)if(c.call(a[g],g,a[g++])===!1)break;return a},trim:G?function(a){return a==null?"":G.call(a)}:function(a){return a==null?"":(a+"").replace(k,"").replace(l,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var d=e.type(a);a.length==null||d==="string"||d==="function"||d==="regexp"||e.isWindow(a)?E.call(c,a):e.merge(c,a)}return c},inArray:function(a,b,c){var d;if(b){if(H)return H.call(b,a,c);d=b.length,c=c?c<0?Math.max(0,d+c):c:0;for(;c<d;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=a.length,e=0;if(typeof c.length=="number")for(var f=c.length;e<f;e++)a[d++]=c[e];else while(c[e]!==b)a[d++]=c[e++];a.length=d;return a},grep:function(a,b,c){var d=[],e;c=!!c;for(var f=0,g=a.length;f<g;f++)e=!!b(a[f],f),c!==e&&d.push(a[f]);return d},map:function(a,c,d){var f,g,h=[],i=0,j=a.length,k=a instanceof e||j!==b&&typeof j=="number"&&(j>0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i<j;i++)f=c(a[i],i,d),f!=null&&(h[h.length]=f);else for(g in a)f=c(a[g],g,d),f!=null&&(h[h.length]=f);return h.concat.apply([],h)},guid:1,proxy:function(a,c){if(typeof c=="string"){var d=a[c];c=a,a=d}if(!e.isFunction(a))return b;var f=F.call(arguments,2),g=function(){return a.apply(c,f.concat(F.call(arguments)))};g.guid=a.guid=a.guid||g.guid||e.guid++;return g},access:function(a,c,d,f,g,h,i){var j,k=d==null,l=0,m=a.length;if(d&&typeof d=="object"){for(l in d)e.access(a,c,l,d[l],1,h,f);g=1}else if(f!==b){j=i===b&&e.isFunction(f),k&&(j?(j=c,c=function(a,b,c){return j.call(e(a),c)}):(c.call(a,f),c=null));if(c)for(;l<m;l++)c(a[l],d,j?f.call(a[l],l,c(a[l],d)):f,i);g=1}return g?a:k?c.call(a):m?c(a[0],d):h},now:function(){return(new Date).getTime()},uaMatch:function(a){a=a.toLowerCase();var b=r.exec(a)||s.exec(a)||t.exec(a)||a.indexOf("compatible")<0&&u.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},sub:function(){function a(b,c){return new a.fn.init(b,c)}e.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function(d,f){f&&f instanceof e&&!(f instanceof a)&&(f=a(f));return e.fn.init.call(this,d,f,b)},a.fn.init.prototype=a.fn;var b=a(c);return a},browser:{}}),e.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){I["[object "+b+"]"]=b.toLowerCase()}),z=e.uaMatch(y),z.browser&&(e.browser[z.browser]=!0,e.browser.version=z.version),e.browser.webkit&&(e.browser.safari=!0),j.test(" ")&&(k=/^[\s\xA0]+/,l=/[\s\xA0]+$/),h=e(c),c.addEventListener?B=function(){c.removeEventListener("DOMContentLoaded",B,!1),e.ready()}:c.attachEvent&&(B=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",B),e.ready())});return e}(),g={};f.Callbacks=function(a){a=a?g[a]||h(a):{};var c=[],d=[],e,i,j,k,l,m,n=function(b){var d,e,g,h,i;for(d=0,e=b.length;d<e;d++)g=b[d],h=f.type(g),h==="array"?n(g):h==="function"&&(!a.unique||!p.has(g))&&c.push(g)},o=function(b,f){f=f||[],e=!a.memory||[b,f],i=!0,j=!0,m=k||0,k=0,l=c.length;for(;c&&m<l;m++)if(c[m].apply(b,f)===!1&&a.stopOnFalse){e=!0;break}j=!1,c&&(a.once?e===!0?p.disable():c=[]:d&&d.length&&(e=d.shift(),p.fireWith(e[0],e[1])))},p={add:function(){if(c){var a=c.length;n(arguments),j?l=c.length:e&&e!==!0&&(k=a,o(e[0],e[1]))}return this},remove:function(){if(c){var b=arguments,d=0,e=b.length;for(;d<e;d++)for(var f=0;f<c.length;f++)if(b[d]===c[f]){j&&f<=l&&(l--,f<=m&&m--),c.splice(f--,1);if(a.unique)break}}return this},has:function(a){if(c){var b=0,d=c.length;for(;b<d;b++)if(a===c[b])return!0}return!1},empty:function(){c=[];return this},disable:function(){c=d=e=b;return this},disabled:function(){return!c},lock:function(){d=b,(!e||e===!0)&&p.disable();return this},locked:function(){return!d},fireWith:function(b,c){d&&(j?a.once||d.push([b,c]):(!a.once||!e)&&o(b,c));return this},fire:function(){p.fireWith(this,arguments);return this},fired:function(){return!!i}};return p};var i=[].slice;f.extend({Deferred:function(a){var b=f.Callbacks("once memory"),c=f.Callbacks("once memory"),d=f.Callbacks("memory"),e="pending",g={resolve:b,reject:c,notify:d},h={done:b.add,fail:c.add,progress:d.add,state:function(){return e},isResolved:b.fired,isRejected:c.fired,then:function(a,b,c){i.done(a).fail(b).progress(c);return this},always:function(){i.done.apply(i,arguments).fail.apply(i,arguments);return this},pipe:function(a,b,c){return f.Deferred(function(d){f.each({done:[a,"resolve"],fail:[b,"reject"],progress:[c,"notify"]},function(a,b){var c=b[0],e=b[1],g;f.isFunction(c)?i[a](function(){g=c.apply(this,arguments),g&&f.isFunction(g.promise)?g.promise().then(d.resolve,d.reject,d.notify):d[e+"With"](this===i?d:this,[g])}):i[a](d[e])})}).promise()},promise:function(a){if(a==null)a=h;else for(var b in h)a[b]=h[b];return a}},i=h.promise({}),j;for(j in g)i[j]=g[j].fire,i[j+"With"]=g[j].fireWith;i.done(function(){e="resolved"},c.disable,d.lock).fail(function(){e="rejected"},b.disable,d.lock),a&&a.call(i,i);return i},when:function(a){function m(a){return function(b){e[a]=arguments.length>1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c<d;c++)b[c]&&b[c].promise&&f.isFunction(b[c].promise)?b[c].promise().then(l(c),j.reject,m(c)):--g;g||j.resolveWith(j,b)}else j!==a&&j.resolveWith(j,d?[a]:[]);return k}}),f.support=function(){var b,d,e,g,h,i,j,k,l,m,n,o,p=c.createElement("div"),q=c.documentElement;p.setAttribute("className","t"),p.innerHTML="   <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>",d=p.getElementsByTagName("*"),e=p.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=p.getElementsByTagName("input")[0],b={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:p.className!=="t",enctype:!!c.createElement("form").enctype,html5Clone:c.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,pixelMargin:!0},f.boxModel=b.boxModel=c.compatMode==="CSS1Compat",i.checked=!0,b.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,b.optDisabled=!h.disabled;try{delete p.test}catch(r){b.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",function(){b.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),b.radioValue=i.value==="t",i.setAttribute("checked","checked"),i.setAttribute("name","t"),p.appendChild(i),j=c.createDocumentFragment(),j.appendChild(p.lastChild),b.checkClone=j.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=i.checked,j.removeChild(i),j.appendChild(p);if(p.attachEvent)for(n in{submit:1,change:1,focusin:1})m="on"+n,o=m in p,o||(p.setAttribute(m,"return;"),o=typeof p[m]=="function"),b[n+"Bubbles"]=o;j.removeChild(p),j=g=h=p=i=null,f(function(){var d,e,g,h,i,j,l,m,n,q,r,s,t,u=c.getElementsByTagName("body")[0];!u||(m=1,t="padding:0;margin:0;border:",r="position:absolute;top:0;left:0;width:1px;height:1px;",s=t+"0;visibility:hidden;",n="style='"+r+t+"5px solid #000;",q="<div "+n+"display:block;'><div style='"+t+"0;display:block;overflow:hidden;'></div></div>"+"<table "+n+"' cellpadding='0' cellspacing='0'>"+"<tr><td></td></tr></table>",d=c.createElement("div"),d.style.cssText=s+"width:0;height:0;position:static;top:0;margin-top:"+m+"px",u.insertBefore(d,u.firstChild),p=c.createElement("div"),d.appendChild(p),p.innerHTML="<table><tr><td style='"+t+"0;display:none'></td><td>t</td></tr></table>",k=p.getElementsByTagName("td"),o=k[0].offsetHeight===0,k[0].style.display="",k[1].style.display="none",b.reliableHiddenOffsets=o&&k[0].offsetHeight===0,a.getComputedStyle&&(p.innerHTML="",l=c.createElement("div"),l.style.width="0",l.style.marginRight="0",p.style.width="2px",p.appendChild(l),b.reliableMarginRight=(parseInt((a.getComputedStyle(l,null)||{marginRight:0}).marginRight,10)||0)===0),typeof p.style.zoom!="undefined"&&(p.innerHTML="",p.style.width=p.style.padding="1px",p.style.border=0,p.style.overflow="hidden",p.style.display="inline",p.style.zoom=1,b.inlineBlockNeedsLayout=p.offsetWidth===3,p.style.display="block",p.style.overflow="visible",p.innerHTML="<div style='width:5px;'></div>",b.shrinkWrapBlocks=p.offsetWidth!==3),p.style.cssText=r+s,p.innerHTML=q,e=p.firstChild,g=e.firstChild,i=e.nextSibling.firstChild.firstChild,j={doesNotAddBorder:g.offsetTop!==5,doesAddBorderForTableAndCells:i.offsetTop===5},g.style.position="fixed",g.style.top="20px",j.fixedPosition=g.offsetTop===20||g.offsetTop===15,g.style.position=g.style.top="",e.style.overflow="hidden",e.style.position="relative",j.subtractsBorderForOverflowNotVisible=g.offsetTop===-5,j.doesNotIncludeMarginInBodyOffset=u.offsetTop!==m,a.getComputedStyle&&(p.style.marginTop="1%",b.pixelMargin=(a.getComputedStyle(p,null)||{marginTop:0}).marginTop!=="1%"),typeof d.style.zoom!="undefined"&&(d.style.zoom=1),u.removeChild(d),l=p=d=null,f.extend(b,j))});return b}();var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[j]:a[j]&&j,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[j]=n=++f.uuid:n=j),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[h]:h;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)||(b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,g=b.length;e<g;e++)delete d[b[e]];if(!(c?m:f.isEmptyObject)(d))return}}if(!c){delete j[k].data;if(!m(j[k]))return}f.support.deleteExpando||!j.setInterval?delete j[k]:j[k]=null,i&&(f.support.deleteExpando?delete a[h]:a.removeAttribute?a.removeAttribute(h):a[h]=null)}},_data:function(a,b,c){return f.data(a,b,c,!0)},acceptData:function(a){if(a.nodeName){var b=f.noData[a.nodeName.toLowerCase()];if(b)return b!==!0&&a.getAttribute("classid")===b}return!0}}),f.fn.extend({data:function(a,c){var d,e,g,h,i,j=this[0],k=0,m=null;if(a===b){if(this.length){m=f.data(j);if(j.nodeType===1&&!f._data(j,"parsedAttrs")){g=j.attributes;for(i=g.length;k<i;k++)h=g[k].name,h.indexOf("data-")===0&&(h=f.camelCase(h.substring(5)),l(j,h,m[h]));f._data(j,"parsedAttrs",!0)}}return m}if(typeof a=="object")return this.each(function(){f.data(this,a)});d=a.split(".",2),d[1]=d[1]?"."+d[1]:"",e=d[1]+"!";return f.access(this,function(c){if(c===b){m=this.triggerHandler("getData"+e,[d[0]]),m===b&&j&&(m=f.data(j,a),m=l(j,a,m));return m===b&&d[1]?this.data(d[0]):m}d[1]=c,this.each(function(){var b=f(this);b.triggerHandler("setData"+e,d),f.data(this,a,c),b.triggerHandler("changeData"+e,d)})},null,c,arguments.length>1,null,!1)},removeData:function(a){return this.each(function(){f.removeData(this,a)})}}),f.extend({_mark:function(a,b){a&&(b=(b||"fx")+"mark",f._data(a,b,(f._data(a,b)||0)+1))},_unmark:function(a,b,c){a!==!0&&(c=b,b=a,a=!1);if(b){c=c||"fx";var d=c+"mark",e=a?0:(f._data(b,d)||1)-1;e?f._data(b,d,e):(f.removeData(b,d,!0),n(b,c,"mark"))}},queue:function(a,b,c){var d;if(a){b=(b||"fx")+"queue",d=f._data(a,b),c&&(!d||f.isArray(c)?d=f._data(a,b,f.makeArray(c)):d.push(c));return d||[]}},dequeue:function(a,b){b=b||"fx";var c=f.queue(a,b),d=c.shift(),e={};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),f._data(a,b+".run",e),d.call(a,function(){f.dequeue(a,b)},e)),c.length||(f.removeData(a,b+"queue "+b+".run",!0),n(a,b,"queue"))}}),f.fn.extend({queue:function(a,c){var d=2;typeof a!="string"&&(c=a,a="fx",d--);if(arguments.length<d)return f.queue(this[0],a);return c===b?this:this.each(function(){var b=f.queue(this,a,c);a==="fx"&&b[0]!=="inprogress"&&f.dequeue(this,a)})},dequeue:function(a){return this.each(function(){f.dequeue(this,a)})},delay:function(a,b){a=f.fx?f.fx.speeds[a]||a:a,b=b||"fx";return this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){function m(){--h||d.resolveWith(e,[e])}typeof a!="string"&&(c=a,a=b),a=a||"fx";var d=f.Deferred(),e=this,g=e.length,h=1,i=a+"defer",j=a+"queue",k=a+"mark",l;while(g--)if(l=f.data(e[g],i,b,!0)||(f.data(e[g],j,b,!0)||f.data(e[g],k,b,!0))&&f.data(e[g],i,f.Callbacks("once memory"),!0))h++,l.add(m);m();return d.promise(c)}});var o=/[\n\t\r]/g,p=/\s+/,q=/\r/g,r=/^(?:button|input)$/i,s=/^(?:button|input|object|select|textarea)$/i,t=/^a(?:rea)?$/i,u=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,v=f.support.getSetAttribute,w,x,y;f.fn.extend({attr:function(a,b){return f.access(this,f.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){f.removeAttr(this,a)})},prop:function(a,b){return f.access(this,f.prop,a,b,arguments.length>1)},removeProp:function(a){a=f.propFix[a]||a;return this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,g,h,i;if(f.isFunction(a))return this.each(function(b){f(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(p);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{g=" "+e.className+" ";for(h=0,i=b.length;h<i;h++)~g.indexOf(" "+b[h]+" ")||(g+=b[h]+" ");e.className=f.trim(g)}}}return this},removeClass:function(a){var c,d,e,g,h,i,j;if(f.isFunction(a))return this.each(function(b){f(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(p);for(d=0,e=this.length;d<e;d++){g=this[d];if(g.nodeType===1&&g.className)if(a){h=(" "+g.className+" ").replace(o," ");for(i=0,j=c.length;i<j;i++)h=h.replace(" "+c[i]+" "," ");g.className=f.trim(h)}else g.className=""}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";if(f.isFunction(a))return this.each(function(c){f(this).toggleClass(a.call(this,c,this.className,b),b)});return this.each(function(){if(c==="string"){var e,g=0,h=f(this),i=b,j=a.split(p);while(e=j[g++])i=d?i:!h.hasClass(e),h[i?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&f._data(this,"__className__",this.className),this.className=this.className||a===!1?"":f._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(o," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e,g=this[0];{if(!!arguments.length){e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.type]||f.valHooks[this.nodeName.toLowerCase()];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}if(g){c=f.valHooks[g.type]||f.valHooks[g.nodeName.toLowerCase()];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}}}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c<d;c++){e=i[c];if(e.selected&&(f.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!f.nodeName(e.parentNode,"optgroup"))){b=f(e).val();if(j)return b;h.push(b)}}if(j&&!h.length&&i.length)return f(i[g]).val();return h},set:function(a,b){var c=f.makeArray(b);f(a).find("option").each(function(){this.selected=f.inArray(f(this).val(),c)>=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!!a&&j!==3&&j!==8&&j!==2){if(e&&c in f.attrFn)return f(a)[c](d);if(typeof a.getAttribute=="undefined")return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g}},removeAttr:function(a,b){var c,d,e,g,h,i=0;if(b&&a.nodeType===1){d=b.toLowerCase().split(p),g=d.length;for(;i<g;i++)e=d[i],e&&(c=f.propFix[e]||e,h=u.test(e),h||f.attr(a,e,""),a.removeAttribute(v?e:c),h&&c in a&&(a[c]=!1))}},attrHooks:{type:{set:function(a,b){if(r.test(a.nodeName)&&a.parentNode)f.error("type property can't be changed");else if(!f.support.radioValue&&b==="radio"&&f.nodeName(a,"input")){var c=a.value;a.setAttribute("type",b),c&&(a.value=c);return b}}},value:{get:function(a,b){if(w&&f.nodeName(a,"button"))return w.get(a,b);return b in a?a.value:null},set:function(a,b,c){if(w&&f.nodeName(a,"button"))return w.set(a,b,c);a.value=b}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(a,c,d){var e,g,h,i=a.nodeType;if(!!a&&i!==3&&i!==8&&i!==2){h=i!==1||!f.isXMLDoc(a),h&&(c=f.propFix[c]||c,g=f.propHooks[c]);return d!==b?g&&"set"in g&&(e=g.set(a,d,c))!==b?e:a[c]=d:g&&"get"in g&&(e=g.get(a,c))!==null?e:a[c]}},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):s.test(a.nodeName)||t.test(a.nodeName)&&a.href?0:b}}}}),f.attrHooks.tabindex=f.propHooks.tabIndex,x={get:function(a,c){var d,e=f.prop(a,c);return e===!0||typeof e!="boolean"&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;b===!1?f.removeAttr(a,c):(d=f.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase()));return c}},v||(y={name:!0,id:!0,coords:!0},w=f.valHooks.button={get:function(a,c){var d;d=a.getAttributeNode(c);return d&&(y[c]?d.nodeValue!=="":d.specified)?d.nodeValue:b},set:function(a,b,d){var e=a.getAttributeNode(d);e||(e=c.createAttribute(d),a.setAttributeNode(e));return e.nodeValue=b+""}},f.attrHooks.tabindex.set=w.set,f.each(["width","height"],function(a,b){f.attrHooks[b]=f.extend(f.attrHooks[b],{set:function(a,c){if(c===""){a.setAttribute(b,"auto");return c}}})}),f.attrHooks.contenteditable={get:w.get,set:function(a,b,c){b===""&&(b="false"),w.set(a,b,c)}}),f.support.hrefNormalized||f.each(["href","src","width","height"],function(a,c){f.attrHooks[c]=f.extend(f.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),f.support.style||(f.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),f.support.optSelected||(f.propHooks.selected=f.extend(f.propHooks.selected,{get:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex);return null}})),f.support.enctype||(f.propFix.enctype="encoding"),f.support.checkOn||f.each(["radio","checkbox"],function(){f.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),f.each(["radio","checkbox"],function(){f.valHooks[this]=f.extend(f.valHooks[this],{set:function(a,b){if(f.isArray(b))return a.checked=f.inArray(f(a).val(),b)>=0}})});var z=/^(?:textarea|input|select)$/i,A=/^([^\.]*)?(?:\.(.+))?$/,B=/(?:^|\s)hover(\.\S+)?\b/,C=/^key/,D=/^(?:mouse|contextmenu)|click/,E=/^(?:focusinfocus|focusoutblur)$/,F=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,G=function(
+a){var b=F.exec(a);b&&(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},H=function(a,b){var c=a.attributes||{};return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||(c.id||{}).value===b[2])&&(!b[3]||b[3].test((c["class"]||{}).value))},I=function(a){return f.event.special.hover?a:a.replace(B,"mouseenter$1 mouseleave$1")};f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler,g=p.selector),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=f.trim(I(c)).split(" ");for(k=0;k<c.length;k++){l=A.exec(c[k])||[],m=l[1],n=(l[2]||"").split(".").sort(),s=f.event.special[m]||{},m=(g?s.delegateType:s.bindType)||m,s=f.event.special[m]||{},o=f.extend({type:m,origType:l[1],data:e,handler:d,guid:d.guid,selector:g,quick:g&&G(g),namespace:n.join(".")},p),r=j[m];if(!r){r=j[m]=[],r.delegateCount=0;if(!s.setup||s.setup.call(a,e,n,i)===!1)a.addEventListener?a.addEventListener(m,i,!1):a.attachEvent&&a.attachEvent("on"+m,i)}s.add&&(s.add.call(a,o),o.handler.guid||(o.handler.guid=d.guid)),g?r.splice(r.delegateCount++,0,o):r.push(o),f.event.global[m]=!0}a=null}},global:{},remove:function(a,b,c,d,e){var g=f.hasData(a)&&f._data(a),h,i,j,k,l,m,n,o,p,q,r,s;if(!!g&&!!(o=g.events)){b=f.trim(I(b||"")).split(" ");for(h=0;h<b.length;h++){i=A.exec(b[h])||[],j=k=i[1],l=i[2];if(!j){for(j in o)f.event.remove(a,j+b[h],c,d,!0);continue}p=f.event.special[j]||{},j=(d?p.delegateType:p.bindType)||j,r=o[j]||[],m=r.length,l=l?new RegExp("(^|\\.)"+l.split(".").sort().join("\\.(?:.*\\.)?")+"(\\.|$)"):null;for(n=0;n<r.length;n++)s=r[n],(e||k===s.origType)&&(!c||c.guid===s.guid)&&(!l||l.test(s.namespace))&&(!d||d===s.selector||d==="**"&&s.selector)&&(r.splice(n--,1),s.selector&&r.delegateCount--,p.remove&&p.remove.call(a,s));r.length===0&&m!==r.length&&((!p.teardown||p.teardown.call(a,l)===!1)&&f.removeEvent(a,j,g.handle),delete o[j])}f.isEmptyObject(o)&&(q=g.handle,q&&(q.elem=null),f.removeData(a,["events","handle"],!0))}},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,e,g){if(!e||e.nodeType!==3&&e.nodeType!==8){var h=c.type||c,i=[],j,k,l,m,n,o,p,q,r,s;if(E.test(h+f.event.triggered))return;h.indexOf("!")>=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"";if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,m=E.test(s+h)?e:e.parentNode,n=null;for(;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;l<r.length&&!c.isPropagationStopped();l++)m=r[l][0],c.type=r[l][1],q=(f._data(m,"events")||{})[c.type]&&f._data(m,"handle"),q&&q.apply(m,d),q=o&&m[o],q&&f.acceptData(m)&&q.apply(m,d)===!1&&c.preventDefault();c.type=h,!g&&!c.isDefaultPrevented()&&(!p._default||p._default.apply(e.ownerDocument,d)===!1)&&(h!=="click"||!f.nodeName(e,"a"))&&f.acceptData(e)&&o&&e[h]&&(h!=="focus"&&h!=="blur"||c.target.offsetWidth!==0)&&!f.isWindow(e)&&(n=e[o],n&&(e[o]=null),f.event.triggered=h,e[h](),f.event.triggered=b,n&&(e[o]=n));return c.result}},dispatch:function(c){c=f.event.fix(c||a.event);var d=(f._data(this,"events")||{})[c.type]||[],e=d.delegateCount,g=[].slice.call(arguments,0),h=!c.exclusive&&!c.namespace,i=f.event.special[c.type]||{},j=[],k,l,m,n,o,p,q,r,s,t,u;g[0]=c,c.delegateTarget=this;if(!i.preDispatch||i.preDispatch.call(this,c)!==!1){if(e&&(!c.button||c.type!=="click")){n=f(this),n.context=this.ownerDocument||this;for(m=c.target;m!=this;m=m.parentNode||this)if(m.disabled!==!0){p={},r=[],n[0]=m;for(k=0;k<e;k++)s=d[k],t=s.selector,p[t]===b&&(p[t]=s.quick?H(m,s.quick):n.is(t)),p[t]&&r.push(s);r.length&&j.push({elem:m,matches:r})}}d.length>e&&j.push({elem:this,matches:d.slice(e)});for(k=0;k<j.length&&!c.isPropagationStopped();k++){q=j[k],c.currentTarget=q.elem;for(l=0;l<q.matches.length&&!c.isImmediatePropagationStopped();l++){s=q.matches[l];if(h||!c.namespace&&!s.namespace||c.namespace_re&&c.namespace_re.test(s.namespace))c.data=s.data,c.handleObj=s,o=((f.event.special[s.origType]||{}).handle||s.handler).apply(q.elem,g),o!==b&&(c.result=o,o===!1&&(c.preventDefault(),c.stopPropagation()))}}i.postDispatch&&i.postDispatch.call(this,c);return c.result}},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode);return a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,d){var e,f,g,h=d.button,i=d.fromElement;a.pageX==null&&d.clientX!=null&&(e=a.target.ownerDocument||c,f=e.documentElement,g=e.body,a.pageX=d.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=d.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?d.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0);return a}},fix:function(a){if(a[f.expando])return a;var d,e,g=a,h=f.event.fixHooks[a.type]||{},i=h.props?this.props.concat(h.props):this.props;a=f.Event(g);for(d=i.length;d;)e=i[--d],a[e]=g[e];a.target||(a.target=g.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey===b&&(a.metaKey=a.ctrlKey);return h.filter?h.filter(a,g):a},special:{ready:{setup:f.bindReady},load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){f.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=f.extend(new f.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?f.event.trigger(e,null,b):f.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},f.event.handle=f.event.dispatch,f.removeEvent=c.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){a.detachEvent&&a.detachEvent("on"+b,c)},f.Event=function(a,b){if(!(this instanceof f.Event))return new f.Event(a,b);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?K:J):this.type=a,b&&f.extend(this,b),this.timeStamp=a&&a.timeStamp||f.now(),this[f.expando]=!0},f.Event.prototype={preventDefault:function(){this.isDefaultPrevented=K;var a=this.originalEvent;!a||(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=K;var a=this.originalEvent;!a||(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=K,this.stopPropagation()},isDefaultPrevented:J,isPropagationStopped:J,isImmediatePropagationStopped:J},f.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){f.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c=this,d=a.relatedTarget,e=a.handleObj,g=e.selector,h;if(!d||d!==c&&!f.contains(c,d))a.type=e.origType,h=e.handler.apply(this,arguments),a.type=b;return h}}}),f.support.submitBubbles||(f.event.special.submit={setup:function(){if(f.nodeName(this,"form"))return!1;f.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=f.nodeName(c,"input")||f.nodeName(c,"button")?c.form:b;d&&!d._submit_attached&&(f.event.add(d,"submit._submit",function(a){a._submit_bubble=!0}),d._submit_attached=!0)})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&f.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){if(f.nodeName(this,"form"))return!1;f.event.remove(this,"._submit")}}),f.support.changeBubbles||(f.event.special.change={setup:function(){if(z.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")f.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),f.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1,f.event.simulate("change",this,a,!0))});return!1}f.event.add(this,"beforeactivate._change",function(a){var b=a.target;z.test(b.nodeName)&&!b._change_attached&&(f.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&!a.isTrigger&&f.event.simulate("change",this.parentNode,a,!0)}),b._change_attached=!0)})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this,arguments)},teardown:function(){f.event.remove(this,"._change");return z.test(this.nodeName)}}),f.support.focusinBubbles||f.each({focus:"focusin",blur:"focusout"},function(a,b){var d=0,e=function(a){f.event.simulate(b,a.target,f.event.fix(a),!0)};f.event.special[b]={setup:function(){d++===0&&c.addEventListener(a,e,!0)},teardown:function(){--d===0&&c.removeEventListener(a,e,!0)}}}),f.fn.extend({on:function(a,c,d,e,g){var h,i;if(typeof a=="object"){typeof c!="string"&&(d=d||c,c=b);for(i in a)this.on(i,c,d,a[i],g);return this}d==null&&e==null?(e=c,d=c=b):e==null&&(typeof c=="string"?(e=d,d=b):(e=d,d=c,c=b));if(e===!1)e=J;else if(!e)return this;g===1&&(h=e,e=function(a){f().off(a);return h.apply(this,arguments)},e.guid=h.guid||(h.guid=f.guid++));return this.each(function(){f.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,c,d){if(a&&a.preventDefault&&a.handleObj){var e=a.handleObj;f(a.delegateTarget).off(e.namespace?e.origType+"."+e.namespace:e.origType,e.selector,e.handler);return this}if(typeof a=="object"){for(var g in a)this.off(g,c,a[g]);return this}if(c===!1||typeof c=="function")d=c,c=b;d===!1&&(d=J);return this.each(function(){f.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){f(this.context).on(a,this.selector,b,c);return this},die:function(a,b){f(this.context).off(a,this.selector||"**",b);return this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return arguments.length==1?this.off(a,"**"):this.off(b,a,c)},trigger:function(a,b){return this.each(function(){f.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return f.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||f.guid++,d=0,e=function(c){var e=(f._data(this,"lastToggle"+a.guid)||0)%d;f._data(this,"lastToggle"+a.guid,e+1),c.preventDefault();return b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),f.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 contextmenu".split(" "),function(a,b){f.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.on(b,null,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),C.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),D.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}if(j.nodeType===1){g||(j[d]=c,j.sizset=h);if(typeof b!="string"){if(j===b){k=!0;break}}else if(m.filter(b,[j]).length>0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}j.nodeType===1&&!g&&(j[d]=c,j.sizset=h);if(j.nodeName.toLowerCase()===b){k=j;break}j=j[a]}e[h]=k}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},m.matches=function(a,b){return m(a,null,null,b)},m.matchesSelector=function(a,b){return m(b,null,null,[a]).length>0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e<f;e++){h=o.order[e];if(g=o.leftMatch[h].exec(a)){i=g[1],g.splice(1,1);if(i.substr(i.length-1)!=="\\"){g[1]=(g[1]||"").replace(j,""),d=o.find[h](g,b,c);if(d!=null){a=a.replace(o.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},m.filter=function(a,c,d,e){var f,g,h,i,j,k,l,n,p,q=a,r=[],s=c,t=c&&c[0]&&m.isXML(c[0]);while(a&&c.length){for(h in o.filter)if((f=o.leftMatch[h].exec(a))!=null&&f[2]){k=o.filter[h],l=f[1],g=!1,f.splice(1,1);if(l.substr(l.length-1)==="\\")continue;s===r&&(r=[]);if(o.preFilter[h]){f=o.preFilter[h](f,s,d,r,e,t);if(!f)g=i=!0;else if(f===!0)continue}if(f)for(n=0;(j=s[n])!=null;n++)j&&(i=k(j,f,n,s),p=e^i,d&&i!=null?p?g=!0:s[n]=!1:p&&(r.push(j),g=!0));if(i!==b){d||(s=r),a=a.replace(o.match[h],"");if(!g)return[];break}}if(a===q)if(g==null)m.error(a);else break;q=a}return s},m.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)};var n=m.getText=function(a){var b,c,d=a.nodeType,e="";if(d){if(d===1||d===9||d===11){if(typeof a.textContent=="string")return a.textContent;if(typeof a.innerText=="string")return a.innerText.replace(k,"");for(a=a.firstChild;a;a=a.nextSibling)e+=n(a)}else if(d===3||d===4)return a.nodeValue}else for(b=0;c=a[b];b++)c.nodeType!==8&&(e+=n(c));return e},o=m.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|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(a){return a.getAttribute("href")},type:function(a){return a.getAttribute("type")}},relative:{"+":function(a,b){var c=typeof b=="string",d=c&&!l.test(b),e=c&&!d;d&&(b=b.toLowerCase());for(var f=0,g=a.length,h;f<g;f++)if(h=a[f]){while((h=h.previousSibling)&&h.nodeType!==1);a[f]=e||h&&h.nodeName.toLowerCase()===b?h||!1:h===b}e&&m.filter(b,a,!0)},">":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e<f;e++){c=a[e];if(c){var g=c.parentNode;a[e]=g.nodeName.toLowerCase()===b?g:!1}}}else{for(;e<f;e++)c=a[e],c&&(a[e]=d?c.parentNode:c.parentNode===b);d&&m.filter(b,a,!0)}},"":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("parentNode",b,f,a,d,c)},"~":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("previousSibling",b,f,a,d,c)}},find:{ID:function(a,b,c){if(typeof b.getElementById!="undefined"&&!c){var d=b.getElementById(a[1]);return d&&d.parentNode?[d]:[]}},NAME:function(a,b){if(typeof b.getElementsByName!="undefined"){var c=[],d=b.getElementsByName(a[1]);for(var e=0,f=d.length;e<f;e++)d[e].getAttribute("name")===a[1]&&c.push(d[e]);return c.length===0?null:c}},TAG:function(a,b){if(typeof b.getElementsByTagName!="undefined")return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(j,"")+" ";if(f)return a;for(var g=0,h;(h=b[g])!=null;g++)h&&(e^(h.className&&(" "+h.className+" ").replace(/[\t\n\r]/g," ").indexOf(a)>=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return b<c[3]-0},gt:function(a,b,c){return b>c[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h<i;h++)if(g[h]===a)return!1;return!0}m.error(e)},CHILD:function(a,b){var c,e,f,g,h,i,j,k=b[1],l=a;switch(k){case"only":case"first":while(l=l.previousSibling)if(l.nodeType===1)return!1;if(k==="first")return!0;l=a;case"last":while(l=l.nextSibling)if(l.nodeType===1)return!1;return!0;case"nth":c=b[2],e=b[3];if(c===1&&e===0)return!0;f=b[0],g=a.parentNode;if(g&&(g[d]!==f||!a.nodeIndex)){i=0;for(l=g.firstChild;l;l=l.nextSibling)l.nodeType===1&&(l.nodeIndex=++i);g[d]=f}j=a.nodeIndex-e;return c===0?j===0:j%c===0&&j/c>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));o.match.globalPOS=p;var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c<e;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var u,v;c.documentElement.compareDocumentPosition?u=function(a,b){if(a===b){h=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(u=function(a,b){if(a===b){h=!0;return 0}if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],g=a.parentNode,i=b.parentNode,j=g;if(g===i)return v(a,b);if(!g)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;k<c&&k<d;k++)if(e[k]!==f[k])return v(e[k],f[k]);return k===c?v(a,f[k],-1):v(e[k],b,1)},v=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),function(){var a=c.createElement("div"),d="script"+(new Date).getTime(),e=c.documentElement;a.innerHTML="<a name='"+d+"'/>",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h<i;h++)m(a,g[h],e,c);return m.filter(f,e)};m.attr=f.attr,m.selectors.attrMap={},f.find=m,f.expr=m.selectors,f.expr[":"]=f.expr.filters,f.unique=m.uniqueSort,f.text=m.getText,f.isXMLDoc=m.isXML,f.contains=m.contains}();var L=/Until$/,M=/^(?:parents|prevUntil|prevAll)/,N=/,/,O=/^.[^:#\[\.,]*$/,P=Array.prototype.slice,Q=f.expr.match.globalPOS,R={children:!0,contents:!0,next:!0,prev:!0};f.fn.extend({find:function(a){var b=this,c,d;if(typeof a!="string")return f(a).filter(function(){for(c=0,d=b.length;c<d;c++)if(f.contains(b[c],this))return!0});var e=this.pushStack("","find",a),g,h,i;for(c=0,d=this.length;c<d;c++){g=e.length,f.find(a,this[c],e);if(c>0)for(h=g;h<e.length;h++)for(i=0;i<g;i++)if(e[i]===e[h]){e.splice(h--,1);break}}return e},has:function(a){var b=f(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(f.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(T(this,a,!1),"not",a)},filter:function(a){return this.pushStack(T(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?Q.test(a)?f(a,this.context).index(this[0])>=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d<a.length;d++)f(g).is(a[d])&&c.push({selector:a[d],elem:g,level:h});g=g.parentNode,h++}return c}var i=Q.test(a)||typeof a!="string"?f(a,b||this.context):0;for(d=0,e=this.length;d<e;d++){g=this[d];while(g){if(i?i.index(g)>-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(S(c[0])||S(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c);L.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!R[a]?f.unique(e):e,(this.length>1||N.test(d))&&M.test(a)&&(e=e.reverse());return this.pushStack(e,a,P.call(arguments).join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var V="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",W=/ jQuery\d+="(?:\d+|null)"/g,X=/^\s+/,Y=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Z=/<([\w:]+)/,$=/<tbody/i,_=/<|&#?\w+;/,ba=/<(?:script|style)/i,bb=/<(?:script|object|embed|option|style)/i,bc=new RegExp("<(?:"+V+")[\\s/>]","i"),bd=/checked\s*(?:[^=]|=\s*.checked.)/i,be=/\/(java|ecma)script/i,bf=/^\s*<!(?:\[CDATA\[|\-\-)/,bg={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,"",""]},bh=U(c);bg.optgroup=bg.option,bg.tbody=bg.tfoot=bg.colgroup=bg.caption=bg.thead,bg.th=bg.td,f.support.htmlSerialize||(bg._default=[1,"div<div>","</div>"]),f.fn.extend({text:function(a){return f.access(this,function(a){return a===b?f.text(this):this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=f.isFunction(a);return this.each(function(c){f(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f
+.clean(arguments);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,f.clean(arguments));return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){return f.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(W,""):null;if(typeof a=="string"&&!ba.test(a)&&(f.support.leadingWhitespace||!X.test(a))&&!bg[(Z.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Y,"<$1></$2>");try{for(;d<e;d++)c=this[d]||{},c.nodeType===1&&(f.cleanData(c.getElementsByTagName("*")),c.innerHTML=a);c=0}catch(g){}}c&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(f.isFunction(a))return this.each(function(b){var c=f(this),d=c.html();c.replaceWith(a.call(this,b,d))});typeof a!="string"&&(a=f(a).detach());return this.each(function(){var b=this.nextSibling,c=this.parentNode;f(this).remove(),b?f(b).before(a):f(c).append(a)})}return this.length?this.pushStack(f(f.isFunction(a)?a():a),"replaceWith",a):this},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){var e,g,h,i,j=a[0],k=[];if(!f.support.checkClone&&arguments.length===3&&typeof j=="string"&&bd.test(j))return this.each(function(){f(this).domManip(a,c,d,!0)});if(f.isFunction(j))return this.each(function(e){var g=f(this);a[0]=j.call(this,e,c?g.html():b),g.domManip(a,c,d)});if(this[0]){i=j&&j.parentNode,f.support.parentNode&&i&&i.nodeType===11&&i.childNodes.length===this.length?e={fragment:i}:e=f.buildFragment(a,this,k),h=e.fragment,h.childNodes.length===1?g=h=h.firstChild:g=h.firstChild;if(g){c=c&&f.nodeName(g,"tr");for(var l=0,m=this.length,n=m-1;l<m;l++)d.call(c?bi(this[l],g):this[l],e.cacheable||m>1&&l<n?f.clone(h,!0,!0):h)}k.length&&f.each(k,function(a,b){b.src?f.ajax({type:"GET",global:!1,url:b.src,async:!1,dataType:"script"}):f.globalEval((b.text||b.textContent||b.innerHTML||"").replace(bf,"/*$0*/")),b.parentNode&&b.parentNode.removeChild(b)})}return this}}),f.buildFragment=function(a,b,d){var e,g,h,i,j=a[0];b&&b[0]&&(i=b[0].ownerDocument||b[0]),i.createDocumentFragment||(i=c),a.length===1&&typeof j=="string"&&j.length<512&&i===c&&j.charAt(0)==="<"&&!bb.test(j)&&(f.support.checkClone||!bd.test(j))&&(f.support.html5Clone||!bc.test(j))&&(g=!0,h=f.fragments[j],h&&h!==1&&(e=h)),e||(e=i.createDocumentFragment(),f.clean(a,i,e,d)),g&&(f.fragments[j]=h?e:1);return{fragment:e,cacheable:g}},f.fragments={},f.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){f.fn[a]=function(c){var d=[],e=f(c),g=this.length===1&&this[0].parentNode;if(g&&g.nodeType===11&&g.childNodes.length===1&&e.length===1){e[b](this[0]);return this}for(var h=0,i=e.length;h<i;h++){var j=(h>0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d,e,g,h=f.support.html5Clone||f.isXMLDoc(a)||!bc.test("<"+a.nodeName+">")?a.cloneNode(!0):bo(a);if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bk(a,h),d=bl(a),e=bl(h);for(g=0;d[g];++g)e[g]&&bk(d[g],e[g])}if(b){bj(a,h);if(c){d=bl(a),e=bl(h);for(g=0;d[g];++g)bj(d[g],e[g])}}d=e=null;return h},clean:function(a,b,d,e){var g,h,i,j=[];b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);for(var k=0,l;(l=a[k])!=null;k++){typeof l=="number"&&(l+="");if(!l)continue;if(typeof l=="string")if(!_.test(l))l=b.createTextNode(l);else{l=l.replace(Y,"<$1></$2>");var m=(Z.exec(l)||["",""])[1].toLowerCase(),n=bg[m]||bg._default,o=n[0],p=b.createElement("div"),q=bh.childNodes,r;b===c?bh.appendChild(p):U(b).appendChild(p),p.innerHTML=n[1]+l+n[2];while(o--)p=p.lastChild;if(!f.support.tbody){var s=$.test(l),t=m==="table"&&!s?p.firstChild&&p.firstChild.childNodes:n[1]==="<table>"&&!s?p.childNodes:[];for(i=t.length-1;i>=0;--i)f.nodeName(t[i],"tbody")&&!t[i].childNodes.length&&t[i].parentNode.removeChild(t[i])}!f.support.leadingWhitespace&&X.test(l)&&p.insertBefore(b.createTextNode(X.exec(l)[0]),p.firstChild),l=p.childNodes,p&&(p.parentNode.removeChild(p),q.length>0&&(r=q[q.length-1],r&&r.parentNode&&r.parentNode.removeChild(r)))}var u;if(!f.support.appendChecked)if(l[0]&&typeof (u=l.length)=="number")for(i=0;i<u;i++)bn(l[i]);else bn(l);l.nodeType?j.push(l):j=f.merge(j,l)}if(d){g=function(a){return!a.type||be.test(a.type)};for(k=0;j[k];k++){h=j[k];if(e&&f.nodeName(h,"script")&&(!h.type||be.test(h.type)))e.push(h.parentNode?h.parentNode.removeChild(h):h);else{if(h.nodeType===1){var v=f.grep(h.getElementsByTagName("script"),g);j.splice.apply(j,[k+1,0].concat(v))}d.appendChild(h)}}}return j},cleanData:function(a){var b,c,d=f.cache,e=f.event.special,g=f.support.deleteExpando;for(var h=0,i;(i=a[h])!=null;h++){if(i.nodeName&&f.noData[i.nodeName.toLowerCase()])continue;c=i[f.expando];if(c){b=d[c];if(b&&b.events){for(var j in b.events)e[j]?f.event.remove(i,j):f.removeEvent(i,j,b.handle);b.handle&&(b.handle.elem=null)}g?delete i[f.expando]:i.removeAttribute&&i.removeAttribute(f.expando),delete d[c]}}}});var bp=/alpha\([^)]*\)/i,bq=/opacity=([^)]*)/,br=/([A-Z]|^ms)/g,bs=/^[\-+]?(?:\d*\.)?\d+$/i,bt=/^-?(?:\d*\.)?\d+(?!px)[^\d\s]+$/i,bu=/^([\-+])=([\-+.\de]+)/,bv=/^margin/,bw={position:"absolute",visibility:"hidden",display:"block"},bx=["Top","Right","Bottom","Left"],by,bz,bA;f.fn.css=function(a,c){return f.access(this,function(a,c,d){return d!==b?f.style(a,c,d):f.css(a,c)},a,c,arguments.length>1)},f.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=by(a,"opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":f.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!!a&&a.nodeType!==3&&a.nodeType!==8&&!!a.style){var g,h,i=f.camelCase(c),j=a.style,k=f.cssHooks[i];c=f.cssProps[i]||i;if(d===b){if(k&&"get"in k&&(g=k.get(a,!1,e))!==b)return g;return j[c]}h=typeof d,h==="string"&&(g=bu.exec(d))&&(d=+(g[1]+1)*+g[2]+parseFloat(f.css(a,c)),h="number");if(d==null||h==="number"&&isNaN(d))return;h==="number"&&!f.cssNumber[i]&&(d+="px");if(!k||!("set"in k)||(d=k.set(a,d))!==b)try{j[c]=d}catch(l){}}},css:function(a,c,d){var e,g;c=f.camelCase(c),g=f.cssHooks[c],c=f.cssProps[c]||c,c==="cssFloat"&&(c="float");if(g&&"get"in g&&(e=g.get(a,!0,d))!==b)return e;if(by)return by(a,c)},swap:function(a,b,c){var d={},e,f;for(f in b)d[f]=a.style[f],a.style[f]=b[f];e=c.call(a);for(f in b)a.style[f]=d[f];return e}}),f.curCSS=f.css,c.defaultView&&c.defaultView.getComputedStyle&&(bz=function(a,b){var c,d,e,g,h=a.style;b=b.replace(br,"-$1").toLowerCase(),(d=a.ownerDocument.defaultView)&&(e=d.getComputedStyle(a,null))&&(c=e.getPropertyValue(b),c===""&&!f.contains(a.ownerDocument.documentElement,a)&&(c=f.style(a,b))),!f.support.pixelMargin&&e&&bv.test(b)&&bt.test(c)&&(g=h.width,h.width=c,c=e.width,h.width=g);return c}),c.documentElement.currentStyle&&(bA=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f==null&&g&&(e=g[b])&&(f=e),bt.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),by=bz||bA,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth!==0?bB(a,b,d):f.swap(a,bw,function(){return bB(a,b,d)})},set:function(a,b){return bs.test(b)?b+"px":b}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return bq.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bp,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bp.test(g)?g.replace(bp,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){return f.swap(a,{display:"inline-block"},function(){return b?by(a,"margin-right"):a.style.marginRight})}})}),f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)}),f.each({margin:"",padding:"",border:"Width"},function(a,b){f.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bx[d]+b]=e[d]||e[d-2]||e[0];return f}}});var bC=/%20/g,bD=/\[\]$/,bE=/\r?\n/g,bF=/#.*$/,bG=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bH=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bI=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bJ=/^(?:GET|HEAD)$/,bK=/^\/\//,bL=/\?/,bM=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bN=/^(?:select|textarea)/i,bO=/\s+/,bP=/([?&])_=[^&]*/,bQ=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bR=f.fn.load,bS={},bT={},bU,bV,bW=["*/"]+["*"];try{bU=e.href}catch(bX){bU=c.createElement("a"),bU.href="",bU=bU.href}bV=bQ.exec(bU.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bR)return bR.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("<div>").append(c.replace(bM,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bN.test(this.nodeName)||bH.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bE,"\r\n")}}):{name:b.name,value:c.replace(bE,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.on(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?b$(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),b$(a,b);return a},ajaxSettings:{url:bU,isLocal:bI.test(bV[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":bW},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:bY(bS),ajaxTransport:bY(bT),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?ca(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=cb(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bG.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bF,"").replace(bK,bV[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bO),d.crossDomain==null&&(r=bQ.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bV[1]&&r[2]==bV[2]&&(r[3]||(r[1]==="http:"?80:443))==(bV[3]||(bV[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),bZ(bS,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bJ.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bL.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bP,"$1_="+x);d.url=y+(y===d.url?(bL.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bW+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=bZ(bT,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){if(s<2)w(-1,z);else throw z}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)b_(g,a[g],c,e);return d.join("&").replace(bC,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cc=f.now(),cd=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cc++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=typeof b.data=="string"&&/^application\/x\-www\-form\-urlencoded/.test(b.contentType);if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(cd.test(b.url)||e&&cd.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(cd,l),b.url===j&&(e&&(k=k.replace(cd,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var ce=a.ActiveXObject?function(){for(var a in cg)cg[a](0,1)}:!1,cf=0,cg;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ch()||ci()}:ch,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,ce&&delete cg[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n);try{m.text=h.responseText}catch(a){}try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++cf,ce&&(cg||(cg={},f(a).unload(ce)),cg[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var cj={},ck,cl,cm=/^(?:toggle|show|hide)$/,cn=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,co,cp=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cq;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(ct("show",3),a,b,c);for(var g=0,h=this.length;g<h;g++)d=this[g],d.style&&(e=d.style.display,!f._data(d,"olddisplay")&&e==="none"&&(e=d.style.display=""),(e===""&&f.css(d,"display")==="none"||!f.contains(d.ownerDocument.documentElement,d))&&f._data(d,"olddisplay",cu(d.nodeName)));for(g=0;g<h;g++){d=this[g];if(d.style){e=d.style.display;if(e===""||e==="none")d.style.display=f._data(d,"olddisplay")||""}}return this},hide:function(a,b,c){if(a||a===0)return this.animate(ct("hide",3),a,b,c);var d,e,g=0,h=this.length;for(;g<h;g++)d=this[g],d.style&&(e=f.css(d,"display"),e!=="none"&&!f._data(d,"olddisplay")&&f._data(d,"olddisplay",e));for(g=0;g<h;g++)this[g].style&&(this[g].style.display="none");return this},_toggle:f.fn.toggle,toggle:function(a,b,c){var d=typeof a=="boolean";f.isFunction(a)&&f.isFunction(b)?this._toggle.apply(this,arguments):a==null||d?this.each(function(){var b=d?a:f(this).is(":hidden");f(this)[b?"show":"hide"]()}):this.animate(ct("toggle",3),a,b,c);return this},fadeTo:function(a,b,c,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){function g(){e.queue===!1&&f._mark(this);var b=f.extend({},e),c=this.nodeType===1,d=c&&f(this).is(":hidden"),g,h,i,j,k,l,m,n,o,p,q;b.animatedProperties={};for(i in a){g=f.camelCase(i),i!==g&&(a[g]=a[i],delete a[i]);if((k=f.cssHooks[g])&&"expand"in k){l=k.expand(a[g]),delete a[g];for(i in l)i in a||(a[i]=l[i])}}for(g in a){h=a[g],f.isArray(h)?(b.animatedProperties[g]=h[1],h=a[g]=h[0]):b.animatedProperties[g]=b.specialEasing&&b.specialEasing[g]||b.easing||"swing";if(h==="hide"&&d||h==="show"&&!d)return b.complete.call(this);c&&(g==="height"||g==="width")&&(b.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY],f.css(this,"display")==="inline"&&f.css(this,"float")==="none"&&(!f.support.inlineBlockNeedsLayout||cu(this.nodeName)==="inline"?this.style.display="inline-block":this.style.zoom=1))}b.overflow!=null&&(this.style.overflow="hidden");for(i in a)j=new f.fx(this,b,i),h=a[i],cm.test(h)?(q=f._data(this,"toggle"+i)||(h==="toggle"?d?"show":"hide":0),q?(f._data(this,"toggle"+i,q==="show"?"hide":"show"),j[q]()):j[h]()):(m=cn.exec(h),n=j.cur(),m?(o=parseFloat(m[2]),p=m[3]||(f.cssNumber[i]?"":"px"),p!=="px"&&(f.style(this,i,(o||1)+p),n=(o||1)/j.cur()*n,f.style(this,i,n+p)),m[1]&&(o=(m[1]==="-="?-1:1)*o+n),j.custom(n,o,p)):j.custom(n,h,""));return!0}var e=f.speed(b,c,d);if(f.isEmptyObject(a))return this.each(e.complete,[!1]);a=f.extend({},a);return e.queue===!1?this.each(g):this.queue(e.queue,g)},stop:function(a,c,d){typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]);return this.each(function(){function h(a,b,c){var e=b[c];f.removeData(a,c,!0),e.stop(d)}var b,c=!1,e=f.timers,g=f._data(this);d||f._unmark(!0,this);if(a==null)for(b in g)g[b]&&g[b].stop&&b.indexOf(".run")===b.length-4&&h(this,g,b);else g[b=a+".run"]&&g[b].stop&&h(this,g,b);for(b=e.length;b--;)e[b].elem===this&&(a==null||e[b].queue===a)&&(d?e[b](!0):e[b].saveState(),c=!0,e.splice(b,1));(!d||!c)&&f.dequeue(this,a)})}}),f.each({slideDown:ct("show",1),slideUp:ct("hide",1),slideToggle:ct("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){f.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),f.extend({speed:function(a,b,c){var d=a&&typeof a=="object"?f.extend({},a):{complete:c||!c&&b||f.isFunction(a)&&a,duration:a,easing:c&&b||b&&!f.isFunction(b)&&b};d.duration=f.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in f.fx.speeds?f.fx.speeds[d.duration]:f.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";d.old=d.complete,d.complete=function(a){f.isFunction(d.old)&&d.old.call(this),d.queue?f.dequeue(this,d.queue):a!==!1&&f._unmark(this)};return d},easing:{linear:function(a){return a},swing:function(a){return-Math.cos(a*Math.PI)/2+.5}},timers:[],fx:function(a,b,c){this.options=b,this.elem=a,this.prop=c,b.orig=b.orig||{}}}),f.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this),(f.fx.step[this.prop]||f.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,b=f.css(this.elem,this.prop);return isNaN(a=parseFloat(b))?!b||b==="auto"?0:b:a},custom:function(a,c,d){function h(a){return e.step(a)}var e=this,g=f.fx;this.startTime=cq||cr(),this.end=c,this.now=this.start=a,this.pos=this.state=0,this.unit=d||this.unit||(f.cssNumber[this.prop]?"":"px"),h.queue=this.options.queue,h.elem=this.elem,h.saveState=function(){f._data(e.elem,"fxshow"+e.prop)===b&&(e.options.hide?f._data(e.elem,"fxshow"+e.prop,e.start):e.options.show&&f._data(e.elem,"fxshow"+e.prop,e.end))},h()&&f.timers.push(h)&&!co&&(co=setInterval(g.tick,g.interval))},show:function(){var a=f._data(this.elem,"fxshow"+this.prop);this.options.orig[this.prop]=a||f.style(this.elem,this.prop),this.options.show=!0,a!==b?this.custom(this.cur(),a):this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),f(this.elem).show()},hide:function(){this.options.orig[this.prop]=f._data(this.elem,"fxshow"+this.prop)||f.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b,c,d,e=cq||cr(),g=!0,h=this.elem,i=this.options;if(a||e>=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||f.fx.stop()},interval:13,stop:function(){clearInterval(co),co=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){f.style(a.elem,"opacity",a.now)},_default:function(a){a.elem.style&&a.elem.style[a.prop]!=null?a.elem.style[a.prop]=a.now+a.unit:a.elem[a.prop]=a.now}}}),f.each(cp.concat.apply([],cp),function(a,b){b.indexOf("margin")&&(f.fx.step[b]=function(a){f.style(a.elem,b,Math.max(0,a.now)+a.unit)})}),f.expr&&f.expr.filters&&(f.expr.filters.animated=function(a){return f.grep(f.timers,function(b){return a===b.elem}).length});var cv,cw=/^t(?:able|d|h)$/i,cx=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?cv=function(a,b,c,d){try{d=a.getBoundingClientRect()}catch(e){}if(!d||!f.contains(c,a))return d?{top:d.top,left:d.left}:{top:0,left:0};var g=b.body,h=cy(b),i=c.clientTop||g.clientTop||0,j=c.clientLeft||g.clientLeft||0,k=h.pageYOffset||f.support.boxModel&&c.scrollTop||g.scrollTop,l=h.pageXOffset||f.support.boxModel&&c.scrollLeft||g.scrollLeft,m=d.top+k-i,n=d.left+l-j;return{top:m,left:n}}:cv=function(a,b,c){var d,e=a.offsetParent,g=a,h=b.body,i=b.defaultView,j=i?i.getComputedStyle(a,null):a.currentStyle,k=a.offsetTop,l=a.offsetLeft;while((a=a.parentNode)&&a!==h&&a!==c){if(f.support.fixedPosition&&j.position==="fixed")break;d=i?i.getComputedStyle(a,null):a.currentStyle,k-=a.scrollTop,l-=a.scrollLeft,a===e&&(k+=a.offsetTop,l+=a.offsetLeft,f.support.doesNotAddBorder&&(!f.support.doesAddBorderForTableAndCells||!cw.test(a.nodeName))&&(k+=parseFloat(d.borderTopWidth)||0,l+=parseFloat(d.borderLeftWidth)||0),g=e,e=a.offsetParent),f.support.subtractsBorderForOverflowNotVisible&&d.overflow!=="visible"&&(k+=parseFloat(d.borderTopWidth)||0,l+=parseFloat(d.borderLeftWidth)||0),j=d}if(j.position==="relative"||j.position==="static")k+=h.offsetTop,l+=h.offsetLeft;f.support.fixedPosition&&j.position==="fixed"&&(k+=Math.max(c.scrollTop,h.scrollTop),l+=Math.max(c.scrollLeft,h.scrollLeft));return{top:k,left:l}},f.fn.offset=function(a){if(arguments.length)return a===b?this:this.each(function(b){f.offset.setOffset(this,a,b)});var c=this[0],d=c&&c.ownerDocument;if(!d)return null;if(c===d.body)return f.offset.bodyOffset(c);return cv(c,d,d.documentElement)},f.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;f.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(f.css(a,"marginTop"))||0,c+=parseFloat(f.css(a,"marginLeft"))||0);return{top:b,left:c}},setOffset:function(a,b,c){var d=f.css(a,"position");d==="static"&&(a.style.position="relative");var e=f(a),g=e.offset(),h=f.css(a,"top"),i=f.css(a,"left"),j=(d==="absolute"||d==="fixed")&&f.inArray("auto",[h,i])>-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cx.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cx.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);f.fn[a]=function(e){return f.access(this,function(a,e,g){var h=cy(a);if(g===b)return h?c in h?h[c]:f.support.boxModel&&h.document.documentElement[e]||h.document.body[e]:a[e];h?h.scrollTo(d?f(h).scrollLeft():g,d?g:f(h).scrollTop()):a[e]=g},a,e,arguments.length,null)}}),f.each({Height:"height",Width:"width"},function(a,c){var d="client"+a,e="scroll"+a,g="offset"+a;f.fn["inner"+a]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,c,"padding")):this[c]():null},f.fn["outer"+a]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,c,a?"margin":"border")):this[c]():null},f.fn[c]=function(a){return f.access(this,function(a,c,h){var i,j,k,l;if(f.isWindow(a)){i=a.document,j=i.documentElement[d];return f.support.boxModel&&j||i.body&&i.body[d]||j}if(a.nodeType===9){i=a.documentElement;if(i[d]>=i[e])return i[d];return Math.max(a.body[e],i[e],a.body[g],i[g])}if(h===b){k=f.css(a,c),l=parseFloat(k);return f.isNumeric(l)?l:k}f(a).css(c,h)},c,a,arguments.length,null)}}),a.jQuery=a.$=f,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return f})})(window);
\ No newline at end of file
diff --git a/plugins/pres_view/static/js/mootools-core.js b/plugins/pres_view/static/js/mootools-core.js
new file mode 100644 (file)
index 0000000..0098571
--- /dev/null
@@ -0,0 +1,4329 @@
+/*
+---
+
+script: Core.js
+
+description: The core of MooTools, contains all the base functions and the Native and Hash implementations. Required by all the other scripts.
+
+license: MIT-style license.
+
+copyright: Copyright (c) 2006-2008 [Valerio Proietti](http://mad4milk.net/).
+
+authors: The MooTools production team (http://mootools.net/developers/)
+
+inspiration:
+- Class implementation inspired by [Base.js](http://dean.edwards.name/weblog/2006/03/base/) Copyright (c) 2006 Dean Edwards, [GNU Lesser General Public License](http://opensource.org/licenses/lgpl-license.php)
+- Some functionality inspired by [Prototype.js](http://prototypejs.org) Copyright (c) 2005-2007 Sam Stephenson, [MIT License](http://opensource.org/licenses/mit-license.php)
+
+provides: [Mootools, Native, Hash.base, Array.each, $util]
+
+...
+*/
+
+var MooTools = {
+       'version': '1.2.4',
+       'build': '0d9113241a90b9cd5643b926795852a2026710d4'
+};
+
+var Native = function(options){
+       options = options || {};
+       var name = options.name;
+       var legacy = options.legacy;
+       var protect = options.protect;
+       var methods = options.implement;
+       var generics = options.generics;
+       var initialize = options.initialize;
+       var afterImplement = options.afterImplement || function(){};
+       var object = initialize || legacy;
+       generics = generics !== false;
+
+       object.constructor = Native;
+       object.$family = {name: 'native'};
+       if (legacy && initialize) object.prototype = legacy.prototype;
+       object.prototype.constructor = object;
+
+       if (name){
+               var family = name.toLowerCase();
+               object.prototype.$family = {name: family};
+               Native.typize(object, family);
+       }
+
+       var add = function(obj, name, method, force){
+               if (!protect || force || !obj.prototype[name]) obj.prototype[name] = method;
+               if (generics) Native.genericize(obj, name, protect);
+               afterImplement.call(obj, name, method);
+               return obj;
+       };
+
+       object.alias = function(a1, a2, a3){
+               if (typeof a1 == 'string'){
+                       var pa1 = this.prototype[a1];
+                       if ((a1 = pa1)) return add(this, a2, a1, a3);
+               }
+               for (var a in a1) this.alias(a, a1[a], a2);
+               return this;
+       };
+
+       object.implement = function(a1, a2, a3){
+               if (typeof a1 == 'string') return add(this, a1, a2, a3);
+               for (var p in a1) add(this, p, a1[p], a2);
+               return this;
+       };
+
+       if (methods) object.implement(methods);
+
+       return object;
+};
+
+Native.genericize = function(object, property, check){
+       if ((!check || !object[property]) && typeof object.prototype[property] == 'function') object[property] = function(){
+               var args = Array.prototype.slice.call(arguments);
+               return object.prototype[property].apply(args.shift(), args);
+       };
+};
+
+Native.implement = function(objects, properties){
+       for (var i = 0, l = objects.length; i < l; i++) objects[i].implement(properties);
+};
+
+Native.typize = function(object, family){
+       if (!object.type) object.type = function(item){
+               return ($type(item) === family);
+       };
+};
+
+(function(){
+       var natives = {'Array': Array, 'Date': Date, 'Function': Function, 'Number': Number, 'RegExp': RegExp, 'String': String};
+       for (var n in natives) new Native({name: n, initialize: natives[n], protect: true});
+
+       var types = {'boolean': Boolean, 'native': Native, 'object': Object};
+       for (var t in types) Native.typize(types[t], t);
+
+       var generics = {
+               'Array': ["concat", "indexOf", "join", "lastIndexOf", "pop", "push", "reverse", "shift", "slice", "sort", "splice", "toString", "unshift", "valueOf"],
+               'String': ["charAt", "charCodeAt", "concat", "indexOf", "lastIndexOf", "match", "replace", "search", "slice", "split", "substr", "substring", "toLowerCase", "toUpperCase", "valueOf"]
+       };
+       for (var g in generics){
+               for (var i = generics[g].length; i--;) Native.genericize(natives[g], generics[g][i], true);
+       }
+})();
+
+var Hash = new Native({
+
+       name: 'Hash',
+
+       initialize: function(object){
+               if ($type(object) == 'hash') object = $unlink(object.getClean());
+               for (var key in object) this[key] = object[key];
+               return this;
+       }
+
+});
+
+Hash.implement({
+
+       forEach: function(fn, bind){
+               for (var key in this){
+                       if (this.hasOwnProperty(key)) fn.call(bind, this[key], key, this);
+               }
+       },
+
+       getClean: function(){
+               var clean = {};
+               for (var key in this){
+                       if (this.hasOwnProperty(key)) clean[key] = this[key];
+               }
+               return clean;
+       },
+
+       getLength: function(){
+               var length = 0;
+               for (var key in this){
+                       if (this.hasOwnProperty(key)) length++;
+               }
+               return length;
+       }
+
+});
+
+Hash.alias('forEach', 'each');
+
+Array.implement({
+
+       forEach: function(fn, bind){
+               for (var i = 0, l = this.length; i < l; i++) fn.call(bind, this[i], i, this);
+       }
+
+});
+
+Array.alias('forEach', 'each');
+
+function $A(iterable){
+       if (iterable.item){
+               var l = iterable.length, array = new Array(l);
+               while (l--) array[l] = iterable[l];
+               return array;
+       }
+       return Array.prototype.slice.call(iterable);
+};
+
+function $arguments(i){
+       return function(){
+               return arguments[i];
+       };
+};
+
+function $chk(obj){
+       return !!(obj || obj === 0);
+};
+
+function $clear(timer){
+       clearTimeout(timer);
+       clearInterval(timer);
+       return null;
+};
+
+function $defined(obj){
+       return (obj != undefined);
+};
+
+function $each(iterable, fn, bind){
+       var type = $type(iterable);
+       ((type == 'arguments' || type == 'collection' || type == 'array') ? Array : Hash).each(iterable, fn, bind);
+};
+
+function $empty(){};
+
+function $extend(original, extended){
+       for (var key in (extended || {})) original[key] = extended[key];
+       return original;
+};
+
+function $H(object){
+       return new Hash(object);
+};
+
+function $lambda(value){
+       return ($type(value) == 'function') ? value : function(){
+               return value;
+       };
+};
+
+function $merge(){
+       var args = Array.slice(arguments);
+       args.unshift({});
+       return $mixin.apply(null, args);
+};
+
+function $mixin(mix){
+       for (var i = 1, l = arguments.length; i < l; i++){
+               var object = arguments[i];
+               if ($type(object) != 'object') continue;
+               for (var key in object){
+                       var op = object[key], mp = mix[key];
+                       mix[key] = (mp && $type(op) == 'object' && $type(mp) == 'object') ? $mixin(mp, op) : $unlink(op);
+               }
+       }
+       return mix;
+};
+
+function $pick(){
+       for (var i = 0, l = arguments.length; i < l; i++){
+               if (arguments[i] != undefined) return arguments[i];
+       }
+       return null;
+};
+
+function $random(min, max){
+       return Math.floor(Math.random() * (max - min + 1) + min);
+};
+
+function $splat(obj){
+       var type = $type(obj);
+       return (type) ? ((type != 'array' && type != 'arguments') ? [obj] : obj) : [];
+};
+
+var $time = Date.now || function(){
+       return +new Date;
+};
+
+function $try(){
+       for (var i = 0, l = arguments.length; i < l; i++){
+               try {
+                       return arguments[i]();
+               } catch(e){}
+       }
+       return null;
+};
+
+function $type(obj){
+       if (obj == undefined) return false;
+       if (obj.$family) return (obj.$family.name == 'number' && !isFinite(obj)) ? false : obj.$family.name;
+       if (obj.nodeName){
+               switch (obj.nodeType){
+                       case 1: return 'element';
+                       case 3: return (/\S/).test(obj.nodeValue) ? 'textnode' : 'whitespace';
+               }
+       } else if (typeof obj.length == 'number'){
+               if (obj.callee) return 'arguments';
+               else if (obj.item) return 'collection';
+       }
+       return typeof obj;
+};
+
+function $unlink(object){
+       var unlinked;
+       switch ($type(object)){
+               case 'object':
+                       unlinked = {};
+                       for (var p in object) unlinked[p] = $unlink(object[p]);
+               break;
+               case 'hash':
+                       unlinked = new Hash(object);
+               break;
+               case 'array':
+                       unlinked = [];
+                       for (var i = 0, l = object.length; i < l; i++) unlinked[i] = $unlink(object[i]);
+               break;
+               default: return object;
+       }
+       return unlinked;
+};
+
+
+/*
+---
+
+script: Browser.js
+
+description: The Browser Core. Contains Browser initialization, Window and Document, and the Browser Hash.
+
+license: MIT-style license.
+
+requires: 
+- /Native
+- /$util
+
+provides: [Browser, Window, Document, $exec]
+
+...
+*/
+
+var Browser = $merge({
+
+       Engine: {name: 'unknown', version: 0},
+
+       Platform: {name: (window.orientation != undefined) ? 'ipod' : (navigator.platform.match(/mac|win|linux/i) || ['other'])[0].toLowerCase()},
+
+       Features: {xpath: !!(document.evaluate), air: !!(window.runtime), query: !!(document.querySelector)},
+
+       Plugins: {},
+
+       Engines: {
+
+               presto: function(){
+                       return (!window.opera) ? false : ((arguments.callee.caller) ? 960 : ((document.getElementsByClassName) ? 950 : 925));
+               },
+
+               trident: function(){
+                       return (!window.ActiveXObject) ? false : ((window.XMLHttpRequest) ? ((document.querySelectorAll) ? 6 : 5) : 4);
+               },
+
+               webkit: function(){
+                       return (navigator.taintEnabled) ? false : ((Browser.Features.xpath) ? ((Browser.Features.query) ? 525 : 420) : 419);
+               },
+
+               gecko: function(){
+                       return (!document.getBoxObjectFor && window.mozInnerScreenX == null) ? false : ((document.getElementsByClassName) ? 19 : 18);
+               }
+
+       }
+
+}, Browser || {});
+
+Browser.Platform[Browser.Platform.name] = true;
+
+Browser.detect = function(){
+
+       for (var engine in this.Engines){
+               var version = this.Engines[engine]();
+               if (version){
+                       this.Engine = {name: engine, version: version};
+                       this.Engine[engine] = this.Engine[engine + version] = true;
+                       break;
+               }
+       }
+
+       return {name: engine, version: version};
+
+};
+
+Browser.detect();
+
+Browser.Request = function(){
+       return $try(function(){
+               return new XMLHttpRequest();
+       }, function(){
+               return new ActiveXObject('MSXML2.XMLHTTP');
+       }, function(){
+               return new ActiveXObject('Microsoft.XMLHTTP');
+       });
+};
+
+Browser.Features.xhr = !!(Browser.Request());
+
+Browser.Plugins.Flash = (function(){
+       var version = ($try(function(){
+               return navigator.plugins['Shockwave Flash'].description;
+       }, function(){
+               return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version');
+       }) || '0 r0').match(/\d+/g);
+       return {version: parseInt(version[0] || 0 + '.' + version[1], 10) || 0, build: parseInt(version[2], 10) || 0};
+})();
+
+function $exec(text){
+       if (!text) return text;
+       if (window.execScript){
+               window.execScript(text);
+       } else {
+               var script = document.createElement('script');
+               script.setAttribute('type', 'text/javascript');
+               script[(Browser.Engine.webkit && Browser.Engine.version < 420) ? 'innerText' : 'text'] = text;
+               document.head.appendChild(script);
+               document.head.removeChild(script);
+       }
+       return text;
+};
+
+Native.UID = 1;
+
+var $uid = (Browser.Engine.trident) ? function(item){
+       return (item.uid || (item.uid = [Native.UID++]))[0];
+} : function(item){
+       return item.uid || (item.uid = Native.UID++);
+};
+
+var Window = new Native({
+
+       name: 'Window',
+
+       legacy: (Browser.Engine.trident) ? null: window.Window,
+
+       initialize: function(win){
+               $uid(win);
+               if (!win.Element){
+                       win.Element = $empty;
+                       if (Browser.Engine.webkit) win.document.createElement("iframe"); //fixes safari 2
+                       win.Element.prototype = (Browser.Engine.webkit) ? window["[[DOMElement.prototype]]"] : {};
+               }
+               win.document.window = win;
+               return $extend(win, Window.Prototype);
+       },
+
+       afterImplement: function(property, value){
+               window[property] = Window.Prototype[property] = value;
+       }
+
+});
+
+Window.Prototype = {$family: {name: 'window'}};
+
+new Window(window);
+
+var Document = new Native({
+
+       name: 'Document',
+
+       legacy: (Browser.Engine.trident) ? null: window.Document,
+
+       initialize: function(doc){
+               $uid(doc);
+               doc.head = doc.getElementsByTagName('head')[0];
+               doc.html = doc.getElementsByTagName('html')[0];
+               if (Browser.Engine.trident && Browser.Engine.version <= 4) $try(function(){
+                       doc.execCommand("BackgroundImageCache", false, true);
+               });
+               if (Browser.Engine.trident) doc.window.attachEvent('onunload', function(){
+                       doc.window.detachEvent('onunload', arguments.callee);
+                       doc.head = doc.html = doc.window = null;
+               });
+               return $extend(doc, Document.Prototype);
+       },
+
+       afterImplement: function(property, value){
+               document[property] = Document.Prototype[property] = value;
+       }
+
+});
+
+Document.Prototype = {$family: {name: 'document'}};
+
+new Document(document);
+
+
+/*
+---
+
+script: Array.js
+
+description: Contains Array Prototypes like each, contains, and erase.
+
+license: MIT-style license.
+
+requires:
+- /$util
+- /Array.each
+
+provides: [Array]
+
+...
+*/
+
+Array.implement({
+
+       every: function(fn, bind){
+               for (var i = 0, l = this.length; i < l; i++){
+                       if (!fn.call(bind, this[i], i, this)) return false;
+               }
+               return true;
+       },
+
+       filter: function(fn, bind){
+               var results = [];
+               for (var i = 0, l = this.length; i < l; i++){
+                       if (fn.call(bind, this[i], i, this)) results.push(this[i]);
+               }
+               return results;
+       },
+
+       clean: function(){
+               return this.filter($defined);
+       },
+
+       indexOf: function(item, from){
+               var len = this.length;
+               for (var i = (from < 0) ? Math.max(0, len + from) : from || 0; i < len; i++){
+                       if (this[i] === item) return i;
+               }
+               return -1;
+       },
+
+       map: function(fn, bind){
+               var results = [];
+               for (var i = 0, l = this.length; i < l; i++) results[i] = fn.call(bind, this[i], i, this);
+               return results;
+       },
+
+       some: function(fn, bind){
+               for (var i = 0, l = this.length; i < l; i++){
+                       if (fn.call(bind, this[i], i, this)) return true;
+               }
+               return false;
+       },
+
+       associate: function(keys){
+               var obj = {}, length = Math.min(this.length, keys.length);
+               for (var i = 0; i < length; i++) obj[keys[i]] = this[i];
+               return obj;
+       },
+
+       link: function(object){
+               var result = {};
+               for (var i = 0, l = this.length; i < l; i++){
+                       for (var key in object){
+                               if (object[key](this[i])){
+                                       result[key] = this[i];
+                                       delete object[key];
+                                       break;
+                               }
+                       }
+               }
+               return result;
+       },
+
+       contains: function(item, from){
+               return this.indexOf(item, from) != -1;
+       },
+
+       extend: function(array){
+               for (var i = 0, j = array.length; i < j; i++) this.push(array[i]);
+               return this;
+       },
+       
+       getLast: function(){
+               return (this.length) ? this[this.length - 1] : null;
+       },
+
+       getRandom: function(){
+               return (this.length) ? this[$random(0, this.length - 1)] : null;
+       },
+
+       include: function(item){
+               if (!this.contains(item)) this.push(item);
+               return this;
+       },
+
+       combine: function(array){
+               for (var i = 0, l = array.length; i < l; i++) this.include(array[i]);
+               return this;
+       },
+
+       erase: function(item){
+               for (var i = this.length; i--; i){
+                       if (this[i] === item) this.splice(i, 1);
+               }
+               return this;
+       },
+
+       empty: function(){
+               this.length = 0;
+               return this;
+       },
+
+       flatten: function(){
+               var array = [];
+               for (var i = 0, l = this.length; i < l; i++){
+                       var type = $type(this[i]);
+                       if (!type) continue;
+                       array = array.concat((type == 'array' || type == 'collection' || type == 'arguments') ? Array.flatten(this[i]) : this[i]);
+               }
+               return array;
+       },
+
+       hexToRgb: function(array){
+               if (this.length != 3) return null;
+               var rgb = this.map(function(value){
+                       if (value.length == 1) value += value;
+                       return value.toInt(16);
+               });
+               return (array) ? rgb : 'rgb(' + rgb + ')';
+       },
+
+       rgbToHex: function(array){
+               if (this.length < 3) return null;
+               if (this.length == 4 && this[3] == 0 && !array) return 'transparent';
+               var hex = [];
+               for (var i = 0; i < 3; i++){
+                       var bit = (this[i] - 0).toString(16);
+                       hex.push((bit.length == 1) ? '0' + bit : bit);
+               }
+               return (array) ? hex : '#' + hex.join('');
+       }
+
+});
+
+
+/*
+---
+
+script: Function.js
+
+description: Contains Function Prototypes like create, bind, pass, and delay.
+
+license: MIT-style license.
+
+requires:
+- /Native
+- /$util
+
+provides: [Function]
+
+...
+*/
+
+Function.implement({
+
+       extend: function(properties){
+               for (var property in properties) this[property] = properties[property];
+               return this;
+       },
+
+       create: function(options){
+               var self = this;
+               options = options || {};
+               return function(event){
+                       var args = options.arguments;
+                       args = (args != undefined) ? $splat(args) : Array.slice(arguments, (options.event) ? 1 : 0);
+                       if (options.event) args = [event || window.event].extend(args);
+                       var returns = function(){
+                               return self.apply(options.bind || null, args);
+                       };
+                       if (options.delay) return setTimeout(returns, options.delay);
+                       if (options.periodical) return setInterval(returns, options.periodical);
+                       if (options.attempt) return $try(returns);
+                       return returns();
+               };
+       },
+
+       run: function(args, bind){
+               return this.apply(bind, $splat(args));
+       },
+
+       pass: function(args, bind){
+               return this.create({bind: bind, arguments: args});
+       },
+
+       bind: function(bind, args){
+               return this.create({bind: bind, arguments: args});
+       },
+
+       bindWithEvent: function(bind, args){
+               return this.create({bind: bind, arguments: args, event: true});
+       },
+
+       attempt: function(args, bind){
+               return this.create({bind: bind, arguments: args, attempt: true})();
+       },
+
+       delay: function(delay, bind, args){
+               return this.create({bind: bind, arguments: args, delay: delay})();
+       },
+
+       periodical: function(periodical, bind, args){
+               return this.create({bind: bind, arguments: args, periodical: periodical})();
+       }
+
+});
+
+
+/*
+---
+
+script: Number.js
+
+description: Contains Number Prototypes like limit, round, times, and ceil.
+
+license: MIT-style license.
+
+requires:
+- /Native
+- /$util
+
+provides: [Number]
+
+...
+*/
+
+Number.implement({
+
+       limit: function(min, max){
+               return Math.min(max, Math.max(min, this));
+       },
+
+       round: function(precision){
+               precision = Math.pow(10, precision || 0);
+               return Math.round(this * precision) / precision;
+       },
+
+       times: function(fn, bind){
+               for (var i = 0; i < this; i++) fn.call(bind, i, this);
+       },
+
+       toFloat: function(){
+               return parseFloat(this);
+       },
+
+       toInt: function(base){
+               return parseInt(this, base || 10);
+       }
+
+});
+
+Number.alias('times', 'each');
+
+(function(math){
+       var methods = {};
+       math.each(function(name){
+               if (!Number[name]) methods[name] = function(){
+                       return Math[name].apply(null, [this].concat($A(arguments)));
+               };
+       });
+       Number.implement(methods);
+})(['abs', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'exp', 'floor', 'log', 'max', 'min', 'pow', 'sin', 'sqrt', 'tan']);
+
+
+/*
+---
+
+script: String.js
+
+description: Contains String Prototypes like camelCase, capitalize, test, and toInt.
+
+license: MIT-style license.
+
+requires:
+- /Native
+
+provides: [String]
+
+...
+*/
+
+String.implement({
+
+       test: function(regex, params){
+               return ((typeof regex == 'string') ? new RegExp(regex, params) : regex).test(this);
+       },
+
+       contains: function(string, separator){
+               return (separator) ? (separator + this + separator).indexOf(separator + string + separator) > -1 : this.indexOf(string) > -1;
+       },
+
+       trim: function(){
+               return this.replace(/^\s+|\s+$/g, '');
+       },
+
+       clean: function(){
+               return this.replace(/\s+/g, ' ').trim();
+       },
+
+       camelCase: function(){
+               return this.replace(/-\D/g, function(match){
+                       return match.charAt(1).toUpperCase();
+               });
+       },
+
+       hyphenate: function(){
+               return this.replace(/[A-Z]/g, function(match){
+                       return ('-' + match.charAt(0).toLowerCase());
+               });
+       },
+
+       capitalize: function(){
+               return this.replace(/\b[a-z]/g, function(match){
+                       return match.toUpperCase();
+               });
+       },
+
+       escapeRegExp: function(){
+               return this.replace(/([-.*+?^${}()|[\]\/\\])/g, '\\$1');
+       },
+
+       toInt: function(base){
+               return parseInt(this, base || 10);
+       },
+
+       toFloat: function(){
+               return parseFloat(this);
+       },
+
+       hexToRgb: function(array){
+               var hex = this.match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/);
+               return (hex) ? hex.slice(1).hexToRgb(array) : null;
+       },
+
+       rgbToHex: function(array){
+               var rgb = this.match(/\d{1,3}/g);
+               return (rgb) ? rgb.rgbToHex(array) : null;
+       },
+
+       stripScripts: function(option){
+               var scripts = '';
+               var text = this.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, function(){
+                       scripts += arguments[1] + '\n';
+                       return '';
+               });
+               if (option === true) $exec(scripts);
+               else if ($type(option) == 'function') option(scripts, text);
+               return text;
+       },
+
+       substitute: function(object, regexp){
+               return this.replace(regexp || (/\\?\{([^{}]+)\}/g), function(match, name){
+                       if (match.charAt(0) == '\\') return match.slice(1);
+                       return (object[name] != undefined) ? object[name] : '';
+               });
+       }
+
+});
+
+
+/*
+---
+
+script: Hash.js
+
+description: Contains Hash Prototypes. Provides a means for overcoming the JavaScript practical impossibility of extending native Objects.
+
+license: MIT-style license.
+
+requires:
+- /Hash.base
+
+provides: [Hash]
+
+...
+*/
+
+Hash.implement({
+
+       has: Object.prototype.hasOwnProperty,
+
+       keyOf: function(value){
+               for (var key in this){
+                       if (this.hasOwnProperty(key) && this[key] === value) return key;
+               }
+               return null;
+       },
+
+       hasValue: function(value){
+               return (Hash.keyOf(this, value) !== null);
+       },
+
+       extend: function(properties){
+               Hash.each(properties || {}, function(value, key){
+                       Hash.set(this, key, value);
+               }, this);
+               return this;
+       },
+
+       combine: function(properties){
+               Hash.each(properties || {}, function(value, key){
+                       Hash.include(this, key, value);
+               }, this);
+               return this;
+       },
+
+       erase: function(key){
+               if (this.hasOwnProperty(key)) delete this[key];
+               return this;
+       },
+
+       get: function(key){
+               return (this.hasOwnProperty(key)) ? this[key] : null;
+       },
+
+       set: function(key, value){
+               if (!this[key] || this.hasOwnProperty(key)) this[key] = value;
+               return this;
+       },
+
+       empty: function(){
+               Hash.each(this, function(value, key){
+                       delete this[key];
+               }, this);
+               return this;
+       },
+
+       include: function(key, value){
+               if (this[key] == undefined) this[key] = value;
+               return this;
+       },
+
+       map: function(fn, bind){
+               var results = new Hash;
+               Hash.each(this, function(value, key){
+                       results.set(key, fn.call(bind, value, key, this));
+               }, this);
+               return results;
+       },
+
+       filter: function(fn, bind){
+               var results = new Hash;
+               Hash.each(this, function(value, key){
+                       if (fn.call(bind, value, key, this)) results.set(key, value);
+               }, this);
+               return results;
+       },
+
+       every: function(fn, bind){
+               for (var key in this){
+                       if (this.hasOwnProperty(key) && !fn.call(bind, this[key], key)) return false;
+               }
+               return true;
+       },
+
+       some: function(fn, bind){
+               for (var key in this){
+                       if (this.hasOwnProperty(key) && fn.call(bind, this[key], key)) return true;
+               }
+               return false;
+       },
+
+       getKeys: function(){
+               var keys = [];
+               Hash.each(this, function(value, key){
+                       keys.push(key);
+               });
+               return keys;
+       },
+
+       getValues: function(){
+               var values = [];
+               Hash.each(this, function(value){
+                       values.push(value);
+               });
+               return values;
+       },
+
+       toQueryString: function(base){
+               var queryString = [];
+               Hash.each(this, function(value, key){
+                       if (base) key = base + '[' + key + ']';
+                       var result;
+                       switch ($type(value)){
+                               case 'object': result = Hash.toQueryString(value, key); break;
+                               case 'array':
+                                       var qs = {};
+                                       value.each(function(val, i){
+                                               qs[i] = val;
+                                       });
+                                       result = Hash.toQueryString(qs, key);
+                               break;
+                               default: result = key + '=' + encodeURIComponent(value);
+                       }
+                       if (value != undefined) queryString.push(result);
+               });
+
+               return queryString.join('&');
+       }
+
+});
+
+Hash.alias({keyOf: 'indexOf', hasValue: 'contains'});
+
+
+/*
+---
+
+script: Event.js
+
+description: Contains the Event Class, to make the event object cross-browser.
+
+license: MIT-style license.
+
+requires:
+- /Window
+- /Document
+- /Hash
+- /Array
+- /Function
+- /String
+
+provides: [Event]
+
+...
+*/
+
+var Event = new Native({
+
+       name: 'Event',
+
+       initialize: function(event, win){
+               win = win || window;
+               var doc = win.document;
+               event = event || win.event;
+               if (event.$extended) return event;
+               this.$extended = true;
+               var type = event.type;
+               var target = event.target || event.srcElement;
+               while (target && target.nodeType == 3) target = target.parentNode;
+
+               if (type.test(/key/)){
+                       var code = event.which || event.keyCode;
+                       var key = Event.Keys.keyOf(code);
+                       if (type == 'keydown'){
+                               var fKey = code - 111;
+                               if (fKey > 0 && fKey < 13) key = 'f' + fKey;
+                       }
+                       key = key || String.fromCharCode(code).toLowerCase();
+               } else if (type.match(/(click|mouse|menu)/i)){
+                       doc = (!doc.compatMode || doc.compatMode == 'CSS1Compat') ? doc.html : doc.body;
+                       var page = {
+                               x: event.pageX || event.clientX + doc.scrollLeft,
+                               y: event.pageY || event.clientY + doc.scrollTop
+                       };
+                       var client = {
+                               x: (event.pageX) ? event.pageX - win.pageXOffset : event.clientX,
+                               y: (event.pageY) ? event.pageY - win.pageYOffset : event.clientY
+                       };
+                       if (type.match(/DOMMouseScroll|mousewheel/)){
+                               var wheel = (event.wheelDelta) ? event.wheelDelta / 120 : -(event.detail || 0) / 3;
+                       }
+                       var rightClick = (event.which == 3) || (event.button == 2);
+                       var related = null;
+                       if (type.match(/over|out/)){
+                               switch (type){
+                                       case 'mouseover': related = event.relatedTarget || event.fromElement; break;
+                                       case 'mouseout': related = event.relatedTarget || event.toElement;
+                               }
+                               if (!(function(){
+                                       while (related && related.nodeType == 3) related = related.parentNode;
+                                       return true;
+                               }).create({attempt: Browser.Engine.gecko})()) related = false;
+                       }
+               }
+
+               return $extend(this, {
+                       event: event,
+                       type: type,
+
+                       page: page,
+                       client: client,
+                       rightClick: rightClick,
+
+                       wheel: wheel,
+
+                       relatedTarget: related,
+                       target: target,
+
+                       code: code,
+                       key: key,
+
+                       shift: event.shiftKey,
+                       control: event.ctrlKey,
+                       alt: event.altKey,
+                       meta: event.metaKey
+               });
+       }
+
+});
+
+Event.Keys = new Hash({
+       'enter': 13,
+       'up': 38,
+       'down': 40,
+       'left': 37,
+       'right': 39,
+       'esc': 27,
+       'space': 32,
+       'backspace': 8,
+       'tab': 9,
+       'delete': 46
+});
+
+Event.implement({
+
+       stop: function(){
+               return this.stopPropagation().preventDefault();
+       },
+
+       stopPropagation: function(){
+               if (this.event.stopPropagation) this.event.stopPropagation();
+               else this.event.cancelBubble = true;
+               return this;
+       },
+
+       preventDefault: function(){
+               if (this.event.preventDefault) this.event.preventDefault();
+               else this.event.returnValue = false;
+               return this;
+       }
+
+});
+
+
+/*
+---
+
+script: Class.js
+
+description: Contains the Class Function for easily creating, extending, and implementing reusable Classes.
+
+license: MIT-style license.
+
+requires:
+- /$util
+- /Native
+- /Array
+- /String
+- /Function
+- /Number
+- /Hash
+
+provides: [Class]
+
+...
+*/
+
+function Class(params){
+       
+       if (params instanceof Function) params = {initialize: params};
+       
+       var newClass = function(){
+               Object.reset(this);
+               if (newClass._prototyping) return this;
+               this._current = $empty;
+               var value = (this.initialize) ? this.initialize.apply(this, arguments) : this;
+               delete this._current; delete this.caller;
+               return value;
+       }.extend(this);
+       
+       newClass.implement(params);
+       
+       newClass.constructor = Class;
+       newClass.prototype.constructor = newClass;
+
+       return newClass;
+
+};
+
+Function.prototype.protect = function(){
+       this._protected = true;
+       return this;
+};
+
+Object.reset = function(object, key){
+               
+       if (key == null){
+               for (var p in object) Object.reset(object, p);
+               return object;
+       }
+       
+       delete object[key];
+       
+       switch ($type(object[key])){
+               case 'object':
+                       var F = function(){};
+                       F.prototype = object[key];
+                       var i = new F;
+                       object[key] = Object.reset(i);
+               break;
+               case 'array': object[key] = $unlink(object[key]); break;
+       }
+       
+       return object;
+       
+};
+
+new Native({name: 'Class', initialize: Class}).extend({
+
+       instantiate: function(F){
+               F._prototyping = true;
+               var proto = new F;
+               delete F._prototyping;
+               return proto;
+       },
+       
+       wrap: function(self, key, method){
+               if (method._origin) method = method._origin;
+               
+               return function(){
+                       if (method._protected && this._current == null) throw new Error('The method "' + key + '" cannot be called.');
+                       var caller = this.caller, current = this._current;
+                       this.caller = current; this._current = arguments.callee;
+                       var result = method.apply(this, arguments);
+                       this._current = current; this.caller = caller;
+                       return result;
+               }.extend({_owner: self, _origin: method, _name: key});
+
+       }
+       
+});
+
+Class.implement({
+       
+       implement: function(key, value){
+               
+               if ($type(key) == 'object'){
+                       for (var p in key) this.implement(p, key[p]);
+                       return this;
+               }
+               
+               var mutator = Class.Mutators[key];
+               
+               if (mutator){
+                       value = mutator.call(this, value);
+                       if (value == null) return this;
+               }
+               
+               var proto = this.prototype;
+
+               switch ($type(value)){
+                       
+                       case 'function':
+                               if (value._hidden) return this;
+                               proto[key] = Class.wrap(this, key, value);
+                       break;
+                       
+                       case 'object':
+                               var previous = proto[key];
+                               if ($type(previous) == 'object') $mixin(previous, value);
+                               else proto[key] = $unlink(value);
+                       break;
+                       
+                       case 'array':
+                               proto[key] = $unlink(value);
+                       break;
+                       
+                       default: proto[key] = value;
+
+               }
+               
+               return this;
+
+       }
+       
+});
+
+Class.Mutators = {
+       
+       Extends: function(parent){
+
+               this.parent = parent;
+               this.prototype = Class.instantiate(parent);
+
+               this.implement('parent', function(){
+                       var name = this.caller._name, previous = this.caller._owner.parent.prototype[name];
+                       if (!previous) throw new Error('The method "' + name + '" has no parent.');
+                       return previous.apply(this, arguments);
+               }.protect());
+
+       },
+
+       Implements: function(items){
+               $splat(items).each(function(item){
+                       if (item instanceof Function) item = Class.instantiate(item);
+                       this.implement(item);
+               }, this);
+
+       }
+       
+};
+
+
+/*
+---
+
+script: Class.Extras.js
+
+description: Contains Utility Classes that can be implemented into your own Classes to ease the execution of many common tasks.
+
+license: MIT-style license.
+
+requires:
+- /Class
+
+provides: [Chain, Events, Options]
+
+...
+*/
+
+var Chain = new Class({
+
+       $chain: [],
+
+       chain: function(){
+               this.$chain.extend(Array.flatten(arguments));
+               return this;
+       },
+
+       callChain: function(){
+               return (this.$chain.length) ? this.$chain.shift().apply(this, arguments) : false;
+       },
+
+       clearChain: function(){
+               this.$chain.empty();
+               return this;
+       }
+
+});
+
+var Events = new Class({
+
+       $events: {},
+
+       addEvent: function(type, fn, internal){
+               type = Events.removeOn(type);
+               if (fn != $empty){
+                       this.$events[type] = this.$events[type] || [];
+                       this.$events[type].include(fn);
+                       if (internal) fn.internal = true;
+               }
+               return this;
+       },
+
+       addEvents: function(events){
+               for (var type in events) this.addEvent(type, events[type]);
+               return this;
+       },
+
+       fireEvent: function(type, args, delay){
+               type = Events.removeOn(type);
+               if (!this.$events || !this.$events[type]) return this;
+               this.$events[type].each(function(fn){
+                       fn.create({'bind': this, 'delay': delay, 'arguments': args})();
+               }, this);
+               return this;
+       },
+
+       removeEvent: function(type, fn){
+               type = Events.removeOn(type);
+               if (!this.$events[type]) return this;
+               if (!fn.internal) this.$events[type].erase(fn);
+               return this;
+       },
+
+       removeEvents: function(events){
+               var type;
+               if ($type(events) == 'object'){
+                       for (type in events) this.removeEvent(type, events[type]);
+                       return this;
+               }
+               if (events) events = Events.removeOn(events);
+               for (type in this.$events){
+                       if (events && events != type) continue;
+                       var fns = this.$events[type];
+                       for (var i = fns.length; i--; i) this.removeEvent(type, fns[i]);
+               }
+               return this;
+       }
+
+});
+
+Events.removeOn = function(string){
+       return string.replace(/^on([A-Z])/, function(full, first){
+               return first.toLowerCase();
+       });
+};
+
+var Options = new Class({
+
+       setOptions: function(){
+               this.options = $merge.run([this.options].extend(arguments));
+               if (!this.addEvent) return this;
+               for (var option in this.options){
+                       if ($type(this.options[option]) != 'function' || !(/^on[A-Z]/).test(option)) continue;
+                       this.addEvent(option, this.options[option]);
+                       delete this.options[option];
+               }
+               return this;
+       }
+
+});
+
+
+/*
+---
+
+script: Element.js
+
+description: One of the most important items in MooTools. Contains the dollar function, the dollars function, and an handful of cross-browser, time-saver methods to let you easily work with HTML Elements.
+
+license: MIT-style license.
+
+requires:
+- /Window
+- /Document
+- /Array
+- /String
+- /Function
+- /Number
+- /Hash
+
+provides: [Element, Elements, $, $$, Iframe]
+
+...
+*/
+
+var Element = new Native({
+
+       name: 'Element',
+
+       legacy: window.Element,
+
+       initialize: function(tag, props){
+               var konstructor = Element.Constructors.get(tag);
+               if (konstructor) return konstructor(props);
+               if (typeof tag == 'string') return document.newElement(tag, props);
+               return document.id(tag).set(props);
+       },
+
+       afterImplement: function(key, value){
+               Element.Prototype[key] = value;
+               if (Array[key]) return;
+               Elements.implement(key, function(){
+                       var items = [], elements = true;
+                       for (var i = 0, j = this.length; i < j; i++){
+                               var returns = this[i][key].apply(this[i], arguments);
+                               items.push(returns);
+                               if (elements) elements = ($type(returns) == 'element');
+                       }
+                       return (elements) ? new Elements(items) : items;
+               });
+       }
+
+});
+
+Element.Prototype = {$family: {name: 'element'}};
+
+Element.Constructors = new Hash;
+
+var IFrame = new Native({
+
+       name: 'IFrame',
+
+       generics: false,
+
+       initialize: function(){
+               var params = Array.link(arguments, {properties: Object.type, iframe: $defined});
+               var props = params.properties || {};
+               var iframe = document.id(params.iframe);
+               var onload = props.onload || $empty;
+               delete props.onload;
+               props.id = props.name = $pick(props.id, props.name, iframe ? (iframe.id || iframe.name) : 'IFrame_' + $time());
+               iframe = new Element(iframe || 'iframe', props);
+               var onFrameLoad = function(){
+                       var host = $try(function(){
+                               return iframe.contentWindow.location.host;
+                       });
+                       if (!host || host == window.location.host){
+                               var win = new Window(iframe.contentWindow);
+                               new Document(iframe.contentWindow.document);
+                               $extend(win.Element.prototype, Element.Prototype);
+                       }
+                       onload.call(iframe.contentWindow, iframe.contentWindow.document);
+               };
+               var contentWindow = $try(function(){
+                       return iframe.contentWindow;
+               });
+               ((contentWindow && contentWindow.document.body) || window.frames[props.id]) ? onFrameLoad() : iframe.addListener('load', onFrameLoad);
+               return iframe;
+       }
+
+});
+
+var Elements = new Native({
+
+       initialize: function(elements, options){
+               options = $extend({ddup: true, cash: true}, options);
+               elements = elements || [];
+               if (options.ddup || options.cash){
+                       var uniques = {}, returned = [];
+                       for (var i = 0, l = elements.length; i < l; i++){
+                               var el = document.id(elements[i], !options.cash);
+                               if (options.ddup){
+                                       if (uniques[el.uid]) continue;
+                                       uniques[el.uid] = true;
+                               }
+                               if (el) returned.push(el);
+                       }
+                       elements = returned;
+               }
+               return (options.cash) ? $extend(elements, this) : elements;
+       }
+
+});
+
+Elements.implement({
+
+       filter: function(filter, bind){
+               if (!filter) return this;
+               return new Elements(Array.filter(this, (typeof filter == 'string') ? function(item){
+                       return item.match(filter);
+               } : filter, bind));
+       }
+
+});
+
+Document.implement({
+
+       newElement: function(tag, props){
+               if (Browser.Engine.trident && props){
+                       ['name', 'type', 'checked'].each(function(attribute){
+                               if (!props[attribute]) return;
+                               tag += ' ' + attribute + '="' + props[attribute] + '"';
+                               if (attribute != 'checked') delete props[attribute];
+                       });
+                       tag = '<' + tag + '>';
+               }
+               return document.id(this.createElement(tag)).set(props);
+       },
+
+       newTextNode: function(text){
+               return this.createTextNode(text);
+       },
+
+       getDocument: function(){
+               return this;
+       },
+
+       getWindow: function(){
+               return this.window;
+       },
+       
+       id: (function(){
+               
+               var types = {
+
+                       string: function(id, nocash, doc){
+                               id = doc.getElementById(id);
+                               return (id) ? types.element(id, nocash) : null;
+                       },
+                       
+                       element: function(el, nocash){
+                               $uid(el);
+                               if (!nocash && !el.$family && !(/^object|embed$/i).test(el.tagName)){
+                                       var proto = Element.Prototype;
+                                       for (var p in proto) el[p] = proto[p];
+                               };
+                               return el;
+                       },
+                       
+                       object: function(obj, nocash, doc){
+                               if (obj.toElement) return types.element(obj.toElement(doc), nocash);
+                               return null;
+                       }
+                       
+               };
+
+               types.textnode = types.whitespace = types.window = types.document = $arguments(0);
+               
+               return function(el, nocash, doc){
+                       if (el && el.$family && el.uid) return el;
+                       var type = $type(el);
+                       return (types[type]) ? types[type](el, nocash, doc || document) : null;
+               };
+
+       })()
+
+});
+
+if (window.$ == null) Window.implement({
+       $: function(el, nc){
+               return document.id(el, nc, this.document);
+       }
+});
+
+Window.implement({
+
+       $$: function(selector){
+               if (arguments.length == 1 && typeof selector == 'string') return this.document.getElements(selector);
+               var elements = [];
+               var args = Array.flatten(arguments);
+               for (var i = 0, l = args.length; i < l; i++){
+                       var item = args[i];
+                       switch ($type(item)){
+                               case 'element': elements.push(item); break;
+                               case 'string': elements.extend(this.document.getElements(item, true));
+                       }
+               }
+               return new Elements(elements);
+       },
+
+       getDocument: function(){
+               return this.document;
+       },
+
+       getWindow: function(){
+               return this;
+       }
+
+});
+
+Native.implement([Element, Document], {
+
+       getElement: function(selector, nocash){
+               return document.id(this.getElements(selector, true)[0] || null, nocash);
+       },
+
+       getElements: function(tags, nocash){
+               tags = tags.split(',');
+               var elements = [];
+               var ddup = (tags.length > 1);
+               tags.each(function(tag){
+                       var partial = this.getElementsByTagName(tag.trim());
+                       (ddup) ? elements.extend(partial) : elements = partial;
+               }, this);
+               return new Elements(elements, {ddup: ddup, cash: !nocash});
+       }
+
+});
+
+(function(){
+
+var collected = {}, storage = {};
+var props = {input: 'checked', option: 'selected', textarea: (Browser.Engine.webkit && Browser.Engine.version < 420) ? 'innerHTML' : 'value'};
+
+var get = function(uid){
+       return (storage[uid] || (storage[uid] = {}));
+};
+
+var clean = function(item, retain){
+       if (!item) return;
+       var uid = item.uid;
+       if (Browser.Engine.trident){
+               if (item.clearAttributes){
+                       var clone = retain && item.cloneNode(false);
+                       item.clearAttributes();
+                       if (clone) item.mergeAttributes(clone);
+               } else if (item.removeEvents){
+                       item.removeEvents();
+               }
+               if ((/object/i).test(item.tagName)){
+                       for (var p in item){
+                               if (typeof item[p] == 'function') item[p] = $empty;
+                       }
+                       Element.dispose(item);
+               }
+       }       
+       if (!uid) return;
+       collected[uid] = storage[uid] = null;
+};
+
+var purge = function(){
+       Hash.each(collected, clean);
+       if (Browser.Engine.trident) $A(document.getElementsByTagName('object')).each(clean);
+       if (window.CollectGarbage) CollectGarbage();
+       collected = storage = null;
+};
+
+var walk = function(element, walk, start, match, all, nocash){
+       var el = element[start || walk];
+       var elements = [];
+       while (el){
+               if (el.nodeType == 1 && (!match || Element.match(el, match))){
+                       if (!all) return document.id(el, nocash);
+                       elements.push(el);
+               }
+               el = el[walk];
+       }
+       return (all) ? new Elements(elements, {ddup: false, cash: !nocash}) : null;
+};
+
+var attributes = {
+       'html': 'innerHTML',
+       'class': 'className',
+       'for': 'htmlFor',
+       'defaultValue': 'defaultValue',
+       'text': (Browser.Engine.trident || (Browser.Engine.webkit && Browser.Engine.version < 420)) ? 'innerText' : 'textContent'
+};
+var bools = ['compact', 'nowrap', 'ismap', 'declare', 'noshade', 'checked', 'disabled', 'readonly', 'multiple', 'selected', 'noresize', 'defer'];
+var camels = ['value', 'type', 'defaultValue', 'accessKey', 'cellPadding', 'cellSpacing', 'colSpan', 'frameBorder', 'maxLength', 'readOnly', 'rowSpan', 'tabIndex', 'useMap'];
+
+bools = bools.associate(bools);
+
+Hash.extend(attributes, bools);
+Hash.extend(attributes, camels.associate(camels.map(String.toLowerCase)));
+
+var inserters = {
+
+       before: function(context, element){
+               if (element.parentNode) element.parentNode.insertBefore(context, element);
+       },
+
+       after: function(context, element){
+               if (!element.parentNode) return;
+               var next = element.nextSibling;
+               (next) ? element.parentNode.insertBefore(context, next) : element.parentNode.appendChild(context);
+       },
+
+       bottom: function(context, element){
+               element.appendChild(context);
+       },
+
+       top: function(context, element){
+               var first = element.firstChild;
+               (first) ? element.insertBefore(context, first) : element.appendChild(context);
+       }
+
+};
+
+inserters.inside = inserters.bottom;
+
+Hash.each(inserters, function(inserter, where){
+
+       where = where.capitalize();
+
+       Element.implement('inject' + where, function(el){
+               inserter(this, document.id(el, true));
+               return this;
+       });
+
+       Element.implement('grab' + where, function(el){
+               inserter(document.id(el, true), this);
+               return this;
+       });
+
+});
+
+Element.implement({
+
+       set: function(prop, value){
+               switch ($type(prop)){
+                       case 'object':
+                               for (var p in prop) this.set(p, prop[p]);
+                               break;
+                       case 'string':
+                               var property = Element.Properties.get(prop);
+                               (property && property.set) ? property.set.apply(this, Array.slice(arguments, 1)) : this.setProperty(prop, value);
+               }
+               return this;
+       },
+
+       get: function(prop){
+               var property = Element.Properties.get(prop);
+               return (property && property.get) ? property.get.apply(this, Array.slice(arguments, 1)) : this.getProperty(prop);
+       },
+
+       erase: function(prop){
+               var property = Element.Properties.get(prop);
+               (property && property.erase) ? property.erase.apply(this) : this.removeProperty(prop);
+               return this;
+       },
+
+       setProperty: function(attribute, value){
+               var key = attributes[attribute];
+               if (value == undefined) return this.removeProperty(attribute);
+               if (key && bools[attribute]) value = !!value;
+               (key) ? this[key] = value : this.setAttribute(attribute, '' + value);
+               return this;
+       },
+
+       setProperties: function(attributes){
+               for (var attribute in attributes) this.setProperty(attribute, attributes[attribute]);
+               return this;
+       },
+
+       getProperty: function(attribute){
+               var key = attributes[attribute];
+               var value = (key) ? this[key] : this.getAttribute(attribute, 2);
+               return (bools[attribute]) ? !!value : (key) ? value : value || null;
+       },
+
+       getProperties: function(){
+               var args = $A(arguments);
+               return args.map(this.getProperty, this).associate(args);
+       },
+
+       removeProperty: function(attribute){
+               var key = attributes[attribute];
+               (key) ? this[key] = (key && bools[attribute]) ? false : '' : this.removeAttribute(attribute);
+               return this;
+       },
+
+       removeProperties: function(){
+               Array.each(arguments, this.removeProperty, this);
+               return this;
+       },
+
+       hasClass: function(className){
+               return this.className.contains(className, ' ');
+       },
+
+       addClass: function(className){
+               if (!this.hasClass(className)) this.className = (this.className + ' ' + className).clean();
+               return this;
+       },
+
+       removeClass: function(className){
+               this.className = this.className.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)'), '$1');
+               return this;
+       },
+
+       toggleClass: function(className){
+               return this.hasClass(className) ? this.removeClass(className) : this.addClass(className);
+       },
+
+       adopt: function(){
+               Array.flatten(arguments).each(function(element){
+                       element = document.id(element, true);
+                       if (element) this.appendChild(element);
+               }, this);
+               return this;
+       },
+
+       appendText: function(text, where){
+               return this.grab(this.getDocument().newTextNode(text), where);
+       },
+
+       grab: function(el, where){
+               inserters[where || 'bottom'](document.id(el, true), this);
+               return this;
+       },
+
+       inject: function(el, where){
+               inserters[where || 'bottom'](this, document.id(el, true));
+               return this;
+       },
+
+       replaces: function(el){
+               el = document.id(el, true);
+               el.parentNode.replaceChild(this, el);
+               return this;
+       },
+
+       wraps: function(el, where){
+               el = document.id(el, true);
+               return this.replaces(el).grab(el, where);
+       },
+
+       getPrevious: function(match, nocash){
+               return walk(this, 'previousSibling', null, match, false, nocash);
+       },
+
+       getAllPrevious: function(match, nocash){
+               return walk(this, 'previousSibling', null, match, true, nocash);
+       },
+
+       getNext: function(match, nocash){
+               return walk(this, 'nextSibling', null, match, false, nocash);
+       },
+
+       getAllNext: function(match, nocash){
+               return walk(this, 'nextSibling', null, match, true, nocash);
+       },
+
+       getFirst: function(match, nocash){
+               return walk(this, 'nextSibling', 'firstChild', match, false, nocash);
+       },
+
+       getLast: function(match, nocash){
+               return walk(this, 'previousSibling', 'lastChild', match, false, nocash);
+       },
+
+       getParent: function(match, nocash){
+               return walk(this, 'parentNode', null, match, false, nocash);
+       },
+
+       getParents: function(match, nocash){
+               return walk(this, 'parentNode', null, match, true, nocash);
+       },
+       
+       getSiblings: function(match, nocash){
+               return this.getParent().getChildren(match, nocash).erase(this);
+       },
+
+       getChildren: function(match, nocash){
+               return walk(this, 'nextSibling', 'firstChild', match, true, nocash);
+       },
+
+       getWindow: function(){
+               return this.ownerDocument.window;
+       },
+
+       getDocument: function(){
+               return this.ownerDocument;
+       },
+
+       getElementById: function(id, nocash){
+               var el = this.ownerDocument.getElementById(id);
+               if (!el) return null;
+               for (var parent = el.parentNode; parent != this; parent = parent.parentNode){
+                       if (!parent) return null;
+               }
+               return document.id(el, nocash);
+       },
+
+       getSelected: function(){
+               return new Elements($A(this.options).filter(function(option){
+                       return option.selected;
+               }));
+       },
+
+       getComputedStyle: function(property){
+               if (this.currentStyle) return this.currentStyle[property.camelCase()];
+               var computed = this.getDocument().defaultView.getComputedStyle(this, null);
+               return (computed) ? computed.getPropertyValue([property.hyphenate()]) : null;
+       },
+
+       toQueryString: function(){
+               var queryString = [];
+               this.getElements('input, select, textarea', true).each(function(el){
+                       if (!el.name || el.disabled || el.type == 'submit' || el.type == 'reset' || el.type == 'file') return;
+                       var value = (el.tagName.toLowerCase() == 'select') ? Element.getSelected(el).map(function(opt){
+                               return opt.value;
+                       }) : ((el.type == 'radio' || el.type == 'checkbox') && !el.checked) ? null : el.value;
+                       $splat(value).each(function(val){
+                               if (typeof val != 'undefined') queryString.push(el.name + '=' + encodeURIComponent(val));
+                       });
+               });
+               return queryString.join('&');
+       },
+
+       clone: function(contents, keepid){
+               contents = contents !== false;
+               var clone = this.cloneNode(contents);
+               var clean = function(node, element){
+                       if (!keepid) node.removeAttribute('id');
+                       if (Browser.Engine.trident){
+                               node.clearAttributes();
+                               node.mergeAttributes(element);
+                               node.removeAttribute('uid');
+                               if (node.options){
+                                       var no = node.options, eo = element.options;
+                                       for (var j = no.length; j--;) no[j].selected = eo[j].selected;
+                               }
+                       }
+                       var prop = props[element.tagName.toLowerCase()];
+                       if (prop && element[prop]) node[prop] = element[prop];
+               };
+
+               if (contents){
+                       var ce = clone.getElementsByTagName('*'), te = this.getElementsByTagName('*');
+                       for (var i = ce.length; i--;) clean(ce[i], te[i]);
+               }
+
+               clean(clone, this);
+               return document.id(clone);
+       },
+
+       destroy: function(){
+               Element.empty(this);
+               Element.dispose(this);
+               clean(this, true);
+               return null;
+       },
+
+       empty: function(){
+               $A(this.childNodes).each(function(node){
+                       Element.destroy(node);
+               });
+               return this;
+       },
+
+       dispose: function(){
+               return (this.parentNode) ? this.parentNode.removeChild(this) : this;
+       },
+
+       hasChild: function(el){
+               el = document.id(el, true);
+               if (!el) return false;
+               if (Browser.Engine.webkit && Browser.Engine.version < 420) return $A(this.getElementsByTagName(el.tagName)).contains(el);
+               return (this.contains) ? (this != el && this.contains(el)) : !!(this.compareDocumentPosition(el) & 16);
+       },
+
+       match: function(tag){
+               return (!tag || (tag == this) || (Element.get(this, 'tag') == tag));
+       }
+
+});
+
+Native.implement([Element, Window, Document], {
+
+       addListener: function(type, fn){
+               if (type == 'unload'){
+                       var old = fn, self = this;
+                       fn = function(){
+                               self.removeListener('unload', fn);
+                               old();
+                       };
+               } else {
+                       collected[this.uid] = this;
+               }
+               if (this.addEventListener) this.addEventListener(type, fn, false);
+               else this.attachEvent('on' + type, fn);
+               return this;
+       },
+
+       removeListener: function(type, fn){
+               if (this.removeEventListener) this.removeEventListener(type, fn, false);
+               else this.detachEvent('on' + type, fn);
+               return this;
+       },
+
+       retrieve: function(property, dflt){
+               var storage = get(this.uid), prop = storage[property];
+               if (dflt != undefined && prop == undefined) prop = storage[property] = dflt;
+               return $pick(prop);
+       },
+
+       store: function(property, value){
+               var storage = get(this.uid);
+               storage[property] = value;
+               return this;
+       },
+
+       eliminate: function(property){
+               var storage = get(this.uid);
+               delete storage[property];
+               return this;
+       }
+
+});
+
+window.addListener('unload', purge);
+
+})();
+
+Element.Properties = new Hash;
+
+Element.Properties.style = {
+
+       set: function(style){
+               this.style.cssText = style;
+       },
+
+       get: function(){
+               return this.style.cssText;
+       },
+
+       erase: function(){
+               this.style.cssText = '';
+       }
+
+};
+
+Element.Properties.tag = {
+
+       get: function(){
+               return this.tagName.toLowerCase();
+       }
+
+};
+
+Element.Properties.html = (function(){
+       var wrapper = document.createElement('div');
+
+       var translations = {
+               table: [1, '<table>', '</table>'],
+               select: [1, '<select>', '</select>'],
+               tbody: [2, '<table><tbody>', '</tbody></table>'],
+               tr: [3, '<table><tbody><tr>', '</tr></tbody></table>']
+       };
+       translations.thead = translations.tfoot = translations.tbody;
+
+       var html = {
+               set: function(){
+                       var html = Array.flatten(arguments).join('');
+                       var wrap = Browser.Engine.trident && translations[this.get('tag')];
+                       if (wrap){
+                               var first = wrapper;
+                               first.innerHTML = wrap[1] + html + wrap[2];
+                               for (var i = wrap[0]; i--;) first = first.firstChild;
+                               this.empty().adopt(first.childNodes);
+                       } else {
+                               this.innerHTML = html;
+                       }
+               }
+       };
+
+       html.erase = html.set;
+
+       return html;
+})();
+
+if (Browser.Engine.webkit && Browser.Engine.version < 420) Element.Properties.text = {
+       get: function(){
+               if (this.innerText) return this.innerText;
+               var temp = this.ownerDocument.newElement('div', {html: this.innerHTML}).inject(this.ownerDocument.body);
+               var text = temp.innerText;
+               temp.destroy();
+               return text;
+       }
+};
+
+
+/*
+---
+
+script: Element.Event.js
+
+description: Contains Element methods for dealing with events. This file also includes mouseenter and mouseleave custom Element Events.
+
+license: MIT-style license.
+
+requires: 
+- /Element
+- /Event
+
+provides: [Element.Event]
+
+...
+*/
+
+Element.Properties.events = {set: function(events){
+       this.addEvents(events);
+}};
+
+Native.implement([Element, Window, Document], {
+
+       addEvent: function(type, fn){
+               var events = this.retrieve('events', {});
+               events[type] = events[type] || {'keys': [], 'values': []};
+               if (events[type].keys.contains(fn)) return this;
+               events[type].keys.push(fn);
+               var realType = type, custom = Element.Events.get(type), condition = fn, self = this;
+               if (custom){
+                       if (custom.onAdd) custom.onAdd.call(this, fn);
+                       if (custom.condition){
+                               condition = function(event){
+                                       if (custom.condition.call(this, event)) return fn.call(this, event);
+                                       return true;
+                               };
+                       }
+                       realType = custom.base || realType;
+               }
+               var defn = function(){
+                       return fn.call(self);
+               };
+               var nativeEvent = Element.NativeEvents[realType];
+               if (nativeEvent){
+                       if (nativeEvent == 2){
+                               defn = function(event){
+                                       event = new Event(event, self.getWindow());
+                                       if (condition.call(self, event) === false) event.stop();
+                               };
+                       }
+                       this.addListener(realType, defn);
+               }
+               events[type].values.push(defn);
+               return this;
+       },
+
+       removeEvent: function(type, fn){
+               var events = this.retrieve('events');
+               if (!events || !events[type]) return this;
+               var pos = events[type].keys.indexOf(fn);
+               if (pos == -1) return this;
+               events[type].keys.splice(pos, 1);
+               var value = events[type].values.splice(pos, 1)[0];
+               var custom = Element.Events.get(type);
+               if (custom){
+                       if (custom.onRemove) custom.onRemove.call(this, fn);
+                       type = custom.base || type;
+               }
+               return (Element.NativeEvents[type]) ? this.removeListener(type, value) : this;
+       },
+
+       addEvents: function(events){
+               for (var event in events) this.addEvent(event, events[event]);
+               return this;
+       },
+
+       removeEvents: function(events){
+               var type;
+               if ($type(events) == 'object'){
+                       for (type in events) this.removeEvent(type, events[type]);
+                       return this;
+               }
+               var attached = this.retrieve('events');
+               if (!attached) return this;
+               if (!events){
+                       for (type in attached) this.removeEvents(type);
+                       this.eliminate('events');
+               } else if (attached[events]){
+                       while (attached[events].keys[0]) this.removeEvent(events, attached[events].keys[0]);
+                       attached[events] = null;
+               }
+               return this;
+       },
+
+       fireEvent: function(type, args, delay){
+               var events = this.retrieve('events');
+               if (!events || !events[type]) return this;
+               events[type].keys.each(function(fn){
+                       fn.create({'bind': this, 'delay': delay, 'arguments': args})();
+               }, this);
+               return this;
+       },
+
+       cloneEvents: function(from, type){
+               from = document.id(from);
+               var fevents = from.retrieve('events');
+               if (!fevents) return this;
+               if (!type){
+                       for (var evType in fevents) this.cloneEvents(from, evType);
+               } else if (fevents[type]){
+                       fevents[type].keys.each(function(fn){
+                               this.addEvent(type, fn);
+                       }, this);
+               }
+               return this;
+       }
+
+});
+
+Element.NativeEvents = {
+       click: 2, dblclick: 2, mouseup: 2, mousedown: 2, contextmenu: 2, //mouse buttons
+       mousewheel: 2, DOMMouseScroll: 2, //mouse wheel
+       mouseover: 2, mouseout: 2, mousemove: 2, selectstart: 2, selectend: 2, //mouse movement
+       keydown: 2, keypress: 2, keyup: 2, //keyboard
+       focus: 2, blur: 2, change: 2, reset: 2, select: 2, submit: 2, //form elements
+       load: 1, unload: 1, beforeunload: 2, resize: 1, move: 1, DOMContentLoaded: 1, readystatechange: 1, //window
+       error: 1, abort: 1, scroll: 1 //misc
+};
+
+(function(){
+
+var $check = function(event){
+       var related = event.relatedTarget;
+       if (related == undefined) return true;
+       if (related === false) return false;
+       return ($type(this) != 'document' && related != this && related.prefix != 'xul' && !this.hasChild(related));
+};
+
+Element.Events = new Hash({
+
+       mouseenter: {
+               base: 'mouseover',
+               condition: $check
+       },
+
+       mouseleave: {
+               base: 'mouseout',
+               condition: $check
+       },
+
+       mousewheel: {
+               base: (Browser.Engine.gecko) ? 'DOMMouseScroll' : 'mousewheel'
+       }
+
+});
+
+})();
+
+
+/*
+---
+
+script: Element.Style.js
+
+description: Contains methods for interacting with the styles of Elements in a fashionable way.
+
+license: MIT-style license.
+
+requires:
+- /Element
+
+provides: [Element.Style]
+
+...
+*/
+
+Element.Properties.styles = {set: function(styles){
+       this.setStyles(styles);
+}};
+
+Element.Properties.opacity = {
+
+       set: function(opacity, novisibility){
+               if (!novisibility){
+                       if (opacity == 0){
+                               if (this.style.visibility != 'hidden') this.style.visibility = 'hidden';
+                       } else {
+                               if (this.style.visibility != 'visible') this.style.visibility = 'visible';
+                       }
+               }
+               if (!this.currentStyle || !this.currentStyle.hasLayout) this.style.zoom = 1;
+               if (Browser.Engine.trident) this.style.filter = (opacity == 1) ? '' : 'alpha(opacity=' + opacity * 100 + ')';
+               this.style.opacity = opacity;
+               this.store('opacity', opacity);
+       },
+
+       get: function(){
+               return this.retrieve('opacity', 1);
+       }
+
+};
+
+Element.implement({
+
+       setOpacity: function(value){
+               return this.set('opacity', value, true);
+       },
+
+       getOpacity: function(){
+               return this.get('opacity');
+       },
+
+       setStyle: function(property, value){
+               switch (property){
+                       case 'opacity': return this.set('opacity', parseFloat(value));
+                       case 'float': property = (Browser.Engine.trident) ? 'styleFloat' : 'cssFloat';
+               }
+               property = property.camelCase();
+               if ($type(value) != 'string'){
+                       var map = (Element.Styles.get(property) || '@').split(' ');
+                       value = $splat(value).map(function(val, i){
+                               if (!map[i]) return '';
+                               return ($type(val) == 'number') ? map[i].replace('@', Math.round(val)) : val;
+                       }).join(' ');
+               } else if (value == String(Number(value))){
+                       value = Math.round(value);
+               }
+               this.style[property] = value;
+               return this;
+       },
+
+       getStyle: function(property){
+               switch (property){
+                       case 'opacity': return this.get('opacity');
+                       case 'float': property = (Browser.Engine.trident) ? 'styleFloat' : 'cssFloat';
+               }
+               property = property.camelCase();
+               var result = this.style[property];
+               if (!$chk(result)){
+                       result = [];
+                       for (var style in Element.ShortStyles){
+                               if (property != style) continue;
+                               for (var s in Element.ShortStyles[style]) result.push(this.getStyle(s));
+                               return result.join(' ');
+                       }
+                       result = this.getComputedStyle(property);
+               }
+               if (result){
+                       result = String(result);
+                       var color = result.match(/rgba?\([\d\s,]+\)/);
+                       if (color) result = result.replace(color[0], color[0].rgbToHex());
+               }
+               if (Browser.Engine.presto || (Browser.Engine.trident && !$chk(parseInt(result, 10)))){
+                       if (property.test(/^(height|width)$/)){
+                               var values = (property == 'width') ? ['left', 'right'] : ['top', 'bottom'], size = 0;
+                               values.each(function(value){
+                                       size += this.getStyle('border-' + value + '-width').toInt() + this.getStyle('padding-' + value).toInt();
+                               }, this);
+                               return this['offset' + property.capitalize()] - size + 'px';
+                       }
+                       if ((Browser.Engine.presto) && String(result).test('px')) return result;
+                       if (property.test(/(border(.+)Width|margin|padding)/)) return '0px';
+               }
+               return result;
+       },
+
+       setStyles: function(styles){
+               for (var style in styles) this.setStyle(style, styles[style]);
+               return this;
+       },
+
+       getStyles: function(){
+               var result = {};
+               Array.flatten(arguments).each(function(key){
+                       result[key] = this.getStyle(key);
+               }, this);
+               return result;
+       }
+
+});
+
+Element.Styles = new Hash({
+       left: '@px', top: '@px', bottom: '@px', right: '@px',
+       width: '@px', height: '@px', maxWidth: '@px', maxHeight: '@px', minWidth: '@px', minHeight: '@px',
+       backgroundColor: 'rgb(@, @, @)', backgroundPosition: '@px @px', color: 'rgb(@, @, @)',
+       fontSize: '@px', letterSpacing: '@px', lineHeight: '@px', clip: 'rect(@px @px @px @px)',
+       margin: '@px @px @px @px', padding: '@px @px @px @px', border: '@px @ rgb(@, @, @) @px @ rgb(@, @, @) @px @ rgb(@, @, @)',
+       borderWidth: '@px @px @px @px', borderStyle: '@ @ @ @', borderColor: 'rgb(@, @, @) rgb(@, @, @) rgb(@, @, @) rgb(@, @, @)',
+       zIndex: '@', 'zoom': '@', fontWeight: '@', textIndent: '@px', opacity: '@'
+});
+
+Element.ShortStyles = {margin: {}, padding: {}, border: {}, borderWidth: {}, borderStyle: {}, borderColor: {}};
+
+['Top', 'Right', 'Bottom', 'Left'].each(function(direction){
+       var Short = Element.ShortStyles;
+       var All = Element.Styles;
+       ['margin', 'padding'].each(function(style){
+               var sd = style + direction;
+               Short[style][sd] = All[sd] = '@px';
+       });
+       var bd = 'border' + direction;
+       Short.border[bd] = All[bd] = '@px @ rgb(@, @, @)';
+       var bdw = bd + 'Width', bds = bd + 'Style', bdc = bd + 'Color';
+       Short[bd] = {};
+       Short.borderWidth[bdw] = Short[bd][bdw] = All[bdw] = '@px';
+       Short.borderStyle[bds] = Short[bd][bds] = All[bds] = '@';
+       Short.borderColor[bdc] = Short[bd][bdc] = All[bdc] = 'rgb(@, @, @)';
+});
+
+
+/*
+---
+
+script: Element.Dimensions.js
+
+description: Contains methods to work with size, scroll, or positioning of Elements and the window object.
+
+license: MIT-style license.
+
+credits:
+- Element positioning based on the [qooxdoo](http://qooxdoo.org/) code and smart browser fixes, [LGPL License](http://www.gnu.org/licenses/lgpl.html).
+- Viewport dimensions based on [YUI](http://developer.yahoo.com/yui/) code, [BSD License](http://developer.yahoo.com/yui/license.html).
+
+requires:
+- /Element
+
+provides: [Element.Dimensions]
+
+...
+*/
+
+(function(){
+
+Element.implement({
+
+       scrollTo: function(x, y){
+               if (isBody(this)){
+                       this.getWindow().scrollTo(x, y);
+               } else {
+                       this.scrollLeft = x;
+                       this.scrollTop = y;
+               }
+               return this;
+       },
+
+       getSize: function(){
+               if (isBody(this)) return this.getWindow().getSize();
+               return {x: this.offsetWidth, y: this.offsetHeight};
+       },
+
+       getScrollSize: function(){
+               if (isBody(this)) return this.getWindow().getScrollSize();
+               return {x: this.scrollWidth, y: this.scrollHeight};
+       },
+
+       getScroll: function(){
+               if (isBody(this)) return this.getWindow().getScroll();
+               return {x: this.scrollLeft, y: this.scrollTop};
+       },
+
+       getScrolls: function(){
+               var element = this, position = {x: 0, y: 0};
+               while (element && !isBody(element)){
+                       position.x += element.scrollLeft;
+                       position.y += element.scrollTop;
+                       element = element.parentNode;
+               }
+               return position;
+       },
+
+       getOffsetParent: function(){
+               var element = this;
+               if (isBody(element)) return null;
+               if (!Browser.Engine.trident) return element.offsetParent;
+               while ((element = element.parentNode) && !isBody(element)){
+                       if (styleString(element, 'position') != 'static') return element;
+               }
+               return null;
+       },
+
+       getOffsets: function(){
+               if (this.getBoundingClientRect){
+                       var bound = this.getBoundingClientRect(),
+                               html = document.id(this.getDocument().documentElement),
+                               htmlScroll = html.getScroll(),
+                               elemScrolls = this.getScrolls(),
+                               elemScroll = this.getScroll(),
+                               isFixed = (styleString(this, 'position') == 'fixed');
+
+                       return {
+                               x: bound.left.toInt() + elemScrolls.x - elemScroll.x + ((isFixed) ? 0 : htmlScroll.x) - html.clientLeft,
+                               y: bound.top.toInt()  + elemScrolls.y - elemScroll.y + ((isFixed) ? 0 : htmlScroll.y) - html.clientTop
+                       };
+               }
+
+               var element = this, position = {x: 0, y: 0};
+               if (isBody(this)) return position;
+
+               while (element && !isBody(element)){
+                       position.x += element.offsetLeft;
+                       position.y += element.offsetTop;
+
+                       if (Browser.Engine.gecko){
+                               if (!borderBox(element)){
+                                       position.x += leftBorder(element);
+                                       position.y += topBorder(element);
+                               }
+                               var parent = element.parentNode;
+                               if (parent && styleString(parent, 'overflow') != 'visible'){
+                                       position.x += leftBorder(parent);
+                                       position.y += topBorder(parent);
+                               }
+                       } else if (element != this && Browser.Engine.webkit){
+                               position.x += leftBorder(element);
+                               position.y += topBorder(element);
+                       }
+
+                       element = element.offsetParent;
+               }
+               if (Browser.Engine.gecko && !borderBox(this)){
+                       position.x -= leftBorder(this);
+                       position.y -= topBorder(this);
+               }
+               return position;
+       },
+
+       getPosition: function(relative){
+               if (isBody(this)) return {x: 0, y: 0};
+               var offset = this.getOffsets(),
+                               scroll = this.getScrolls();
+               var position = {
+                       x: offset.x - scroll.x,
+                       y: offset.y - scroll.y
+               };
+               var relativePosition = (relative && (relative = document.id(relative))) ? relative.getPosition() : {x: 0, y: 0};
+               return {x: position.x - relativePosition.x, y: position.y - relativePosition.y};
+       },
+
+       getCoordinates: function(element){
+               if (isBody(this)) return this.getWindow().getCoordinates();
+               var position = this.getPosition(element),
+                               size = this.getSize();
+               var obj = {
+                       left: position.x,
+                       top: position.y,
+                       width: size.x,
+                       height: size.y
+               };
+               obj.right = obj.left + obj.width;
+               obj.bottom = obj.top + obj.height;
+               return obj;
+       },
+
+       computePosition: function(obj){
+               return {
+                       left: obj.x - styleNumber(this, 'margin-left'),
+                       top: obj.y - styleNumber(this, 'margin-top')
+               };
+       },
+
+       setPosition: function(obj){
+               return this.setStyles(this.computePosition(obj));
+       }
+
+});
+
+
+Native.implement([Document, Window], {
+
+       getSize: function(){
+               if (Browser.Engine.presto || Browser.Engine.webkit){
+                       var win = this.getWindow();
+                       return {x: win.innerWidth, y: win.innerHeight};
+               }
+               var doc = getCompatElement(this);
+               return {x: doc.clientWidth, y: doc.clientHeight};
+       },
+
+       getScroll: function(){
+               var win = this.getWindow(), doc = getCompatElement(this);
+               return {x: win.pageXOffset || doc.scrollLeft, y: win.pageYOffset || doc.scrollTop};
+       },
+
+       getScrollSize: function(){
+               var doc = getCompatElement(this), min = this.getSize();
+               return {x: Math.max(doc.scrollWidth, min.x), y: Math.max(doc.scrollHeight, min.y)};
+       },
+
+       getPosition: function(){
+               return {x: 0, y: 0};
+       },
+
+       getCoordinates: function(){
+               var size = this.getSize();
+               return {top: 0, left: 0, bottom: size.y, right: size.x, height: size.y, width: size.x};
+       }
+
+});
+
+// private methods
+
+var styleString = Element.getComputedStyle;
+
+function styleNumber(element, style){
+       return styleString(element, style).toInt() || 0;
+};
+
+function borderBox(element){
+       return styleString(element, '-moz-box-sizing') == 'border-box';
+};
+
+function topBorder(element){
+       return styleNumber(element, 'border-top-width');
+};
+
+function leftBorder(element){
+       return styleNumber(element, 'border-left-width');
+};
+
+function isBody(element){
+       return (/^(?:body|html)$/i).test(element.tagName);
+};
+
+function getCompatElement(element){
+       var doc = element.getDocument();
+       return (!doc.compatMode || doc.compatMode == 'CSS1Compat') ? doc.html : doc.body;
+};
+
+})();
+
+//aliases
+Element.alias('setPosition', 'position'); //compatability
+
+Native.implement([Window, Document, Element], {
+
+       getHeight: function(){
+               return this.getSize().y;
+       },
+
+       getWidth: function(){
+               return this.getSize().x;
+       },
+
+       getScrollTop: function(){
+               return this.getScroll().y;
+       },
+
+       getScrollLeft: function(){
+               return this.getScroll().x;
+       },
+
+       getScrollHeight: function(){
+               return this.getScrollSize().y;
+       },
+
+       getScrollWidth: function(){
+               return this.getScrollSize().x;
+       },
+
+       getTop: function(){
+               return this.getPosition().y;
+       },
+
+       getLeft: function(){
+               return this.getPosition().x;
+       }
+
+});
+
+
+/*
+---
+
+script: Selectors.js
+
+description: Adds advanced CSS-style querying capabilities for targeting HTML Elements. Includes pseudo selectors.
+
+license: MIT-style license.
+
+requires:
+- /Element
+
+provides: [Selectors]
+
+...
+*/
+
+Native.implement([Document, Element], {
+
+       getElements: function(expression, nocash){
+               expression = expression.split(',');
+               var items, local = {};
+               for (var i = 0, l = expression.length; i < l; i++){
+                       var selector = expression[i], elements = Selectors.Utils.search(this, selector, local);
+                       if (i != 0 && elements.item) elements = $A(elements);
+                       items = (i == 0) ? elements : (items.item) ? $A(items).concat(elements) : items.concat(elements);
+               }
+               return new Elements(items, {ddup: (expression.length > 1), cash: !nocash});
+       }
+
+});
+
+Element.implement({
+
+       match: function(selector){
+               if (!selector || (selector == this)) return true;
+               var tagid = Selectors.Utils.parseTagAndID(selector);
+               var tag = tagid[0], id = tagid[1];
+               if (!Selectors.Filters.byID(this, id) || !Selectors.Filters.byTag(this, tag)) return false;
+               var parsed = Selectors.Utils.parseSelector(selector);
+               return (parsed) ? Selectors.Utils.filter(this, parsed, {}) : true;
+       }
+
+});
+
+var Selectors = {Cache: {nth: {}, parsed: {}}};
+
+Selectors.RegExps = {
+       id: (/#([\w-]+)/),
+       tag: (/^(\w+|\*)/),
+       quick: (/^(\w+|\*)$/),
+       splitter: (/\s*([+>~\s])\s*([a-zA-Z#.*:\[])/g),
+       combined: (/\.([\w-]+)|\[(\w+)(?:([!*^$~|]?=)(["']?)([^\4]*?)\4)?\]|:([\w-]+)(?:\(["']?(.*?)?["']?\)|$)/g)
+};
+
+Selectors.Utils = {
+
+       chk: function(item, uniques){
+               if (!uniques) return true;
+               var uid = $uid(item);
+               if (!uniques[uid]) return uniques[uid] = true;
+               return false;
+       },
+
+       parseNthArgument: function(argument){
+               if (Selectors.Cache.nth[argument]) return Selectors.Cache.nth[argument];
+               var parsed = argument.match(/^([+-]?\d*)?([a-z]+)?([+-]?\d*)?$/);
+               if (!parsed) return false;
+               var inta = parseInt(parsed[1], 10);
+               var a = (inta || inta === 0) ? inta : 1;
+               var special = parsed[2] || false;
+               var b = parseInt(parsed[3], 10) || 0;
+               if (a != 0){
+                       b--;
+                       while (b < 1) b += a;
+                       while (b >= a) b -= a;
+               } else {
+                       a = b;
+                       special = 'index';
+               }
+               switch (special){
+                       case 'n': parsed = {a: a, b: b, special: 'n'}; break;
+                       case 'odd': parsed = {a: 2, b: 0, special: 'n'}; break;
+                       case 'even': parsed = {a: 2, b: 1, special: 'n'}; break;
+                       case 'first': parsed = {a: 0, special: 'index'}; break;
+                       case 'last': parsed = {special: 'last-child'}; break;
+                       case 'only': parsed = {special: 'only-child'}; break;
+                       default: parsed = {a: (a - 1), special: 'index'};
+               }
+
+               return Selectors.Cache.nth[argument] = parsed;
+       },
+
+       parseSelector: function(selector){
+               if (Selectors.Cache.parsed[selector]) return Selectors.Cache.parsed[selector];
+               var m, parsed = {classes: [], pseudos: [], attributes: []};
+               while ((m = Selectors.RegExps.combined.exec(selector))){
+                       var cn = m[1], an = m[2], ao = m[3], av = m[5], pn = m[6], pa = m[7];
+                       if (cn){
+                               parsed.classes.push(cn);
+                       } else if (pn){
+                               var parser = Selectors.Pseudo.get(pn);
+                               if (parser) parsed.pseudos.push({parser: parser, argument: pa});
+                               else parsed.attributes.push({name: pn, operator: '=', value: pa});
+                       } else if (an){
+                               parsed.attributes.push({name: an, operator: ao, value: av});
+                       }
+               }
+               if (!parsed.classes.length) delete parsed.classes;
+               if (!parsed.attributes.length) delete parsed.attributes;
+               if (!parsed.pseudos.length) delete parsed.pseudos;
+               if (!parsed.classes && !parsed.attributes && !parsed.pseudos) parsed = null;
+               return Selectors.Cache.parsed[selector] = parsed;
+       },
+
+       parseTagAndID: function(selector){
+               var tag = selector.match(Selectors.RegExps.tag);
+               var id = selector.match(Selectors.RegExps.id);
+               return [(tag) ? tag[1] : '*', (id) ? id[1] : false];
+       },
+
+       filter: function(item, parsed, local){
+               var i;
+               if (parsed.classes){
+                       for (i = parsed.classes.length; i--; i){
+                               var cn = parsed.classes[i];
+                               if (!Selectors.Filters.byClass(item, cn)) return false;
+                       }
+               }
+               if (parsed.attributes){
+                       for (i = parsed.attributes.length; i--; i){
+                               var att = parsed.attributes[i];
+                               if (!Selectors.Filters.byAttribute(item, att.name, att.operator, att.value)) return false;
+                       }
+               }
+               if (parsed.pseudos){
+                       for (i = parsed.pseudos.length; i--; i){
+                               var psd = parsed.pseudos[i];
+                               if (!Selectors.Filters.byPseudo(item, psd.parser, psd.argument, local)) return false;
+                       }
+               }
+               return true;
+       },
+
+       getByTagAndID: function(ctx, tag, id){
+               if (id){
+                       var item = (ctx.getElementById) ? ctx.getElementById(id, true) : Element.getElementById(ctx, id, true);
+                       return (item && Selectors.Filters.byTag(item, tag)) ? [item] : [];
+               } else {
+                       return ctx.getElementsByTagName(tag);
+               }
+       },
+
+       search: function(self, expression, local){
+               var splitters = [];
+
+               var selectors = expression.trim().replace(Selectors.RegExps.splitter, function(m0, m1, m2){
+                       splitters.push(m1);
+                       return ':)' + m2;
+               }).split(':)');
+
+               var items, filtered, item;
+
+               for (var i = 0, l = selectors.length; i < l; i++){
+
+                       var selector = selectors[i];
+
+                       if (i == 0 && Selectors.RegExps.quick.test(selector)){
+                               items = self.getElementsByTagName(selector);
+                               continue;
+                       }
+
+                       var splitter = splitters[i - 1];
+
+                       var tagid = Selectors.Utils.parseTagAndID(selector);
+                       var tag = tagid[0], id = tagid[1];
+
+                       if (i == 0){
+                               items = Selectors.Utils.getByTagAndID(self, tag, id);
+                       } else {
+                               var uniques = {}, found = [];
+                               for (var j = 0, k = items.length; j < k; j++) found = Selectors.Getters[splitter](found, items[j], tag, id, uniques);
+                               items = found;
+                       }
+
+                       var parsed = Selectors.Utils.parseSelector(selector);
+
+                       if (parsed){
+                               filtered = [];
+                               for (var m = 0, n = items.length; m < n; m++){
+                                       item = items[m];
+                                       if (Selectors.Utils.filter(item, parsed, local)) filtered.push(item);
+                               }
+                               items = filtered;
+                       }
+
+               }
+
+               return items;
+
+       }
+
+};
+
+Selectors.Getters = {
+
+       ' ': function(found, self, tag, id, uniques){
+               var items = Selectors.Utils.getByTagAndID(self, tag, id);
+               for (var i = 0, l = items.length; i < l; i++){
+                       var item = items[i];
+                       if (Selectors.Utils.chk(item, uniques)) found.push(item);
+               }
+               return found;
+       },
+
+       '>': function(found, self, tag, id, uniques){
+               var children = Selectors.Utils.getByTagAndID(self, tag, id);
+               for (var i = 0, l = children.length; i < l; i++){
+                       var child = children[i];
+                       if (child.parentNode == self && Selectors.Utils.chk(child, uniques)) found.push(child);
+               }
+               return found;
+       },
+
+       '+': function(found, self, tag, id, uniques){
+               while ((self = self.nextSibling)){
+                       if (self.nodeType == 1){
+                               if (Selectors.Utils.chk(self, uniques) && Selectors.Filters.byTag(self, tag) && Selectors.Filters.byID(self, id)) found.push(self);
+                               break;
+                       }
+               }
+               return found;
+       },
+
+       '~': function(found, self, tag, id, uniques){
+               while ((self = self.nextSibling)){
+                       if (self.nodeType == 1){
+                               if (!Selectors.Utils.chk(self, uniques)) break;
+                               if (Selectors.Filters.byTag(self, tag) && Selectors.Filters.byID(self, id)) found.push(self);
+                       }
+               }
+               return found;
+       }
+
+};
+
+Selectors.Filters = {
+
+       byTag: function(self, tag){
+               return (tag == '*' || (self.tagName && self.tagName.toLowerCase() == tag));
+       },
+
+       byID: function(self, id){
+               return (!id || (self.id && self.id == id));
+       },
+
+       byClass: function(self, klass){
+               return (self.className && self.className.contains && self.className.contains(klass, ' '));
+       },
+
+       byPseudo: function(self, parser, argument, local){
+               return parser.call(self, argument, local);
+       },
+
+       byAttribute: function(self, name, operator, value){
+               var result = Element.prototype.getProperty.call(self, name);
+               if (!result) return (operator == '!=');
+               if (!operator || value == undefined) return true;
+               switch (operator){
+                       case '=': return (result == value);
+                       case '*=': return (result.contains(value));
+                       case '^=': return (result.substr(0, value.length) == value);
+                       case '$=': return (result.substr(result.length - value.length) == value);
+                       case '!=': return (result != value);
+                       case '~=': return result.contains(value, ' ');
+                       case '|=': return result.contains(value, '-');
+               }
+               return false;
+       }
+
+};
+
+Selectors.Pseudo = new Hash({
+
+       // w3c pseudo selectors
+
+       checked: function(){
+               return this.checked;
+       },
+       
+       empty: function(){
+               return !(this.innerText || this.textContent || '').length;
+       },
+
+       not: function(selector){
+               return !Element.match(this, selector);
+       },
+
+       contains: function(text){
+               return (this.innerText || this.textContent || '').contains(text);
+       },
+
+       'first-child': function(){
+               return Selectors.Pseudo.index.call(this, 0);
+       },
+
+       'last-child': function(){
+               var element = this;
+               while ((element = element.nextSibling)){
+                       if (element.nodeType == 1) return false;
+               }
+               return true;
+       },
+
+       'only-child': function(){
+               var prev = this;
+               while ((prev = prev.previousSibling)){
+                       if (prev.nodeType == 1) return false;
+               }
+               var next = this;
+               while ((next = next.nextSibling)){
+                       if (next.nodeType == 1) return false;
+               }
+               return true;
+       },
+
+       'nth-child': function(argument, local){
+               argument = (argument == undefined) ? 'n' : argument;
+               var parsed = Selectors.Utils.parseNthArgument(argument);
+               if (parsed.special != 'n') return Selectors.Pseudo[parsed.special].call(this, parsed.a, local);
+               var count = 0;
+               local.positions = local.positions || {};
+               var uid = $uid(this);
+               if (!local.positions[uid]){
+                       var self = this;
+                       while ((self = self.previousSibling)){
+                               if (self.nodeType != 1) continue;
+                               count ++;
+                               var position = local.positions[$uid(self)];
+                               if (position != undefined){
+                                       count = position + count;
+                                       break;
+                               }
+                       }
+                       local.positions[uid] = count;
+               }
+               return (local.positions[uid] % parsed.a == parsed.b);
+       },
+
+       // custom pseudo selectors
+
+       index: function(index){
+               var element = this, count = 0;
+               while ((element = element.previousSibling)){
+                       if (element.nodeType == 1 && ++count > index) return false;
+               }
+               return (count == index);
+       },
+
+       even: function(argument, local){
+               return Selectors.Pseudo['nth-child'].call(this, '2n+1', local);
+       },
+
+       odd: function(argument, local){
+               return Selectors.Pseudo['nth-child'].call(this, '2n', local);
+       },
+       
+       selected: function(){
+               return this.selected;
+       },
+       
+       enabled: function(){
+               return (this.disabled === false);
+       }
+
+});
+
+
+/*
+---
+
+script: DomReady.js
+
+description: Contains the custom event domready.
+
+license: MIT-style license.
+
+requires:
+- /Element.Event
+
+provides: [DomReady]
+
+...
+*/
+
+Element.Events.domready = {
+
+       onAdd: function(fn){
+               if (Browser.loaded) fn.call(this);
+       }
+
+};
+
+(function(){
+
+       var domready = function(){
+               if (Browser.loaded) return;
+               Browser.loaded = true;
+               window.fireEvent('domready');
+               document.fireEvent('domready');
+       };
+       
+       window.addEvent('load', domready);
+
+       if (Browser.Engine.trident){
+               var temp = document.createElement('div');
+               (function(){
+                       ($try(function(){
+                               temp.doScroll(); // Technique by Diego Perini
+                               return document.id(temp).inject(document.body).set('html', 'temp').dispose();
+                       })) ? domready() : arguments.callee.delay(50);
+               })();
+       } else if (Browser.Engine.webkit && Browser.Engine.version < 525){
+               (function(){
+                       (['loaded', 'complete'].contains(document.readyState)) ? domready() : arguments.callee.delay(50);
+               })();
+       } else {
+               document.addEvent('DOMContentLoaded', domready);
+       }
+
+})();
+
+
+/*
+---
+
+script: JSON.js
+
+description: JSON encoder and decoder.
+
+license: MIT-style license.
+
+See Also: <http://www.json.org/>
+
+requires:
+- /Array
+- /String
+- /Number
+- /Function
+- /Hash
+
+provides: [JSON]
+
+...
+*/
+
+var JSON = new Hash(this.JSON && {
+       stringify: JSON.stringify,
+       parse: JSON.parse
+}).extend({
+       
+       $specialChars: {'\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\'},
+
+       $replaceChars: function(chr){
+               return JSON.$specialChars[chr] || '\\u00' + Math.floor(chr.charCodeAt() / 16).toString(16) + (chr.charCodeAt() % 16).toString(16);
+       },
+
+       encode: function(obj){
+               switch ($type(obj)){
+                       case 'string':
+                               return '"' + obj.replace(/[\x00-\x1f\\"]/g, JSON.$replaceChars) + '"';
+                       case 'array':
+                               return '[' + String(obj.map(JSON.encode).clean()) + ']';
+                       case 'object': case 'hash':
+                               var string = [];
+                               Hash.each(obj, function(value, key){
+                                       var json = JSON.encode(value);
+                                       if (json) string.push(JSON.encode(key) + ':' + json);
+                               });
+                               return '{' + string + '}';
+                       case 'number': case 'boolean': return String(obj);
+                       case false: return 'null';
+               }
+               return null;
+       },
+
+       decode: function(string, secure){
+               if ($type(string) != 'string' || !string.length) return null;
+               if (secure && !(/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(string.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, ''))) return null;
+               return eval('(' + string + ')');
+       }
+
+});
+
+Native.implement([Hash, Array, String, Number], {
+
+       toJSON: function(){
+               return JSON.encode(this);
+       }
+
+});
+
+
+/*
+---
+
+script: Cookie.js
+
+description: Class for creating, reading, and deleting browser Cookies.
+
+license: MIT-style license.
+
+credits:
+- Based on the functions by Peter-Paul Koch (http://quirksmode.org).
+
+requires:
+- /Options
+
+provides: [Cookie]
+
+...
+*/
+
+var Cookie = new Class({
+
+       Implements: Options,
+
+       options: {
+               path: false,
+               domain: false,
+               duration: false,
+               secure: false,
+               document: document
+       },
+
+       initialize: function(key, options){
+               this.key = key;
+               this.setOptions(options);
+       },
+
+       write: function(value){
+               value = encodeURIComponent(value);
+               if (this.options.domain) value += '; domain=' + this.options.domain;
+               if (this.options.path) value += '; path=' + this.options.path;
+               if (this.options.duration){
+                       var date = new Date();
+                       date.setTime(date.getTime() + this.options.duration * 24 * 60 * 60 * 1000);
+                       value += '; expires=' + date.toGMTString();
+               }
+               if (this.options.secure) value += '; secure';
+               this.options.document.cookie = this.key + '=' + value;
+               return this;
+       },
+
+       read: function(){
+               var value = this.options.document.cookie.match('(?:^|;)\\s*' + this.key.escapeRegExp() + '=([^;]*)');
+               return (value) ? decodeURIComponent(value[1]) : null;
+       },
+
+       dispose: function(){
+               new Cookie(this.key, $merge(this.options, {duration: -1})).write('');
+               return this;
+       }
+
+});
+
+Cookie.write = function(key, value, options){
+       return new Cookie(key, options).write(value);
+};
+
+Cookie.read = function(key){
+       return new Cookie(key).read();
+};
+
+Cookie.dispose = function(key, options){
+       return new Cookie(key, options).dispose();
+};
+
+
+/*
+---
+
+script: Swiff.js
+
+description: Wrapper for embedding SWF movies. Supports External Interface Communication.
+
+license: MIT-style license.
+
+credits: 
+- Flash detection & Internet Explorer + Flash Player 9 fix inspired by SWFObject.
+
+requires:
+- /Options
+- /$util
+
+provides: [Swiff]
+
+...
+*/
+
+var Swiff = new Class({
+
+       Implements: [Options],
+
+       options: {
+               id: null,
+               height: 1,
+               width: 1,
+               container: null,
+               properties: {},
+               params: {
+                       quality: 'high',
+                       allowScriptAccess: 'always',
+                       wMode: 'transparent',
+                       swLiveConnect: true
+               },
+               callBacks: {},
+               vars: {}
+       },
+
+       toElement: function(){
+               return this.object;
+       },
+
+       initialize: function(path, options){
+               this.instance = 'Swiff_' + $time();
+
+               this.setOptions(options);
+               options = this.options;
+               var id = this.id = options.id || this.instance;
+               var container = document.id(options.container);
+
+               Swiff.CallBacks[this.instance] = {};
+
+               var params = options.params, vars = options.vars, callBacks = options.callBacks;
+               var properties = $extend({height: options.height, width: options.width}, options.properties);
+
+               var self = this;
+
+               for (var callBack in callBacks){
+                       Swiff.CallBacks[this.instance][callBack] = (function(option){
+                               return function(){
+                                       return option.apply(self.object, arguments);
+                               };
+                       })(callBacks[callBack]);
+                       vars[callBack] = 'Swiff.CallBacks.' + this.instance + '.' + callBack;
+               }
+
+               params.flashVars = Hash.toQueryString(vars);
+               if (Browser.Engine.trident){
+                       properties.classid = 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000';
+                       params.movie = path;
+               } else {
+                       properties.type = 'application/x-shockwave-flash';
+                       properties.data = path;
+               }
+               var build = '<object id="' + id + '"';
+               for (var property in properties) build += ' ' + property + '="' + properties[property] + '"';
+               build += '>';
+               for (var param in params){
+                       if (params[param]) build += '<param name="' + param + '" value="' + params[param] + '" />';
+               }
+               build += '</object>';
+               this.object = ((container) ? container.empty() : new Element('div')).set('html', build).firstChild;
+       },
+
+       replaces: function(element){
+               element = document.id(element, true);
+               element.parentNode.replaceChild(this.toElement(), element);
+               return this;
+       },
+
+       inject: function(element){
+               document.id(element, true).appendChild(this.toElement());
+               return this;
+       },
+
+       remote: function(){
+               return Swiff.remote.apply(Swiff, [this.toElement()].extend(arguments));
+       }
+
+});
+
+Swiff.CallBacks = {};
+
+Swiff.remote = function(obj, fn){
+       var rs = obj.CallFunction('<invoke name="' + fn + '" returntype="javascript">' + __flash__argumentsToXML(arguments, 2) + '</invoke>');
+       return eval(rs);
+};
+
+
+/*
+---
+
+script: Fx.js
+
+description: Contains the basic animation logic to be extended by all other Fx Classes.
+
+license: MIT-style license.
+
+requires:
+- /Chain
+- /Events
+- /Options
+
+provides: [Fx]
+
+...
+*/
+
+var Fx = new Class({
+
+       Implements: [Chain, Events, Options],
+
+       options: {
+               /*
+               onStart: $empty,
+               onCancel: $empty,
+               onComplete: $empty,
+               */
+               fps: 50,
+               unit: false,
+               duration: 500,
+               link: 'ignore'
+       },
+
+       initialize: function(options){
+               this.subject = this.subject || this;
+               this.setOptions(options);
+               this.options.duration = Fx.Durations[this.options.duration] || this.options.duration.toInt();
+               var wait = this.options.wait;
+               if (wait === false) this.options.link = 'cancel';
+       },
+
+       getTransition: function(){
+               return function(p){
+                       return -(Math.cos(Math.PI * p) - 1) / 2;
+               };
+       },
+
+       step: function(){
+               var time = $time();
+               if (time < this.time + this.options.duration){
+                       var delta = this.transition((time - this.time) / this.options.duration);
+                       this.set(this.compute(this.from, this.to, delta));
+               } else {
+                       this.set(this.compute(this.from, this.to, 1));
+                       this.complete();
+               }
+       },
+
+       set: function(now){
+               return now;
+       },
+
+       compute: function(from, to, delta){
+               return Fx.compute(from, to, delta);
+       },
+
+       check: function(){
+               if (!this.timer) return true;
+               switch (this.options.link){
+                       case 'cancel': this.cancel(); return true;
+                       case 'chain': this.chain(this.caller.bind(this, arguments)); return false;
+               }
+               return false;
+       },
+
+       start: function(from, to){
+               if (!this.check(from, to)) return this;
+               this.from = from;
+               this.to = to;
+               this.time = 0;
+               this.transition = this.getTransition();
+               this.startTimer();
+               this.onStart();
+               return this;
+       },
+
+       complete: function(){
+               if (this.stopTimer()) this.onComplete();
+               return this;
+       },
+
+       cancel: function(){
+               if (this.stopTimer()) this.onCancel();
+               return this;
+       },
+
+       onStart: function(){
+               this.fireEvent('start', this.subject);
+       },
+
+       onComplete: function(){
+               this.fireEvent('complete', this.subject);
+               if (!this.callChain()) this.fireEvent('chainComplete', this.subject);
+       },
+
+       onCancel: function(){
+               this.fireEvent('cancel', this.subject).clearChain();
+       },
+
+       pause: function(){
+               this.stopTimer();
+               return this;
+       },
+
+       resume: function(){
+               this.startTimer();
+               return this;
+       },
+
+       stopTimer: function(){
+               if (!this.timer) return false;
+               this.time = $time() - this.time;
+               this.timer = $clear(this.timer);
+               return true;
+       },
+
+       startTimer: function(){
+               if (this.timer) return false;
+               this.time = $time() - this.time;
+               this.timer = this.step.periodical(Math.round(1000 / this.options.fps), this);
+               return true;
+       }
+
+});
+
+Fx.compute = function(from, to, delta){
+       return (to - from) * delta + from;
+};
+
+Fx.Durations = {'short': 250, 'normal': 500, 'long': 1000};
+
+
+/*
+---
+
+script: Fx.CSS.js
+
+description: Contains the CSS animation logic. Used by Fx.Tween, Fx.Morph, Fx.Elements.
+
+license: MIT-style license.
+
+requires:
+- /Fx
+- /Element.Style
+
+provides: [Fx.CSS]
+
+...
+*/
+
+Fx.CSS = new Class({
+
+       Extends: Fx,
+
+       //prepares the base from/to object
+
+       prepare: function(element, property, values){
+               values = $splat(values);
+               var values1 = values[1];
+               if (!$chk(values1)){
+                       values[1] = values[0];
+                       values[0] = element.getStyle(property);
+               }
+               var parsed = values.map(this.parse);
+               return {from: parsed[0], to: parsed[1]};
+       },
+
+       //parses a value into an array
+
+       parse: function(value){
+               value = $lambda(value)();
+               value = (typeof value == 'string') ? value.split(' ') : $splat(value);
+               return value.map(function(val){
+                       val = String(val);
+                       var found = false;
+                       Fx.CSS.Parsers.each(function(parser, key){
+                               if (found) return;
+                               var parsed = parser.parse(val);
+                               if ($chk(parsed)) found = {value: parsed, parser: parser};
+                       });
+                       found = found || {value: val, parser: Fx.CSS.Parsers.String};
+                       return found;
+               });
+       },
+
+       //computes by a from and to prepared objects, using their parsers.
+
+       compute: function(from, to, delta){
+               var computed = [];
+               (Math.min(from.length, to.length)).times(function(i){
+                       computed.push({value: from[i].parser.compute(from[i].value, to[i].value, delta), parser: from[i].parser});
+               });
+               computed.$family = {name: 'fx:css:value'};
+               return computed;
+       },
+
+       //serves the value as settable
+
+       serve: function(value, unit){
+               if ($type(value) != 'fx:css:value') value = this.parse(value);
+               var returned = [];
+               value.each(function(bit){
+                       returned = returned.concat(bit.parser.serve(bit.value, unit));
+               });
+               return returned;
+       },
+
+       //renders the change to an element
+
+       render: function(element, property, value, unit){
+               element.setStyle(property, this.serve(value, unit));
+       },
+
+       //searches inside the page css to find the values for a selector
+
+       search: function(selector){
+               if (Fx.CSS.Cache[selector]) return Fx.CSS.Cache[selector];
+               var to = {};
+               Array.each(document.styleSheets, function(sheet, j){
+                       var href = sheet.href;
+                       if (href && href.contains('://') && !href.contains(document.domain)) return;
+                       var rules = sheet.rules || sheet.cssRules;
+                       Array.each(rules, function(rule, i){
+                               if (!rule.style) return;
+                               var selectorText = (rule.selectorText) ? rule.selectorText.replace(/^\w+/, function(m){
+                                       return m.toLowerCase();
+                               }) : null;
+                               if (!selectorText || !selectorText.test('^' + selector + '$')) return;
+                               Element.Styles.each(function(value, style){
+                                       if (!rule.style[style] || Element.ShortStyles[style]) return;
+                                       value = String(rule.style[style]);
+                                       to[style] = (value.test(/^rgb/)) ? value.rgbToHex() : value;
+                               });
+                       });
+               });
+               return Fx.CSS.Cache[selector] = to;
+       }
+
+});
+
+Fx.CSS.Cache = {};
+
+Fx.CSS.Parsers = new Hash({
+
+       Color: {
+               parse: function(value){
+                       if (value.match(/^#[0-9a-f]{3,6}$/i)) return value.hexToRgb(true);
+                       return ((value = value.match(/(\d+),\s*(\d+),\s*(\d+)/))) ? [value[1], value[2], value[3]] : false;
+               },
+               compute: function(from, to, delta){
+                       return from.map(function(value, i){
+                               return Math.round(Fx.compute(from[i], to[i], delta));
+                       });
+               },
+               serve: function(value){
+                       return value.map(Number);
+               }
+       },
+
+       Number: {
+               parse: parseFloat,
+               compute: Fx.compute,
+               serve: function(value, unit){
+                       return (unit) ? value + unit : value;
+               }
+       },
+
+       String: {
+               parse: $lambda(false),
+               compute: $arguments(1),
+               serve: $arguments(0)
+       }
+
+});
+
+
+/*
+---
+
+script: Fx.Tween.js
+
+description: Formerly Fx.Style, effect to transition any CSS property for an element.
+
+license: MIT-style license.
+
+requires: 
+- /Fx.CSS
+
+provides: [Fx.Tween, Element.fade, Element.highlight]
+
+...
+*/
+
+Fx.Tween = new Class({
+
+       Extends: Fx.CSS,
+
+       initialize: function(element, options){
+               this.element = this.subject = document.id(element);
+               this.parent(options);
+       },
+
+       set: function(property, now){
+               if (arguments.length == 1){
+                       now = property;
+                       property = this.property || this.options.property;
+               }
+               this.render(this.element, property, now, this.options.unit);
+               return this;
+       },
+
+       start: function(property, from, to){
+               if (!this.check(property, from, to)) return this;
+               var args = Array.flatten(arguments);
+               this.property = this.options.property || args.shift();
+               var parsed = this.prepare(this.element, this.property, args);
+               return this.parent(parsed.from, parsed.to);
+       }
+
+});
+
+Element.Properties.tween = {
+
+       set: function(options){
+               var tween = this.retrieve('tween');
+               if (tween) tween.cancel();
+               return this.eliminate('tween').store('tween:options', $extend({link: 'cancel'}, options));
+       },
+
+       get: function(options){
+               if (options || !this.retrieve('tween')){
+                       if (options || !this.retrieve('tween:options')) this.set('tween', options);
+                       this.store('tween', new Fx.Tween(this, this.retrieve('tween:options')));
+               }
+               return this.retrieve('tween');
+       }
+
+};
+
+Element.implement({
+
+       tween: function(property, from, to){
+               this.get('tween').start(arguments);
+               return this;
+       },
+
+       fade: function(how){
+               var fade = this.get('tween'), o = 'opacity', toggle;
+               how = $pick(how, 'toggle');
+               switch (how){
+                       case 'in': fade.start(o, 1); break;
+                       case 'out': fade.start(o, 0); break;
+                       case 'show': fade.set(o, 1); break;
+                       case 'hide': fade.set(o, 0); break;
+                       case 'toggle':
+                               var flag = this.retrieve('fade:flag', this.get('opacity') == 1);
+                               fade.start(o, (flag) ? 0 : 1);
+                               this.store('fade:flag', !flag);
+                               toggle = true;
+                       break;
+                       default: fade.start(o, arguments);
+               }
+               if (!toggle) this.eliminate('fade:flag');
+               return this;
+       },
+
+       highlight: function(start, end){
+               if (!end){
+                       end = this.retrieve('highlight:original', this.getStyle('background-color'));
+                       end = (end == 'transparent') ? '#fff' : end;
+               }
+               var tween = this.get('tween');
+               tween.start('background-color', start || '#ffff88', end).chain(function(){
+                       this.setStyle('background-color', this.retrieve('highlight:original'));
+                       tween.callChain();
+               }.bind(this));
+               return this;
+       }
+
+});
+
+
+/*
+---
+
+script: Fx.Morph.js
+
+description: Formerly Fx.Styles, effect to transition any number of CSS properties for an element using an object of rules, or CSS based selector rules.
+
+license: MIT-style license.
+
+requires:
+- /Fx.CSS
+
+provides: [Fx.Morph]
+
+...
+*/
+
+Fx.Morph = new Class({
+
+       Extends: Fx.CSS,
+
+       initialize: function(element, options){
+               this.element = this.subject = document.id(element);
+               this.parent(options);
+       },
+
+       set: function(now){
+               if (typeof now == 'string') now = this.search(now);
+               for (var p in now) this.render(this.element, p, now[p], this.options.unit);
+               return this;
+       },
+
+       compute: function(from, to, delta){
+               var now = {};
+               for (var p in from) now[p] = this.parent(from[p], to[p], delta);
+               return now;
+       },
+
+       start: function(properties){
+               if (!this.check(properties)) return this;
+               if (typeof properties == 'string') properties = this.search(properties);
+               var from = {}, to = {};
+               for (var p in properties){
+                       var parsed = this.prepare(this.element, p, properties[p]);
+                       from[p] = parsed.from;
+                       to[p] = parsed.to;
+               }
+               return this.parent(from, to);
+       }
+
+});
+
+Element.Properties.morph = {
+
+       set: function(options){
+               var morph = this.retrieve('morph');
+               if (morph) morph.cancel();
+               return this.eliminate('morph').store('morph:options', $extend({link: 'cancel'}, options));
+       },
+
+       get: function(options){
+               if (options || !this.retrieve('morph')){
+                       if (options || !this.retrieve('morph:options')) this.set('morph', options);
+                       this.store('morph', new Fx.Morph(this, this.retrieve('morph:options')));
+               }
+               return this.retrieve('morph');
+       }
+
+};
+
+Element.implement({
+
+       morph: function(props){
+               this.get('morph').start(props);
+               return this;
+       }
+
+});
+
+
+/*
+---
+
+script: Fx.Transitions.js
+
+description: Contains a set of advanced transitions to be used with any of the Fx Classes.
+
+license: MIT-style license.
+
+credits:
+- Easing Equations by Robert Penner, <http://www.robertpenner.com/easing/>, modified and optimized to be used with MooTools.
+
+requires:
+- /Fx
+
+provides: [Fx.Transitions]
+
+...
+*/
+
+Fx.implement({
+
+       getTransition: function(){
+               var trans = this.options.transition || Fx.Transitions.Sine.easeInOut;
+               if (typeof trans == 'string'){
+                       var data = trans.split(':');
+                       trans = Fx.Transitions;
+                       trans = trans[data[0]] || trans[data[0].capitalize()];
+                       if (data[1]) trans = trans['ease' + data[1].capitalize() + (data[2] ? data[2].capitalize() : '')];
+               }
+               return trans;
+       }
+
+});
+
+Fx.Transition = function(transition, params){
+       params = $splat(params);
+       return $extend(transition, {
+               easeIn: function(pos){
+                       return transition(pos, params);
+               },
+               easeOut: function(pos){
+                       return 1 - transition(1 - pos, params);
+               },
+               easeInOut: function(pos){
+                       return (pos <= 0.5) ? transition(2 * pos, params) / 2 : (2 - transition(2 * (1 - pos), params)) / 2;
+               }
+       });
+};
+
+Fx.Transitions = new Hash({
+
+       linear: $arguments(0)
+
+});
+
+Fx.Transitions.extend = function(transitions){
+       for (var transition in transitions) Fx.Transitions[transition] = new Fx.Transition(transitions[transition]);
+};
+
+Fx.Transitions.extend({
+
+       Pow: function(p, x){
+               return Math.pow(p, x[0] || 6);
+       },
+
+       Expo: function(p){
+               return Math.pow(2, 8 * (p - 1));
+       },
+
+       Circ: function(p){
+               return 1 - Math.sin(Math.acos(p));
+       },
+
+       Sine: function(p){
+               return 1 - Math.sin((1 - p) * Math.PI / 2);
+       },
+
+       Back: function(p, x){
+               x = x[0] || 1.618;
+               return Math.pow(p, 2) * ((x + 1) * p - x);
+       },
+
+       Bounce: function(p){
+               var value;
+               for (var a = 0, b = 1; 1; a += b, b /= 2){
+                       if (p >= (7 - 4 * a) / 11){
+                               value = b * b - Math.pow((11 - 6 * a - 11 * p) / 4, 2);
+                               break;
+                       }
+               }
+               return value;
+       },
+
+       Elastic: function(p, x){
+               return Math.pow(2, 10 * --p) * Math.cos(20 * p * Math.PI * (x[0] || 1) / 3);
+       }
+
+});
+
+['Quad', 'Cubic', 'Quart', 'Quint'].each(function(transition, i){
+       Fx.Transitions[transition] = new Fx.Transition(function(p){
+               return Math.pow(p, [i + 2]);
+       });
+});
+
+
+/*
+---
+
+script: Request.js
+
+description: Powerful all purpose Request Class. Uses XMLHTTPRequest.
+
+license: MIT-style license.
+
+requires:
+- /Element
+- /Chain
+- /Events
+- /Options
+- /Browser
+
+provides: [Request]
+
+...
+*/
+
+var Request = new Class({
+
+       Implements: [Chain, Events, Options],
+
+       options: {/*
+               onRequest: $empty,
+               onComplete: $empty,
+               onCancel: $empty,
+               onSuccess: $empty,
+               onFailure: $empty,
+               onException: $empty,*/
+               url: '',
+               data: '',
+               headers: {
+                       'X-Requested-With': 'XMLHttpRequest',
+                       'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
+               },
+               async: true,
+               format: false,
+               method: 'post',
+               link: 'ignore',
+               isSuccess: null,
+               emulation: true,
+               urlEncoded: true,
+               encoding: 'utf-8',
+               evalScripts: false,
+               evalResponse: false,
+               noCache: false
+       },
+
+       initialize: function(options){
+               this.xhr = new Browser.Request();
+               this.setOptions(options);
+               this.options.isSuccess = this.options.isSuccess || this.isSuccess;
+               this.headers = new Hash(this.options.headers);
+       },
+
+       onStateChange: function(){
+               if (this.xhr.readyState != 4 || !this.running) return;
+               this.running = false;
+               this.status = 0;
+               $try(function(){
+                       this.status = this.xhr.status;
+               }.bind(this));
+               this.xhr.onreadystatechange = $empty;
+               if (this.options.isSuccess.call(this, this.status)){
+                       this.response = {text: this.xhr.responseText, xml: this.xhr.responseXML};
+                       this.success(this.response.text, this.response.xml);
+               } else {
+                       this.response = {text: null, xml: null};
+                       this.failure();
+               }
+       },
+
+       isSuccess: function(){
+               return ((this.status >= 200) && (this.status < 300));
+       },
+
+       processScripts: function(text){
+               if (this.options.evalResponse || (/(ecma|java)script/).test(this.getHeader('Content-type'))) return $exec(text);
+               return text.stripScripts(this.options.evalScripts);
+       },
+
+       success: function(text, xml){
+               this.onSuccess(this.processScripts(text), xml);
+       },
+
+       onSuccess: function(){
+               this.fireEvent('complete', arguments).fireEvent('success', arguments).callChain();
+       },
+
+       failure: function(){
+               this.onFailure();
+       },
+
+       onFailure: function(){
+               this.fireEvent('complete').fireEvent('failure', this.xhr);
+       },
+
+       setHeader: function(name, value){
+               this.headers.set(name, value);
+               return this;
+       },
+
+       getHeader: function(name){
+               return $try(function(){
+                       return this.xhr.getResponseHeader(name);
+               }.bind(this));
+       },
+
+       check: function(){
+               if (!this.running) return true;
+               switch (this.options.link){
+                       case 'cancel': this.cancel(); return true;
+                       case 'chain': this.chain(this.caller.bind(this, arguments)); return false;
+               }
+               return false;
+       },
+
+       send: function(options){
+               if (!this.check(options)) return this;
+               this.running = true;
+
+               var type = $type(options);
+               if (type == 'string' || type == 'element') options = {data: options};
+
+               var old = this.options;
+               options = $extend({data: old.data, url: old.url, method: old.method}, options);
+               var data = options.data, url = String(options.url), method = options.method.toLowerCase();
+
+               switch ($type(data)){
+                       case 'element': data = document.id(data).toQueryString(); break;
+                       case 'object': case 'hash': data = Hash.toQueryString(data);
+               }
+
+               if (this.options.format){
+                       var format = 'format=' + this.options.format;
+                       data = (data) ? format + '&' + data : format;
+               }
+
+               if (this.options.emulation && !['get', 'post'].contains(method)){
+                       var _method = '_method=' + method;
+                       data = (data) ? _method + '&' + data : _method;
+                       method = 'post';
+               }
+
+               if (this.options.urlEncoded && method == 'post'){
+                       var encoding = (this.options.encoding) ? '; charset=' + this.options.encoding : '';
+                       this.headers.set('Content-type', 'application/x-www-form-urlencoded' + encoding);
+               }
+
+               if (this.options.noCache){
+                       var noCache = 'noCache=' + new Date().getTime();
+                       data = (data) ? noCache + '&' + data : noCache;
+               }
+
+               var trimPosition = url.lastIndexOf('/');
+               if (trimPosition > -1 && (trimPosition = url.indexOf('#')) > -1) url = url.substr(0, trimPosition);
+
+               if (data && method == 'get'){
+                       url = url + (url.contains('?') ? '&' : '?') + data;
+                       data = null;
+               }
+
+               this.xhr.open(method.toUpperCase(), url, this.options.async);
+
+               this.xhr.onreadystatechange = this.onStateChange.bind(this);
+
+               this.headers.each(function(value, key){
+                       try {
+                               this.xhr.setRequestHeader(key, value);
+                       } catch (e){
+                               this.fireEvent('exception', [key, value]);
+                       }
+               }, this);
+
+               this.fireEvent('request');
+               this.xhr.send(data);
+               if (!this.options.async) this.onStateChange();
+               return this;
+       },
+
+       cancel: function(){
+               if (!this.running) return this;
+               this.running = false;
+               this.xhr.abort();
+               this.xhr.onreadystatechange = $empty;
+               this.xhr = new Browser.Request();
+               this.fireEvent('cancel');
+               return this;
+       }
+
+});
+
+(function(){
+
+var methods = {};
+['get', 'post', 'put', 'delete', 'GET', 'POST', 'PUT', 'DELETE'].each(function(method){
+       methods[method] = function(){
+               var params = Array.link(arguments, {url: String.type, data: $defined});
+               return this.send($extend(params, {method: method}));
+       };
+});
+
+Request.implement(methods);
+
+})();
+
+Element.Properties.send = {
+
+       set: function(options){
+               var send = this.retrieve('send');
+               if (send) send.cancel();
+               return this.eliminate('send').store('send:options', $extend({
+                       data: this, link: 'cancel', method: this.get('method') || 'post', url: this.get('action')
+               }, options));
+       },
+
+       get: function(options){
+               if (options || !this.retrieve('send')){
+                       if (options || !this.retrieve('send:options')) this.set('send', options);
+                       this.store('send', new Request(this.retrieve('send:options')));
+               }
+               return this.retrieve('send');
+       }
+
+};
+
+Element.implement({
+
+       send: function(url){
+               var sender = this.get('send');
+               sender.send({data: this, url: url || sender.options.url});
+               return this;
+       }
+
+});
+
+
+/*
+---
+
+script: Request.HTML.js
+
+description: Extends the basic Request Class with additional methods for interacting with HTML responses.
+
+license: MIT-style license.
+
+requires:
+- /Request
+- /Element
+
+provides: [Request.HTML]
+
+...
+*/
+
+Request.HTML = new Class({
+
+       Extends: Request,
+
+       options: {
+               update: false,
+               append: false,
+               evalScripts: true,
+               filter: false
+       },
+
+       processHTML: function(text){
+               var match = text.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
+               text = (match) ? match[1] : text;
+
+               var container = new Element('div');
+
+               return $try(function(){
+                       var root = '<root>' + text + '</root>', doc;
+                       if (Browser.Engine.trident){
+                               doc = new ActiveXObject('Microsoft.XMLDOM');
+                               doc.async = false;
+                               doc.loadXML(root);
+                       } else {
+                               doc = new DOMParser().parseFromString(root, 'text/xml');
+                       }
+                       root = doc.getElementsByTagName('root')[0];
+                       if (!root) return null;
+                       for (var i = 0, k = root.childNodes.length; i < k; i++){
+                               var child = Element.clone(root.childNodes[i], true, true);
+                               if (child) container.grab(child);
+                       }
+                       return container;
+               }) || container.set('html', text);
+       },
+
+       success: function(text){
+               var options = this.options, response = this.response;
+
+               response.html = text.stripScripts(function(script){
+                       response.javascript = script;
+               });
+
+               var temp = this.processHTML(response.html);
+
+               response.tree = temp.childNodes;
+               response.elements = temp.getElements('*');
+
+               if (options.filter) response.tree = response.elements.filter(options.filter);
+               if (options.update) document.id(options.update).empty().set('html', response.html);
+               else if (options.append) document.id(options.append).adopt(temp.getChildren());
+               if (options.evalScripts) $exec(response.javascript);
+
+               this.onSuccess(response.tree, response.elements, response.html, response.javascript);
+       }
+
+});
+
+Element.Properties.load = {
+
+       set: function(options){
+               var load = this.retrieve('load');
+               if (load) load.cancel();
+               return this.eliminate('load').store('load:options', $extend({data: this, link: 'cancel', update: this, method: 'get'}, options));
+       },
+
+       get: function(options){
+               if (options || ! this.retrieve('load')){
+                       if (options || !this.retrieve('load:options')) this.set('load', options);
+                       this.store('load', new Request.HTML(this.retrieve('load:options')));
+               }
+               return this.retrieve('load');
+       }
+
+};
+
+Element.implement({
+
+       load: function(){
+               this.get('load').send(Array.link(arguments, {data: Object.type, url: String.type}));
+               return this;
+       }
+
+});
+
+
+/*
+---
+
+script: Request.JSON.js
+
+description: Extends the basic Request Class with additional methods for sending and receiving JSON data.
+
+license: MIT-style license.
+
+requires:
+- /Request JSON
+
+provides: [Request.HTML]
+
+...
+*/
+
+Request.JSON = new Class({
+
+       Extends: Request,
+
+       options: {
+               secure: true
+       },
+
+       initialize: function(options){
+               this.parent(options);
+               this.headers.extend({'Accept': 'application/json', 'X-Request': 'JSON'});
+       },
+
+       success: function(text){
+               this.response.json = JSON.decode(text, this.options.secure);
+               this.onSuccess(this.response.json, text);
+       }
+
+});
diff --git a/plugins/pres_view/static/js/pres_view.js b/plugins/pres_view/static/js/pres_view.js
new file mode 100644 (file)
index 0000000..bd49c1c
--- /dev/null
@@ -0,0 +1,160 @@
+/**
+ * Description: PresView plugin
+ * Copyright (c) 2012 UPMC Sorbonne Universite
+ * License: GPLv3
+ */
+
+/*
+ * It's a best practice to pass jQuery to an IIFE (Immediately Invoked Function
+ * Expression) that maps it to the dollar sign so it can't be overwritten by
+ * another library in the scope of its execution.
+ */
+
+(function($){
+
+    var PLUGIN_NAME = 'PresView';
+
+    // routing calls
+    jQuery.fn.PresView = function( method ) {
+               if ( methods[method] ) {
+                       return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
+               } else if ( typeof method === 'object' || ! method ) {
+                       return methods.init.apply( this, arguments );
+               } else {
+                       jQuery.error( 'Method ' +  method + ' does not exist on jQuery.' + PLUGIN_NAME );
+               }    
+    };
+
+    /***************************************************************************
+     * Public methods
+     ***************************************************************************/
+
+    var methods = {
+
+        /**
+         * @brief Plugin initialization
+         * @param options : an associative array of setting values
+         * @return : a jQuery collection of objects on which the plugin is
+         *     applied, which allows to maintain chainability of calls
+         */
+        init : function ( options ) {
+
+            return this.each(function() {
+
+                var $this = $(this);
+
+                /* An object that will hold private variables and methods */
+                var plugin = new PresView(options);
+                $this.data('Manifold', plugin);
+
+                /* Events */
+                $this.on('show.' + PLUGIN_NAME, methods.show);
+
+            }); // this.each
+        }, // init
+
+        /**
+         * @brief Plugin destruction
+         * @return : a jQuery collection of objects on which the plugin is
+         *     applied, which allows to maintain chainability of calls
+         */
+        destroy : function( ) {
+
+            return this.each(function() {
+                var $this = $(this);
+                var plugin = $this.data('Manifold');
+
+                // Unbind all events using namespacing
+                $(window).unbind(PLUGIN_NAME);
+
+                // Remove associated data
+                plugin.remove();
+                $this.removeData('Manifold');
+            });
+        }, // destroy
+
+        show : function( ) {
+            google.maps.event.trigger(map, 'resize');
+        } // show
+
+    }; // var methods;
+
+    /***************************************************************************
+     * Plugin object
+     ***************************************************************************/
+
+    function PresView(options)
+    {
+
+        /* member variables */
+        this.options = options;
+
+        var object = this;
+      
+        /**
+         *
+         */
+        this.initialize = function() {
+                       //APE + no conflit
+            j = jQuery.noConflict();
+                   ape_initialize();
+                   j.getScript('/all-static/js/config.js');
+
+                       // jquery:datepicker
+                       j(".datepicker").datepicker({
+                               showOtherMonths: true,
+                               selectOtherMonths: true,
+                               showAnim: 'slideDown',
+                               //regional: 'fr',
+                               dateFormat: 'dd/mm/yy',
+                               setDate: -14
+                       });
+
+                       // jquery:accordion
+                       j("#accordion").accordion({ 
+                               animated: 'easeslide',
+                               autoHeight: false,
+                               //fillSpace: true
+                       });
+                       
+                       // jquery:slider
+                       j("#interval_animation").slider({
+                               min: 0.5,
+                               max: 10,
+                               step: 0.5,
+                               value: 4
+                       });
+
+                       // jquery:tooltip
+                       // http://www.alessioatzeni.com/blog/simple-tooltip-with-jquery-only-text/
+                       // Tooltip only Text
+                       j('.masterTooltip').hover(function(){
+                                       // Hover over code
+                                       var title = j('#interval_animation').attr('title');
+                                       j('#interval_animation').data('tipText', title).removeAttr('title');
+                                       j('<p class="tooltip"></p>')
+                                       .text(title)
+                                       .appendTo('body')
+                                       .fadeIn('slow');
+                       }, function() {
+                                       // Hover out code
+                                       j('#interval_animation').attr('title', j('#interval_animation').data('tipText'));
+                                       j('.tooltip').remove();
+                       }).mousemove(function(e) {
+                                       var mousex = e.pageX + 20; //Get X coordinates
+                                       var mousey = e.pageY + 10; //Get Y coordinates
+                                       j('.tooltip')
+                                       .css({ top: mousey, left: mousex })
+                       });
+        },
+      
+
+        /* Constructor */
+
+        this.initialize();
+
+    } // function PresView
+
+})( jQuery );
+
+
diff --git a/plugins/pres_view/static/js/recup_data.js b/plugins/pres_view/static/js/recup_data.js
new file mode 100644 (file)
index 0000000..ba930e2
--- /dev/null
@@ -0,0 +1,158 @@
+function recup_data (url,id,method)
+{                      
+                               var longueur;
+                               j.getJSON(url, function(data) 
+                               {
+                                       j.each(data     , function(key, val) 
+                                       {       
+                                               switch ( val.params.data.print_method )
+                                                       {
+                                                               case 'marker' :
+                                                                               pos_marker[id]= [];
+                                                                               opt_marker[id]= [];
+                                                                               marker[id]= [];
+                                                                               ref[id] = 'marker';
+                                                               break;
+                                                               case 'line' :
+                                                                               opt_line[id] =[];
+                                                                               pos_line[id]= [];
+                                                                               line[id]= [];
+                                                                               ref[id] = 'line';
+                                                               break;
+                                                               case 'circle' :
+                                                                               opt_circle[id] =[];
+                                                                               pos_circle[id]= [];
+                                                                               circle[id]= [];
+                                                                               ref[id] = 'circle';
+                                                               break;
+                                                               default:
+                                                                       alert ("unknown method");
+                                                               break;
+                                                       }       
+                                               for ( var i= 0; i<val.params.data.message.length;i++)
+                                               {
+                                                       var longueur;
+                                                       switch ( val.params.data.print_method )
+                                                       {
+                                                               case 'marker' :
+                                                                       pos_marker[id].push( new google.maps.LatLng(val.params.data.message[i].ape_position[0].latitude,val.params.data.message[i].ape_position[0].longitude));
+
+                                                                               opt_marker[id].push 
+                                                                               ({
+                                                                                       position: pos_marker[id][pos_marker[id].length - 1],
+                                                                                       visible: true,
+                                                                                       map : map
+                                                                                       //title : val.params.data.message.ape_timestamp
+                                                                               });
+                                                                       
+                                                                       //marker[id].push( new google.maps.Marker(opt_marker[id][opt_marker[id].length - 1 ])); 
+                                                                       if ( val.params.data.print_options )
+                                                                       {
+                                                                               opt_conf[id] = val.params.data.print_options;
+                                                                       }
+                                                                       
+                                                               break;
+                                                               
+                                                               case 'line' :
+                                                                       for ( var j = 0 ; j < val.params.data.message[i].ape_position.length ; j++ ) 
+                                                                       {
+                                                                               pos_line[id].push(new google.maps.LatLng(val.params.data.message[i].ape_position[j].latitude,val.params.data.message[i].ape_position[j].longitude)) ;
+                                                                       }       
+                                                                       
+                                                                       opt_line[id].push
+                                                                       ({
+                                                                               path : pos_line[id] ,
+                                                                               map : map,
+                                                                               strokeColor: "#FF0000",
+                                                                               strokeOpacity: 1.0,
+                                                                               strokeWeight: 2
+                                                                       })
+
+                                                                       if ( val.params.data.print_options )
+                                                                       {
+                                                                               opt_conf[id] = val.params.data.print_options;
+                                                                       }
+                                                                       
+                                                               break;
+                                                               
+                                                               case 'circle':
+                                                                       
+                                                                       longueur = pos_circle[id].length;
+                                                                       pos_circle[id][longueur]= [];
+                                                                       pos_circle[id][longueur].push( new google.maps.LatLng(val.params.data.message[i].ape_position[0].latitude,val.params.data.message[i].ape_position[0].longitude));
+                                                                       var l_radius=get_Radius(val.params.data.message[i], val.params.data.print_options);
+                                                                       opt_circle[id].push({
+                                                                               map : map,
+                                                                               center : pos_circle[id][longueur][0],
+                                                                               radius : l_radius
+                                                                       })
+                                                                       if ( val.params.data.print_options )
+                                                                       {
+                                                                               opt_conf[id] = val.params.data.print_options;
+                                                                       }
+                                                                       
+                                                               break;
+                                                               
+                                                               default :
+                                                                       alert("pas bon");
+                                                               break;
+                                                       }
+                                                               
+                                               }
+                                               
+                                       });
+                                       afficher_par_id(id,method);
+                                       set_options(id);
+                               });
+                               
+}
+
+function set_options(id) {
+       if (opt_conf[id]){
+               
+               switch ( ref[id] ) 
+                               {
+                                       case 'marker' :
+                                               for ( var i = 0; i < marker[id].length ; i++ ) 
+                                                       {
+                                                               {
+                                                                               if ( opt_conf[id].icon ) // color need to be in english 
+                                                                               {
+                                                                                       marker[id][i].setIcon("http://labs.google.com/ridefinder/images/mm_20_"+opt_conf[id].icon+".png");
+                                                                               }
+                                                               }
+                                                       }
+                                               break;
+                                               
+                                       case'circle':
+                                       
+                                       break;
+                                       
+                                       case'line':
+                                       
+                                       
+                                       break;
+                                               
+                                               
+                                       default :
+                                                       { alert ( "set_options : mauvais id" );}
+                                       break;
+                                       }
+       }
+}
+
+function get_Radius(message,print_options){
+       var tiny        =       1000;
+       var small       =       5000;
+       var avg         =       10000;
+       var big         =       100000;
+       var giant       =       500000;
+       console.log(print_options.circle_radius_arg+"--"+message.date_created);
+       console.log(eval('message.'+print_options.circle_radius_arg));
+       data = eval('message.'+print_options.circle_radius_arg);
+       if (data < print_options.size.tiny){return tiny;}
+       else if(data < print_options.size.small){return small;}
+       else if(data < print_options.size.avg){return avg;}
+       else if(data < print_options.size.big){return big;}
+       else {return giant;}
+}
diff --git a/plugins/pres_view/static/js/recup_direct.js b/plugins/pres_view/static/js/recup_direct.js
new file mode 100644 (file)
index 0000000..d3b38ed
--- /dev/null
@@ -0,0 +1,113 @@
+/* 
+
+               meme chose que recup_data sauf qu'il n'y a pas besoin d'url puisque cela r�agi a l'envoi du d�mon 
+               
+*/
+
+
+function recup_direct(data, method,id) 
+                               {
+                                       //j.each(data   , function(key, val) 
+                                       //{                     
+                                               //alert ( data.data.print_method );
+                                               switch ( data.data.print_method )
+                                                       {
+                                                               case 'marker' :
+                                                                               pos_marker[id]= [];
+                                                                               opt_marker[id] =[];
+                                                                               marker[id]= [];
+                                                                               ref[id] = 'marker';
+                                                               break;
+                                                               case 'line' :
+                                                                               opt_line[id] =[];
+                                                                               pos_line[id]= [];
+                                                                               line[id]= [];
+                                                                               ref[id] = 'line';
+                                                               break;
+                                                               case 'circle' :
+                                                                               opt_circle[id] =[];
+                                                                               pos_circle[id]= [];
+                                                                               circle[id]= [];
+                                                                               ref[id] = 'circle';
+                                                               break;
+                                                               default:
+                                                                       alert ("unknown method");
+                                                               break;
+                                                       }       
+                                               for ( var i= 0; i<data.data.message.length;i++)
+                                               {
+                                                       var longueur;
+                                                       switch ( data.data.print_method )
+                                                       {
+                                                               case 'marker' :
+                                                                       pos_marker[id].push( new google.maps.LatLng(data.data.message[i].ape_position[0].latitude,data.data.message[i].ape_position[0].longitude));
+
+                                                                               opt_marker[id].push 
+                                                                               ({
+                                                                                       position: pos_marker[id][pos_marker[id].length - 1],
+                                                                                       visible: true,
+                                                                                       map : map
+                                                                                       //title : data.data.message.ape_timestamp
+                                                                               });
+                                                                       
+                                                                       //marker[id].push( new google.maps.Marker(opt_marker[id][opt_marker[id].length - 1 ])); 
+                                                                       if ( data.data.print_options )
+                                                                       {
+                                                                               opt_conf[id] = data.data.print_options;
+                                                                       }
+                                                                       
+                                                               break;
+                                                               
+                                                               case 'line' :
+                                                                       for ( var j = 0 ; j < val[i].params.data.message.ape_position.length ; j++ ) 
+                                                                       {
+                                                                               pos_line[id].push(new google.maps.LatLng(data.data.message[i].ape_position[j].latitude,data.data.message[i].ape_position[j].longitude)) ;
+                                                                       }       
+                                                                       
+                                                                       opt_line[id].push
+                                                                       ({
+                                                                               path : pos_line[id] ,
+                                                                               map : map,
+                                                                               strokeColor: "#FF0000",
+                                                                               strokeOpacity: 1.0,
+                                                                               strokeWeight: 2
+                                                                       })
+
+                                                                       if ( data.data.print_options )
+                                                                       {
+                                                                               opt_conf[id] = data.data.print_options;
+                                                                       }
+                                                                       
+                                                               break;
+                                                               
+                                                               case 'circle':
+                                                               
+                                                                       longueur = circle.length;
+                                                                       circle[longueur] = [];
+                                                                       // circle[longueur].push (val[i].message.ape_position[0].latitude) ; pour le timestamp
+                                                                       pos_circle[longueur].push(new google.maps.LatLng(val[i].data.message.ape_position[0].latitude,val[i].data.message.ape_position[1].longitude));
+                                                                       // pos_circle[longueur].push circle[longueur][1][1] = val[i].message.ape_position[0].radian;
+                                                                       opt_circle.push({
+                                                                               map : map,
+                                                                               center : pos_circle[longueur][0],
+                                                                               radius : pos_circle[longueur][1]
+                                                                       })
+                                                                       if ( data.data.print_options )
+                                                                       {
+                                                                               opt_conf[id] = data.data.print_options;
+                                                                       }
+                                                                       
+                                                               break;
+                                                               
+                                                               default :
+                                                                       alert("pas bon");
+                                                               break;
+                                                       }
+                                                               
+                                               }
+                                               
+                                       //});
+                                       afficher_par_id(id,"static");
+                                       set_options(id);
+                               }
+
diff --git a/plugins/pres_view/static/js/recup_liste.js b/plugins/pres_view/static/js/recup_liste.js
new file mode 100644 (file)
index 0000000..10a06cc
--- /dev/null
@@ -0,0 +1,162 @@
+/* 
+
+       affiche la liste des possibililt�es d'affichage lors de la connexion au serveur
+
+
+*/
+
+
+function recup_liste ( method )
+{
+                               var method2 = "opt_"+method;
+                               var element, t,label,type_text,input ;
+                                        j.getJSON("methods/" + method, function(data) 
+                                       {
+                                               j.each(data     , function(key, val) 
+                                               {
+                                               
+                                                       switch ( method ) 
+                                                       {
+                                                       
+                                                               case 'dynamic':
+                                                                       
+                                                                       for( var i=0 ; i < val.length ; i++ )
+                                                                       {       
+                                                                               label                   = document.createElement("label");
+                                                                               input           = document.createElement("input");
+                                                                               input.id = ( val[i].id.toString() ) ;
+                                                                               input.setAttribute ( "type","checkbox");
+                                                                               label.appendChild(input);
+                                                                               input.setAttribute ( "onclick","client.ape_join('"+val[i].id.toString()+"')");
+
+                                                                               t                       = document.createTextNode(val[i].name+" ");
+                                                                               label.appendChild(t);
+                                                                               document.getElementById(method2).appendChild(label);
+                                                                               document.getElementById(method2).appendChild(document.createElement("br"));
+                                                                       }
+                                                                       
+                                                                       
+                                                               break;
+                                                               
+                                                               default:
+                                                                       for( var i=0 ; i < val.length ; i++ )
+                                                                       {       
+                                                                               label                   = document.createElement("label");
+                                                                               label.title     = val[i].descriptif;
+                                                                               label.setAttribute      ("class", "masterTooltip");
+                                                                               input           = document.createElement("input");
+                                                                               input.id = ( val[i].id.toString() ) ;
+                                                                               input.setAttribute ( "type","checkbox");
+                                                                               label.appendChild(input);
+
+                                                                               t                       = document.createTextNode(val[i].name+" ");
+                                                                               label.appendChild(t);
+                                                                               document.getElementById(method2).appendChild(label);
+                                                                               
+
+                                                                               // gestion des contraintes 
+                                                                               
+                                                                               if ( val[i].contraints.length != null ) {
+                                                                               
+                                                                                       //var texte="recup_data(\"methods/"+method.toString()+"/constraints=";
+                                                                                       var texte="recup_data(\""+method.toString()+"/";
+                                                                                       for (var  j=0 ; j< val[i].contraints.length ;j++ ) // asscoci� � un nom 
+                                                                                       {
+                                                                                               for ( var k=0 ; k < val[i].contraints[j].ens.length ; k++ ) //associ� a un ensemble de contraite
+                                                                                               {
+                                                                                                       var contrainte = "";
+                                                                                                       element                 = document.createElement("input");
+                                                                                                       element.setAttribute("style","width:75px");
+                                                                                                       if ( k != 0 ) contrainte += ",";
+                                                                                                       switch ( val[i].contraints[j].ens[k].type )
+                                                                                                       {
+                                                       
+                                                                                                               case 'date':
+                                                                                                                               element.setAttribute ( "type","text");
+                                                                                                                               element.className = "datepicker";
+                                                                                                                               element.id = "contrainte"+val[i].id.toString()+i.toString()+k.toString();
+                                                                                                                               document.getElementById(method2).appendChild(element);
+                                                                                                                               jQuery(function() {
+                                                                                                                                       jQuery(".datepicker").datepicker({
+                                                                                                                                               showOtherMonths: true,
+                                                                                                                                               selectOtherMonths: true,
+                                                                                                                                               showAnim: 'slideDown',
+                                                                                                                                               //regional: 'fr',
+                                                                                                                                               dateFormat: 'dd/mm/yy'
+                                                                                                                                       });
+                                                                                                                                       jQuery(".datepicker").datepicker("setDate", -14);
+                                                                                                                               });
+                                                                                                                               jQuery("contrainte"+val[i].id.toString()+i.toString()+k.toString()).datepicker("setDate", -14);
+
+                                                                                                                               contrainte += "'"+val[i].contraints[j].ens[k].op.toString()+val[i].contraints[j].ens[k].variable.toString()+"':\"+j(\"#contrainte"+val[i].id.toString()+i.toString()+k.toString()+"\").datepicker(\"getDate\").getTime()/1000+\"";
+                                                                                                               break;
+                                                                                                               
+                                                                                                               case 'texte':
+                                                                                                                               element                 = document.createElement("input");
+                                                                                                                               element.setAttribute("type","text");
+                                                                                                                               element.setAttribute("id","contrainte"+val[i].id.toString()+i.toString()+k.toString());
+                                                                                                                               contrainte += "'"+val[i].contraints[j].ens[k].op.toString()+val[i].contraints[j].ens[k].varariable.toString()+"':\"+this.value+\"       ";
+                                                                                                               break;
+                                                                                                               
+                                                                                                               default:
+                                                                                                                       alert ( 'mauvais type dans le fichier conf') ;
+                                                                                                               break;
+                                                                                                       }
+                                                                                                       tooltip();
+
+                                                                                               }
+                                                                                               //texte += contrainte +"&id="+val[i].id.toString()+"\",\""+val[i].id.toString()+"\",\""+method.toString()+"\");" ;
+                                                                                               texte += contrainte +"/"+val[i].id.toString()+"\",\""+val[i].id.toString()+"\",\""+method.toString()+"\");" ;
+                                                                                               document.getElementById(method2).appendChild(document.createElement("br"));
+                                                                                       }
+                                                                                                       
+                                                                                               
+                                                                                       /* type_text            = document.createElement("input");
+                                                                                       type_text.setAttribute("id",val[i].id.toString()+"2" );
+                                                                                       type_text.setAttribute("type","text");                                          
+                                                                                       type_text.value         = val[i].contraints;
+                                                                                       document.getElementById(method2).insertBefore(type_text,document.getElementById(method2).childNodes[0]);
+                                                                                       var texte = "recup_data(\"lib/cgi/static.py?constraints=']date_created':\"+j(\".datepicker\").datepicker(\"getDate\").getTime()/1000+\"&id="+val[i].id.toString()+"\","+val[i].id.toString()+","+method.toString()+")";
+                                                                                       element.setAttribute("onclick","if ( this.checked ){if ( "+texte+"}else{set_visibility(false,"+val[i].id.toString()+")}");
+                                                                                       */
+                                                                                       
+                                                                               } else { 
+                                                                                       
+                                                                                       var texte = "recup_data(\""+method.toString()+"/']date_created':\"+j(\".datepicker\").datepicker(\"getDate\").getTime()/1000+\"/"+val[i].id.toString()+"\",\""+val[i].id.toString()+"\",\""+method.toString()+"\");";
+                                                                                       //var texte = "recup_data(\"methods/"+method.toString()+"?constraints=']date_created':\"+j(\".datepicker\").datepicker(\"getDate\").getTime()/1000+\"&id="+val[i].id.toString()+"\",\""+val[i].id.toString()+"\",\""+method.toString()+"\");";
+                                                                                       document.getElementById(method2).appendChild(document.createElement("br"));     
+                                                                               }
+                                                                               input.setAttribute("onclick","if ( this.checked ){"+texte+"}else{set_visibility(false,"+val[i].id.toString()+",\""+method.toString()+"\")}");
+
+
+                                                                       }
+                                                               break;
+                                                               
+                                                       }
+                                                       
+                                               });
+                                       });
+}
+
+
+function tooltip ()
+{
+                                       jQuery('.masterTooltip').hover(function(){
+                                                       // Hover over code
+                                                       var title = j(this).attr('title');
+                                                       j(this).data('tipText', title).removeAttr('title');
+                                                       j('<p class="tooltip"></p>')
+                                                       .text(title)
+                                                       .appendTo('body')
+                                                       .fadeIn('slow');
+                                       }, function() {
+                                                       // Hover out code
+                                                       j(this).attr('title', j(this).data('tipText'));
+                                                       j('.tooltip').remove();
+                                       }).mousemove(function(e) {
+                                                       var mousex = e.pageX + 20; //Get X coordinates
+                                                       var mousey = e.pageY + 10; //Get Y coordinates
+                                                       j('.tooltip')
+                                                       .css({ top: mousey, left: mousex })
+                                       });
+}
diff --git a/plugins/pres_view/static/js/recup_tout_sites.js b/plugins/pres_view/static/js/recup_tout_sites.js
new file mode 100644 (file)
index 0000000..30260cd
--- /dev/null
@@ -0,0 +1,64 @@
+function recup_sites (url)
+{
+               var test = false;
+       if ( visible ) 
+       {
+               test = true;
+               set_visibility (false);
+       }
+               bulle = [];
+               opt_bulle = [] ;
+               pos = [];
+               x = [];
+               y = [];
+               name = [];
+
+               j.getJSON(url, function(data) 
+               {
+                       j.each(data     , function(key, val) {
+       
+               for ( var i= 0; i<val.length;i++)
+                       {
+                               x.push(val[i].latitude);
+                               y.push(val[i].longitude);
+                               name.push(val[i].site_id);
+                       }                                       
+               });
+               for ( var i=0 ; i<x.length ; i++ )
+               {
+                       pos.push( new google.maps.LatLng(x[i], y[i]));
+                       opt_bulle.push ({
+                               position: pos[i],
+                               visible: visible,
+                               map : map,
+                               title : name[i]
+                       });
+                       bulle.push( new google.maps.Marker(opt_bulle[i]));
+                       google.maps.event.addListener(bulle[i], 'click', function() {
+                               var url = '/cgi-bin/max-perso/prod/get_site_property.py?site_id='+this.getTitle();
+                               j.getJSON(url, function (data)
+                               {
+                                       j.each( data, function ( key, val )
+                                       {
+                                               for ( var j=0; j<val.length ;j++ )
+                                               {
+                                                       j("#site_name").empty();
+                                                       j("#site_name").append( val[j].name);
+                                               }
+                                       });
+                               });
+                       });
+
+               }
+
+
+               //var info = new google.maps.InfoWindow({content:"test"});
+               //info.open( map, bulle[0]); 
+               });    
+               if ( test ) 
+               {
+               set_visibility(true);      
+               }
+}
+
+
diff --git a/plugins/pres_view/static/js/visible.js b/plugins/pres_view/static/js/visible.js
new file mode 100644 (file)
index 0000000..94086fa
--- /dev/null
@@ -0,0 +1,83 @@
+/*
+
+               modifie la visibilité des markers si une case est décoché 
+               
+*/
+
+
+
+function set_visibility ( v, id, method ) 
+{
+       switch ( method )
+       {
+               case 'static':
+                       if ( typeof(marker[id])!='undefined' )
+                       {
+                               for ( var i=0 ; i< marker[id].length; i++ )
+                               {
+                                       marker[id][i].setVisible(v);
+                               }
+                       }else if ( typeof(line[id])!='undefined' ){
+                               {
+                                       for ( var i=0 ; i< line[id].length; i++ )
+                                       {
+                                               line[id][i].setVisible(v);
+                                       }
+                               }
+                       }
+                       else if ( typeof(circle[id])!='undefined' ) {
+                               {
+                                       for ( var i=0 ; i < circle[id].length; i++ )
+                                       {
+                                               circle[id][i].setVisible(v);
+                                       }
+                               }
+                       }
+               break;
+               
+               case 'animation':
+                       if ( opt_marker[id].length != null )
+                       {
+                               for ( var i=0 ; i< marker[id].length; i++ )
+                               {
+                                       
+                                       marker[id][i].setVisible(v);
+                               }
+                       }else if ( line[id].length != null ){
+                               {
+                                       for ( var i=0 ; i< line[id].length; i++ )
+                                       {
+                                               line[id][i].setVisible(v);
+                                       }
+                               }
+                       }
+                       else if ( circle[id].length != null ) {
+                               {
+                                       for ( var i=0 ; i < circle[id].length; i++ )
+                                       {
+                                               circle[id][i].setVisible(v);
+                                       }
+                               }
+                       }
+                       for ( var i=0 ; i< animation[id].length; i++ )
+                       {
+                               
+                               clearTimeout ( animation[id][i] );
+                       }
+                       animation [id] = []; 
+               break;
+               
+               default:
+               
+               break;
+       }
+       
+}
+
+function sup_sites (tab)
+{
+       for( var i=0; i < tab.length; i++)
+       {
+               tab[i].setVisible(false);
+       }
+}
\ No newline at end of file
diff --git a/plugins/pres_view/static/pres_view.html b/plugins/pres_view/static/pres_view.html
new file mode 100644 (file)
index 0000000..21b5c67
--- /dev/null
@@ -0,0 +1,40 @@
+<div id="wrapper">
+       <div id="gmaps">
+               <script type="text/javascript">
+                       initialiser();
+               </script>
+       </div>
+       <div id="sbar">
+                       <h3>Viewing options</h3>
+               <div id="accordion">
+                               <h3 class="ui-accordion-header ui-corner-top"  onclick="if(direct){ client.ape_quit();direct=0}">Static</h3>
+                               <div class="sbar_cont ui-accordion-content ui-widget-content ui-corner-bottom" id="opt_static" >
+                                       <script type="text/javascript">
+                                               recup_liste("static");
+                                       </script>
+                               </div>
+
+                               <h3 class="ui-accordion-header ui-corner-top" onclick="if ( direct== 0 ){ape_load();direct=1}">Dynamic</h3>
+                               <div class="sbar_cont ui-accordion-content ui-widget-content ui-corner-bottom" id="opt_dynamic">
+                                       <script type="text/javascript">
+                                               recup_liste("dynamic");
+                                       </script>
+                               </div>
+
+                               <h3 class="ui-accordion-header ui-corner-top"  onclick="if(direct){ client.ape_quit();direct=0}">Animation</h3>
+                               <div class="sbar_cont ui-accordion-content ui-widget-content ui-corner-bottom">
+                                       <div id="interval_animation" class="masterTooltip" title="Choisir la vitesse de l'animation"></div>
+                                       <div id="opt_animation">
+                                               <script type="text/javascript">
+                                                       recup_liste("animation");
+                                               </script>
+                                       </div>
+                               </div>
+               </div>
+       </div>
+       <div class="clear"></div>
+       <div id="statusbar">
+               <div id="sb1"></div>
+               <div id="sb2"></div>
+       </div>
+</div>
diff --git a/plugins/query_editor/__init__.py b/plugins/query_editor/__init__.py
new file mode 100644 (file)
index 0000000..1a42989
--- /dev/null
@@ -0,0 +1,86 @@
+from unfold.plugin import Plugin
+
+from django.template.loader import render_to_string
+
+# XXX We need naming helpers in the python Plugin class also, used in template
+
+class QueryEditor(Plugin):
+
+    def template_file(self):
+        return "query_editor.html"
+
+    def requirements (self):
+        reqs = {
+            'js_files' : [
+                # XXX datatables
+                'js/query_editor.js',
+            ] ,
+            'css_files': [
+                'css/query_editor.css',
+                'css/jquery-ui.css',
+                'css/demo_page.css',
+                'css/demo_table.css',
+            ]
+        }
+        return reqs
+
+    def json_settings_list (self):
+        return ['plugin_uuid', 'domid', 'query_uuid']
+
+    def export_json_settings (self):
+        return True
+
+    def template_env(self, request):
+        fields = []
+        metadata = self.page.get_metadata()
+        md_fields = metadata.details_by_object('resource')
+
+        # XXX use django templating system here
+        for md_field in md_fields['column']:
+
+            if md_field['type'] == 'string':
+                if 'allowed_values' in md_field:
+                    allowed_values = md_field['allowed_values'].split(',')
+
+                    options = []
+                    for v in allowed_values:
+                        v_desc = v.split('-')
+                        options.append(v_desc[0])
+
+                    env = {
+                        'domid': self.domid,
+                        'options': options
+                    }
+                    filter_input = render_to_string('filter_input_string_values.html', env)
+                else:
+                    env = {
+                        'domid': self.domid,
+                        'field': md_field['name']
+                    }
+                    filter_input = render_to_string('filter_input_string.html', env)
+                    
+            elif md_field['type'] == 'int':
+                allowed_values = md_field.get('allowed_values', '0,0').split(',')
+                env = {
+                    'domid': self.domid,
+                    'field': md_field['name'],
+                    'min'  : allowed_values[0],
+                    'max'  : allowed_values[1]
+                }
+                filter_input = render_to_string('filter_input_integer.html', env)
+            else:
+                env = {
+                    'domid': self.domid,
+                    'field': md_field['name']
+                }
+                filter_input = render_to_string('filter_input_others.html', env)
+
+            fields.append({
+                'name':          md_field['name'],
+                'type':          md_field['type'],
+                'resource_type': 'N/A',
+                'filter_input':  filter_input,
+                'header':        None,
+                'checked':       md_field['name'] in self.query.get_select()
+            })
+        return { 'fields': fields }
diff --git a/plugins/query_editor/static/css/demo_page.css b/plugins/query_editor/static/css/demo_page.css
new file mode 100644 (file)
index 0000000..bee7b0d
--- /dev/null
@@ -0,0 +1,93 @@
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+ * General page setup
+ */
+#dt_example {
+       font: 80%/1.45em "Lucida Grande", Verdana, Arial, Helvetica, sans-serif;
+       margin: 0;
+       padding: 0;
+       color: #333;
+       background-color: #fff;
+}
+
+
+#dt_example #container {
+       width: 800px;
+       margin: 30px auto;
+       padding: 0;
+}
+
+
+#dt_example #footer {
+       margin: 50px auto 0 auto;
+       padding: 0;
+}
+
+#dt_example #demo {
+       margin: 30px auto 0 auto;
+}
+
+#dt_example .demo_jui {
+       margin: 30px auto 0 auto;
+}
+
+#dt_example .big {
+       font-size: 1.3em;
+       font-weight: bold;
+       line-height: 1.6em;
+       color: #4E6CA3;
+}
+
+#dt_example .spacer {
+       height: 20px;
+       clear: both;
+}
+
+#dt_example .clear {
+       clear: both;
+}
+
+#dt_example pre {
+       padding: 15px;
+       background-color: #F5F5F5;
+       border: 1px solid #CCCCCC;
+}
+
+#dt_example h1 {
+       margin-top: 2em;
+       font-size: 1.3em;
+       font-weight: normal;
+       line-height: 1.6em;
+       color: #4E6CA3;
+       border-bottom: 1px solid #B0BED9;
+       clear: both;
+}
+
+#dt_example h2 {
+       font-size: 1.2em;
+       font-weight: normal;
+       line-height: 1.6em;
+       color: #4E6CA3;
+       clear: both;
+}
+
+#dt_example a {
+       color: #0063DC;
+       text-decoration: none;
+}
+
+#dt_example a:hover {
+       text-decoration: underline;
+}
+
+#dt_example ul {
+       color: #4E6CA3;
+}
+
+.css_right {
+       float: right;
+}
+
+.css_left {
+       float: left;
+}
\ No newline at end of file
diff --git a/plugins/query_editor/static/css/demo_table.css b/plugins/query_editor/static/css/demo_table.css
new file mode 100644 (file)
index 0000000..6b6fb34
--- /dev/null
@@ -0,0 +1,546 @@
+/*
+ *  File:         demo_table.css
+ *  CVS:          $Id$
+ *  Description:  CSS descriptions for DataTables demo pages
+ *  Author:       Allan Jardine
+ *  Created:      Tue May 12 06:47:22 BST 2009
+ *  Modified:     $Date$ by $Author$
+ *  Language:     CSS
+ *  Project:      DataTables
+ *
+ *  Copyright 2009 Allan Jardine. All Rights Reserved.
+ *
+ * ***************************************************************************
+ * DESCRIPTION
+ *
+ * The styles given here are suitable for the demos that are used with the standard DataTables
+ * distribution (see www.datatables.net). You will most likely wish to modify these styles to
+ * meet the layout requirements of your site.
+ *
+ * Common issues:
+ *   'full_numbers' pagination - I use an extra selector on the body tag to ensure that there is
+ *     no conflict between the two pagination types. If you want to use full_numbers pagination
+ *     ensure that you either have "example_alt_pagination" as a body class name, or better yet,
+ *     modify that selector.
+ *   Note that the path used for Images is relative. All images are by default located in
+ *     ../images/ - relative to this CSS file.
+ */
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+ * DataTables features
+ */
+
+/*
+.dataTables_wrapper {
+    padding-bottom: 0em;
+    padding-top: 0em;
+       position: relative;
+       min-height: 302px;
+       clear: both;
+       _height: 302px;
+       zoom: 1; / Feeling sorry for IE /
+}
+*/
+.dataTables_processing {
+       position: absolute;
+       top: 50%;
+       left: 50%;
+       width: 250px;
+       height: 30px;
+       margin-left: -125px;
+       margin-top: -15px;
+       padding: 14px 0 2px 0;
+       border: 1px solid #ddd;
+       text-align: center;
+       color: #999;
+       font-size: 14px;
+       background-color: white;
+}
+
+.dataTables_length {
+       width: 40%;
+       float: left;
+}
+
+.dataTables_filter {
+       width: 50%;
+       float: right;
+       text-align: right;
+}
+
+.dataTables_info {
+/*     width: 45%;
+       float: left;
+    padding-top: 1.2em;
+    padding-left: 1em;
+}
+
+.dataTables_paginate {
+       /* width: 44px;
+        width: 50px;
+       float: right;
+       text-align: right;
+}
+*/
+
+/* Pagination nested */
+.paginate_disabled_previous, .paginate_enabled_previous, .paginate_disabled_next, .paginate_enabled_next {
+       height: 19px;
+       width: 19px;
+       margin-left: 3px;
+       /*float: left;*/
+}
+
+.paginate_disabled_previous {
+       background-image: url('images/back_disabled.jpg');
+}
+
+.paginate_enabled_previous {
+       background-image: url('images/back_enabled.jpg');
+}
+
+.paginate_disabled_next {
+       background-image: url('images/forward_disabled.jpg');
+}
+
+.paginate_enabled_next {
+       background-image: url('images/forward_enabled.jpg');
+}
+
+
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+ * DataTables display
+ */
+table.display {
+       margin: 0 auto;
+       clear: both;
+       width: 100%;
+       
+       /* Note Firefox 3.5 and before have a bug with border-collapse
+        * ( https://bugzilla.mozilla.org/show%5Fbug.cgi?id=155955 ) 
+        * border-spacing: 0; is one possible option. Conditional-css.com is
+        * useful for this kind of thing
+        *
+        * Further note IE 6/7 has problems when calculating widths with border width.
+        * It subtracts one px relative to the other browsers from the first column, and
+        * adds one to the end...
+        *
+        * If you want that effect I'd suggest setting a border-top/left on th/td's and 
+        * then filling in the gaps with other borders.
+        */
+}
+
+table.display thead th {
+       padding: 3px 18px 3px 10px;
+       border-bottom: 1px solid black;
+       font-weight: bold;
+       cursor: pointer;
+       * cursor: hand;
+}
+
+table.display tfoot th {
+       padding: 3px 18px 3px 10px;
+       border-top: 1px solid black;
+       font-weight: bold;
+}
+
+table.display tr.heading2 td {
+       border-bottom: 1px solid #aaa;
+}
+
+table.display td {
+       padding: 3px 10px;
+}
+
+table.display td.center {
+       text-align: center;
+}
+
+
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+ * DataTables sorting
+ */
+
+.sorting_asc {
+       background: url('images/sort_asc.png') no-repeat center right;
+}
+
+.sorting_desc {
+       background: url('images/sort_desc.png') no-repeat center right;
+}
+
+.sorting {
+       background: url('images/sort_both.png') no-repeat center right;
+}
+
+.sorting_asc_disabled {
+       background: url('images/sort_asc_disabled.png') no-repeat center right;
+}
+
+.sorting_desc_disabled {
+       background: url('images/sort_desc_disabled.png') no-repeat center right;
+}
+
+
+
+
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+ * DataTables row classes
+ */
+table.display tr.odd.gradeA {
+       background-color: #ddffdd;
+}
+
+table.display tr.even.gradeA {
+       background-color: #eeffee;
+}
+
+table.display tr.odd.gradeC {
+       background-color: #ddddff;
+}
+
+table.display tr.even.gradeC {
+       background-color: #eeeeff;
+}
+
+table.display tr.odd.gradeX {
+       background-color: #ffdddd;
+}
+
+table.display tr.even.gradeX {
+       background-color: #ffeeee;
+}
+
+table.display tr.odd.gradeU {
+       background-color: #ddd;
+}
+
+table.display tr.even.gradeU {
+       background-color: #eee;
+}
+
+
+tr.odd {
+       background-color: #E2E4FF;
+}
+
+tr.even {
+       background-color: white;
+}
+
+
+
+
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+ * Misc
+ */
+.dataTables_scroll {
+/*     clear: both; JORDAN */
+}
+
+.dataTables_scrollBody {
+       *margin-top: -1px;
+}
+/*
+.top, .bottom {
+       padding: 15px;
+       background-color: #F5F5F5;
+       border: 1px solid #CCCCCC;
+}
+
+.top .dataTables_info {
+       float: none;
+}
+*/
+.clear {
+       clear: both;
+}
+
+.dataTables_empty {
+       text-align: center;
+}
+
+tfoot input {
+       margin: 0.5em 0;
+       width: 100%;
+       color: #444;
+}
+
+tfoot input.search_init {
+       color: #999;
+}
+
+td.group {
+       background-color: #d1cfd0;
+       border-bottom: 2px solid #A19B9E;
+       border-top: 2px solid #A19B9E;
+}
+
+td.details {
+       background-color: #d1cfd0;
+       border: 2px solid #A19B9E;
+}
+
+
+.example_alt_pagination div.dataTables_info {
+       width: 40%;
+}
+
+.paging_full_numbers {
+       width: 45%;
+       height: 22px;
+       line-height: 22px;
+    padding-top: 1em;    
+    padding-right: 1em;    
+}
+
+.paging_full_numbers a.paginate_button,
+       .paging_full_numbers a.paginate_active {
+       border: 1px solid #aaa;
+       -webkit-border-radius: 5px;
+       -moz-border-radius: 5px;
+       padding: 2px 5px;
+       margin: 0 3px;
+       cursor: pointer;
+       *cursor: hand;
+}
+
+.paging_full_numbers a.paginate_button {
+       background-color: #ddd;
+}
+
+.paging_full_numbers a.paginate_button:hover {
+       background-color: #ccc;
+}
+
+.paging_full_numbers a.paginate_active {
+       background-color: #99B3FF;
+}
+
+table.display tr.even.row_selected td {
+       background-color: #B0BED9;
+}
+
+table.display tr.odd.row_selected td {
+       background-color: #9FAFD1;
+}
+
+
+/*
+ * Sorting classes for columns
+ */
+/* For the standard odd/even */
+tr.odd td.sorting_1 {
+       background-color: #D3D6FF;
+}
+
+tr.odd td.sorting_2 {
+       background-color: #DADCFF;
+}
+
+tr.odd td.sorting_3 {
+       background-color: #E0E2FF;
+}
+
+tr.even td.sorting_1 {
+       background-color: #EAEBFF;
+}
+
+tr.even td.sorting_2 {
+       background-color: #F2F3FF;
+}
+
+tr.even td.sorting_3 {
+       background-color: #F9F9FF;
+}
+
+
+/* For the Conditional-CSS grading rows */
+/*
+       Colour calculations (based off the main row colours)
+  Level 1:
+               dd > c4
+               ee > d5
+       Level 2:
+         dd > d1
+         ee > e2
+ */
+tr.odd.gradeA td.sorting_1 {
+       background-color: #c4ffc4;
+}
+
+tr.odd.gradeA td.sorting_2 {
+       background-color: #d1ffd1;
+}
+
+tr.odd.gradeA td.sorting_3 {
+       background-color: #d1ffd1;
+}
+
+tr.even.gradeA td.sorting_1 {
+       background-color: #d5ffd5;
+}
+
+tr.even.gradeA td.sorting_2 {
+       background-color: #e2ffe2;
+}
+
+tr.even.gradeA td.sorting_3 {
+       background-color: #e2ffe2;
+}
+
+tr.odd.gradeC td.sorting_1 {
+       background-color: #c4c4ff;
+}
+
+tr.odd.gradeC td.sorting_2 {
+       background-color: #d1d1ff;
+}
+
+tr.odd.gradeC td.sorting_3 {
+       background-color: #d1d1ff;
+}
+
+tr.even.gradeC td.sorting_1 {
+       background-color: #d5d5ff;
+}
+
+tr.even.gradeC td.sorting_2 {
+       background-color: #e2e2ff;
+}
+
+tr.even.gradeC td.sorting_3 {
+       background-color: #e2e2ff;
+}
+
+tr.odd.gradeX td.sorting_1 {
+       background-color: #ffc4c4;
+}
+
+tr.odd.gradeX td.sorting_2 {
+       background-color: #ffd1d1;
+}
+
+tr.odd.gradeX td.sorting_3 {
+       background-color: #ffd1d1;
+}
+
+tr.even.gradeX td.sorting_1 {
+       background-color: #ffd5d5;
+}
+
+tr.even.gradeX td.sorting_2 {
+       background-color: #ffe2e2;
+}
+
+tr.even.gradeX td.sorting_3 {
+       background-color: #ffe2e2;
+}
+
+tr.odd.gradeU td.sorting_1 {
+       background-color: #c4c4c4;
+}
+
+tr.odd.gradeU td.sorting_2 {
+       background-color: #d1d1d1;
+}
+
+tr.odd.gradeU td.sorting_3 {
+       background-color: #d1d1d1;
+}
+
+tr.even.gradeU td.sorting_1 {
+       background-color: #d5d5d5;
+}
+
+tr.even.gradeU td.sorting_2 {
+       background-color: #e2e2e2;
+}
+
+tr.even.gradeU td.sorting_3 {
+       background-color: #e2e2e2;
+}
+
+
+/*
+ * Row highlighting example
+ */
+.ex_highlight #example tbody tr.even:hover, #example tbody tr.even td.highlighted {
+       background-color: #ECFFB3;
+}
+
+.ex_highlight #example tbody tr.odd:hover, #example tbody tr.odd td.highlighted {
+       background-color: #E6FF99;
+}
+
+.ex_highlight_row #example tr.even:hover {
+       background-color: #ECFFB3;
+}
+
+.ex_highlight_row #example tr.even:hover td.sorting_1 {
+       background-color: #DDFF75;
+}
+
+.ex_highlight_row #example tr.even:hover td.sorting_2 {
+       background-color: #E7FF9E;
+}
+
+.ex_highlight_row #example tr.even:hover td.sorting_3 {
+       background-color: #E2FF89;
+}
+
+.ex_highlight_row #example tr.odd:hover {
+       background-color: #E6FF99;
+}
+
+.ex_highlight_row #example tr.odd:hover td.sorting_1 {
+       background-color: #D6FF5C;
+}
+
+.ex_highlight_row #example tr.odd:hover td.sorting_2 {
+       background-color: #E0FF84;
+}
+
+.ex_highlight_row #example tr.odd:hover td.sorting_3 {
+       background-color: #DBFF70;
+}
+
+
+/*
+ * KeyTable
+ */
+table.KeyTable td {
+       border: 3px solid transparent;
+}
+
+table.KeyTable td.focus {
+       border: 3px solid #3366FF;
+}
+
+table.display tr.gradeA {
+       background-color: #eeffee;
+}
+
+table.display tr.gradeC {
+       background-color: #ddddff;
+}
+
+table.display tr.gradeX {
+       background-color: #ffdddd;
+}
+
+table.display tr.gradeU {
+       background-color: #ddd;
+}
+
+div.box {
+       height: 100px;
+       padding: 10px;
+       overflow: auto;
+       border: 1px solid #8080FF;
+       background-color: #E5E5FF;
+}
diff --git a/plugins/query_editor/static/css/query_editor.css b/plugins/query_editor/static/css/query_editor.css
new file mode 100644 (file)
index 0000000..5ef2875
--- /dev/null
@@ -0,0 +1,341 @@
+/* Add a scrollbar to autocomplete fields */
+.ui-autocomplete {
+        max-height: 100px;
+        overflow-y: auto;
+        /* prevent horizontal scrollbar */
+        overflow-x: hidden;
+        /* add padding to account for vertical scrollbar */
+        padding-right: 20px;
+        
+        /* NEED TO BE IMPROVED LATER... */
+        /* How to use properties from content class in /templates/myslice/css/myslice.css ? */
+        /* How to factorize this ? Maybe applied differently in other plugins ? */        
+        font-size: 11px;
+}
+.queryeditor-auto-filter{
+    width:200px;
+}
+/* IE 6 doesn't support max-height
+    * we use height instead, but this forces the menu to always be this tall
+    */
+* html .ui-autocomplete {
+        height: 100px;
+}
+
+table.columns {
+       margin: 0 auto;
+       clear: both;
+       /* width: 80%;*/
+       width: 300px;
+}
+
+table.columns thead th {
+       padding: 3px 18px 3px 3px; 
+       border-bottom: 1px solid black;
+       font-weight: bold;
+       cursor: pointer;
+       * cursor: hand;
+}
+
+table.columns tfoot th {
+       padding: 3px 18px 3px 10px;
+       border-top: 1px solid black;
+       font-weight: bold;
+}
+
+table.columns td {
+       padding: 3px 5px;
+}
+
+table.columns td.center {
+       text-align: center;
+}
+
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
+ * DataTables row classes
+ */
+table.columns tr.odd.gradeA {
+       background-color: #ddffdd;
+}
+
+table.columns tr.even.gradeA {
+       background-color: #eeffee;
+}
+
+table.columns tr.odd.gradeC {
+       background-color: #ddddff;
+}
+
+table.columns tr.even.gradeC {
+       background-color: #eeeeff;
+}
+
+table.columns tr.odd.gradeX {
+       background-color: #ffdddd;
+}
+
+table.columns tr.even.gradeX {
+       background-color: #ffeeee;
+}
+
+table.columns tr.odd.gradeU {
+       background-color: #ddd;
+}
+
+table.columns tr.even.gradeU {
+       background-color: #eee;
+}
+
+/* change color: T / even -> odd +1 +5 -3*/
+table.columns tr.odd.row_sliver td {
+       background-color: #9FAFD1;
+}
+
+table.columns tr.even.row_added td {
+       background-color: #b1d19f;
+}
+table.columns tr.odd.row_added td {
+       background-color: #a3c98f;
+}
+
+table.columns tr.even.row_removed td {
+       background-color: #d9b0b0;
+}
+
+table.columns tr.odd.row_removed td {
+       background-color: #d1a09f;
+}
+
+table.columns tr.gradeA {
+       background-color: #eeffee;
+}
+
+table.columns tr.gradeC {
+       background-color: #ddddff;
+}
+
+table.columns tr.gradeX {
+       background-color: #ffdddd;
+}
+
+table.columns tr.gradeU {
+       background-color: #ddd;
+}
+
+
+
+
+div.selected{background-color:gray; color:black}
+
+/* icons */
+.myslice-icon-timestamp {
+    background-image: url('images/myslice-icon-timestamp.png') !important;
+}
+.myslice-icon-filter {
+    background-image: url('images/myslice-icon-filter.png') !important;
+}
+.myslice-icon-fields {
+    background-image: url('images/myslice-icon-fields.png') !important;
+}
+.myslice-icon-groups {
+    background-image: url('images/myslice-icon-groups.png') !important;
+}
+.myslice-icon-summary {
+    background-image: url('images/myslice-icon-summary.png') !important;
+}
+.myslice-icon-resources {
+    background-image: url('images/myslice-icon-resources.png') !important;
+}
+.myslice-icon-users {
+    background-image: url('images/myslice-icon-users.png') !important;
+}
+
+a.source-url{
+    font-weight: bold;
+}
+
+span.bold {
+    font-weight: bold;
+}
+
+div#selectdescr {
+    padding-top:2em;
+    color: #555555;
+}
+
+span.short {
+height:10px;
+}
+
+span.column-title {
+    font-size: 15px;
+    font-weight: bold;
+}
+
+span.column-detail {
+    font-size: 11px; 
+    font-style: italic;
+}
+
+span.group_info {
+    font-size: 11px; 
+    color: green;
+    font-weight: bold;
+}
+
+span.filter_info {
+    color: red;
+    font-weight: bold;
+}
+
+
+/* column configuation style */
+
+OPTION.out{background-color:white; color:black}
+OPTION.in{background-color:#CAE8EA; color:#4f6b72}
+
+/* jordan disabled
+div.out{background-color:white; color:black}
+div.in{background-color:#CAE8EA; color:#4f6b72}
+div.selected{background-color:gray; color:black}
+div.invisible{display:none}
+*/
+
+div.note-div {
+       padding: 4px;
+       background-color: #cae8ea;
+       width: 800px;
+       margin-left:auto;
+       margin-right:auto;
+
+}
+
+div#scrolldiv_old {
+       border : solid 2px grey; 
+       padding:4px; 
+       width:300px; 
+       height:180px; 
+       overflow:auto;
+}
+
+th,td.top {
+       vertical-align: top;
+       text-align: left;
+       padding:10px;
+}
+
+tr.hidden {
+    display:none;
+}
+
+td.smallright {
+       text-align: right;
+       width:20px;
+}
+
+table.center {
+       margin-left:auto; 
+       margin-right:auto;
+}
+
+table.columnlist {
+       width:270px;
+}
+
+table.columns td.header {
+       background-color: #CAE8EA;
+       text-align: center;
+       width:30px;
+}
+
+span.header {
+       font-weight: bold;
+       color: #3399CC;
+}
+
+a.source-url{
+        font-weight: bold;
+}
+
+span.menubig {
+        font-size: 16px;
+        font-weight: bold;
+}
+
+span.menusmall {
+        font-size: 14px;
+        font-weight: bold;
+}
+
+span.menuright {
+        font-weight: bold;
+       float: right;
+}
+
+span.simpleright {
+       float: right;
+}
+
+span.gray{
+        color: #555555;
+}
+
+span.short {
+       height:10px;
+}
+
+span.column-title {
+        font-size: 13px;
+        font-weight: bold;
+}
+
+span.column-detail {
+        font-size: 11px; 
+        font-style: italic;
+}
+
+span.myslice_small {
+        font-size: 11px; 
+}
+
+span#username {
+    font-weight: bold;
+    font-size: 1.3em;
+}
+
+.filter_popup{
+    position:relative; /*this is the key*/
+    float: right;
+    z-index:24;
+    background: url('images/myslice-icon-filter.png') no-repeat;
+    //background-color:#ccc;
+    width: 200px;
+    height: 300px;
+    color:#000;
+    text-decoration:none;
+    clear: both;
+}
+
+.filter_popup:hover{
+    z-index:25;
+    //background-color:#ff0
+}
+
+.filter_popup span{display: none}
+
+.filter_popup:hover span{ /*the span will display just on :hover state*/
+    display:block;
+    position:absolute;
+    //top:1em;
+    left:-19em;
+    width: 20em;
+    font-size: 8pt;
+    border:1px solid #ccdddd;
+    background-color:#ddeeee;
+    color:#000;
+    text-align: left;
+    padding: 0em 0em 0em 1em;
+}
+
+
diff --git a/plugins/query_editor/static/filter_input_integer.html b/plugins/query_editor/static/filter_input_integer.html
new file mode 100644 (file)
index 0000000..bdbacb6
--- /dev/null
@@ -0,0 +1,5 @@
+<div class="ui-widget content" style="margin-top:0px;">
+<label for='{{field}}'></label>
+<input class='queryeditor-filter-min' id='{{domid}}__field__{{field}}__min' type=text size=3 value='{{ min }}'></input>&nbsp;-
+<input class='queryeditor-filter-max' id='{{domid}}__field__{{field}}__max' type=text size=3 value='{{ max }}'></input>
+</div>
diff --git a/plugins/query_editor/static/filter_input_others.html b/plugins/query_editor/static/filter_input_others.html
new file mode 100644 (file)
index 0000000..14e6033
--- /dev/null
@@ -0,0 +1,4 @@
+<div class='ui-widget content' style='margin-top:0px;'>
+    <label for='{{field}}'></label>
+    <input class='queryeditor-auto-filter' id='{{domid}}__field__{{field}}' type='text' style='width:206px;'></input>
+</div>
diff --git a/plugins/query_editor/static/filter_input_string.html b/plugins/query_editor/static/filter_input_string.html
new file mode 100644 (file)
index 0000000..110f16d
--- /dev/null
@@ -0,0 +1,4 @@
+<div class='ui-widget content' style='margin-top:0px;'>
+  <label for='{{domid}}__field__{{field}}'></label>
+  <input class='queryeditor-auto-filter' id='{{domid}}__field__{{field}}' type='text' style='width:206px;'></input>
+</div>
diff --git a/plugins/query_editor/static/filter_input_string_values.html b/plugins/query_editor/static/filter_input_string_values.html
new file mode 100644 (file)
index 0000000..6a8aeca
--- /dev/null
@@ -0,0 +1,6 @@
+<select class='queryeditor-filter' id='$filter_id'>
+    <option value=''>Show all</option>
+       {% for option in options %}
+       <option>{{option}}</option>
+       {% endfor %}
+</select>
diff --git a/plugins/query_editor/static/img/details_close.png b/plugins/query_editor/static/img/details_close.png
new file mode 100644 (file)
index 0000000..fcc23c6
Binary files /dev/null and b/plugins/query_editor/static/img/details_close.png differ
diff --git a/plugins/query_editor/static/img/myslice-icon-filter.png b/plugins/query_editor/static/img/myslice-icon-filter.png
new file mode 100644 (file)
index 0000000..b2f4ec7
Binary files /dev/null and b/plugins/query_editor/static/img/myslice-icon-filter.png differ
diff --git a/plugins/query_editor/static/js/query_editor.js b/plugins/query_editor/static/js/query_editor.js
new file mode 100644 (file)
index 0000000..e065a65
--- /dev/null
@@ -0,0 +1,290 @@
+/**
+ * Description: QueryEditor plugin
+ * Copyright (c) 2012-2013 UPMC Sorbonne Universite
+ * License: GPLv3
+ */
+
+// XXX TODO This plugin will be interested in changes in metadata
+// What if we remove a filter, is it removed in the right min/max field ???
+//  -> no on_filter_removed is not yet implemented
+// XXX if a plugin has not declared a handler, it might become inconsistent,
+// and the interface should either reset or disable it
+(function($){
+
+    var QueryEditor = Plugin.extend({
+
+        event_filter_added: function(op, suffix) {
+            suffix = (typeof suffix === 'undefined') ? '' : manifold.separator + suffix;
+            var self = this;
+            return function(e) {
+                var array = self.array_from_id(e.target.id);
+                var key   = self.field_from_id(array); // No need to remove suffix...
+                var value = e.target.value;
+
+                if (value) {
+                    // XXX This should be handled by manifold
+                    //manifold.raise_event(object.options.query_uuid, FILTER_UPDATED, [key, op, value]);
+                    manifold.raise_event(self.options.query_uuid, FILTER_ADDED, [key, op, value]);
+                } else {
+                    // XXX This should be handled by manifold
+                    manifold.raise_event(self.options.query_uuid, FILTER_REMOVED, [key, op]);
+                }
+            }
+        },
+
+        init: function(options, element) {
+            this._super(options, element);
+
+            this.listen_query(options.query_uuid);
+
+            this.els('queryeditor-auto-filter').change(this.event_filter_added('='));
+            this.els('queryeditor-filter').change(this.event_filter_added('='));
+            this.els('queryeditor-filter-min').change(this.event_filter_added('>'));
+            this.els('queryeditor-filter-max').change(this.event_filter_added('<'));
+
+            var self = this;
+            this.els('queryeditor-check').click(function() { 
+                manifold.raise_event(self.options.query_uuid, this.checked?FIELD_ADDED:FIELD_REMOVED, this.value);
+            });
+
+            /* The following code adds an expandable column for the table
+            // XXX Why isn't it done statically ?
+            var nCloneTh = document.createElement( 'th' );
+            var nCloneTd = document.createElement( 'td' );
+            nCloneTd.innerHTML = "<span class='ui-icon ui-icon-triangle-1-e' style='cursor:pointer'></span>";
+            //nCloneTd.innerHTML = '<img src="/components/com_tophat/images/details_open.png">';
+            nCloneTh.innerHTML = '<b>Info</b>';
+            nCloneTd.className = "center";
+            nCloneTh.className = "center";
+            this.el('table thead tr').each(function() {
+                this.insertBefore(nCloneTh, this.childNodes[0]);
+            });
+            this.el('table tbody tr').each(function() {
+                this.insertBefore(nCloneTd.cloneNode( true ), this.childNodes[0]);
+            });
+            */
+         
+            // We are currently using a DataTable display, but another browsing component could be better
+            //jQuery('#'+this.options.plugin_uuid+'-table').dataTable...
+            var  metaTable = this.el('table').dataTable({
+                bFilter     : false,
+                bPaginate   : false,
+                bInfo       : false,
+                sScrollX    : '100%',         // Horizontal scrolling
+                sScrollY    : '200px',
+                //bJQueryUI   : true,           // Use jQuery UI
+                bProcessing : true,           // Loading
+                aaSorting   : [[ 1, "asc" ]], // sort by column fields on load
+                aoColumnDefs: [
+                    { 'bSortable': false, 'aTargets': [ 0 ]},
+                    { 'sWidth': '8px', 'aTargets': [ 0 ] },
+                    { 'sWidth': '8px', 'aTargets': [ 4 ] } // XXX NB OF COLS
+                ]
+            });
+
+            var self = this;
+            // Actions on the newly added fields
+            this.el('table tbody td span').on('click', function() {
+                var nTr = this.parentNode.parentNode;
+                // use jQuery UI instead of images to keep a common UI
+                // class="ui-icon treeclick ui-icon-triangle-1-s tree-minus"
+                // East oriented Triangle class="ui-icon-triangle-1-e"
+                // South oriented Triangle class="ui-icon-triangle-1-s"
+                
+                if (this.className=="ui-icon ui-icon-triangle-1-e") {
+                    this.removeClass("ui-icon-triangle-1-e").addClass("ui-icon-triangle-1-s");
+                    // XXX ??????
+                    metaTable.fnOpen(nTr, this.fnFormatDetails(metaTable, nTr, self.options.plugin_uuid+'_div'), 'details' );
+                } else {
+                    this.removeClass("ui-icon-triangle-1-s").addClass("ui-icon-triangle-1-e");
+                    metaTable.fnClose(nTr);
+                }
+            });
+
+            this.el('table_wrapper').css({
+                'padding-top'   : '0em',
+                'padding-bottom': '0em'
+            });
+
+        }, // init
+
+        /* UI management */
+
+        check_field: function(field)
+        {
+            this.el('check', field).attr('checked', true);
+        },
+
+        uncheck_field: function(field)
+        {
+            this.el('check', field).attr('checked', false);
+        },
+
+        update_filter_value: function(filter, removed)
+        {
+            removed = !(typeof removed === 'undefined'); // default = False
+
+            var key   = filter[0];
+            var op    = filter[1];
+            var value = filter[2];
+
+            var id = this.id_from_field(key);
+
+            if (op == '=') {
+                var element = this.el(id);
+            } else {
+                var suffix;
+                if (op == '<') {
+                    this.el(id, 'max').val(value);
+                } else if (op == '>') {
+                    this.el(id, 'min').val(value);
+                } else {
+                    return;
+                }
+                var element = this.el(id, suffix);
+            }
+
+            element.val(removed?null:value);
+
+        },
+
+        /* Events */
+
+        on_filter_added: function(filter)
+        {
+            this.update_filter_value(filter);
+        },
+
+        on_filter_removed: function(filter)
+        {
+            this.update_filter_value(filter, true);
+        },
+
+        on_field_added: function(field)
+        {
+            this.check_field(field);
+        },
+
+        on_field_removed: function(field)
+        {
+            this.uncheck_field(field);
+        },
+
+        /* Former code not used at the moment */
+
+        print_field_description: function(field_header, div_id) 
+        { 
+            //var selected = all_headers[field_header];
+            var selected = getMetadata_field('resource',field_header);
+
+            field_header = div_id+"_"+field_header;
+
+            var output = "<div id='desc"+field_header+"'>";
+
+            output += "<div id='divinfo"+field_header+"'>";
+            output += '<p><span class="column-title">'+selected['title']+'</span></p></span>'; 
+            output += '<p><span class="column-detail">'+selected['description']+'</span></p></span>'; 
+
+            var period_select = "<select id='selectperiod"+field_header+"'><option value='Now'> Now </option><option value='latest'> Latest  </option><option value=w> Week </option><option value=m> Month </option><option value=y> Year </option></select>";
+
+            if (selected['value_type'] == 'string') {
+
+                var values_select = "<p><select id='selectvalues"+field_header+"' MULTIPLE size=3>";
+
+                output += '<p>Values: ';
+
+                var values_list = selected['allowed_values'].split(",");
+
+                for (var value_index = 0; value_index < values_list.length ; value_index++) {
+                    var value_desc = values_list[value_index].split("-");
+                    if (value_index > 0)
+                        output += ', ';
+                    output += '<span class="bold">'+value_desc[0]+'</span>';
+                    values_select += "<option value ='"+value_desc[0]+"'>&nbsp;"+value_desc[0];
+                    if (value_desc[1]!='') 
+                        output += ' ('+value_desc[1]+')';
+
+                    values_select += "&nbsp;</option>";
+                }
+                values_select += "</select>";
+            }
+            else
+                output+='<p>Unit: '+selected['unit'];
+
+            output+= '</p>';
+
+            output += '<p>Source: <a class="source-url" target="source_window" href="'+selected['platform_url']+'">'+selected['platform']+'</a>';
+
+            //if (selected['via'] != '') 
+                //output += ' via <a class="source-url" target="source_window" href="http://'+selected['via_url']+'">'+selected['via']+'</a>';
+
+            output += '</p>';
+            output += "</div>";
+
+    /*
+            output += "<div id='divgroup"+field_header+"'>";
+            output += "<p>Group resources with the same value <input type=checkbox></input>";
+            output += "<p>Select aggregator : <select><option>Count</option><option selected=true>Average</option><option>Maximum</option><option>Minimum</option></select>";
+            output += "</div>";
+            output += "<div id='divtime"+field_header+"'>";
+            output += "<p>Select timestamp : ";
+            output += period_select;
+            output += "</div>";
+    */
+            output += "</div>";
+
+            return output;
+        },
+
+        update_autocomplete: function(e, rows, current_query)
+        {
+            var d = data;
+            d.current_query = current_query;
+            var availableTags={};
+            jQuery.each (rows, function(index, obj) {                    
+                jQuery.each(obj,function(key,value){                       
+                    value = get_value(value); 
+                    if(!availableTags.hasOwnProperty(key)){availableTags[key]=new Array();}
+                    //availableTags[key].push(value);
+                    var currentArray=availableTags[key];
+                    if(value!=null){
+                        if(jQuery.inArray(value,currentArray)==-1){availableTags[key].push(value);}
+                    }
+                });                    
+            });
+            jQuery.each(availableTags, function(key, value){
+                value.sort();
+                jQuery("#"+options.plugin_uuid+"-filter-"+key).autocomplete({
+                            source: value,
+                            selectFirst: true,
+                            minLength: 0, // allows to browse items with no value typed in
+                            select: function(event, ui) {
+                                var key=getKeySplitId(this.id,"-");
+                                var op='=';
+                                var val=ui.item.value;
+                                
+                                query=d.current_query;
+                                query.update_filter(key,op,val);
+                                // Publish the query changed, the other plugins with subscribe will get the changes
+                                jQuery.publish('/query/' + query.uuid + '/changed', query);
+                                //add_ActiveFilter(this.id,'=',ui.item.value,d);
+                            }
+                });
+            });                
+        }, // update_autocomplete     
+
+        fnFormatDetails: function( metaTable, nTr, div_id ) 
+        {
+            var aData = metaTable.fnGetData( nTr );
+            var sOut = '<blockquote>';
+            //sOut += prepare_tab_description(aData[1].substr(21, aData[1].length-21-7), div_id);
+            sOut += this.print_field_description(aData[1].substring(3, aData[1].length-4), div_id);
+            sOut += '</blockquote>';
+         
+            return sOut;
+        }
+    });
+
+    $.plugin('QueryEditor', QueryEditor);
+
+})(jQuery);
diff --git a/plugins/query_editor/static/query_editor.html b/plugins/query_editor/static/query_editor.html
new file mode 100644 (file)
index 0000000..930053c
--- /dev/null
@@ -0,0 +1,42 @@
+<!--
+       $infopopup = <<<EOF
+<span class='info'><span> This tab allows you to customize the visible columns in the resource list, below. Note that information on the nodes comes from a variety of monitoring sources.  If you, as either a user or a provider of monitoring data, would like to see additional columns made available, please send us your request in mail to <a href='mailto:support@myslice.info'>support@myslice.info</a>. You can find more information about the MySlice project at <a href='http://trac.myslice.info'>http://trac.myslice.info</a>.  </span></span>
+EOF;
+
+           $filter_input = "<input id='filter_value' type=text size=5></input>";
+
+EOF; -->
+
+<div>
+  <table id='{{domid}}__table' class='display' width='95%'>
+    <thead>
+      <tr>
+        <th class='center'>Info</th>
+        <th class='center'>Field</th>
+        <th class='center'>Resource</th>
+        <th class='center'>Type</th>
+        <th class='center'>Filter</th>
+        <th class='center'>+/-</th>
+      </tr>
+    </thead>
+    <tbody>
+
+    {# Loop through metadata and display related information #}
+    {% for field in fields %}
+
+      <tr>
+        <td class='center'><span class='ui-icon ui-icon-triangle-1-e' style='cursor:pointer'></span></td>
+        <td class='center'>{{ field.name }}</td>
+        <td class='center'>{{ field.resource_type }}</td>
+        <td class='center'>{{ field.type }}</td>
+        <td class='center'>{{ field.filter_input }}</td>
+        <td class='center'>
+          <input class='queryeditor-check' id='{{domid}}__check__{{ field.name }}' name='{{ field.header }}' type='checkbox' autocomplete='off' value='{{ field.name }}' {% if field.checked %} checked {% endif %}></input>
+        </td>
+      </tr>
+               
+       {% endfor %}
+
+    </tbody>
+  </table>
+</div>
similarity index 97%
rename from plugins/querycode/querycode.js
rename to plugins/querycode/static/js/querycode.js
index 6dc00c4..c655529 100644 (file)
        });
        ofs = '[' + ofs + ']';
 
-       output += 'pp srv.call("' + mixed_case(query.action) +'", auth, "' + query.subject + '", "' + query.timestamp + '", ' + ifs + ', ' + ofs + ')';
+       output += 'pp srv.call("' + mixed_case(query.action) +'", auth, "' + query.object + '", "' + query.timestamp + '", ' + ifs + ', ' + ofs + ')';
 
        var output = '<pre class="brush: ruby; toolbar: false;">' + output + "</pre>";
        return output;
        });
        ofs = '[' + ofs + ']';
 
-       output += 'srv.' + mixed_case(query.action) + '(auth, "' + query.subject + '", ' + ifs + ', {}, ' + ofs + ')';
+       output += 'srv.' + mixed_case(query.action) + '(auth, "' + query.object + '", ' + ifs + ', {}, ' + ofs + ')';
        var output = '<pre class="brush: python; toolbar: false;">' + output + "</pre>";
        return output;
     }
diff --git a/plugins/resources_selected/__init__.py b/plugins/resources_selected/__init__.py
new file mode 100644 (file)
index 0000000..a5bbac7
--- /dev/null
@@ -0,0 +1,19 @@
+from unfold.plugin import Plugin
+
+class ResourcesSelected(Plugin):
+
+    def template_file (self):
+        return "resources_selected.html"
+
+    def requirements (self):
+        reqs = {
+            'js_files' : [ "js/resources_selected.js" ] ,
+            'css_files': [ "css/resources_selected.css" ],
+            }
+        return reqs
+
+    def json_settings_list (self):
+        return ['plugin_uuid', 'domid', 'query_uuid']
+
+    def export_json_settings (self):
+        return True
diff --git a/plugins/resources_selected/static/css/resources_selected.css b/plugins/resources_selected/static/css/resources_selected.css
new file mode 100644 (file)
index 0000000..a9a0bda
--- /dev/null
@@ -0,0 +1,34 @@
+/* 
+    Document   : ResourcesSelected
+    Created on : 9 août 2012, 11:54:41
+    Author     : loicbaron
+    Description:
+        Purpose of the stylesheet follows.
+*/
+
+tr.add td{ 
+    background-color: #E3F6CE;
+}
+tr.remove td{ 
+    background-color: #F6CECE;
+}
+.ResourceSelectedClose{
+    cursor: pointer;
+}
+
+input.myslice_action {
+   font-size:13px;
+   font-family:Arial,sans-serif;
+   font-weight:bold;
+   color:#0066CC;
+   width:100px;
+   height:30px;
+   background-color:#FF9933;
+}
+
+.ResourcesSelected .added {
+    background-color: #E3F6CE;
+}
+.ResourcesSelected .removed {
+    background-color: #F6CECE;
+}
diff --git a/plugins/resources_selected/static/js/resources_selected.js b/plugins/resources_selected/static/js/resources_selected.js
new file mode 100644 (file)
index 0000000..56a49af
--- /dev/null
@@ -0,0 +1,439 @@
+/**
+ * MySlice ResourcesSelected plugin
+ * Version: 0.1.0
+ * URL: http://www.myslice.info
+ * Description: display of selected resources
+ * Requires: 
+ * Author: The MySlice Team
+ * Copyright: Copyright 2012 UPMC Sorbonne Universités
+ * License: GPLv3
+ */
+
+(function( $ ){
+
+    // XXX record selected (multiple selection ?)
+    // XXX record disabled ?
+    // XXX out of sync plugin ?
+    // XXX out of date record ?
+    // record tags ???
+    //
+    // criticality of the absence of a handler in a plugin
+    // non-critical only can have switch case
+    // 
+    // Record state through the query cycle
+
+
+    var ResourcesSelected = Plugin.extend({
+
+        init: function(options, element)
+        {
+            this._super(options, element);
+
+            var self = this;
+            this.table = this.el('table').dataTable({
+                //sPaginationType: 'full_numbers',  // Use pagination
+                sPaginationType: 'bootstrap',
+                //bJQueryUI      : true,
+                //bRetrieve      : true,
+                sScrollX       : '100%',                 // Horizontal scrolling 
+                bSortClasses   : false,              // Disable style for the sorted column
+                aaSorting      : [[ 0, 'asc' ]],        // Default sorting on URN
+                fnDrawCallback: function() {      // Reassociate close click every time the table is redrawn
+                    /* Prevent to loop on click while redrawing table  */
+                    $('.ResourceSelectedClose').unbind('click');
+                    /* Handle clicks on close span */
+                    /* Reassociate close click every time the table is redrawn */
+                    $('.ResourceSelectedClose').bind('click', self, self._close_click);
+                }
+             });
+            
+            // XXX This should not be done at init...
+            this.el('update').click(this, this.do_update);
+            this.el('refresh').click(this, this.do_refresh);
+            this.el('reset').click(this, this.do_reset);
+            this.el('clear_annotations').click(this, this.do_clear_annotations);
+
+            this.listen_query(options.query_uuid);
+        },
+
+        /*************************** PLUGIN EVENTS ****************************/
+
+        /***************************** GUI EVENTS *****************************/
+
+        do_update: function(e) 
+        {
+            var self = e.data;
+            // XXX check that the query is not disabled
+            manifold.raise_event(self.options.query_uuid, RUN_UPDATE);
+        },
+
+        do_refresh: function(e)
+        {
+            throw 'Not implemented';
+        },
+
+        do_reset: function(e)
+        {
+            throw 'Not implemented';
+        },
+
+        do_clear_annotations: function(e)
+        {
+            throw 'Not implemented';
+        },
+        
+        /************************** GUI MANIPULATION **************************/
+
+        
+        set_button_state: function(name, state)
+        {
+            this.el(name).attr('disabled', state ? false : 'disabled');
+        },
+
+        clear: function()
+        {
+
+        },
+
+        find_row: function(key)
+        {
+            // key in third position, column id = 2
+            var KEY_POS = 2;
+
+            var cols = $.grep(this.table.fnSettings().aoData, function(col) {
+                return (col._aData[KEY_POS] == key);
+            } );
+
+            if (cols.length == 0)
+                return null;
+            if (cols.length > 1)
+                throw "Too many same-key rows in ResourceSelected plugin";
+
+            return cols[0];
+        },
+
+        set_state: function(data)
+        {
+            var action;
+            var msg;
+            var button = '';
+
+            var row;
+
+            switch(data.request) {
+                case FIELD_REQUEST_ADD_RESET:
+                case FIELD_REQUEST_REMOVE_RESET:
+                    // find line and delete it
+                    row = this.find_row(data.value);
+                    if (row)
+                        this.table.fnDeleteRow(row.nTr);
+                    return;
+                case FIELD_REQUEST_CHANGE:
+                    action = 'UPDATE';
+                    break;
+                case FIELD_REQUEST_ADD:
+                    action = 'ADD';
+                    break;
+                case FIELD_REQUEST_REMOVE:
+                    action = 'REMOVE';
+                    break;
+            }
+
+            switch(data.status) {
+                case FIELD_REQUEST_PENDING:
+                    msg   = 'PENDING';
+                    button = "<span class='ui-icon ui-icon-close ResourceSelectedClose' id='" + data.key + "'/>";
+                    break;
+                case FIELD_REQUEST_SUCCESS:
+                    msg   = 'SUCCESS';
+                    break;
+                case FIELD_REQUEST_FAILURE:
+                    msg   = 'FAILURE';
+                    break;
+            }
+
+            var status = msg + status;
+
+            // find line
+            // if no, create it, else replace it
+            // XXX it's not just about adding lines, but sometimes removing some
+            // XXX how do we handle status reset ?
+            row = this.find_row(data.value);
+            newline = [
+                action,
+                data.key,
+                data.value,
+                msg,
+                button
+            ];
+            if (!row) {
+                // XXX second parameter refresh = false can improve performance. todo in hazelnut also
+                this.table.fnAddData(newline);
+                row = this.find_row(data.value);
+            } else {
+                // Update row text...
+                this.table.fnUpdate(newline, row.nTr);
+            }
+
+            // Change cell color according to status
+            if (row) {
+                $(row.nTr).removeClass('add remove')
+                var cls = action.toLowerCase();
+                if (cls)
+                    $(row.nTr).addClass(cls);
+            }
+        },
+
+        /*************************** QUERY HANDLER ****************************/
+
+        // NONE
+
+        /*************************** RECORD HANDLER ***************************/
+
+        on_new_record: function(record)
+        {
+            // if (not and update) {
+
+                // initial['resource'], initial['lease'] ?
+                this.initial.push(record.urn);
+
+                // We simply add to the table
+            // } else {
+                //                 \ this.initial_resources
+                //                  \
+                // this.             \
+                // current_resources  \    YES    |   NO
+                // --------------------+----------+---------
+                //       YES           | attached | added
+                //       NO            | removed  |   /
+                // 
+
+            // }
+        },
+
+        // QUERY STATUS
+        //                                      +-----------------+--------------+
+        //                                      v        R        |              |
+        // +-------+  ?G    +-------+        +-------+        +---+---+          |
+        // |       | -----> |       |  !G    |       |        |       |    DA    |
+        // |  ND   |        |  PG   | -----> |   D   | -----> |  PC   | <------+ |
+        // |       | <----- |       |  ~G    |       |   C    |       |        | | 
+        // +-------+   GE   +-------+        +-------+        +-------+      +------+
+        //                                       ^              ^  |         |      |
+        //                                       | DA        UE |  | ?U      | PCA  |
+        //                                       |              |  v         |      |
+        //                                   +-------+        +-------+      +------+
+        //                                   |       |   !U   |       |         ^
+        //                                   |  AD   | <----- |  PU   | --------+
+        //                                   |       |        |       |   ~U     
+        //                                   +-------+        +-------+          
+        //                                                                       
+        //
+        // LEGEND:
+        // 
+        // Plugins (i) receive state information, (ii) perform actions
+        //
+        // States:                                  Actions:
+        // ND : No data                             ?G : Get query
+        // PG : Pending Get                         !G : Get reply  
+        //  D : Data present                        ~G : Get partial reply
+        // PC : Pending changes                     GE : Get error                            
+        // PU : Pending update                       C : Change request
+        // PCA: Pending change with annotation       R : Reset request
+        // AD : Annotated data                      ?U : Update query
+        //                                          !U : Update reply
+        //                                          ~U : Update partial reply
+        //                                          UE : Update error            
+        //                                          DA : Delete annotation request
+        // NOTE:
+        // - D -> PU directly if the user chooses 'dynamic update'
+        // - Be careful for updates if partial Get success
+
+        // ND: No data == initialization state
+        
+        // PG : Pending get
+        // - on_query_in_progress
+        // NOTE: cannot distinguish get and update here. Is it important ?
+
+        on_query_in_progress: function()
+        {
+            this.spin();
+        },
+
+        // D : Data present
+        // - on_clear_records (Get)
+        // - on_new_record (shared with AD) XXX
+        // - on_query_done
+        // NOTE: cannot distinguish get and update here. Is it important ?
+        // NOTE: Would record key be sufficient for update ?
+
+        on_clear_records: function()
+        {
+            this.clear();
+        },
+
+        on_new_record: function(record)
+        {
+        },
+
+        on_query_done: function()
+        {
+            this.unspin();
+        },
+
+        // PC : Pending changes
+        // NOTE: record_key could be sufficient 
+        on_added_record: function(record)
+        {
+            this.set_record_state(record, RECORD_STATE_ADDED);
+        },
+
+        on_removed_record: function(record_key)
+        {
+            this.set_record_state(RECORD_STATE_REMOVED);
+        },
+
+        // PU : Pending update
+        // - on_query_in_progress (already done)
+        
+        // PCA : Pending change with annotation
+        // NOTE: Manifold will inform the plugin about updates, and thus won't
+        // call new record, even if the same channel UUID is used...
+        // - TODO on_updated_record
+        // - Key and confirmation could be sufficient, or key and record state
+        // XXX move record state to the manifold plugin API
+
+        on_field_state_changed: function(request, key, value, status)
+        {
+            this.set_state(request, key, value, status);
+        },
+
+        // XXX we will have the requests for change
+        // XXX + the requests to move into the query cycle = the buttons aforementioned
+
+        // XXX what happens in case of updates ? not implemented yet
+        // XXX we want resources and leases
+        // listen for SET_ADD and SET_REMOVE for slice query
+
+        /************************** PRIVATE METHODS ***************************/
+
+        _close_click: function(e)
+        {
+            var self = e.data;
+
+            //jQuery.publish('selected', 'add/'+key_value);
+            // this.parentNode is <td> this.parentNode.parentNode is <tr> 
+            // this.parentNode.parentNode.firstChild is the first cell <td> of this line <tr>
+            // this.parentNode.parentNode.firstChild.firstChild is the text in that cell
+            //var firstCellVal=this.parentNode.parentNode.firstChild.firstChild.data;
+            var remove_urn = this.id; 
+            var current_resources = event.data.instance.current_resources;
+            var list_resources = $.grep(current_resources, function(x) {return x.urn != remove_urn});
+            //jQuery.publish('selected', 'cancel/'+this.id+'/'+get_value(firstCellVal));
+            $.publish('/update-set/' + event.data.instance.options.resource_query_uuid, [list_resources, true]);
+        },
+
+        /******************************** TODO ********************************/
+
+        update_resources: function(resources, change)
+        {
+            console.log("update_resources");
+            var my_oTable = this.table.dataTable();
+            var prev_resources = this.current_resources; 
+
+            /*
+             * The first time the query is advertised, don't do anything.  The
+             * component will learn nodes in the slice through the manifest
+             * received through the other subscription 
+             */
+             if (!change)
+                return;
+             // ioi: Refubrished
+             var initial = this.initial_resources;
+             //var r_removed  = []; //
+             /*-----------------------------------------------------------------------
+                TODO: remove this dirty hack !!!
+             */
+             resources = jQuery.map(resources, function(x){
+                if(!('timeslot' in x)){x.timeslot=0;}
+                return x;
+             });
+             /*
+                TODO: handle generic keys instead of specific stuff
+                      ex: urn
+                          urn-lease
+             */
+             var initial_urn = $.map(initial, function(x){return x.urn;});
+             var resources_urn = $.map(resources, function(x){return x.urn;});
+             var r_removed = $.grep(initial, function (x) { return $.inArray(x.urn, resources_urn) == -1 });
+             var r_attached = $.grep(initial, function (x) { return $.inArray(x.urn, resources_urn) > -1 });
+             var r_added = $.grep(resources, function (x) { return $.inArray(x.urn, initial_urn) == -1 });
+             exists = false; // ioi
+             /*-----------------------------------------------------------------------*/
+
+             my_oTable.fnClearTable();
+             /*
+                TODO: factorization of this code !!!
+             */
+             $.each(r_added, function(i, r) { 
+                //var type = (typeof initial == 'undefined' || r.node != initial.node) ? 'add' : 'attached';
+                var type = 'add';  
+                // Create the resource objects
+                // ioi: refubrished
+                var urn = r.urn;
+                time = r.timeslot;
+                              
+                var SPAN = "<span class='ui-icon ui-icon-close ResourceSelectedClose' id='"+urn+"'/>";
+                var slot = "<span id='resource_"+urn+"'>" + time + "</span>"; //ioi
+                // ioi
+                var newline=Array();
+                newline.push(type, urn, slot, SPAN); // ioi
+                var line = my_oTable.fnAddData(newline);
+                var nTr = my_oTable.fnSettings().aoData[ line[0] ].nTr;
+                nTr.className = type;
+             });
+             $.each(r_attached, function(i, r) {  
+                //var type = (typeof initial == 'undefined' || r.node != initial.node) ? 'add' : 'attached';
+                var type = 'attached';
+                // Create the resource objects
+                // ioi: refubrished
+                var node = r.urn;
+                time = r.timeslot;
+
+                var SPAN = "<span class='ui-icon ui-icon-close ResourceSelectedClose' id='"+node+"'/>";
+                var slot = "<span id='resource_"+node+"'>" + time + "</span>"; //ioi
+                // ioi
+                var newline=Array();
+                newline.push(type, node, slot, SPAN); // ioi
+                var line = my_oTable.fnAddData(newline);
+                var nTr = my_oTable.fnSettings().aoData[ line[0] ].nTr;
+                nTr.className = type;
+             });
+             $.each(r_removed, function(i, r) { 
+                // The list contains objects
+                // ioi: refubrished
+                var node = r.urn;
+                var time = r.timeslot;
+                    
+                var SPAN = "<span class='ui-icon ui-icon-close ResourceSelectedClose' id='"+node+"'/>";
+                var slot = "<span id='resource_"+node+"'>" + time + "</span>";
+                // ioi
+                var newline=Array();
+                newline.push('remove', node, slot, SPAN); // ioi
+                var line = my_oTable.fnAddData(newline);
+                var nTr = my_oTable.fnSettings().aoData[ line[0] ].nTr;
+                nTr.className = 'remove';
+             });
+
+             this.current_resources = $.merge(r_attached,r_added);
+
+             /* Allow the user to update the slice */
+             //jQuery('#updateslice-' + data.ResourceSelected.plugin_uuid).prop('disabled', false);
+
+        }, // update_resources
+
+    });
+
+    $.plugin('ResourcesSelected', ResourcesSelected);
+
+})(jQuery);
diff --git a/plugins/resources_selected/static/resources_selected.html b/plugins/resources_selected/static/resources_selected.html
new file mode 100644 (file)
index 0000000..aa5e485
--- /dev/null
@@ -0,0 +1,15 @@
+<table class='display' id='{{domid}}__table'>
+  <thead>
+    <tr>
+      <th>action</th>
+      <th>key</th>
+      <th>value</th>
+      <th>status</th>
+      <th>+/-</th>
+    </tr>
+  </thead>
+</table>
+<input id="{{domid}}__update" type=button value="Update" />
+<input id="{{domid}}__refresh" type=button value="Refresh" />
+<input id="{{domid}}__reset" type=button value="Reset" />
+<input id="{{domid}}__clear_annotations" type=button value="Clear annotations" />
diff --git a/plugins/tabs/static/js/tabs.js b/plugins/tabs/static/js/tabs.js
new file mode 100644 (file)
index 0000000..b5b1cd0
--- /dev/null
@@ -0,0 +1,12 @@
+(function($){
+
+    $.fn.Tabs = function( method ) {
+
+        $('a[data-toggle="tab"]').on('shown', function (e) {
+          // find the plugin object inside the tab content referenced by the current tabs
+          $('.plugin', $($(e.target).attr('href'))).trigger('show');
+        });
+
+    };
+
+})( jQuery );
index 0350c26..6da94da 100644 (file)
@@ -3,7 +3,7 @@ from unfold.composite import Composite
 class Tabs (Composite):
     
     def requirements (self):
-        return { 'js_files'     : 'js/bootstrap.js',
+        return { 'js_files'     : ['js/tabs.js', 'js/bootstrap.js'],
                  'css_files'    : ['css/bootstrap.css', 'css/tabs.css', ] 
                  }
 
@@ -12,3 +12,8 @@ class Tabs (Composite):
 
     # see Composite.py for the details of template_env, that exposes global
     # 'sons' as a list of sons with each a set of a few attributes
+    def json_settings_list (self):
+        return []
+
+    def export_json_settings(self):
+        return True
diff --git a/plugins/updater/WARNING b/plugins/updater/WARNING
new file mode 100644 (file)
index 0000000..9e0494c
--- /dev/null
@@ -0,0 +1,4 @@
+This plugin was an early attempt at implementing the widget that would
+. actually gather pending changes
+. and have an 'Update' button so as to post them
+However this work has been put on hold and is currently not used in real apps.
index e69de29..2f68b41 100644 (file)
@@ -0,0 +1,31 @@
+from unfold.plugin import Plugin
+
+class Updater (Plugin):
+
+    def __init__ (self, query, label="Update", **settings):
+        Plugin.__init__ (self, **settings)
+        self.query=query
+        if query.action != "get": print "Updater on non-get query: ",query.action
+        self.label=label
+
+    def template_file (self):
+        return "updater.html"
+
+    def requirements (self):
+        return {
+            'js_files' :  [ "js/updater.js" , "js/manifold.js", "js/manifold-query.js", 
+                            "js/spin.presets.js", "js/spin.min.js", "js/jquery.spin.js",
+                            "js/Math.uuid.js",
+                            ],
+            'css_files' : "css/updater.css",
+            }
+
+    # although this has no query, we need a plugin instance to be created in the js output
+    def export_json_settings (self):     return True
+    # the js plugin expects a domid
+    def json_settings_list (self):       return [ 'plugin_uuid', 'query_uuid', ]
+
+    # and we don't need a spin wheel 
+    def start_with_spin (self):          return False
+
+    def default_togglable (self):        return False
diff --git a/plugins/updater/static/js/updater.js b/plugins/updater/static/js/updater.js
new file mode 100644 (file)
index 0000000..d14d5d8
--- /dev/null
@@ -0,0 +1,144 @@
+/**
+ * Description: Manage query updates
+ * Copyright (c) 2012-2013 UPMC Sorbonne Universite - INRIA
+ * License: GPLv3
+ */
+
+(function( $ ) {
+    
+    var debug=false;
+//    debug=true
+
+    var Updater = Plugin.extend({
+
+        init: function(options, element)
+        {
+            this._super(options, element);
+            
+            this.listen_query(options.query_uuid);
+        },
+
+        
+        /*************************** PLUGIN EVENTS ****************************/
+
+        /***************************** GUI EVENTS *****************************/
+
+        arm_button: function()
+        {
+               this.el('updater').click(this, this.submit_update_request);
+        },
+
+        submit_update_request: function (e) 
+        {
+            var self = e.data;
+
+            manifold.raise_event(self.options.query_uuid, RUN_UPDATE);
+
+        },
+
+        /************************** GUI MANIPULATION **************************/
+
+        disable_update_button: function()
+        {
+            this.el('updater').attr('disabled', 'disabled');
+        },
+
+        /*************************** QUERY HANDLER ****************************/
+
+        /*************************** RECORD HANDLER ***************************/
+
+        /************************** PRIVATE METHODS ***************************/
+
+        /******************************** TODO ********************************/
+
+        /*
+           query_failed: function (e, code, output) 
+        {
+            var plugindiv=e.data;
+            var updater=plugindiv.data('Updater');
+                $('#updater-' + updater.options.plugin_uuid).removeAttr('disabled');
+            // just as a means to deom how to retrieve the stuff passed on the channel
+            if (debug)
+                messages.debug("retrieved error code " + code + " and output " + output);
+       },
+           
+        update_resources: function (e, resources, change)
+        {
+                data = e.data.instance.data().Slices;
+
+                data.update_query.params['resource'] = resources
+                $.publish('/update/' + data.options.query_uuid, [data.update_query, true]);
+        },
+
+        update_leases: function (e, leases, change) 
+        {
+            data = e.data.instance.data().Slices;
+            
+            data.update_query.params['lease'] = leases
+            $.publish('/update/' + data.options.query_uuid, [data.update_query, true]);
+        },
+        
+        query_completed: function (e, rows, query)
+        {
+
+            // This function is called twice : get and update 
+            messages.info("updater.query_completed - not implemented yet");
+            return;
+          
+            var data = e.data.instance.data().Slices;
+          
+            // Update placeholders and trigger subqueries updates 
+            if (rows.length == 0) {
+            alert("no result");
+            return;
+            }
+            var slice = rows[0];
+          
+            // for get
+            if (data.update_query == null) {
+                data.update_query = new Query('update','slice', 'now', query.filter, {"resource": null, "lease": null}, query.fields, 0, data.options.query_uuid);
+            }
+            // In case of update the list of resources and leases should be updated accordingly
+          
+            // only for get ?
+            $.each(slice, function(key, value) {
+            if (typeof value == 'string') {
+                $('#myslice__' + key).html(value);
+            }
+            });
+          
+            // TODO avoid repetitions + made this code generic and plugin-independent 
+            
+            if (query.method == 'update') {
+                // XXX NON, les uuid doivent etre les memes que dans la query Get, cet appel devrait etre fait avant.
+                query.analyzed_subqueries();
+            }
+          
+            // NOTE: Dans le cadre d'un update, on n'a pas besoin de refaire tout
+            // le query plan et obtenir toutes les infos, par contre on ne peut pas
+            // savoir d'avance quels parametres ont été accordés, changés, etc.
+            // Dans le cas général, ca pourrait affecter le query plan...
+            // Par contre on n'a pas d'information sur toutes les resources, mais
+            // uniquement celles dans la liste. Comment gérer ?
+            
+            // Inform child plugins about their respective parts of the results 
+            // Only for get 
+            var r_subq = query.analyzed_query.subqueries['resource'];
+            var l_subq = query.analyzed_query.subqueries['lease'];
+            $.publish('/results/' + r_subq.uuid + '/changed', [slice['resource'], r_subq]);
+            $.publish('/results/' + l_subq.uuid + '/changed', [slice['lease'],    l_subq]);
+            
+            // Subscribe to get notifications from child plugins
+            if (!data.child_subscribe) {
+                $.subscribe('/update-set/' + r_subq.uuid, {instance: e.data.instance}, update_resources);
+                $.subscribe('/update-set/' + l_subq.uuid, {instance: e.data.instance}, update_leases);
+                data.child_subscribe = true
+            }
+            
+        }
+        */
+    });
+
+    $.plugin('Updater', Updater);
+
+})( jQuery );
diff --git a/plugins/updater/static/updater.html b/plugins/updater/static/updater.html
new file mode 100644 (file)
index 0000000..798b17a
--- /dev/null
@@ -0,0 +1 @@
+<input id="{{domid}}__updater" class="updater" type=button value="{{ label }}" />
diff --git a/plugins/updater/updater.html b/plugins/updater/updater.html
deleted file mode 100644 (file)
index 7edc44d..0000000
+++ /dev/null
@@ -1 +0,0 @@
-<input id="updater-{{ domid }}" class="updater" type=button value="{{ label }}" />
diff --git a/plugins/updater/updater.js b/plugins/updater/updater.js
deleted file mode 100644 (file)
index 3c35b4d..0000000
+++ /dev/null
@@ -1,167 +0,0 @@
-/**
- * Description: associate with a Get query, maintains the 'Update' query that records pending changes
- * Copyright (c) 2012 UPMC Sorbonne Universite - INRIA
- * License: GPLv3
- */
-
-// xxx this is ongoing work, very rough, and not working at all yet 
-
-( function ( $ ) {
-    
-    var debug=false;
-//    debug=true
-
-    $.fn.Updater = function ( method ) {
-        /* Method calling logic */
-        if ( methods[method] ) {
-            return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
-        } else if ( typeof method === 'object' || ! method ) {
-            return methods.init.apply( this, arguments );
-        } else {
-            $.error( 'Method ' +  method + ' does not exist on $.Updater' );
-        }
-    };
-    
-    var methods = {
-       init : function( options ) {
-           return this.each(function(){
-               var $this = $(this);
-               var updater = new Updater (options);
-               $this.data('Updater',updater);
-               // xxx not tested yet
-                var results_channel = '/results/' + options.query_uuid + '/changed';
-               $.subscribe(results_channel, function (e,rows) { updater.query_completed (e,rows); } );
-               // under test..
-               var failed_channel = '/results/' + options.query_uuid + '/failed';
-               $.subscribe(failed_channel, $this, function (e,code,output) { updater.query_failed (e, code, output); } );
-           });
-       },
-       destroy : function( ) {
-            return this.each(function(){
-               var $this = $(this);
-               $(window).unbind('Updater');
-               data.Updater.remove();
-               $this.removeData('Updater');
-            });
-       },
-
-       show : function( content ) { }
-    };
-    
-    function Updater (options) {
-       this.options=options;
-       // xxx should try to locate update_query first, in case we have several Updaters
-       // on the same query
-       // however the mental model behind the global manifold object for now is 
-       // to unambiguously find a query based on its query_uuid, which in the joomla
-       // implementation wouldn't fly
-       // we keep this for a later improvement
-       var query=manifold.find_query (options.query_uuid);
-       // very rough way of filling this for now
-       this.update_query = 
-           new ManifoldQuery ("update", query.subject, null, query.filters, 
-                              {}, // params
-                              query.fields, 
-                              undefined, /* unique */ 
-                              Math.uuid(32,16), 
-                              undefined, undefined /* maybe some day I'll get that one */);
-       manifold.insert_query (this.update_query);
-       // arm button once document is loaded
-       (function(updater) {$(document).ready(function(){updater.arm_button()})})(this);
-
-       this.arm_button = function () {
-           $('#updater-' + this.options.plugin_uuid).click(this, this.submit_update_request);
-       },
-       this.submit_update_request = function (e) {
-           var query_uuid = e.data.options.query_uuid;
-           var update_query = e.data.update_query;
-           if (debug) messages.debug("Updater.submit_update_request " + update_query.__repr());
-           // actually send the Update query, but publish results as if coming from the original query
-           manifold.asynchroneous_exec ( [ {'query_uuid': update_query.query_uuid, 'publish_uuid' : query_uuid} ], false);
-           // disable button while the query is flying
-            $('#updater-' + e.data.options.plugin_uuid).attr('disabled', 'disabled');
-        },
-
-       this.query_failed = function (e, code, output) {
-           var plugindiv=e.data;
-           var updater=plugindiv.data('Updater');
-            $('#updater-' + updater.options.plugin_uuid).removeAttr('disabled');
-           // just as a means to deom how to retrieve the stuff passed on the channel
-           if (debug) messages.debug("retrieved error code " + code + " and output " + output);
-       }
-           
-       this.update_resources = function (e, resources, change) {
-            data = e.data.instance.data().Slices;
-
-            data.update_query.params['resource'] = resources
-            $.publish('/update/' + data.options.query_uuid, [data.update_query, true]);
-       },
-
-       this.update_leases = function (e, leases, change) {
-           data = e.data.instance.data().Slices;
-           
-           data.update_query.params['lease'] = leases
-           $.publish('/update/' + data.options.query_uuid, [data.update_query, true]);
-       },
-       
-       this.query_completed = function (e, rows, query) {
-
-           /* This function is called twice : get and update */
-           messages.info("updater.query_completed - not implemented yet");
-           return;
-      
-           var data = e.data.instance.data().Slices;
-      
-           /* Update placeholders and trigger subqueries updates */
-           if (rows.length == 0) {
-               alert("no result");
-               return;
-           }
-           var slice = rows[0];
-      
-           /* for get */
-           if (data.update_query == null) {
-               data.update_query = new Query('update','slice', 'now', query.filter, {"resource": null, "lease": null}, query.fields, 0, data.options.query_uuid);
-           }
-           /* In case of update the list of resources and leases should be updated accordingly */
-      
-           /* only for get ? */
-           $.each(slice, function(key, value) {
-               if (typeof value == 'string') {
-                   $('#myslice__' + key).html(value);
-               }
-           });
-      
-           /* TODO avoid repetitions + made this code generic and plugin-independent */
-           
-           if (query.method == 'update') {
-               // XXX NON, les uuid doivent etre les memes que dans la query Get, cet appel devrait etre fait avant.
-               query.analyzed_subqueries();
-           }
-      
-           /* NOTE: Dans le cadre d'un update, on n'a pas besoin de refaire tout
-            * le query plan et obtenir toutes les infos, par contre on ne peut pas
-            * savoir d'avance quels parametres ont été accordés, changés, etc.
-            * Dans le cas général, ca pourrait affecter le query plan...
-            * Par contre on n'a pas d'information sur toutes les resources, mais
-            * uniquement celles dans la liste. Comment gérer ?
-            */
-           
-            /* Inform child plugins about their respective parts of the results */
-            /* Only for get */
-            var r_subq = query.analyzed_query.subqueries['resource'];
-            var l_subq = query.analyzed_query.subqueries['lease'];
-            $.publish('/results/' + r_subq.uuid + '/changed', [slice['resource'], r_subq]);
-            $.publish('/results/' + l_subq.uuid + '/changed', [slice['lease'],    l_subq]);
-           
-            /* Subscribe to get notifications from child plugins */
-            if (!data.child_subscribe) {
-               $.subscribe('/update-set/' + r_subq.uuid, {instance: e.data.instance}, update_resources);
-               $.subscribe('/update-set/' + l_subq.uuid, {instance: e.data.instance}, update_leases);
-               data.child_subscribe = true
-            }
-           
-       }
-    }
-})( jQuery );
-
diff --git a/plugins/updater/updater.py b/plugins/updater/updater.py
deleted file mode 100644 (file)
index 2f68b41..0000000
+++ /dev/null
@@ -1,31 +0,0 @@
-from unfold.plugin import Plugin
-
-class Updater (Plugin):
-
-    def __init__ (self, query, label="Update", **settings):
-        Plugin.__init__ (self, **settings)
-        self.query=query
-        if query.action != "get": print "Updater on non-get query: ",query.action
-        self.label=label
-
-    def template_file (self):
-        return "updater.html"
-
-    def requirements (self):
-        return {
-            'js_files' :  [ "js/updater.js" , "js/manifold.js", "js/manifold-query.js", 
-                            "js/spin.presets.js", "js/spin.min.js", "js/jquery.spin.js",
-                            "js/Math.uuid.js",
-                            ],
-            'css_files' : "css/updater.css",
-            }
-
-    # although this has no query, we need a plugin instance to be created in the js output
-    def export_json_settings (self):     return True
-    # the js plugin expects a domid
-    def json_settings_list (self):       return [ 'plugin_uuid', 'query_uuid', ]
-
-    # and we don't need a spin wheel 
-    def start_with_spin (self):          return False
-
-    def default_togglable (self):        return False
diff --git a/plugins/wizard/__init__.py b/plugins/wizard/__init__.py
new file mode 100644 (file)
index 0000000..672321c
--- /dev/null
@@ -0,0 +1,24 @@
+from unfold.composite import Composite
+from unfold.plugin    import Plugin
+
+class Wizard(Composite):
+   
+    def __init__(self, *args, **kwargs):
+        Composite.__init__(self, *args, **kwargs)
+        self.validate_step_js = []
+        
+    def export_json_settings(self):
+        # We need initialization, even though we are not associated with a query
+        return True
+    
+    def requirements (self):
+        #return { 'js_files'     : ['js/wizard.js', 'js/jquery.smartWizard-2.0.min.js', ],
+        return { 'js_files'     : ['js/wizard.js', 'js/jquery.smartWizard-2.0.js', ],
+                 'css_files'    : ['css/wizard.css', 'css/smart_wizard.css', ] 
+                 }
+
+    def template_file (self):
+        return "wizard.html"
+
+    # the list of things passed to the js plugin
+    def json_settings_list (self): return ['plugin_uuid', 'start_step']
diff --git a/plugins/wizard/static/css/wizard.css b/plugins/wizard/static/css/wizard.css
new file mode 100644 (file)
index 0000000..0c79c47
--- /dev/null
@@ -0,0 +1,11 @@
+.swMain {
+       width: 100% !important;
+}
+
+.swMain .stepContainer div.content {
+       width: 100% !important;
+}
+
+.swMain .stepContainer {
+       overflow: scroll !important;
+}
diff --git a/plugins/wizard/static/js/wizard.js b/plugins/wizard/static/js/wizard.js
new file mode 100644 (file)
index 0000000..c95826f
--- /dev/null
@@ -0,0 +1,478 @@
+/**
+ * Description: implements a wizard-like interface
+ * Copyright (c) 2013 UPMC Sorbonne Universite
+ * Based on SmartWizard 2.0 plugin by Dipu (http://www.techlaboratory.net)
+ * License: GPLv3
+ */
+
+/*
+ * It's a best practice to pass jQuery to an IIFE (Immediately Invoked Function
+ * Expression) that maps it to the dollar sign so it can't be overwritten by
+ * another library in the scope of its execution.
+ */
+(function($){
+
+    /***************************************************************************
+     * Method calling logic
+     ***************************************************************************/
+
+    $.fn.Wizard = function( method ) {
+        if ( methods[method] ) {
+            return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
+        } else if ( typeof method === 'object' || ! method ) {
+            return methods.init.apply( this, arguments );
+        } else {
+            //$.error( 'Method ' +  method + ' does not exist on jQuery.Wizard' );
+            return undefined;
+        }    
+    };
+
+    /***************************************************************************
+     * Public methods
+     ***************************************************************************/
+
+    var methods = {
+
+        /**
+         * @brief Plugin initialization
+         * @param options : an associative array of setting values
+         * @return : a jQuery collection of objects on which the plugin is
+         *     applied, which allows to maintain chainability of calls
+         */
+        init : function ( options ) {
+
+            /* Default settings */
+            var options = $.extend({}, $.fn.Wizard.defaults, options);
+
+            return this.each(function() {
+                var $this = $(this);
+                var obj = $(wizard, this);
+
+                /* An object that will hold private variables and methods */
+                var form = new Wizard(options, obj);
+                $this.data('Wizard', form);
+
+                form.init();
+
+//                // Initialize the smart-wizard third-party jquery plugin
+//                $(wizard, this).smartWizard({
+//                    selected    : options.start_step - 1,
+//                    errorSteps  : [5],
+//                    onLeaveStep : leaveAStepCallback,
+////                  onFinish    : onFinishCallback
+//                });
+//
+//                // XXX Mark some steps as done !
+//                $(wizard, this).smartWizard('setDone',{stepnum: 1, isdone:true});
+//
+//                function leaveAStepCallback(obj){
+//                    var step_num= obj.attr('rel')-1; // get the current step number
+//                    func = options.validate_step_js[step_num];
+//                    if (func == 'null')
+//                        return true;
+//                    return window[func]();
+//                }
+//
+//                function onFinishCallback(){
+//                    window.location.href('/');
+//                }
+
+
+            }); // this.each
+        } // init
+
+    };
+
+    /***************************************************************************
+     * Wizard object
+     ***************************************************************************/
+
+    /**
+     * \param options (dict) : a dictionary of options
+     * \param obj (jQuery ref) : handler to the wizard plugin
+    */
+    function Wizard(options, obj) {
+
+        /* save a reference to this */
+        var $this = this;
+
+        /* member variables */
+        this.options = options;
+
+        /* methods */
+
+        /**
+         * \brief get a handle on a wizard step by id
+           \param stepIdx (integer) : step identifier (0-based)
+           \returns jQuery selector
+         */
+        this.get_step = function(stepIdx) { return $('.plugin', $(stepIdx.attr('href'))); }
+
+        this.get_plugin = function(step) { return step.data().plugin; }
+
+        this.init1 = function() {
+            $this.curStepIdx = options.selected;
+            $this.steps = $("ul > li > a[href^='#step-']", obj); // Get all anchors in this array
+            $this.contentWidth = 0;
+            //this.loader,msgBox,elmActionBar,elmStepContainer,btNext,btPrevious,btFinish;
+            
+            $this.elmActionBar = $('.actionBar',obj);
+            if($this.elmActionBar.length == 0){
+              $this.elmActionBar = $('<div></div>').addClass("actionBar");                
+            }
+
+            $this.msgBox = $('.msgBox',obj);
+            if($this.msgBox.length == 0){
+              $this.msgBox = $('<div class="msgBox"><div class="content"></div><a href="#" class="close">X</a></div>');
+              $this.elmActionBar.append($this.msgBox);                
+            }
+            
+            $('.close',$this.msgBox).click(function() {
+                $this.msgBox.fadeOut("normal");
+                return false;
+            });
+        } // this.init1
+
+        this.init = function() {
+            this.init1();
+
+            var allDivs =obj.children('div'); //$("div", obj);                
+            obj.children('ul').addClass("anchor");
+            allDivs.addClass("content");
+            // Create Elements
+            loader = $('<div>Loading</div>').addClass("loader");
+            elmActionBar = $('<div></div>').addClass("actionBar");
+            elmStepContainer = $('<div></div>').addClass("stepContainer");
+            btNext = $('<a>'+options.labelNext+'</a>').attr("href","#").addClass("buttonNext");
+            btPrevious = $('<a>'+options.labelPrevious+'</a>').attr("href","#").addClass("buttonPrevious");
+            btFinish = $('<a>'+options.labelFinish+'</a>').attr("href","#").addClass("buttonFinish");
+            
+            // highlight steps with errors
+            if(options.errorSteps && options.errorSteps.length>0){
+              $.each(options.errorSteps, function(i, n){
+                $this.setError(n,true);
+              });
+            }
+
+
+            elmStepContainer.append(allDivs);
+            elmActionBar.append(loader);
+            obj.append(elmStepContainer);
+            obj.append(elmActionBar); 
+            if (options.includeFinishButton) {
+              elmActionBar.append(btFinish);
+            }
+            elmActionBar.append(btNext).append(btPrevious); 
+            contentWidth = elmStepContainer.width();
+
+            $(btNext).click(function() {
+                if($(this).hasClass('buttonDisabled')){
+                  return false;
+                }
+                $this.doForwardProgress();
+                return false;
+            }); 
+            $(btPrevious).click(function() {
+                if($(this).hasClass('buttonDisabled')){
+                  return false;
+                }
+                $this.doBackwardProgress();
+                return false;
+            }); 
+            $(btFinish).click(function() {
+                if(!$(this).hasClass('buttonDisabled')){
+                   if($.isFunction(options.onFinish)) {
+                      if(!options.onFinish.call(this,$(this.steps))){
+                        return false;
+                      }
+                   }else{
+                     var frm = $(obj).parents('form');
+                     if(frm && frm.length){
+                       frm.submit();
+                     }                         
+                   }                      
+                }
+
+                return false;
+            }); 
+            
+            $(this.steps).bind("click", function(e){
+                if(steps.index(this) == $this.curStepIdx){
+                  return false;                    
+                }
+                var nextStepIdx = steps.index(this);
+                var isDone = steps.eq(nextStepIdx).attr("isDone") - 0;
+                if(isDone == 1){
+                  $this.LoadContent(nextStepIdx);                    
+                }
+                return false;
+            }); 
+            
+            // Enable keyboard navigation                 
+            if(options.keyNavigation){
+                $(document).keyup(function(e){
+                    if(e.which==39){ // Right Arrow
+                      $this.doForwardProgress();
+                    }else if(e.which==37){ // Left Arrow
+                      $this.doBackwardProgress();
+                    }
+                });
+            }
+            //  Prepare the steps
+            this.prepareSteps();
+            // Show the first slected step
+            this.LoadContent($this.curStepIdx);                  
+        }
+
+        this.prepareSteps = function() {
+            if (!options.enableAllSteps) {
+                $(this.steps, obj).removeClass("selected").removeClass("done").addClass("disabled"); 
+                $(this.steps, obj).attr("isDone",0);                 
+            } else {
+                $(this.steps, obj).removeClass("selected").removeClass("disabled").addClass("done"); 
+                $(this.steps, obj).attr("isDone",1); 
+            }
+
+            $(this.steps, obj).each(function(i){
+                $($(this).attr("href"), obj).hide();
+                $(this).attr("rel",i+1);
+            });
+        }
+                    
+        this.LoadContent = function(stepIdx) {
+            var selStep = this.steps.eq(stepIdx);
+            var ajaxurl = options.contentURL;
+            var hasContent =  selStep.data('hasContent');
+            stepNum = stepIdx+1;
+            if(ajaxurl && ajaxurl.length>0){
+               if(options.contentCache && hasContent){
+                   this.showStep(stepIdx);                          
+               }else{
+                   $.ajax({
+                    url: ajaxurl,
+                    type: "POST",
+                    data: ({step_number : stepNum}),
+                    dataType: "text",
+                    beforeSend: function(){ loader.show(); },
+                    error: function(){loader.hide();},
+                    success: function(res){ 
+                      loader.hide();       
+                      if(res && res.length>0){  
+                         selStep.data('hasContent',true);            
+                         $($(selStep, obj).attr("href"), obj).html(res);
+                         this.showStep(stepIdx);
+                      }
+                    }
+                  }); 
+              }
+            }else{
+              this.showStep(stepIdx);
+            }
+        } // this.LoadContent
+                    
+        this.showStep = function(stepIdx) 
+        {
+            var selStep = this.steps.eq(stepIdx); 
+            var curStep = this.steps.eq($this.curStepIdx);
+
+
+            if(stepIdx != $this.curStepIdx){
+              if($.isFunction(options.onLeaveStep)) {
+                if(!options.onLeaveStep.call(this,$(curStep))){
+                  return false;
+                }
+              }
+            }     
+            if (options.updateHeight)
+                elmStepContainer.height($($(selStep, obj).attr("href"), obj).outerHeight());               
+            if(options.transitionEffect == 'slide'){
+              $($(curStep, obj).attr("href"), obj).slideUp("fast",function(e){
+                    $($(selStep, obj).attr("href"), obj).slideDown("fast");
+                    $this.curStepIdx =  stepIdx;                        
+                    $this.SetupStep(curStep,selStep);
+                  });
+            } else if(options.transitionEffect == 'fade'){                      
+              $($(curStep, obj).attr("href"), obj).fadeOut("fast",function(e){
+                    $($(selStep, obj).attr("href"), obj).fadeIn("fast");
+                    $this.curStepIdx =  stepIdx;                        
+                    $this.SetupStep(curStep,selStep);                           
+                  });                    
+            } else if(options.transitionEffect == 'slideleft'){
+                var nextElmLeft = 0;
+                var curElementLeft = 0;
+                if(stepIdx > $this.curStepIdx){
+                    nextElmLeft1 = contentWidth + 10;
+                    nextElmLeft2 = 0;
+                    curElementLeft = 0 - $($(curStep, obj).attr("href"), obj).outerWidth();
+                } else {
+                    nextElmLeft1 = 0 - $($(selStep, obj).attr("href"), obj).outerWidth() + 20;
+                    nextElmLeft2 = 0;
+                    curElementLeft = 10 + $($(curStep, obj).attr("href"), obj).outerWidth();
+                }
+                if(stepIdx == $this.curStepIdx){
+                    nextElmLeft1 = $($(selStep, obj).attr("href"), obj).outerWidth() + 20;
+                    nextElmLeft2 = 0;
+                    curElementLeft = 0 - $($(curStep, obj).attr("href"), obj).outerWidth();                           
+                }else{
+                    $($(curStep, obj).attr("href"), obj).animate({left:curElementLeft},"fast",function(e){
+                      $($(curStep, obj).attr("href"), obj).hide();
+                    });                       
+                }
+
+                $($(selStep, obj).attr("href"), obj).css("left",nextElmLeft1);
+                $($(selStep, obj).attr("href"), obj).show();
+                $($(selStep, obj).attr("href"), obj).animate({left:nextElmLeft2},"fast",function(e){
+                  $this.curStepIdx =  stepIdx;                        
+                  $this.SetupStep(curStep,selStep);                      
+                });
+            } else{
+                $($(curStep, obj).attr("href"), obj).hide(); 
+                $($(selStep, obj).attr("href"), obj).show();
+                $this.curStepIdx =  stepIdx;                        
+                $this.SetupStep(curStep,selStep);
+            }
+            return true;
+        } // this.showStep
+                    
+        this.SetupStep = function(curStep,selStep)
+        {
+            $(curStep, obj).removeClass("selected");
+            $(curStep, obj).addClass("done");
+            
+            $(selStep, obj).removeClass("disabled");
+            $(selStep, obj).removeClass("done");
+            $(selStep, obj).addClass("selected");
+            $(selStep, obj).attr("isDone",1);
+            $this.adjustButton();
+            if($.isFunction(options.onShowStep)) {
+               if(!options.onShowStep.call(this,$(selStep))){
+                 return false;
+               }
+            } 
+        }                
+
+        this.validate_callback = function(validated) {
+            /* In case of failure, inform the user of what went wrong */
+            if (!validated) {
+                return;
+            }
+            
+            /* Otherwise, proceed to next step */
+            $this.GoToNextStep();
+        }
+    
+        this.doForwardProgress = function()
+        {
+            var curStep = this.steps.eq($this.curStepIdx);
+            var step = this.get_step(curStep);
+            var plugin = this.get_plugin(step);
+
+            /* If the plugin has a validate method, trigger it and wait for
+             * callback */
+            if (plugin.validate) {
+                /* Trigger validation code and wait for callback */
+                // XXX We should inform the user about progress and disable buttons 
+                plugin.validate(this.validate_callback);
+                return;
+            }
+
+            /* Otherwise, proceed to next step */
+            this.GoToNextStep();
+        }
+        
+        this.GoToNextStep = function()
+        {
+            var nextStepIdx = $this.curStepIdx + 1;
+
+            if(this.steps.length <= nextStepIdx){
+                if (!options.cycleSteps) {
+                    return false;
+                }                  
+                nextStepIdx = 0;
+            }
+            this.LoadContent(nextStepIdx);
+        }
+                    
+        this.doBackwardProgress = function()
+        {
+            var nextStepIdx = $this.curStepIdx-1;
+            if(0 > nextStepIdx){
+              if(!options.cycleSteps){
+                return false;
+              }
+              nextStepIdx = this.steps.length - 1;
+            }
+            this.LoadContent(nextStepIdx);
+        }  
+                    
+        this.adjustButton = function()
+        {
+            if(!options.cycleSteps){                
+              if(0 >= $this.curStepIdx){
+                $(btPrevious).addClass("buttonDisabled");
+              }else{
+                $(btPrevious).removeClass("buttonDisabled");
+              }
+              if(($this.steps.length-1) <= $this.curStepIdx){
+                $(btNext).addClass("buttonDisabled");
+              }else{
+                $(btNext).removeClass("buttonDisabled");
+              }
+            }
+            // Finish Button 
+            if(!$this.steps.hasClass('disabled') || options.enableFinishButton){
+              $(btFinish).removeClass("buttonDisabled");
+            }else{
+              $(btFinish).addClass("buttonDisabled");
+            }                  
+        }
+                    
+        this.showMessage = function(msg)
+        {
+            $('.content',msgBox).html(msg);
+            msgBox.show();
+        }
+                    
+        this.setError = function(stepnum,iserror)
+        {
+            if(iserror){                    
+              $(this.steps.eq(stepnum-1), obj).addClass('error')
+            }else{
+              $(this.steps.eq(stepnum-1), obj).removeClass("error");
+            }                                   
+        }                        
+
+        this.setDone = function(stepnum,isdone)
+        {
+            if(isdone){                    
+              $(this.steps.eq(stepnum-1), obj).removeClass("selected").removeClass("disabled").addClass('done')
+            }else{
+              $(this.steps.eq(stepnum-1), obj).removeClass("done");
+            }                                   
+        }
+    }
+
+    /// KEEP BELOW
+
+    // Default Properties and Events
+    $.fn.Wizard.defaults = {
+        selected: 0,  // Selected Step, 0 = first step   
+        keyNavigation: true, // Enable/Disable key navigation(left and right keys are used if enabled)
+        enableAllSteps: false,
+        updateHeight: true,
+        transitionEffect: 'fade', // Effect on navigation, none/fade/slide/slideleft
+        contentURL:null, // content url, Enables Ajax content loading
+        contentCache:true, // cache step contents, if false content is fetched always from ajax url
+        cycleSteps: false, // cycle step navigation
+        includeFinishButton: true, // whether to show a Finish button
+        enableFinishButton: false, // make finish button enabled always
+        errorSteps:[],    // Array Steps with errors
+        labelNext:'Next',
+        labelPrevious:'Previous',
+        labelFinish:'Finish',          
+        onLeaveStep: null, // triggers when leaving a step
+        onShowStep: null,  // triggers when showing a step
+        onFinish: null  // triggers when Finish button is clicked
+    };    
+
+})( jQuery );
diff --git a/plugins/wizard/static/test.html b/plugins/wizard/static/test.html
new file mode 100644 (file)
index 0000000..7e8ba91
--- /dev/null
@@ -0,0 +1,405 @@
+<table align="center" border="0" cellpadding="0" cellspacing="0">
+
+
+<tr><td> 
+
+
+<!-- Smart Wizard -->
+
+
+               <div id="wizard_test" class="swMain">
+
+
+                       <ul class='anchor'>
+
+
+                               <li><a href="#step-1">
+
+
+                <label class="stepNumber">1</label>
+
+
+                <span class="stepDesc">
+
+
+                   Step 1<br />
+
+
+                   <small>Step 1 description</small>
+
+
+                </span>
+
+
+            </a></li>
+
+
+                               <li><a href="#step-2">
+
+
+                <label class="stepNumber">2</label>
+
+
+                <span class="stepDesc">
+
+
+                   Step 2<br />
+
+
+                   <small>Step 2 description</small>
+
+
+                </span>
+
+
+            </a></li>
+
+
+                               <li><a href="#step-3">
+
+
+                <label class="stepNumber">3</label>
+
+
+                <span class="stepDesc">
+
+
+                   Step 3<br />
+
+
+                   <small>Step 3 description</small>
+
+
+                </span>                   
+
+
+             </a></li>
+
+
+                               <li><a href="#step-4">
+
+
+                <label class="stepNumber">4</label>
+
+
+                <span class="stepDesc">
+
+
+                   Step 4<br />
+
+
+                   <small>Step 4 description</small>
+
+
+                </span>                   
+
+
+            </a></li>
+
+
+                       </ul>
+
+
+                       <div id="step-1">       
+
+
+            <h2 class="StepTitle">Step 1 Content</h2>
+
+
+            <ul type="disk">
+
+
+                                   <li>List 1</li>
+
+
+                                   <li>List 2</li>
+
+
+            </ul>
+
+
+            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+
+
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+
+
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+
+
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+
+
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+
+
+            </p>
+
+
+            <p>
+
+
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+
+
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+
+
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+
+
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+
+
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+
+
+            </p>
+
+
+            <p>
+
+
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+
+
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+
+
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+
+
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+
+
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+
+
+            </p>                               
+
+
+        </div>
+
+
+                       <div id="step-2">
+
+
+            <h2 class="StepTitle">Step 2 Content</h2>  
+
+
+            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+
+
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+
+
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+
+
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+
+
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+
+
+            </p>
+
+
+            <p>
+
+
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+
+
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+
+
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+
+
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+
+
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+
+
+            </p>
+
+
+            <p>
+
+
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+
+
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+
+
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+
+
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+
+
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+
+
+            </p> 
+
+
+            <p>
+
+
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+
+
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+
+
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+
+
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+
+
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+
+
+            </p>          
+
+
+        </div>                      
+
+
+                       <div id="step-3">
+
+
+            <h2 class="StepTitle">Step 3 Content</h2>  
+
+
+            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+
+
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+
+
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+
+
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+
+
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+
+
+            </p>
+
+
+            <p>
+
+
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+
+
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+
+
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+
+
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+
+
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+
+
+            </p>                                                         
+
+
+        </div>
+
+
+                       <div id="step-4">
+
+
+            <h2 class="StepTitle">Step 4 Content</h2>  
+
+
+            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+
+
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+
+
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+
+
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+
+
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+
+
+            </p>
+
+
+            <p>
+
+
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+
+
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+
+
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+
+
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+
+
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+
+
+            </p>
+
+
+            <p>
+
+
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+
+
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+
+
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+
+
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+
+
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+
+
+            </p>                                       
+
+
+        </div>
+
+
+               </div>
+
+
+<!-- End SmartWizard Content -->               
+
+
+               
+
+
+</td></tr>
+
+
+</table>
+
+
diff --git a/plugins/wizard/static/wizard.html b/plugins/wizard/static/wizard.html
new file mode 100644 (file)
index 0000000..3b6c300
--- /dev/null
@@ -0,0 +1,21 @@
+<!-- BEGIN Smart Wizard -->
+<div id="wizard" class="swMain">
+  <ul>
+    {% for son in sons %}
+    <li>
+      <a href="#step-{{forloop.counter}}">
+        <label class="stepNumber">{{forloop.counter}}</label>
+        <span class="stepDesc">Step {{forloop.counter}}<br/><small>{{ son.title }}</small></span>
+      </a>
+    </li>
+    {% endfor %}
+  </ul>
+  
+  {% for son in sons %}
+  <div id="step-{{forloop.counter}}">  
+    <h2 class="StepTitle">{{ son.title }}</h2>
+    {{son.rendered}}
+  </div>
+  {% endfor %}
+</div> <!-- END wizard -->
+<!-- END Smart Wizard -->
diff --git a/portal/__init__.py b/portal/__init__.py
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/portal/accountview.py b/portal/accountview.py
new file mode 100644 (file)
index 0000000..e57dfed
--- /dev/null
@@ -0,0 +1,161 @@
+from portal.templateviews            import LoginRequiredAutoLogoutView
+#
+from manifold.core.query             import Query
+from manifold.manifoldapi            import execute_query
+from portal.actions                  import manifold_update_user
+#
+from myslice.viewutils               import topmenu_items, the_user
+#
+from django.http                     import HttpResponse
+from django.contrib.auth.decorators  import login_required
+import json
+
+# requires login
+class AccountView(LoginRequiredAutoLogoutView):
+    template_name = "my_account.html"
+    
+    def dispatch(self, *args, **kwargs):
+        return super(AccountView, self).dispatch(*args, **kwargs)
+
+
+    def get_context_data(self, **kwargs):
+
+        user_query  = Query().get('local:user').select('config','email')
+        user_details = execute_query(self.request, user_query)
+        
+        # not always found in user_details...
+        config={}
+        for user_detail in user_details:
+            #email = user_detail['email']
+            if user_detail['config']:
+                config = json.loads(user_detail['config'])
+
+        platform_query  = Query().get('local:platform').select('platform_id','platform')
+        account_query  = Query().get('local:account').select('user_id','platform_id','auth_type','config')
+        platform_details = execute_query(self.request, platform_query)
+        account_details = execute_query(self.request, account_query)
+       
+        # initial assignment needed for users having no account  
+        platform_name = ''
+        account_type = ''
+        account_usr_hrn = ''
+        account_pub_key = ''
+        platform_name_list = []
+        account_type_list = []
+        usr_hrn_list = []
+        pub_key_list = []          
+        for account_detail in account_details:
+            for platform_detail in platform_details:
+                if platform_detail['platform_id'] == account_detail['platform_id']:
+                    platform_name = platform_detail['platform']
+                    account_type = account_detail['auth_type']
+                    account_config = json.loads(account_detail['config'])
+                    # a bit more pythonic
+                    account_usr_hrn = account_config.get('user_hrn','N/A')
+                    account_pub_key = account_config.get('user_public_key','N/A')
+                    
+                    platform_name_list.append(platform_name)
+                    account_type_list.append(account_type)
+                    usr_hrn_list.append(account_usr_hrn)
+                    pub_key_list.append(account_pub_key)
+        
+        # combining 4 lists into 1 [to render in the template] 
+        lst = [{'platform_name': t[0], 'account_type': t[1], 'usr_hrn':t[2], 'usr_pubkey':t[3]} 
+               for t in zip(platform_name_list, account_type_list, usr_hrn_list, pub_key_list)]
+        #print "test"
+        #print lst
+
+        context = super(AccountView, self).get_context_data(**kwargs)
+        context['data'] = lst
+        context['person']   = self.request.user
+        context ['firstname'] = config.get('firstname',"?")
+        context ['lastname'] = config.get('lastname',"?")
+        context ['fullname'] = context['firstname'] +' '+ context['lastname']
+        context ['authority'] = config.get('authority',"Unknown Authority")
+        #context['users'] = userlist.render(self.request)
+        
+        # XXX This is repeated in all pages
+        # more general variables expected in the template
+        context['title'] = 'Platforms connected to MySlice'
+        # the menu items on the top
+        context['topmenu_items'] = topmenu_items('My Account', self.request)
+        # so we can sho who is logged
+        context['username'] = the_user(self.request)
+#        context ['firstname'] = config['firstname']
+        #context.update(page.prelude_env())
+        return context
+
+
+@login_required
+#my_acc form value processing
+def account_process(request):
+    user_query  = Query().get('local:user').select('password','config')
+    user_details = execute_query(request, user_query)
+
+    if 'submit_name' in request.POST:
+        edited_first_name =  request.POST['fname']
+        edited_last_name =  request.POST['lname']
+        
+        config={}
+        for user_config in user_details:
+        #email = user_detail['email']
+            if user_config['config']:
+                config = json.loads(user_config['config'])
+                config['firstname'] = edited_first_name
+                config['lastname'] = edited_last_name
+                config['authority'] = config.get('authority','Unknown Authority')
+                updated_config = json.dumps(config)
+        
+        # updating config local:user in manifold       
+        user_params = { 'config': updated_config}
+        manifold_update_user(request,user_params)
+        # this will be depricated, we will show the success msg in same page
+        return HttpResponse('Sucess: First Name and Last Name Updated!')       
+    elif 'submit_pass' in request.POST:
+        edited_password = request.POST['password']
+        
+        for user_pass in user_details:
+            user_pass['password'] = edited_password
+        #updating password in local:user
+        user_params = { 'password': user_pass['password']}
+        manifold_update_user(request,user_params)
+
+        return HttpResponse('Success: Password Changed!!')
+    elif 'generate' in request.POST:
+        # Generate public and private keys using SFA Library
+        from sfa.trust.certificate  import Keypair
+        k = Keypair(create=True)
+        public_key = k.get_pubkey_string()
+        private_key = k.as_pem()
+        private_key = ''.join(private_key.split())
+        public_key = "ssh-rsa " + public_key
+        # Saving to DB
+        keypair = '{"user_public_key":"'+ public_key + '", "user_private_key":"'+ private_key + '"}'
+#        keypair = re.sub("\r", "", keypair)
+#        keypair = re.sub("\n", "\\n", keypair)
+#        #keypair = keypair.rstrip('\r\n')
+#        keypair = ''.join(keypair.split())
+        get_user.keypair = keypair
+        get_user.save()
+        return HttpResponse('Success: New Keypair Generated! %s' % keypair)
+
+    elif 'upload_key' in request.POST:
+        up_file = request.FILES['pubkey']
+        file_content =  up_file.read()
+        file_name = up_file.name
+        file_extension = os.path.splitext(file_name)[1] 
+        allowed_extension =  ['.pub','.txt']
+        if file_extension in allowed_extension and re.search(r'ssh-rsa',file_content):
+            file_content = '{"user_public_key":"'+ file_content +'"}'
+            file_content = re.sub("\r", "", file_content)
+            file_content = re.sub("\n", "\\n",file_content)
+            file_content = ''.join(file_content.split())
+            get_user.keypair = file_content
+            get_user.save()
+            return HttpResponse('Success: Publickey uploaded! Old records overwritten')
+        else:
+            return HttpResponse('Please upload a valid RSA public key [.txt or .pub].')    
+        
+    else:
+        message = 'You submitted an empty form.'
+        return HttpResponse(message)
diff --git a/portal/actions.py b/portal/actions.py
new file mode 100644 (file)
index 0000000..03a0e93
--- /dev/null
@@ -0,0 +1,206 @@
+from django.http                 import HttpResponse
+from manifold.core.query         import Query
+from manifold.manifoldapi        import execute_query
+from portal.models               import PendingUser, PendingSlice
+import json
+
+# Get the list of authorities
+
+def authority_get_pis(request, authority_hrn):
+    query = Query.get('authority').filter_by('authority_hrn', '==', authority_hrn).select('pi_users')
+    results = execute_query(request, query)
+    # NOTE: temporarily commented. Because results is giving empty list. 
+    # Needs more debugging
+    #if not results:
+    #    raise Exception, "Authority not found: %s" % authority_hrn
+    #result, = results
+    #return result['pi_users']
+    return results
+
+def authority_get_pi_emails(request,authority_hrn):
+    user_hrns = authority_get_pis(request,authority_hrn)
+    
+    query = Query.get('user').filter_by('user_hrn', 'included', user_hrns).select('user_email')
+    results = execute_query(request,query)
+    
+    return [result['user_email'] for result in results]
+
+# SFA add record (user, slice)
+
+def sfa_add_user(user_params):
+    # sfi.py add --xrn=fed4fire.upmc.timur_friedman --type=user --key=/root/.sfi/timur.pub --email=timur.friedman@lip6.fr --extra=first_name=Timur --extra=last_name=Friedman --extra=enabled=true
+    # user_params: xrn type key email + first_name last_name enabled
+    query = Query.create('user').set(user_params).select('user_hrn')
+    results = execute_query(query)
+    if not results:
+        raise Exception, "Failed creating SFA user: %s" % user_params['user_hrn']
+    result, = results
+    return result['user_hrn']
+
+def sfa_add_slice(slice_params):
+    pass
+
+# Propose hrn
+
+def manifold_add_user(request, user_params):
+    # user_params: email, password e.g., user_params = {'email':'aa@aa.com','password':'demo'}
+    query = Query.create('local:user').set(user_params).select('email')
+    results = execute_query(request,query)
+    if not results:
+        raise Exception, "Failed creating manifold user: %s" % user_params['email']
+    result, = results
+    return result['email']
+
+def manifold_update_user(request, user_params):
+    # user_params: password, config e.g., 
+    query = Query.update('local:user').filter_by('email', '==', request.user.email).set(user_params).select('email')
+    results = execute_query(request,query)
+    # NOTE: results remains empty and goes to Exception. However, it updates the manifold DB.
+    # That's why I commented the exception part. -- Yasin 
+    #if not results:
+    #    raise Exception, "Failed updating manifold user: %s" % user_params['email']
+    #result, = results
+    return results
+
+def manifold_add_account(request, account_params):
+    query = Query.create('local:account').set(account_params).select(['user', 'platform'])
+    results = execute_query(request,query)
+    if not results:
+        raise Exception, "Failed creating manifold account on platform %s for user: %s" % (account_params['platform'], account_params['user'])
+    result, = results
+    return (result['user'], result['platform'])
+
+def manifold_update_account(request,account_params):
+    # account_params: config
+    query = Query.update('local:account').filter_by('email', '==', request.user.email).set(account_params).select('email')
+    results = execute_query(request,query)
+    # NOTE: results remains empty and goes to Exception. However, it updates the manifold DB.
+    # That's why I commented the exception part. -- Yasin 
+    #if not results:
+    #    raise Exception, "Failed updating manifold account: config %s" % account_params['config']
+    #result, = results
+    return results
+
+
+def make_request_user(user):
+    request = {}
+    request['type'] = 'user'
+    request['id'] = user.id
+    request['timestamp'] = 'TODO' # XXX in DB ?
+    request['authority_hrn'] = user.authority_hrn
+    request['first_name'] = user.first_name
+    request['last_name'] = user.last_name
+    request['email'] = user.email
+    return request
+
+def make_request_slice(slice):
+    request = {}
+    request['type'] = 'slice'
+    request['id'] = slice.id
+    request['timestamp'] = 'TODO' # XXX in DB ?
+    request['authority_hrn'] = slice.authority_hrn
+    request['number_of_nodes'] = slice.number_of_nodes
+    request['type_of_nodes'] = slice.type_of_nodes
+    request['purpose'] = slice.purpose
+    return request
+
+def make_requests(pending_users, pending_slices):
+    print "pending users =", pending_users
+    print "pending slices =", pending_slices
+
+    requests = []
+    for user in pending_users:
+        requests.append(make_request_user(user))
+    for slice in pending_slices:
+        requests.append(make_request_slice(slice))
+    return requests   
+
+def get_request_by_id(ids):
+    sorted_ids = { 'user': [], 'slice': [] }
+    for type__id in ids:
+        type, id = type__id.split('__')
+        sorted_ids[type].append(id)
+        
+    if not ids:
+        pending_users  = PendingUser.objects.all()
+        pending_slices = PendingSlice.objects.all()
+    else:
+        pending_users  = PendingUser.objects.filter(id__in=sorted_ids['user']).all()
+        pending_slices = PendingSlice.objects.filter(id__in=sorted_ids['slice']).all()
+
+    return make_requests(pending_users, pending_slices)
+
+def get_request_by_authority(authority_hrns):
+    if not authority_hrns:
+        pending_users  = PendingUser.objects.all()
+        pending_slices = PendingSlice.objects.all()
+    else:
+        pending_users  = PendingUser.objects.filter(authority_hrn__in=authority_hrns).all()
+        pending_slices = PendingSlice.objects.filter(authority_hrn__in=authority_hrns).all()
+
+    return make_requests(pending_users, pending_slices)
+    
+SFA_USER_KEYS         = ['xrn', 'type', 'key', 'first_name', 'last_name', 'email']
+SFA_SLICE_KEYS        = []
+MANIFOLD_USER_KEYS    = ['email', 'password']
+MANIFOLD_ACCOUNT_KEYS = []
+
+def portal_validate_request(request_ids):
+    status = {}
+
+    if not isinstance(request_ids, list):
+        request_ids = [request_ids]
+
+    requests = get_request_by_id(request_ids)
+    for request in requests:
+        # type, id, timestamp, details, allowed -- MISSING: authority_hrn
+        # CAREFUL about details
+        # user  : first name, last name, email, password, keypair
+        # slice : number of nodes, type of nodes, purpose
+        
+        request_status = {}
+
+        if request['type'] == 'user':
+            try:
+                sfa_user_params = { key: request[key] for key in SFA_USER_KEYS }
+                sfa_user_params['enabled'] = True
+                # XXX # sfa_add_user(sfa_user_params)
+                request_status['SFA user'] = {'status': True }
+            except Exception, e:
+                request_status['SFA user'] = {'status': False, 'description': str(e)}
+
+            try:
+                manifold_user_params = { key: request[key] for key in MANIFOLD_USER_KEYS }
+                # XXX # manifold_add_user(manifold_user_params)
+                request_status['MySlice user'] = {'status': True }
+            except Exception, e:
+                request_status['MySlice user'] = {'status': False, 'description': str(e)}
+
+            # XXX
+            #manifold_account_params = { key: request[key] for key in MANIFOLD_ACCOUNT_KEYS }
+            #manifold_add_account(manifold_account_params)
+            request_status['MySlice testbed accounts'] = {'status': False }
+
+        elif request['type'] == 'slice':
+            try:
+                sfa_slice_params = { key: request[key] for key in SFA_SLICE_KEYS }
+                # XXX # sfa_add_slice(sfa_slice_params)
+                request_status['SFA slice'] = {'status': True }
+            except Exception, e:
+                request_status['SFA slice'] = {'status': False, 'description': str(e)}
+
+        status['%s__%s' % (request['type'], request['id'])] = request_status
+
+    # XXX remove from database succeeded actions
+
+    return status
+
+
+def validate_action(*args, **kwargs):
+    ids = filter(None, kwargs['id'].split('/'))
+    status = portal_validate_request(ids)
+    json_answer = json.dumps(status)
+    return HttpResponse (json_answer, mimetype="application/json")
+
+# Django and ajax
+# http://djangosnippets.org/snippets/942/
diff --git a/portal/contactview.py b/portal/contactview.py
new file mode 100644 (file)
index 0000000..0b459a3
--- /dev/null
@@ -0,0 +1,45 @@
+from django.shortcuts           import render
+
+from django.views.generic       import View
+
+from myslice.viewutils          import topmenu_items, the_user
+
+from portal.forms               import ContactForm
+
+# splitting the 2 functions done here
+# GET is for displaying the empty form
+# POST is to process it once filled - or show the form again if anything is missing
+class ContactView (View):
+    def post (self, request):
+        form = ContactForm(request.POST) # A form bound to the POST data
+        if form.is_valid(): # All validation rules pass
+            # Process the data in form.cleaned_data
+            first_name = form.cleaned_data['first_name']
+            last_name = form.cleaned_data['last_name']
+            affiliation = form.cleaned_data['affiliation']
+            subject = form.cleaned_data['subject']
+            message = form.cleaned_data['message']
+            email = form.cleaned_data['email'] # email of the sender
+            cc_myself = form.cleaned_data['cc_myself']
+
+            #recipients = authority_get_pi_emails(authority_hrn)
+            recipients = ['yasin.upmc@gmail.com', 'thierry.parmentelat@inria.fr', ]
+            if cc_myself:
+                recipients.append(email)
+
+            from django.core.mail import send_mail
+            send_mail("Onelab user %s submitted a query "%email, 
+                      [first_name,last_name,affiliation,subject,message], email, recipients)
+            return render(request,'contact_sent.html') # Redirect after POST
+        else:
+            return self._display (request, form)
+
+    def get (self, request):
+        return self._display (request, ContactForm()) # A fresh unbound form
+        
+    def _display (self, request, form):
+        return render(request, 'contact.html', {
+                'form': form,
+                'topmenu_items': topmenu_items('Contact Us', request),
+                'username': the_user (request)
+                })
diff --git a/portal/dashboardview.py b/portal/dashboardview.py
new file mode 100644 (file)
index 0000000..961b7dc
--- /dev/null
@@ -0,0 +1,65 @@
+from manifold.core.query        import Query
+from unfold.page                import Page
+
+from plugins.lists.simplelist    import SimpleList
+
+from portal.templateviews       import LoginRequiredAutoLogoutView
+
+from myslice.viewutils           import topmenu_items, the_user
+
+#This view requires login 
+class DashboardView (LoginRequiredAutoLogoutView):
+
+    template_name = "dashboard.html"
+    
+    def get_context_data(self, **kwargs):
+        # We might have slices on different registries with different user accounts 
+        # We note that this portal could be specific to a given registry, to which we register users, but i'm not sure that simplifies things
+        # Different registries mean different identities, unless we identify via SFA HRN or have associated the user email to a single hrn
+
+        #messages.info(self.request, 'You have logged in')
+        page = Page(self.request)
+
+        # Slow...
+        #slice_query = Query().get('slice').filter_by('user.user_hrn', 'contains', user_hrn).select('slice_hrn')
+        slice_query = Query().get('user').filter_by('user_hrn', '==', '$user_hrn').select('user_hrn', 'slice.slice_hrn')
+        auth_query  = Query().get('network').select('network_hrn')
+        print "AUTH QUERY =====================", auth_query
+        print "filter", auth_query.filters
+        page.enqueue_query(slice_query)
+        page.enqueue_query(auth_query)
+
+        page.expose_js_metadata()
+        page.expose_queries()
+
+        slicelist = SimpleList(
+            title = None,
+            page  = page,
+            key   = 'slice.slice_hrn',
+            query = slice_query,
+        )
+         
+        authlist = SimpleList(
+            title = None,
+            page  = page,
+            key   = 'network_hrn',
+            query = auth_query,
+        )
+
+        context = super(DashboardView, self).get_context_data(**kwargs)
+        context['person']   = self.request.user
+        context['networks'] = authlist.render(self.request) 
+        context['slices']   = slicelist.render(self.request)
+
+        # XXX This is repeated in all pages
+        # more general variables expected in the template
+        context['title'] = 'Test view that combines various plugins'
+        # the menu items on the top
+        context['topmenu_items'] = topmenu_items('Dashboard', self.request) 
+        # so we can sho who is logged
+        context['username'] = the_user(self.request) 
+
+        context.update(page.prelude_env())
+
+        return context
+
diff --git a/portal/event.py b/portal/event.py
new file mode 100644 (file)
index 0000000..cf95b5e
--- /dev/null
@@ -0,0 +1,135 @@
+# !/usr/bin/python
+# -*-coding: utf-8-*-
+
+import pickle
+import os.path
+import xmlrpclib
+import ast
+import time
+
+class Event:
+    def __init__(self, structure):
+        self.srv=""
+        self.structure = structure
+        self.authType = ""
+        self.server = ""
+        self.methode = ""
+        self.parameters = {}
+        self.return_fields = []
+        
+        self.auth = {}
+        self.print_method=""
+        self.print_options=""
+        self.geo_methode=""
+        self.id=""
+        
+        ##APE###
+        self.raw = ""
+        self.channel = ""
+        #######
+
+
+        
+        
+        self.data = self.make_data()
+        
+        
+    def split(self):
+        args = self.structure.split(";");
+        self.raw = args[0]
+        self.channel = args[1]
+        self.print_method = args[2]
+        self.print_options = ast.literal_eval(args[3])
+       self.authType = args[4]
+       self.server = ast.literal_eval(args[5])
+       self.server = self.server["server"]
+        self.methode = args[6]
+        self.parameters = ast.literal_eval(args[7])
+        self.return_fields = eval(args[8])
+        
+    def makeAuth(self): 
+        if self.authType=="anonymous":
+            self.auth["AuthMethod"] = "anonymous"
+        elif type=="password":
+            self.auth["AuthMethod"] = "password"
+            self.auth["Username"] = "XXX"
+            self.auth["AuthString"] = "XXX"
+        elif self.authType=="session":
+            self.auth["AuthMethod"] = "session"
+            self.auth["session"] = "XXX"
+        elif self.authType=="gpg":
+            self.auth["AuthMethod"] = "gpg"
+            self.auth["name"] = "XXX"
+            self.auth["signature"] = "XXX"
+    
+    def include_geoposition(self, data):
+        list=[]
+        if len(data)<8:
+            for i in data:
+                i["ape_position"] = self.get_geoposition(i) 
+                list.append(i)
+            return list
+        else:
+            try:
+                sites_id = self.srv.GetSites(self.auth,{},["site_id","latitude","longitude"])
+            except :
+                return 45
+            try:
+                for i in data:
+                    for j in sites_id:
+                        if i["site_id"]==j["site_id"]:
+                            try:
+                                pos=[{"latitude": j["latitude"], "longitude": j["longitude"]}]
+                            except:
+                                return 83
+                                                       #
+                            i["ape_position"] = pos
+                            list.append(i)
+                    
+            except:
+                return 82      
+            return list
+        
+    def get_geoposition(self,i):
+        if self.geo_methode == "site_id":
+            id = i["site_id"]
+            try:
+                geo_pos =  self.srv.GetSites(self.auth, {"site_id": id}, ["latitude","longitude"])
+            except:
+                geo_pos = 43
+            return geo_pos
+        else:
+            return 42
+        
+
+    def get_event_list_from_xmlrpc(self):
+        self.srv = xmlrpclib.Server(self.server, allow_none = 1)
+        if self.methode=="GetSites":
+            self.geo_methode="site_id";
+            try :
+                if len(self.return_fields)==0:
+                    return self.srv.GetSites(self.auth, self.parameters) 
+                else :
+                    return self.srv.GetSites(self.auth, self.parameters, self.return_fields)
+            except:
+                    return 0
+        else:
+            return 0
+    
+    def make_data(self):
+        try :
+            self.split()
+            self.makeAuth()
+        except:
+            return 43
+        try : 
+            rototo = self.get_event_list_from_xmlrpc()
+        except: 
+            return 44
+        try:
+
+            return self.include_geoposition(rototo)
+        except:
+             return 47
+        
+        
diff --git a/portal/forms.py b/portal/forms.py
new file mode 100644 (file)
index 0000000..7abc0e4
--- /dev/null
@@ -0,0 +1,154 @@
+# -*- coding: utf-8 -*-
+#
+# portal/forms.py: forms for the portal application
+# This file is part of the Manifold project.
+#
+# Authors:
+#   Jordan Augé <jordan.auge@lip6.fr>
+#   Mohammed-Yasin Rahman <mohammed-yasin.rahman@lip6.fr>
+# Copyright 2013, UPMC Sorbonne Universités / LIP6
+#
+# This program is free software; you can redistribute it and/or modify it under
+# the terms of the GNU General Public License as published by the Free Software
+# Foundation; either version 3, or (at your option) any later version.
+# 
+# This program is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
+# details.
+# 
+# You should have received a copy of the GNU General Public License along with
+# this program; see the file COPYING.  If not, write to the Free Software
+# Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+from django import forms
+from portal.models import PendingUser, PendingSlice
+#from crispy_forms.helper import FormHelper
+#from crispy_forms.layout import Submit
+from django.utils.translation import ugettext_lazy as _
+
+# DEPRECATED # class UserRegisterForm(forms.Form): # Not ModelForm
+# DEPRECATED #     """
+# DEPRECATED #     Form for registering a new user account.
+# DEPRECATED #     
+# DEPRECATED #     Validates that the requested username is not already in use, and
+# DEPRECATED #     requires the password to be entered twice to catch typos.
+# DEPRECATED #     
+# DEPRECATED #     Subclasses should feel free to add any additional validation they
+# DEPRECATED #     need, but should avoid defining a ``save()`` method -- the actual
+# DEPRECATED #     saving of collected user data is delegated to the active
+# DEPRECATED #     registration backend.
+# DEPRECATED # 
+# DEPRECATED #     """
+# DEPRECATED #     required_css_class = 'required'
+# DEPRECATED #     
+# DEPRECATED #     first_name = forms.RegexField(regex=r'^[\w+\s.@+-]+$',
+# DEPRECATED #                                  max_length=30,
+# DEPRECATED #                                  label=_("First name"),
+# DEPRECATED #                                  error_messages={'invalid': _("This value may contain only letters, numbers and @/./+/-/_ characters.")})
+# DEPRECATED #     last_name = forms.RegexField(regex=r'^[\w+\s.@+-]+$',
+# DEPRECATED #                                  max_length=30,
+# DEPRECATED #                                  label=_("Last name"),
+# DEPRECATED #                                  error_messages={'invalid': _("This value may contain only letters, numbers and @/./+/-/_ characters.")})
+# DEPRECATED #     affiliation = forms.RegexField(regex=r'^[\w+\s.@+-]+$',
+# DEPRECATED #                              max_length=30,
+# DEPRECATED #                              label=_("Affiliation"),
+# DEPRECATED #                              error_messages={'invalid': _("This value may contain only letters, numbers and @/./+/-/_ characters.")})
+# DEPRECATED # 
+# DEPRECATED #     email = forms.EmailField(label=_("E-mail"))
+# DEPRECATED #     password1 = forms.CharField(widget=forms.PasswordInput,
+# DEPRECATED #                                 label=_("Password"))
+# DEPRECATED #     password2 = forms.CharField(widget=forms.PasswordInput,
+# DEPRECATED #                                 label=_("Password (again)"))
+# DEPRECATED #     keypair    = forms.CharField( widget=forms.FileInput )
+# DEPRECATED #    
+# DEPRECATED #     #my_keypairs = forms.ChoiceField(widget = forms.Select(), 
+# DEPRECATED #     #             choices = ([('1','generate'), ('2','upload')])) 
+# DEPRECATED #     tos = forms.BooleanField(widget=forms.CheckboxInput,
+# DEPRECATED #                              label=_(u'I have read and agree to the Terms of Service'),
+# DEPRECATED #                              error_messages={'required': _("You must agree to the terms to register")})
+# DEPRECATED # 
+# DEPRECATED # #    def clean_username(self):
+# DEPRECATED # #        """
+# DEPRECATED # #        Validate that the username is alphanumeric and is not already
+# DEPRECATED # #        in use.
+# DEPRECATED # #        
+# DEPRECATED # #        """
+# DEPRECATED # #        existing = User.objects.filter(username__iexact=self.cleaned_data['username'])
+# DEPRECATED # #        if existing.exists():
+# DEPRECATED # #            raise forms.ValidationError(_("A user with that username already exists."))
+# DEPRECATED # #        else:
+# DEPRECATED # #            return self.cleaned_data['username']
+# DEPRECATED # 
+# DEPRECATED #     def clean_email(self):
+# DEPRECATED #         """
+# DEPRECATED #         Validate that the supplied email address is unique for the
+# DEPRECATED #         site.
+# DEPRECATED #         
+# DEPRECATED #         """
+# DEPRECATED #         if PendingUser.objects.filter(email__iexact=self.cleaned_data['email']):
+# DEPRECATED #             raise forms.ValidationError(_("This email address is already in use. Please supply a different email address."))
+# DEPRECATED #         return self.cleaned_data['email']
+# DEPRECATED # 
+# DEPRECATED #     def clean(self):
+# DEPRECATED #         """
+# DEPRECATED #         Verifiy that the values entered into the two password fields
+# DEPRECATED #         match. Note that an error here will end up in
+# DEPRECATED #         ``non_field_errors()`` because it doesn't apply to a single
+# DEPRECATED #         field.
+# DEPRECATED #         
+# DEPRECATED #         """
+# DEPRECATED #         if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
+# DEPRECATED #             if self.cleaned_data['password1'] != self.cleaned_data['password2']:
+# DEPRECATED #                 raise forms.ValidationError(_("The two password fields didn't match."))
+# DEPRECATED #         return self.cleaned_data
+# DEPRECATED # 
+# DEPRECATED #    class Meta:
+# DEPRECATED #        model = PendingUser
+# DEPRECATED #
+# DEPRECATED #class SliceRequestForm(forms.ModelForm):
+# DEPRECATED #    slice_name = forms.CharField( widget=forms.TextInput )
+# DEPRECATED #    class Meta:
+# DEPRECATED #        model = PendingSlice
+# DEPRECATED #
+# DEPRECATED #class RegisterUserStep2Form(forms.ModelForm):
+# DEPRECATED #    class Meta:
+# DEPRECATED #        model = PendingUser
+
+class ContactForm(forms.Form):
+    first_name = forms.CharField()
+    last_name = forms.CharField()
+    affiliation = forms.CharField()
+    subject = forms.CharField(max_length=100)
+    message = forms.CharField(widget=forms.Textarea)
+    email = forms.EmailField()
+    cc_myself = forms.BooleanField(required=False)
+
+class SliceRequestForm(forms.Form):
+    slice_name = forms.CharField()
+    authority_hrn = forms.ChoiceField(choices=[(1, 'un')])
+    number_of_nodes  = forms.DecimalField()
+    type_of_nodes = forms.CharField()
+    purpose = forms.CharField(widget=forms.Textarea)
+    email = forms.EmailField()
+    cc_myself = forms.BooleanField(required=False)
+
+    def __init__(self, *args, **kwargs):
+        initial =  kwargs.get('initial', {})
+        authority_hrn = initial.get('authority_hrn', None)
+
+        # set just the initial value
+        # in the real form needs something like this {'authority_hrn':'a'}
+        # but in this case you want {'authority_hrn':('a', 'letter_a')}
+        if authority_hrn:
+            kwargs['initial']['authority_hrn'] = authority_hrn[0]
+
+        # create the form
+        super(SliceRequestForm, self).__init__(*args, **kwargs)
+
+        # self.fields only exist after, so a double validation is needed
+        if authority_hrn:# and authority_hrn[0] not in (c[0] for c in authority_hrn):
+            # XXX This does not work, the choicefield is not updated...
+            #self.fields['authority_hrn'].choices.extend(authority_hrn)
+            self.fields['authority_hrn'] = forms.ChoiceField( choices=authority_hrn)
+    
diff --git a/portal/homeview.py b/portal/homeview.py
new file mode 100644 (file)
index 0000000..a66cd36
--- /dev/null
@@ -0,0 +1,48 @@
+# this somehow is not used anymore - should it not be ?
+from django.views.generic import View
+from django.core.context_processors import csrf
+from django.http import HttpResponseRedirect
+from django.contrib.auth import authenticate, login, logout
+from django.template import RequestContext
+from django.shortcuts import render_to_response
+
+from myslice.viewutils import topmenu_items, the_user
+from myslice.config import Config
+
+class HomeView (View):
+
+    def default_env (self):
+        return { 
+                 'manifold_url':Config.manifold_url,
+                 }
+
+    def post (self,request):
+        env = self.default_env()
+        username = request.POST.get('username')
+        password = request.POST.get('password')
+        
+        # pass request within the token, so manifold session key can be attached to the request session.
+        token = {'username': username, 'password': password, 'request': request}    
+
+        user = authenticate(token=token)
+        if user is not None:
+            if user.is_active:
+                print "LOGGING IN"
+                login(request, user)
+                return HttpResponseRedirect ('/login-ok')
+            else:
+                env['state'] = "Your account is not active, please contact the site admin."
+                return render_to_response('home-view.html',env, context_instance=RequestContext(request))
+        else:
+            env['state'] = "Your username and/or password were incorrect."
+            return render_to_response('home-view.html',env, context_instance=RequestContext(request))
+
+    # login-ok sets state="Welcome to MySlice" in urls.py
+    def get (self, request, state=None):
+        env = self.default_env()
+        env['username']=the_user(request)
+        env['topmenu_items'] = topmenu_items('', request)
+        if state: env['state'] = state
+        elif not env['username']: env['state'] = "Please sign in"
+        return render_to_response('home-view.html',env, context_instance=RequestContext(request))
+
diff --git a/portal/img/account_validated.png b/portal/img/account_validated.png
new file mode 100644 (file)
index 0000000..12e5e93
Binary files /dev/null and b/portal/img/account_validated.png differ
diff --git a/portal/img/account_validated.png.olf b/portal/img/account_validated.png.olf
new file mode 100644 (file)
index 0000000..d2da4cf
Binary files /dev/null and b/portal/img/account_validated.png.olf differ
diff --git a/portal/migrations/0001_initial.py b/portal/migrations/0001_initial.py
new file mode 100644 (file)
index 0000000..24960f3
--- /dev/null
@@ -0,0 +1,74 @@
+# -*- coding: utf-8 -*-
+import datetime
+from south.db import db
+from south.v2 import SchemaMigration
+from django.db import models
+
+
+class Migration(SchemaMigration):
+
+    def forwards(self, orm):
+        # Adding model 'Institution'
+        db.create_table(u'portal_institution', (
+            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
+            ('name', self.gf('django.db.models.fields.TextField')()),
+        ))
+        db.send_create_signal(u'portal', ['Institution'])
+
+        # Adding model 'PendingUser'
+        db.create_table(u'portal_pendinguser', (
+            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
+            ('first_name', self.gf('django.db.models.fields.TextField')()),
+            ('last_name', self.gf('django.db.models.fields.TextField')()),
+            ('affiliation', self.gf('django.db.models.fields.TextField')()),
+            ('email', self.gf('django.db.models.fields.EmailField')(max_length=75)),
+            ('password', self.gf('django.db.models.fields.TextField')()),
+            ('keypair', self.gf('django.db.models.fields.TextField')()),
+            ('authority_hrn', self.gf('django.db.models.fields.TextField')()),
+        ))
+        db.send_create_signal(u'portal', ['PendingUser'])
+
+        # Adding model 'PendingSlice'
+        db.create_table(u'portal_pendingslice', (
+            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
+            ('slice_name', self.gf('django.db.models.fields.TextField')()),
+        ))
+        db.send_create_signal(u'portal', ['PendingSlice'])
+
+
+    def backwards(self, orm):
+        # Deleting model 'Institution'
+        db.delete_table(u'portal_institution')
+
+        # Deleting model 'PendingUser'
+        db.delete_table(u'portal_pendinguser')
+
+        # Deleting model 'PendingSlice'
+        db.delete_table(u'portal_pendingslice')
+
+
+    models = {
+        u'portal.institution': {
+            'Meta': {'object_name': 'Institution'},
+            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'name': ('django.db.models.fields.TextField', [], {})
+        },
+        u'portal.pendingslice': {
+            'Meta': {'object_name': 'PendingSlice'},
+            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'slice_name': ('django.db.models.fields.TextField', [], {})
+        },
+        u'portal.pendinguser': {
+            'Meta': {'object_name': 'PendingUser'},
+            'affiliation': ('django.db.models.fields.TextField', [], {}),
+            'authority_hrn': ('django.db.models.fields.TextField', [], {}),
+            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}),
+            'first_name': ('django.db.models.fields.TextField', [], {}),
+            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'keypair': ('django.db.models.fields.TextField', [], {}),
+            'last_name': ('django.db.models.fields.TextField', [], {}),
+            'password': ('django.db.models.fields.TextField', [], {})
+        }
+    }
+
+    complete_apps = ['portal']
\ No newline at end of file
diff --git a/portal/migrations/0002_extend_slice.py b/portal/migrations/0002_extend_slice.py
new file mode 100644 (file)
index 0000000..633006a
--- /dev/null
@@ -0,0 +1,47 @@
+# -*- coding: utf-8 -*-
+import datetime
+from south.db import db
+from south.v2 import SchemaMigration
+from django.db import models
+
+
+class Migration(SchemaMigration):
+
+    def forwards(self, orm):
+        # Adding field 'PendingSlice.authority_hrn'
+        db.add_column(u'portal_pendingslice', 'authority_hrn',
+                      self.gf('django.db.models.fields.TextField')(null=True),
+                      keep_default=False)
+
+
+    def backwards(self, orm):
+        # Deleting field 'PendingSlice.authority_hrn'
+        db.delete_column(u'portal_pendingslice', 'authority_hrn')
+
+
+    models = {
+        u'portal.institution': {
+            'Meta': {'object_name': 'Institution'},
+            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'name': ('django.db.models.fields.TextField', [], {})
+        },
+        u'portal.pendingslice': {
+            'Meta': {'object_name': 'PendingSlice'},
+            'authority_hrn': ('django.db.models.fields.TextField', [], {'null': 'True'}),
+            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'slice_name': ('django.db.models.fields.TextField', [], {})
+        },
+        u'portal.pendinguser': {
+            'Meta': {'object_name': 'PendingUser'},
+            'affiliation': ('django.db.models.fields.TextField', [], {}),
+            'authority_hrn': ('django.db.models.fields.TextField', [], {}),
+            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}),
+            'first_name': ('django.db.models.fields.TextField', [], {}),
+            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'keypair': ('django.db.models.fields.TextField', [], {}),
+            'last_name': ('django.db.models.fields.TextField', [], {}),
+            'password': ('django.db.models.fields.TextField', [], {})
+        }
+    }
+
+    complete_apps = ['portal']
\ No newline at end of file
diff --git a/portal/migrations/0003_extend_slice.py b/portal/migrations/0003_extend_slice.py
new file mode 100644 (file)
index 0000000..2437098
--- /dev/null
@@ -0,0 +1,66 @@
+# -*- coding: utf-8 -*-
+import datetime
+from south.db import db
+from south.v2 import SchemaMigration
+from django.db import models
+
+
+class Migration(SchemaMigration):
+
+    def forwards(self, orm):
+        # Adding field 'PendingSlice.number_of_nodes'
+        db.add_column(u'portal_pendingslice', 'number_of_nodes',
+                      self.gf('django.db.models.fields.TextField')(default=0),
+                      keep_default=False)
+
+        # Adding field 'PendingSlice.type_of_nodes'
+        db.add_column(u'portal_pendingslice', 'type_of_nodes',
+                      self.gf('django.db.models.fields.TextField')(default='NA'),
+                      keep_default=False)
+
+        # Adding field 'PendingSlice.purpose'
+        db.add_column(u'portal_pendingslice', 'purpose',
+                      self.gf('django.db.models.fields.TextField')(default='NA'),
+                      keep_default=False)
+
+
+    def backwards(self, orm):
+        # Deleting field 'PendingSlice.number_of_nodes'
+        db.delete_column(u'portal_pendingslice', 'number_of_nodes')
+
+        # Deleting field 'PendingSlice.type_of_nodes'
+        db.delete_column(u'portal_pendingslice', 'type_of_nodes')
+
+        # Deleting field 'PendingSlice.purpose'
+        db.delete_column(u'portal_pendingslice', 'purpose')
+
+
+    models = {
+        u'portal.institution': {
+            'Meta': {'object_name': 'Institution'},
+            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'name': ('django.db.models.fields.TextField', [], {})
+        },
+        u'portal.pendingslice': {
+            'Meta': {'object_name': 'PendingSlice'},
+            'authority_hrn': ('django.db.models.fields.TextField', [], {'null': 'True'}),
+            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'number_of_nodes': ('django.db.models.fields.TextField', [], {'default': '0'}),
+            'purpose': ('django.db.models.fields.TextField', [], {'default': "'NA'"}),
+            'slice_name': ('django.db.models.fields.TextField', [], {}),
+            'type_of_nodes': ('django.db.models.fields.TextField', [], {'default': "'NA'"})
+        },
+        u'portal.pendinguser': {
+            'Meta': {'object_name': 'PendingUser'},
+            'affiliation': ('django.db.models.fields.TextField', [], {}),
+            'authority_hrn': ('django.db.models.fields.TextField', [], {}),
+            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}),
+            'first_name': ('django.db.models.fields.TextField', [], {}),
+            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'keypair': ('django.db.models.fields.TextField', [], {}),
+            'last_name': ('django.db.models.fields.TextField', [], {}),
+            'password': ('django.db.models.fields.TextField', [], {})
+        }
+    }
+
+    complete_apps = ['portal']
\ No newline at end of file
diff --git a/portal/migrations/__init__.py b/portal/migrations/__init__.py
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/portal/models.py b/portal/models.py
new file mode 100644 (file)
index 0000000..06cfa54
--- /dev/null
@@ -0,0 +1,317 @@
+# -*- coding: utf-8 -*-
+#
+# portal/models.py: models for the portal application
+# This file is part of the Manifold project.
+#
+# Authors:
+#   Jordan Augé <jordan.auge@lip6.fr>
+# Copyright 2013, UPMC Sorbonne Universités / LIP6
+#
+# This program is free software; you can redistribute it and/or modify it under
+# the terms of the GNU General Public License as published by the Free Software
+# Foundation; either version 3, or (at your option) any later version.
+# 
+# This program is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
+# details.
+# 
+# You should have received a copy of the GNU General Public License along with
+# this program; see the file COPYING.  If not, write to the Free Software
+# Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+import datetime
+import hashlib
+import random
+import re
+
+from django.conf              import settings
+from django.core.mail         import send_mail
+from django.db                import models
+from django.db                import transaction
+from django.utils.translation import ugettext_lazy as _
+from django.template.loader   import render_to_string
+
+#from django.core.validators import validate_email
+
+try:
+    from django.contrib.auth import get_user_model
+    User = get_user_model()
+except ImportError:
+    from django.contrib.auth.models import User
+
+try:
+    from django.utils.timezone import now as datetime_now
+except ImportError:
+    datetime_now = datetime.datetime.now
+
+SHA1_RE = re.compile('^[a-f0-9]{40}$')
+
+# Create your models here.
+
+class Institution(models.Model):
+    name = models.TextField()
+    # list of associated email domains 
+
+# code borrowed from django-registration
+# https://bitbucket.org/ubernostrum/django-registration/
+
+#DEPRECATED
+#class RegistrationManager(models.Manager):
+#    """
+#    Custom manager for the ``RegistrationProfile`` model.
+#    
+#    The methods defined here provide shortcuts for account creation
+#    and activation (including generation and emailing of activation
+#    keys), and for cleaning out expired inactive accounts.
+#    
+#    """
+#    def activate_user(self, activation_key):
+#        """
+#        Validate an activation key and activate the corresponding
+#        ``User`` if valid.
+#        
+#        If the key is valid and has not expired, return the ``User``
+#        after activating.
+#        
+#        If the key is not valid or has expired, return ``False``.
+#        
+#        If the key is valid but the ``User`` is already active,
+#        return ``False``.
+#        
+#        To prevent reactivation of an account which has been
+#        deactivated by site administrators, the activation key is
+#        reset to the string constant ``RegistrationProfile.ACTIVATED``
+#        after successful activation.
+#
+#        """
+#        # Make sure the key we're trying conforms to the pattern of a
+#        # SHA1 hash; if it doesn't, no point trying to look it up in
+#        # the database.
+#        if SHA1_RE.search(activation_key):
+#            try:
+#                profile = self.get(activation_key=activation_key)
+#            except self.model.DoesNotExist:
+#                return False
+#            if not profile.activation_key_expired():
+#                user = profile.user
+#                user.is_active = True
+#                user.save()
+#                profile.activation_key = self.model.ACTIVATED
+#                profile.save()
+#                return user
+#        return False
+#    
+#    def create_user(self, first_name, last_name, email, password):
+#        pending_user = self.create(first_name=first_name, last_name=last_name, email=email, password=password)
+#        return pending_user
+#
+#    def create_inactive_user(self, first_name, last_name, email, password, site,
+#                             send_email=True):
+#        """
+#        Create a new, inactive ``User``, generate a
+#        ``RegistrationProfile`` and email its activation key to the
+#        ``User``, returning the new ``User``.
+#
+#        By default, an activation email will be sent to the new
+#        user. To disable this, pass ``send_email=False``.
+#        
+#        """
+#        salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
+#        if isinstance(email, unicode):
+#            email = email.encode('utf-8')
+#        activation_key = hashlib.sha1(salt+email).hexdigest()
+#
+#        new_user = PendingUser.objects.create_user(first_name, last_name, email, password)
+#        new_user.is_active = False
+#        new_user.activation_key=activation_key
+#        new_user.save()
+#
+#        # We might not need this
+#        #registration_profile = self.create_profile(new_user)
+#
+#        if send_email:
+#            new_user.send_activation_email(site)
+#            #registration_profile.send_activation_email(site)
+#
+#        return new_user
+#    create_inactive_user = transaction.commit_on_success(create_inactive_user)
+#
+#    def create_profile(self, user):
+#        """
+#        Create a ``RegistrationProfile`` for a given
+#        ``User``, and return the ``RegistrationProfile``.
+#        
+#        The activation key for the ``RegistrationProfile`` will be a
+#        SHA1 hash, generated from a combination of the ``User``'s
+#        username and a random salt.
+#        
+#        """
+#        salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
+#        username = user.username
+#        if isinstance(username, unicode):
+#            username = username.encode('utf-8')
+#        activation_key = hashlib.sha1(salt+username).hexdigest()
+#        return self.create(user=user,
+#                           activation_key=activation_key)
+#        
+#    def delete_expired_users(self):
+#        """
+#        Remove expired instances of ``RegistrationProfile`` and their
+#        associated ``User``s.
+#        
+#        Accounts to be deleted are identified by searching for
+#        instances of ``RegistrationProfile`` with expired activation
+#        keys, and then checking to see if their associated ``User``
+#        instances have the field ``is_active`` set to ``False``; any
+#        ``User`` who is both inactive and has an expired activation
+#        key will be deleted.
+#        
+#        It is recommended that this method be executed regularly as
+#        part of your routine site maintenance; this application
+#        provides a custom management command which will call this
+#        method, accessible as ``manage.py cleanupregistration``.
+#        
+#        Regularly clearing out accounts which have never been
+#        activated serves two useful purposes:
+#        
+#        1. It alleviates the ocasional need to reset a
+#           ``RegistrationProfile`` and/or re-send an activation email
+#           when a user does not receive or does not act upon the
+#           initial activation email; since the account will be
+#           deleted, the user will be able to simply re-register and
+#           receive a new activation key.
+#        
+#        2. It prevents the possibility of a malicious user registering
+#           one or more accounts and never activating them (thus
+#           denying the use of those usernames to anyone else); since
+#           those accounts will be deleted, the usernames will become
+#           available for use again.
+#        
+#        If you have a troublesome ``User`` and wish to disable their
+#        account while keeping it in the database, simply delete the
+#        associated ``RegistrationProfile``; an inactive ``User`` which
+#        does not have an associated ``RegistrationProfile`` will not
+#        be deleted.
+#        
+#        """
+#        for profile in self.all():
+#            try:
+#                if profile.activation_key_expired():
+#                    user = profile.user
+#                    if not user.is_active:
+#                        user.delete()
+#                        profile.delete()
+#            except User.DoesNotExist:
+#                profile.delete()
+#DEPRECATED
+
+class PendingUser(models.Model):
+    # NOTE We might consider migrating the fields to CharField, which would
+    # simplify form creation in forms.py
+    first_name  = models.TextField()
+    last_name   = models.TextField()
+#    affiliation = models.TextField()
+    email       = models.EmailField() #validators=[validate_email])
+    password    = models.TextField()
+    keypair     = models.TextField()
+    # institution
+    authority_hrn = models.TextField()
+    # models.ForeignKey(Institution)
+#DEPRECATED
+#    objects = RegistrationManager()
+#
+#    class Meta:
+#        verbose_name = _('registration profile')
+#        verbose_name_plural = _('registration profiles')
+#    
+#    def __unicode__(self):
+#        return u"Registration information for %s" % self.email
+#
+#    def activation_key_expired(self):
+#        """
+#        Determine whether this ``RegistrationProfile``'s activation
+#        key has expired, returning a boolean -- ``True`` if the key
+#        has expired.
+#        
+#        Key expiration is determined by a two-step process:
+#        
+#        1. If the user has already activated, the key will have been
+#           reset to the string constant ``ACTIVATED``. Re-activating
+#           is not permitted, and so this method returns ``True`` in
+#           this case.
+#
+#        2. Otherwise, the date the user signed up is incremented by
+#           the number of days specified in the setting
+#           ``ACCOUNT_ACTIVATION_DAYS`` (which should be the number of
+#           days after signup during which a user is allowed to
+#           activate their account); if the result is less than or
+#           equal to the current date, the key has expired and this
+#           method returns ``True``.
+#        
+#        """
+#        expiration_date = datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS)
+#        return self.activation_key == self.ACTIVATED or \
+#               (self.user.date_joined + expiration_date <= datetime_now())
+#    activation_key_expired.boolean = True
+#
+#    def send_activation_email(self, site):
+#        """
+#        Send an activation email to the user associated with this
+#        ``RegistrationProfile``.
+#        
+#        The activation email will make use of two templates:
+#
+#        ``user_register_email_subject.txt``
+#            This template will be used for the subject line of the
+#            email. Because it is used as the subject line of an email,
+#            this template's output **must** be only a single line of
+#            text; output longer than one line will be forcibly joined
+#            into only a single line.
+#
+#        ``user_register_email.txt``
+#            This template will be used for the body of the email.
+#
+#        These templates will each receive the following context
+#        variables:
+#
+#        ``activation_key``
+#            The activation key for the new account.
+#
+#        ``expiration_days``
+#            The number of days remaining during which the account may
+#            be activated.
+#
+#        ``site``
+#            An object representing the site on which the user
+#            registered; depending on whether ``django.contrib.sites``
+#            is installed, this may be an instance of either
+#            ``django.contrib.sites.models.Site`` (if the sites
+#            application is installed) or
+#            ``django.contrib.sites.models.RequestSite`` (if
+#            not). Consult the documentation for the Django sites
+#            framework for details regarding these objects' interfaces.
+#
+#        """
+#        ctx_dict = {'activation_key': self.activation_key,
+#                    'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
+#                    'site': site}
+#        subject = render_to_string('user_register_email_subject.txt',
+#                                   ctx_dict)
+#        # Email subject *must not* contain newlines
+#        subject = ''.join(subject.splitlines())
+#
+#        message = render_to_string('user_register_email.txt',
+#                                   ctx_dict)
+#
+#        send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [self.email])
+#DEPRECATED
+
+
+
+class PendingSlice(models.Model):
+    slice_name      = models.TextField()
+    authority_hrn   = models.TextField(null=True)
+    number_of_nodes = models.TextField(default=0)
+    type_of_nodes   = models.TextField(default='NA')
+    purpose         = models.TextField(default='NA')
diff --git a/portal/platformsview.py b/portal/platformsview.py
new file mode 100644 (file)
index 0000000..7c83d94
--- /dev/null
@@ -0,0 +1,61 @@
+from django.views.generic.base   import TemplateView
+
+from manifold.core.query         import Query
+from unfold.page                 import Page
+
+from myslice.viewutils           import topmenu_items, the_user
+
+from plugins.hazelnut            import Hazelnut
+
+# View for platforms
+class PlatformsView(TemplateView):
+    template_name = "platforms.html"
+
+    def get_context_data(self, **kwargs):
+        page = Page(self.request)
+
+        #network_query  = Query().get('local:platform').filter_by('disabled', '==', '0').select('platform','platform_longname','gateway_type')
+        network_query  = Query().get('local:platform').select('platform','platform_longname','gateway_type')
+        page.enqueue_query(network_query)
+
+        page.expose_js_metadata()
+        page.expose_queries()
+        networklist = Hazelnut(
+            page  = page,
+            title = 'List',
+            domid = 'checkboxes',
+            # this is the query at the core of the slice list
+            query = network_query,
+            query_all = network_query,
+            checkboxes = False,
+            datatables_options = {
+            # for now we turn off sorting on the checkboxes columns this way
+            # this of course should be automatic in hazelnut
+            'aoColumns'      : [None, None, None, None, {'bSortable': False}],
+            'iDisplayLength' : 25,
+            'bLengthChange'  : True,
+            },
+        )
+#
+#        networklist = SimpleList(
+#            title = None,
+#            page  = page,
+#            key   = 'platform',
+#            query = network_query,
+#        )
+
+        context = super(PlatformsView, self).get_context_data(**kwargs)
+        context['person']   = self.request.user
+        context['networks'] = networklist.render(self.request)
+
+        # XXX This is repeated in all pages
+        # more general variables expected in the template
+        context['title'] = 'Platforms connected to MySlice'
+        # the menu items on the top
+        context['topmenu_items'] = topmenu_items('Platforms', self.request)
+        # so we can sho who is logged
+        context['username'] = the_user(self.request)
+
+        context.update(page.prelude_env())
+
+        return context
diff --git a/portal/platformview.py b/portal/platformview.py
new file mode 100644 (file)
index 0000000..a432bc1
--- /dev/null
@@ -0,0 +1,70 @@
+from django.views.generic.base   import TemplateView
+
+from manifold.core.query         import Query
+from unfold.page                 import Page
+
+from myslice.viewutils           import topmenu_items, the_user
+
+from plugins.hazelnut            import Hazelnut
+
+# View for 1 platform and its details
+class PlatformView(TemplateView):
+    template_name = "platform.html"
+
+    def get_context_data(self, **kwargs):
+        page = Page(self.request)
+
+        for key, value in kwargs.iteritems():
+            print "%s = %s" % (key, value)       
+            if key == "platformname":
+                platformname=value
+                
+        network_query  = Query().get('local:platform')\
+            .filter_by('platform', '==', platformname)\
+            .select('platform','platform_longname','gateway_type')
+        page.enqueue_query(network_query)
+
+        page.expose_js_metadata()
+        page.expose_queries()
+        networklist = Hazelnut(
+            page  = page,
+            title = 'List',
+            domid = 'checkboxes',
+            # this is the query at the core of the slice list
+            query = network_query,
+            query_all = network_query,
+            checkboxes = False,
+            datatables_options = {
+            # for now we turn off sorting on the checkboxes columns this way
+            # this of course should be automatic in hazelnut
+            'aoColumns'      : [None, None, None, None, {'bSortable': False}],
+            'iDisplayLength' : 25,
+            'bLengthChange'  : True,
+            },
+        )
+#
+#        networklist = SimpleList(
+#            title = None,
+#            page  = page,
+#            key   = 'platform',
+#            query = network_query,
+#        )
+
+        context = super(PlatformView, self).get_context_data(**kwargs)
+        context['person']   = self.request.user
+        context['networks'] = networklist.render(self.request)
+
+        # XXX This is repeated in all pages
+        # more general variables expected in the template
+        context['title'] = 'Platforms connected to MySlice'
+        # the menu items on the top
+        context['topmenu_items'] = topmenu_items('Platforms', self.request)
+        # so we can sho who is logged
+        context['username'] = the_user(self.request)
+
+        context.update(page.prelude_env())
+
+        return context
+
+
+
diff --git a/portal/portalpage.py b/portal/portalpage.py
new file mode 100644 (file)
index 0000000..3cc5ab9
--- /dev/null
@@ -0,0 +1,36 @@
+from django.template import RequestContext
+from django.shortcuts import render_to_response
+
+from unfold.page import Page
+from myslice.viewutils import topmenu_items, the_user
+
+class PortalPage(Page):
+    def __init__(self, request):
+        Page.__init__(self, request)
+        self._content = []
+
+    def __lshift__(self, content):
+        self._content.append(content)
+
+    def render(self):
+        template_env = {}
+        
+        # define 'unfold1_main' to the template engine - the main contents
+        template_env [ 'unfold1_main' ] = "\n".join(self._content)
+
+        # more general variables expected in the template
+        template_env [ 'title' ] = 'Test view that combines various plugins'
+        # the menu items on the top
+        template_env [ 'topmenu_items' ] = topmenu_items('slice', self.request) 
+        # so we can sho who is logged
+        template_env [ 'username' ] = the_user (self.request) 
+
+        # don't forget to run the requests
+        # Jordan: it seems we need this to init plugins js
+        # Issue a "manifold is not defined" error
+        #self.expose_queries ()
+
+        template_env.update(self.prelude_env())
+        result=render_to_response ('view-unfold1.html',template_env,
+                                   context_instance=RequestContext(self.request))
+        return result
diff --git a/portal/registrationview.py b/portal/registrationview.py
new file mode 100644 (file)
index 0000000..e85d44f
--- /dev/null
@@ -0,0 +1,133 @@
+import os.path, re
+
+from django.core.mail            import send_mail
+
+from django.views.generic       import View
+from django.template.loader     import render_to_string
+from django.shortcuts           import render
+
+from myslice.viewutils          import topmenu_items
+
+from manifold.manifoldapi       import execute_query
+from manifold.core.query        import Query
+
+# This is a rough porting from views.py
+# the former function-based view is now made a class
+# we redefine dispatch as it is simple
+# and coincidentally works since we do not need LoginRequiredAutoLogoutView
+# a second stab should redefine post and get instead
+# also this was not thoroughly tested either, might miss some imports
+# to be continued...
+
+class RegistrationView (View):
+
+  def dispatch (self, request):
+
+    errors = []
+
+    authorities_query = Query.get('authority').filter_by('authority_hrn', 'included', ['ple.inria', 'ple.upmc']).select('name', 'authority_hrn')
+    #authorities_query = Query.get('authority').select('authority_hrn')
+    authorities = execute_query(request, authorities_query)
+
+    if request.method == 'POST':
+        # We shall use a form here
+
+        #get_email = PendingUser.objects.get(email)
+        reg_fname = request.POST.get('firstname', '')
+        reg_lname = request.POST.get('lastname', '')
+        #reg_aff = request.POST.get('affiliation','')
+        reg_auth = request.POST.get('authority_hrn', '')
+        reg_email = request.POST.get('email','').lower()
+        
+        #POST value validation  
+        if (re.search(r'^[\w+\s.@+-]+$', reg_fname)==None):
+            errors.append('First Name may contain only letters, numbers, spaces and @/./+/-/_ characters.')
+            #return HttpResponse("Only Letters, Numbers, - and _ allowd in First Name")
+            #return render(request, 'registration_view.html')
+        if (re.search(r'^[\w+\s.@+-]+$', reg_lname) == None):
+            errors.append('Last Name may contain only letters, numbers, spaces and @/./+/-/_ characters.')
+            #return HttpResponse("Only Letters, Numbers, - and _ is allowed in Last name")
+            #return render(request, 'registration_view.html')
+#        if (re.search(r'^[\w+\s.@+-]+$', reg_aff) == None):
+#            errors.append('Affiliation may contain only letters, numbers, spaces and @/./+/-/_ characters.')
+            #return HttpResponse("Only Letters, Numbers and _ is allowed in Affiliation")
+            #return render(request, 'registration_view.html')
+        # XXX validate authority hrn !!
+        if PendingUser.objects.filter(email__iexact=reg_email):
+            errors.append('Email already registered.Please provide a new email address.')
+            #return HttpResponse("Email Already exists")
+            #return render(request, 'registration_view.html')
+        if 'generate' in request.POST['question']:
+            # Generate public and private keys using SFA Library
+            from sfa.trust.certificate  import Keypair
+            k = Keypair(create=True)
+            public_key = k.get_pubkey_string()
+            private_key = k.as_pem()
+            private_key = ''.join(private_key.split())
+            public_key = "ssh-rsa " + public_key
+            # Saving to DB
+            keypair = '{"user_public_key":"'+ public_key + '", "user_private_key":"'+ private_key + '"}'
+#            keypair = re.sub("\r", "", keypair)
+#            keypair = re.sub("\n", "\\n", keypair)
+#            #keypair = keypair.rstrip('\r\n')
+#            keypair = ''.join(keypair.split())
+        else:
+            up_file = request.FILES['user_public_key']
+            file_content =  up_file.read()
+            file_name = up_file.name
+            file_extension = os.path.splitext(file_name)[1]
+            allowed_extension =  ['.pub','.txt']
+            if file_extension in allowed_extension and re.search(r'ssh-rsa',file_content):
+                keypair = '{"user_public_key":"'+ file_content +'"}'
+                keypair = re.sub("\r", "", keypair)
+                keypair = re.sub("\n", "\\n",keypair)
+                keypair = ''.join(keypair.split())
+            else:
+                errors.append('Please upload a valid RSA public key [.txt or .pub].')
+
+        #b = PendingUser(first_name=reg_fname, last_name=reg_lname, affiliation=reg_aff, 
+        #                email=reg_email, password=request.POST['password'], keypair=keypair)
+        #b.save()
+        if not errors:
+            b = PendingUser(
+                first_name=reg_fname, 
+                last_name=reg_lname, 
+                #affiliation=reg_aff,
+                authority_hrn=reg_auth,
+                email=reg_email, 
+                password=request.POST['password'],
+                keypair=keypair
+            )
+            b.save()
+
+            # Send email
+            ctx = {
+                first_name   : reg_fname, 
+                last_name    : reg_lname, 
+                #affiliation  : reg_aff,
+                authority_hrn: reg_auth,
+                email        : reg_email, 
+                keypair      : keypair,
+                cc_myself    : True # form.cleaned_data['cc_myself']
+            }
+
+            recipients = authority_get_pi_emails(authority_hrn)
+            if ctx['cc_myself']:
+                recipients.append(ctx['email'])
+
+            msg = render_to_string('user_request_email.txt', ctx)
+            send_mail("Onelab New User request for %s submitted"%email, msg, email, recipients)
+
+            return render(request, 'user_register_complete.html')
+
+    return render(request, 'registration_view.html',{
+        'topmenu_items': topmenu_items('Register', request),
+        'errors': errors,
+        'firstname': request.POST.get('firstname', ''),
+        'lastname': request.POST.get('lastname', ''),
+        #'affiliation': request.POST.get('affiliation', ''),
+        'authority_hrn': request.POST.get('authority_hrn', ''),
+        'email': request.POST.get('email', ''),
+        'password': request.POST.get('password', ''),           
+        'authorities': authorities
+    })        
diff --git a/portal/signals.py b/portal/signals.py
new file mode 100644 (file)
index 0000000..124f295
--- /dev/null
@@ -0,0 +1,7 @@
+from django.dispatch import Signal
+
+# A new user has registered.
+user_registered = Signal(providing_args=["user", "request"])
+
+# A user has activated his or her account.
+user_activated = Signal(providing_args=["user", "request"])
diff --git a/portal/slicerequestview.py b/portal/slicerequestview.py
new file mode 100644 (file)
index 0000000..4f332e4
--- /dev/null
@@ -0,0 +1,74 @@
+from django.template.loader      import render_to_string
+from django.shortcuts            import render
+from django.core.mail            import send_mail
+
+from manifold.core.query         import Query
+from manifold.manifoldapi        import execute_query
+
+from portal.models               import PendingSlice
+from portal.actions              import authority_get_pi_emails
+from portal.forms                import SliceRequestForm
+from portal.templateviews        import LoginRequiredAutoLogoutView
+from myslice.viewutils           import topmenu_items, the_user
+
+class SliceRequestView (LoginRequiredAutoLogoutView):
+
+    def authority_hrn_initial (self, request):
+        authorities_query = Query.get('authority').filter_by('authority_hrn', 'included', ['ple.inria', 'ple.upmc']).select('name', 'authority_hrn')
+#        authorities_query = Query.get('authority').select('authority_hrn')
+        authorities = execute_query(request, authorities_query)
+        
+        authority_hrn_tuples = [ (authority['authority_hrn'], authority['name'],) for authority in authorities ]
+        return {'authority_hrn': authority_hrn_tuples}
+
+    # because we inherit LoginRequiredAutoLogoutView that is implemented by redefining 'dispatch'
+    # we cannot redefine dispatch here, or we'd lose LoginRequired and AutoLogout behaviours
+    def post (self, request):
+        
+        # The form has been submitted
+        form = SliceRequestForm(request.POST, initial=self.authority_hrn_initial(request)) 
+
+        if form.is_valid():
+            slice_name      = form.cleaned_data['slice_name']
+            authority_hrn   = form.cleaned_data['authority_hrn']
+            number_of_nodes = form.cleaned_data['number_of_nodes']
+            type_of_nodes   = form.cleaned_data['type_of_nodes']
+            purpose         = form.cleaned_data['purpose']
+            
+            s = PendingSlice(
+                slice_name      = slice_name,
+                authority_hrn   = authority_hrn,
+                number_of_nodes = number_of_nodes,
+                type_of_nodes   = type_of_nodes,
+                purpose         = purpose
+            )
+            s.save()
+
+            # All validation rules pass; process data in form.cleaned_data
+            # slice_name, number_of_nodes, type_of_nodes, purpose
+            email = form.cleaned_data['email'] # email of the sender
+            cc_myself = form.cleaned_data['cc_myself']
+
+            # The recipients are the PI of the authority
+            recipients = authority_get_pi_emails(request,authority_hrn)
+            #recipients = ['yasin.upmc@gmail.com','jordan.auge@lip6.fr']
+            if cc_myself:
+                recipients.append(email)
+            msg = render_to_string('slice_request_email.txt', form.cleaned_data)
+            send_mail("Onelab New Slice request form submitted", msg, email, recipients)
+
+            return render(request,'slicereq_recvd.html') # Redirect after POST
+        else:
+            return self._display (request, form)
+
+    def get (self, request):
+        return self._display (request, SliceRequestForm(initial=self.authority_hrn_initial(request)))
+
+    def _display (self, request, form):
+        return render(request, 'slice_request.html', {
+                'form': form,
+                'topmenu_items': topmenu_items('Request a slice', request),
+                'username': the_user (request) 
+                })
+
+
diff --git a/portal/sliceview.py b/portal/sliceview.py
new file mode 100644 (file)
index 0000000..53a77e1
--- /dev/null
@@ -0,0 +1,282 @@
+from django.template                 import RequestContext
+from django.shortcuts                import render_to_response
+
+from portal.templateviews            import LoginRequiredAutoLogoutView
+
+from unfold.page                     import Page
+from manifold.core.query             import Query, AnalyzedQuery
+
+from myslice.viewutils               import topmenu_items, the_user
+
+from plugins.raw.raw                 import Raw
+from plugins.stack.stack             import Stack
+from plugins.tabs.tabs               import Tabs
+from plugins.lists.slicelist         import SliceList
+from plugins.hazelnut                import Hazelnut 
+from plugins.resources_selected      import ResourcesSelected
+from plugins.googlemaps              import GoogleMaps
+from plugins.senslabmap.senslabmap   import SensLabMap
+from plugins.querycode.querycode     import QueryCode
+from plugins.query_editor            import QueryEditor
+from plugins.active_filters          import ActiveFilters
+from plugins.quickfilter.quickfilter import QuickFilter
+from plugins.messages.messages       import Messages
+#from plugins.updater                 import Updater
+
+tmp_default_slice='ple.upmc.myslicedemo'
+
+class SliceView (LoginRequiredAutoLogoutView):
+
+#    def __init__ (self, slicename=None):
+#        self.slicename = slicename or tmp_default_slice
+
+    def get (self,request, slicename=tmp_default_slice):
+    
+        page = Page(request)
+        page.expose_js_metadata()
+    
+        metadata = page.get_metadata()
+        resource_md = metadata.details_by_object('resource')
+        resource_fields = [column['name'] for column in resource_md['column']]
+    
+        user_md = metadata.details_by_object('user')
+        user_fields = ['user_hrn'] # [column['name'] for column in user_md['column']]
+    
+        # TODO The query to run is embedded in the URL
+        main_query = Query.get('slice').filter_by('slice_hrn', '=', slicename)
+        main_query.select(
+                'slice_hrn',
+                'resource.resource_hrn', 'resource.hostname', 'resource.type', 'resource.network_hrn',
+                #'lease.urn',
+                'user.user_hrn',
+                #'application.measurement_point.counter'
+        )
+    
+        query_resource_all = Query.get('resource').select(resource_fields)
+        query_user_all = Query.get('user').select(user_fields)
+    
+        aq = AnalyzedQuery(main_query, metadata=metadata)
+        page.enqueue_query(main_query, analyzed_query=aq)
+        page.enqueue_query(query_resource_all)
+        page.enqueue_query(query_user_all)
+    
+        # Prepare the display according to all metadata
+        # (some parts will be pending, others can be triggered by users).
+        # 
+        # For example slice measurements will not be requested by default...
+    
+        # Create the base layout (Stack)...
+        main_plugin = Stack (
+            page=page,
+            title="Slice !!view for %s"%slicename,
+            sons=[],
+        )
+    
+        # ... responsible for the slice properties...
+    
+    
+        main_plugin.insert (
+            Raw (page=page,togglable=False, toggled=True,html="<h2> Slice page for %s</h2>"%slicename)
+        )
+    
+        main_plugin.insert(
+            Raw (page=page,togglable=False, toggled=True,html='<b>Description:</b> TODO')
+        )
+    
+        sq_plugin = Tabs (
+            page=page,
+            title="Slice view for %s"%slicename,
+            togglable=False,
+            sons=[],
+        )
+    
+    
+        # ... and for the relations
+        # XXX Let's hardcode resources for now
+        sq_resource = aq.subquery('resource')
+        sq_user     = aq.subquery('user')
+        sq_lease    = aq.subquery('lease')
+        sq_measurement = aq.subquery('measurement')
+        
+    
+        ############################################################################
+        # RESOURCES
+        # 
+        # A stack inserted in the subquery tab that will hold all operations
+        # related to resources
+        # 
+        
+        stack_resources = Stack(
+            page = page,
+            title        = 'Resources',
+            sons=[],
+        )
+    
+        resource_query_editor = QueryEditor(
+            page  = page,
+            query = sq_resource,
+        )
+        stack_resources.insert(resource_query_editor)
+    
+        resource_active_filters = ActiveFilters(
+            page  = page,
+            query = sq_resource,
+        )
+        stack_resources.insert(resource_active_filters)
+    
+        # --------------------------------------------------------------------------
+        # Different displays = DataTables + GoogleMaps
+        #
+        tab_resource_plugins = Tabs(
+            page    = page,
+            sons = []
+        )
+    
+        tab_resource_plugins.insert(Hazelnut( 
+            page       = page,
+            title      = 'List',
+            domid      = 'checkboxes',
+            # this is the query at the core of the slice list
+            query      = sq_resource,
+            query_all  = query_resource_all,
+            checkboxes = True,
+            datatables_options = { 
+                # for now we turn off sorting on the checkboxes columns this way
+                # this of course should be automatic in hazelnut
+                'aoColumns'      : [None, None, None, None, {'bSortable': False}],
+                'iDisplayLength' : 25,
+                'bLengthChange'  : True,
+            },
+        ))
+    
+        tab_resource_plugins.insert(GoogleMaps(
+            page       = page,
+            title      = 'Geographic view',
+            domid      = 'gmap',
+            # tab's sons preferably turn this off
+            togglable  = False,
+            query      = sq_resource,
+            query_all  = query_resource_all,
+            checkboxes = True,
+            # center on Paris
+            latitude   = 49.,
+            longitude  = 2.2,
+            zoom       = 3,
+        ))
+    
+        stack_resources.insert(tab_resource_plugins)
+    
+        sq_plugin.insert(stack_resources)
+    
+        ############################################################################
+        # USERS
+        # 
+    
+        tab_users = Tabs(
+            page         = page,
+            title        = 'Users',
+            domid        = 'thetabs2',
+            # activeid   = 'checkboxes',
+            active_domid = 'checkboxes2',
+        )
+        sq_plugin.insert(tab_users)
+    
+        tab_users.insert(Hazelnut( 
+            page        = page,
+            title       = 'List',
+            domid       = 'checkboxes2',
+            # tab's sons preferably turn this off
+            togglable   = False,
+            # this is the query at the core of the slice list
+            query       = sq_user,
+            query_all  = query_user_all,
+            checkboxes  = True,
+            datatables_options = { 
+                # for now we turn off sorting on the checkboxes columns this way
+                # this of course should be automatic in hazelnut
+                'aoColumns'      : [None, None, None, None, {'bSortable': False}],
+                'iDisplayLength' : 25,
+                'bLengthChange'  : True,
+            },
+        ))
+    
+        tab_measurements = Tabs (
+            page         = page,
+            title        = 'Measurements',
+            domid        = 'thetabs3',
+            # activeid   = 'checkboxes',
+            active_domid = 'checkboxes3',
+        )
+        sq_plugin.insert(tab_measurements)
+    
+        tab_measurements.insert(Hazelnut( 
+            page        = page,
+            title       = 'List',
+            domid       = 'checkboxes3',
+            # tab's sons preferably turn this off
+            togglable   = False,
+            # this is the query at the core of the slice list
+            query       = sq_measurement,
+            checkboxes  = True,
+            datatables_options = { 
+                # for now we turn off sorting on the checkboxes columns this way
+                # this of course should be automatic in hazelnut
+                'aoColumns'      : [None, None, None, None, {'bSortable': False}],
+                'iDisplayLength' : 25,
+                'bLengthChange'  : True,
+            },
+        ))
+    
+        main_plugin.insert(sq_plugin)
+    
+        # --------------------------------------------------------------------------
+        # ResourcesSelected
+        #
+        main_plugin.insert(ResourcesSelected(
+            page                = page,
+            title               = 'Pending operations',
+            query               = main_query,
+            togglable           = True,
+        ))
+    
+        main_plugin.insert(Messages(
+            page   = page,
+            title  = "Runtime messages for slice %s"%slicename,
+            domid  = "msgs-pre",
+            levels = "ALL",
+        ))
+    #    main_plugin.insert(Updater(
+    #        page   = page,
+    #        title  = "wont show up as non togglable by default",
+    #        query  = main_query,
+    #        label  = "Update slice",
+    #    ))
+        
+    
+    
+        # variables that will get passed to the view-unfold1.html template
+        template_env = {}
+        
+        # define 'unfold1_main' to the template engine - the main contents
+        template_env [ 'unfold1_main' ] = main_plugin.render(request)
+    
+        # more general variables expected in the template
+        template_env [ 'title' ] = '%(slicename)s'%locals()
+        # the menu items on the top
+        template_env [ 'topmenu_items' ] = topmenu_items('Slice', request) 
+        # so we can sho who is logged
+        template_env [ 'username' ] = the_user (request) 
+    
+        # don't forget to run the requests
+        page.expose_queries ()
+    
+        # xxx create another plugin with the same query and a different layout (with_datatables)
+        # show that it worls as expected, one single api call to backend and 2 refreshed views
+    
+        # the prelude object in page contains a summary of the requirements() for all plugins
+        # define {js,css}_{files,chunks}
+        prelude_env = page.prelude_env()
+        template_env.update(prelude_env)
+        result=render_to_response ('view-unfold1.html',template_env,
+                                   context_instance=RequestContext(request))
+        return result
diff --git a/portal/static/css/dashboard.css b/portal/static/css/dashboard.css
new file mode 100644 (file)
index 0000000..d5b6361
--- /dev/null
@@ -0,0 +1,92 @@
+
+.ms-dashboard {
+    width: 100%;
+}
+
+.ms-dashboard-panel {
+
+}
+
+.ms-dashboard-caption {
+    padding-left: 40px;
+}
+
+.ms-dashboard-caption h2 {
+    position: relative;
+    border-bottom: solid 1px #CCC;
+    width: 100%;
+}
+
+.ms-dashboard-content {
+    padding-left: 40px;
+}
+
+#ms-dashboard-profile>div.ms-dashboard-caption {
+    background: no-repeat url(../img/user.png);
+}   
+
+#ms-dashboard-testbeds>div.ms-dashboard-caption {
+    background: no-repeat url(../img/testbeds.png);
+}   
+
+#ms-dashboard-slices>div.ms-dashboard-caption {
+    background: no-repeat url(../img/experiments.png);
+}   
+
+
+#ms-dashboard-profile {
+    float: left;
+    position: relative;
+    top: 1em;
+    width: 45%;
+    min-height:200px;
+    height:auto !important;
+    height:200px; 
+}
+
+#ms-dashboard-slices {
+    float: left;
+    position: relative;
+    width: 45%;
+    padding-top: 1em;
+}
+
+#ms-dashboard-testbeds {
+    float: right;
+    border: 1px #CCC;
+    padding: 15px;
+    top: 0.5em;
+    width: 45%;
+    min-height:200px;
+    height:auto !important;
+    height:200px; 
+}
+
+li.icn {
+    padding: 0 0 0 0;
+    list-style: none;
+    padding-left: 20px;
+}
+
+img.icn {
+    padding: 0 0 0 0;
+    position: relative;
+    top: 4px;
+    padding-right: 5px;
+}
+
+li.icn-warning {
+    background: no-repeat url(images/button-warning-12x12.png) 0 2px;
+}
+li.icn-play {
+    background: no-repeat url(images/button-play-12x12.png) 0 2px;
+}
+li.icn-stop {
+    background: no-repeat url(images/button-stop-12x12.png) 0 2px;
+}
+li.icn-forbidden {
+    background: no-repeat url(images/button-forbidden-12x12.png) 0 2px;
+}
+li.icn a {
+    text-decoration: none;
+}
diff --git a/portal/static/css/my_account.common.css b/portal/static/css/my_account.common.css
new file mode 100644 (file)
index 0000000..7c59bd8
--- /dev/null
@@ -0,0 +1,243 @@
+/*****************************************************************
+<File Name>
+       common.css
+
+<Started>
+       January 18, 2009
+       
+<Refactored>
+    March 7, 2009
+
+<Author>
+       shawiz@cs.washington.edu
+       Xuanhua (Sean) Ren
+
+<Purpose>
+       Provides the common stylesheet for Seattle Clearinghouse
+
+
+*****************************************************************/
+
+
+/*******************
+* RESET
+********************/
+
+* {
+       margin: 0;
+       padding: 0;
+}
+
+fieldset, img {
+       border: 0;
+}
+
+
+
+/************************
+* GENERAL
+************************/
+
+body {
+       background-color: #fff;
+       /* font-family: "Segoe UI", "Lucida Grande", "Helvetica" , sans-serif;
+       font-size: 12pt; */
+       min-width: 1000px; /* ADDED July 2012 */
+       margin: 0px auto; /* ADDED Aug 14, 2012 */
+}
+
+ol {
+    list-style-position: inside;
+}
+
+a {
+    text-decoration: none;
+    color: #0066FF;
+}
+
+code {
+    font-family: "Consolas", "Lucida Console", "Monaco", "Courier New";
+}
+
+.odd {
+    background-color: #fff;
+}
+
+.even {
+    background-color: #eee;
+}
+
+
+/************************
+* LAYOUT
+************************/
+
+/***** Header *****/
+
+#header {
+    width: 900px;   /* Edited Aug 14, 2012  prev width:70%*/
+    margin: 30px auto 20px auto;
+}
+
+#header #logo {
+    font-size: 42px;  /* Edited Sept 28, 2012  prev value :36pt*/
+    font-weight: bold;
+}
+
+#header #logo a {
+    color: #000;
+}
+
+#header #caption {
+    margin-left: 20px;
+    font-size: 13.3333px; 
+}
+
+#header #caption a {
+       color: #0066FF;
+}
+
+
+/***** Navigator *****/
+
+#navigator {
+    border-bottom: 3px solid #222;
+    width: 100%;
+    margin: 0 auto;  /* ADDED Aug 14, 2012 */
+}
+
+#tabs {
+    margin: 0 auto; 
+    width: 900px; /* Editied Aug 14, 2012 prev width: 70% */
+}
+
+#meta {
+    float: right;
+    font-size: 13pt;
+    margin: 5px 0;
+}
+
+#meta a.logout {
+    color: red;
+}
+
+#tabs table {
+    border-collapse: collapse;
+    border-spacing: 0;
+}
+
+#tabs table tr td {
+   padding: 5px 15px;
+   font-size: 14pt;
+   border-top: 1px solid #222;
+   border-right: 2px solid #222;
+   border-left: 2px solid #222;
+}
+
+#tabs table tr td a {
+    color: #000;
+}
+
+#tabs table tr td.active {
+    background-color: #222;
+    color: #fff;
+}
+
+#tabs table tr td.active a {
+    color: #fff;
+}
+
+
+/***** Main *****/
+
+#main {
+    width: 100%;
+    height: 400px;
+    padding: 40px 0;
+    background-image: url(../images/bg.png);
+    background-repeat: repeat-x;
+}
+
+#middle {
+   margin: 0 auto;
+   width: 900px;  /* Edited Aug 14, 2012 prev width:70% */
+  padding-bottom: 60px;
+}
+
+
+/***** Notifications *****/
+
+.warning {
+       border: 1px solid red;
+       margin: 20px 60px;
+       padding: 10px 20px;
+       color: red;
+       background-color: #f2dbdb;
+       text-align: center;
+}
+.warning2 {
+       border: 1px solid red;
+       margin: 20px 60px;
+       padding: 10px 20px;
+       color: red;
+       background-color: #f2dbdb;
+       text-align: center;
+}
+.message {
+       border: 1px solid green;
+          max-width : 682px;  /* ADDED July 2012 */
+       margin: 20px 60px;
+       padding: 10px 20px;
+       color: green;
+       font-weight: bold;
+       background-color: #CCFFCC;
+       text-align: center;
+}
+
+.tooltip {
+       background-color: #efefef;
+       color: #333;
+       font-size: 10pt;
+       padding: 3px;
+    border: solid 1px #333;
+       z-index:100;
+}
+
+ul.errorlist li {
+       color: red;
+       font-weight: normal;
+       font-size: 10pt;
+       background-color: #f2dbdb;
+    padding: 3px;
+    list-style-position: inside;
+}
+
+#learn-about-seattle {
+   /* max-width : 70%;*/
+    text-align : center;
+    background-color : #ded;
+    border : 1px solid #0a0;
+    padding : 1em;
+    margin-top : 1em;
+    margin-bottom : 1em;
+    font-size : 1.3em;
+}
+
+
+
+
+table.mytable { border-collapse: collapse; border: 1px solid #839E99; 
+background: #f1f8ee; font: .9em/1.2em Georgia, "Times New Roman", Times, serif; color: #033;table-layout:fixed; }
+.mytable caption { font-size: 1.3em; font-weight: bold; text-align: left; padding: 1em 4px; }
+.mytable td, th { padding: 3px 3px .75em 3px; line-height: 1.3em; }
+.mytable th { background: #839E99; color: #fff; font-weight: bold; text-align: left; padding-right: .5em; vertical-align: top; align="center" style="width:15%;word-wrap: break-word" }
+.mytable thead th { background: #2C5755; text-align: center; }
+.mytable thead td {style="width:15%;word-wrap: break-word"}
+.mytable .odd td { background: #DBE6DD; style="width:15%;word-wrap: break-word"}
+.mytable .odd th { background: #6E8D88; }
+.mytable td a, td a:link { color: #325C91; }
+.mytable td a:visited { color: #466C8E; }
+.mytable td a:hover, td a:focus { color: #1E4C94; }
+.mytable th a, td a:active { color: #fff; }
+.mytable tfoot th, tfoot td { background: #2C5755; color: #fff; }
+.mytable th + td { padding-left: .5em; }
diff --git a/portal/static/css/my_account.profile.css b/portal/static/css/my_account.profile.css
new file mode 100644 (file)
index 0000000..b6e1b20
--- /dev/null
@@ -0,0 +1,173 @@
+
+
+/******************************
+* STYLE FOR PROFILE PAGE
+*******************************/
+
+h1 { 
+  font-size: 1.8em; 
+  border-bottom: 1px solid #bbb; 
+  width: 70%; 
+  min-width: 688px;
+}
+
+#info {
+  background-color : #ded;
+  border : 1px solid #0a0;
+  padding : 1em;
+  margin-bottom : 1em;
+}
+
+#error_msg {
+  background-color : #f2dbdb;
+  border : 1px solid red;
+  padding : 1em;
+  margin-bottom : 1em;
+}
+
+ul.errorlist li {
+       font-size: 12pt;
+  padding: 0px;
+}
+
+/* ADDED July 27, 2012 to fix the table collapsing on itself when the browser is below a certain size */
+table.profile {  
+  border-collapse: collapse;
+  border-spacing: 0;
+  width: 70%;
+  min-width: 703px; 
+}
+
+table.profile tr td.key {
+  text-align: right;
+  height: 30px;
+       font-size: 16px;
+  font-weight: bold;
+  width: 160px;
+}
+
+table.profile tr td.value {
+  padding-left: 20px;   
+    min-width: 500px; /* ADDED July 27, 2012 */
+}
+
+table.profile button { 
+  width: 80px;
+  vertical-align: middle;
+  float: right;
+  margin-right: 15px;
+}
+
+table.profile span.hide_this{ 
+       display: inline;
+       display: none;
+}
+
+table.profile form{ 
+       display:inline;
+}
+
+#download {
+  float: right;
+  border: 2px solid #666;
+  background-color: #fff;
+  padding: 10px;
+  margin-right: 0px;
+  text-align: center;
+  font-weight: bold;
+}
+
+#download a img {
+  display: block;
+  width: 150px;
+}
+
+#download a {
+  color: black;
+}
+
+#download_pubkey_form {
+  display : inline;    
+}
+/* ADDED(everything below) Aug 14, 2012 */
+#generate_api {
+  width: 175px;
+}
+
+#change_key form {
+  display: inline;
+  width: 688px; 
+}
+
+#generate_keypair {
+  position:relative;
+  width: 175px;
+  float: right;
+  margin-right: 15px;
+
+}
+#edit_password table {
+ display:inline;
+ margin: auto;
+  border-collapse: collapse;
+  border-spacing: 0;
+  padding-left: 5px;
+  width: 100%;
+}
+
+#edit_password td.field {
+  padding-left: 5px;
+
+}
+
+.wide_button {
+  width: 175px;
+}
+
+.api_cell {
+  color:red;
+}
+
+.api_cell:hover {
+  text-decoration: underline; 
+}
+
+img.help {
+  position: relative;
+  float: left;
+  left: 162px;
+  display: none;
+  /* when a negative margin is applied to right or bottom
+  it allows the element to overlap
+  */
+  margin-bottom: -50px;
+}
+
+#id_email {
+  width: 200px; 
+}
+
+#aff_list {
+  width: 200px;
+}
+#name {
+  width: 200px;
+}
+
+/*Added Sept 2012 to fix long api keys creating a new line*/
+#api_key {
+  color: red;
+  font-family: courier;
+}
+
+#up_arrow {
+  height: 36px;
+  width: 36px;
+  float: right;
+  position: relative;
+  margin-right: 132px;
+  /*when a negative margin is applied to right or bottom
+  it allows the element to overlap
+  */
+  margin-bottom:-50px;
+}
diff --git a/portal/static/css/onelab.css b/portal/static/css/onelab.css
new file mode 100644 (file)
index 0000000..70418c0
--- /dev/null
@@ -0,0 +1,16 @@
+/* Thierry's Note 
+it seems to me that most of the stuff here is not register-related,
+but general-purpose settings for an openlab style
+I've started to move over such stuff in onelab.css
+feel free to add to this collection
+*/
+
+/* these in general are div.well */
+div.onelab-title{
+    margin-top:20px;
+    margin-bottom:20px;
+    text-align: center;
+    border: 1px solid #61210B;
+    background-color: #e0f0f0;
+}
+
diff --git a/portal/static/css/registration.css b/portal/static/css/registration.css
new file mode 100644 (file)
index 0000000..958f26f
--- /dev/null
@@ -0,0 +1,100 @@
+/* Thierry's Note 
+it seems to me that most of the stuff here is not register-related,
+but general-purpose settings for an openlab style
+I've started to move over such stuff in onelab.css
+feel free to add to this collection
+*/
+#commentForm {
+    margin:0 auto;
+    width:800px;
+    padding:10px;
+    font-size:12pt;
+    overflow:auto;
+}    
+#register {
+    text-align: center;
+}
+/*
+input {
+    height: 22px;
+    width: 200px;
+}
+*/
+/*
+    border:2px solid #456879;
+    font-size: 10px; 
+*/
+label { 
+    float: left;
+    font-weight: bold;
+    text-align: right;
+    margin-right: 20px;
+    width: 200px;
+    display: inline-block;
+        
+}
+label.error { 
+    float: none;
+    color: red;
+    padding-left: .5em;
+    vertical-align:
+    top; 
+    font-size: 12px; 
+}
+
+p {
+    color:#666666;
+/* border-bottom:1px solid #B7DDF2; */
+/* font-size:10px; */
+/* margin-bottom:20px; */
+/* padding-bottom:10px; */
+}
+
+
+
+legend {
+    position: relative;
+    top: -2px;
+    background: cornsilk;
+    padding: 10px 100px;
+    border: 2px groove threedface;
+    border-top: none;
+    box-shadow: inset 0 -5px 5px rgba(0,0,0,.2);
+    text-shadow: 1px 1px 2px rgba(0,0,0,.3);
+    font-weight: bold;
+    font-size: 25px;
+    margin-left: 90px;
+}
+
+textarea:focus, input:focus {
+    border: 2px solid #900;
+}
+
+.required {
+    font-size:12pt;
+}
+/* 
+   .submit {
+    text-align: center;
+    margin-top: 15px;
+    margin-left: 250px;
+}
+*/
+.field {
+    padding:10px;
+}
+.hint {
+    display:none;
+}
+.field:hover .hint {
+    position: absolute;
+    display: block;
+    margin: -30px 0 0 455px;
+    color: #FFFFFF;
+    padding: 7px 10px;
+    background: rgba(0, 0, 0, 0.6);
+    -moz-border-radius: 7px;
+    -webkit-border-radius: 7px;
+    border-radius: 7px;
+}
diff --git a/portal/static/css/validate_pending.css b/portal/static/css/validate_pending.css
new file mode 100644 (file)
index 0000000..d0a7a56
--- /dev/null
@@ -0,0 +1,61 @@
+.portal_validate_request {
+       background-repeat: no-repeat;
+       background-position: 10px center;
+       padding: 10px;
+       position:relative;
+}
+
+.portal_validate_request.slice {
+       background-image: url(../img/slice-icon.png);
+}
+
+.portal_validate_request.user {
+       background-image: url(../img/user-icon.png);
+}
+
+.portal_validate_request.authority {
+       background-image: url(../img/authority-icon.png);
+}
+
+.portal_validate_request .type {
+       position: relative;
+       left: 2%;
+}
+
+.portal_validate_request .id {
+       position: absolute;
+       left: 5%;
+}
+
+.portal_validate_request .authority {
+       position: absolute;
+       left: 7%;
+}
+
+.portal_validate_request .details {
+       position: absolute;
+       left: 15%;
+}
+
+.portal_validate_request .timestamp {
+       position: absolute;
+       left: 50%;
+}
+
+.portal_validate_request .status {
+       position: absolute;
+       left: 65%;
+}
+
+.portal_validate_request input {
+       position: absolute;
+       left: 60%;
+}
+
+.portal_validate_request.even {
+       background-color: white;
+}
+
+.portal_validate_request.odd {
+       background-color: azure;
+}
diff --git a/portal/static/img/authority-icon.png b/portal/static/img/authority-icon.png
new file mode 100644 (file)
index 0000000..bde603a
Binary files /dev/null and b/portal/static/img/authority-icon.png differ
diff --git a/portal/static/img/experiments.png b/portal/static/img/experiments.png
new file mode 100644 (file)
index 0000000..cd97086
Binary files /dev/null and b/portal/static/img/experiments.png differ
diff --git a/portal/static/img/ques_icon.png b/portal/static/img/ques_icon.png
new file mode 100644 (file)
index 0000000..4113c12
Binary files /dev/null and b/portal/static/img/ques_icon.png differ
diff --git a/portal/static/img/resource-icon.png b/portal/static/img/resource-icon.png
new file mode 100644 (file)
index 0000000..919bdbe
Binary files /dev/null and b/portal/static/img/resource-icon.png differ
diff --git a/portal/static/img/slice-icon.png b/portal/static/img/slice-icon.png
new file mode 100644 (file)
index 0000000..9e8747b
Binary files /dev/null and b/portal/static/img/slice-icon.png differ
diff --git a/portal/static/img/testbeds.png b/portal/static/img/testbeds.png
new file mode 100644 (file)
index 0000000..ed9aa0e
Binary files /dev/null and b/portal/static/img/testbeds.png differ
diff --git a/portal/static/img/user-icon.png b/portal/static/img/user-icon.png
new file mode 100644 (file)
index 0000000..88f6bf8
Binary files /dev/null and b/portal/static/img/user-icon.png differ
diff --git a/portal/static/img/user.png b/portal/static/img/user.png
new file mode 100644 (file)
index 0000000..fa72bdd
Binary files /dev/null and b/portal/static/img/user.png differ
diff --git a/portal/static/jquery.validate.js b/portal/static/jquery.validate.js
new file mode 100644 (file)
index 0000000..51eb2ef
--- /dev/null
@@ -0,0 +1,1222 @@
+/**
+ * jQuery Validation Plugin 1.11.0pre
+ *
+ * http://bassistance.de/jquery-plugins/jquery-plugin-validation/
+ * http://docs.jquery.com/Plugins/Validation
+ *
+ * Copyright 2013 Jörn Zaefferer
+ * Released under the MIT license:
+ *   http://www.opensource.org/licenses/mit-license.php
+ */
+
+(function($) {
+
+$.extend($.fn, {
+    // http://docs.jquery.com/Plugins/Validation/validate
+    validate: function( options ) {
+
+        // if nothing is selected, return nothing; can't chain anyway
+        if ( !this.length ) {
+            if ( options && options.debug && window.console ) {
+                console.warn( "Nothing selected, can't validate, returning nothing." );
+            }
+            return;
+        }
+
+        // check if a validator for this form was already created
+        var validator = $.data( this[0], "validator" );
+        if ( validator ) {
+            return validator;
+        }
+
+        // Add novalidate tag if HTML5.
+        this.attr( "novalidate", "novalidate" );
+
+        validator = new $.validator( options, this[0] );
+        $.data( this[0], "validator", validator );
+
+        if ( validator.settings.onsubmit ) {
+
+            this.validateDelegate( ":submit", "click", function( event ) {
+                if ( validator.settings.submitHandler ) {
+                    validator.submitButton = event.target;
+                }
+                // allow suppressing validation by adding a cancel class to the submit button
+                if ( $(event.target).hasClass("cancel") ) {
+                    validator.cancelSubmit = true;
+                }
+            });
+
+            // validate the form on submit
+            this.submit( function( event ) {
+                if ( validator.settings.debug ) {
+                    // prevent form submit to be able to see console output
+                    event.preventDefault();
+                }
+                function handle() {
+                    var hidden;
+                    if ( validator.settings.submitHandler ) {
+                        if ( validator.submitButton ) {
+                            // insert a hidden input as a replacement for the missing submit button
+                            hidden = $("<input type='hidden'/>").attr("name", validator.submitButton.name).val(validator.submitButton.value).appendTo(validator.currentForm);
+                        }
+                        validator.settings.submitHandler.call( validator, validator.currentForm, event );
+                        if ( validator.submitButton ) {
+                            // and clean up afterwards; thanks to no-block-scope, hidden can be referenced
+                            hidden.remove();
+                        }
+                        return false;
+                    }
+                    return true;
+                }
+
+                // prevent submit for invalid forms or custom submit handlers
+                if ( validator.cancelSubmit ) {
+                    validator.cancelSubmit = false;
+                    return handle();
+                }
+                if ( validator.form() ) {
+                    if ( validator.pendingRequest ) {
+                        validator.formSubmitted = true;
+                        return false;
+                    }
+                    return handle();
+                } else {
+                    validator.focusInvalid();
+                    return false;
+                }
+            });
+        }
+
+        return validator;
+    },
+    // http://docs.jquery.com/Plugins/Validation/valid
+    valid: function() {
+        if ( $(this[0]).is("form")) {
+            return this.validate().form();
+        } else {
+            var valid = true;
+            var validator = $(this[0].form).validate();
+            this.each(function() {
+                valid &= validator.element(this);
+            });
+            return valid;
+        }
+    },
+    // attributes: space seperated list of attributes to retrieve and remove
+    removeAttrs: function( attributes ) {
+        var result = {},
+            $element = this;
+        $.each(attributes.split(/\s/), function( index, value ) {
+            result[value] = $element.attr(value);
+            $element.removeAttr(value);
+        });
+        return result;
+    },
+    // http://docs.jquery.com/Plugins/Validation/rules
+    rules: function( command, argument ) {
+        var element = this[0];
+
+        if ( command ) {
+            var settings = $.data(element.form, "validator").settings;
+            var staticRules = settings.rules;
+            var existingRules = $.validator.staticRules(element);
+            switch(command) {
+            case "add":
+                $.extend(existingRules, $.validator.normalizeRule(argument));
+                staticRules[element.name] = existingRules;
+                if ( argument.messages ) {
+                    settings.messages[element.name] = $.extend( settings.messages[element.name], argument.messages );
+                }
+                break;
+            case "remove":
+                if ( !argument ) {
+                    delete staticRules[element.name];
+                    return existingRules;
+                }
+                var filtered = {};
+                $.each(argument.split(/\s/), function( index, method ) {
+                    filtered[method] = existingRules[method];
+                    delete existingRules[method];
+                });
+                return filtered;
+            }
+        }
+
+        var data = $.validator.normalizeRules(
+        $.extend(
+            {},
+            $.validator.classRules(element),
+            $.validator.attributeRules(element),
+            $.validator.dataRules(element),
+            $.validator.staticRules(element)
+        ), element);
+
+        // make sure required is at front
+        if ( data.required ) {
+            var param = data.required;
+            delete data.required;
+            data = $.extend({required: param}, data);
+        }
+
+        return data;
+    }
+});
+
+// Custom selectors
+$.extend($.expr[":"], {
+    // http://docs.jquery.com/Plugins/Validation/blank
+    blank: function( a ) { return !$.trim("" + a.value); },
+    // http://docs.jquery.com/Plugins/Validation/filled
+    filled: function( a ) { return !!$.trim("" + a.value); },
+    // http://docs.jquery.com/Plugins/Validation/unchecked
+    unchecked: function( a ) { return !a.checked; }
+});
+
+// constructor for validator
+$.validator = function( options, form ) {
+    this.settings = $.extend( true, {}, $.validator.defaults, options );
+    this.currentForm = form;
+    this.init();
+};
+
+$.validator.format = function( source, params ) {
+    if ( arguments.length === 1 ) {
+        return function() {
+            var args = $.makeArray(arguments);
+            args.unshift(source);
+            return $.validator.format.apply( this, args );
+        };
+    }
+    if ( arguments.length > 2 && params.constructor !== Array  ) {
+        params = $.makeArray(arguments).slice(1);
+    }
+    if ( params.constructor !== Array ) {
+        params = [ params ];
+    }
+    $.each(params, function( i, n ) {
+        source = source.replace( new RegExp("\\{" + i + "\\}", "g"), function() {
+            return n;
+        });
+    });
+    return source;
+};
+
+$.extend($.validator, {
+
+    defaults: {
+        messages: {},
+        groups: {},
+        rules: {},
+        errorClass: "error",
+        validClass: "valid",
+        errorElement: "label",
+        focusInvalid: true,
+        errorContainer: $([]),
+        errorLabelContainer: $([]),
+        onsubmit: true,
+        ignore: ":hidden",
+        ignoreTitle: false,
+        onfocusin: function( element, event ) {
+            this.lastActive = element;
+
+            // hide error label and remove error class on focus if enabled
+            if ( this.settings.focusCleanup && !this.blockFocusCleanup ) {
+                if ( this.settings.unhighlight ) {
+                    this.settings.unhighlight.call( this, element, this.settings.errorClass, this.settings.validClass );
+                }
+                this.addWrapper(this.errorsFor(element)).hide();
+            }
+        },
+        onfocusout: function( element, event ) {
+            if ( !this.checkable(element) && (element.name in this.submitted || !this.optional(element)) ) {
+                this.element(element);
+            }
+        },
+        onkeyup: function( element, event ) {
+            if ( event.which === 9 && this.elementValue(element) === "" ) {
+                return;
+            } else if ( element.name in this.submitted || element === this.lastElement ) {
+                this.element(element);
+            }
+        },
+        onclick: function( element, event ) {
+            // click on selects, radiobuttons and checkboxes
+            if ( element.name in this.submitted ) {
+                this.element(element);
+            }
+            // or option elements, check parent select in that case
+            else if ( element.parentNode.name in this.submitted ) {
+                this.element(element.parentNode);
+            }
+        },
+        highlight: function( element, errorClass, validClass ) {
+            if ( element.type === "radio" ) {
+                this.findByName(element.name).addClass(errorClass).removeClass(validClass);
+            } else {
+                $(element).addClass(errorClass).removeClass(validClass);
+            }
+        },
+        unhighlight: function( element, errorClass, validClass ) {
+            if ( element.type === "radio" ) {
+                this.findByName(element.name).removeClass(errorClass).addClass(validClass);
+            } else {
+                $(element).removeClass(errorClass).addClass(validClass);
+            }
+        }
+    },
+
+    // http://docs.jquery.com/Plugins/Validation/Validator/setDefaults
+    setDefaults: function( settings ) {
+        $.extend( $.validator.defaults, settings );
+    },
+
+    messages: {
+        required: "This field is required.",
+        remote: "Please fix this field.",
+        email: "Please enter a valid email address.",
+        url: "Please enter a valid URL.",
+        date: "Please enter a valid date.",
+        dateISO: "Please enter a valid date (ISO).",
+        number: "Please enter a valid number.",
+        digits: "Please enter only digits.",
+        creditcard: "Please enter a valid credit card number.",
+        equalTo: "Please enter the same value again.",
+        maxlength: $.validator.format("Please enter no more than {0} characters."),
+        minlength: $.validator.format("Please enter at least {0} characters."),
+        rangelength: $.validator.format("Please enter a value between {0} and {1} characters long."),
+        range: $.validator.format("Please enter a value between {0} and {1}."),
+        max: $.validator.format("Please enter a value less than or equal to {0}."),
+        min: $.validator.format("Please enter a value greater than or equal to {0}.")
+    },
+
+    autoCreateRanges: false,
+
+    prototype: {
+
+        init: function() {
+            this.labelContainer = $(this.settings.errorLabelContainer);
+            this.errorContext = this.labelContainer.length && this.labelContainer || $(this.currentForm);
+            this.containers = $(this.settings.errorContainer).add( this.settings.errorLabelContainer );
+            this.submitted = {};
+            this.valueCache = {};
+            this.pendingRequest = 0;
+            this.pending = {};
+            this.invalid = {};
+            this.reset();
+
+            var groups = (this.groups = {});
+            $.each(this.settings.groups, function( key, value ) {
+                if ( typeof value === "string" ) {
+                    value = value.split(/\s/);
+                }
+                $.each(value, function( index, name ) {
+                    groups[name] = key;
+                });
+            });
+            var rules = this.settings.rules;
+            $.each(rules, function( key, value ) {
+                rules[key] = $.validator.normalizeRule(value);
+            });
+
+            function delegate(event) {
+                var validator = $.data(this[0].form, "validator"),
+                    eventType = "on" + event.type.replace(/^validate/, "");
+                if ( validator.settings[eventType] ) {
+                    validator.settings[eventType].call(validator, this[0], event);
+                }
+            }
+            $(this.currentForm)
+                .validateDelegate(":text, [type='password'], [type='file'], select, textarea, " +
+                    "[type='number'], [type='search'] ,[type='tel'], [type='url'], " +
+                    "[type='email'], [type='datetime'], [type='date'], [type='month'], " +
+                    "[type='week'], [type='time'], [type='datetime-local'], " +
+                    "[type='range'], [type='color'] ",
+                    "focusin focusout keyup", delegate)
+                .validateDelegate("[type='radio'], [type='checkbox'], select, option", "click", delegate);
+
+            if ( this.settings.invalidHandler ) {
+                $(this.currentForm).bind("invalid-form.validate", this.settings.invalidHandler);
+            }
+        },
+
+        // http://docs.jquery.com/Plugins/Validation/Validator/form
+        form: function() {
+            this.checkForm();
+            $.extend(this.submitted, this.errorMap);
+            this.invalid = $.extend({}, this.errorMap);
+            if ( !this.valid() ) {
+                $(this.currentForm).triggerHandler("invalid-form", [this]);
+            }
+            this.showErrors();
+            return this.valid();
+        },
+
+        checkForm: function() {
+            this.prepareForm();
+            for ( var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++ ) {
+                this.check( elements[i] );
+            }
+            return this.valid();
+        },
+
+        // http://docs.jquery.com/Plugins/Validation/Validator/element
+        element: function( element ) {
+            element = this.validationTargetFor( this.clean( element ) );
+            this.lastElement = element;
+            this.prepareElement( element );
+            this.currentElements = $(element);
+            var result = this.check( element ) !== false;
+            if ( result ) {
+                delete this.invalid[element.name];
+            } else {
+                this.invalid[element.name] = true;
+            }
+            if ( !this.numberOfInvalids() ) {
+                // Hide error containers on last error
+                this.toHide = this.toHide.add( this.containers );
+            }
+            this.showErrors();
+            return result;
+        },
+
+        // http://docs.jquery.com/Plugins/Validation/Validator/showErrors
+        showErrors: function( errors ) {
+            if ( errors ) {
+                // add items to error list and map
+                $.extend( this.errorMap, errors );
+                this.errorList = [];
+                for ( var name in errors ) {
+                    this.errorList.push({
+                        message: errors[name],
+                        element: this.findByName(name)[0]
+                    });
+                }
+                // remove items from success list
+                this.successList = $.grep( this.successList, function( element ) {
+                    return !(element.name in errors);
+                });
+            }
+            if ( this.settings.showErrors ) {
+                this.settings.showErrors.call( this, this.errorMap, this.errorList );
+            } else {
+                this.defaultShowErrors();
+            }
+        },
+
+        // http://docs.jquery.com/Plugins/Validation/Validator/resetForm
+        resetForm: function() {
+            if ( $.fn.resetForm ) {
+                $(this.currentForm).resetForm();
+            }
+            this.submitted = {};
+            this.lastElement = null;
+            this.prepareForm();
+            this.hideErrors();
+            this.elements().removeClass( this.settings.errorClass ).removeData( "previousValue" );
+        },
+
+        numberOfInvalids: function() {
+            return this.objectLength(this.invalid);
+        },
+
+        objectLength: function( obj ) {
+            var count = 0;
+            for ( var i in obj ) {
+                count++;
+            }
+            return count;
+        },
+
+        hideErrors: function() {
+            this.addWrapper( this.toHide ).hide();
+        },
+
+        valid: function() {
+            return this.size() === 0;
+        },
+
+        size: function() {
+            return this.errorList.length;
+        },
+
+        focusInvalid: function() {
+            if ( this.settings.focusInvalid ) {
+                try {
+                    $(this.findLastActive() || this.errorList.length && this.errorList[0].element || [])
+                    .filter(":visible")
+                    .focus()
+                    // manually trigger focusin event; without it, focusin handler isn't called, findLastActive won't have anything to find
+                    .trigger("focusin");
+                } catch(e) {
+                    // ignore IE throwing errors when focusing hidden elements
+                }
+            }
+        },
+
+        findLastActive: function() {
+            var lastActive = this.lastActive;
+            return lastActive && $.grep(this.errorList, function( n ) {
+                return n.element.name === lastActive.name;
+            }).length === 1 && lastActive;
+        },
+
+        elements: function() {
+            var validator = this,
+                rulesCache = {};
+
+            // select all valid inputs inside the form (no submit or reset buttons)
+            return $(this.currentForm)
+            .find("input, select, textarea")
+            .not(":submit, :reset, :image, [disabled]")
+            .not( this.settings.ignore )
+            .filter(function() {
+                if ( !this.name ) {
+                    if ( window.console ) {
+                        console.error( "%o has no name assigned", this );
+                    }
+                    throw new Error( "Failed to validate, found an element with no name assigned. See console for element reference." );
+                }
+
+                // select only the first element for each name, and only those with rules specified
+                if ( this.name in rulesCache || !validator.objectLength($(this).rules()) ) {
+                    return false;
+                }
+
+                rulesCache[this.name] = true;
+                return true;
+            });
+        },
+
+        clean: function( selector ) {
+            return $(selector)[0];
+        },
+
+        errors: function() {
+            var errorClass = this.settings.errorClass.replace(" ", ".");
+            return $(this.settings.errorElement + "." + errorClass, this.errorContext);
+        },
+
+        reset: function() {
+            this.successList = [];
+            this.errorList = [];
+            this.errorMap = {};
+            this.toShow = $([]);
+            this.toHide = $([]);
+            this.currentElements = $([]);
+        },
+
+        prepareForm: function() {
+            this.reset();
+            this.toHide = this.errors().add( this.containers );
+        },
+
+        prepareElement: function( element ) {
+            this.reset();
+            this.toHide = this.errorsFor(element);
+        },
+
+        elementValue: function( element ) {
+            var type = $(element).attr("type"),
+                val = $(element).val();
+
+            if ( type === "radio" || type === "checkbox" ) {
+                return $("input[name='" + $(element).attr("name") + "']:checked").val();
+            }
+
+            if ( typeof val === "string" ) {
+                return val.replace(/\r/g, "");
+            }
+            return val;
+        },
+
+        check: function( element ) {
+            element = this.validationTargetFor( this.clean( element ) );
+
+            var rules = $(element).rules();
+            var dependencyMismatch = false;
+            var val = this.elementValue(element);
+            var result;
+
+            for (var method in rules ) {
+                var rule = { method: method, parameters: rules[method] };
+                try {
+
+                    result = $.validator.methods[method].call( this, val, element, rule.parameters );
+
+                    // if a method indicates that the field is optional and therefore valid,
+                    // don't mark it as valid when there are no other rules
+                    if ( result === "dependency-mismatch" ) {
+                        dependencyMismatch = true;
+                        continue;
+                    }
+                    dependencyMismatch = false;
+
+                    if ( result === "pending" ) {
+                        this.toHide = this.toHide.not( this.errorsFor(element) );
+                        return;
+                    }
+
+                    if ( !result ) {
+                        this.formatAndAdd( element, rule );
+                        return false;
+                    }
+                } catch(e) {
+                    if ( this.settings.debug && window.console ) {
+                        console.log( "Exception occured when checking element " + element.id + ", check the '" + rule.method + "' method.", e );
+                    }
+                    throw e;
+                }
+            }
+            if ( dependencyMismatch ) {
+                return;
+            }
+            if ( this.objectLength(rules) ) {
+                this.successList.push(element);
+            }
+            return true;
+        },
+
+        // return the custom message for the given element and validation method
+        // specified in the element's HTML5 data attribute
+        customDataMessage: function( element, method ) {
+            return $(element).data("msg-" + method.toLowerCase()) || (element.attributes && $(element).attr("data-msg-" + method.toLowerCase()));
+        },
+
+        // return the custom message for the given element name and validation method
+        customMessage: function( name, method ) {
+            var m = this.settings.messages[name];
+            return m && (m.constructor === String ? m : m[method]);
+        },
+
+        // return the first defined argument, allowing empty strings
+        findDefined: function() {
+            for(var i = 0; i < arguments.length; i++) {
+                if ( arguments[i] !== undefined ) {
+                    return arguments[i];
+                }
+            }
+            return undefined;
+        },
+
+        defaultMessage: function( element, method ) {
+            return this.findDefined(
+                this.customMessage( element.name, method ),
+                this.customDataMessage( element, method ),
+                // title is never undefined, so handle empty string as undefined
+                !this.settings.ignoreTitle && element.title || undefined,
+                $.validator.messages[method],
+                "<strong>Warning: No message defined for " + element.name + "</strong>"
+            );
+        },
+
+        formatAndAdd: function( element, rule ) {
+            var message = this.defaultMessage( element, rule.method ),
+                theregex = /\$?\{(\d+)\}/g;
+            if ( typeof message === "function" ) {
+                message = message.call(this, rule.parameters, element);
+            } else if (theregex.test(message)) {
+                message = $.validator.format(message.replace(theregex, "{$1}"), rule.parameters);
+            }
+            this.errorList.push({
+                message: message,
+                element: element
+            });
+
+            this.errorMap[element.name] = message;
+            this.submitted[element.name] = message;
+        },
+
+        addWrapper: function( toToggle ) {
+            if ( this.settings.wrapper ) {
+                toToggle = toToggle.add( toToggle.parent( this.settings.wrapper ) );
+            }
+            return toToggle;
+        },
+
+        defaultShowErrors: function() {
+            var i, elements;
+            for ( i = 0; this.errorList[i]; i++ ) {
+                var error = this.errorList[i];
+                if ( this.settings.highlight ) {
+                    this.settings.highlight.call( this, error.element, this.settings.errorClass, this.settings.validClass );
+                }
+                this.showLabel( error.element, error.message );
+            }
+            if ( this.errorList.length ) {
+                this.toShow = this.toShow.add( this.containers );
+            }
+            if ( this.settings.success ) {
+                for ( i = 0; this.successList[i]; i++ ) {
+                    this.showLabel( this.successList[i] );
+                }
+            }
+            if ( this.settings.unhighlight ) {
+                for ( i = 0, elements = this.validElements(); elements[i]; i++ ) {
+                    this.settings.unhighlight.call( this, elements[i], this.settings.errorClass, this.settings.validClass );
+                }
+            }
+            this.toHide = this.toHide.not( this.toShow );
+            this.hideErrors();
+            this.addWrapper( this.toShow ).show();
+        },
+
+        validElements: function() {
+            return this.currentElements.not(this.invalidElements());
+        },
+
+        invalidElements: function() {
+            return $(this.errorList).map(function() {
+                return this.element;
+            });
+        },
+
+        showLabel: function( element, message ) {
+            var label = this.errorsFor( element );
+            if ( label.length ) {
+                // refresh error/success class
+                label.removeClass( this.settings.validClass ).addClass( this.settings.errorClass );
+
+                // check if we have a generated label, replace the message then
+                if ( label.attr("generated") ) {
+                    label.html(message);
+                }
+            } else {
+                // create label
+                label = $("<" + this.settings.errorElement + "/>")
+                    .attr({"for":  this.idOrName(element), generated: true})
+                    .addClass(this.settings.errorClass)
+                    .html(message || "");
+                if ( this.settings.wrapper ) {
+                    // make sure the element is visible, even in IE
+                    // actually showing the wrapped element is handled elsewhere
+                    label = label.hide().show().wrap("<" + this.settings.wrapper + "/>").parent();
+                }
+                if ( !this.labelContainer.append(label).length ) {
+                    if ( this.settings.errorPlacement ) {
+                        this.settings.errorPlacement(label, $(element) );
+                    } else {
+                        label.insertAfter(element);
+                    }
+                }
+            }
+            if ( !message && this.settings.success ) {
+                label.text("");
+                if ( typeof this.settings.success === "string" ) {
+                    label.addClass( this.settings.success );
+                } else {
+                    this.settings.success( label, element );
+                }
+            }
+            this.toShow = this.toShow.add(label);
+        },
+
+        errorsFor: function( element ) {
+            var name = this.idOrName(element);
+            return this.errors().filter(function() {
+                return $(this).attr("for") === name;
+            });
+        },
+
+        idOrName: function( element ) {
+            return this.groups[element.name] || (this.checkable(element) ? element.name : element.id || element.name);
+        },
+
+        validationTargetFor: function( element ) {
+            // if radio/checkbox, validate first element in group instead
+            if ( this.checkable(element) ) {
+                element = this.findByName( element.name ).not(this.settings.ignore)[0];
+            }
+            return element;
+        },
+
+        checkable: function( element ) {
+            return (/radio|checkbox/i).test(element.type);
+        },
+
+        findByName: function( name ) {
+            return $(this.currentForm).find("[name='" + name + "']");
+        },
+
+        getLength: function( value, element ) {
+            switch( element.nodeName.toLowerCase() ) {
+            case "select":
+                return $("option:selected", element).length;
+            case "input":
+                if ( this.checkable( element) ) {
+                    return this.findByName(element.name).filter(":checked").length;
+                }
+            }
+            return value.length;
+        },
+
+        depend: function( param, element ) {
+            return this.dependTypes[typeof param] ? this.dependTypes[typeof param](param, element) : true;
+        },
+
+        dependTypes: {
+            "boolean": function( param, element ) {
+                return param;
+            },
+            "string": function( param, element ) {
+                return !!$(param, element.form).length;
+            },
+            "function": function( param, element ) {
+                return param(element);
+            }
+        },
+
+        optional: function( element ) {
+            var val = this.elementValue(element);
+            return !$.validator.methods.required.call(this, val, element) && "dependency-mismatch";
+        },
+
+        startRequest: function( element ) {
+            if ( !this.pending[element.name] ) {
+                this.pendingRequest++;
+                this.pending[element.name] = true;
+            }
+        },
+
+        stopRequest: function( element, valid ) {
+            this.pendingRequest--;
+            // sometimes synchronization fails, make sure pendingRequest is never < 0
+            if ( this.pendingRequest < 0 ) {
+                this.pendingRequest = 0;
+            }
+            delete this.pending[element.name];
+            if ( valid && this.pendingRequest === 0 && this.formSubmitted && this.form() ) {
+                $(this.currentForm).submit();
+                this.formSubmitted = false;
+            } else if (!valid && this.pendingRequest === 0 && this.formSubmitted) {
+                $(this.currentForm).triggerHandler("invalid-form", [this]);
+                this.formSubmitted = false;
+            }
+        },
+
+        previousValue: function( element ) {
+            return $.data(element, "previousValue") || $.data(element, "previousValue", {
+                old: null,
+                valid: true,
+                message: this.defaultMessage( element, "remote" )
+            });
+        }
+
+    },
+
+    classRuleSettings: {
+        required: {required: true},
+        email: {email: true},
+        url: {url: true},
+        date: {date: true},
+        dateISO: {dateISO: true},
+        number: {number: true},
+        digits: {digits: true},
+        creditcard: {creditcard: true}
+    },
+
+    addClassRules: function( className, rules ) {
+        if ( className.constructor === String ) {
+            this.classRuleSettings[className] = rules;
+        } else {
+            $.extend(this.classRuleSettings, className);
+        }
+    },
+
+    classRules: function( element ) {
+        var rules = {};
+        var classes = $(element).attr("class");
+        if ( classes ) {
+            $.each(classes.split(" "), function() {
+                if ( this in $.validator.classRuleSettings ) {
+                    $.extend(rules, $.validator.classRuleSettings[this]);
+                }
+            });
+        }
+        return rules;
+    },
+
+    attributeRules: function( element ) {
+        var rules = {};
+        var $element = $(element);
+
+        for (var method in $.validator.methods) {
+            var value;
+
+            // support for <input required> in both html5 and older browsers
+            if ( method === "required" ) {
+                value = $element.get(0).getAttribute(method);
+                // Some browsers return an empty string for the required attribute
+                // and non-HTML5 browsers might have required="" markup
+                if ( value === "" ) {
+                    value = true;
+                }
+                // force non-HTML5 browsers to return bool
+                value = !!value;
+            } else {
+                value = $element.attr(method);
+            }
+
+            if ( value ) {
+                rules[method] = value;
+            } else if ( $element[0].getAttribute("type") === method ) {
+                rules[method] = true;
+            }
+        }
+
+        // maxlength may be returned as -1, 2147483647 (IE) and 524288 (safari) for text inputs
+        if ( rules.maxlength && /-1|2147483647|524288/.test(rules.maxlength) ) {
+            delete rules.maxlength;
+        }
+
+        return rules;
+    },
+
+    dataRules: function( element ) {
+        var method, value,
+            rules = {}, $element = $(element);
+        for (method in $.validator.methods) {
+            value = $element.data("rule-" + method.toLowerCase());
+            if ( value !== undefined ) {
+                rules[method] = value;
+            }
+        }
+        return rules;
+    },
+
+    staticRules: function( element ) {
+        var rules = {};
+        var validator = $.data(element.form, "validator");
+        if ( validator.settings.rules ) {
+            rules = $.validator.normalizeRule(validator.settings.rules[element.name]) || {};
+        }
+        return rules;
+    },
+
+    normalizeRules: function( rules, element ) {
+        // handle dependency check
+        $.each(rules, function( prop, val ) {
+            // ignore rule when param is explicitly false, eg. required:false
+            if ( val === false ) {
+                delete rules[prop];
+                return;
+            }
+            if ( val.param || val.depends ) {
+                var keepRule = true;
+                switch (typeof val.depends) {
+                case "string":
+                    keepRule = !!$(val.depends, element.form).length;
+                    break;
+                case "function":
+                    keepRule = val.depends.call(element, element);
+                    break;
+                }
+                if ( keepRule ) {
+                    rules[prop] = val.param !== undefined ? val.param : true;
+                } else {
+                    delete rules[prop];
+                }
+            }
+        });
+
+        // evaluate parameters
+        $.each(rules, function( rule, parameter ) {
+            rules[rule] = $.isFunction(parameter) ? parameter(element) : parameter;
+        });
+
+        // clean number parameters
+        $.each(["minlength", "maxlength", "min", "max"], function() {
+            if ( rules[this] ) {
+                rules[this] = Number(rules[this]);
+            }
+        });
+        $.each(["rangelength", "range"], function() {
+            var parts;
+            if ( rules[this] ) {
+                if ( $.isArray(rules[this]) ) {
+                    rules[this] = [Number(rules[this][0]), Number(rules[this][1])];
+                } else if ( typeof rules[this] === "string" ) {
+                    parts = rules[this].split(/[\s,]+/);
+                    rules[this] = [Number(parts[0]), Number(parts[1])];
+                }
+            }
+        });
+
+        if ( $.validator.autoCreateRanges ) {
+            // auto-create ranges
+            if ( rules.min && rules.max ) {
+                rules.range = [rules.min, rules.max];
+                delete rules.min;
+                delete rules.max;
+            }
+            if ( rules.minlength && rules.maxlength ) {
+                rules.rangelength = [rules.minlength, rules.maxlength];
+                delete rules.minlength;
+                delete rules.maxlength;
+            }
+        }
+
+        return rules;
+    },
+
+    // Converts a simple string to a {string: true} rule, e.g., "required" to {required:true}
+    normalizeRule: function( data ) {
+        if ( typeof data === "string" ) {
+            var transformed = {};
+            $.each(data.split(/\s/), function() {
+                transformed[this] = true;
+            });
+            data = transformed;
+        }
+        return data;
+    },
+
+    // http://docs.jquery.com/Plugins/Validation/Validator/addMethod
+    addMethod: function( name, method, message ) {
+        $.validator.methods[name] = method;
+        $.validator.messages[name] = message !== undefined ? message : $.validator.messages[name];
+        if ( method.length < 3 ) {
+            $.validator.addClassRules(name, $.validator.normalizeRule(name));
+        }
+    },
+
+    methods: {
+
+        // http://docs.jquery.com/Plugins/Validation/Methods/required
+        required: function( value, element, param ) {
+            // check if dependency is met
+            if ( !this.depend(param, element) ) {
+                return "dependency-mismatch";
+            }
+            if ( element.nodeName.toLowerCase() === "select" ) {
+                // could be an array for select-multiple or a string, both are fine this way
+                var val = $(element).val();
+                return val && val.length > 0;
+            }
+            if ( this.checkable(element) ) {
+                return this.getLength(value, element) > 0;
+            }
+            return $.trim(value).length > 0;
+        },
+
+        // http://docs.jquery.com/Plugins/Validation/Methods/remote
+        remote: function( value, element, param ) {
+            if ( this.optional(element) ) {
+                return "dependency-mismatch";
+            }
+
+            var previous = this.previousValue(element);
+            if (!this.settings.messages[element.name] ) {
+                this.settings.messages[element.name] = {};
+            }
+            previous.originalMessage = this.settings.messages[element.name].remote;
+            this.settings.messages[element.name].remote = previous.message;
+
+            param = typeof param === "string" && {url:param} || param;
+
+            if ( previous.old === value ) {
+                return previous.valid;
+            }
+
+            previous.old = value;
+            var validator = this;
+            this.startRequest(element);
+            var data = {};
+            data[element.name] = value;
+            $.ajax($.extend(true, {
+                url: param,
+                mode: "abort",
+                port: "validate" + element.name,
+                dataType: "json",
+                data: data,
+                success: function( response ) {
+                    validator.settings.messages[element.name].remote = previous.originalMessage;
+                    var valid = response === true || response === "true";
+                    if ( valid ) {
+                        var submitted = validator.formSubmitted;
+                        validator.prepareElement(element);
+                        validator.formSubmitted = submitted;
+                        validator.successList.push(element);
+                        delete validator.invalid[element.name];
+                        validator.showErrors();
+                    } else {
+                        var errors = {};
+                        var message = response || validator.defaultMessage( element, "remote" );
+                        errors[element.name] = previous.message = $.isFunction(message) ? message(value) : message;
+                        validator.invalid[element.name] = true;
+                        validator.showErrors(errors);
+                    }
+                    previous.valid = valid;
+                    validator.stopRequest(element, valid);
+                }
+            }, param));
+            return "pending";
+        },
+
+        // http://docs.jquery.com/Plugins/Validation/Methods/minlength
+        minlength: function( value, element, param ) {
+            var length = $.isArray( value ) ? value.length : this.getLength($.trim(value), element);
+            return this.optional(element) || length >= param;
+        },
+
+        // http://docs.jquery.com/Plugins/Validation/Methods/maxlength
+        maxlength: function( value, element, param ) {
+            var length = $.isArray( value ) ? value.length : this.getLength($.trim(value), element);
+            return this.optional(element) || length <= param;
+        },
+
+        // http://docs.jquery.com/Plugins/Validation/Methods/rangelength
+        rangelength: function( value, element, param ) {
+            var length = $.isArray( value ) ? value.length : this.getLength($.trim(value), element);
+            return this.optional(element) || ( length >= param[0] && length <= param[1] );
+        },
+
+        // http://docs.jquery.com/Plugins/Validation/Methods/min
+        min: function( value, element, param ) {
+            return this.optional(element) || value >= param;
+        },
+
+        // http://docs.jquery.com/Plugins/Validation/Methods/max
+        max: function( value, element, param ) {
+            return this.optional(element) || value <= param;
+        },
+
+        // http://docs.jquery.com/Plugins/Validation/Methods/range
+        range: function( value, element, param ) {
+            return this.optional(element) || ( value >= param[0] && value <= param[1] );
+        },
+
+        // http://docs.jquery.com/Plugins/Validation/Methods/email
+        email: function( value, element ) {
+            // contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
+            return this.optional(element) || /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(value);
+        },
+
+        // http://docs.jquery.com/Plugins/Validation/Methods/url
+        url: function( value, element ) {
+            // contributed by Scott Gonzalez: http://projects.scottsplayground.com/iri/
+            return this.optional(element) || /^(https?|s?ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value);
+        },
+
+        // http://docs.jquery.com/Plugins/Validation/Methods/date
+        date: function( value, element ) {
+            return this.optional(element) || !/Invalid|NaN/.test(new Date(value).toString());
+        },
+
+        // http://docs.jquery.com/Plugins/Validation/Methods/dateISO
+        dateISO: function( value, element ) {
+            return this.optional(element) || /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/.test(value);
+        },
+
+        // http://docs.jquery.com/Plugins/Validation/Methods/number
+        number: function( value, element ) {
+            return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(value);
+        },
+
+        // http://docs.jquery.com/Plugins/Validation/Methods/digits
+        digits: function( value, element ) {
+            return this.optional(element) || /^\d+$/.test(value);
+        },
+
+        // http://docs.jquery.com/Plugins/Validation/Methods/creditcard
+        // based on http://en.wikipedia.org/wiki/Luhn
+        creditcard: function( value, element ) {
+            if ( this.optional(element) ) {
+                return "dependency-mismatch";
+            }
+            // accept only spaces, digits and dashes
+            if ( /[^0-9 \-]+/.test(value) ) {
+                return false;
+            }
+            var nCheck = 0,
+                nDigit = 0,
+                bEven = false;
+
+            value = value.replace(/\D/g, "");
+
+            for (var n = value.length - 1; n >= 0; n--) {
+                var cDigit = value.charAt(n);
+                nDigit = parseInt(cDigit, 10);
+                if ( bEven ) {
+                    if ( (nDigit *= 2) > 9 ) {
+                        nDigit -= 9;
+                    }
+                }
+                nCheck += nDigit;
+                bEven = !bEven;
+            }
+
+            return (nCheck % 10) === 0;
+        },
+
+        // http://docs.jquery.com/Plugins/Validation/Methods/equalTo
+        equalTo: function( value, element, param ) {
+            // bind to the blur event of the target in order to revalidate whenever the target field is updated
+            // TODO find a way to bind the event just once, avoiding the unbind-rebind overhead
+            var target = $(param);
+            if ( this.settings.onfocusout ) {
+                target.unbind(".validate-equalTo").bind("blur.validate-equalTo", function() {
+                    $(element).valid();
+                });
+            }
+            return value === target.val();
+        }
+
+    }
+
+});
+
+// deprecated, use $.validator.format instead
+$.format = $.validator.format;
+
+}(jQuery));
+
+// ajax mode: abort
+// usage: $.ajax({ mode: "abort"[, port: "uniqueport"]});
+// if mode:"abort" is used, the previous request on that port (port can be undefined) is aborted via XMLHttpRequest.abort()
+(function($) {
+    var pendingRequests = {};
+    // Use a prefilter if available (1.5+)
+    if ( $.ajaxPrefilter ) {
+        $.ajaxPrefilter(function( settings, _, xhr ) {
+            var port = settings.port;
+            if ( settings.mode === "abort" ) {
+                if ( pendingRequests[port] ) {
+                    pendingRequests[port].abort();
+                }
+                pendingRequests[port] = xhr;
+            }
+        });
+    } else {
+        // Proxy ajax
+        var ajax = $.ajax;
+        $.ajax = function( settings ) {
+            var mode = ( "mode" in settings ? settings : $.ajaxSettings ).mode,
+                port = ( "port" in settings ? settings : $.ajaxSettings ).port;
+            if ( mode === "abort" ) {
+                if ( pendingRequests[port] ) {
+                    pendingRequests[port].abort();
+                }
+                return (pendingRequests[port] = ajax.apply(this, arguments));
+            }
+            return ajax.apply(this, arguments);
+        };
+    }
+}(jQuery));
+
+// provides delegate(type: String, delegate: Selector, handler: Callback) plugin for easier event delegation
+// handler is only called when $(event.target).is(delegate), in the scope of the jquery-object for event.target
+(function($) {
+    $.extend($.fn, {
+        validateDelegate: function( delegate, type, handler ) {
+            return this.bind(type, function( event ) {
+                var target = $(event.target);
+                if ( target.is(delegate) ) {
+                    return handler.apply(target, arguments);
+                }
+            });
+        }
+    });
+}(jQuery));
+
+
diff --git a/portal/static/my_account.edit_profile.js b/portal/static/my_account.edit_profile.js
new file mode 100644 (file)
index 0000000..dcbfbb3
--- /dev/null
@@ -0,0 +1,198 @@
+/*
+                        *********
+ ******* JQuery for the MySlice [Local] account buttons ********************* 
+                        ********
+Authors:
+  Mohammed Yasin Rahman <mohammed-yasin.rahman@lip6.fr>
+Copyright 2013, UPMC Sorbonne Universités / LIP6
+   
+ */
+
+jQuery(document).ready(function(){
+                      // jquery functionalities of different buttons [Edit, Cancel, Upload]
+                      //edit name
+                      jQuery("#edit_name").click(function(){
+
+                              jQuery("#span_name").show();
+                              jQuery("#nameval").hide();
+                              jQuery("#edit_name").hide();
+                              // enforcing when one edit is clicked the rest will not work at same time
+                              jQuery("#span_pass").hide();
+                              jQuery("#edit_pass").show();
+                              jQuery("#passval").show();
+                              jQuery("#span_aff").hide();
+                              jQuery("#edit_aff").show();
+                              jQuery("#affval").show();
+                              jQuery("#span_email").hide();
+                              jQuery("#edit_email").show();
+                              jQuery("#emailval").show();
+                              jQuery("#span_upload").hide();
+                              jQuery("#keyval").show();
+                              jQuery("#dl_file").show();
+                              jQuery("#upload_file").show();
+                      });
+                      jQuery("#cancel_name_change").click(function(){
+
+                              jQuery("#span_name").hide();
+                              jQuery("#nameval").show();
+                              jQuery("#edit_name").show();
+
+
+                      });
+                      //edit pass
+                      jQuery("#edit_pass").click(function(){
+
+                              jQuery("#span_pass").show();
+                              jQuery("#passval").hide();
+                              jQuery("#edit_pass").hide();
+                              // enforcing when one edit is clicked the rest will not work at same time
+                              jQuery("#span_name").hide();
+                              jQuery("#edit_name").show();
+                              jQuery("#nameval").show();
+                              jQuery("#span_aff").hide();
+                              jQuery("#edit_aff").show();
+                              jQuery("#affval").show();
+                              jQuery("#span_email").hide();
+                              jQuery("#edit_email").show();
+                              jQuery("#emailval").show();
+                              jQuery("#span_upload").hide();
+                              jQuery("#keyval").show();
+                              jQuery("#dl_file").show();
+                              jQuery("#upload_file").show();
+                      });
+                      jQuery("#cancel_pass_change").click(function(){
+
+                              jQuery("#span_pass").hide();
+                              jQuery("#passval").show();
+                              jQuery("#edit_pass").show();
+                      });
+                      // both password should be same
+                      jQuery("#editForm").validate({
+                        rules: {
+                            password: { 
+                                required: true
+                                }, 
+                            confirmpassword: { 
+                                required: true, equalTo: "#password"
+                                }
+                            }
+                      });
+                      //edit affiliation
+                      jQuery("#edit_aff").click(function(){
+
+                              jQuery("#span_aff").show();
+                              jQuery("#affval").hide();
+                              jQuery("#edit_aff").hide();
+                              // enforcing when one edit is clicked the rest will not work at same time
+                              jQuery("#span_pass").hide();
+                              jQuery("#edit_pass").show();
+                              jQuery("#passval").show();
+                              jQuery("#span_name").hide();
+                              jQuery("#edit_name").show();
+                              jQuery("#nameval").show();
+                              jQuery("#span_email").hide();
+                              jQuery("#edit_email").show();
+                              jQuery("#emailval").show();
+                              jQuery("#span_upload").hide();
+                              jQuery("#keyval").show();
+                              jQuery("#dl_file").show();
+                              jQuery("#upload_file").show();
+                      });
+                      jQuery("#cancel_aff_change").click(function(){
+
+                              jQuery("#span_aff").hide();
+                              jQuery("#affval").show();
+                              jQuery("#edit_aff").show();
+                      });
+                      //edit email
+                      /* edit email will be done by PI if needed
+                      jQuery("#edit_email").click(function(){
+
+                              jQuery("#span_email").show();
+                              jQuery("#emailval").hide();
+                              jQuery("#edit_email").hide();
+                              // enforcing when one edit is clicked the rest will not work at same time
+                              jQuery("#span_pass").hide();
+                              jQuery("#edit_pass").show();
+                              jQuery("#passval").show();
+                              jQuery("#span_aff").hide();
+                              jQuery("#edit_aff").show();
+                              jQuery("#affval").show();
+                              jQuery("#span_name").hide();
+                              jQuery("#edit_name").show();
+                              jQuery("#nameval").show();
+                              jQuery("#span_upload").hide();
+                              jQuery("#keyval").show();
+                              jQuery("#dl_file").show();
+                              jQuery("#upload_file").show();
+                      });
+                      jQuery("#cancel_email_change").click(function(){
+
+                              jQuery("#span_email").hide();
+                              jQuery("#emailval").show();
+                              jQuery("#edit_email").show();
+                      }); */
+                      //upload pub keys
+                      jQuery("#upload_file").click(function(){
+
+                              jQuery("#span_upload").show();
+                              jQuery("#dl_file").hide();
+                              jQuery("#upload_file").hide();
+                              jQuery("#keyval").hide();
+                              // enforcing when one edit is clicked the rest will not work at same time
+                              jQuery("#span_name").hide();
+                              jQuery("#edit_name").show();
+                              jQuery("#nameval").show();
+                              jQuery("#span_pass").hide();
+                              jQuery("#edit_pass").show();
+                              jQuery("#passval").show();
+                              jQuery("#span_aff").hide();
+                              jQuery("#edit_aff").show();
+                              jQuery("#affval").show();
+                              jQuery("#span_email").hide();
+                              jQuery("#edit_email").show();
+                              jQuery("#emailval").show();
+                      });
+                      jQuery("#cancel_upload").click(function(){
+
+                              jQuery("#span_upload").hide();
+                              jQuery("#keyval").show();
+                              jQuery("#dl_file").show();
+                              jQuery("#upload_file").show();
+                      });
+                  });
+
+// alert box for the "Generate new Key Pair button"
+function myFunction()
+{
+alert("You have requested to generate new key pairs. Please download and save the new keypairs after receiving the success message.");
+}
+
+function emailAlert()
+{
+alert("To edit email please contact the administratior. You will be redirected to the support page now");
+window.location.href = "/portal/contact/";
+}
+
+function affAlert()
+{
+alert("To edit affiliation please contact the administratior. You will be redirected to the support page now");
+window.location.href = "/portal/contact/";
+}
+/*
+ // alert having ok or cancel option
+function show_confirm()
+{
+var r=confirm("Press a button!");
+if (r==true)
+  {
+  alert("You pressed OK!");
+  }
+else
+  {
+  alert("You pressed Cancel!");
+  }
+}
+*/
+
+
diff --git a/portal/static/my_account.register.js b/portal/static/my_account.register.js
new file mode 100644 (file)
index 0000000..bb7fba4
--- /dev/null
@@ -0,0 +1,56 @@
+/* 
+# Jquery for password matching and Affiliation list
+
+Authors:
+  Mohammed Yasin Rahman <mohammed-yasin.rahman@lip6.fr>
+Copyright 2013, UPMC Sorbonne Universités / LIP6
+
+*/
+jQuery(document).ready(function(){
+    
+    jQuery("#commentForm").validate({
+        rules: {
+          password: { 
+                required: true
+          }, 
+          confirmpassword: { 
+                required: true, equalTo: "#password"
+          }
+        }
+    });
+    // upload button
+    jQuery("#question").change(function(){
+        if(this.value=="upload"){
+            jQuery("#upload_key").show();
+        }else{
+            jQuery("#upload_key").hide();
+        }
+    });
+
+});
+
+jQuery(function() {
+    var availableTags = [
+      "iMinds",
+      "IT Innovation",
+      "UPMC",
+      "Fraunhofer",
+      "TUB",
+      "UEDIN",
+      "INRIA",
+      "NICTA",
+      "ATOS",
+      "UTH",
+      "NTUA",
+      "UNIVBRIS",
+      "i2CAT",
+      "EUR",
+      "DANTE Limited",
+      "UC",
+      "NIA"
+    ];
+    jQuery( "#aff_list" ).autocomplete({
+      source: availableTags
+    });
+  });
+
diff --git a/portal/templates/account_validated.html b/portal/templates/account_validated.html
new file mode 100644 (file)
index 0000000..4aa120c
--- /dev/null
@@ -0,0 +1,6 @@
+<img src='{{ STATIC_URL }}img/account_validated.png' alt='account validated'/>
+<b>Your account has been validated!</b>
+
+Delegation
+
+You will be redirected to the dashboard where you can get an overview of your user account, your slices, and the platforms you have access to.
diff --git a/portal/templates/contact.html b/portal/templates/contact.html
new file mode 100644 (file)
index 0000000..bd37415
--- /dev/null
@@ -0,0 +1,29 @@
+{% extends "layout-unfold1.html" %}
+
+{% block head %}
+{{ wizard.form.media }}
+{% endblock %}
+
+{% block unfold1_main %}
+
+<link rel="stylesheet" type="text/css" href="{{STATIC_URL}}/css/onelab.css" />
+<!-- xxx ideally only onelab.css but ... xxx -->
+<link rel="stylesheet" type="text/css" href="{{STATIC_URL}}/css/registration.css" />
+<div class="onelab-title well well-lg">
+  <h2>Onelab Support</h2>
+  <h4>If you have already registered, then please <a href="mailto:support@myslice.info">send an e-mail</a>
+  or <a href="http://trac.myslice.info/" >visit us</a></h4>
+</div>
+
+<div class='well'>
+<form class="cmxform" id="commentForm" action="#" method="post">{% csrf_token %}
+<fieldset>
+{{ form.as_p }}
+<p style="text-align: center;width: 80%;">
+  <input class="btn" type="submit" value="Submit" />
+</p>
+</fieldset>
+</form>
+</div>
+{% endblock %}
+
diff --git a/portal/templates/contact_sent.html b/portal/templates/contact_sent.html
new file mode 100644 (file)
index 0000000..ca12d5f
--- /dev/null
@@ -0,0 +1,9 @@
+{% extends "layout-unfold1.html" %}
+
+{% block unfold1_main %}
+
+  <h1>Query Received !</h1>
+
+We will study your problem and get back to you as soon as possible.
+{% endblock %}
+
diff --git a/portal/templates/dashboard.html b/portal/templates/dashboard.html
new file mode 100644 (file)
index 0000000..df5c211
--- /dev/null
@@ -0,0 +1,44 @@
+{% extends "layout-unfold1.html" %}
+
+{% block head %}
+<link rel="stylesheet" type="text/css" href="{{STATIC_URL}}/css/dashboard.css" />
+{% endblock %}
+
+{% block unfold1_main %}
+
+<div id='tophat_status'></div>
+<div id='ms-dashboard'>
+
+  <div class='ms-dashboard-panel' id="ms-dashboard-profile">
+    <div class='ms-dashboard-caption'>
+      <h2>User profile</h2>
+    </div>
+    <div class='ms-dashboard-content'>
+      <ul>
+        <li><span id='username'>{{person.first_name}} {{person.last_name}}</span></li>
+        <li><b>Email: </b><a href='mailto:#'>{{person.email}}</a></li>
+      </ul>
+      <button id="account" onclick="location.href='{{URL}}/portal/account'" class="btn">Modify</button>
+    </div>
+  </div>
+
+  <div class='ms-dashboard-panel' id='ms-dashboard-testbeds'>
+    <div class='ms-dashboard-caption'>
+      <h2>Testbeds access</h2>
+    </div>
+    <div class='ms-dashboard-content' id='tophat__list__network_hrn__network_name'>
+    {{networks}}
+       </div>
+  </div>
+
+  <div class='ms-dashboard-panel' id='ms-dashboard-slices'>
+    <div class='ms-dashboard-caption'>
+      <h2>Slices</h2>
+    </div>
+    <div class='ms-dashboard-content' id='tophat__list__slice_hrn__slice_hrn'>
+    {{slices}}
+    </div>
+  </div>
+</div>
+
+{% endblock %}
diff --git a/portal/templates/home-view.html b/portal/templates/home-view.html
new file mode 100644 (file)
index 0000000..5072e52
--- /dev/null
@@ -0,0 +1,31 @@
+{% extends 'layout-unfold2.html' %}
+
+{% block unfold2_margin %}
+{% if not username %}
+{% include 'widget-login.html' %}
+{% endif %}
+{% endblock unfold2_margin %}
+
+{% block unfold2_main %}
+<link rel="stylesheet" type="text/css" href="{{STATIC_URL}}/css/onelab.css" />
+<!-- xxx ideally only onelab.css but ... xxx -->
+<link rel="stylesheet" type="text/css" href="{{STATIC_URL}}/css/registration.css" />
+<div class='well well-lg onelab-title'>
+  <h2 style="font-weight: bold;">Welcome to the OneLab portal !</h2>
+  <h4>New to OneLab? Please <a href="/portal/register">register</a> or learn more about <a href="http://www.onelab.eu/" target="_blank">the project</a>.</h3>
+</div>
+<div class='well'>
+<p>
+Experimentally-driven research is key to success in exploring the possible
+futures of the Internet. The OneLab initiative provides an open,
+general-purpose, shared experimental facility, both large-scale and
+sustainable, which allows European industry and academia to innovate and assess
+the performance of their solutions. Based on the results of several different
+European and national projects, OneLab offers access to a range of  tools and
+testbeds including PlanetLab Europe, the NITOS wireless testbed, and other
+federated testbeds.
+</p>
+<p>This UI server is connected to the manifold backend running at <code>{{ manifold_url }}</code>.</p>
+</div>
+
+{% endblock unfold2_main %}
diff --git a/portal/templates/my_account.html b/portal/templates/my_account.html
new file mode 100644 (file)
index 0000000..75cb11f
--- /dev/null
@@ -0,0 +1,167 @@
+{% extends "layout-unfold1.html" %}
+
+{% block head %}
+<link rel="stylesheet" type="text/css" href="{{STATIC_URL}}/css/my_account.common.css" />
+<link rel="stylesheet" type="text/css" href="{{STATIC_URL}}/css/my_account.profile.css" />
+<!-- <link rel="stylesheet" type="text/css" href="{{STATIC_URL}}/css/dashboard.css" /> !-->
+<script type="text/javascript" src="{{STATIC_URL}}/jquery.validate.js"></script> 
+<script type="text/javascript" src="{{STATIC_URL}}/my_account.edit_profile.js"></script>
+<script type="text/javascript" src="{{STATIC_URL}}/my_account.register.js"></script>
+{% endblock %}
+
+{% block unfold1_main %}
+
+
+<h2>Platform Access</h2>
+<table class="mytable"> 
+       <tr class="odd"> 
+       <th>Platform</th> 
+        <th>Account Type</th> 
+        <th>user_hrn</th>
+        <th>Pub Key</th>
+    </tr>   
+       {% for row in data %}         
+       <tr class="even">
+       <td class="odd"> {{ row.platform_name }} </td>
+        <td class="even"> {{ row.account_type }} </td>
+               <td class="odd"> {{ row.usr_hrn }}  </td>
+        <td class="even"> {{ row.usr_pubkey }} </td>
+    </tr> 
+       {%endfor%}               
+</table>
+
+
+
+
+<div class='ms-dashboard-panel' id='ms-dashboard-slices' style=" display:block; float:none"  >
+  <div class='ms-dashboard-caption'>
+    <h2>MySlice  Account</h2>
+  </div>
+  <div class='ms-dashboard-content' id='tophat__list__user_hrn'>
+    <div id="main">
+      <div id="middle" align="center">
+       <form id="editForm"  method="POST" action="account_process" enctype="multipart/form-data">
+         {% csrf_token %}
+         <table class="profile">          
+           <tr class="odd">
+             <td colspan="2">
+               <div id="info">Personal Details</div>
+             </td>
+           </tr>
+           <tr class="even">
+             <td class="key">Email</td>
+             <td class="value">
+               <span id="emailval" class="value" >{{ person.email }}</span>
+               <img class="logo" src="{{STATIC_URL}}/img/ques_icon.png" onclick="emailAlert()"  title="To change your email please contact the administrator" style="height: 20px; width: 20px; position: absolute; left: 625px; left: 900px; margin-top: -9px;">
+               </td>
+             </tr>
+             <tr class="odd">
+               <td class="key">Password</td>
+               <td class="value"> 
+                 <button class="edit" type="button" title="Password" name="edit_pass" id="edit_pass">Edit</button>
+                 <span id="passval"class="value">******** </span>
+                 <span class="hide_this" id="span_pass">
+                   <button type="button" class="cancel" title="Cancel" id="cancel_pass_change"> Cancel </button>
+                   <div style='display:none;' id="pass_form">
+                   <input type='hidden'  value='' /></div>
+                   <table id="edit_password">
+                     <tr>
+                       <td>Enter password: </td>
+                       <td class="field"> 
+                         <input type="password" name="password" id="password" />
+                       </td>
+                     </tr>
+                     <tr>
+                       <td>Confirm password: </td>
+                       <td class="field"> 
+                         <input type="password" name="confirmpassword" id="confirmpassword" /> 
+                         <input type="submit" name="submit_pass" value="Save"/> 
+                       </td>
+                     </tr>
+                   </table>
+                 </span>       
+               </td>
+             </tr>
+             <tr class="even">
+               <td class="key">Full Name</td>
+               <td class="value">
+                 <span id="nameval" class="value" >{{ fullname }} </span>
+                 <span class="hide_this" id="span_name">
+                   <button type="button" class="cancel" title="Cancel" id="cancel_name_change"> Cancel </button>
+                   
+                   <div style='display:none;'><input type='hidden'  name='nameform'  /></div>
+                   <input id="fname" type="text" name="fname" class="required"  maxlength="200" value="{{firstname}}" />
+                   <input id="lname" type="text" name="lname" class="required"  maxlength="200" value="{{lastname}}" />
+                   <input type="submit" name="submit_name" value="Save"/>
+                 </span>
+                 <button class="edit" type="button"title="Full Name" id="edit_name">Edit</button>
+               </td>
+
+             </tr>
+             <tr class="odd">
+               <td class="key">Authority</td>
+               <td class="value">
+                 <span id="affval" class="value">{{ authority }}</span>
+                 <img class="logo" src="{{STATIC_URL}}/img/ques_icon.png" onclick="affAlert()"  title="To change your affiliation please contact the administrator" style="height: 20px; width: 20px; position: absolute; left: 625px; left: 900px; ">
+                 </td>
+               </tr>
+               
+               <tr class="even">
+                 <td class="key">Generate Keys</td>
+                 <td> 
+                 </div>
+                 <button id="generate_keypair" name="generate" type="submit" onclick="myFunction()" title="Generate a new key pair. After it is generated, you will need to download your public and private keys again.">Generate a new Key Pair </button>
+               </div>
+             </td> 
+           </tr>
+           <tr class="odd">
+             <td class="key">Public Key
+             </td>
+             <td class="value">
+               
+               <span id="keyval" class="value">******** </span>
+               <span class="hide_this" id="span_upload">
+                 <button type="button" class="cancel" title="Cancel" id="cancel_upload"> Cancel </button>
+                 <div style='display:none;'>
+                 <input type='hidden'  name='upload'  /></div>
+                 <input type="file" name="pubkey" class="required" id="pubkey"/> 
+                 
+                 <button name="upload_key" id="upload_key"  type="submit" title="Delete your private key">Upload </button>
+                 
+               </span>
+               <div style='display:none;'>
+                 <input type='hidden'  name='dload'  />
+               </div> 
+               <button type="submit" name="dl_pubkey" class="download" title="Download your public key" id="dl_file"> Download </button>
+               <button id="upload_file" type="button" title="Upload a public key"> Upload </button>       
+             </td>
+           </tr>
+           <tr class="even" id="pkey_row" display="none">
+             <td class="key">Private Key </td>
+             <td class="value">********<a href="#">
+             <button type="submit" name="dl_pkey" class="download" title="Download your privaye key" id="dl_pkey"> Download </button>
+             <button id="delete" name="delete" type="submit" title="Delete your private key">Delete </button>
+           </td>
+         </tr>
+         <tr class="odd">
+           <td colspan="2">
+
+             <p class="warning" id="pkey_del_msg"> For better
+             security we recommend that you
+             download and delete your 
+             private key from the 
+             server. Always store your 
+             private key in a secure 
+             location. </p>
+           </td>
+         </tr>
+
+       </table>
+      </form>
+    </div>
+  </div>
+  
+</div>
+</div>
+
+{% endblock %}
diff --git a/portal/templates/platform.html b/portal/templates/platform.html
new file mode 100644 (file)
index 0000000..d24d9ed
--- /dev/null
@@ -0,0 +1,11 @@
+{% extends "layout-unfold1.html" %}
+
+{% block head %}
+<link rel="stylesheet" type="text/css" href="{{STATIC_URL}}/css/dashboard.css" />
+{% endblock %}
+
+{% block unfold1_main %}
+
+<h1>Platform</h1>
+{{networks}}
+{% endblock %}
diff --git a/portal/templates/platforms.html b/portal/templates/platforms.html
new file mode 100644 (file)
index 0000000..33fb0b3
--- /dev/null
@@ -0,0 +1,11 @@
+{% extends "layout-unfold1.html" %}
+
+{% block head %}
+<link rel="stylesheet" type="text/css" href="{{STATIC_URL}}/css/dashboard.css" />
+{% endblock %}
+
+{% block unfold1_main %}
+
+<h1>Platforms</h1>
+{{networks}}
+{% endblock %}
diff --git a/portal/templates/register_user_wizard.html b/portal/templates/register_user_wizard.html
new file mode 100644 (file)
index 0000000..8d1d528
--- /dev/null
@@ -0,0 +1,68 @@
+{% extends "layout-unfold1.html" %}
+{% load i18n %}
+{% load crispy_forms_tags %}
+
+
+{% block head %}
+{{ wizard.form.media }}
+<link rel="stylesheet" type="text/css" href="{{STATIC_URL}}css/smart_wizard.css" />
+{% endblock %}
+
+{% block unfold1_main %}
+
+  <h1>User registration</h1>
+
+  <div class='swMain'>
+
+    <ul class='anchor'>
+      {% for step in wizard.steps.all %}
+        <li>
+          <a href="#step-1" class="selected" isdone="0" rel="1">
+            <label class="stepNumber">{{forloop.counter}}</label>
+            <span class="stepDesc">Step {{forloop.counter}}<br><small>NAME OF THE STEP HERE</small></span>
+          </a>
+        </li>
+      {% endfor %}
+    </ul>
+    <div style='clear: both;'/>
+    
+        <form action="" method="post">{% csrf_token %}
+          <table>
+            {% if wizard.form.forms %}
+                {{ wizard.management_form }}
+                {% for form in wizard.form.forms %}
+                    {% crispy form form.helper %}
+                {% endfor %}
+            {% else %}
+                {{ wizard.management_form }}
+                {% crispy wizard.form %}
+            {% endif %}
+          </table>
+
+    {% if wizard.steps.prev %}
+      <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">{% trans "first step" %}</button>
+      <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">{% trans "prev step" %}</button>
+    {% endif %}
+
+    <div class='actionBar'>
+      <input class='buttonNext' type="submit" value="{% trans "submit" %}"/>
+
+      <div class="contrdol-group">
+        <div class="contrdols">
+          {% if wizard.steps.prev %}
+            <button class="buttonPrevious" name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">prev step</button>
+          {% endif %}
+          <input class="buttonNext" type="submit" value="next step"/>
+        </div>
+      </div>
+    </div>
+        </form>
+
+    <div class="progress progress-info progress-striped" style="clear: both;">
+        <div class="bar" style="width:{% widthratio wizard.steps.step1 wizard.steps.count 100%}%">
+          Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}
+        </div>
+    </div>
+  </div><!-- swMain -->
+
+{% endblock %}
diff --git a/portal/templates/registration_view.html b/portal/templates/registration_view.html
new file mode 100644 (file)
index 0000000..7e1c1d7
--- /dev/null
@@ -0,0 +1,100 @@
+{% extends "layout-unfold1.html" %}
+
+{% block head %}                
+<link rel="stylesheet" type="text/css" href="{{STATIC_URL}}/css/onelab.css" />
+<!-- xxx ideally only onelab.css but ... xxx -->
+<link rel="stylesheet" type="text/css" href="{{STATIC_URL}}/css/registration.css" />
+<script type="text/javascript" src="{{STATIC_URL}}/jquery.validate.js"></script> 
+<script type="text/javascript" src="{{STATIC_URL}}/my_account.register.js"></script>
+{% endblock %}                              
+                                    
+{% block unfold1_main %}        
+
+
+{% if errors %}
+<ul>
+  {% for error in errors %}
+  <li>{{ error }}</li>
+  {% endfor %}
+</ul>
+{% endif %}
+
+
+<div class="onelab-title well well-lg">
+  <h2>OneLab Experimenter Registration</h2>
+  <h4>For First Line Support please <a href="/portal/contact" >Contact Support</a></h3>
+</div>
+   
+<div class="well">
+<form class="cmxform" id="commentForm" method="post" action="" enctype="multipart/form-data" >
+{% csrf_token %}
+ <fieldset>
+   <div class="field">
+     <label for="cname">First Name</label>
+     <input type="text" id="firstname" name="firstname" size="25" class="required" minlength="2" value="{{ firstname}}" /> 
+     <p class="hint">Enter your first name</p>
+     <?php echo $errfName;?>
+   </div>
+   <div class="field">
+     <label for="lname">Last Name</label>
+     <input type="text" id="lastname" name="lastname" size="25" class="required" minlength="2" value="{{ lastname }}"/> 
+     <p class="hint">Enter your last name</p>
+     <?php echo $errlName;?>
+   </div>
+   <!-- DEPRECATED
+       <div class="field">
+     <label for="aff_list">Affiliation</label>
+     <input type="text" id="aff_list" name="affiliation" size="25" class="required"  value="{{ affiliation }}"/> 
+     <p class="hint">Enter your Institution name</p>
+     <?php echo $erraffiliation;?>
+   </div>
+       -->
+    <div class="field">
+      <label for="auth_list">Authority</label>
+      <select id="auth_list" name="authority_hrn" size="1" class="required">
+        {% for authority in authorities %}
+        <option value="{{ authority.authority_hrn }}"/>{{authority.name}} ({{authority.authority_hrn}})</option>
+        {% endfor %}
+     </select>
+     <p class="hint">Please select an authority responsible for vetting your account</p>
+   </div>
+
+   <div class="field">
+     <label for="cemail">Email</label>
+     <input type="text" id="email" name="email" size="25"  class="required email" value="{{ email }}"/> 
+     <p class="hint">Enter a valid email address</p>
+     <?php echo $errEmail; ?>
+   </div>
+   <div class="field">
+     <label for="password">Password</label>
+     <input type="password"  id="password" name="password"   class="required" minlength="4" value="{{ password }}"/> 
+     <p class="hint">Enter password</p>
+     <?php //echo $errPass;?>
+   </div>
+   <div class="field">
+     <label for="password">Confirm Password</label>
+     <input type="password"  id="confirmpassword" name="confirmpassword"   minlength="4" class="required" value=""/>
+     <p class="hint">Retype the password</p>
+   </div>
+   <div class="field">
+      <label for="question">My Public Key</label>
+      <select name="question" class="required" id="question">        
+        <option value="generate">Generate key pairs for me </option>
+        <option value="upload">Upload my public key </option>
+      </select> 
+      <?php echo $errFile; ?>
+   </div>
+   <div class="field" style="display:none;" id="upload_key">
+      <label for="file">Upload public key</label>
+      <input type="file" name="user_public_key" class="required" id="user_public_key"/>
+      <p class="hint">Upload a valid public key</p>
+   </div>
+   <div class="field" id="register">
+     <input class="submit btn" type="submit"  name="submit" value="Register"/>
+   </div>
+ </fieldset>
+</form>
+</div>
+
+{% endblock %}
+
diff --git a/portal/templates/slice_request.html b/portal/templates/slice_request.html
new file mode 100644 (file)
index 0000000..175863c
--- /dev/null
@@ -0,0 +1,25 @@
+{% extends "layout-unfold1.html" %}
+{% load i18n %}
+
+{% block head %}
+{{ wizard.form.media }}
+{% endblock %}
+
+{% block unfold1_main %}
+
+<link rel="stylesheet" type="text/css" href="{{STATIC_URL}}/css/onelab.css" />
+<!-- xxx ideally only onelab.css but ... xxx -->
+<link rel="stylesheet" type="text/css" href="{{STATIC_URL}}/css/registration.css" />
+
+<div class="onelab-title well well-lg">
+  <h2>Request a Slice</h2>
+</div>
+
+<div class='well'>
+<form id="commentForm" action="" method="post">{% csrf_token %}
+{{ form.as_p }}
+<input class="btn" type="submit" value="Submit" />
+</form>
+</div>
+
+{% endblock %}
diff --git a/portal/templates/slice_request_email.txt b/portal/templates/slice_request_email.txt
new file mode 100644 (file)
index 0000000..ef46a04
--- /dev/null
@@ -0,0 +1,9 @@
+NEW SLICE REQUEST
+
+slice name      : {{slice_name}}
+number of nodes : {{number_of_nodes}}
+type of nodes   : {{type_of_nodes}}
+purpose         : {{purpose}}
+email           : {{email}}
+cc myself       : {{cc_myself}}
+
diff --git a/portal/templates/slicereq_recvd.html b/portal/templates/slicereq_recvd.html
new file mode 100644 (file)
index 0000000..7ea26ed
--- /dev/null
@@ -0,0 +1,9 @@
+{% extends "layout-unfold1.html" %}
+
+{% block unfold1_main %}
+
+  <h1>Slice request Received !</h1>
+
+We will process your request and get back to you as soon as possible.
+{% endblock %}
+
diff --git a/portal/templates/user-registration-step2.html b/portal/templates/user-registration-step2.html
new file mode 100644 (file)
index 0000000..28d0af9
--- /dev/null
@@ -0,0 +1 @@
+coucou
diff --git a/portal/templates/user_register.html b/portal/templates/user_register.html
new file mode 100644 (file)
index 0000000..baa5667
--- /dev/null
@@ -0,0 +1,21 @@
+{% extends "layout-unfold1.html" %}
+
+{% block head %}
+{{ wizard.form.media }}
+<link rel="stylesheet" type="text/css" href="{{STATIC_URL}}css/smart_wizard.css" />
+{% endblock %}
+
+{% block unfold1_main %}
+
+  <h1>User registration</h1>
+
+{% if envoi %}Your registration message has been sent !{% endif %}
+<div class='well'>
+<form enctype="multipart/form-data" action="" method="post">{% csrf_token %}
+{{ form.as_p }}
+<input type="submit" value="Submit" />
+</form>
+</div>
+
+{% endblock %}
diff --git a/portal/templates/user_register_complete.html b/portal/templates/user_register_complete.html
new file mode 100644 (file)
index 0000000..9e134cf
--- /dev/null
@@ -0,0 +1,8 @@
+{% extends "layout-unfold1.html" %}
+
+{% block unfold1_main %}
+
+  <h1>User registration complete !</h1>
+
+You will receive an email with further instructions.
+{% endblock %}
diff --git a/portal/templates/user_register_email.txt b/portal/templates/user_register_email.txt
new file mode 100644 (file)
index 0000000..dc34c21
--- /dev/null
@@ -0,0 +1,4 @@
+Your have registered for an account in {{site}}.
+
+Your activation key is :{{activation_key}}; it will expire in {{expiration_days}} days.
+
diff --git a/portal/templates/user_register_email_subject.txt b/portal/templates/user_register_email_subject.txt
new file mode 100644 (file)
index 0000000..fc024dd
--- /dev/null
@@ -0,0 +1 @@
+pouet
diff --git a/portal/templates/user_request_email.txt b/portal/templates/user_request_email.txt
new file mode 100644 (file)
index 0000000..3e18d0e
--- /dev/null
@@ -0,0 +1,9 @@
+NEW USER REQUEST
+
+first_name   : {{first_name}}
+last_name    : {{last_name}} 
+authority_hrn: {{authority_hrn}}
+keypair      : {{keypair}}
+email        : {{email}}
+cc myself    : {{cc_myself}}
+
diff --git a/portal/templates/validate_pending.html b/portal/templates/validate_pending.html
new file mode 100644 (file)
index 0000000..74176ea
--- /dev/null
@@ -0,0 +1,122 @@
+{% extends "layout-unfold1.html" %}
+
+{% block head %}
+<link rel="stylesheet" type="text/css" href="{{STATIC_URL}}/css/validate_pending.css" />
+<script type="text/javascript">
+       function on_click_event() {
+               var ids = []; 
+               $('.portal__validate__checkbox').each(function(i, el) {
+                       if ($(el).attr('checked')) {
+                               // portal__validate__checkbox__slice__2
+                               var id_array = $(el).attr('id').split('__');
+                               // push(slice__2)
+                               ids.push(id_array[3] + '__' + id_array[4]);
+                       }
+               });
+               if (ids.length > 0) {
+                       var id_str = ids.join('/');
+
+                       // XXX spinner
+
+                       $.getJSON('/portal/validate_action/' + id_str,
+                               function(status) {
+                                       $.each(status, function(request_type__id, request_status) {
+                                               // request_status: NAME -> dict (status, description)
+                                               var status_str = '';
+                                               $.each(request_status, function(name, result) {
+                                                       if (status_str != '')
+                                                               status_str += ' -- ';
+
+                                                       if (result.status) {
+                                                               status_str += '<font color="green">' + name + '</font>';
+                                                               $('#portal__validate__checkbox__' + request_type__id).hide();
+                                                       } else {
+                                                               status_str += '<font color="red">' + name + ' (' + result.description + ')</font>';
+                                                       }
+                                               });
+                                               $('#portal__status__' + request_type__id).html(status_str)
+
+
+                                       });
+                               }
+                       );
+               }
+       }
+</script>
+{% endblock %}
+
+{% block unfold1_main %}
+
+<h1>Pending requests</h1>
+
+<h2>My authorities</h2>
+
+{% if my_authorities %}
+
+{% for authority, requests in my_authorities.items %}
+<h3>{{authority}}</h3>
+    {% for request in requests %}
+    <div class='portal_validate_request {{request.type}} {% if forloop.counter|divisibleby:2 %}even{% else %}odd{% endif %}'>
+               <span class='type'>{{ request.type }}</span>
+               <span class='id'>{{ request.id }}</span>
+               <span class='timestamp'>{{ request.timestamp }}</span>
+               <span class='authority'>{{ request.authority_hrn }}</span>
+        
+        {% if request.type == 'user' %}
+        <span class='details'>First name: {{request.first_name}} -- Last name: {{request.last_name}} -- Email: {{request.email}}</span>
+        {% else %}
+            {% if request.type == 'slice' %}
+        <span class='details'>Number of nodes: {{request.number_of_nodes}} -- Type of nodes: {{request.type_of_nodes}} -- Purpose: {{request.purpose}}</span>
+            {% else %} {# authority #}
+        <span class='details'>TODO</span>
+            {% endif %}
+        {% endif %}
+
+               {% if request.allowed == 'allowed' %}
+               <input class='portal__validate__checkbox' id='portal__validate__checkbox__{{request.type}}__{{request.id}}' type='checkbox'/>
+               {% else %}
+                       {% if request.allowed == 'expired' %}
+                               expired
+                       {% else %} {# denied #}
+                               denied
+                       {% endif %}
+               {% endif %}
+               <span class='status' id='portal__status__{{request.type}}__{{request.id}}'></span>
+       </div>
+    {% endfor %}
+{% endfor %}
+
+{% else %}
+<i>There is no pending request waiting for validation.</i>
+{% endif %}
+
+{% if delegation_authorities %}
+<h2>Authorities with delegation</h2>
+
+{% for authority, requests in delegation_authorities.items %}
+<h3>{{authority}}</h3>
+    {% for request in requests %}
+    <div class='portal_validate_request {{request.type}} {% if forloop.counter|divisibleby:2 %}even{% else %}odd{% endif %}'>
+               <span class='type'>{{ request.type }}</span>
+               <span class='id'>{{ request.id }}</span>
+               <span class='timestamp'>{{ request.timestamp }}</span>
+               <span class='details'>{{ request.details }}</span>
+               {% if request.allowed == 'allowed' %}
+               <input class='portal__validate__checkbox' id='portal__validate__checkbox__{{request.type}}__{{request.id}}' type='checkbox'/>
+               {% else %}
+                       {% if request.allowed == 'expired' %}
+                               expired
+                       {% else %} {# denied #}
+                               denied
+                       {% endif %}
+               {% endif %}
+               <span class='status' id='portal__status__{{request.type}}__{{request.id}}'></span>
+       </div>
+    {% endfor %}
+{% endfor %}
+
+{% endif %}
+
+<input type='button' id='portal__validate' value='Validate' onclick='on_click_event();'/>
+
+{% endblock %}
diff --git a/portal/templateviews.py b/portal/templateviews.py
new file mode 100644 (file)
index 0000000..0f46ff7
--- /dev/null
@@ -0,0 +1,53 @@
+from django.contrib.auth.decorators     import login_required
+from django.utils.decorators            import method_decorator
+from django.http                        import HttpResponseRedirect
+# for 'as_view' that we need to call in urls.py and the like
+from django.views.generic.base          import TemplateView
+
+from manifold.manifoldresult            import ManifoldException
+
+########## the base class for views that require a login
+class LoginRequiredView (TemplateView):
+
+    @method_decorator(login_required)
+    def dispatch(self, request, *args, **kwargs):
+        return super(LoginRequiredView, self).dispatch(request, *args, **kwargs)
+
+
+########## the base class for views that need to protect against ManifoldException
+# a decorator for view classes to catch manifold exceptions
+# by design views should not directly exercise a manifold query
+# given that these are asynchroneous, you would expect a view to just 
+# return a mundane skeleton
+# however of course this is not always true, 
+# e.g. we deal with metadata some other way, and so
+# it is often a good idea for a view to monitor these exceptions
+# and to take this opportunity to logout people 
+
+def logout_on_manifold_exception (fun_that_returns_httpresponse):
+    def wrapped (request, *args, **kwds):
+        print 'wrapped by logout_on_manifold_exception'
+        try:
+            return fun_that_returns_httpresponse(request,*args, **kwds)
+        except ManifoldException, manifold_result:
+            # xxx we need a means to display this message to user...
+            from django.contrib.auth import logout
+            logout(request)
+            return HttpResponseRedirect ('/')
+        except Exception, e:
+            # xxx we need to sugarcoat this error message in some error template...
+            print "Unexpected exception",e
+            import traceback
+            traceback.print_exc()
+            return HttpResponseRedirect ('/')
+    return wrapped
+
+# at first sight this matters only for views that require login
+# so for now we expose a single class that behaves like 
+# login_required + logout_on_manifold_exception
+class LoginRequiredAutoLogoutView (TemplateView):
+
+    @logout_on_manifold_exception
+    @method_decorator(login_required)
+    def dispatch (self, request, *args, **kwds):
+        return super(LoginRequiredAutoLogoutView,self).dispatch(request,*args,**kwds)
diff --git a/portal/tests.py b/portal/tests.py
new file mode 100644 (file)
index 0000000..501deb7
--- /dev/null
@@ -0,0 +1,16 @@
+"""
+This file demonstrates writing tests using the unittest module. These will pass
+when you run "manage.py test".
+
+Replace this with more appropriate tests for your application.
+"""
+
+from django.test import TestCase
+
+
+class SimpleTest(TestCase):
+    def test_basic_addition(self):
+        """
+        Tests that 1 + 1 always equals 2.
+        """
+        self.assertEqual(1 + 1, 2)
diff --git a/portal/tests/__init__.py b/portal/tests/__init__.py
new file mode 100644 (file)
index 0000000..2ae207c
--- /dev/null
@@ -0,0 +1,2 @@
+from portal.tests.models import *
+
diff --git a/portal/tests/models.py b/portal/tests/models.py
new file mode 100755 (executable)
index 0000000..bac20f2
--- /dev/null
@@ -0,0 +1,20 @@
+#!/usr/bin/env python 
+# -*- coding: utf-8 -*-
+#
+#DJANGO_SETTINGS_MODULE="repos.myslice-django.myslice.settings" ./test-send-email.py
+#
+#from django.core import mail
+from django.test import TestCase
+from django.conf import settings
+from django.core.mail import EmailMessage
+import myslice.settings
+
+class EmailTest(TestCase):
+    def test_send_email(self):
+       email = EmailMessage('Hello', 'World', to=['jordan.auge@lip6.fr'])
+        email.send()
+
+
+
+
+
diff --git a/portal/urls.py b/portal/urls.py
new file mode 100644 (file)
index 0000000..6e73348
--- /dev/null
@@ -0,0 +1,88 @@
+# -*- coding: utf-8 -*-
+#
+# portal/urls.py: URL mappings for the portal application
+# This file is part of the Manifold project.
+#
+# Authors:
+#   Jordan Augé <jordan.auge@lip6.fr>
+# Copyright 2013, UPMC Sorbonne Universités / LIP6
+#
+# This program is free software; you can redistribute it and/or modify it under
+# the terms of the GNU General Public License as published by the Free Software
+# Foundation; either version 3, or (at your option) any later version.
+# 
+# This program is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
+# details.
+# 
+# You should have received a copy of the GNU General Public License along with
+# this program; see the file COPYING.  If not, write to the Free Software
+# Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+from django.views.generic.base   import TemplateView
+from django.conf.urls           import patterns, include, url
+
+from portal.platformsview       import PlatformsView
+from portal.platformview        import PlatformView
+from portal.dashboardview       import DashboardView
+from portal.accountview         import AccountView, account_process
+from portal.contactview         import ContactView
+from portal.slicerequestview    import SliceRequestView
+from portal.registrationview    import RegistrationView
+from portal.sliceview           import SliceView
+
+# hopefully these should move in dedicated source files too
+from portal.views               import PresViewView, pres_view_static, pres_view_methods, pres_view_animation
+from portal.views               import ValidatePendingView
+
+
+# DEPRECATED #named_register_forms = (
+# DEPRECATED #    ("step1", RegisterUserForm),
+# DEPRECATED #    ("step2", RegisterUserStep2Form)
+# DEPRECATED #)
+# DEPRECATED #
+# DEPRECATED #register_wizard = RegisterUserWizardView.as_view(named_register_forms,
+# DEPRECATED #    url_name="register_wizard_step")
+
+urlpatterns = patterns('',
+    # User registration
+    #url(r'^user/register/?$', UserRegisterView.as_view(), name='user_register'),
+    url(r'^user/register/complete/$',
+        TemplateView.as_view(template_name='user_register_complete.html'),
+        name='user_register_complete'),
+    # User validation
+    #url(r'^user/validate/?$', UserValidateView.as_view(), name='user_validate'),
+    url(r'^dashboard/?$', DashboardView.as_view(), name='dashboard'),
+    #url(r'^my_account/?$', MyAccountView.as_view(), name='my_account'),
+    url(r'^account/?$', AccountView.as_view(), name='account'),
+    url(r'^platforms/?$', PlatformsView.as_view(), name='platforms'),
+    url(r'^platform/(?P<platformname>[\w\.]+)/?$', PlatformView.as_view(), name='platform'),
+    url(r'^slice/?$',SliceView.as_view(),name='slice'),
+    url(r'^slice/(?P<slicename>[\w\.]+)/?$', SliceView.as_view(),name='slice'),
+    url(r'^account/account_process/?$', account_process),
+    url(r'^register/?$', RegistrationView.as_view(), name='registration'),
+    url(r'^contact/?$', ContactView.as_view(), name='contact'),
+    # Slice request
+    url(r'^slice_request/?$', SliceRequestView.as_view(), name='slice_request'),
+    # Validate pending requests
+    url(r'^validate/?$', ValidatePendingView.as_view()),
+    # http://stackoverflow.com/questions/2360179/django-urls-how-to-pass-a-list-of-items-via-clean-urls
+    # (r'^validate_action/(?P<constraints>[^/]+)/(?P<id>\w+)/?$', 'portal.views.pres_view_static'),
+     (r'^validate_action(?P<id>(?:/\w+)+)/?$', 'portal.actions.validate_action'),
+
+    url(r'^pres_view/?$', PresViewView.as_view(), name='pres_view'),
+    (r'^methods/(?P<type>\w+)/?$', 'portal.views.pres_view_methods'),
+    (r'^animation/(?P<constraints>[^/]+)/(?P<id>\w+)/?$', 'portal.views.pres_view_animation'),
+    (r'^static/(?P<constraints>[^/]+)/(?P<id>\w+)/?$', 'portal.views.pres_view_static'),
+    #url(r'^slice/request/?$',  views.slice_request,  name='slice_request'),
+    # Slice confirmation
+    #url(r'^slice/validate/?$', views.slice_validate, name='slice_validate'),
+)
+# (r'^accounts/', include('registration.backends.default.urls')),
+
+
+# DEPRECATED #    url(r'^$', views.index, name='index'),
+# DEPRECATED #    url(r"^registerwizard/(?P<step>[-\w]+)/$", register_wizard,
+# DEPRECATED #        name="register_wizard_step"),
+# DEPRECATED #    url(r"^registerwizard/$", register_wizard, name="register_wizard")
diff --git a/portal/util.py b/portal/util.py
new file mode 100644 (file)
index 0000000..df3606c
--- /dev/null
@@ -0,0 +1,175 @@
+# -*- coding: utf-8 -*-
+#
+# Code borrowed from the django-registration application
+# https://bitbucket.org/ubernostrum/django-registration
+
+from django.shortcuts import redirect
+from django.views.generic.edit import FormView
+from django.views.generic.base  import TemplateView
+
+class _RequestPassingFormView(FormView):
+    """
+    A version of FormView which passes extra arguments to certain
+    methods, notably passing the HTTP request nearly everywhere, to
+    enable finer-grained processing.
+    
+    """
+    def get(self, request, *args, **kwargs):
+        # Pass request to get_form_class and get_form for per-request
+        # form control.
+        form_class = self.get_form_class(request)
+        form = self.get_form(form_class)
+        return self.render_to_response(self.get_context_data(form=form))
+
+    def post(self, request, *args, **kwargs):
+        # Pass request to get_form_class and get_form for per-request
+        # form control.
+        form_class = self.get_form_class(request)
+        form = self.get_form(form_class)
+        if form.is_valid():
+            # Pass request to form_valid.
+            return self.form_valid(request, form)
+        else:
+            return self.form_invalid(form)
+
+    def get_form_class(self, request=None):
+        return super(_RequestPassingFormView, self).get_form_class()
+
+    def get_form_kwargs(self, request=None, form_class=None):
+        return super(_RequestPassingFormView, self).get_form_kwargs()
+
+    def get_initial(self, request=None):
+        return super(_RequestPassingFormView, self).get_initial()
+
+    def get_success_url(self, request=None, user=None):
+        # We need to be able to use the request and the new user when
+        # constructing success_url.
+        return super(_RequestPassingFormView, self).get_success_url()
+
+    def form_valid(self, form, request=None):
+        return super(_RequestPassingFormView, self).form_valid(form)
+
+    def form_invalid(self, form, request=None):
+        return super(_RequestPassingFormView, self).form_invalid(form)
+
+class RegistrationView(_RequestPassingFormView):
+    """
+    Base class for user registration views.
+    
+    """
+    disallowed_url = 'registration_disallowed'
+    #form_class =  RegistrationForm
+    http_method_names = ['get', 'post', 'head', 'options', 'trace']
+    success_url = None
+    template_name = 'user_register.html' #registration/registration_form.html'
+
+    def dispatch(self, request, *args, **kwargs):
+        """
+        Check that user signup is allowed before even bothering to
+        dispatch or do other processing.
+        
+        """
+        if not self.registration_allowed(request):
+            return redirect(self.disallowed_url)
+        return super(RegistrationView, self).dispatch(request, *args, **kwargs)
+
+    def form_valid(self, request, form):
+        new_user = self.register(request, **form.cleaned_data)
+        success_url = self.get_success_url(request, new_user)
+        
+        # success_url may be a simple string, or a tuple providing the
+        # full argument set for redirect(). Attempting to unpack it
+        # tells us which one it is.
+        try:
+            to, args, kwargs = success_url
+            return redirect(to, *args, **kwargs)
+        except ValueError:
+            return redirect(success_url)
+
+    def registration_allowed(self, request):
+        """
+        Override this to enable/disable user registration, either
+        globally or on a per-request basis.
+        
+        """
+        return True
+
+    def register(self, request, **cleaned_data):
+        """
+        Implement user-registration logic here. Access to both the
+        request and the full cleaned_data of the registration form is
+        available here.
+        
+        """
+        raise NotImplementedError
+
+class ActivationView(TemplateView):
+    """
+    Base class for user activation views.
+    
+    """
+    http_method_names = ['get']
+    template_name = 'registration/activate.html'
+
+    def get(self, request, *args, **kwargs):
+        activated_user = self.activate(request, *args, **kwargs)
+        if activated_user:
+            signals.user_activated.send(sender=self.__class__,
+                                        user=activated_user,
+                                        request=request)
+            success_url = self.get_success_url(request, activated_user)
+            try:
+                to, args, kwargs = success_url
+                return redirect(to, *args, **kwargs)
+            except ValueError:
+                return redirect(success_url)
+        return super(ActivationView, self).get(request, *args, **kwargs)
+
+    def activate(self, request, *args, **kwargs):
+        """
+        Implement account-activation logic here.
+        
+        """
+        raise NotImplementedError
+
+    def get_success_url(self, request, user):
+        raise NotImplementedError
+
+
+# DEPRECATED #def user_register(request):
+# DEPRECATED #    if request.method == 'POST':
+# DEPRECATED #        form = UserRegisterForm(request.POST)
+# DEPRECATED #        if form.is_valid():
+# DEPRECATED #            first_name = form.cleaned_data['first_name']
+# DEPRECATED #            last_name  = form.cleaned_data['last_name']
+# DEPRECATED #            email      = form.cleaned_data['email']
+# DEPRECATED #            password   = form.cleaned_data['password']
+# DEPRECATED #            password2  = form.cleaned_data['password2']
+# DEPRECATED #            keypair    = form.cleaned_data['keypair']
+# DEPRECATED #            ## Ici nous pouvons traiter les données du formulaire
+# DEPRECATED #            #sujet = form.cleaned_data['sujet']
+# DEPRECATED #            #message = form.cleaned_data['message']
+# DEPRECATED #            #envoyeur = form.cleaned_data['envoyeur']
+# DEPRECATED #            #renvoi = form.cleaned_data['renvoi']
+# DEPRECATED #            ## Nous pourrions ici envoyer l'e-mail grâce aux données que nous venons de récupérer
+# DEPRECATED #            #envoi = True
+# DEPRECATED #
+# DEPRECATED #            
+# DEPRECATED #    else:
+# DEPRECATED #        form = UserRegisterForm()
+# DEPRECATED #    return render(request, 'user_register.html', locals())
+# DEPRECATED #
+# DEPRECATED #def user_validate(request):
+# DEPRECATED #    pass
+
+def slice_request(request):
+    if request.method == 'POST':
+        form = SliceRequestForm(request.POST)
+        if form.is_valid():
+            slice_name = form.cleaned_data['slice_name']
+    else:
+        form = SliceRequestForm()
+    return render(request, 'slice_request.html', locals())
+
+def slice_validate(request):
+    pass
diff --git a/portal/views.py b/portal/views.py
new file mode 100644 (file)
index 0000000..2029e70
--- /dev/null
@@ -0,0 +1,382 @@
+# -*- coding: utf-8 -*-
+#
+# portal/views.py: views for the portal application
+# This file is part of the Manifold project.
+#
+# Authors:
+#   Jordan Augé <jordan.auge@lip6.fr>
+#   Mohammed Yasin Rahman <mohammed-yasin.rahman@lip6.fr>
+# Copyright 2013, UPMC Sorbonne Universités / LIP6
+#
+# This program is free software; you can redistribute it and/or modify it under
+# the terms of the GNU General Public License as published by the Free Software
+# Foundation; either version 3, or (at your option) any later version.
+# 
+# This program is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
+# details.
+# 
+# You should have received a copy of the GNU General Public License along with
+# this program; see the file COPYING.  If not, write to the Free Software
+# Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+import json
+
+from django.http                import HttpResponseRedirect, HttpResponse
+from django.views.generic.base  import TemplateView
+from django.shortcuts           import render
+from django.template.loader     import render_to_string
+
+from myslice.viewutils          import topmenu_items, the_user
+
+from plugins.pres_view          import PresView
+from portal.event               import Event
+
+# these seem totally unused for now
+#from portal.util                import RegistrationView, ActivationView
+
+from portal.models              import PendingUser, PendingSlice
+from portal.actions             import get_request_by_authority
+from manifold.manifoldapi       import execute_query
+from manifold.core.query        import Query
+from unfold.page                import Page
+
+# NOTE
+# initially all the portal views were defined in this single file
+# all the other ones have now migrated into separate classes/files for more convenience
+# I'm leaving these ones here for now as I could not exactly figure what the purpose was 
+# (i.e. what the correct name should be, as presviewview was a bit cryptic)
+class PresViewView(TemplateView):
+    template_name = "view-unfold1.html"
+
+    def get_context_data(self, **kwargs):
+
+        page = Page(self.request)
+
+        pres_view = PresView(page = page)
+
+        context = super(PresViewView, self).get_context_data(**kwargs)
+
+        #context['ALL_STATIC'] = "all_static"
+        context['unfold1_main'] = pres_view.render(self.request)
+
+        # XXX This is repeated in all pages
+        # more general variables expected in the template
+        context['title'] = 'Test view that combines various plugins'
+        # the menu items on the top
+        context['topmenu_items'] = topmenu_items('PresView', self.request)
+        # so we can sho who is logged
+        context['username'] = the_user(self.request)
+
+        prelude_env = page.prelude_env()
+        context.update(prelude_env)
+
+        return context
+
+def json_me(config_file,type):
+    json_answer = ''
+    for ligne in config_file:
+        if not ligne.startswith('#'):
+            args = ligne.split(';')
+            json_answer += str('{ "name": "' + args[0] + '" ,"id":"' + args[1]  + '" ,"descriptif":"' + args[2]+'"')
+            if type!="dynamic":
+                json_answer += str(',"contraints":')
+                if args[3]=="":
+                    json_answer += str('""')
+                else:
+                    json_answer += str(args[3])
+            json_answer += str('},')
+    return json_answer[:-1]
+
+
+DIR = '/var/myslice/'
+STATIC = '%s/config_method_static' % DIR
+DYNAMIC = '%s/config_method_dynamic' % DIR
+ANIMATION = '%s/config_method_animation' % DIR
+
+def pres_view_methods(request, type):
+
+    if type ==None:
+        return 0
+    elif type =="static":
+        config = open(STATIC, "r")
+        json_answer = str('{ "options": [')
+        json_answer += str(json_me(config,"static"))
+        json_answer += str('] }')
+        config.close()
+    elif type =="dynamic":
+        config = open(DYNAMIC, "r")
+        json_answer = str('{ "options": [')
+        json_answer += str(json_me(config,"dynamic"))
+        json_answer += str('] }')
+        config.close()
+    elif type =="animation":
+        config = open(ANIMATION, "r")
+        json_answer = str('{ "options": [')
+        json_answer += str(json_me(config,"animation"))
+        json_answer += str('] }')
+        config.close()
+    elif type =="all":
+        config = open(STATIC, "r")
+        json_answer = str('{ "static": [')
+        json_answer += str(json_me(config,"static"))
+        json_answer += str('],')
+        json_answer += str('"dynamic": [')
+        config.close()
+        config = open(DYNAMIC, "r")
+        json_answer += str(json_me(config,"dynamic"))
+        json_answer += str('],')
+        json_answer += str('"animation": [')
+        config.close()
+        config = open(ANIMATION, "r")
+        json_answer += str(json_me(config,"animation"))
+        json_answer += str('] }')
+        config.close()
+    else:
+        return 0
+    return HttpResponse (json_answer, mimetype="application/json")
+
+def pres_view_animation(request, constraints, id):
+
+# sites crees depuis 2008
+# static.py?contraints=']date_created':1262325600&id='name_id"'
+
+    # method = request.getvalue('method') #ex : GetSites
+    #constraints = "']date_created':1262325600"
+    #id = "2"
+
+    if id == None:
+        return 0
+
+    # method = 'GetSites'#request.getvalue('method') #ex : GetSites
+    # constraints = {}#request.getvalue('constraints') // nul = {}
+    # response_field = "'site_id','name','date_created'"#request.getvalue('response_field')
+
+    config_file = open(ANIMATION, "r")
+    for ligne in config_file:
+        if not ligne.startswith('#'):
+            ligne = ligne.split('\n')
+            first = ligne[0].split(';')
+            if (str(first[1]) == str(id)):
+                save = first
+    config_file.close()
+
+    #Les print_method, print_option sont definis par le client (js)
+    #Les animations acceptent que les connexions anonymous
+    # args = "postmsg;animation;;;anonymous;https://www.planet-lab.eu/PLCAPI/;"
+    args = ";;"+str(save[8])+";"+str(save[9])+";anonymous;"+str(save[5])+";"+str(save[6])+";{"+str(constraints)+"};"+str(save[7])+";"
+
+
+    #Creation d'un objet event
+    event = Event(args)
+    cmd = [{"params": {
+            "data": {
+                "print_options": event.print_options,
+                "print_method": event.print_method,
+                "message": event.data
+            }
+        }
+    }]
+
+    json_answer = json.dumps(cmd)
+    return HttpResponse (json_answer, mimetype="application/json")
+
+def pres_view_static(request, constraints, id):
+    #constraints = "']date_created':1262325600"
+    #id = "2"
+
+    # method = 'GetSites'#request.getvalue('method') #ex : GetSites
+    # constraints = {}#request.getvalue('constraints') // nul = {}
+    # response_field = "'site_id','name','date_created'"#request.getvalue('response_field')
+
+    config_file = open(STATIC, "r")
+    for ligne in config_file:
+        if not ligne.startswith('#'):
+            ligne = ligne.split('\n')
+            first = ligne[0].split(';')
+            if (str(first[1]) == str(id)):
+                save = first
+    config_file.close()
+
+    #Les print_method, print_option sont definis par le client (js)
+    #Les animations acceptent que les connexions anonymous
+    # args = "postmsg;animation;;;anonymous;https://www.planet-lab.eu/PLCAPI/;"
+    args = ";;"+str(save[8])+";"+str(save[9])+";anonymous;"+str(save[5])+";"+str(save[6])+";{"+str(constraints)+"};"+str(save[7])+";"
+
+
+    #Creation d'un objet event
+    event = Event(args)
+    cmd = [{"params": {
+            "data": {
+                "print_options": event.print_options,
+                "print_method": event.print_method,
+                "message": event.data
+            }
+        }
+    }]
+
+    json_answer = json.dumps(cmd)
+    return HttpResponse (json_answer, mimetype="application/json")
+
+class ValidatePendingView(TemplateView):
+    template_name = "validate_pending.html"
+
+    def get_context_data(self, **kwargs):
+        # We might have slices on different registries with different user accounts 
+        # We note that this portal could be specific to a given registry, to which we register users, but i'm not sure that simplifies things
+        # Different registries mean different identities, unless we identify via SFA HRN or have associated the user email to a single hrn
+
+        #messages.info(self.request, 'You have logged in')
+        page = Page(self.request)
+
+        ctx_my_authorities = {}
+        ctx_delegation_authorities = {}
+
+
+        # The user need to be logged in
+        if the_user(self.request):
+            # Who can a PI validate:
+            # His own authorities + those he has credentials for.
+            # In MySlice we need to look at credentials also.
+            
+
+            # XXX This will have to be asynchroneous. Need to implement barriers,
+            # for now it will be sufficient to have it working statically
+
+            # get user_id to later on query accounts
+            # XXX Having real query plan on local tables would simplify all this
+            # XXX $user_email is still not available for local tables
+            #user_query = Query().get('local:user').filter_by('email', '==', '$user_email').select('user_id')
+            user_query = Query().get('local:user').filter_by('email', '==', the_user(self.request)).select('user_id')
+            user, = execute_query(self.request, user_query)
+            user_id = user['user_id']
+
+            # Query manifold to learn about available SFA platforms for more information
+            # In general we will at least have the portal
+            # For now we are considering all registries
+            all_authorities = []
+            platform_ids = []
+            sfa_platforms_query = Query().get('local:platform').filter_by('gateway_type', '==', 'sfa').select('platform_id', 'platform', 'auth_type')
+            sfa_platforms = execute_query(self.request, sfa_platforms_query)
+            for sfa_platform in sfa_platforms:
+                print "SFA PLATFORM > ", sfa_platform['platform']
+                if not 'auth_type' in sfa_platform:
+                    continue
+                auth = sfa_platform['auth_type']
+                if not auth in all_authorities:
+                    all_authorities.append(auth)
+                platform_ids.append(sfa_platform['platform_id'])
+
+            # We can check on which the user has authoritity credentials = PI rights
+            credential_authorities = set()
+            credential_authorities_expired = set()
+
+            # User account on these registries
+            user_accounts_query = Query.get('local:account').filter_by('user_id', '==', user_id).filter_by('platform_id', 'included', platform_ids).select('config')
+            user_accounts = execute_query(self.request, user_accounts_query)
+            #print "=" * 80
+            #print user_accounts
+            #print "=" * 80
+            for user_account in user_accounts:
+                config = json.loads(user_account['config'])
+                creds = []
+                if 'authority_credentials' in config:
+                    for authority_hrn, credential in config['authority_credentials'].items():
+                        #if credential is not expired:
+                        credential_authorities.add(authority_hrn)
+                        #else
+                        #    credential_authorities_expired.add(authority_hrn)
+                if 'delegated_authority_credentials' in config:
+                    for authority_hrn, credential in config['delegated_authority_credentials'].items():
+                        #if credential is not expired:
+                        credential_authorities.add(authority_hrn)
+                        #else
+                        #    credential_authorities_expired.add(authority_hrn)
+
+            print 'credential_authorities =', credential_authorities
+            print 'credential_authorities_expired =', credential_authorities_expired
+
+            # ** Where am I a PI **
+            # For this we need to ask SFA (of all authorities) = PI function
+            pi_authorities_query = Query.get('user').filter_by('user_hrn', '==', '$user_hrn').select('pi_authorities')
+            pi_authorities_tmp = execute_query(self.request, pi_authorities_query)
+            pi_authorities = set()
+            for pa in pi_authorities_tmp:
+                pi_authorities |= set(pa['pi_authorities'])
+
+            print "pi_authorities =", pi_authorities
+            
+            # My authorities + I have a credential
+            pi_credential_authorities = pi_authorities & credential_authorities
+            pi_no_credential_authorities = pi_authorities - credential_authorities - credential_authorities_expired
+            pi_expired_credential_authorities = pi_authorities & credential_authorities_expired
+            # Authorities I've been delegated PI rights
+            pi_delegation_credential_authorities = credential_authorities - pi_authorities
+            pi_delegation_expired_authorities = credential_authorities_expired - pi_authorities
+
+            print "pi_credential_authorities =", pi_credential_authorities
+            print "pi_no_credential_authorities =", pi_no_credential_authorities
+            print "pi_expired_credential_authorities =", pi_expired_credential_authorities
+            print "pi_delegation_credential_authorities = ", pi_delegation_credential_authorities
+            print "pi_delegation_expired_authorities = ", pi_delegation_expired_authorities
+
+            # Summary intermediary
+            pi_my_authorities = pi_credential_authorities | pi_no_credential_authorities | pi_expired_credential_authorities
+            pi_delegation_authorities = pi_delegation_credential_authorities | pi_delegation_expired_authorities
+
+            print "--"
+            print "pi_my_authorities = ", pi_my_authorities
+            print "pi_delegation_authorities = ", pi_delegation_authorities
+
+            # Summary all
+            queried_pending_authorities = pi_my_authorities | pi_delegation_authorities
+            print "----"
+            print "queried_pending_authorities = ", queried_pending_authorities
+
+            requests = get_request_by_authority(queried_pending_authorities)
+            for request in requests:
+                auth_hrn = request['authority_hrn']
+
+                if auth_hrn in pi_my_authorities:
+                    dest = ctx_my_authorities
+
+                    # define the css class
+                    if auth_hrn in pi_credential_authorities:
+                        request['allowed'] = 'allowed'
+                    elif auth_hrn in pi_expired_credential_authorities:
+                        request['allowed'] = 'expired'
+                    else: # pi_no_credential_authorities
+                        request['allowed'] = 'denied'
+
+                elif auth_hrn in pi_delegation_authorities:
+                    dest = ctx_delegation_authorities
+
+                    if auth_hrn in pi_delegation_credential_authorities:
+                        request['allowed'] = 'allowed'
+                    else: # pi_delegation_expired_authorities
+                        request['allowed'] = 'expired'
+
+                else:
+                    continue
+
+                if not auth_hrn in dest:
+                    dest[auth_hrn] = []
+                dest[auth_hrn].append(request) 
+        
+        context = super(ValidatePendingView, self).get_context_data(**kwargs)
+        context['my_authorities']   = ctx_my_authorities
+        context['delegation_authorities'] = ctx_delegation_authorities
+
+        # XXX This is repeated in all pages
+        # more general variables expected in the template
+        context['title'] = 'Test view that combines various plugins'
+        # the menu items on the top
+        context['topmenu_items'] = topmenu_items('Dashboard', self.request) 
+        # so we can sho who is logged
+        context['username'] = the_user(self.request) 
+
+        # XXX We need to prepare the page for queries
+        #context.update(page.prelude_env())
+
+        return context
diff --git a/requirements.txt b/requirements.txt
new file mode 100644 (file)
index 0000000..a75e4e3
--- /dev/null
@@ -0,0 +1,2 @@
+# Install all of our production dependencies only.
+-r requirements/prod.txt
diff --git a/requirements/common.txt b/requirements/common.txt
new file mode 100644 (file)
index 0000000..43afd6d
--- /dev/null
@@ -0,0 +1,5 @@
+# requirements/common.txt
+#Django==1.4
+django-registration==1.0
+Sphinx==1.1.3
+django-south
diff --git a/requirements/dev.txt b/requirements/dev.txt
new file mode 100644 (file)
index 0000000..e82ac89
--- /dev/null
@@ -0,0 +1,3 @@
+# requirements/dev.txt
+-r common.txt
+django-debug-toolbar==0.9.4
diff --git a/requirements/prod.txt b/requirements/prod.txt
new file mode 100644 (file)
index 0000000..b658f94
--- /dev/null
@@ -0,0 +1,2 @@
+# requirements/prod.txt
+-r common.txt
diff --git a/requirements/test.txt b/requirements/test.txt
new file mode 100644 (file)
index 0000000..83e4e8a
--- /dev/null
@@ -0,0 +1,6 @@
+# requirements/test.txt
+-r common.txt
+django-coverage==1.2.2
+django-nose==0.1.3
+mock==0.8.0
+nosexcover==1.0.7
diff --git a/reset.py b/reset.py
new file mode 100755 (executable)
index 0000000..b7bb571
--- /dev/null
+++ b/reset.py
@@ -0,0 +1,4 @@
+#!/usr/bin/env python
+rm myslice.sqlite3
+./manage.py syncdb
+./manage.py migrate portal
diff --git a/sample/__init__.py b/sample/__init__.py
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/sample/templates/websockets.html b/sample/templates/websockets.html
new file mode 100644 (file)
index 0000000..9942fd0
--- /dev/null
@@ -0,0 +1,41 @@
+<!DOCTYPE html>
+<html>
+   <head>
+      <script type="text/javascript">
+         var sock = null;
+         var wsuri = "ws://dev.myslice.info:9000";
+         window.onload = function() {
+            sock = new WebSocket(wsuri);
+            sock.onopen = function() {
+               console.log("connected to " + wsuri);
+            }
+            sock.onclose = function(e) {
+               console.log("connection closed (" + e.code + ")");
+            }
+            sock.onmessage = function(e) {
+               console.log("message received: " + e.data);
+            }
+         };
+         function send() {
+            var msg = document.getElementById('message').value;
+            sock.send(msg);
+         };
+      </script>
+   </head>
+   <body>
+      <h1>WebSocket Echo Test</h1>
+      <form>
+         <p>
+            Message:
+            <input id="message" type="text" value="Hello, world!">
+         </p>
+      </form>
+      <button onclick='send();'>Send Message</button>
+   </body>
+</html>
diff --git a/sample/templates/websockets2.html b/sample/templates/websockets2.html
new file mode 100644 (file)
index 0000000..b1119d0
--- /dev/null
@@ -0,0 +1,69 @@
+<!DOCTYPE html>
+<html>
+   <head>
+      <script type="text/javascript">
+         var sock = null;
+         var ellog = null;
+
+         window.onload = function() {
+
+            var wsuri;
+            ellog = document.getElementById('log');
+
+            if (window.location.protocol === "file:") {
+               wsuri = "ws://localhost:9000";
+            } else {
+               wsuri = "ws://" + window.location.hostname + ":9000";
+            }
+
+            if ("WebSocket" in window) {
+               sock = new WebSocket(wsuri);
+            } else if ("MozWebSocket" in window) {
+               sock = new MozWebSocket(wsuri);
+            } else {
+               log("Browser does not support WebSocket!");
+               window.location = "http://autobahn.ws/unsupportedbrowser";
+            }
+
+            if (sock) {
+               sock.onopen = function() {
+                  log("Connected to " + wsuri);
+               }
+
+               sock.onclose = function(e) {
+                  log("Connection closed (wasClean = " + e.wasClean + ", code = " + e.code + ", reason = '" + e.reason + "')");
+                  sock = null;
+               }
+
+               sock.onmessage = function(e) {
+                  log("Got echo: " + e.data);
+               }
+            }
+         };
+
+         function broadcast() {
+            var msg = document.getElementById('message').value;
+            if (sock) {
+               sock.send(msg);
+               log("Sent: " + msg);
+            } else {
+               log("Not connected.");
+            }
+         };
+
+         function log(m) {
+            ellog.innerHTML += m + '\n';
+            ellog.scrollTop = ellog.scrollHeight;
+         };
+      </script>
+   </head>
+   <body>
+      <h1>Autobahn WebSocket Broadcast Demo</h1>
+      <noscript>You must enable JavaScript</noscript>
+      <form>
+         <p>Broadcast Message: <input id="message" type="text" size="50" maxlength="50" value="Hello from Browser!"></p>
+      </form>
+      <button onclick='broadcast();'>Broadcast Message</button>
+      <pre id="log" style="height: 20em; overflow-y: scroll; background-color: #faa;"></pre>
+   </body>
+</html>
diff --git a/sample/urls.py b/sample/urls.py
new file mode 100644 (file)
index 0000000..d56b5dc
--- /dev/null
@@ -0,0 +1,29 @@
+# -*- coding: utf-8 -*-
+#
+# sample/urls.py: URL mappings for the sample application
+# This file is part of the Manifold project.
+#
+# Authors:
+#   Jordan Augé <jordan.auge@lip6.fr>
+# Copyright 2013, UPMC Sorbonne Universités / LIP6
+#
+# This program is free software; you can redistribute it and/or modify it under
+# the terms of the GNU General Public License as published by the Free Software
+# Foundation; either version 3, or (at your option) any later version.
+# 
+# This program is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
+# details.
+# 
+# You should have received a copy of the GNU General Public License along with
+# this program; see the file COPYING.  If not, write to the Free Software
+# Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+from django.conf.urls import patterns, url
+from sample.views     import WebSocketsView, WebSockets2View
+
+urlpatterns = patterns('',
+    url(r'^websockets/?$', WebSocketsView.as_view(), name='websockets'),
+    url(r'^websockets2/?$', WebSockets2View.as_view(), name='websockets2'),
+)
diff --git a/sample/views.py b/sample/views.py
new file mode 100644 (file)
index 0000000..c134269
--- /dev/null
@@ -0,0 +1,66 @@
+# -*- coding: utf-8 -*-
+#
+# sample/views.py: views for the sample application
+# This file is part of the Manifold project.
+#
+# Authors:
+#   Jordan Augé <jordan.auge@lip6.fr>
+# Copyright 2013, UPMC Sorbonne Universités / LIP6
+#
+# This program is free software; you can redistribute it and/or modify it under
+# the terms of the GNU General Public License as published by the Free Software
+# Foundation; either version 3, or (at your option) any later version.
+# 
+# This program is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
+# details.
+# 
+# You should have received a copy of the GNU General Public License along with
+# this program; see the file COPYING.  If not, write to the Free Software
+# Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+from django.views.generic.base   import TemplateView
+from myslice.viewutils           import topmenu_items, the_user
+
+class WebSocketsView(TemplateView):
+    template_name = "websockets.html"
+
+    def get_context_data(self, **kwargs):
+        # We might have slices on different registries with different user accounts 
+        # We note that this portal could be specific to a given registry, to which we register users, but i'm not sure that simplifies things
+        # Different registries mean different identities, unless we identify via SFA HRN or have associated the user email to a single hrn
+
+        context = super(WebSocketsView, self).get_context_data(**kwargs)
+
+        # XXX This is repeated in all pages
+        # more general variables expected in the template
+        context['title'] = 'SAMPLE WEBSOCKET PAGE',
+        # the menu items on the top
+        context['topmenu_items'] = topmenu_items('Dashboard', self.request) 
+        # so we can sho who is logged
+        context['username'] = the_user(self.request) 
+
+        return context
+
+
+class WebSockets2View(TemplateView):
+    template_name = "websockets2.html"
+
+    def get_context_data(self, **kwargs):
+        # We might have slices on different registries with different user accounts 
+        # We note that this portal could be specific to a given registry, to which we register users, but i'm not sure that simplifies things
+        # Different registries mean different identities, unless we identify via SFA HRN or have associated the user email to a single hrn
+
+        context = super(WebSockets2View, self).get_context_data(**kwargs)
+
+        # XXX This is repeated in all pages
+        # more general variables expected in the template
+        context['title'] = 'SAMPLE WEBSOCKET PAGE',
+        # the menu items on the top
+        context['topmenu_items'] = topmenu_items('Dashboard', self.request) 
+        # so we can sho who is logged
+        context['username'] = the_user(self.request) 
+
+        return context
+
index 04d8d54..459a7ca 120000 (symlink)
@@ -1 +1 @@
-bootstrap-2.3.1/
\ No newline at end of file
+bootstrap-3.0.0
\ No newline at end of file
diff --git a/third-party/bootstrap-3.0.0/css/bootstrap-theme.css b/third-party/bootstrap-3.0.0/css/bootstrap-theme.css
new file mode 100644 (file)
index 0000000..ad11735
--- /dev/null
@@ -0,0 +1,384 @@
+.btn-default,
+.btn-primary,
+.btn-success,
+.btn-info,
+.btn-warning,
+.btn-danger {
+  text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.2);
+  -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.15), 0 1px 1px rgba(0, 0, 0, 0.075);
+          box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.15), 0 1px 1px rgba(0, 0, 0, 0.075);
+}
+
+.btn-default:active,
+.btn-primary:active,
+.btn-success:active,
+.btn-info:active,
+.btn-warning:active,
+.btn-danger:active,
+.btn-default.active,
+.btn-primary.active,
+.btn-success.active,
+.btn-info.active,
+.btn-warning.active,
+.btn-danger.active {
+  -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
+          box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
+}
+
+.btn:active,
+.btn.active {
+  background-image: none;
+}
+
+.btn-default {
+  text-shadow: 0 1px 0 #fff;
+  background-image: -webkit-gradient(linear, left 0%, left 100%, from(#ffffff), to(#e6e6e6));
+  background-image: -webkit-linear-gradient(top, #ffffff, 0%, #e6e6e6, 100%);
+  background-image: -moz-linear-gradient(top, #ffffff 0%, #e6e6e6 100%);
+  background-image: linear-gradient(to bottom, #ffffff 0%, #e6e6e6 100%);
+  background-repeat: repeat-x;
+  border-color: #e0e0e0;
+  border-color: #ccc;
+  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe6e6e6', GradientType=0);
+}
+
+.btn-default:active,
+.btn-default.active {
+  background-color: #e6e6e6;
+  border-color: #e0e0e0;
+}
+
+.btn-primary {
+  background-image: -webkit-gradient(linear, left 0%, left 100%, from(#428bca), to(#3071a9));
+  background-image: -webkit-linear-gradient(top, #428bca, 0%, #3071a9, 100%);
+  background-image: -moz-linear-gradient(top, #428bca 0%, #3071a9 100%);
+  background-image: linear-gradient(to bottom, #428bca 0%, #3071a9 100%);
+  background-repeat: repeat-x;
+  border-color: #2d6ca2;
+  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca', endColorstr='#ff3071a9', GradientType=0);
+}
+
+.btn-primary:active,
+.btn-primary.active {
+  background-color: #3071a9;
+  border-color: #2d6ca2;
+}
+
+.btn-success {
+  background-image: -webkit-gradient(linear, left 0%, left 100%, from(#5cb85c), to(#449d44));
+  background-image: -webkit-linear-gradient(top, #5cb85c, 0%, #449d44, 100%);
+  background-image: -moz-linear-gradient(top, #5cb85c 0%, #449d44 100%);
+  background-image: linear-gradient(to bottom, #5cb85c 0%, #449d44 100%);
+  background-repeat: repeat-x;
+  border-color: #419641;
+  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5cb85c', endColorstr='#ff449d44', GradientType=0);
+}
+
+.btn-success:active,
+.btn-success.active {
+  background-color: #449d44;
+  border-color: #419641;
+}
+
+.btn-warning {
+  background-image: -webkit-gradient(linear, left 0%, left 100%, from(#f0ad4e), to(#ec971f));
+  background-image: -webkit-linear-gradient(top, #f0ad4e, 0%, #ec971f, 100%);
+  background-image: -moz-linear-gradient(top, #f0ad4e 0%, #ec971f 100%);
+  background-image: linear-gradient(to bottom, #f0ad4e 0%, #ec971f 100%);
+  background-repeat: repeat-x;
+  border-color: #eb9316;
+  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff0ad4e', endColorstr='#ffec971f', GradientType=0);
+}
+
+.btn-warning:active,
+.btn-warning.active {
+  background-color: #ec971f;
+  border-color: #eb9316;
+}
+
+.btn-danger {
+  background-image: -webkit-gradient(linear, left 0%, left 100%, from(#d9534f), to(#c9302c));
+  background-image: -webkit-linear-gradient(top, #d9534f, 0%, #c9302c, 100%);
+  background-image: -moz-linear-gradient(top, #d9534f 0%, #c9302c 100%);
+  background-image: linear-gradient(to bottom, #d9534f 0%, #c9302c 100%);
+  background-repeat: repeat-x;
+  border-color: #c12e2a;
+  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9534f', endColorstr='#ffc9302c', GradientType=0);
+}
+
+.btn-danger:active,
+.btn-danger.active {
+  background-color: #c9302c;
+  border-color: #c12e2a;
+}
+
+.btn-info {
+  background-image: -webkit-gradient(linear, left 0%, left 100%, from(#5bc0de), to(#31b0d5));
+  background-image: -webkit-linear-gradient(top, #5bc0de, 0%, #31b0d5, 100%);
+  background-image: -moz-linear-gradient(top, #5bc0de 0%, #31b0d5 100%);
+  background-image: linear-gradient(to bottom, #5bc0de 0%, #31b0d5 100%);
+  background-repeat: repeat-x;
+  border-color: #2aabd2;
+  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff31b0d5', GradientType=0);
+}
+
+.btn-info:active,
+.btn-info.active {
+  background-color: #31b0d5;
+  border-color: #2aabd2;
+}
+
+.thumbnail,
+.img-thumbnail {
+  -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.075);
+          box-shadow: 0 1px 2px rgba(0, 0, 0, 0.075);
+}
+
+.dropdown-menu > li > a:hover,
+.dropdown-menu > li > a:focus,
+.dropdown-menu > .active > a,
+.dropdown-menu > .active > a:hover,
+.dropdown-menu > .active > a:focus {
+  background-color: #357ebd;
+  background-image: -webkit-gradient(linear, left 0%, left 100%, from(#428bca), to(#357ebd));
+  background-image: -webkit-linear-gradient(top, #428bca, 0%, #357ebd, 100%);
+  background-image: -moz-linear-gradient(top, #428bca 0%, #357ebd 100%);
+  background-image: linear-gradient(to bottom, #428bca 0%, #357ebd 100%);
+  background-repeat: repeat-x;
+  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca', endColorstr='#ff357ebd', GradientType=0);
+}
+
+.navbar {
+  background-image: -webkit-gradient(linear, left 0%, left 100%, from(#ffffff), to(#f8f8f8));
+  background-image: -webkit-linear-gradient(top, #ffffff, 0%, #f8f8f8, 100%);
+  background-image: -moz-linear-gradient(top, #ffffff 0%, #f8f8f8 100%);
+  background-image: linear-gradient(to bottom, #ffffff 0%, #f8f8f8 100%);
+  background-repeat: repeat-x;
+  border-radius: 4px;
+  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#fff8f8f8', GradientType=0);
+  -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.15), 0 1px 5px rgba(0, 0, 0, 0.075);
+          box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.15), 0 1px 5px rgba(0, 0, 0, 0.075);
+}
+
+.navbar .navbar-nav > .active > a {
+  background-color: #f8f8f8;
+}
+
+.navbar-brand,
+.navbar-nav > li > a {
+  text-shadow: 0 1px 0 rgba(255, 255, 255, 0.25);
+}
+
+.navbar-inverse {
+  background-image: -webkit-gradient(linear, left 0%, left 100%, from(#3c3c3c), to(#222222));
+  background-image: -webkit-linear-gradient(top, #3c3c3c, 0%, #222222, 100%);
+  background-image: -moz-linear-gradient(top, #3c3c3c 0%, #222222 100%);
+  background-image: linear-gradient(to bottom, #3c3c3c 0%, #222222 100%);
+  background-repeat: repeat-x;
+  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff3c3c3c', endColorstr='#ff222222', GradientType=0);
+}
+
+.navbar-inverse .navbar-nav > .active > a {
+  background-color: #222222;
+}
+
+.navbar-inverse .navbar-brand,
+.navbar-inverse .navbar-nav > li > a {
+  text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);
+}
+
+.navbar-static-top,
+.navbar-fixed-top,
+.navbar-fixed-bottom {
+  border-radius: 0;
+}
+
+.alert {
+  text-shadow: 0 1px 0 rgba(255, 255, 255, 0.2);
+  -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.25), 0 1px 2px rgba(0, 0, 0, 0.05);
+          box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.25), 0 1px 2px rgba(0, 0, 0, 0.05);
+}
+
+.alert-success {
+  background-image: -webkit-gradient(linear, left 0%, left 100%, from(#dff0d8), to(#c8e5bc));
+  background-image: -webkit-linear-gradient(top, #dff0d8, 0%, #c8e5bc, 100%);
+  background-image: -moz-linear-gradient(top, #dff0d8 0%, #c8e5bc 100%);
+  background-image: linear-gradient(to bottom, #dff0d8 0%, #c8e5bc 100%);
+  background-repeat: repeat-x;
+  border-color: #b2dba1;
+  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdff0d8', endColorstr='#ffc8e5bc', GradientType=0);
+}
+
+.alert-info {
+  background-image: -webkit-gradient(linear, left 0%, left 100%, from(#d9edf7), to(#b9def0));
+  background-image: -webkit-linear-gradient(top, #d9edf7, 0%, #b9def0, 100%);
+  background-image: -moz-linear-gradient(top, #d9edf7 0%, #b9def0 100%);
+  background-image: linear-gradient(to bottom, #d9edf7 0%, #b9def0 100%);
+  background-repeat: repeat-x;
+  border-color: #9acfea;
+  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9edf7', endColorstr='#ffb9def0', GradientType=0);
+}
+
+.alert-warning {
+  background-image: -webkit-gradient(linear, left 0%, left 100%, from(#fcf8e3), to(#f8efc0));
+  background-image: -webkit-linear-gradient(top, #fcf8e3, 0%, #f8efc0, 100%);
+  background-image: -moz-linear-gradient(top, #fcf8e3 0%, #f8efc0 100%);
+  background-image: linear-gradient(to bottom, #fcf8e3 0%, #f8efc0 100%);
+  background-repeat: repeat-x;
+  border-color: #f5e79e;
+  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffcf8e3', endColorstr='#fff8efc0', GradientType=0);
+}
+
+.alert-danger {
+  background-image: -webkit-gradient(linear, left 0%, left 100%, from(#f2dede), to(#e7c3c3));
+  background-image: -webkit-linear-gradient(top, #f2dede, 0%, #e7c3c3, 100%);
+  background-image: -moz-linear-gradient(top, #f2dede 0%, #e7c3c3 100%);
+  background-image: linear-gradient(to bottom, #f2dede 0%, #e7c3c3 100%);
+  background-repeat: repeat-x;
+  border-color: #dca7a7;
+  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2dede', endColorstr='#ffe7c3c3', GradientType=0);
+}
+
+.progress {
+  background-image: -webkit-gradient(linear, left 0%, left 100%, from(#ebebeb), to(#f5f5f5));
+  background-image: -webkit-linear-gradient(top, #ebebeb, 0%, #f5f5f5, 100%);
+  background-image: -moz-linear-gradient(top, #ebebeb 0%, #f5f5f5 100%);
+  background-image: linear-gradient(to bottom, #ebebeb 0%, #f5f5f5 100%);
+  background-repeat: repeat-x;
+  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffebebeb', endColorstr='#fff5f5f5', GradientType=0);
+}
+
+.progress-bar {
+  background-image: -webkit-gradient(linear, left 0%, left 100%, from(#428bca), to(#3071a9));
+  background-image: -webkit-linear-gradient(top, #428bca, 0%, #3071a9, 100%);
+  background-image: -moz-linear-gradient(top, #428bca 0%, #3071a9 100%);
+  background-image: linear-gradient(to bottom, #428bca 0%, #3071a9 100%);
+  background-repeat: repeat-x;
+  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca', endColorstr='#ff3071a9', GradientType=0);
+}
+
+.progress-bar-success {
+  background-image: -webkit-gradient(linear, left 0%, left 100%, from(#5cb85c), to(#449d44));
+  background-image: -webkit-linear-gradient(top, #5cb85c, 0%, #449d44, 100%);
+  background-image: -moz-linear-gradient(top, #5cb85c 0%, #449d44 100%);
+  background-image: linear-gradient(to bottom, #5cb85c 0%, #449d44 100%);
+  background-repeat: repeat-x;
+  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5cb85c', endColorstr='#ff449d44', GradientType=0);
+}
+
+.progress-bar-info {
+  background-image: -webkit-gradient(linear, left 0%, left 100%, from(#5bc0de), to(#31b0d5));
+  background-image: -webkit-linear-gradient(top, #5bc0de, 0%, #31b0d5, 100%);
+  background-image: -moz-linear-gradient(top, #5bc0de 0%, #31b0d5 100%);
+  background-image: linear-gradient(to bottom, #5bc0de 0%, #31b0d5 100%);
+  background-repeat: repeat-x;
+  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff31b0d5', GradientType=0);
+}
+
+.progress-bar-warning {
+  background-image: -webkit-gradient(linear, left 0%, left 100%, from(#f0ad4e), to(#ec971f));
+  background-image: -webkit-linear-gradient(top, #f0ad4e, 0%, #ec971f, 100%);
+  background-image: -moz-linear-gradient(top, #f0ad4e 0%, #ec971f 100%);
+  background-image: linear-gradient(to bottom, #f0ad4e 0%, #ec971f 100%);
+  background-repeat: repeat-x;
+  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff0ad4e', endColorstr='#ffec971f', GradientType=0);
+}
+
+.progress-bar-danger {
+  background-image: -webkit-gradient(linear, left 0%, left 100%, from(#d9534f), to(#c9302c));
+  background-image: -webkit-linear-gradient(top, #d9534f, 0%, #c9302c, 100%);
+  background-image: -moz-linear-gradient(top, #d9534f 0%, #c9302c 100%);
+  background-image: linear-gradient(to bottom, #d9534f 0%, #c9302c 100%);
+  background-repeat: repeat-x;
+  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9534f', endColorstr='#ffc9302c', GradientType=0);
+}
+
+.list-group {
+  border-radius: 4px;
+  -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.075);
+          box-shadow: 0 1px 2px rgba(0, 0, 0, 0.075);
+}
+
+.list-group-item.active,
+.list-group-item.active:hover,
+.list-group-item.active:focus {
+  text-shadow: 0 -1px 0 #3071a9;
+  background-image: -webkit-gradient(linear, left 0%, left 100%, from(#428bca), to(#3278b3));
+  background-image: -webkit-linear-gradient(top, #428bca, 0%, #3278b3, 100%);
+  background-image: -moz-linear-gradient(top, #428bca 0%, #3278b3 100%);
+  background-image: linear-gradient(to bottom, #428bca 0%, #3278b3 100%);
+  background-repeat: repeat-x;
+  border-color: #3278b3;
+  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca', endColorstr='#ff3278b3', GradientType=0);
+}
+
+.panel {
+  -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
+          box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
+}
+
+.panel-default > .panel-heading {
+  background-image: -webkit-gradient(linear, left 0%, left 100%, from(#f5f5f5), to(#e8e8e8));
+  background-image: -webkit-linear-gradient(top, #f5f5f5, 0%, #e8e8e8, 100%);
+  background-image: -moz-linear-gradient(top, #f5f5f5 0%, #e8e8e8 100%);
+  background-image: linear-gradient(to bottom, #f5f5f5 0%, #e8e8e8 100%);
+  background-repeat: repeat-x;
+  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5', endColorstr='#ffe8e8e8', GradientType=0);
+}
+
+.panel-primary > .panel-heading {
+  background-image: -webkit-gradient(linear, left 0%, left 100%, from(#428bca), to(#357ebd));
+  background-image: -webkit-linear-gradient(top, #428bca, 0%, #357ebd, 100%);
+  background-image: -moz-linear-gradient(top, #428bca 0%, #357ebd 100%);
+  background-image: linear-gradient(to bottom, #428bca 0%, #357ebd 100%);
+  background-repeat: repeat-x;
+  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca', endColorstr='#ff357ebd', GradientType=0);
+}
+
+.panel-success > .panel-heading {
+  background-image: -webkit-gradient(linear, left 0%, left 100%, from(#dff0d8), to(#d0e9c6));
+  background-image: -webkit-linear-gradient(top, #dff0d8, 0%, #d0e9c6, 100%);
+  background-image: -moz-linear-gradient(top, #dff0d8 0%, #d0e9c6 100%);
+  background-image: linear-gradient(to bottom, #dff0d8 0%, #d0e9c6 100%);
+  background-repeat: repeat-x;
+  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdff0d8', endColorstr='#ffd0e9c6', GradientType=0);
+}
+
+.panel-info > .panel-heading {
+  background-image: -webkit-gradient(linear, left 0%, left 100%, from(#d9edf7), to(#c4e3f3));
+  background-image: -webkit-linear-gradient(top, #d9edf7, 0%, #c4e3f3, 100%);
+  background-image: -moz-linear-gradient(top, #d9edf7 0%, #c4e3f3 100%);
+  background-image: linear-gradient(to bottom, #d9edf7 0%, #c4e3f3 100%);
+  background-repeat: repeat-x;
+  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9edf7', endColorstr='#ffc4e3f3', GradientType=0);
+}
+
+.panel-warning > .panel-heading {
+  background-image: -webkit-gradient(linear, left 0%, left 100%, from(#fcf8e3), to(#faf2cc));
+  background-image: -webkit-linear-gradient(top, #fcf8e3, 0%, #faf2cc, 100%);
+  background-image: -moz-linear-gradient(top, #fcf8e3 0%, #faf2cc 100%);
+  background-image: linear-gradient(to bottom, #fcf8e3 0%, #faf2cc 100%);
+  background-repeat: repeat-x;
+  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffcf8e3', endColorstr='#fffaf2cc', GradientType=0);
+}
+
+.panel-danger > .panel-heading {
+  background-image: -webkit-gradient(linear, left 0%, left 100%, from(#f2dede), to(#ebcccc));
+  background-image: -webkit-linear-gradient(top, #f2dede, 0%, #ebcccc, 100%);
+  background-image: -moz-linear-gradient(top, #f2dede 0%, #ebcccc 100%);
+  background-image: linear-gradient(to bottom, #f2dede 0%, #ebcccc 100%);
+  background-repeat: repeat-x;
+  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2dede', endColorstr='#ffebcccc', GradientType=0);
+}
+
+.well {
+  background-image: -webkit-gradient(linear, left 0%, left 100%, from(#e8e8e8), to(#f5f5f5));
+  background-image: -webkit-linear-gradient(top, #e8e8e8, 0%, #f5f5f5, 100%);
+  background-image: -moz-linear-gradient(top, #e8e8e8 0%, #f5f5f5 100%);
+  background-image: linear-gradient(to bottom, #e8e8e8 0%, #f5f5f5 100%);
+  background-repeat: repeat-x;
+  border-color: #dcdcdc;
+  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffe8e8e8', endColorstr='#fff5f5f5', GradientType=0);
+  -webkit-box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.05), 0 1px 0 rgba(255, 255, 255, 0.1);
+          box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.05), 0 1px 0 rgba(255, 255, 255, 0.1);
+}
\ No newline at end of file
diff --git a/third-party/bootstrap-3.0.0/css/bootstrap-theme.min.css b/third-party/bootstrap-3.0.0/css/bootstrap-theme.min.css
new file mode 100644 (file)
index 0000000..cad36b4
--- /dev/null
@@ -0,0 +1 @@
+.btn-default,.btn-primary,.btn-success,.btn-info,.btn-warning,.btn-danger{text-shadow:0 -1px 0 rgba(0,0,0,0.2);-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.15),0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 0 rgba(255,255,255,0.15),0 1px 1px rgba(0,0,0,0.075)}.btn-default:active,.btn-primary:active,.btn-success:active,.btn-info:active,.btn-warning:active,.btn-danger:active,.btn-default.active,.btn-primary.active,.btn-success.active,.btn-info.active,.btn-warning.active,.btn-danger.active{-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,0.125);box-shadow:inset 0 3px 5px rgba(0,0,0,0.125)}.btn:active,.btn.active{background-image:none}.btn-default{text-shadow:0 1px 0 #fff;background-image:-webkit-gradient(linear,left 0,left 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,0%,#e6e6e6,100%);background-image:-moz-linear-gradient(top,#fff 0,#e6e6e6 100%);background-image:linear-gradient(to bottom,#fff 0,#e6e6e6 100%);background-repeat:repeat-x;border-color:#e0e0e0;border-color:#ccc;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffe6e6e6',GradientType=0)}.btn-default:active,.btn-default.active{background-color:#e6e6e6;border-color:#e0e0e0}.btn-primary{background-image:-webkit-gradient(linear,left 0,left 100%,from(#428bca),to(#3071a9));background-image:-webkit-linear-gradient(top,#428bca,0%,#3071a9,100%);background-image:-moz-linear-gradient(top,#428bca 0,#3071a9 100%);background-image:linear-gradient(to bottom,#428bca 0,#3071a9 100%);background-repeat:repeat-x;border-color:#2d6ca2;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca',endColorstr='#ff3071a9',GradientType=0)}.btn-primary:active,.btn-primary.active{background-color:#3071a9;border-color:#2d6ca2}.btn-success{background-image:-webkit-gradient(linear,left 0,left 100%,from(#5cb85c),to(#449d44));background-image:-webkit-linear-gradient(top,#5cb85c,0%,#449d44,100%);background-image:-moz-linear-gradient(top,#5cb85c 0,#449d44 100%);background-image:linear-gradient(to bottom,#5cb85c 0,#449d44 100%);background-repeat:repeat-x;border-color:#419641;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5cb85c',endColorstr='#ff449d44',GradientType=0)}.btn-success:active,.btn-success.active{background-color:#449d44;border-color:#419641}.btn-warning{background-image:-webkit-gradient(linear,left 0,left 100%,from(#f0ad4e),to(#ec971f));background-image:-webkit-linear-gradient(top,#f0ad4e,0%,#ec971f,100%);background-image:-moz-linear-gradient(top,#f0ad4e 0,#ec971f 100%);background-image:linear-gradient(to bottom,#f0ad4e 0,#ec971f 100%);background-repeat:repeat-x;border-color:#eb9316;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff0ad4e',endColorstr='#ffec971f',GradientType=0)}.btn-warning:active,.btn-warning.active{background-color:#ec971f;border-color:#eb9316}.btn-danger{background-image:-webkit-gradient(linear,left 0,left 100%,from(#d9534f),to(#c9302c));background-image:-webkit-linear-gradient(top,#d9534f,0%,#c9302c,100%);background-image:-moz-linear-gradient(top,#d9534f 0,#c9302c 100%);background-image:linear-gradient(to bottom,#d9534f 0,#c9302c 100%);background-repeat:repeat-x;border-color:#c12e2a;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9534f',endColorstr='#ffc9302c',GradientType=0)}.btn-danger:active,.btn-danger.active{background-color:#c9302c;border-color:#c12e2a}.btn-info{background-image:-webkit-gradient(linear,left 0,left 100%,from(#5bc0de),to(#31b0d5));background-image:-webkit-linear-gradient(top,#5bc0de,0%,#31b0d5,100%);background-image:-moz-linear-gradient(top,#5bc0de 0,#31b0d5 100%);background-image:linear-gradient(to bottom,#5bc0de 0,#31b0d5 100%);background-repeat:repeat-x;border-color:#2aabd2;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de',endColorstr='#ff31b0d5',GradientType=0)}.btn-info:active,.btn-info.active{background-color:#31b0d5;border-color:#2aabd2}.thumbnail,.img-thumbnail{-webkit-box-shadow:0 1px 2px rgba(0,0,0,0.075);box-shadow:0 1px 2px rgba(0,0,0,0.075)}.dropdown-menu>li>a:hover,.dropdown-menu>li>a:focus,.dropdown-menu>.active>a,.dropdown-menu>.active>a:hover,.dropdown-menu>.active>a:focus{background-color:#357ebd;background-image:-webkit-gradient(linear,left 0,left 100%,from(#428bca),to(#357ebd));background-image:-webkit-linear-gradient(top,#428bca,0%,#357ebd,100%);background-image:-moz-linear-gradient(top,#428bca 0,#357ebd 100%);background-image:linear-gradient(to bottom,#428bca 0,#357ebd 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca',endColorstr='#ff357ebd',GradientType=0)}.navbar{background-image:-webkit-gradient(linear,left 0,left 100%,from(#fff),to(#f8f8f8));background-image:-webkit-linear-gradient(top,#fff,0%,#f8f8f8,100%);background-image:-moz-linear-gradient(top,#fff 0,#f8f8f8 100%);background-image:linear-gradient(to bottom,#fff 0,#f8f8f8 100%);background-repeat:repeat-x;border-radius:4px;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#fff8f8f8',GradientType=0);-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.15),0 1px 5px rgba(0,0,0,0.075);box-shadow:inset 0 1px 0 rgba(255,255,255,0.15),0 1px 5px rgba(0,0,0,0.075)}.navbar .navbar-nav>.active>a{background-color:#f8f8f8}.navbar-brand,.navbar-nav>li>a{text-shadow:0 1px 0 rgba(255,255,255,0.25)}.navbar-inverse{background-image:-webkit-gradient(linear,left 0,left 100%,from(#3c3c3c),to(#222));background-image:-webkit-linear-gradient(top,#3c3c3c,0%,#222,100%);background-image:-moz-linear-gradient(top,#3c3c3c 0,#222 100%);background-image:linear-gradient(to bottom,#3c3c3c 0,#222 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff3c3c3c',endColorstr='#ff222222',GradientType=0)}.navbar-inverse .navbar-nav>.active>a{background-color:#222}.navbar-inverse .navbar-brand,.navbar-inverse .navbar-nav>li>a{text-shadow:0 -1px 0 rgba(0,0,0,0.25)}.navbar-static-top,.navbar-fixed-top,.navbar-fixed-bottom{border-radius:0}.alert{text-shadow:0 1px 0 rgba(255,255,255,0.2);-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.25),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 1px 0 rgba(255,255,255,0.25),0 1px 2px rgba(0,0,0,0.05)}.alert-success{background-image:-webkit-gradient(linear,left 0,left 100%,from(#dff0d8),to(#c8e5bc));background-image:-webkit-linear-gradient(top,#dff0d8,0%,#c8e5bc,100%);background-image:-moz-linear-gradient(top,#dff0d8 0,#c8e5bc 100%);background-image:linear-gradient(to bottom,#dff0d8 0,#c8e5bc 100%);background-repeat:repeat-x;border-color:#b2dba1;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdff0d8',endColorstr='#ffc8e5bc',GradientType=0)}.alert-info{background-image:-webkit-gradient(linear,left 0,left 100%,from(#d9edf7),to(#b9def0));background-image:-webkit-linear-gradient(top,#d9edf7,0%,#b9def0,100%);background-image:-moz-linear-gradient(top,#d9edf7 0,#b9def0 100%);background-image:linear-gradient(to bottom,#d9edf7 0,#b9def0 100%);background-repeat:repeat-x;border-color:#9acfea;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9edf7',endColorstr='#ffb9def0',GradientType=0)}.alert-warning{background-image:-webkit-gradient(linear,left 0,left 100%,from(#fcf8e3),to(#f8efc0));background-image:-webkit-linear-gradient(top,#fcf8e3,0%,#f8efc0,100%);background-image:-moz-linear-gradient(top,#fcf8e3 0,#f8efc0 100%);background-image:linear-gradient(to bottom,#fcf8e3 0,#f8efc0 100%);background-repeat:repeat-x;border-color:#f5e79e;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffcf8e3',endColorstr='#fff8efc0',GradientType=0)}.alert-danger{background-image:-webkit-gradient(linear,left 0,left 100%,from(#f2dede),to(#e7c3c3));background-image:-webkit-linear-gradient(top,#f2dede,0%,#e7c3c3,100%);background-image:-moz-linear-gradient(top,#f2dede 0,#e7c3c3 100%);background-image:linear-gradient(to bottom,#f2dede 0,#e7c3c3 100%);background-repeat:repeat-x;border-color:#dca7a7;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2dede',endColorstr='#ffe7c3c3',GradientType=0)}.progress{background-image:-webkit-gradient(linear,left 0,left 100%,from(#ebebeb),to(#f5f5f5));background-image:-webkit-linear-gradient(top,#ebebeb,0%,#f5f5f5,100%);background-image:-moz-linear-gradient(top,#ebebeb 0,#f5f5f5 100%);background-image:linear-gradient(to bottom,#ebebeb 0,#f5f5f5 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffebebeb',endColorstr='#fff5f5f5',GradientType=0)}.progress-bar{background-image:-webkit-gradient(linear,left 0,left 100%,from(#428bca),to(#3071a9));background-image:-webkit-linear-gradient(top,#428bca,0%,#3071a9,100%);background-image:-moz-linear-gradient(top,#428bca 0,#3071a9 100%);background-image:linear-gradient(to bottom,#428bca 0,#3071a9 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca',endColorstr='#ff3071a9',GradientType=0)}.progress-bar-success{background-image:-webkit-gradient(linear,left 0,left 100%,from(#5cb85c),to(#449d44));background-image:-webkit-linear-gradient(top,#5cb85c,0%,#449d44,100%);background-image:-moz-linear-gradient(top,#5cb85c 0,#449d44 100%);background-image:linear-gradient(to bottom,#5cb85c 0,#449d44 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5cb85c',endColorstr='#ff449d44',GradientType=0)}.progress-bar-info{background-image:-webkit-gradient(linear,left 0,left 100%,from(#5bc0de),to(#31b0d5));background-image:-webkit-linear-gradient(top,#5bc0de,0%,#31b0d5,100%);background-image:-moz-linear-gradient(top,#5bc0de 0,#31b0d5 100%);background-image:linear-gradient(to bottom,#5bc0de 0,#31b0d5 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de',endColorstr='#ff31b0d5',GradientType=0)}.progress-bar-warning{background-image:-webkit-gradient(linear,left 0,left 100%,from(#f0ad4e),to(#ec971f));background-image:-webkit-linear-gradient(top,#f0ad4e,0%,#ec971f,100%);background-image:-moz-linear-gradient(top,#f0ad4e 0,#ec971f 100%);background-image:linear-gradient(to bottom,#f0ad4e 0,#ec971f 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff0ad4e',endColorstr='#ffec971f',GradientType=0)}.progress-bar-danger{background-image:-webkit-gradient(linear,left 0,left 100%,from(#d9534f),to(#c9302c));background-image:-webkit-linear-gradient(top,#d9534f,0%,#c9302c,100%);background-image:-moz-linear-gradient(top,#d9534f 0,#c9302c 100%);background-image:linear-gradient(to bottom,#d9534f 0,#c9302c 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9534f',endColorstr='#ffc9302c',GradientType=0)}.list-group{border-radius:4px;-webkit-box-shadow:0 1px 2px rgba(0,0,0,0.075);box-shadow:0 1px 2px rgba(0,0,0,0.075)}.list-group-item.active,.list-group-item.active:hover,.list-group-item.active:focus{text-shadow:0 -1px 0 #3071a9;background-image:-webkit-gradient(linear,left 0,left 100%,from(#428bca),to(#3278b3));background-image:-webkit-linear-gradient(top,#428bca,0%,#3278b3,100%);background-image:-moz-linear-gradient(top,#428bca 0,#3278b3 100%);background-image:linear-gradient(to bottom,#428bca 0,#3278b3 100%);background-repeat:repeat-x;border-color:#3278b3;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca',endColorstr='#ff3278b3',GradientType=0)}.panel{-webkit-box-shadow:0 1px 2px rgba(0,0,0,0.05);box-shadow:0 1px 2px rgba(0,0,0,0.05)}.panel-default>.panel-heading{background-image:-webkit-gradient(linear,left 0,left 100%,from(#f5f5f5),to(#e8e8e8));background-image:-webkit-linear-gradient(top,#f5f5f5,0%,#e8e8e8,100%);background-image:-moz-linear-gradient(top,#f5f5f5 0,#e8e8e8 100%);background-image:linear-gradient(to bottom,#f5f5f5 0,#e8e8e8 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5',endColorstr='#ffe8e8e8',GradientType=0)}.panel-primary>.panel-heading{background-image:-webkit-gradient(linear,left 0,left 100%,from(#428bca),to(#357ebd));background-image:-webkit-linear-gradient(top,#428bca,0%,#357ebd,100%);background-image:-moz-linear-gradient(top,#428bca 0,#357ebd 100%);background-image:linear-gradient(to bottom,#428bca 0,#357ebd 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca',endColorstr='#ff357ebd',GradientType=0)}.panel-success>.panel-heading{background-image:-webkit-gradient(linear,left 0,left 100%,from(#dff0d8),to(#d0e9c6));background-image:-webkit-linear-gradient(top,#dff0d8,0%,#d0e9c6,100%);background-image:-moz-linear-gradient(top,#dff0d8 0,#d0e9c6 100%);background-image:linear-gradient(to bottom,#dff0d8 0,#d0e9c6 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdff0d8',endColorstr='#ffd0e9c6',GradientType=0)}.panel-info>.panel-heading{background-image:-webkit-gradient(linear,left 0,left 100%,from(#d9edf7),to(#c4e3f3));background-image:-webkit-linear-gradient(top,#d9edf7,0%,#c4e3f3,100%);background-image:-moz-linear-gradient(top,#d9edf7 0,#c4e3f3 100%);background-image:linear-gradient(to bottom,#d9edf7 0,#c4e3f3 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9edf7',endColorstr='#ffc4e3f3',GradientType=0)}.panel-warning>.panel-heading{background-image:-webkit-gradient(linear,left 0,left 100%,from(#fcf8e3),to(#faf2cc));background-image:-webkit-linear-gradient(top,#fcf8e3,0%,#faf2cc,100%);background-image:-moz-linear-gradient(top,#fcf8e3 0,#faf2cc 100%);background-image:linear-gradient(to bottom,#fcf8e3 0,#faf2cc 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffcf8e3',endColorstr='#fffaf2cc',GradientType=0)}.panel-danger>.panel-heading{background-image:-webkit-gradient(linear,left 0,left 100%,from(#f2dede),to(#ebcccc));background-image:-webkit-linear-gradient(top,#f2dede,0%,#ebcccc,100%);background-image:-moz-linear-gradient(top,#f2dede 0,#ebcccc 100%);background-image:linear-gradient(to bottom,#f2dede 0,#ebcccc 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2dede',endColorstr='#ffebcccc',GradientType=0)}.well{background-image:-webkit-gradient(linear,left 0,left 100%,from(#e8e8e8),to(#f5f5f5));background-image:-webkit-linear-gradient(top,#e8e8e8,0%,#f5f5f5,100%);background-image:-moz-linear-gradient(top,#e8e8e8 0,#f5f5f5 100%);background-image:linear-gradient(to bottom,#e8e8e8 0,#f5f5f5 100%);background-repeat:repeat-x;border-color:#dcdcdc;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffe8e8e8',endColorstr='#fff5f5f5',GradientType=0);-webkit-box-shadow:inset 0 1px 3px rgba(0,0,0,0.05),0 1px 0 rgba(255,255,255,0.1);box-shadow:inset 0 1px 3px rgba(0,0,0,0.05),0 1px 0 rgba(255,255,255,0.1)}
\ No newline at end of file
diff --git a/third-party/bootstrap-3.0.0/css/bootstrap.css b/third-party/bootstrap-3.0.0/css/bootstrap.css
new file mode 100644 (file)
index 0000000..bbda4ee
--- /dev/null
@@ -0,0 +1,6805 @@
+/*!
+ * Bootstrap v3.0.0
+ *
+ * Copyright 2013 Twitter, Inc
+ * Licensed under the Apache License v2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Designed and built with all the love in the world by @mdo and @fat.
+ */
+
+/*! normalize.css v2.1.0 | MIT License | git.io/normalize */
+
+article,
+aside,
+details,
+figcaption,
+figure,
+footer,
+header,
+hgroup,
+main,
+nav,
+section,
+summary {
+  display: block;
+}
+
+audio,
+canvas,
+video {
+  display: inline-block;
+}
+
+audio:not([controls]) {
+  display: none;
+  height: 0;
+}
+
+[hidden] {
+  display: none;
+}
+
+html {
+  font-family: sans-serif;
+  -webkit-text-size-adjust: 100%;
+      -ms-text-size-adjust: 100%;
+}
+
+body {
+  margin: 0;
+}
+
+a:focus {
+  outline: thin dotted;
+}
+
+a:active,
+a:hover {
+  outline: 0;
+}
+
+h1 {
+  margin: 0.67em 0;
+  font-size: 2em;
+}
+
+abbr[title] {
+  border-bottom: 1px dotted;
+}
+
+b,
+strong {
+  font-weight: bold;
+}
+
+dfn {
+  font-style: italic;
+}
+
+hr {
+  height: 0;
+  -moz-box-sizing: content-box;
+       box-sizing: content-box;
+}
+
+mark {
+  color: #000;
+  background: #ff0;
+}
+
+code,
+kbd,
+pre,
+samp {
+  font-family: monospace, serif;
+  font-size: 1em;
+}
+
+pre {
+  white-space: pre-wrap;
+}
+
+q {
+  quotes: "\201C" "\201D" "\2018" "\2019";
+}
+
+small {
+  font-size: 80%;
+}
+
+sub,
+sup {
+  position: relative;
+  font-size: 75%;
+  line-height: 0;
+  vertical-align: baseline;
+}
+
+sup {
+  top: -0.5em;
+}
+
+sub {
+  bottom: -0.25em;
+}
+
+img {
+  border: 0;
+}
+
+svg:not(:root) {
+  overflow: hidden;
+}
+
+figure {
+  margin: 0;
+}
+
+fieldset {
+  padding: 0.35em 0.625em 0.75em;
+  margin: 0 2px;
+  border: 1px solid #c0c0c0;
+}
+
+legend {
+  padding: 0;
+  border: 0;
+}
+
+button,
+input,
+select,
+textarea {
+  margin: 0;
+  font-family: inherit;
+  font-size: 100%;
+}
+
+button,
+input {
+  line-height: normal;
+}
+
+button,
+select {
+  text-transform: none;
+}
+
+button,
+html input[type="button"],
+input[type="reset"],
+input[type="submit"] {
+  cursor: pointer;
+  -webkit-appearance: button;
+}
+
+button[disabled],
+html input[disabled] {
+  cursor: default;
+}
+
+input[type="checkbox"],
+input[type="radio"] {
+  padding: 0;
+  box-sizing: border-box;
+}
+
+input[type="search"] {
+  -webkit-box-sizing: content-box;
+     -moz-box-sizing: content-box;
+          box-sizing: content-box;
+  -webkit-appearance: textfield;
+}
+
+input[type="search"]::-webkit-search-cancel-button,
+input[type="search"]::-webkit-search-decoration {
+  -webkit-appearance: none;
+}
+
+button::-moz-focus-inner,
+input::-moz-focus-inner {
+  padding: 0;
+  border: 0;
+}
+
+textarea {
+  overflow: auto;
+  vertical-align: top;
+}
+
+table {
+  border-collapse: collapse;
+  border-spacing: 0;
+}
+
+@media print {
+  * {
+    color: #000 !important;
+    text-shadow: none !important;
+    background: transparent !important;
+    box-shadow: none !important;
+  }
+  a,
+  a:visited {
+    text-decoration: underline;
+  }
+  a[href]:after {
+    content: " (" attr(href) ")";
+  }
+  abbr[title]:after {
+    content: " (" attr(title) ")";
+  }
+  .ir a:after,
+  a[href^="javascript:"]:after,
+  a[href^="#"]:after {
+    content: "";
+  }
+  pre,
+  blockquote {
+    border: 1px solid #999;
+    page-break-inside: avoid;
+  }
+  thead {
+    display: table-header-group;
+  }
+  tr,
+  img {
+    page-break-inside: avoid;
+  }
+  img {
+    max-width: 100% !important;
+  }
+  @page  {
+    margin: 2cm .5cm;
+  }
+  p,
+  h2,
+  h3 {
+    orphans: 3;
+    widows: 3;
+  }
+  h2,
+  h3 {
+    page-break-after: avoid;
+  }
+  .navbar {
+    display: none;
+  }
+  .table td,
+  .table th {
+    background-color: #fff !important;
+  }
+  .btn > .caret,
+  .dropup > .btn > .caret {
+    border-top-color: #000 !important;
+  }
+  .label {
+    border: 1px solid #000;
+  }
+  .table {
+    border-collapse: collapse !important;
+  }
+  .table-bordered th,
+  .table-bordered td {
+    border: 1px solid #ddd !important;
+  }
+}
+
+*,
+*:before,
+*:after {
+  -webkit-box-sizing: border-box;
+     -moz-box-sizing: border-box;
+          box-sizing: border-box;
+}
+
+html {
+  font-size: 62.5%;
+  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
+}
+
+body {
+  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
+  font-size: 14px;
+  line-height: 1.428571429;
+  color: #333333;
+  background-color: #ffffff;
+}
+
+input,
+button,
+select,
+textarea {
+  font-family: inherit;
+  font-size: inherit;
+  line-height: inherit;
+}
+
+button,
+input,
+select[multiple],
+textarea {
+  background-image: none;
+}
+
+a {
+  color: #428bca;
+  text-decoration: none;
+}
+
+a:hover,
+a:focus {
+  color: #2a6496;
+  text-decoration: underline;
+}
+
+a:focus {
+  outline: thin dotted #333;
+  outline: 5px auto -webkit-focus-ring-color;
+  outline-offset: -2px;
+}
+
+img {
+  vertical-align: middle;
+}
+
+.img-responsive {
+  display: block;
+  height: auto;
+  max-width: 100%;
+}
+
+.img-rounded {
+  border-radius: 6px;
+}
+
+.img-thumbnail {
+  display: inline-block;
+  height: auto;
+  max-width: 100%;
+  padding: 4px;
+  line-height: 1.428571429;
+  background-color: #ffffff;
+  border: 1px solid #dddddd;
+  border-radius: 4px;
+  -webkit-transition: all 0.2s ease-in-out;
+          transition: all 0.2s ease-in-out;
+}
+
+.img-circle {
+  border-radius: 50%;
+}
+
+hr {
+  margin-top: 20px;
+  margin-bottom: 20px;
+  border: 0;
+  border-top: 1px solid #eeeeee;
+}
+
+.sr-only {
+  position: absolute;
+  width: 1px;
+  height: 1px;
+  padding: 0;
+  margin: -1px;
+  overflow: hidden;
+  clip: rect(0 0 0 0);
+  border: 0;
+}
+
+p {
+  margin: 0 0 10px;
+}
+
+.lead {
+  margin-bottom: 20px;
+  font-size: 16.099999999999998px;
+  font-weight: 200;
+  line-height: 1.4;
+}
+
+@media (min-width: 768px) {
+  .lead {
+    font-size: 21px;
+  }
+}
+
+small {
+  font-size: 85%;
+}
+
+cite {
+  font-style: normal;
+}
+
+.text-muted {
+  color: #999999;
+}
+
+.text-primary {
+  color: #428bca;
+}
+
+.text-warning {
+  color: #c09853;
+}
+
+.text-danger {
+  color: #b94a48;
+}
+
+.text-success {
+  color: #468847;
+}
+
+.text-info {
+  color: #3a87ad;
+}
+
+.text-left {
+  text-align: left;
+}
+
+.text-right {
+  text-align: right;
+}
+
+.text-center {
+  text-align: center;
+}
+
+h1,
+h2,
+h3,
+h4,
+h5,
+h6,
+.h1,
+.h2,
+.h3,
+.h4,
+.h5,
+.h6 {
+  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
+  font-weight: 500;
+  line-height: 1.1;
+}
+
+h1 small,
+h2 small,
+h3 small,
+h4 small,
+h5 small,
+h6 small,
+.h1 small,
+.h2 small,
+.h3 small,
+.h4 small,
+.h5 small,
+.h6 small {
+  font-weight: normal;
+  line-height: 1;
+  color: #999999;
+}
+
+h1,
+h2,
+h3 {
+  margin-top: 20px;
+  margin-bottom: 10px;
+}
+
+h4,
+h5,
+h6 {
+  margin-top: 10px;
+  margin-bottom: 10px;
+}
+
+h1,
+.h1 {
+  font-size: 36px;
+}
+
+h2,
+.h2 {
+  font-size: 30px;
+}
+
+h3,
+.h3 {
+  font-size: 24px;
+}
+
+h4,
+.h4 {
+  font-size: 18px;
+}
+
+h5,
+.h5 {
+  font-size: 14px;
+}
+
+h6,
+.h6 {
+  font-size: 12px;
+}
+
+h1 small,
+.h1 small {
+  font-size: 24px;
+}
+
+h2 small,
+.h2 small {
+  font-size: 18px;
+}
+
+h3 small,
+.h3 small,
+h4 small,
+.h4 small {
+  font-size: 14px;
+}
+
+.page-header {
+  padding-bottom: 9px;
+  margin: 40px 0 20px;
+  border-bottom: 1px solid #eeeeee;
+}
+
+ul,
+ol {
+  margin-top: 0;
+  margin-bottom: 10px;
+}
+
+ul ul,
+ol ul,
+ul ol,
+ol ol {
+  margin-bottom: 0;
+}
+
+.list-unstyled {
+  padding-left: 0;
+  list-style: none;
+}
+
+.list-inline {
+  padding-left: 0;
+  list-style: none;
+}
+
+.list-inline > li {
+  display: inline-block;
+  padding-right: 5px;
+  padding-left: 5px;
+}
+
+dl {
+  margin-bottom: 20px;
+}
+
+dt,
+dd {
+  line-height: 1.428571429;
+}
+
+dt {
+  font-weight: bold;
+}
+
+dd {
+  margin-left: 0;
+}
+
+@media (min-width: 768px) {
+  .dl-horizontal dt {
+    float: left;
+    width: 160px;
+    overflow: hidden;
+    clear: left;
+    text-align: right;
+    text-overflow: ellipsis;
+    white-space: nowrap;
+  }
+  .dl-horizontal dd {
+    margin-left: 180px;
+  }
+  .dl-horizontal dd:before,
+  .dl-horizontal dd:after {
+    display: table;
+    content: " ";
+  }
+  .dl-horizontal dd:after {
+    clear: both;
+  }
+  .dl-horizontal dd:before,
+  .dl-horizontal dd:after {
+    display: table;
+    content: " ";
+  }
+  .dl-horizontal dd:after {
+    clear: both;
+  }
+}
+
+abbr[title],
+abbr[data-original-title] {
+  cursor: help;
+  border-bottom: 1px dotted #999999;
+}
+
+abbr.initialism {
+  font-size: 90%;
+  text-transform: uppercase;
+}
+
+blockquote {
+  padding: 10px 20px;
+  margin: 0 0 20px;
+  border-left: 5px solid #eeeeee;
+}
+
+blockquote p {
+  font-size: 17.5px;
+  font-weight: 300;
+  line-height: 1.25;
+}
+
+blockquote p:last-child {
+  margin-bottom: 0;
+}
+
+blockquote small {
+  display: block;
+  line-height: 1.428571429;
+  color: #999999;
+}
+
+blockquote small:before {
+  content: '\2014 \00A0';
+}
+
+blockquote.pull-right {
+  padding-right: 15px;
+  padding-left: 0;
+  border-right: 5px solid #eeeeee;
+  border-left: 0;
+}
+
+blockquote.pull-right p,
+blockquote.pull-right small {
+  text-align: right;
+}
+
+blockquote.pull-right small:before {
+  content: '';
+}
+
+blockquote.pull-right small:after {
+  content: '\00A0 \2014';
+}
+
+q:before,
+q:after,
+blockquote:before,
+blockquote:after {
+  content: "";
+}
+
+address {
+  display: block;
+  margin-bottom: 20px;
+  font-style: normal;
+  line-height: 1.428571429;
+}
+
+code,
+pre {
+  font-family: Monaco, Menlo, Consolas, "Courier New", monospace;
+}
+
+code {
+  padding: 2px 4px;
+  font-size: 90%;
+  color: #c7254e;
+  white-space: nowrap;
+  background-color: #f9f2f4;
+  border-radius: 4px;
+}
+
+pre {
+  display: block;
+  padding: 9.5px;
+  margin: 0 0 10px;
+  font-size: 13px;
+  line-height: 1.428571429;
+  color: #333333;
+  word-break: break-all;
+  word-wrap: break-word;
+  background-color: #f5f5f5;
+  border: 1px solid #cccccc;
+  border-radius: 4px;
+}
+
+pre.prettyprint {
+  margin-bottom: 20px;
+}
+
+pre code {
+  padding: 0;
+  font-size: inherit;
+  color: inherit;
+  white-space: pre-wrap;
+  background-color: transparent;
+  border: 0;
+}
+
+.pre-scrollable {
+  max-height: 340px;
+  overflow-y: scroll;
+}
+
+.container {
+  padding-right: 15px;
+  padding-left: 15px;
+  margin-right: auto;
+  margin-left: auto;
+}
+
+.container:before,
+.container:after {
+  display: table;
+  content: " ";
+}
+
+.container:after {
+  clear: both;
+}
+
+.container:before,
+.container:after {
+  display: table;
+  content: " ";
+}
+
+.container:after {
+  clear: both;
+}
+
+.row {
+  margin-right: -15px;
+  margin-left: -15px;
+}
+
+.row:before,
+.row:after {
+  display: table;
+  content: " ";
+}
+
+.row:after {
+  clear: both;
+}
+
+.row:before,
+.row:after {
+  display: table;
+  content: " ";
+}
+
+.row:after {
+  clear: both;
+}
+
+.col-xs-1,
+.col-xs-2,
+.col-xs-3,
+.col-xs-4,
+.col-xs-5,
+.col-xs-6,
+.col-xs-7,
+.col-xs-8,
+.col-xs-9,
+.col-xs-10,
+.col-xs-11,
+.col-xs-12,
+.col-sm-1,
+.col-sm-2,
+.col-sm-3,
+.col-sm-4,
+.col-sm-5,
+.col-sm-6,
+.col-sm-7,
+.col-sm-8,
+.col-sm-9,
+.col-sm-10,
+.col-sm-11,
+.col-sm-12,
+.col-md-1,
+.col-md-2,
+.col-md-3,
+.col-md-4,
+.col-md-5,
+.col-md-6,
+.col-md-7,
+.col-md-8,
+.col-md-9,
+.col-md-10,
+.col-md-11,
+.col-md-12,
+.col-lg-1,
+.col-lg-2,
+.col-lg-3,
+.col-lg-4,
+.col-lg-5,
+.col-lg-6,
+.col-lg-7,
+.col-lg-8,
+.col-lg-9,
+.col-lg-10,
+.col-lg-11,
+.col-lg-12 {
+  position: relative;
+  min-height: 1px;
+  padding-right: 15px;
+  padding-left: 15px;
+}
+
+.col-xs-1,
+.col-xs-2,
+.col-xs-3,
+.col-xs-4,
+.col-xs-5,
+.col-xs-6,
+.col-xs-7,
+.col-xs-8,
+.col-xs-9,
+.col-xs-10,
+.col-xs-11 {
+  float: left;
+}
+
+.col-xs-1 {
+  width: 8.333333333333332%;
+}
+
+.col-xs-2 {
+  width: 16.666666666666664%;
+}
+
+.col-xs-3 {
+  width: 25%;
+}
+
+.col-xs-4 {
+  width: 33.33333333333333%;
+}
+
+.col-xs-5 {
+  width: 41.66666666666667%;
+}
+
+.col-xs-6 {
+  width: 50%;
+}
+
+.col-xs-7 {
+  width: 58.333333333333336%;
+}
+
+.col-xs-8 {
+  width: 66.66666666666666%;
+}
+
+.col-xs-9 {
+  width: 75%;
+}
+
+.col-xs-10 {
+  width: 83.33333333333334%;
+}
+
+.col-xs-11 {
+  width: 91.66666666666666%;
+}
+
+.col-xs-12 {
+  width: 100%;
+}
+
+@media (min-width: 768px) {
+  .container {
+    max-width: 750px;
+  }
+  .col-sm-1,
+  .col-sm-2,
+  .col-sm-3,
+  .col-sm-4,
+  .col-sm-5,
+  .col-sm-6,
+  .col-sm-7,
+  .col-sm-8,
+  .col-sm-9,
+  .col-sm-10,
+  .col-sm-11 {
+    float: left;
+  }
+  .col-sm-1 {
+    width: 8.333333333333332%;
+  }
+  .col-sm-2 {
+    width: 16.666666666666664%;
+  }
+  .col-sm-3 {
+    width: 25%;
+  }
+  .col-sm-4 {
+    width: 33.33333333333333%;
+  }
+  .col-sm-5 {
+    width: 41.66666666666667%;
+  }
+  .col-sm-6 {
+    width: 50%;
+  }
+  .col-sm-7 {
+    width: 58.333333333333336%;
+  }
+  .col-sm-8 {
+    width: 66.66666666666666%;
+  }
+  .col-sm-9 {
+    width: 75%;
+  }
+  .col-sm-10 {
+    width: 83.33333333333334%;
+  }
+  .col-sm-11 {
+    width: 91.66666666666666%;
+  }
+  .col-sm-12 {
+    width: 100%;
+  }
+  .col-sm-push-1 {
+    left: 8.333333333333332%;
+  }
+  .col-sm-push-2 {
+    left: 16.666666666666664%;
+  }
+  .col-sm-push-3 {
+    left: 25%;
+  }
+  .col-sm-push-4 {
+    left: 33.33333333333333%;
+  }
+  .col-sm-push-5 {
+    left: 41.66666666666667%;
+  }
+  .col-sm-push-6 {
+    left: 50%;
+  }
+  .col-sm-push-7 {
+    left: 58.333333333333336%;
+  }
+  .col-sm-push-8 {
+    left: 66.66666666666666%;
+  }
+  .col-sm-push-9 {
+    left: 75%;
+  }
+  .col-sm-push-10 {
+    left: 83.33333333333334%;
+  }
+  .col-sm-push-11 {
+    left: 91.66666666666666%;
+  }
+  .col-sm-pull-1 {
+    right: 8.333333333333332%;
+  }
+  .col-sm-pull-2 {
+    right: 16.666666666666664%;
+  }
+  .col-sm-pull-3 {
+    right: 25%;
+  }
+  .col-sm-pull-4 {
+    right: 33.33333333333333%;
+  }
+  .col-sm-pull-5 {
+    right: 41.66666666666667%;
+  }
+  .col-sm-pull-6 {
+    right: 50%;
+  }
+  .col-sm-pull-7 {
+    right: 58.333333333333336%;
+  }
+  .col-sm-pull-8 {
+    right: 66.66666666666666%;
+  }
+  .col-sm-pull-9 {
+    right: 75%;
+  }
+  .col-sm-pull-10 {
+    right: 83.33333333333334%;
+  }
+  .col-sm-pull-11 {
+    right: 91.66666666666666%;
+  }
+  .col-sm-offset-1 {
+    margin-left: 8.333333333333332%;
+  }
+  .col-sm-offset-2 {
+    margin-left: 16.666666666666664%;
+  }
+  .col-sm-offset-3 {
+    margin-left: 25%;
+  }
+  .col-sm-offset-4 {
+    margin-left: 33.33333333333333%;
+  }
+  .col-sm-offset-5 {
+    margin-left: 41.66666666666667%;
+  }
+  .col-sm-offset-6 {
+    margin-left: 50%;
+  }
+  .col-sm-offset-7 {
+    margin-left: 58.333333333333336%;
+  }
+  .col-sm-offset-8 {
+    margin-left: 66.66666666666666%;
+  }
+  .col-sm-offset-9 {
+    margin-left: 75%;
+  }
+  .col-sm-offset-10 {
+    margin-left: 83.33333333333334%;
+  }
+  .col-sm-offset-11 {
+    margin-left: 91.66666666666666%;
+  }
+}
+
+@media (min-width: 992px) {
+  .container {
+    max-width: 970px;
+  }
+  .col-md-1,
+  .col-md-2,
+  .col-md-3,
+  .col-md-4,
+  .col-md-5,
+  .col-md-6,
+  .col-md-7,
+  .col-md-8,
+  .col-md-9,
+  .col-md-10,
+  .col-md-11 {
+    float: left;
+  }
+  .col-md-1 {
+    width: 8.333333333333332%;
+  }
+  .col-md-2 {
+    width: 16.666666666666664%;
+  }
+  .col-md-3 {
+    width: 25%;
+  }
+  .col-md-4 {
+    width: 33.33333333333333%;
+  }
+  .col-md-5 {
+    width: 41.66666666666667%;
+  }
+  .col-md-6 {
+    width: 50%;
+  }
+  .col-md-7 {
+    width: 58.333333333333336%;
+  }
+  .col-md-8 {
+    width: 66.66666666666666%;
+  }
+  .col-md-9 {
+    width: 75%;
+  }
+  .col-md-10 {
+    width: 83.33333333333334%;
+  }
+  .col-md-11 {
+    width: 91.66666666666666%;
+  }
+  .col-md-12 {
+    width: 100%;
+  }
+  .col-md-push-0 {
+    left: auto;
+  }
+  .col-md-push-1 {
+    left: 8.333333333333332%;
+  }
+  .col-md-push-2 {
+    left: 16.666666666666664%;
+  }
+  .col-md-push-3 {
+    left: 25%;
+  }
+  .col-md-push-4 {
+    left: 33.33333333333333%;
+  }
+  .col-md-push-5 {
+    left: 41.66666666666667%;
+  }
+  .col-md-push-6 {
+    left: 50%;
+  }
+  .col-md-push-7 {
+    left: 58.333333333333336%;
+  }
+  .col-md-push-8 {
+    left: 66.66666666666666%;
+  }
+  .col-md-push-9 {
+    left: 75%;
+  }
+  .col-md-push-10 {
+    left: 83.33333333333334%;
+  }
+  .col-md-push-11 {
+    left: 91.66666666666666%;
+  }
+  .col-md-pull-0 {
+    right: auto;
+  }
+  .col-md-pull-1 {
+    right: 8.333333333333332%;
+  }
+  .col-md-pull-2 {
+    right: 16.666666666666664%;
+  }
+  .col-md-pull-3 {
+    right: 25%;
+  }
+  .col-md-pull-4 {
+    right: 33.33333333333333%;
+  }
+  .col-md-pull-5 {
+    right: 41.66666666666667%;
+  }
+  .col-md-pull-6 {
+    right: 50%;
+  }
+  .col-md-pull-7 {
+    right: 58.333333333333336%;
+  }
+  .col-md-pull-8 {
+    right: 66.66666666666666%;
+  }
+  .col-md-pull-9 {
+    right: 75%;
+  }
+  .col-md-pull-10 {
+    right: 83.33333333333334%;
+  }
+  .col-md-pull-11 {
+    right: 91.66666666666666%;
+  }
+  .col-md-offset-0 {
+    margin-left: 0;
+  }
+  .col-md-offset-1 {
+    margin-left: 8.333333333333332%;
+  }
+  .col-md-offset-2 {
+    margin-left: 16.666666666666664%;
+  }
+  .col-md-offset-3 {
+    margin-left: 25%;
+  }
+  .col-md-offset-4 {
+    margin-left: 33.33333333333333%;
+  }
+  .col-md-offset-5 {
+    margin-left: 41.66666666666667%;
+  }
+  .col-md-offset-6 {
+    margin-left: 50%;
+  }
+  .col-md-offset-7 {
+    margin-left: 58.333333333333336%;
+  }
+  .col-md-offset-8 {
+    margin-left: 66.66666666666666%;
+  }
+  .col-md-offset-9 {
+    margin-left: 75%;
+  }
+  .col-md-offset-10 {
+    margin-left: 83.33333333333334%;
+  }
+  .col-md-offset-11 {
+    margin-left: 91.66666666666666%;
+  }
+}
+
+@media (min-width: 1200px) {
+  .container {
+    max-width: 1170px;
+  }
+  .col-lg-1,
+  .col-lg-2,
+  .col-lg-3,
+  .col-lg-4,
+  .col-lg-5,
+  .col-lg-6,
+  .col-lg-7,
+  .col-lg-8,
+  .col-lg-9,
+  .col-lg-10,
+  .col-lg-11 {
+    float: left;
+  }
+  .col-lg-1 {
+    width: 8.333333333333332%;
+  }
+  .col-lg-2 {
+    width: 16.666666666666664%;
+  }
+  .col-lg-3 {
+    width: 25%;
+  }
+  .col-lg-4 {
+    width: 33.33333333333333%;
+  }
+  .col-lg-5 {
+    width: 41.66666666666667%;
+  }
+  .col-lg-6 {
+    width: 50%;
+  }
+  .col-lg-7 {
+    width: 58.333333333333336%;
+  }
+  .col-lg-8 {
+    width: 66.66666666666666%;
+  }
+  .col-lg-9 {
+    width: 75%;
+  }
+  .col-lg-10 {
+    width: 83.33333333333334%;
+  }
+  .col-lg-11 {
+    width: 91.66666666666666%;
+  }
+  .col-lg-12 {
+    width: 100%;
+  }
+  .col-lg-push-0 {
+    left: auto;
+  }
+  .col-lg-push-1 {
+    left: 8.333333333333332%;
+  }
+  .col-lg-push-2 {
+    left: 16.666666666666664%;
+  }
+  .col-lg-push-3 {
+    left: 25%;
+  }
+  .col-lg-push-4 {
+    left: 33.33333333333333%;
+  }
+  .col-lg-push-5 {
+    left: 41.66666666666667%;
+  }
+  .col-lg-push-6 {
+    left: 50%;
+  }
+  .col-lg-push-7 {
+    left: 58.333333333333336%;
+  }
+  .col-lg-push-8 {
+    left: 66.66666666666666%;
+  }
+  .col-lg-push-9 {
+    left: 75%;
+  }
+  .col-lg-push-10 {
+    left: 83.33333333333334%;
+  }
+  .col-lg-push-11 {
+    left: 91.66666666666666%;
+  }
+  .col-lg-pull-0 {
+    right: auto;
+  }
+  .col-lg-pull-1 {
+    right: 8.333333333333332%;
+  }
+  .col-lg-pull-2 {
+    right: 16.666666666666664%;
+  }
+  .col-lg-pull-3 {
+    right: 25%;
+  }
+  .col-lg-pull-4 {
+    right: 33.33333333333333%;
+  }
+  .col-lg-pull-5 {
+    right: 41.66666666666667%;
+  }
+  .col-lg-pull-6 {
+    right: 50%;
+  }
+  .col-lg-pull-7 {
+    right: 58.333333333333336%;
+  }
+  .col-lg-pull-8 {
+    right: 66.66666666666666%;
+  }
+  .col-lg-pull-9 {
+    right: 75%;
+  }
+  .col-lg-pull-10 {
+    right: 83.33333333333334%;
+  }
+  .col-lg-pull-11 {
+    right: 91.66666666666666%;
+  }
+  .col-lg-offset-0 {
+    margin-left: 0;
+  }
+  .col-lg-offset-1 {
+    margin-left: 8.333333333333332%;
+  }
+  .col-lg-offset-2 {
+    margin-left: 16.666666666666664%;
+  }
+  .col-lg-offset-3 {
+    margin-left: 25%;
+  }
+  .col-lg-offset-4 {
+    margin-left: 33.33333333333333%;
+  }
+  .col-lg-offset-5 {
+    margin-left: 41.66666666666667%;
+  }
+  .col-lg-offset-6 {
+    margin-left: 50%;
+  }
+  .col-lg-offset-7 {
+    margin-left: 58.333333333333336%;
+  }
+  .col-lg-offset-8 {
+    margin-left: 66.66666666666666%;
+  }
+  .col-lg-offset-9 {
+    margin-left: 75%;
+  }
+  .col-lg-offset-10 {
+    margin-left: 83.33333333333334%;
+  }
+  .col-lg-offset-11 {
+    margin-left: 91.66666666666666%;
+  }
+}
+
+table {
+  max-width: 100%;
+  background-color: transparent;
+}
+
+th {
+  text-align: left;
+}
+
+.table {
+  width: 100%;
+  margin-bottom: 20px;
+}
+
+.table thead > tr > th,
+.table tbody > tr > th,
+.table tfoot > tr > th,
+.table thead > tr > td,
+.table tbody > tr > td,
+.table tfoot > tr > td {
+  padding: 8px;
+  line-height: 1.428571429;
+  vertical-align: top;
+  border-top: 1px solid #dddddd;
+}
+
+.table thead > tr > th {
+  vertical-align: bottom;
+  border-bottom: 2px solid #dddddd;
+}
+
+.table caption + thead tr:first-child th,
+.table colgroup + thead tr:first-child th,
+.table thead:first-child tr:first-child th,
+.table caption + thead tr:first-child td,
+.table colgroup + thead tr:first-child td,
+.table thead:first-child tr:first-child td {
+  border-top: 0;
+}
+
+.table tbody + tbody {
+  border-top: 2px solid #dddddd;
+}
+
+.table .table {
+  background-color: #ffffff;
+}
+
+.table-condensed thead > tr > th,
+.table-condensed tbody > tr > th,
+.table-condensed tfoot > tr > th,
+.table-condensed thead > tr > td,
+.table-condensed tbody > tr > td,
+.table-condensed tfoot > tr > td {
+  padding: 5px;
+}
+
+.table-bordered {
+  border: 1px solid #dddddd;
+}
+
+.table-bordered > thead > tr > th,
+.table-bordered > tbody > tr > th,
+.table-bordered > tfoot > tr > th,
+.table-bordered > thead > tr > td,
+.table-bordered > tbody > tr > td,
+.table-bordered > tfoot > tr > td {
+  border: 1px solid #dddddd;
+}
+
+.table-bordered > thead > tr > th,
+.table-bordered > thead > tr > td {
+  border-bottom-width: 2px;
+}
+
+.table-striped > tbody > tr:nth-child(odd) > td,
+.table-striped > tbody > tr:nth-child(odd) > th {
+  background-color: #f9f9f9;
+}
+
+.table-hover > tbody > tr:hover > td,
+.table-hover > tbody > tr:hover > th {
+  background-color: #f5f5f5;
+}
+
+table col[class*="col-"] {
+  display: table-column;
+  float: none;
+}
+
+table td[class*="col-"],
+table th[class*="col-"] {
+  display: table-cell;
+  float: none;
+}
+
+.table > thead > tr > td.active,
+.table > tbody > tr > td.active,
+.table > tfoot > tr > td.active,
+.table > thead > tr > th.active,
+.table > tbody > tr > th.active,
+.table > tfoot > tr > th.active,
+.table > thead > tr.active > td,
+.table > tbody > tr.active > td,
+.table > tfoot > tr.active > td,
+.table > thead > tr.active > th,
+.table > tbody > tr.active > th,
+.table > tfoot > tr.active > th {
+  background-color: #f5f5f5;
+}
+
+.table > thead > tr > td.success,
+.table > tbody > tr > td.success,
+.table > tfoot > tr > td.success,
+.table > thead > tr > th.success,
+.table > tbody > tr > th.success,
+.table > tfoot > tr > th.success,
+.table > thead > tr.success > td,
+.table > tbody > tr.success > td,
+.table > tfoot > tr.success > td,
+.table > thead > tr.success > th,
+.table > tbody > tr.success > th,
+.table > tfoot > tr.success > th {
+  background-color: #dff0d8;
+  border-color: #d6e9c6;
+}
+
+.table-hover > tbody > tr > td.success:hover,
+.table-hover > tbody > tr > th.success:hover,
+.table-hover > tbody > tr.success:hover > td {
+  background-color: #d0e9c6;
+  border-color: #c9e2b3;
+}
+
+.table > thead > tr > td.danger,
+.table > tbody > tr > td.danger,
+.table > tfoot > tr > td.danger,
+.table > thead > tr > th.danger,
+.table > tbody > tr > th.danger,
+.table > tfoot > tr > th.danger,
+.table > thead > tr.danger > td,
+.table > tbody > tr.danger > td,
+.table > tfoot > tr.danger > td,
+.table > thead > tr.danger > th,
+.table > tbody > tr.danger > th,
+.table > tfoot > tr.danger > th {
+  background-color: #f2dede;
+  border-color: #eed3d7;
+}
+
+.table-hover > tbody > tr > td.danger:hover,
+.table-hover > tbody > tr > th.danger:hover,
+.table-hover > tbody > tr.danger:hover > td {
+  background-color: #ebcccc;
+  border-color: #e6c1c7;
+}
+
+.table > thead > tr > td.warning,
+.table > tbody > tr > td.warning,
+.table > tfoot > tr > td.warning,
+.table > thead > tr > th.warning,
+.table > tbody > tr > th.warning,
+.table > tfoot > tr > th.warning,
+.table > thead > tr.warning > td,
+.table > tbody > tr.warning > td,
+.table > tfoot > tr.warning > td,
+.table > thead > tr.warning > th,
+.table > tbody > tr.warning > th,
+.table > tfoot > tr.warning > th {
+  background-color: #fcf8e3;
+  border-color: #fbeed5;
+}
+
+.table-hover > tbody > tr > td.warning:hover,
+.table-hover > tbody > tr > th.warning:hover,
+.table-hover > tbody > tr.warning:hover > td {
+  background-color: #faf2cc;
+  border-color: #f8e5be;
+}
+
+@media (max-width: 768px) {
+  .table-responsive {
+    width: 100%;
+    margin-bottom: 15px;
+    overflow-x: scroll;
+    overflow-y: hidden;
+    border: 1px solid #dddddd;
+  }
+  .table-responsive > .table {
+    margin-bottom: 0;
+    background-color: #fff;
+  }
+  .table-responsive > .table > thead > tr > th,
+  .table-responsive > .table > tbody > tr > th,
+  .table-responsive > .table > tfoot > tr > th,
+  .table-responsive > .table > thead > tr > td,
+  .table-responsive > .table > tbody > tr > td,
+  .table-responsive > .table > tfoot > tr > td {
+    white-space: nowrap;
+  }
+  .table-responsive > .table-bordered {
+    border: 0;
+  }
+  .table-responsive > .table-bordered > thead > tr > th:first-child,
+  .table-responsive > .table-bordered > tbody > tr > th:first-child,
+  .table-responsive > .table-bordered > tfoot > tr > th:first-child,
+  .table-responsive > .table-bordered > thead > tr > td:first-child,
+  .table-responsive > .table-bordered > tbody > tr > td:first-child,
+  .table-responsive > .table-bordered > tfoot > tr > td:first-child {
+    border-left: 0;
+  }
+  .table-responsive > .table-bordered > thead > tr > th:last-child,
+  .table-responsive > .table-bordered > tbody > tr > th:last-child,
+  .table-responsive > .table-bordered > tfoot > tr > th:last-child,
+  .table-responsive > .table-bordered > thead > tr > td:last-child,
+  .table-responsive > .table-bordered > tbody > tr > td:last-child,
+  .table-responsive > .table-bordered > tfoot > tr > td:last-child {
+    border-right: 0;
+  }
+  .table-responsive > .table-bordered > thead > tr:last-child > th,
+  .table-responsive > .table-bordered > tbody > tr:last-child > th,
+  .table-responsive > .table-bordered > tfoot > tr:last-child > th,
+  .table-responsive > .table-bordered > thead > tr:last-child > td,
+  .table-responsive > .table-bordered > tbody > tr:last-child > td,
+  .table-responsive > .table-bordered > tfoot > tr:last-child > td {
+    border-bottom: 0;
+  }
+}
+
+fieldset {
+  padding: 0;
+  margin: 0;
+  border: 0;
+}
+
+legend {
+  display: block;
+  width: 100%;
+  padding: 0;
+  margin-bottom: 20px;
+  font-size: 21px;
+  line-height: inherit;
+  color: #333333;
+  border: 0;
+  border-bottom: 1px solid #e5e5e5;
+}
+
+label {
+  display: inline-block;
+  margin-bottom: 5px;
+  font-weight: bold;
+}
+
+input[type="search"] {
+  -webkit-box-sizing: border-box;
+     -moz-box-sizing: border-box;
+          box-sizing: border-box;
+}
+
+input[type="radio"],
+input[type="checkbox"] {
+  margin: 4px 0 0;
+  margin-top: 1px \9;
+  /* IE8-9 */
+
+  line-height: normal;
+}
+
+input[type="file"] {
+  display: block;
+}
+
+select[multiple],
+select[size] {
+  height: auto;
+}
+
+select optgroup {
+  font-family: inherit;
+  font-size: inherit;
+  font-style: inherit;
+}
+
+input[type="file"]:focus,
+input[type="radio"]:focus,
+input[type="checkbox"]:focus {
+  outline: thin dotted #333;
+  outline: 5px auto -webkit-focus-ring-color;
+  outline-offset: -2px;
+}
+
+input[type="number"]::-webkit-outer-spin-button,
+input[type="number"]::-webkit-inner-spin-button {
+  height: auto;
+}
+
+.form-control:-moz-placeholder {
+  color: #999999;
+}
+
+.form-control::-moz-placeholder {
+  color: #999999;
+}
+
+.form-control:-ms-input-placeholder {
+  color: #999999;
+}
+
+.form-control::-webkit-input-placeholder {
+  color: #999999;
+}
+
+.form-control {
+  display: block;
+  width: 100%;
+  height: 34px;
+  padding: 6px 12px;
+  font-size: 14px;
+  line-height: 1.428571429;
+  color: #555555;
+  vertical-align: middle;
+  background-color: #ffffff;
+  border: 1px solid #cccccc;
+  border-radius: 4px;
+  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
+          box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
+  -webkit-transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
+          transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
+}
+
+.form-control:focus {
+  border-color: #66afe9;
+  outline: 0;
+  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(102, 175, 233, 0.6);
+          box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(102, 175, 233, 0.6);
+}
+
+.form-control[disabled],
+.form-control[readonly],
+fieldset[disabled] .form-control {
+  cursor: not-allowed;
+  background-color: #eeeeee;
+}
+
+textarea.form-control {
+  height: auto;
+}
+
+.form-group {
+  margin-bottom: 15px;
+}
+
+.radio,
+.checkbox {
+  display: block;
+  min-height: 20px;
+  padding-left: 20px;
+  margin-top: 10px;
+  margin-bottom: 10px;
+  vertical-align: middle;
+}
+
+.radio label,
+.checkbox label {
+  display: inline;
+  margin-bottom: 0;
+  font-weight: normal;
+  cursor: pointer;
+}
+
+.radio input[type="radio"],
+.radio-inline input[type="radio"],
+.checkbox input[type="checkbox"],
+.checkbox-inline input[type="checkbox"] {
+  float: left;
+  margin-left: -20px;
+}
+
+.radio + .radio,
+.checkbox + .checkbox {
+  margin-top: -5px;
+}
+
+.radio-inline,
+.checkbox-inline {
+  display: inline-block;
+  padding-left: 20px;
+  margin-bottom: 0;
+  font-weight: normal;
+  vertical-align: middle;
+  cursor: pointer;
+}
+
+.radio-inline + .radio-inline,
+.checkbox-inline + .checkbox-inline {
+  margin-top: 0;
+  margin-left: 10px;
+}
+
+input[type="radio"][disabled],
+input[type="checkbox"][disabled],
+.radio[disabled],
+.radio-inline[disabled],
+.checkbox[disabled],
+.checkbox-inline[disabled],
+fieldset[disabled] input[type="radio"],
+fieldset[disabled] input[type="checkbox"],
+fieldset[disabled] .radio,
+fieldset[disabled] .radio-inline,
+fieldset[disabled] .checkbox,
+fieldset[disabled] .checkbox-inline {
+  cursor: not-allowed;
+}
+
+.input-sm {
+  height: 30px;
+  padding: 5px 10px;
+  font-size: 12px;
+  line-height: 1.5;
+  border-radius: 3px;
+}
+
+select.input-sm {
+  height: 30px;
+  line-height: 30px;
+}
+
+textarea.input-sm {
+  height: auto;
+}
+
+.input-lg {
+  height: 45px;
+  padding: 10px 16px;
+  font-size: 18px;
+  line-height: 1.33;
+  border-radius: 6px;
+}
+
+select.input-lg {
+  height: 45px;
+  line-height: 45px;
+}
+
+textarea.input-lg {
+  height: auto;
+}
+
+.has-warning .help-block,
+.has-warning .control-label {
+  color: #c09853;
+}
+
+.has-warning .form-control {
+  border-color: #c09853;
+  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
+          box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
+}
+
+.has-warning .form-control:focus {
+  border-color: #a47e3c;
+  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #dbc59e;
+          box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #dbc59e;
+}
+
+.has-warning .input-group-addon {
+  color: #c09853;
+  background-color: #fcf8e3;
+  border-color: #c09853;
+}
+
+.has-error .help-block,
+.has-error .control-label {
+  color: #b94a48;
+}
+
+.has-error .form-control {
+  border-color: #b94a48;
+  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
+          box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
+}
+
+.has-error .form-control:focus {
+  border-color: #953b39;
+  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #d59392;
+          box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #d59392;
+}
+
+.has-error .input-group-addon {
+  color: #b94a48;
+  background-color: #f2dede;
+  border-color: #b94a48;
+}
+
+.has-success .help-block,
+.has-success .control-label {
+  color: #468847;
+}
+
+.has-success .form-control {
+  border-color: #468847;
+  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
+          box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
+}
+
+.has-success .form-control:focus {
+  border-color: #356635;
+  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7aba7b;
+          box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7aba7b;
+}
+
+.has-success .input-group-addon {
+  color: #468847;
+  background-color: #dff0d8;
+  border-color: #468847;
+}
+
+.form-control-static {
+  padding-top: 7px;
+  margin-bottom: 0;
+}
+
+.help-block {
+  display: block;
+  margin-top: 5px;
+  margin-bottom: 10px;
+  color: #737373;
+}
+
+@media (min-width: 768px) {
+  .form-inline .form-group {
+    display: inline-block;
+    margin-bottom: 0;
+    vertical-align: middle;
+  }
+  .form-inline .form-control {
+    display: inline-block;
+  }
+  .form-inline .radio,
+  .form-inline .checkbox {
+    display: inline-block;
+    padding-left: 0;
+    margin-top: 0;
+    margin-bottom: 0;
+  }
+  .form-inline .radio input[type="radio"],
+  .form-inline .checkbox input[type="checkbox"] {
+    float: none;
+    margin-left: 0;
+  }
+}
+
+.form-horizontal .control-label,
+.form-horizontal .radio,
+.form-horizontal .checkbox,
+.form-horizontal .radio-inline,
+.form-horizontal .checkbox-inline {
+  padding-top: 7px;
+  margin-top: 0;
+  margin-bottom: 0;
+}
+
+.form-horizontal .form-group {
+  margin-right: -15px;
+  margin-left: -15px;
+}
+
+.form-horizontal .form-group:before,
+.form-horizontal .form-group:after {
+  display: table;
+  content: " ";
+}
+
+.form-horizontal .form-group:after {
+  clear: both;
+}
+
+.form-horizontal .form-group:before,
+.form-horizontal .form-group:after {
+  display: table;
+  content: " ";
+}
+
+.form-horizontal .form-group:after {
+  clear: both;
+}
+
+@media (min-width: 768px) {
+  .form-horizontal .control-label {
+    text-align: right;
+  }
+}
+
+.btn {
+  display: inline-block;
+  padding: 6px 12px;
+  margin-bottom: 0;
+  font-size: 14px;
+  font-weight: normal;
+  line-height: 1.428571429;
+  text-align: center;
+  white-space: nowrap;
+  vertical-align: middle;
+  cursor: pointer;
+  border: 1px solid transparent;
+  border-radius: 4px;
+  -webkit-user-select: none;
+     -moz-user-select: none;
+      -ms-user-select: none;
+       -o-user-select: none;
+          user-select: none;
+}
+
+.btn:focus {
+  outline: thin dotted #333;
+  outline: 5px auto -webkit-focus-ring-color;
+  outline-offset: -2px;
+}
+
+.btn:hover,
+.btn:focus {
+  color: #333333;
+  text-decoration: none;
+}
+
+.btn:active,
+.btn.active {
+  background-image: none;
+  outline: 0;
+  -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
+          box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
+}
+
+.btn.disabled,
+.btn[disabled],
+fieldset[disabled] .btn {
+  pointer-events: none;
+  cursor: not-allowed;
+  opacity: 0.65;
+  filter: alpha(opacity=65);
+  -webkit-box-shadow: none;
+          box-shadow: none;
+}
+
+.btn-default {
+  color: #333333;
+  background-color: #ffffff;
+  border-color: #cccccc;
+}
+
+.btn-default:hover,
+.btn-default:focus,
+.btn-default:active,
+.btn-default.active,
+.open .dropdown-toggle.btn-default {
+  color: #333333;
+  background-color: #ebebeb;
+  border-color: #adadad;
+}
+
+.btn-default:active,
+.btn-default.active,
+.open .dropdown-toggle.btn-default {
+  background-image: none;
+}
+
+.btn-default.disabled,
+.btn-default[disabled],
+fieldset[disabled] .btn-default,
+.btn-default.disabled:hover,
+.btn-default[disabled]:hover,
+fieldset[disabled] .btn-default:hover,
+.btn-default.disabled:focus,
+.btn-default[disabled]:focus,
+fieldset[disabled] .btn-default:focus,
+.btn-default.disabled:active,
+.btn-default[disabled]:active,
+fieldset[disabled] .btn-default:active,
+.btn-default.disabled.active,
+.btn-default[disabled].active,
+fieldset[disabled] .btn-default.active {
+  background-color: #ffffff;
+  border-color: #cccccc;
+}
+
+.btn-primary {
+  color: #ffffff;
+  background-color: #428bca;
+  border-color: #357ebd;
+}
+
+.btn-primary:hover,
+.btn-primary:focus,
+.btn-primary:active,
+.btn-primary.active,
+.open .dropdown-toggle.btn-primary {
+  color: #ffffff;
+  background-color: #3276b1;
+  border-color: #285e8e;
+}
+
+.btn-primary:active,
+.btn-primary.active,
+.open .dropdown-toggle.btn-primary {
+  background-image: none;
+}
+
+.btn-primary.disabled,
+.btn-primary[disabled],
+fieldset[disabled] .btn-primary,
+.btn-primary.disabled:hover,
+.btn-primary[disabled]:hover,
+fieldset[disabled] .btn-primary:hover,
+.btn-primary.disabled:focus,
+.btn-primary[disabled]:focus,
+fieldset[disabled] .btn-primary:focus,
+.btn-primary.disabled:active,
+.btn-primary[disabled]:active,
+fieldset[disabled] .btn-primary:active,
+.btn-primary.disabled.active,
+.btn-primary[disabled].active,
+fieldset[disabled] .btn-primary.active {
+  background-color: #428bca;
+  border-color: #357ebd;
+}
+
+.btn-warning {
+  color: #ffffff;
+  background-color: #f0ad4e;
+  border-color: #eea236;
+}
+
+.btn-warning:hover,
+.btn-warning:focus,
+.btn-warning:active,
+.btn-warning.active,
+.open .dropdown-toggle.btn-warning {
+  color: #ffffff;
+  background-color: #ed9c28;
+  border-color: #d58512;
+}
+
+.btn-warning:active,
+.btn-warning.active,
+.open .dropdown-toggle.btn-warning {
+  background-image: none;
+}
+
+.btn-warning.disabled,
+.btn-warning[disabled],
+fieldset[disabled] .btn-warning,
+.btn-warning.disabled:hover,
+.btn-warning[disabled]:hover,
+fieldset[disabled] .btn-warning:hover,
+.btn-warning.disabled:focus,
+.btn-warning[disabled]:focus,
+fieldset[disabled] .btn-warning:focus,
+.btn-warning.disabled:active,
+.btn-warning[disabled]:active,
+fieldset[disabled] .btn-warning:active,
+.btn-warning.disabled.active,
+.btn-warning[disabled].active,
+fieldset[disabled] .btn-warning.active {
+  background-color: #f0ad4e;
+  border-color: #eea236;
+}
+
+.btn-danger {
+  color: #ffffff;
+  background-color: #d9534f;
+  border-color: #d43f3a;
+}
+
+.btn-danger:hover,
+.btn-danger:focus,
+.btn-danger:active,
+.btn-danger.active,
+.open .dropdown-toggle.btn-danger {
+  color: #ffffff;
+  background-color: #d2322d;
+  border-color: #ac2925;
+}
+
+.btn-danger:active,
+.btn-danger.active,
+.open .dropdown-toggle.btn-danger {
+  background-image: none;
+}
+
+.btn-danger.disabled,
+.btn-danger[disabled],
+fieldset[disabled] .btn-danger,
+.btn-danger.disabled:hover,
+.btn-danger[disabled]:hover,
+fieldset[disabled] .btn-danger:hover,
+.btn-danger.disabled:focus,
+.btn-danger[disabled]:focus,
+fieldset[disabled] .btn-danger:focus,
+.btn-danger.disabled:active,
+.btn-danger[disabled]:active,
+fieldset[disabled] .btn-danger:active,
+.btn-danger.disabled.active,
+.btn-danger[disabled].active,
+fieldset[disabled] .btn-danger.active {
+  background-color: #d9534f;
+  border-color: #d43f3a;
+}
+
+.btn-success {
+  color: #ffffff;
+  background-color: #5cb85c;
+  border-color: #4cae4c;
+}
+
+.btn-success:hover,
+.btn-success:focus,
+.btn-success:active,
+.btn-success.active,
+.open .dropdown-toggle.btn-success {
+  color: #ffffff;
+  background-color: #47a447;
+  border-color: #398439;
+}
+
+.btn-success:active,
+.btn-success.active,
+.open .dropdown-toggle.btn-success {
+  background-image: none;
+}
+
+.btn-success.disabled,
+.btn-success[disabled],
+fieldset[disabled] .btn-success,
+.btn-success.disabled:hover,
+.btn-success[disabled]:hover,
+fieldset[disabled] .btn-success:hover,
+.btn-success.disabled:focus,
+.btn-success[disabled]:focus,
+fieldset[disabled] .btn-success:focus,
+.btn-success.disabled:active,
+.btn-success[disabled]:active,
+fieldset[disabled] .btn-success:active,
+.btn-success.disabled.active,
+.btn-success[disabled].active,
+fieldset[disabled] .btn-success.active {
+  background-color: #5cb85c;
+  border-color: #4cae4c;
+}
+
+.btn-info {
+  color: #ffffff;
+  background-color: #5bc0de;
+  border-color: #46b8da;
+}
+
+.btn-info:hover,
+.btn-info:focus,
+.btn-info:active,
+.btn-info.active,
+.open .dropdown-toggle.btn-info {
+  color: #ffffff;
+  background-color: #39b3d7;
+  border-color: #269abc;
+}
+
+.btn-info:active,
+.btn-info.active,
+.open .dropdown-toggle.btn-info {
+  background-image: none;
+}
+
+.btn-info.disabled,
+.btn-info[disabled],
+fieldset[disabled] .btn-info,
+.btn-info.disabled:hover,
+.btn-info[disabled]:hover,
+fieldset[disabled] .btn-info:hover,
+.btn-info.disabled:focus,
+.btn-info[disabled]:focus,
+fieldset[disabled] .btn-info:focus,
+.btn-info.disabled:active,
+.btn-info[disabled]:active,
+fieldset[disabled] .btn-info:active,
+.btn-info.disabled.active,
+.btn-info[disabled].active,
+fieldset[disabled] .btn-info.active {
+  background-color: #5bc0de;
+  border-color: #46b8da;
+}
+
+.btn-link {
+  font-weight: normal;
+  color: #428bca;
+  cursor: pointer;
+  border-radius: 0;
+}
+
+.btn-link,
+.btn-link:active,
+.btn-link[disabled],
+fieldset[disabled] .btn-link {
+  background-color: transparent;
+  -webkit-box-shadow: none;
+          box-shadow: none;
+}
+
+.btn-link,
+.btn-link:hover,
+.btn-link:focus,
+.btn-link:active {
+  border-color: transparent;
+}
+
+.btn-link:hover,
+.btn-link:focus {
+  color: #2a6496;
+  text-decoration: underline;
+  background-color: transparent;
+}
+
+.btn-link[disabled]:hover,
+fieldset[disabled] .btn-link:hover,
+.btn-link[disabled]:focus,
+fieldset[disabled] .btn-link:focus {
+  color: #999999;
+  text-decoration: none;
+}
+
+.btn-lg {
+  padding: 10px 16px;
+  font-size: 18px;
+  line-height: 1.33;
+  border-radius: 6px;
+}
+
+.btn-sm,
+.btn-xs {
+  padding: 5px 10px;
+  font-size: 12px;
+  line-height: 1.5;
+  border-radius: 3px;
+}
+
+.btn-xs {
+  padding: 1px 5px;
+}
+
+.btn-block {
+  display: block;
+  width: 100%;
+  padding-right: 0;
+  padding-left: 0;
+}
+
+.btn-block + .btn-block {
+  margin-top: 5px;
+}
+
+input[type="submit"].btn-block,
+input[type="reset"].btn-block,
+input[type="button"].btn-block {
+  width: 100%;
+}
+
+.fade {
+  opacity: 0;
+  -webkit-transition: opacity 0.15s linear;
+          transition: opacity 0.15s linear;
+}
+
+.fade.in {
+  opacity: 1;
+}
+
+.collapse {
+  display: none;
+}
+
+.collapse.in {
+  display: block;
+}
+
+.collapsing {
+  position: relative;
+  height: 0;
+  overflow: hidden;
+  -webkit-transition: height 0.35s ease;
+          transition: height 0.35s ease;
+}
+
+@font-face {
+  font-family: 'Glyphicons Halflings';
+  src: url('../fonts/glyphicons-halflings-regular.eot');
+  src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
+}
+
+.glyphicon {
+  position: relative;
+  top: 1px;
+  display: inline-block;
+  font-family: 'Glyphicons Halflings';
+  -webkit-font-smoothing: antialiased;
+  font-style: normal;
+  font-weight: normal;
+  line-height: 1;
+}
+
+.glyphicon-asterisk:before {
+  content: "\2a";
+}
+
+.glyphicon-plus:before {
+  content: "\2b";
+}
+
+.glyphicon-euro:before {
+  content: "\20ac";
+}
+
+.glyphicon-minus:before {
+  content: "\2212";
+}
+
+.glyphicon-cloud:before {
+  content: "\2601";
+}
+
+.glyphicon-envelope:before {
+  content: "\2709";
+}
+
+.glyphicon-pencil:before {
+  content: "\270f";
+}
+
+.glyphicon-glass:before {
+  content: "\e001";
+}
+
+.glyphicon-music:before {
+  content: "\e002";
+}
+
+.glyphicon-search:before {
+  content: "\e003";
+}
+
+.glyphicon-heart:before {
+  content: "\e005";
+}
+
+.glyphicon-star:before {
+  content: "\e006";
+}
+
+.glyphicon-star-empty:before {
+  content: "\e007";
+}
+
+.glyphicon-user:before {
+  content: "\e008";
+}
+
+.glyphicon-film:before {
+  content: "\e009";
+}
+
+.glyphicon-th-large:before {
+  content: "\e010";
+}
+
+.glyphicon-th:before {
+  content: "\e011";
+}
+
+.glyphicon-th-list:before {
+  content: "\e012";
+}
+
+.glyphicon-ok:before {
+  content: "\e013";
+}
+
+.glyphicon-remove:before {
+  content: "\e014";
+}
+
+.glyphicon-zoom-in:before {
+  content: "\e015";
+}
+
+.glyphicon-zoom-out:before {
+  content: "\e016";
+}
+
+.glyphicon-off:before {
+  content: "\e017";
+}
+
+.glyphicon-signal:before {
+  content: "\e018";
+}
+
+.glyphicon-cog:before {
+  content: "\e019";
+}
+
+.glyphicon-trash:before {
+  content: "\e020";
+}
+
+.glyphicon-home:before {
+  content: "\e021";
+}
+
+.glyphicon-file:before {
+  content: "\e022";
+}
+
+.glyphicon-time:before {
+  content: "\e023";
+}
+
+.glyphicon-road:before {
+  content: "\e024";
+}
+
+.glyphicon-download-alt:before {
+  content: "\e025";
+}
+
+.glyphicon-download:before {
+  content: "\e026";
+}
+
+.glyphicon-upload:before {
+  content: "\e027";
+}
+
+.glyphicon-inbox:before {
+  content: "\e028";
+}
+
+.glyphicon-play-circle:before {
+  content: "\e029";
+}
+
+.glyphicon-repeat:before {
+  content: "\e030";
+}
+
+.glyphicon-refresh:before {
+  content: "\e031";
+}
+
+.glyphicon-list-alt:before {
+  content: "\e032";
+}
+
+.glyphicon-flag:before {
+  content: "\e034";
+}
+
+.glyphicon-headphones:before {
+  content: "\e035";
+}
+
+.glyphicon-volume-off:before {
+  content: "\e036";
+}
+
+.glyphicon-volume-down:before {
+  content: "\e037";
+}
+
+.glyphicon-volume-up:before {
+  content: "\e038";
+}
+
+.glyphicon-qrcode:before {
+  content: "\e039";
+}
+
+.glyphicon-barcode:before {
+  content: "\e040";
+}
+
+.glyphicon-tag:before {
+  content: "\e041";
+}
+
+.glyphicon-tags:before {
+  content: "\e042";
+}
+
+.glyphicon-book:before {
+  content: "\e043";
+}
+
+.glyphicon-print:before {
+  content: "\e045";
+}
+
+.glyphicon-font:before {
+  content: "\e047";
+}
+
+.glyphicon-bold:before {
+  content: "\e048";
+}
+
+.glyphicon-italic:before {
+  content: "\e049";
+}
+
+.glyphicon-text-height:before {
+  content: "\e050";
+}
+
+.glyphicon-text-width:before {
+  content: "\e051";
+}
+
+.glyphicon-align-left:before {
+  content: "\e052";
+}
+
+.glyphicon-align-center:before {
+  content: "\e053";
+}
+
+.glyphicon-align-right:before {
+  content: "\e054";
+}
+
+.glyphicon-align-justify:before {
+  content: "\e055";
+}
+
+.glyphicon-list:before {
+  content: "\e056";
+}
+
+.glyphicon-indent-left:before {
+  content: "\e057";
+}
+
+.glyphicon-indent-right:before {
+  content: "\e058";
+}
+
+.glyphicon-facetime-video:before {
+  content: "\e059";
+}
+
+.glyphicon-picture:before {
+  content: "\e060";
+}
+
+.glyphicon-map-marker:before {
+  content: "\e062";
+}
+
+.glyphicon-adjust:before {
+  content: "\e063";
+}
+
+.glyphicon-tint:before {
+  content: "\e064";
+}
+
+.glyphicon-edit:before {
+  content: "\e065";
+}
+
+.glyphicon-share:before {
+  content: "\e066";
+}
+
+.glyphicon-check:before {
+  content: "\e067";
+}
+
+.glyphicon-move:before {
+  content: "\e068";
+}
+
+.glyphicon-step-backward:before {
+  content: "\e069";
+}
+
+.glyphicon-fast-backward:before {
+  content: "\e070";
+}
+
+.glyphicon-backward:before {
+  content: "\e071";
+}
+
+.glyphicon-play:before {
+  content: "\e072";
+}
+
+.glyphicon-pause:before {
+  content: "\e073";
+}
+
+.glyphicon-stop:before {
+  content: "\e074";
+}
+
+.glyphicon-forward:before {
+  content: "\e075";
+}
+
+.glyphicon-fast-forward:before {
+  content: "\e076";
+}
+
+.glyphicon-step-forward:before {
+  content: "\e077";
+}
+
+.glyphicon-eject:before {
+  content: "\e078";
+}
+
+.glyphicon-chevron-left:before {
+  content: "\e079";
+}
+
+.glyphicon-chevron-right:before {
+  content: "\e080";
+}
+
+.glyphicon-plus-sign:before {
+  content: "\e081";
+}
+
+.glyphicon-minus-sign:before {
+  content: "\e082";
+}
+
+.glyphicon-remove-sign:before {
+  content: "\e083";
+}
+
+.glyphicon-ok-sign:before {
+  content: "\e084";
+}
+
+.glyphicon-question-sign:before {
+  content: "\e085";
+}
+
+.glyphicon-info-sign:before {
+  content: "\e086";
+}
+
+.glyphicon-screenshot:before {
+  content: "\e087";
+}
+
+.glyphicon-remove-circle:before {
+  content: "\e088";
+}
+
+.glyphicon-ok-circle:before {
+  content: "\e089";
+}
+
+.glyphicon-ban-circle:before {
+  content: "\e090";
+}
+
+.glyphicon-arrow-left:before {
+  content: "\e091";
+}
+
+.glyphicon-arrow-right:before {
+  content: "\e092";
+}
+
+.glyphicon-arrow-up:before {
+  content: "\e093";
+}
+
+.glyphicon-arrow-down:before {
+  content: "\e094";
+}
+
+.glyphicon-share-alt:before {
+  content: "\e095";
+}
+
+.glyphicon-resize-full:before {
+  content: "\e096";
+}
+
+.glyphicon-resize-small:before {
+  content: "\e097";
+}
+
+.glyphicon-exclamation-sign:before {
+  content: "\e101";
+}
+
+.glyphicon-gift:before {
+  content: "\e102";
+}
+
+.glyphicon-leaf:before {
+  content: "\e103";
+}
+
+.glyphicon-eye-open:before {
+  content: "\e105";
+}
+
+.glyphicon-eye-close:before {
+  content: "\e106";
+}
+
+.glyphicon-warning-sign:before {
+  content: "\e107";
+}
+
+.glyphicon-plane:before {
+  content: "\e108";
+}
+
+.glyphicon-random:before {
+  content: "\e110";
+}
+
+.glyphicon-comment:before {
+  content: "\e111";
+}
+
+.glyphicon-magnet:before {
+  content: "\e112";
+}
+
+.glyphicon-chevron-up:before {
+  content: "\e113";
+}
+
+.glyphicon-chevron-down:before {
+  content: "\e114";
+}
+
+.glyphicon-retweet:before {
+  content: "\e115";
+}
+
+.glyphicon-shopping-cart:before {
+  content: "\e116";
+}
+
+.glyphicon-folder-close:before {
+  content: "\e117";
+}
+
+.glyphicon-folder-open:before {
+  content: "\e118";
+}
+
+.glyphicon-resize-vertical:before {
+  content: "\e119";
+}
+
+.glyphicon-resize-horizontal:before {
+  content: "\e120";
+}
+
+.glyphicon-hdd:before {
+  content: "\e121";
+}
+
+.glyphicon-bullhorn:before {
+  content: "\e122";
+}
+
+.glyphicon-certificate:before {
+  content: "\e124";
+}
+
+.glyphicon-thumbs-up:before {
+  content: "\e125";
+}
+
+.glyphicon-thumbs-down:before {
+  content: "\e126";
+}
+
+.glyphicon-hand-right:before {
+  content: "\e127";
+}
+
+.glyphicon-hand-left:before {
+  content: "\e128";
+}
+
+.glyphicon-hand-up:before {
+  content: "\e129";
+}
+
+.glyphicon-hand-down:before {
+  content: "\e130";
+}
+
+.glyphicon-circle-arrow-right:before {
+  content: "\e131";
+}
+
+.glyphicon-circle-arrow-left:before {
+  content: "\e132";
+}
+
+.glyphicon-circle-arrow-up:before {
+  content: "\e133";
+}
+
+.glyphicon-circle-arrow-down:before {
+  content: "\e134";
+}
+
+.glyphicon-globe:before {
+  content: "\e135";
+}
+
+.glyphicon-tasks:before {
+  content: "\e137";
+}
+
+.glyphicon-filter:before {
+  content: "\e138";
+}
+
+.glyphicon-fullscreen:before {
+  content: "\e140";
+}
+
+.glyphicon-dashboard:before {
+  content: "\e141";
+}
+
+.glyphicon-heart-empty:before {
+  content: "\e143";
+}
+
+.glyphicon-link:before {
+  content: "\e144";
+}
+
+.glyphicon-phone:before {
+  content: "\e145";
+}
+
+.glyphicon-usd:before {
+  content: "\e148";
+}
+
+.glyphicon-gbp:before {
+  content: "\e149";
+}
+
+.glyphicon-sort:before {
+  content: "\e150";
+}
+
+.glyphicon-sort-by-alphabet:before {
+  content: "\e151";
+}
+
+.glyphicon-sort-by-alphabet-alt:before {
+  content: "\e152";
+}
+
+.glyphicon-sort-by-order:before {
+  content: "\e153";
+}
+
+.glyphicon-sort-by-order-alt:before {
+  content: "\e154";
+}
+
+.glyphicon-sort-by-attributes:before {
+  content: "\e155";
+}
+
+.glyphicon-sort-by-attributes-alt:before {
+  content: "\e156";
+}
+
+.glyphicon-unchecked:before {
+  content: "\e157";
+}
+
+.glyphicon-expand:before {
+  content: "\e158";
+}
+
+.glyphicon-collapse-down:before {
+  content: "\e159";
+}
+
+.glyphicon-collapse-up:before {
+  content: "\e160";
+}
+
+.glyphicon-log-in:before {
+  content: "\e161";
+}
+
+.glyphicon-flash:before {
+  content: "\e162";
+}
+
+.glyphicon-log-out:before {
+  content: "\e163";
+}
+
+.glyphicon-new-window:before {
+  content: "\e164";
+}
+
+.glyphicon-record:before {
+  content: "\e165";
+}
+
+.glyphicon-save:before {
+  content: "\e166";
+}
+
+.glyphicon-open:before {
+  content: "\e167";
+}
+
+.glyphicon-saved:before {
+  content: "\e168";
+}
+
+.glyphicon-import:before {
+  content: "\e169";
+}
+
+.glyphicon-export:before {
+  content: "\e170";
+}
+
+.glyphicon-send:before {
+  content: "\e171";
+}
+
+.glyphicon-floppy-disk:before {
+  content: "\e172";
+}
+
+.glyphicon-floppy-saved:before {
+  content: "\e173";
+}
+
+.glyphicon-floppy-remove:before {
+  content: "\e174";
+}
+
+.glyphicon-floppy-save:before {
+  content: "\e175";
+}
+
+.glyphicon-floppy-open:before {
+  content: "\e176";
+}
+
+.glyphicon-credit-card:before {
+  content: "\e177";
+}
+
+.glyphicon-transfer:before {
+  content: "\e178";
+}
+
+.glyphicon-cutlery:before {
+  content: "\e179";
+}
+
+.glyphicon-header:before {
+  content: "\e180";
+}
+
+.glyphicon-compressed:before {
+  content: "\e181";
+}
+
+.glyphicon-earphone:before {
+  content: "\e182";
+}
+
+.glyphicon-phone-alt:before {
+  content: "\e183";
+}
+
+.glyphicon-tower:before {
+  content: "\e184";
+}
+
+.glyphicon-stats:before {
+  content: "\e185";
+}
+
+.glyphicon-sd-video:before {
+  content: "\e186";
+}
+
+.glyphicon-hd-video:before {
+  content: "\e187";
+}
+
+.glyphicon-subtitles:before {
+  content: "\e188";
+}
+
+.glyphicon-sound-stereo:before {
+  content: "\e189";
+}
+
+.glyphicon-sound-dolby:before {
+  content: "\e190";
+}
+
+.glyphicon-sound-5-1:before {
+  content: "\e191";
+}
+
+.glyphicon-sound-6-1:before {
+  content: "\e192";
+}
+
+.glyphicon-sound-7-1:before {
+  content: "\e193";
+}
+
+.glyphicon-copyright-mark:before {
+  content: "\e194";
+}
+
+.glyphicon-registration-mark:before {
+  content: "\e195";
+}
+
+.glyphicon-cloud-download:before {
+  content: "\e197";
+}
+
+.glyphicon-cloud-upload:before {
+  content: "\e198";
+}
+
+.glyphicon-tree-conifer:before {
+  content: "\e199";
+}
+
+.glyphicon-tree-deciduous:before {
+  content: "\e200";
+}
+
+.glyphicon-briefcase:before {
+  content: "\1f4bc";
+}
+
+.glyphicon-calendar:before {
+  content: "\1f4c5";
+}
+
+.glyphicon-pushpin:before {
+  content: "\1f4cc";
+}
+
+.glyphicon-paperclip:before {
+  content: "\1f4ce";
+}
+
+.glyphicon-camera:before {
+  content: "\1f4f7";
+}
+
+.glyphicon-lock:before {
+  content: "\1f512";
+}
+
+.glyphicon-bell:before {
+  content: "\1f514";
+}
+
+.glyphicon-bookmark:before {
+  content: "\1f516";
+}
+
+.glyphicon-fire:before {
+  content: "\1f525";
+}
+
+.glyphicon-wrench:before {
+  content: "\1f527";
+}
+
+.caret {
+  display: inline-block;
+  width: 0;
+  height: 0;
+  margin-left: 2px;
+  vertical-align: middle;
+  border-top: 4px solid #000000;
+  border-right: 4px solid transparent;
+  border-bottom: 0 dotted;
+  border-left: 4px solid transparent;
+  content: "";
+}
+
+.dropdown {
+  position: relative;
+}
+
+.dropdown-toggle:focus {
+  outline: 0;
+}
+
+.dropdown-menu {
+  position: absolute;
+  top: 100%;
+  left: 0;
+  z-index: 1000;
+  display: none;
+  float: left;
+  min-width: 160px;
+  padding: 5px 0;
+  margin: 2px 0 0;
+  font-size: 14px;
+  list-style: none;
+  background-color: #ffffff;
+  border: 1px solid #cccccc;
+  border: 1px solid rgba(0, 0, 0, 0.15);
+  border-radius: 4px;
+  -webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
+          box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
+  background-clip: padding-box;
+}
+
+.dropdown-menu.pull-right {
+  right: 0;
+  left: auto;
+}
+
+.dropdown-menu .divider {
+  height: 1px;
+  margin: 9px 0;
+  overflow: hidden;
+  background-color: #e5e5e5;
+}
+
+.dropdown-menu > li > a {
+  display: block;
+  padding: 3px 20px;
+  clear: both;
+  font-weight: normal;
+  line-height: 1.428571429;
+  color: #333333;
+  white-space: nowrap;
+}
+
+.dropdown-menu > li > a:hover,
+.dropdown-menu > li > a:focus {
+  color: #ffffff;
+  text-decoration: none;
+  background-color: #428bca;
+}
+
+.dropdown-menu > .active > a,
+.dropdown-menu > .active > a:hover,
+.dropdown-menu > .active > a:focus {
+  color: #ffffff;
+  text-decoration: none;
+  background-color: #428bca;
+  outline: 0;
+}
+
+.dropdown-menu > .disabled > a,
+.dropdown-menu > .disabled > a:hover,
+.dropdown-menu > .disabled > a:focus {
+  color: #999999;
+}
+
+.dropdown-menu > .disabled > a:hover,
+.dropdown-menu > .disabled > a:focus {
+  text-decoration: none;
+  cursor: not-allowed;
+  background-color: transparent;
+  background-image: none;
+  filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);
+}
+
+.open > .dropdown-menu {
+  display: block;
+}
+
+.open > a {
+  outline: 0;
+}
+
+.dropdown-header {
+  display: block;
+  padding: 3px 20px;
+  font-size: 12px;
+  line-height: 1.428571429;
+  color: #999999;
+}
+
+.dropdown-backdrop {
+  position: fixed;
+  top: 0;
+  right: 0;
+  bottom: 0;
+  left: 0;
+  z-index: 990;
+}
+
+.pull-right > .dropdown-menu {
+  right: 0;
+  left: auto;
+}
+
+.dropup .caret,
+.navbar-fixed-bottom .dropdown .caret {
+  border-top: 0 dotted;
+  border-bottom: 4px solid #000000;
+  content: "";
+}
+
+.dropup .dropdown-menu,
+.navbar-fixed-bottom .dropdown .dropdown-menu {
+  top: auto;
+  bottom: 100%;
+  margin-bottom: 1px;
+}
+
+@media (min-width: 768px) {
+  .navbar-right .dropdown-menu {
+    right: 0;
+    left: auto;
+  }
+}
+
+.btn-default .caret {
+  border-top-color: #333333;
+}
+
+.btn-primary .caret,
+.btn-success .caret,
+.btn-warning .caret,
+.btn-danger .caret,
+.btn-info .caret {
+  border-top-color: #fff;
+}
+
+.dropup .btn-default .caret {
+  border-bottom-color: #333333;
+}
+
+.dropup .btn-primary .caret,
+.dropup .btn-success .caret,
+.dropup .btn-warning .caret,
+.dropup .btn-danger .caret,
+.dropup .btn-info .caret {
+  border-bottom-color: #fff;
+}
+
+.btn-group,
+.btn-group-vertical {
+  position: relative;
+  display: inline-block;
+  vertical-align: middle;
+}
+
+.btn-group > .btn,
+.btn-group-vertical > .btn {
+  position: relative;
+  float: left;
+}
+
+.btn-group > .btn:hover,
+.btn-group-vertical > .btn:hover,
+.btn-group > .btn:focus,
+.btn-group-vertical > .btn:focus,
+.btn-group > .btn:active,
+.btn-group-vertical > .btn:active,
+.btn-group > .btn.active,
+.btn-group-vertical > .btn.active {
+  z-index: 2;
+}
+
+.btn-group > .btn:focus,
+.btn-group-vertical > .btn:focus {
+  outline: none;
+}
+
+.btn-group .btn + .btn,
+.btn-group .btn + .btn-group,
+.btn-group .btn-group + .btn,
+.btn-group .btn-group + .btn-group {
+  margin-left: -1px;
+}
+
+.btn-toolbar:before,
+.btn-toolbar:after {
+  display: table;
+  content: " ";
+}
+
+.btn-toolbar:after {
+  clear: both;
+}
+
+.btn-toolbar:before,
+.btn-toolbar:after {
+  display: table;
+  content: " ";
+}
+
+.btn-toolbar:after {
+  clear: both;
+}
+
+.btn-toolbar .btn-group {
+  float: left;
+}
+
+.btn-toolbar > .btn + .btn,
+.btn-toolbar > .btn-group + .btn,
+.btn-toolbar > .btn + .btn-group,
+.btn-toolbar > .btn-group + .btn-group {
+  margin-left: 5px;
+}
+
+.btn-group > .btn:not(:first-child):not(:last-child):not(.dropdown-toggle) {
+  border-radius: 0;
+}
+
+.btn-group > .btn:first-child {
+  margin-left: 0;
+}
+
+.btn-group > .btn:first-child:not(:last-child):not(.dropdown-toggle) {
+  border-top-right-radius: 0;
+  border-bottom-right-radius: 0;
+}
+
+.btn-group > .btn:last-child:not(:first-child),
+.btn-group > .dropdown-toggle:not(:first-child) {
+  border-bottom-left-radius: 0;
+  border-top-left-radius: 0;
+}
+
+.btn-group > .btn-group {
+  float: left;
+}
+
+.btn-group > .btn-group:not(:first-child):not(:last-child) > .btn {
+  border-radius: 0;
+}
+
+.btn-group > .btn-group:first-child > .btn:last-child,
+.btn-group > .btn-group:first-child > .dropdown-toggle {
+  border-top-right-radius: 0;
+  border-bottom-right-radius: 0;
+}
+
+.btn-group > .btn-group:last-child > .btn:first-child {
+  border-bottom-left-radius: 0;
+  border-top-left-radius: 0;
+}
+
+.btn-group .dropdown-toggle:active,
+.btn-group.open .dropdown-toggle {
+  outline: 0;
+}
+
+.btn-group-xs > .btn {
+  padding: 5px 10px;
+  padding: 1px 5px;
+  font-size: 12px;
+  line-height: 1.5;
+  border-radius: 3px;
+}
+
+.btn-group-sm > .btn {
+  padding: 5px 10px;
+  font-size: 12px;
+  line-height: 1.5;
+  border-radius: 3px;
+}
+
+.btn-group-lg > .btn {
+  padding: 10px 16px;
+  font-size: 18px;
+  line-height: 1.33;
+  border-radius: 6px;
+}
+
+.btn-group > .btn + .dropdown-toggle {
+  padding-right: 8px;
+  padding-left: 8px;
+}
+
+.btn-group > .btn-lg + .dropdown-toggle {
+  padding-right: 12px;
+  padding-left: 12px;
+}
+
+.btn-group.open .dropdown-toggle {
+  -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
+          box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
+}
+
+.btn .caret {
+  margin-left: 0;
+}
+
+.btn-lg .caret {
+  border-width: 5px 5px 0;
+  border-bottom-width: 0;
+}
+
+.dropup .btn-lg .caret {
+  border-width: 0 5px 5px;
+}
+
+.btn-group-vertical > .btn,
+.btn-group-vertical > .btn-group {
+  display: block;
+  float: none;
+  width: 100%;
+  max-width: 100%;
+}
+
+.btn-group-vertical > .btn-group:before,
+.btn-group-vertical > .btn-group:after {
+  display: table;
+  content: " ";
+}
+
+.btn-group-vertical > .btn-group:after {
+  clear: both;
+}
+
+.btn-group-vertical > .btn-group:before,
+.btn-group-vertical > .btn-group:after {
+  display: table;
+  content: " ";
+}
+
+.btn-group-vertical > .btn-group:after {
+  clear: both;
+}
+
+.btn-group-vertical > .btn-group > .btn {
+  float: none;
+}
+
+.btn-group-vertical > .btn + .btn,
+.btn-group-vertical > .btn + .btn-group,
+.btn-group-vertical > .btn-group + .btn,
+.btn-group-vertical > .btn-group + .btn-group {
+  margin-top: -1px;
+  margin-left: 0;
+}
+
+.btn-group-vertical > .btn:not(:first-child):not(:last-child) {
+  border-radius: 0;
+}
+
+.btn-group-vertical > .btn:first-child:not(:last-child) {
+  border-top-right-radius: 4px;
+  border-bottom-right-radius: 0;
+  border-bottom-left-radius: 0;
+}
+
+.btn-group-vertical > .btn:last-child:not(:first-child) {
+  border-top-right-radius: 0;
+  border-bottom-left-radius: 4px;
+  border-top-left-radius: 0;
+}
+
+.btn-group-vertical > .btn-group:not(:first-child):not(:last-child) > .btn {
+  border-radius: 0;
+}
+
+.btn-group-vertical > .btn-group:first-child > .btn:last-child,
+.btn-group-vertical > .btn-group:first-child > .dropdown-toggle {
+  border-bottom-right-radius: 0;
+  border-bottom-left-radius: 0;
+}
+
+.btn-group-vertical > .btn-group:last-child > .btn:first-child {
+  border-top-right-radius: 0;
+  border-top-left-radius: 0;
+}
+
+.btn-group-justified {
+  display: table;
+  width: 100%;
+  border-collapse: separate;
+  table-layout: fixed;
+}
+
+.btn-group-justified .btn {
+  display: table-cell;
+  float: none;
+  width: 1%;
+}
+
+[data-toggle="buttons"] > .btn > input[type="radio"],
+[data-toggle="buttons"] > .btn > input[type="checkbox"] {
+  display: none;
+}
+
+.input-group {
+  position: relative;
+  display: table;
+  border-collapse: separate;
+}
+
+.input-group.col {
+  float: none;
+  padding-right: 0;
+  padding-left: 0;
+}
+
+.input-group .form-control {
+  width: 100%;
+  margin-bottom: 0;
+}
+
+.input-group-lg > .form-control,
+.input-group-lg > .input-group-addon,
+.input-group-lg > .input-group-btn > .btn {
+  height: 45px;
+  padding: 10px 16px;
+  font-size: 18px;
+  line-height: 1.33;
+  border-radius: 6px;
+}
+
+select.input-group-lg > .form-control,
+select.input-group-lg > .input-group-addon,
+select.input-group-lg > .input-group-btn > .btn {
+  height: 45px;
+  line-height: 45px;
+}
+
+textarea.input-group-lg > .form-control,
+textarea.input-group-lg > .input-group-addon,
+textarea.input-group-lg > .input-group-btn > .btn {
+  height: auto;
+}
+
+.input-group-sm > .form-control,
+.input-group-sm > .input-group-addon,
+.input-group-sm > .input-group-btn > .btn {
+  height: 30px;
+  padding: 5px 10px;
+  font-size: 12px;
+  line-height: 1.5;
+  border-radius: 3px;
+}
+
+select.input-group-sm > .form-control,
+select.input-group-sm > .input-group-addon,
+select.input-group-sm > .input-group-btn > .btn {
+  height: 30px;
+  line-height: 30px;
+}
+
+textarea.input-group-sm > .form-control,
+textarea.input-group-sm > .input-group-addon,
+textarea.input-group-sm > .input-group-btn > .btn {
+  height: auto;
+}
+
+.input-group-addon,
+.input-group-btn,
+.input-group .form-control {
+  display: table-cell;
+}
+
+.input-group-addon:not(:first-child):not(:last-child),
+.input-group-btn:not(:first-child):not(:last-child),
+.input-group .form-control:not(:first-child):not(:last-child) {
+  border-radius: 0;
+}
+
+.input-group-addon,
+.input-group-btn {
+  width: 1%;
+  white-space: nowrap;
+  vertical-align: middle;
+}
+
+.input-group-addon {
+  padding: 6px 12px;
+  font-size: 14px;
+  font-weight: normal;
+  line-height: 1;
+  text-align: center;
+  background-color: #eeeeee;
+  border: 1px solid #cccccc;
+  border-radius: 4px;
+}
+
+.input-group-addon.input-sm {
+  padding: 5px 10px;
+  font-size: 12px;
+  border-radius: 3px;
+}
+
+.input-group-addon.input-lg {
+  padding: 10px 16px;
+  font-size: 18px;
+  border-radius: 6px;
+}
+
+.input-group-addon input[type="radio"],
+.input-group-addon input[type="checkbox"] {
+  margin-top: 0;
+}
+
+.input-group .form-control:first-child,
+.input-group-addon:first-child,
+.input-group-btn:first-child > .btn,
+.input-group-btn:first-child > .dropdown-toggle,
+.input-group-btn:last-child > .btn:not(:last-child):not(.dropdown-toggle) {
+  border-top-right-radius: 0;
+  border-bottom-right-radius: 0;
+}
+
+.input-group-addon:first-child {
+  border-right: 0;
+}
+
+.input-group .form-control:last-child,
+.input-group-addon:last-child,
+.input-group-btn:last-child > .btn,
+.input-group-btn:last-child > .dropdown-toggle,
+.input-group-btn:first-child > .btn:not(:first-child) {
+  border-bottom-left-radius: 0;
+  border-top-left-radius: 0;
+}
+
+.input-group-addon:last-child {
+  border-left: 0;
+}
+
+.input-group-btn {
+  position: relative;
+  white-space: nowrap;
+}
+
+.input-group-btn > .btn {
+  position: relative;
+}
+
+.input-group-btn > .btn + .btn {
+  margin-left: -4px;
+}
+
+.input-group-btn > .btn:hover,
+.input-group-btn > .btn:active {
+  z-index: 2;
+}
+
+.nav {
+  padding-left: 0;
+  margin-bottom: 0;
+  list-style: none;
+}
+
+.nav:before,
+.nav:after {
+  display: table;
+  content: " ";
+}
+
+.nav:after {
+  clear: both;
+}
+
+.nav:before,
+.nav:after {
+  display: table;
+  content: " ";
+}
+
+.nav:after {
+  clear: both;
+}
+
+.nav > li {
+  position: relative;
+  display: block;
+}
+
+.nav > li > a {
+  position: relative;
+  display: block;
+  padding: 10px 15px;
+}
+
+.nav > li > a:hover,
+.nav > li > a:focus {
+  text-decoration: none;
+  background-color: #eeeeee;
+}
+
+.nav > li.disabled > a {
+  color: #999999;
+}
+
+.nav > li.disabled > a:hover,
+.nav > li.disabled > a:focus {
+  color: #999999;
+  text-decoration: none;
+  cursor: not-allowed;
+  background-color: transparent;
+}
+
+.nav .open > a,
+.nav .open > a:hover,
+.nav .open > a:focus {
+  background-color: #eeeeee;
+  border-color: #428bca;
+}
+
+.nav .nav-divider {
+  height: 1px;
+  margin: 9px 0;
+  overflow: hidden;
+  background-color: #e5e5e5;
+}
+
+.nav > li > a > img {
+  max-width: none;
+}
+
+.nav-tabs {
+  border-bottom: 1px solid #dddddd;
+}
+
+.nav-tabs > li {
+  float: left;
+  margin-bottom: -1px;
+}
+
+.nav-tabs > li > a {
+  margin-right: 2px;
+  line-height: 1.428571429;
+  border: 1px solid transparent;
+  border-radius: 4px 4px 0 0;
+}
+
+.nav-tabs > li > a:hover {
+  border-color: #eeeeee #eeeeee #dddddd;
+}
+
+.nav-tabs > li.active > a,
+.nav-tabs > li.active > a:hover,
+.nav-tabs > li.active > a:focus {
+  color: #555555;
+  cursor: default;
+  background-color: #ffffff;
+  border: 1px solid #dddddd;
+  border-bottom-color: transparent;
+}
+
+.nav-tabs.nav-justified {
+  width: 100%;
+  border-bottom: 0;
+}
+
+.nav-tabs.nav-justified > li {
+  float: none;
+}
+
+.nav-tabs.nav-justified > li > a {
+  text-align: center;
+}
+
+@media (min-width: 768px) {
+  .nav-tabs.nav-justified > li {
+    display: table-cell;
+    width: 1%;
+  }
+}
+
+.nav-tabs.nav-justified > li > a {
+  margin-right: 0;
+  border-bottom: 1px solid #dddddd;
+}
+
+.nav-tabs.nav-justified > .active > a {
+  border-bottom-color: #ffffff;
+}
+
+.nav-pills > li {
+  float: left;
+}
+
+.nav-pills > li > a {
+  border-radius: 5px;
+}
+
+.nav-pills > li + li {
+  margin-left: 2px;
+}
+
+.nav-pills > li.active > a,
+.nav-pills > li.active > a:hover,
+.nav-pills > li.active > a:focus {
+  color: #ffffff;
+  background-color: #428bca;
+}
+
+.nav-stacked > li {
+  float: none;
+}
+
+.nav-stacked > li + li {
+  margin-top: 2px;
+  margin-left: 0;
+}
+
+.nav-justified {
+  width: 100%;
+}
+
+.nav-justified > li {
+  float: none;
+}
+
+.nav-justified > li > a {
+  text-align: center;
+}
+
+@media (min-width: 768px) {
+  .nav-justified > li {
+    display: table-cell;
+    width: 1%;
+  }
+}
+
+.nav-tabs-justified {
+  border-bottom: 0;
+}
+
+.nav-tabs-justified > li > a {
+  margin-right: 0;
+  border-bottom: 1px solid #dddddd;
+}
+
+.nav-tabs-justified > .active > a {
+  border-bottom-color: #ffffff;
+}
+
+.tabbable:before,
+.tabbable:after {
+  display: table;
+  content: " ";
+}
+
+.tabbable:after {
+  clear: both;
+}
+
+.tabbable:before,
+.tabbable:after {
+  display: table;
+  content: " ";
+}
+
+.tabbable:after {
+  clear: both;
+}
+
+.tab-content > .tab-pane,
+.pill-content > .pill-pane {
+  display: none;
+}
+
+.tab-content > .active,
+.pill-content > .active {
+  display: block;
+}
+
+.nav .caret {
+  border-top-color: #428bca;
+  border-bottom-color: #428bca;
+}
+
+.nav a:hover .caret {
+  border-top-color: #2a6496;
+  border-bottom-color: #2a6496;
+}
+
+.nav-tabs .dropdown-menu {
+  margin-top: -1px;
+  border-top-right-radius: 0;
+  border-top-left-radius: 0;
+}
+
+.navbar {
+  position: relative;
+  z-index: 1000;
+  min-height: 50px;
+  margin-bottom: 20px;
+  border: 1px solid transparent;
+}
+
+.navbar:before,
+.navbar:after {
+  display: table;
+  content: " ";
+}
+
+.navbar:after {
+  clear: both;
+}
+
+.navbar:before,
+.navbar:after {
+  display: table;
+  content: " ";
+}
+
+.navbar:after {
+  clear: both;
+}
+
+@media (min-width: 768px) {
+  .navbar {
+    border-radius: 4px;
+  }
+}
+
+.navbar-header:before,
+.navbar-header:after {
+  display: table;
+  content: " ";
+}
+
+.navbar-header:after {
+  clear: both;
+}
+
+.navbar-header:before,
+.navbar-header:after {
+  display: table;
+  content: " ";
+}
+
+.navbar-header:after {
+  clear: both;
+}
+
+@media (min-width: 768px) {
+  .navbar-header {
+    float: left;
+  }
+}
+
+.navbar-collapse {
+  max-height: 340px;
+  padding-right: 15px;
+  padding-left: 15px;
+  overflow-x: visible;
+  border-top: 1px solid transparent;
+  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1);
+  -webkit-overflow-scrolling: touch;
+}
+
+.navbar-collapse:before,
+.navbar-collapse:after {
+  display: table;
+  content: " ";
+}
+
+.navbar-collapse:after {
+  clear: both;
+}
+
+.navbar-collapse:before,
+.navbar-collapse:after {
+  display: table;
+  content: " ";
+}
+
+.navbar-collapse:after {
+  clear: both;
+}
+
+.navbar-collapse.in {
+  overflow-y: auto;
+}
+
+@media (min-width: 768px) {
+  .navbar-collapse {
+    width: auto;
+    border-top: 0;
+    box-shadow: none;
+  }
+  .navbar-collapse.collapse {
+    display: block !important;
+    height: auto !important;
+    padding-bottom: 0;
+    overflow: visible !important;
+  }
+  .navbar-collapse.in {
+    overflow-y: visible;
+  }
+  .navbar-collapse .navbar-nav.navbar-left:first-child {
+    margin-left: -15px;
+  }
+  .navbar-collapse .navbar-nav.navbar-right:last-child {
+    margin-right: -15px;
+  }
+  .navbar-collapse .navbar-text:last-child {
+    margin-right: 0;
+  }
+}
+
+.container > .navbar-header,
+.container > .navbar-collapse {
+  margin-right: -15px;
+  margin-left: -15px;
+}
+
+@media (min-width: 768px) {
+  .container > .navbar-header,
+  .container > .navbar-collapse {
+    margin-right: 0;
+    margin-left: 0;
+  }
+}
+
+.navbar-static-top {
+  border-width: 0 0 1px;
+}
+
+@media (min-width: 768px) {
+  .navbar-static-top {
+    border-radius: 0;
+  }
+}
+
+.navbar-fixed-top,
+.navbar-fixed-bottom {
+  position: fixed;
+  right: 0;
+  left: 0;
+  border-width: 0 0 1px;
+}
+
+@media (min-width: 768px) {
+  .navbar-fixed-top,
+  .navbar-fixed-bottom {
+    border-radius: 0;
+  }
+}
+
+.navbar-fixed-top {
+  top: 0;
+  z-index: 1030;
+}
+
+.navbar-fixed-bottom {
+  bottom: 0;
+  margin-bottom: 0;
+}
+
+.navbar-brand {
+  float: left;
+  padding: 15px 15px;
+  font-size: 18px;
+  line-height: 20px;
+}
+
+.navbar-brand:hover,
+.navbar-brand:focus {
+  text-decoration: none;
+}
+
+@media (min-width: 768px) {
+  .navbar > .container .navbar-brand {
+    margin-left: -15px;
+  }
+}
+
+.navbar-toggle {
+  position: relative;
+  float: right;
+  padding: 9px 10px;
+  margin-top: 8px;
+  margin-right: 15px;
+  margin-bottom: 8px;
+  background-color: transparent;
+  border: 1px solid transparent;
+  border-radius: 4px;
+}
+
+.navbar-toggle .icon-bar {
+  display: block;
+  width: 22px;
+  height: 2px;
+  border-radius: 1px;
+}
+
+.navbar-toggle .icon-bar + .icon-bar {
+  margin-top: 4px;
+}
+
+@media (min-width: 768px) {
+  .navbar-toggle {
+    display: none;
+  }
+}
+
+.navbar-nav {
+  margin: 7.5px -15px;
+}
+
+.navbar-nav > li > a {
+  padding-top: 10px;
+  padding-bottom: 10px;
+  line-height: 20px;
+}
+
+@media (max-width: 767px) {
+  .navbar-nav .open .dropdown-menu {
+    position: static;
+    float: none;
+    width: auto;
+    margin-top: 0;
+    background-color: transparent;
+    border: 0;
+    box-shadow: none;
+  }
+  .navbar-nav .open .dropdown-menu > li > a,
+  .navbar-nav .open .dropdown-menu .dropdown-header {
+    padding: 5px 15px 5px 25px;
+  }
+  .navbar-nav .open .dropdown-menu > li > a {
+    line-height: 20px;
+  }
+  .navbar-nav .open .dropdown-menu > li > a:hover,
+  .navbar-nav .open .dropdown-menu > li > a:focus {
+    background-image: none;
+  }
+}
+
+@media (min-width: 768px) {
+  .navbar-nav {
+    float: left;
+    margin: 0;
+  }
+  .navbar-nav > li {
+    float: left;
+  }
+  .navbar-nav > li > a {
+    padding-top: 15px;
+    padding-bottom: 15px;
+  }
+}
+
+@media (min-width: 768px) {
+  .navbar-left {
+    float: left !important;
+  }
+  .navbar-right {
+    float: right !important;
+  }
+}
+
+.navbar-form {
+  padding: 10px 15px;
+  margin-top: 8px;
+  margin-right: -15px;
+  margin-bottom: 8px;
+  margin-left: -15px;
+  border-top: 1px solid transparent;
+  border-bottom: 1px solid transparent;
+  -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1);
+          box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1);
+}
+
+@media (min-width: 768px) {
+  .navbar-form .form-group {
+    display: inline-block;
+    margin-bottom: 0;
+    vertical-align: middle;
+  }
+  .navbar-form .form-control {
+    display: inline-block;
+  }
+  .navbar-form .radio,
+  .navbar-form .checkbox {
+    display: inline-block;
+    padding-left: 0;
+    margin-top: 0;
+    margin-bottom: 0;
+  }
+  .navbar-form .radio input[type="radio"],
+  .navbar-form .checkbox input[type="checkbox"] {
+    float: none;
+    margin-left: 0;
+  }
+}
+
+@media (max-width: 767px) {
+  .navbar-form .form-group {
+    margin-bottom: 5px;
+  }
+}
+
+@media (min-width: 768px) {
+  .navbar-form {
+    width: auto;
+    padding-top: 0;
+    padding-bottom: 0;
+    margin-right: 0;
+    margin-left: 0;
+    border: 0;
+    -webkit-box-shadow: none;
+            box-shadow: none;
+  }
+}
+
+.navbar-nav > li > .dropdown-menu {
+  margin-top: 0;
+  border-top-right-radius: 0;
+  border-top-left-radius: 0;
+}
+
+.navbar-fixed-bottom .navbar-nav > li > .dropdown-menu {
+  border-bottom-right-radius: 0;
+  border-bottom-left-radius: 0;
+}
+
+.navbar-nav.pull-right > li > .dropdown-menu,
+.navbar-nav > li > .dropdown-menu.pull-right {
+  right: 0;
+  left: auto;
+}
+
+.navbar-btn {
+  margin-top: 8px;
+  margin-bottom: 8px;
+}
+
+.navbar-text {
+  float: left;
+  margin-top: 15px;
+  margin-bottom: 15px;
+}
+
+@media (min-width: 768px) {
+  .navbar-text {
+    margin-right: 15px;
+    margin-left: 15px;
+  }
+}
+
+.navbar-default {
+  background-color: #f8f8f8;
+  border-color: #e7e7e7;
+}
+
+.navbar-default .navbar-brand {
+  color: #777777;
+}
+
+.navbar-default .navbar-brand:hover,
+.navbar-default .navbar-brand:focus {
+  color: #5e5e5e;
+  background-color: transparent;
+}
+
+.navbar-default .navbar-text {
+  color: #777777;
+}
+
+.navbar-default .navbar-nav > li > a {
+  color: #777777;
+}
+
+.navbar-default .navbar-nav > li > a:hover,
+.navbar-default .navbar-nav > li > a:focus {
+  color: #333333;
+  background-color: transparent;
+}
+
+.navbar-default .navbar-nav > .active > a,
+.navbar-default .navbar-nav > .active > a:hover,
+.navbar-default .navbar-nav > .active > a:focus {
+  color: #555555;
+  background-color: #e7e7e7;
+}
+
+.navbar-default .navbar-nav > .disabled > a,
+.navbar-default .navbar-nav > .disabled > a:hover,
+.navbar-default .navbar-nav > .disabled > a:focus {
+  color: #cccccc;
+  background-color: transparent;
+}
+
+.navbar-default .navbar-toggle {
+  border-color: #dddddd;
+}
+
+.navbar-default .navbar-toggle:hover,
+.navbar-default .navbar-toggle:focus {
+  background-color: #dddddd;
+}
+
+.navbar-default .navbar-toggle .icon-bar {
+  background-color: #cccccc;
+}
+
+.navbar-default .navbar-collapse,
+.navbar-default .navbar-form {
+  border-color: #e6e6e6;
+}
+
+.navbar-default .navbar-nav > .dropdown > a:hover .caret,
+.navbar-default .navbar-nav > .dropdown > a:focus .caret {
+  border-top-color: #333333;
+  border-bottom-color: #333333;
+}
+
+.navbar-default .navbar-nav > .open > a,
+.navbar-default .navbar-nav > .open > a:hover,
+.navbar-default .navbar-nav > .open > a:focus {
+  color: #555555;
+  background-color: #e7e7e7;
+}
+
+.navbar-default .navbar-nav > .open > a .caret,
+.navbar-default .navbar-nav > .open > a:hover .caret,
+.navbar-default .navbar-nav > .open > a:focus .caret {
+  border-top-color: #555555;
+  border-bottom-color: #555555;
+}
+
+.navbar-default .navbar-nav > .dropdown > a .caret {
+  border-top-color: #777777;
+  border-bottom-color: #777777;
+}
+
+@media (max-width: 767px) {
+  .navbar-default .navbar-nav .open .dropdown-menu > li > a {
+    color: #777777;
+  }
+  .navbar-default .navbar-nav .open .dropdown-menu > li > a:hover,
+  .navbar-default .navbar-nav .open .dropdown-menu > li > a:focus {
+    color: #333333;
+    background-color: transparent;
+  }
+  .navbar-default .navbar-nav .open .dropdown-menu > .active > a,
+  .navbar-default .navbar-nav .open .dropdown-menu > .active > a:hover,
+  .navbar-default .navbar-nav .open .dropdown-menu > .active > a:focus {
+    color: #555555;
+    background-color: #e7e7e7;
+  }
+  .navbar-default .navbar-nav .open .dropdown-menu > .disabled > a,
+  .navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:hover,
+  .navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:focus {
+    color: #cccccc;
+    background-color: transparent;
+  }
+}
+
+.navbar-default .navbar-link {
+  color: #777777;
+}
+
+.navbar-default .navbar-link:hover {
+  color: #333333;
+}
+
+.navbar-inverse {
+  background-color: #222222;
+  border-color: #080808;
+}
+
+.navbar-inverse .navbar-brand {
+  color: #999999;
+}
+
+.navbar-inverse .navbar-brand:hover,
+.navbar-inverse .navbar-brand:focus {
+  color: #ffffff;
+  background-color: transparent;
+}
+
+.navbar-inverse .navbar-text {
+  color: #999999;
+}
+
+.navbar-inverse .navbar-nav > li > a {
+  color: #999999;
+}
+
+.navbar-inverse .navbar-nav > li > a:hover,
+.navbar-inverse .navbar-nav > li > a:focus {
+  color: #ffffff;
+  background-color: transparent;
+}
+
+.navbar-inverse .navbar-nav > .active > a,
+.navbar-inverse .navbar-nav > .active > a:hover,
+.navbar-inverse .navbar-nav > .active > a:focus {
+  color: #ffffff;
+  background-color: #080808;
+}
+
+.navbar-inverse .navbar-nav > .disabled > a,
+.navbar-inverse .navbar-nav > .disabled > a:hover,
+.navbar-inverse .navbar-nav > .disabled > a:focus {
+  color: #444444;
+  background-color: transparent;
+}
+
+.navbar-inverse .navbar-toggle {
+  border-color: #333333;
+}
+
+.navbar-inverse .navbar-toggle:hover,
+.navbar-inverse .navbar-toggle:focus {
+  background-color: #333333;
+}
+
+.navbar-inverse .navbar-toggle .icon-bar {
+  background-color: #ffffff;
+}
+
+.navbar-inverse .navbar-collapse,
+.navbar-inverse .navbar-form {
+  border-color: #101010;
+}
+
+.navbar-inverse .navbar-nav > .open > a,
+.navbar-inverse .navbar-nav > .open > a:hover,
+.navbar-inverse .navbar-nav > .open > a:focus {
+  color: #ffffff;
+  background-color: #080808;
+}
+
+.navbar-inverse .navbar-nav > .dropdown > a:hover .caret {
+  border-top-color: #ffffff;
+  border-bottom-color: #ffffff;
+}
+
+.navbar-inverse .navbar-nav > .dropdown > a .caret {
+  border-top-color: #999999;
+  border-bottom-color: #999999;
+}
+
+.navbar-inverse .navbar-nav > .open > a .caret,
+.navbar-inverse .navbar-nav > .open > a:hover .caret,
+.navbar-inverse .navbar-nav > .open > a:focus .caret {
+  border-top-color: #ffffff;
+  border-bottom-color: #ffffff;
+}
+
+@media (max-width: 767px) {
+  .navbar-inverse .navbar-nav .open .dropdown-menu > .dropdown-header {
+    border-color: #080808;
+  }
+  .navbar-inverse .navbar-nav .open .dropdown-menu > li > a {
+    color: #999999;
+  }
+  .navbar-inverse .navbar-nav .open .dropdown-menu > li > a:hover,
+  .navbar-inverse .navbar-nav .open .dropdown-menu > li > a:focus {
+    color: #ffffff;
+    background-color: transparent;
+  }
+  .navbar-inverse .navbar-nav .open .dropdown-menu > .active > a,
+  .navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:hover,
+  .navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:focus {
+    color: #ffffff;
+    background-color: #080808;
+  }
+  .navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a,
+  .navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:hover,
+  .navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:focus {
+    color: #444444;
+    background-color: transparent;
+  }
+}
+
+.navbar-inverse .navbar-link {
+  color: #999999;
+}
+
+.navbar-inverse .navbar-link:hover {
+  color: #ffffff;
+}
+
+.breadcrumb {
+  padding: 8px 15px;
+  margin-bottom: 20px;
+  list-style: none;
+  background-color: #f5f5f5;
+  border-radius: 4px;
+}
+
+.breadcrumb > li {
+  display: inline-block;
+}
+
+.breadcrumb > li + li:before {
+  padding: 0 5px;
+  color: #cccccc;
+  content: "/\00a0";
+}
+
+.breadcrumb > .active {
+  color: #999999;
+}
+
+.pagination {
+  display: inline-block;
+  padding-left: 0;
+  margin: 20px 0;
+  border-radius: 4px;
+}
+
+.pagination > li {
+  display: inline;
+}
+
+.pagination > li > a,
+.pagination > li > span {
+  position: relative;
+  float: left;
+  padding: 6px 12px;
+  margin-left: -1px;
+  line-height: 1.428571429;
+  text-decoration: none;
+  background-color: #ffffff;
+  border: 1px solid #dddddd;
+}
+
+.pagination > li:first-child > a,
+.pagination > li:first-child > span {
+  margin-left: 0;
+  border-bottom-left-radius: 4px;
+  border-top-left-radius: 4px;
+}
+
+.pagination > li:last-child > a,
+.pagination > li:last-child > span {
+  border-top-right-radius: 4px;
+  border-bottom-right-radius: 4px;
+}
+
+.pagination > li > a:hover,
+.pagination > li > span:hover,
+.pagination > li > a:focus,
+.pagination > li > span:focus {
+  background-color: #eeeeee;
+}
+
+.pagination > .active > a,
+.pagination > .active > span,
+.pagination > .active > a:hover,
+.pagination > .active > span:hover,
+.pagination > .active > a:focus,
+.pagination > .active > span:focus {
+  z-index: 2;
+  color: #ffffff;
+  cursor: default;
+  background-color: #428bca;
+  border-color: #428bca;
+}
+
+.pagination > .disabled > span,
+.pagination > .disabled > a,
+.pagination > .disabled > a:hover,
+.pagination > .disabled > a:focus {
+  color: #999999;
+  cursor: not-allowed;
+  background-color: #ffffff;
+  border-color: #dddddd;
+}
+
+.pagination-lg > li > a,
+.pagination-lg > li > span {
+  padding: 10px 16px;
+  font-size: 18px;
+}
+
+.pagination-lg > li:first-child > a,
+.pagination-lg > li:first-child > span {
+  border-bottom-left-radius: 6px;
+  border-top-left-radius: 6px;
+}
+
+.pagination-lg > li:last-child > a,
+.pagination-lg > li:last-child > span {
+  border-top-right-radius: 6px;
+  border-bottom-right-radius: 6px;
+}
+
+.pagination-sm > li > a,
+.pagination-sm > li > span {
+  padding: 5px 10px;
+  font-size: 12px;
+}
+
+.pagination-sm > li:first-child > a,
+.pagination-sm > li:first-child > span {
+  border-bottom-left-radius: 3px;
+  border-top-left-radius: 3px;
+}
+
+.pagination-sm > li:last-child > a,
+.pagination-sm > li:last-child > span {
+  border-top-right-radius: 3px;
+  border-bottom-right-radius: 3px;
+}
+
+.pager {
+  padding-left: 0;
+  margin: 20px 0;
+  text-align: center;
+  list-style: none;
+}
+
+.pager:before,
+.pager:after {
+  display: table;
+  content: " ";
+}
+
+.pager:after {
+  clear: both;
+}
+
+.pager:before,
+.pager:after {
+  display: table;
+  content: " ";
+}
+
+.pager:after {
+  clear: both;
+}
+
+.pager li {
+  display: inline;
+}
+
+.pager li > a,
+.pager li > span {
+  display: inline-block;
+  padding: 5px 14px;
+  background-color: #ffffff;
+  border: 1px solid #dddddd;
+  border-radius: 15px;
+}
+
+.pager li > a:hover,
+.pager li > a:focus {
+  text-decoration: none;
+  background-color: #eeeeee;
+}
+
+.pager .next > a,
+.pager .next > span {
+  float: right;
+}
+
+.pager .previous > a,
+.pager .previous > span {
+  float: left;
+}
+
+.pager .disabled > a,
+.pager .disabled > a:hover,
+.pager .disabled > a:focus,
+.pager .disabled > span {
+  color: #999999;
+  cursor: not-allowed;
+  background-color: #ffffff;
+}
+
+.label {
+  display: inline;
+  padding: .2em .6em .3em;
+  font-size: 75%;
+  font-weight: bold;
+  line-height: 1;
+  color: #ffffff;
+  text-align: center;
+  white-space: nowrap;
+  vertical-align: baseline;
+  border-radius: .25em;
+}
+
+.label[href]:hover,
+.label[href]:focus {
+  color: #ffffff;
+  text-decoration: none;
+  cursor: pointer;
+}
+
+.label:empty {
+  display: none;
+}
+
+.label-default {
+  background-color: #999999;
+}
+
+.label-default[href]:hover,
+.label-default[href]:focus {
+  background-color: #808080;
+}
+
+.label-primary {
+  background-color: #428bca;
+}
+
+.label-primary[href]:hover,
+.label-primary[href]:focus {
+  background-color: #3071a9;
+}
+
+.label-success {
+  background-color: #5cb85c;
+}
+
+.label-success[href]:hover,
+.label-success[href]:focus {
+  background-color: #449d44;
+}
+
+.label-info {
+  background-color: #5bc0de;
+}
+
+.label-info[href]:hover,
+.label-info[href]:focus {
+  background-color: #31b0d5;
+}
+
+.label-warning {
+  background-color: #f0ad4e;
+}
+
+.label-warning[href]:hover,
+.label-warning[href]:focus {
+  background-color: #ec971f;
+}
+
+.label-danger {
+  background-color: #d9534f;
+}
+
+.label-danger[href]:hover,
+.label-danger[href]:focus {
+  background-color: #c9302c;
+}
+
+.badge {
+  display: inline-block;
+  min-width: 10px;
+  padding: 3px 7px;
+  font-size: 12px;
+  font-weight: bold;
+  line-height: 1;
+  color: #ffffff;
+  text-align: center;
+  white-space: nowrap;
+  vertical-align: baseline;
+  background-color: #999999;
+  border-radius: 10px;
+}
+
+.badge:empty {
+  display: none;
+}
+
+a.badge:hover,
+a.badge:focus {
+  color: #ffffff;
+  text-decoration: none;
+  cursor: pointer;
+}
+
+.btn .badge {
+  position: relative;
+  top: -1px;
+}
+
+a.list-group-item.active > .badge,
+.nav-pills > .active > a > .badge {
+  color: #428bca;
+  background-color: #ffffff;
+}
+
+.nav-pills > li > a > .badge {
+  margin-left: 3px;
+}
+
+.jumbotron {
+  padding: 30px;
+  margin-bottom: 30px;
+  font-size: 21px;
+  font-weight: 200;
+  line-height: 2.1428571435;
+  color: inherit;
+  background-color: #eeeeee;
+}
+
+.jumbotron h1 {
+  line-height: 1;
+  color: inherit;
+}
+
+.jumbotron p {
+  line-height: 1.4;
+}
+
+.container .jumbotron {
+  border-radius: 6px;
+}
+
+@media screen and (min-width: 768px) {
+  .jumbotron {
+    padding-top: 48px;
+    padding-bottom: 48px;
+  }
+  .container .jumbotron {
+    padding-right: 60px;
+    padding-left: 60px;
+  }
+  .jumbotron h1 {
+    font-size: 63px;
+  }
+}
+
+.thumbnail {
+  display: inline-block;
+  display: block;
+  height: auto;
+  max-width: 100%;
+  padding: 4px;
+  line-height: 1.428571429;
+  background-color: #ffffff;
+  border: 1px solid #dddddd;
+  border-radius: 4px;
+  -webkit-transition: all 0.2s ease-in-out;
+          transition: all 0.2s ease-in-out;
+}
+
+.thumbnail > img {
+  display: block;
+  height: auto;
+  max-width: 100%;
+}
+
+a.thumbnail:hover,
+a.thumbnail:focus {
+  border-color: #428bca;
+}
+
+.thumbnail > img {
+  margin-right: auto;
+  margin-left: auto;
+}
+
+.thumbnail .caption {
+  padding: 9px;
+  color: #333333;
+}
+
+.alert {
+  padding: 15px;
+  margin-bottom: 20px;
+  border: 1px solid transparent;
+  border-radius: 4px;
+}
+
+.alert h4 {
+  margin-top: 0;
+  color: inherit;
+}
+
+.alert .alert-link {
+  font-weight: bold;
+}
+
+.alert > p,
+.alert > ul {
+  margin-bottom: 0;
+}
+
+.alert > p + p {
+  margin-top: 5px;
+}
+
+.alert-dismissable {
+  padding-right: 35px;
+}
+
+.alert-dismissable .close {
+  position: relative;
+  top: -2px;
+  right: -21px;
+  color: inherit;
+}
+
+.alert-success {
+  color: #468847;
+  background-color: #dff0d8;
+  border-color: #d6e9c6;
+}
+
+.alert-success hr {
+  border-top-color: #c9e2b3;
+}
+
+.alert-success .alert-link {
+  color: #356635;
+}
+
+.alert-info {
+  color: #3a87ad;
+  background-color: #d9edf7;
+  border-color: #bce8f1;
+}
+
+.alert-info hr {
+  border-top-color: #a6e1ec;
+}
+
+.alert-info .alert-link {
+  color: #2d6987;
+}
+
+.alert-warning {
+  color: #c09853;
+  background-color: #fcf8e3;
+  border-color: #fbeed5;
+}
+
+.alert-warning hr {
+  border-top-color: #f8e5be;
+}
+
+.alert-warning .alert-link {
+  color: #a47e3c;
+}
+
+.alert-danger {
+  color: #b94a48;
+  background-color: #f2dede;
+  border-color: #eed3d7;
+}
+
+.alert-danger hr {
+  border-top-color: #e6c1c7;
+}
+
+.alert-danger .alert-link {
+  color: #953b39;
+}
+
+@-webkit-keyframes progress-bar-stripes {
+  from {
+    background-position: 40px 0;
+  }
+  to {
+    background-position: 0 0;
+  }
+}
+
+@-moz-keyframes progress-bar-stripes {
+  from {
+    background-position: 40px 0;
+  }
+  to {
+    background-position: 0 0;
+  }
+}
+
+@-o-keyframes progress-bar-stripes {
+  from {
+    background-position: 0 0;
+  }
+  to {
+    background-position: 40px 0;
+  }
+}
+
+@keyframes progress-bar-stripes {
+  from {
+    background-position: 40px 0;
+  }
+  to {
+    background-position: 0 0;
+  }
+}
+
+.progress {
+  height: 20px;
+  margin-bottom: 20px;
+  overflow: hidden;
+  background-color: #f5f5f5;
+  border-radius: 4px;
+  -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
+          box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
+}
+
+.progress-bar {
+  float: left;
+  width: 0;
+  height: 100%;
+  font-size: 12px;
+  color: #ffffff;
+  text-align: center;
+  background-color: #428bca;
+  -webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15);
+          box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15);
+  -webkit-transition: width 0.6s ease;
+          transition: width 0.6s ease;
+}
+
+.progress-striped .progress-bar {
+  background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent));
+  background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
+  background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
+  background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
+  background-size: 40px 40px;
+}
+
+.progress.active .progress-bar {
+  -webkit-animation: progress-bar-stripes 2s linear infinite;
+     -moz-animation: progress-bar-stripes 2s linear infinite;
+      -ms-animation: progress-bar-stripes 2s linear infinite;
+       -o-animation: progress-bar-stripes 2s linear infinite;
+          animation: progress-bar-stripes 2s linear infinite;
+}
+
+.progress-bar-success {
+  background-color: #5cb85c;
+}
+
+.progress-striped .progress-bar-success {
+  background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent));
+  background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
+  background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
+  background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
+}
+
+.progress-bar-info {
+  background-color: #5bc0de;
+}
+
+.progress-striped .progress-bar-info {
+  background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent));
+  background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
+  background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
+  background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
+}
+
+.progress-bar-warning {
+  background-color: #f0ad4e;
+}
+
+.progress-striped .progress-bar-warning {
+  background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent));
+  background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
+  background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
+  background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
+}
+
+.progress-bar-danger {
+  background-color: #d9534f;
+}
+
+.progress-striped .progress-bar-danger {
+  background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent));
+  background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
+  background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
+  background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
+}
+
+.media,
+.media-body {
+  overflow: hidden;
+  zoom: 1;
+}
+
+.media,
+.media .media {
+  margin-top: 15px;
+}
+
+.media:first-child {
+  margin-top: 0;
+}
+
+.media-object {
+  display: block;
+}
+
+.media-heading {
+  margin: 0 0 5px;
+}
+
+.media > .pull-left {
+  margin-right: 10px;
+}
+
+.media > .pull-right {
+  margin-left: 10px;
+}
+
+.media-list {
+  padding-left: 0;
+  list-style: none;
+}
+
+.list-group {
+  padding-left: 0;
+  margin-bottom: 20px;
+}
+
+.list-group-item {
+  position: relative;
+  display: block;
+  padding: 10px 15px;
+  margin-bottom: -1px;
+  background-color: #ffffff;
+  border: 1px solid #dddddd;
+}
+
+.list-group-item:first-child {
+  border-top-right-radius: 4px;
+  border-top-left-radius: 4px;
+}
+
+.list-group-item:last-child {
+  margin-bottom: 0;
+  border-bottom-right-radius: 4px;
+  border-bottom-left-radius: 4px;
+}
+
+.list-group-item > .badge {
+  float: right;
+}
+
+.list-group-item > .badge + .badge {
+  margin-right: 5px;
+}
+
+a.list-group-item {
+  color: #555555;
+}
+
+a.list-group-item .list-group-item-heading {
+  color: #333333;
+}
+
+a.list-group-item:hover,
+a.list-group-item:focus {
+  text-decoration: none;
+  background-color: #f5f5f5;
+}
+
+.list-group-item.active,
+.list-group-item.active:hover,
+.list-group-item.active:focus {
+  z-index: 2;
+  color: #ffffff;
+  background-color: #428bca;
+  border-color: #428bca;
+}
+
+.list-group-item.active .list-group-item-heading,
+.list-group-item.active:hover .list-group-item-heading,
+.list-group-item.active:focus .list-group-item-heading {
+  color: inherit;
+}
+
+.list-group-item.active .list-group-item-text,
+.list-group-item.active:hover .list-group-item-text,
+.list-group-item.active:focus .list-group-item-text {
+  color: #e1edf7;
+}
+
+.list-group-item-heading {
+  margin-top: 0;
+  margin-bottom: 5px;
+}
+
+.list-group-item-text {
+  margin-bottom: 0;
+  line-height: 1.3;
+}
+
+.panel {
+  margin-bottom: 20px;
+  background-color: #ffffff;
+  border: 1px solid transparent;
+  border-radius: 4px;
+  -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05);
+          box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05);
+}
+
+.panel-body {
+  padding: 15px;
+}
+
+.panel-body:before,
+.panel-body:after {
+  display: table;
+  content: " ";
+}
+
+.panel-body:after {
+  clear: both;
+}
+
+.panel-body:before,
+.panel-body:after {
+  display: table;
+  content: " ";
+}
+
+.panel-body:after {
+  clear: both;
+}
+
+.panel > .list-group {
+  margin-bottom: 0;
+}
+
+.panel > .list-group .list-group-item {
+  border-width: 1px 0;
+}
+
+.panel > .list-group .list-group-item:first-child {
+  border-top-right-radius: 0;
+  border-top-left-radius: 0;
+}
+
+.panel > .list-group .list-group-item:last-child {
+  border-bottom: 0;
+}
+
+.panel-heading + .list-group .list-group-item:first-child {
+  border-top-width: 0;
+}
+
+.panel > .table {
+  margin-bottom: 0;
+}
+
+.panel > .panel-body + .table {
+  border-top: 1px solid #dddddd;
+}
+
+.panel-heading {
+  padding: 10px 15px;
+  border-bottom: 1px solid transparent;
+  border-top-right-radius: 3px;
+  border-top-left-radius: 3px;
+}
+
+.panel-title {
+  margin-top: 0;
+  margin-bottom: 0;
+  font-size: 16px;
+}
+
+.panel-title > a {
+  color: inherit;
+}
+
+.panel-footer {
+  padding: 10px 15px;
+  background-color: #f5f5f5;
+  border-top: 1px solid #dddddd;
+  border-bottom-right-radius: 3px;
+  border-bottom-left-radius: 3px;
+}
+
+.panel-group .panel {
+  margin-bottom: 0;
+  overflow: hidden;
+  border-radius: 4px;
+}
+
+.panel-group .panel + .panel {
+  margin-top: 5px;
+}
+
+.panel-group .panel-heading {
+  border-bottom: 0;
+}
+
+.panel-group .panel-heading + .panel-collapse .panel-body {
+  border-top: 1px solid #dddddd;
+}
+
+.panel-group .panel-footer {
+  border-top: 0;
+}
+
+.panel-group .panel-footer + .panel-collapse .panel-body {
+  border-bottom: 1px solid #dddddd;
+}
+
+.panel-default {
+  border-color: #dddddd;
+}
+
+.panel-default > .panel-heading {
+  color: #333333;
+  background-color: #f5f5f5;
+  border-color: #dddddd;
+}
+
+.panel-default > .panel-heading + .panel-collapse .panel-body {
+  border-top-color: #dddddd;
+}
+
+.panel-default > .panel-footer + .panel-collapse .panel-body {
+  border-bottom-color: #dddddd;
+}
+
+.panel-primary {
+  border-color: #428bca;
+}
+
+.panel-primary > .panel-heading {
+  color: #ffffff;
+  background-color: #428bca;
+  border-color: #428bca;
+}
+
+.panel-primary > .panel-heading + .panel-collapse .panel-body {
+  border-top-color: #428bca;
+}
+
+.panel-primary > .panel-footer + .panel-collapse .panel-body {
+  border-bottom-color: #428bca;
+}
+
+.panel-success {
+  border-color: #d6e9c6;
+}
+
+.panel-success > .panel-heading {
+  color: #468847;
+  background-color: #dff0d8;
+  border-color: #d6e9c6;
+}
+
+.panel-success > .panel-heading + .panel-collapse .panel-body {
+  border-top-color: #d6e9c6;
+}
+
+.panel-success > .panel-footer + .panel-collapse .panel-body {
+  border-bottom-color: #d6e9c6;
+}
+
+.panel-warning {
+  border-color: #fbeed5;
+}
+
+.panel-warning > .panel-heading {
+  color: #c09853;
+  background-color: #fcf8e3;
+  border-color: #fbeed5;
+}
+
+.panel-warning > .panel-heading + .panel-collapse .panel-body {
+  border-top-color: #fbeed5;
+}
+
+.panel-warning > .panel-footer + .panel-collapse .panel-body {
+  border-bottom-color: #fbeed5;
+}
+
+.panel-danger {
+  border-color: #eed3d7;
+}
+
+.panel-danger > .panel-heading {
+  color: #b94a48;
+  background-color: #f2dede;
+  border-color: #eed3d7;
+}
+
+.panel-danger > .panel-heading + .panel-collapse .panel-body {
+  border-top-color: #eed3d7;
+}
+
+.panel-danger > .panel-footer + .panel-collapse .panel-body {
+  border-bottom-color: #eed3d7;
+}
+
+.panel-info {
+  border-color: #bce8f1;
+}
+
+.panel-info > .panel-heading {
+  color: #3a87ad;
+  background-color: #d9edf7;
+  border-color: #bce8f1;
+}
+
+.panel-info > .panel-heading + .panel-collapse .panel-body {
+  border-top-color: #bce8f1;
+}
+
+.panel-info > .panel-footer + .panel-collapse .panel-body {
+  border-bottom-color: #bce8f1;
+}
+
+.well {
+  min-height: 20px;
+  padding: 19px;
+  margin-bottom: 20px;
+  background-color: #f5f5f5;
+  border: 1px solid #e3e3e3;
+  border-radius: 4px;
+  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);
+          box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);
+}
+
+.well blockquote {
+  border-color: #ddd;
+  border-color: rgba(0, 0, 0, 0.15);
+}
+
+.well-lg {
+  padding: 24px;
+  border-radius: 6px;
+}
+
+.well-sm {
+  padding: 9px;
+  border-radius: 3px;
+}
+
+.close {
+  float: right;
+  font-size: 21px;
+  font-weight: bold;
+  line-height: 1;
+  color: #000000;
+  text-shadow: 0 1px 0 #ffffff;
+  opacity: 0.2;
+  filter: alpha(opacity=20);
+}
+
+.close:hover,
+.close:focus {
+  color: #000000;
+  text-decoration: none;
+  cursor: pointer;
+  opacity: 0.5;
+  filter: alpha(opacity=50);
+}
+
+button.close {
+  padding: 0;
+  cursor: pointer;
+  background: transparent;
+  border: 0;
+  -webkit-appearance: none;
+}
+
+.modal-open {
+  overflow: hidden;
+}
+
+body.modal-open,
+.modal-open .navbar-fixed-top,
+.modal-open .navbar-fixed-bottom {
+  margin-right: 15px;
+}
+
+.modal {
+  position: fixed;
+  top: 0;
+  right: 0;
+  bottom: 0;
+  left: 0;
+  z-index: 1040;
+  display: none;
+  overflow: auto;
+  overflow-y: scroll;
+}
+
+.modal.fade .modal-dialog {
+  -webkit-transform: translate(0, -25%);
+      -ms-transform: translate(0, -25%);
+          transform: translate(0, -25%);
+  -webkit-transition: -webkit-transform 0.3s ease-out;
+     -moz-transition: -moz-transform 0.3s ease-out;
+       -o-transition: -o-transform 0.3s ease-out;
+          transition: transform 0.3s ease-out;
+}
+
+.modal.in .modal-dialog {
+  -webkit-transform: translate(0, 0);
+      -ms-transform: translate(0, 0);
+          transform: translate(0, 0);
+}
+
+.modal-dialog {
+  z-index: 1050;
+  width: auto;
+  padding: 10px;
+  margin-right: auto;
+  margin-left: auto;
+}
+
+.modal-content {
+  position: relative;
+  background-color: #ffffff;
+  border: 1px solid #999999;
+  border: 1px solid rgba(0, 0, 0, 0.2);
+  border-radius: 6px;
+  outline: none;
+  -webkit-box-shadow: 0 3px 9px rgba(0, 0, 0, 0.5);
+          box-shadow: 0 3px 9px rgba(0, 0, 0, 0.5);
+  background-clip: padding-box;
+}
+
+.modal-backdrop {
+  position: fixed;
+  top: 0;
+  right: 0;
+  bottom: 0;
+  left: 0;
+  z-index: 1030;
+  background-color: #000000;
+}
+
+.modal-backdrop.fade {
+  opacity: 0;
+  filter: alpha(opacity=0);
+}
+
+.modal-backdrop.in {
+  opacity: 0.5;
+  filter: alpha(opacity=50);
+}
+
+.modal-header {
+  min-height: 16.428571429px;
+  padding: 15px;
+  border-bottom: 1px solid #e5e5e5;
+}
+
+.modal-header .close {
+  margin-top: -2px;
+}
+
+.modal-title {
+  margin: 0;
+  line-height: 1.428571429;
+}
+
+.modal-body {
+  position: relative;
+  padding: 20px;
+}
+
+.modal-footer {
+  padding: 19px 20px 20px;
+  margin-top: 15px;
+  text-align: right;
+  border-top: 1px solid #e5e5e5;
+}
+
+.modal-footer:before,
+.modal-footer:after {
+  display: table;
+  content: " ";
+}
+
+.modal-footer:after {
+  clear: both;
+}
+
+.modal-footer:before,
+.modal-footer:after {
+  display: table;
+  content: " ";
+}
+
+.modal-footer:after {
+  clear: both;
+}
+
+.modal-footer .btn + .btn {
+  margin-bottom: 0;
+  margin-left: 5px;
+}
+
+.modal-footer .btn-group .btn + .btn {
+  margin-left: -1px;
+}
+
+.modal-footer .btn-block + .btn-block {
+  margin-left: 0;
+}
+
+@media screen and (min-width: 768px) {
+  .modal-dialog {
+    right: auto;
+    left: 50%;
+    width: 600px;
+    padding-top: 30px;
+    padding-bottom: 30px;
+  }
+  .modal-content {
+    -webkit-box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5);
+            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5);
+  }
+}
+
+.tooltip {
+  position: absolute;
+  z-index: 1030;
+  display: block;
+  font-size: 12px;
+  line-height: 1.4;
+  opacity: 0;
+  filter: alpha(opacity=0);
+  visibility: visible;
+}
+
+.tooltip.in {
+  opacity: 0.9;
+  filter: alpha(opacity=90);
+}
+
+.tooltip.top {
+  padding: 5px 0;
+  margin-top: -3px;
+}
+
+.tooltip.right {
+  padding: 0 5px;
+  margin-left: 3px;
+}
+
+.tooltip.bottom {
+  padding: 5px 0;
+  margin-top: 3px;
+}
+
+.tooltip.left {
+  padding: 0 5px;
+  margin-left: -3px;
+}
+
+.tooltip-inner {
+  max-width: 200px;
+  padding: 3px 8px;
+  color: #ffffff;
+  text-align: center;
+  text-decoration: none;
+  background-color: #000000;
+  border-radius: 4px;
+}
+
+.tooltip-arrow {
+  position: absolute;
+  width: 0;
+  height: 0;
+  border-color: transparent;
+  border-style: solid;
+}
+
+.tooltip.top .tooltip-arrow {
+  bottom: 0;
+  left: 50%;
+  margin-left: -5px;
+  border-top-color: #000000;
+  border-width: 5px 5px 0;
+}
+
+.tooltip.top-left .tooltip-arrow {
+  bottom: 0;
+  left: 5px;
+  border-top-color: #000000;
+  border-width: 5px 5px 0;
+}
+
+.tooltip.top-right .tooltip-arrow {
+  right: 5px;
+  bottom: 0;
+  border-top-color: #000000;
+  border-width: 5px 5px 0;
+}
+
+.tooltip.right .tooltip-arrow {
+  top: 50%;
+  left: 0;
+  margin-top: -5px;
+  border-right-color: #000000;
+  border-width: 5px 5px 5px 0;
+}
+
+.tooltip.left .tooltip-arrow {
+  top: 50%;
+  right: 0;
+  margin-top: -5px;
+  border-left-color: #000000;
+  border-width: 5px 0 5px 5px;
+}
+
+.tooltip.bottom .tooltip-arrow {
+  top: 0;
+  left: 50%;
+  margin-left: -5px;
+  border-bottom-color: #000000;
+  border-width: 0 5px 5px;
+}
+
+.tooltip.bottom-left .tooltip-arrow {
+  top: 0;
+  left: 5px;
+  border-bottom-color: #000000;
+  border-width: 0 5px 5px;
+}
+
+.tooltip.bottom-right .tooltip-arrow {
+  top: 0;
+  right: 5px;
+  border-bottom-color: #000000;
+  border-width: 0 5px 5px;
+}
+
+.popover {
+  position: absolute;
+  top: 0;
+  left: 0;
+  z-index: 1010;
+  display: none;
+  max-width: 276px;
+  padding: 1px;
+  text-align: left;
+  white-space: normal;
+  background-color: #ffffff;
+  border: 1px solid #cccccc;
+  border: 1px solid rgba(0, 0, 0, 0.2);
+  border-radius: 6px;
+  -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
+          box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
+  background-clip: padding-box;
+}
+
+.popover.top {
+  margin-top: -10px;
+}
+
+.popover.right {
+  margin-left: 10px;
+}
+
+.popover.bottom {
+  margin-top: 10px;
+}
+
+.popover.left {
+  margin-left: -10px;
+}
+
+.popover-title {
+  padding: 8px 14px;
+  margin: 0;
+  font-size: 14px;
+  font-weight: normal;
+  line-height: 18px;
+  background-color: #f7f7f7;
+  border-bottom: 1px solid #ebebeb;
+  border-radius: 5px 5px 0 0;
+}
+
+.popover-content {
+  padding: 9px 14px;
+}
+
+.popover .arrow,
+.popover .arrow:after {
+  position: absolute;
+  display: block;
+  width: 0;
+  height: 0;
+  border-color: transparent;
+  border-style: solid;
+}
+
+.popover .arrow {
+  border-width: 11px;
+}
+
+.popover .arrow:after {
+  border-width: 10px;
+  content: "";
+}
+
+.popover.top .arrow {
+  bottom: -11px;
+  left: 50%;
+  margin-left: -11px;
+  border-top-color: #999999;
+  border-top-color: rgba(0, 0, 0, 0.25);
+  border-bottom-width: 0;
+}
+
+.popover.top .arrow:after {
+  bottom: 1px;
+  margin-left: -10px;
+  border-top-color: #ffffff;
+  border-bottom-width: 0;
+  content: " ";
+}
+
+.popover.right .arrow {
+  top: 50%;
+  left: -11px;
+  margin-top: -11px;
+  border-right-color: #999999;
+  border-right-color: rgba(0, 0, 0, 0.25);
+  border-left-width: 0;
+}
+
+.popover.right .arrow:after {
+  bottom: -10px;
+  left: 1px;
+  border-right-color: #ffffff;
+  border-left-width: 0;
+  content: " ";
+}
+
+.popover.bottom .arrow {
+  top: -11px;
+  left: 50%;
+  margin-left: -11px;
+  border-bottom-color: #999999;
+  border-bottom-color: rgba(0, 0, 0, 0.25);
+  border-top-width: 0;
+}
+
+.popover.bottom .arrow:after {
+  top: 1px;
+  margin-left: -10px;
+  border-bottom-color: #ffffff;
+  border-top-width: 0;
+  content: " ";
+}
+
+.popover.left .arrow {
+  top: 50%;
+  right: -11px;
+  margin-top: -11px;
+  border-left-color: #999999;
+  border-left-color: rgba(0, 0, 0, 0.25);
+  border-right-width: 0;
+}
+
+.popover.left .arrow:after {
+  right: 1px;
+  bottom: -10px;
+  border-left-color: #ffffff;
+  border-right-width: 0;
+  content: " ";
+}
+
+.carousel {
+  position: relative;
+}
+
+.carousel-inner {
+  position: relative;
+  width: 100%;
+  overflow: hidden;
+}
+
+.carousel-inner > .item {
+  position: relative;
+  display: none;
+  -webkit-transition: 0.6s ease-in-out left;
+          transition: 0.6s ease-in-out left;
+}
+
+.carousel-inner > .item > img,
+.carousel-inner > .item > a > img {
+  display: block;
+  height: auto;
+  max-width: 100%;
+  line-height: 1;
+}
+
+.carousel-inner > .active,
+.carousel-inner > .next,
+.carousel-inner > .prev {
+  display: block;
+}
+
+.carousel-inner > .active {
+  left: 0;
+}
+
+.carousel-inner > .next,
+.carousel-inner > .prev {
+  position: absolute;
+  top: 0;
+  width: 100%;
+}
+
+.carousel-inner > .next {
+  left: 100%;
+}
+
+.carousel-inner > .prev {
+  left: -100%;
+}
+
+.carousel-inner > .next.left,
+.carousel-inner > .prev.right {
+  left: 0;
+}
+
+.carousel-inner > .active.left {
+  left: -100%;
+}
+
+.carousel-inner > .active.right {
+  left: 100%;
+}
+
+.carousel-control {
+  position: absolute;
+  top: 0;
+  bottom: 0;
+  left: 0;
+  width: 15%;
+  font-size: 20px;
+  color: #ffffff;
+  text-align: center;
+  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6);
+  opacity: 0.5;
+  filter: alpha(opacity=50);
+}
+
+.carousel-control.left {
+  background-image: -webkit-gradient(linear, 0 top, 100% top, from(rgba(0, 0, 0, 0.5)), to(rgba(0, 0, 0, 0.0001)));
+  background-image: -webkit-linear-gradient(left, color-stop(rgba(0, 0, 0, 0.5) 0), color-stop(rgba(0, 0, 0, 0.0001) 100%));
+  background-image: -moz-linear-gradient(left, rgba(0, 0, 0, 0.5) 0, rgba(0, 0, 0, 0.0001) 100%);
+  background-image: linear-gradient(to right, rgba(0, 0, 0, 0.5) 0, rgba(0, 0, 0, 0.0001) 100%);
+  background-repeat: repeat-x;
+  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1);
+}
+
+.carousel-control.right {
+  right: 0;
+  left: auto;
+  background-image: -webkit-gradient(linear, 0 top, 100% top, from(rgba(0, 0, 0, 0.0001)), to(rgba(0, 0, 0, 0.5)));
+  background-image: -webkit-linear-gradient(left, color-stop(rgba(0, 0, 0, 0.0001) 0), color-stop(rgba(0, 0, 0, 0.5) 100%));
+  background-image: -moz-linear-gradient(left, rgba(0, 0, 0, 0.0001) 0, rgba(0, 0, 0, 0.5) 100%);
+  background-image: linear-gradient(to right, rgba(0, 0, 0, 0.0001) 0, rgba(0, 0, 0, 0.5) 100%);
+  background-repeat: repeat-x;
+  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1);
+}
+
+.carousel-control:hover,
+.carousel-control:focus {
+  color: #ffffff;
+  text-decoration: none;
+  opacity: 0.9;
+  filter: alpha(opacity=90);
+}
+
+.carousel-control .icon-prev,
+.carousel-control .icon-next,
+.carousel-control .glyphicon-chevron-left,
+.carousel-control .glyphicon-chevron-right {
+  position: absolute;
+  top: 50%;
+  left: 50%;
+  z-index: 5;
+  display: inline-block;
+}
+
+.carousel-control .icon-prev,
+.carousel-control .icon-next {
+  width: 20px;
+  height: 20px;
+  margin-top: -10px;
+  margin-left: -10px;
+  font-family: serif;
+}
+
+.carousel-control .icon-prev:before {
+  content: '\2039';
+}
+
+.carousel-control .icon-next:before {
+  content: '\203a';
+}
+
+.carousel-indicators {
+  position: absolute;
+  bottom: 10px;
+  left: 50%;
+  z-index: 15;
+  width: 60%;
+  padding-left: 0;
+  margin-left: -30%;
+  text-align: center;
+  list-style: none;
+}
+
+.carousel-indicators li {
+  display: inline-block;
+  width: 10px;
+  height: 10px;
+  margin: 1px;
+  text-indent: -999px;
+  cursor: pointer;
+  border: 1px solid #ffffff;
+  border-radius: 10px;
+}
+
+.carousel-indicators .active {
+  width: 12px;
+  height: 12px;
+  margin: 0;
+  background-color: #ffffff;
+}
+
+.carousel-caption {
+  position: absolute;
+  right: 15%;
+  bottom: 20px;
+  left: 15%;
+  z-index: 10;
+  padding-top: 20px;
+  padding-bottom: 20px;
+  color: #ffffff;
+  text-align: center;
+  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6);
+}
+
+.carousel-caption .btn {
+  text-shadow: none;
+}
+
+@media screen and (min-width: 768px) {
+  .carousel-control .icon-prev,
+  .carousel-control .icon-next {
+    width: 30px;
+    height: 30px;
+    margin-top: -15px;
+    margin-left: -15px;
+    font-size: 30px;
+  }
+  .carousel-caption {
+    right: 20%;
+    left: 20%;
+    padding-bottom: 30px;
+  }
+  .carousel-indicators {
+    bottom: 20px;
+  }
+}
+
+.clearfix:before,
+.clearfix:after {
+  display: table;
+  content: " ";
+}
+
+.clearfix:after {
+  clear: both;
+}
+
+.pull-right {
+  float: right !important;
+}
+
+.pull-left {
+  float: left !important;
+}
+
+.hide {
+  display: none !important;
+}
+
+.show {
+  display: block !important;
+}
+
+.invisible {
+  visibility: hidden;
+}
+
+.text-hide {
+  font: 0/0 a;
+  color: transparent;
+  text-shadow: none;
+  background-color: transparent;
+  border: 0;
+}
+
+.affix {
+  position: fixed;
+}
+
+@-ms-viewport {
+  width: device-width;
+}
+
+@media screen and (max-width: 400px) {
+  @-ms-viewport {
+    width: 320px;
+  }
+}
+
+.hidden {
+  display: none !important;
+  visibility: hidden !important;
+}
+
+.visible-xs {
+  display: none !important;
+}
+
+tr.visible-xs {
+  display: none !important;
+}
+
+th.visible-xs,
+td.visible-xs {
+  display: none !important;
+}
+
+@media (max-width: 767px) {
+  .visible-xs {
+    display: block !important;
+  }
+  tr.visible-xs {
+    display: table-row !important;
+  }
+  th.visible-xs,
+  td.visible-xs {
+    display: table-cell !important;
+  }
+}
+
+@media (min-width: 768px) and (max-width: 991px) {
+  .visible-xs.visible-sm {
+    display: block !important;
+  }
+  tr.visible-xs.visible-sm {
+    display: table-row !important;
+  }
+  th.visible-xs.visible-sm,
+  td.visible-xs.visible-sm {
+    display: table-cell !important;
+  }
+}
+
+@media (min-width: 992px) and (max-width: 1199px) {
+  .visible-xs.visible-md {
+    display: block !important;
+  }
+  tr.visible-xs.visible-md {
+    display: table-row !important;
+  }
+  th.visible-xs.visible-md,
+  td.visible-xs.visible-md {
+    display: table-cell !important;
+  }
+}
+
+@media (min-width: 1200px) {
+  .visible-xs.visible-lg {
+    display: block !important;
+  }
+  tr.visible-xs.visible-lg {
+    display: table-row !important;
+  }
+  th.visible-xs.visible-lg,
+  td.visible-xs.visible-lg {
+    display: table-cell !important;
+  }
+}
+
+.visible-sm {
+  display: none !important;
+}
+
+tr.visible-sm {
+  display: none !important;
+}
+
+th.visible-sm,
+td.visible-sm {
+  display: none !important;
+}
+
+@media (max-width: 767px) {
+  .visible-sm.visible-xs {
+    display: block !important;
+  }
+  tr.visible-sm.visible-xs {
+    display: table-row !important;
+  }
+  th.visible-sm.visible-xs,
+  td.visible-sm.visible-xs {
+    display: table-cell !important;
+  }
+}
+
+@media (min-width: 768px) and (max-width: 991px) {
+  .visible-sm {
+    display: block !important;
+  }
+  tr.visible-sm {
+    display: table-row !important;
+  }
+  th.visible-sm,
+  td.visible-sm {
+    display: table-cell !important;
+  }
+}
+
+@media (min-width: 992px) and (max-width: 1199px) {
+  .visible-sm.visible-md {
+    display: block !important;
+  }
+  tr.visible-sm.visible-md {
+    display: table-row !important;
+  }
+  th.visible-sm.visible-md,
+  td.visible-sm.visible-md {
+    display: table-cell !important;
+  }
+}
+
+@media (min-width: 1200px) {
+  .visible-sm.visible-lg {
+    display: block !important;
+  }
+  tr.visible-sm.visible-lg {
+    display: table-row !important;
+  }
+  th.visible-sm.visible-lg,
+  td.visible-sm.visible-lg {
+    display: table-cell !important;
+  }
+}
+
+.visible-md {
+  display: none !important;
+}
+
+tr.visible-md {
+  display: none !important;
+}
+
+th.visible-md,
+td.visible-md {
+  display: none !important;
+}
+
+@media (max-width: 767px) {
+  .visible-md.visible-xs {
+    display: block !important;
+  }
+  tr.visible-md.visible-xs {
+    display: table-row !important;
+  }
+  th.visible-md.visible-xs,
+  td.visible-md.visible-xs {
+    display: table-cell !important;
+  }
+}
+
+@media (min-width: 768px) and (max-width: 991px) {
+  .visible-md.visible-sm {
+    display: block !important;
+  }
+  tr.visible-md.visible-sm {
+    display: table-row !important;
+  }
+  th.visible-md.visible-sm,
+  td.visible-md.visible-sm {
+    display: table-cell !important;
+  }
+}
+
+@media (min-width: 992px) and (max-width: 1199px) {
+  .visible-md {
+    display: block !important;
+  }
+  tr.visible-md {
+    display: table-row !important;
+  }
+  th.visible-md,
+  td.visible-md {
+    display: table-cell !important;
+  }
+}
+
+@media (min-width: 1200px) {
+  .visible-md.visible-lg {
+    display: block !important;
+  }
+  tr.visible-md.visible-lg {
+    display: table-row !important;
+  }
+  th.visible-md.visible-lg,
+  td.visible-md.visible-lg {
+    display: table-cell !important;
+  }
+}
+
+.visible-lg {
+  display: none !important;
+}
+
+tr.visible-lg {
+  display: none !important;
+}
+
+th.visible-lg,
+td.visible-lg {
+  display: none !important;
+}
+
+@media (max-width: 767px) {
+  .visible-lg.visible-xs {
+    display: block !important;
+  }
+  tr.visible-lg.visible-xs {
+    display: table-row !important;
+  }
+  th.visible-lg.visible-xs,
+  td.visible-lg.visible-xs {
+    display: table-cell !important;
+  }
+}
+
+@media (min-width: 768px) and (max-width: 991px) {
+  .visible-lg.visible-sm {
+    display: block !important;
+  }
+  tr.visible-lg.visible-sm {
+    display: table-row !important;
+  }
+  th.visible-lg.visible-sm,
+  td.visible-lg.visible-sm {
+    display: table-cell !important;
+  }
+}
+
+@media (min-width: 992px) and (max-width: 1199px) {
+  .visible-lg.visible-md {
+    display: block !important;
+  }
+  tr.visible-lg.visible-md {
+    display: table-row !important;
+  }
+  th.visible-lg.visible-md,
+  td.visible-lg.visible-md {
+    display: table-cell !important;
+  }
+}
+
+@media (min-width: 1200px) {
+  .visible-lg {
+    display: block !important;
+  }
+  tr.visible-lg {
+    display: table-row !important;
+  }
+  th.visible-lg,
+  td.visible-lg {
+    display: table-cell !important;
+  }
+}
+
+.hidden-xs {
+  display: block !important;
+}
+
+tr.hidden-xs {
+  display: table-row !important;
+}
+
+th.hidden-xs,
+td.hidden-xs {
+  display: table-cell !important;
+}
+
+@media (max-width: 767px) {
+  .hidden-xs {
+    display: none !important;
+  }
+  tr.hidden-xs {
+    display: none !important;
+  }
+  th.hidden-xs,
+  td.hidden-xs {
+    display: none !important;
+  }
+}
+
+@media (min-width: 768px) and (max-width: 991px) {
+  .hidden-xs.hidden-sm {
+    display: none !important;
+  }
+  tr.hidden-xs.hidden-sm {
+    display: none !important;
+  }
+  th.hidden-xs.hidden-sm,
+  td.hidden-xs.hidden-sm {
+    display: none !important;
+  }
+}
+
+@media (min-width: 992px) and (max-width: 1199px) {
+  .hidden-xs.hidden-md {
+    display: none !important;
+  }
+  tr.hidden-xs.hidden-md {
+    display: none !important;
+  }
+  th.hidden-xs.hidden-md,
+  td.hidden-xs.hidden-md {
+    display: none !important;
+  }
+}
+
+@media (min-width: 1200px) {
+  .hidden-xs.hidden-lg {
+    display: none !important;
+  }
+  tr.hidden-xs.hidden-lg {
+    display: none !important;
+  }
+  th.hidden-xs.hidden-lg,
+  td.hidden-xs.hidden-lg {
+    display: none !important;
+  }
+}
+
+.hidden-sm {
+  display: block !important;
+}
+
+tr.hidden-sm {
+  display: table-row !important;
+}
+
+th.hidden-sm,
+td.hidden-sm {
+  display: table-cell !important;
+}
+
+@media (max-width: 767px) {
+  .hidden-sm.hidden-xs {
+    display: none !important;
+  }
+  tr.hidden-sm.hidden-xs {
+    display: none !important;
+  }
+  th.hidden-sm.hidden-xs,
+  td.hidden-sm.hidden-xs {
+    display: none !important;
+  }
+}
+
+@media (min-width: 768px) and (max-width: 991px) {
+  .hidden-sm {
+    display: none !important;
+  }
+  tr.hidden-sm {
+    display: none !important;
+  }
+  th.hidden-sm,
+  td.hidden-sm {
+    display: none !important;
+  }
+}
+
+@media (min-width: 992px) and (max-width: 1199px) {
+  .hidden-sm.hidden-md {
+    display: none !important;
+  }
+  tr.hidden-sm.hidden-md {
+    display: none !important;
+  }
+  th.hidden-sm.hidden-md,
+  td.hidden-sm.hidden-md {
+    display: none !important;
+  }
+}
+
+@media (min-width: 1200px) {
+  .hidden-sm.hidden-lg {
+    display: none !important;
+  }
+  tr.hidden-sm.hidden-lg {
+    display: none !important;
+  }
+  th.hidden-sm.hidden-lg,
+  td.hidden-sm.hidden-lg {
+    display: none !important;
+  }
+}
+
+.hidden-md {
+  display: block !important;
+}
+
+tr.hidden-md {
+  display: table-row !important;
+}
+
+th.hidden-md,
+td.hidden-md {
+  display: table-cell !important;
+}
+
+@media (max-width: 767px) {
+  .hidden-md.hidden-xs {
+    display: none !important;
+  }
+  tr.hidden-md.hidden-xs {
+    display: none !important;
+  }
+  th.hidden-md.hidden-xs,
+  td.hidden-md.hidden-xs {
+    display: none !important;
+  }
+}
+
+@media (min-width: 768px) and (max-width: 991px) {
+  .hidden-md.hidden-sm {
+    display: none !important;
+  }
+  tr.hidden-md.hidden-sm {
+    display: none !important;
+  }
+  th.hidden-md.hidden-sm,
+  td.hidden-md.hidden-sm {
+    display: none !important;
+  }
+}
+
+@media (min-width: 992px) and (max-width: 1199px) {
+  .hidden-md {
+    display: none !important;
+  }
+  tr.hidden-md {
+    display: none !important;
+  }
+  th.hidden-md,
+  td.hidden-md {
+    display: none !important;
+  }
+}
+
+@media (min-width: 1200px) {
+  .hidden-md.hidden-lg {
+    display: none !important;
+  }
+  tr.hidden-md.hidden-lg {
+    display: none !important;
+  }
+  th.hidden-md.hidden-lg,
+  td.hidden-md.hidden-lg {
+    display: none !important;
+  }
+}
+
+.hidden-lg {
+  display: block !important;
+}
+
+tr.hidden-lg {
+  display: table-row !important;
+}
+
+th.hidden-lg,
+td.hidden-lg {
+  display: table-cell !important;
+}
+
+@media (max-width: 767px) {
+  .hidden-lg.hidden-xs {
+    display: none !important;
+  }
+  tr.hidden-lg.hidden-xs {
+    display: none !important;
+  }
+  th.hidden-lg.hidden-xs,
+  td.hidden-lg.hidden-xs {
+    display: none !important;
+  }
+}
+
+@media (min-width: 768px) and (max-width: 991px) {
+  .hidden-lg.hidden-sm {
+    display: none !important;
+  }
+  tr.hidden-lg.hidden-sm {
+    display: none !important;
+  }
+  th.hidden-lg.hidden-sm,
+  td.hidden-lg.hidden-sm {
+    display: none !important;
+  }
+}
+
+@media (min-width: 992px) and (max-width: 1199px) {
+  .hidden-lg.hidden-md {
+    display: none !important;
+  }
+  tr.hidden-lg.hidden-md {
+    display: none !important;
+  }
+  th.hidden-lg.hidden-md,
+  td.hidden-lg.hidden-md {
+    display: none !important;
+  }
+}
+
+@media (min-width: 1200px) {
+  .hidden-lg {
+    display: none !important;
+  }
+  tr.hidden-lg {
+    display: none !important;
+  }
+  th.hidden-lg,
+  td.hidden-lg {
+    display: none !important;
+  }
+}
+
+.visible-print {
+  display: none !important;
+}
+
+tr.visible-print {
+  display: none !important;
+}
+
+th.visible-print,
+td.visible-print {
+  display: none !important;
+}
+
+@media print {
+  .visible-print {
+    display: block !important;
+  }
+  tr.visible-print {
+    display: table-row !important;
+  }
+  th.visible-print,
+  td.visible-print {
+    display: table-cell !important;
+  }
+  .hidden-print {
+    display: none !important;
+  }
+  tr.hidden-print {
+    display: none !important;
+  }
+  th.hidden-print,
+  td.hidden-print {
+    display: none !important;
+  }
+}
\ No newline at end of file
diff --git a/third-party/bootstrap-3.0.0/css/bootstrap.min.css b/third-party/bootstrap-3.0.0/css/bootstrap.min.css
new file mode 100644 (file)
index 0000000..a553c4f
--- /dev/null
@@ -0,0 +1,9 @@
+/*!
+ * Bootstrap v3.0.0
+ *
+ * Copyright 2013 Twitter, Inc
+ * Licensed under the Apache License v2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Designed and built with all the love in the world by @mdo and @fat.
+ *//*! normalize.css v2.1.0 | MIT License | git.io/normalize */article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block}audio,canvas,video{display:inline-block}audio:not([controls]){display:none;height:0}[hidden]{display:none}html{font-family:sans-serif;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}body{margin:0}a:focus{outline:thin dotted}a:active,a:hover{outline:0}h1{margin:.67em 0;font-size:2em}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:bold}dfn{font-style:italic}hr{height:0;-moz-box-sizing:content-box;box-sizing:content-box}mark{color:#000;background:#ff0}code,kbd,pre,samp{font-family:monospace,serif;font-size:1em}pre{white-space:pre-wrap}q{quotes:"\201C" "\201D" "\2018" "\2019"}small{font-size:80%}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sup{top:-0.5em}sub{bottom:-0.25em}img{border:0}svg:not(:root){overflow:hidden}figure{margin:0}fieldset{padding:.35em .625em .75em;margin:0 2px;border:1px solid #c0c0c0}legend{padding:0;border:0}button,input,select,textarea{margin:0;font-family:inherit;font-size:100%}button,input{line-height:normal}button,select{text-transform:none}button,html input[type="button"],input[type="reset"],input[type="submit"]{cursor:pointer;-webkit-appearance:button}button[disabled],html input[disabled]{cursor:default}input[type="checkbox"],input[type="radio"]{padding:0;box-sizing:border-box}input[type="search"]{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;-webkit-appearance:textfield}input[type="search"]::-webkit-search-cancel-button,input[type="search"]::-webkit-search-decoration{-webkit-appearance:none}button::-moz-focus-inner,input::-moz-focus-inner{padding:0;border:0}textarea{overflow:auto;vertical-align:top}table{border-collapse:collapse;border-spacing:0}@media print{*{color:#000!important;text-shadow:none!important;background:transparent!important;box-shadow:none!important}a,a:visited{text-decoration:underline}a[href]:after{content:" (" attr(href) ")"}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100%!important}@page{margin:2cm .5cm}p,h2,h3{orphans:3;widows:3}h2,h3{page-break-after:avoid}.navbar{display:none}.table td,.table th{background-color:#fff!important}.btn>.caret,.dropup>.btn>.caret{border-top-color:#000!important}.label{border:1px solid #000}.table{border-collapse:collapse!important}.table-bordered th,.table-bordered td{border:1px solid #ddd!important}}*,*:before,*:after{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}html{font-size:62.5%;-webkit-tap-highlight-color:rgba(0,0,0,0)}body{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:1.428571429;color:#333;background-color:#fff}input,button,select,textarea{font-family:inherit;font-size:inherit;line-height:inherit}button,input,select[multiple],textarea{background-image:none}a{color:#428bca;text-decoration:none}a:hover,a:focus{color:#2a6496;text-decoration:underline}a:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}img{vertical-align:middle}.img-responsive{display:block;height:auto;max-width:100%}.img-rounded{border-radius:6px}.img-thumbnail{display:inline-block;height:auto;max-width:100%;padding:4px;line-height:1.428571429;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:all .2s ease-in-out;transition:all .2s ease-in-out}.img-circle{border-radius:50%}hr{margin-top:20px;margin-bottom:20px;border:0;border-top:1px solid #eee}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);border:0}p{margin:0 0 10px}.lead{margin-bottom:20px;font-size:16.099999999999998px;font-weight:200;line-height:1.4}@media(min-width:768px){.lead{font-size:21px}}small{font-size:85%}cite{font-style:normal}.text-muted{color:#999}.text-primary{color:#428bca}.text-warning{color:#c09853}.text-danger{color:#b94a48}.text-success{color:#468847}.text-info{color:#3a87ad}.text-left{text-align:left}.text-right{text-align:right}.text-center{text-align:center}h1,h2,h3,h4,h5,h6,.h1,.h2,.h3,.h4,.h5,.h6{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-weight:500;line-height:1.1}h1 small,h2 small,h3 small,h4 small,h5 small,h6 small,.h1 small,.h2 small,.h3 small,.h4 small,.h5 small,.h6 small{font-weight:normal;line-height:1;color:#999}h1,h2,h3{margin-top:20px;margin-bottom:10px}h4,h5,h6{margin-top:10px;margin-bottom:10px}h1,.h1{font-size:36px}h2,.h2{font-size:30px}h3,.h3{font-size:24px}h4,.h4{font-size:18px}h5,.h5{font-size:14px}h6,.h6{font-size:12px}h1 small,.h1 small{font-size:24px}h2 small,.h2 small{font-size:18px}h3 small,.h3 small,h4 small,.h4 small{font-size:14px}.page-header{padding-bottom:9px;margin:40px 0 20px;border-bottom:1px solid #eee}ul,ol{margin-top:0;margin-bottom:10px}ul ul,ol ul,ul ol,ol ol{margin-bottom:0}.list-unstyled{padding-left:0;list-style:none}.list-inline{padding-left:0;list-style:none}.list-inline>li{display:inline-block;padding-right:5px;padding-left:5px}dl{margin-bottom:20px}dt,dd{line-height:1.428571429}dt{font-weight:bold}dd{margin-left:0}@media(min-width:768px){.dl-horizontal dt{float:left;width:160px;overflow:hidden;clear:left;text-align:right;text-overflow:ellipsis;white-space:nowrap}.dl-horizontal dd{margin-left:180px}.dl-horizontal dd:before,.dl-horizontal dd:after{display:table;content:" "}.dl-horizontal dd:after{clear:both}.dl-horizontal dd:before,.dl-horizontal dd:after{display:table;content:" "}.dl-horizontal dd:after{clear:both}}abbr[title],abbr[data-original-title]{cursor:help;border-bottom:1px dotted #999}abbr.initialism{font-size:90%;text-transform:uppercase}blockquote{padding:10px 20px;margin:0 0 20px;border-left:5px solid #eee}blockquote p{font-size:17.5px;font-weight:300;line-height:1.25}blockquote p:last-child{margin-bottom:0}blockquote small{display:block;line-height:1.428571429;color:#999}blockquote small:before{content:'\2014 \00A0'}blockquote.pull-right{padding-right:15px;padding-left:0;border-right:5px solid #eee;border-left:0}blockquote.pull-right p,blockquote.pull-right small{text-align:right}blockquote.pull-right small:before{content:''}blockquote.pull-right small:after{content:'\00A0 \2014'}q:before,q:after,blockquote:before,blockquote:after{content:""}address{display:block;margin-bottom:20px;font-style:normal;line-height:1.428571429}code,pre{font-family:Monaco,Menlo,Consolas,"Courier New",monospace}code{padding:2px 4px;font-size:90%;color:#c7254e;white-space:nowrap;background-color:#f9f2f4;border-radius:4px}pre{display:block;padding:9.5px;margin:0 0 10px;font-size:13px;line-height:1.428571429;color:#333;word-break:break-all;word-wrap:break-word;background-color:#f5f5f5;border:1px solid #ccc;border-radius:4px}pre.prettyprint{margin-bottom:20px}pre code{padding:0;font-size:inherit;color:inherit;white-space:pre-wrap;background-color:transparent;border:0}.pre-scrollable{max-height:340px;overflow-y:scroll}.container{padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto}.container:before,.container:after{display:table;content:" "}.container:after{clear:both}.container:before,.container:after{display:table;content:" "}.container:after{clear:both}.row{margin-right:-15px;margin-left:-15px}.row:before,.row:after{display:table;content:" "}.row:after{clear:both}.row:before,.row:after{display:table;content:" "}.row:after{clear:both}.col-xs-1,.col-xs-2,.col-xs-3,.col-xs-4,.col-xs-5,.col-xs-6,.col-xs-7,.col-xs-8,.col-xs-9,.col-xs-10,.col-xs-11,.col-xs-12,.col-sm-1,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-10,.col-sm-11,.col-sm-12,.col-md-1,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9,.col-md-10,.col-md-11,.col-md-12,.col-lg-1,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-10,.col-lg-11,.col-lg-12{position:relative;min-height:1px;padding-right:15px;padding-left:15px}.col-xs-1,.col-xs-2,.col-xs-3,.col-xs-4,.col-xs-5,.col-xs-6,.col-xs-7,.col-xs-8,.col-xs-9,.col-xs-10,.col-xs-11{float:left}.col-xs-1{width:8.333333333333332%}.col-xs-2{width:16.666666666666664%}.col-xs-3{width:25%}.col-xs-4{width:33.33333333333333%}.col-xs-5{width:41.66666666666667%}.col-xs-6{width:50%}.col-xs-7{width:58.333333333333336%}.col-xs-8{width:66.66666666666666%}.col-xs-9{width:75%}.col-xs-10{width:83.33333333333334%}.col-xs-11{width:91.66666666666666%}.col-xs-12{width:100%}@media(min-width:768px){.container{max-width:750px}.col-sm-1,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-10,.col-sm-11{float:left}.col-sm-1{width:8.333333333333332%}.col-sm-2{width:16.666666666666664%}.col-sm-3{width:25%}.col-sm-4{width:33.33333333333333%}.col-sm-5{width:41.66666666666667%}.col-sm-6{width:50%}.col-sm-7{width:58.333333333333336%}.col-sm-8{width:66.66666666666666%}.col-sm-9{width:75%}.col-sm-10{width:83.33333333333334%}.col-sm-11{width:91.66666666666666%}.col-sm-12{width:100%}.col-sm-push-1{left:8.333333333333332%}.col-sm-push-2{left:16.666666666666664%}.col-sm-push-3{left:25%}.col-sm-push-4{left:33.33333333333333%}.col-sm-push-5{left:41.66666666666667%}.col-sm-push-6{left:50%}.col-sm-push-7{left:58.333333333333336%}.col-sm-push-8{left:66.66666666666666%}.col-sm-push-9{left:75%}.col-sm-push-10{left:83.33333333333334%}.col-sm-push-11{left:91.66666666666666%}.col-sm-pull-1{right:8.333333333333332%}.col-sm-pull-2{right:16.666666666666664%}.col-sm-pull-3{right:25%}.col-sm-pull-4{right:33.33333333333333%}.col-sm-pull-5{right:41.66666666666667%}.col-sm-pull-6{right:50%}.col-sm-pull-7{right:58.333333333333336%}.col-sm-pull-8{right:66.66666666666666%}.col-sm-pull-9{right:75%}.col-sm-pull-10{right:83.33333333333334%}.col-sm-pull-11{right:91.66666666666666%}.col-sm-offset-1{margin-left:8.333333333333332%}.col-sm-offset-2{margin-left:16.666666666666664%}.col-sm-offset-3{margin-left:25%}.col-sm-offset-4{margin-left:33.33333333333333%}.col-sm-offset-5{margin-left:41.66666666666667%}.col-sm-offset-6{margin-left:50%}.col-sm-offset-7{margin-left:58.333333333333336%}.col-sm-offset-8{margin-left:66.66666666666666%}.col-sm-offset-9{margin-left:75%}.col-sm-offset-10{margin-left:83.33333333333334%}.col-sm-offset-11{margin-left:91.66666666666666%}}@media(min-width:992px){.container{max-width:970px}.col-md-1,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9,.col-md-10,.col-md-11{float:left}.col-md-1{width:8.333333333333332%}.col-md-2{width:16.666666666666664%}.col-md-3{width:25%}.col-md-4{width:33.33333333333333%}.col-md-5{width:41.66666666666667%}.col-md-6{width:50%}.col-md-7{width:58.333333333333336%}.col-md-8{width:66.66666666666666%}.col-md-9{width:75%}.col-md-10{width:83.33333333333334%}.col-md-11{width:91.66666666666666%}.col-md-12{width:100%}.col-md-push-0{left:auto}.col-md-push-1{left:8.333333333333332%}.col-md-push-2{left:16.666666666666664%}.col-md-push-3{left:25%}.col-md-push-4{left:33.33333333333333%}.col-md-push-5{left:41.66666666666667%}.col-md-push-6{left:50%}.col-md-push-7{left:58.333333333333336%}.col-md-push-8{left:66.66666666666666%}.col-md-push-9{left:75%}.col-md-push-10{left:83.33333333333334%}.col-md-push-11{left:91.66666666666666%}.col-md-pull-0{right:auto}.col-md-pull-1{right:8.333333333333332%}.col-md-pull-2{right:16.666666666666664%}.col-md-pull-3{right:25%}.col-md-pull-4{right:33.33333333333333%}.col-md-pull-5{right:41.66666666666667%}.col-md-pull-6{right:50%}.col-md-pull-7{right:58.333333333333336%}.col-md-pull-8{right:66.66666666666666%}.col-md-pull-9{right:75%}.col-md-pull-10{right:83.33333333333334%}.col-md-pull-11{right:91.66666666666666%}.col-md-offset-0{margin-left:0}.col-md-offset-1{margin-left:8.333333333333332%}.col-md-offset-2{margin-left:16.666666666666664%}.col-md-offset-3{margin-left:25%}.col-md-offset-4{margin-left:33.33333333333333%}.col-md-offset-5{margin-left:41.66666666666667%}.col-md-offset-6{margin-left:50%}.col-md-offset-7{margin-left:58.333333333333336%}.col-md-offset-8{margin-left:66.66666666666666%}.col-md-offset-9{margin-left:75%}.col-md-offset-10{margin-left:83.33333333333334%}.col-md-offset-11{margin-left:91.66666666666666%}}@media(min-width:1200px){.container{max-width:1170px}.col-lg-1,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-10,.col-lg-11{float:left}.col-lg-1{width:8.333333333333332%}.col-lg-2{width:16.666666666666664%}.col-lg-3{width:25%}.col-lg-4{width:33.33333333333333%}.col-lg-5{width:41.66666666666667%}.col-lg-6{width:50%}.col-lg-7{width:58.333333333333336%}.col-lg-8{width:66.66666666666666%}.col-lg-9{width:75%}.col-lg-10{width:83.33333333333334%}.col-lg-11{width:91.66666666666666%}.col-lg-12{width:100%}.col-lg-push-0{left:auto}.col-lg-push-1{left:8.333333333333332%}.col-lg-push-2{left:16.666666666666664%}.col-lg-push-3{left:25%}.col-lg-push-4{left:33.33333333333333%}.col-lg-push-5{left:41.66666666666667%}.col-lg-push-6{left:50%}.col-lg-push-7{left:58.333333333333336%}.col-lg-push-8{left:66.66666666666666%}.col-lg-push-9{left:75%}.col-lg-push-10{left:83.33333333333334%}.col-lg-push-11{left:91.66666666666666%}.col-lg-pull-0{right:auto}.col-lg-pull-1{right:8.333333333333332%}.col-lg-pull-2{right:16.666666666666664%}.col-lg-pull-3{right:25%}.col-lg-pull-4{right:33.33333333333333%}.col-lg-pull-5{right:41.66666666666667%}.col-lg-pull-6{right:50%}.col-lg-pull-7{right:58.333333333333336%}.col-lg-pull-8{right:66.66666666666666%}.col-lg-pull-9{right:75%}.col-lg-pull-10{right:83.33333333333334%}.col-lg-pull-11{right:91.66666666666666%}.col-lg-offset-0{margin-left:0}.col-lg-offset-1{margin-left:8.333333333333332%}.col-lg-offset-2{margin-left:16.666666666666664%}.col-lg-offset-3{margin-left:25%}.col-lg-offset-4{margin-left:33.33333333333333%}.col-lg-offset-5{margin-left:41.66666666666667%}.col-lg-offset-6{margin-left:50%}.col-lg-offset-7{margin-left:58.333333333333336%}.col-lg-offset-8{margin-left:66.66666666666666%}.col-lg-offset-9{margin-left:75%}.col-lg-offset-10{margin-left:83.33333333333334%}.col-lg-offset-11{margin-left:91.66666666666666%}}table{max-width:100%;background-color:transparent}th{text-align:left}.table{width:100%;margin-bottom:20px}.table thead>tr>th,.table tbody>tr>th,.table tfoot>tr>th,.table thead>tr>td,.table tbody>tr>td,.table tfoot>tr>td{padding:8px;line-height:1.428571429;vertical-align:top;border-top:1px solid #ddd}.table thead>tr>th{vertical-align:bottom;border-bottom:2px solid #ddd}.table caption+thead tr:first-child th,.table colgroup+thead tr:first-child th,.table thead:first-child tr:first-child th,.table caption+thead tr:first-child td,.table colgroup+thead tr:first-child td,.table thead:first-child tr:first-child td{border-top:0}.table tbody+tbody{border-top:2px solid #ddd}.table .table{background-color:#fff}.table-condensed thead>tr>th,.table-condensed tbody>tr>th,.table-condensed tfoot>tr>th,.table-condensed thead>tr>td,.table-condensed tbody>tr>td,.table-condensed tfoot>tr>td{padding:5px}.table-bordered{border:1px solid #ddd}.table-bordered>thead>tr>th,.table-bordered>tbody>tr>th,.table-bordered>tfoot>tr>th,.table-bordered>thead>tr>td,.table-bordered>tbody>tr>td,.table-bordered>tfoot>tr>td{border:1px solid #ddd}.table-bordered>thead>tr>th,.table-bordered>thead>tr>td{border-bottom-width:2px}.table-striped>tbody>tr:nth-child(odd)>td,.table-striped>tbody>tr:nth-child(odd)>th{background-color:#f9f9f9}.table-hover>tbody>tr:hover>td,.table-hover>tbody>tr:hover>th{background-color:#f5f5f5}table col[class*="col-"]{display:table-column;float:none}table td[class*="col-"],table th[class*="col-"]{display:table-cell;float:none}.table>thead>tr>td.active,.table>tbody>tr>td.active,.table>tfoot>tr>td.active,.table>thead>tr>th.active,.table>tbody>tr>th.active,.table>tfoot>tr>th.active,.table>thead>tr.active>td,.table>tbody>tr.active>td,.table>tfoot>tr.active>td,.table>thead>tr.active>th,.table>tbody>tr.active>th,.table>tfoot>tr.active>th{background-color:#f5f5f5}.table>thead>tr>td.success,.table>tbody>tr>td.success,.table>tfoot>tr>td.success,.table>thead>tr>th.success,.table>tbody>tr>th.success,.table>tfoot>tr>th.success,.table>thead>tr.success>td,.table>tbody>tr.success>td,.table>tfoot>tr.success>td,.table>thead>tr.success>th,.table>tbody>tr.success>th,.table>tfoot>tr.success>th{background-color:#dff0d8;border-color:#d6e9c6}.table-hover>tbody>tr>td.success:hover,.table-hover>tbody>tr>th.success:hover,.table-hover>tbody>tr.success:hover>td{background-color:#d0e9c6;border-color:#c9e2b3}.table>thead>tr>td.danger,.table>tbody>tr>td.danger,.table>tfoot>tr>td.danger,.table>thead>tr>th.danger,.table>tbody>tr>th.danger,.table>tfoot>tr>th.danger,.table>thead>tr.danger>td,.table>tbody>tr.danger>td,.table>tfoot>tr.danger>td,.table>thead>tr.danger>th,.table>tbody>tr.danger>th,.table>tfoot>tr.danger>th{background-color:#f2dede;border-color:#eed3d7}.table-hover>tbody>tr>td.danger:hover,.table-hover>tbody>tr>th.danger:hover,.table-hover>tbody>tr.danger:hover>td{background-color:#ebcccc;border-color:#e6c1c7}.table>thead>tr>td.warning,.table>tbody>tr>td.warning,.table>tfoot>tr>td.warning,.table>thead>tr>th.warning,.table>tbody>tr>th.warning,.table>tfoot>tr>th.warning,.table>thead>tr.warning>td,.table>tbody>tr.warning>td,.table>tfoot>tr.warning>td,.table>thead>tr.warning>th,.table>tbody>tr.warning>th,.table>tfoot>tr.warning>th{background-color:#fcf8e3;border-color:#fbeed5}.table-hover>tbody>tr>td.warning:hover,.table-hover>tbody>tr>th.warning:hover,.table-hover>tbody>tr.warning:hover>td{background-color:#faf2cc;border-color:#f8e5be}@media(max-width:768px){.table-responsive{width:100%;margin-bottom:15px;overflow-x:scroll;overflow-y:hidden;border:1px solid #ddd}.table-responsive>.table{margin-bottom:0;background-color:#fff}.table-responsive>.table>thead>tr>th,.table-responsive>.table>tbody>tr>th,.table-responsive>.table>tfoot>tr>th,.table-responsive>.table>thead>tr>td,.table-responsive>.table>tbody>tr>td,.table-responsive>.table>tfoot>tr>td{white-space:nowrap}.table-responsive>.table-bordered{border:0}.table-responsive>.table-bordered>thead>tr>th:first-child,.table-responsive>.table-bordered>tbody>tr>th:first-child,.table-responsive>.table-bordered>tfoot>tr>th:first-child,.table-responsive>.table-bordered>thead>tr>td:first-child,.table-responsive>.table-bordered>tbody>tr>td:first-child,.table-responsive>.table-bordered>tfoot>tr>td:first-child{border-left:0}.table-responsive>.table-bordered>thead>tr>th:last-child,.table-responsive>.table-bordered>tbody>tr>th:last-child,.table-responsive>.table-bordered>tfoot>tr>th:last-child,.table-responsive>.table-bordered>thead>tr>td:last-child,.table-responsive>.table-bordered>tbody>tr>td:last-child,.table-responsive>.table-bordered>tfoot>tr>td:last-child{border-right:0}.table-responsive>.table-bordered>thead>tr:last-child>th,.table-responsive>.table-bordered>tbody>tr:last-child>th,.table-responsive>.table-bordered>tfoot>tr:last-child>th,.table-responsive>.table-bordered>thead>tr:last-child>td,.table-responsive>.table-bordered>tbody>tr:last-child>td,.table-responsive>.table-bordered>tfoot>tr:last-child>td{border-bottom:0}}fieldset{padding:0;margin:0;border:0}legend{display:block;width:100%;padding:0;margin-bottom:20px;font-size:21px;line-height:inherit;color:#333;border:0;border-bottom:1px solid #e5e5e5}label{display:inline-block;margin-bottom:5px;font-weight:bold}input[type="search"]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}input[type="radio"],input[type="checkbox"]{margin:4px 0 0;margin-top:1px \9;line-height:normal}input[type="file"]{display:block}select[multiple],select[size]{height:auto}select optgroup{font-family:inherit;font-size:inherit;font-style:inherit}input[type="file"]:focus,input[type="radio"]:focus,input[type="checkbox"]:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}input[type="number"]::-webkit-outer-spin-button,input[type="number"]::-webkit-inner-spin-button{height:auto}.form-control:-moz-placeholder{color:#999}.form-control::-moz-placeholder{color:#999}.form-control:-ms-input-placeholder{color:#999}.form-control::-webkit-input-placeholder{color:#999}.form-control{display:block;width:100%;height:34px;padding:6px 12px;font-size:14px;line-height:1.428571429;color:#555;vertical-align:middle;background-color:#fff;border:1px solid #ccc;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-webkit-transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s}.form-control:focus{border-color:#66afe9;outline:0;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(102,175,233,0.6);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(102,175,233,0.6)}.form-control[disabled],.form-control[readonly],fieldset[disabled] .form-control{cursor:not-allowed;background-color:#eee}textarea.form-control{height:auto}.form-group{margin-bottom:15px}.radio,.checkbox{display:block;min-height:20px;padding-left:20px;margin-top:10px;margin-bottom:10px;vertical-align:middle}.radio label,.checkbox label{display:inline;margin-bottom:0;font-weight:normal;cursor:pointer}.radio input[type="radio"],.radio-inline input[type="radio"],.checkbox input[type="checkbox"],.checkbox-inline input[type="checkbox"]{float:left;margin-left:-20px}.radio+.radio,.checkbox+.checkbox{margin-top:-5px}.radio-inline,.checkbox-inline{display:inline-block;padding-left:20px;margin-bottom:0;font-weight:normal;vertical-align:middle;cursor:pointer}.radio-inline+.radio-inline,.checkbox-inline+.checkbox-inline{margin-top:0;margin-left:10px}input[type="radio"][disabled],input[type="checkbox"][disabled],.radio[disabled],.radio-inline[disabled],.checkbox[disabled],.checkbox-inline[disabled],fieldset[disabled] input[type="radio"],fieldset[disabled] input[type="checkbox"],fieldset[disabled] .radio,fieldset[disabled] .radio-inline,fieldset[disabled] .checkbox,fieldset[disabled] .checkbox-inline{cursor:not-allowed}.input-sm{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}select.input-sm{height:30px;line-height:30px}textarea.input-sm{height:auto}.input-lg{height:45px;padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}select.input-lg{height:45px;line-height:45px}textarea.input-lg{height:auto}.has-warning .help-block,.has-warning .control-label{color:#c09853}.has-warning .form-control{border-color:#c09853;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.has-warning .form-control:focus{border-color:#a47e3c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e}.has-warning .input-group-addon{color:#c09853;background-color:#fcf8e3;border-color:#c09853}.has-error .help-block,.has-error .control-label{color:#b94a48}.has-error .form-control{border-color:#b94a48;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.has-error .form-control:focus{border-color:#953b39;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392}.has-error .input-group-addon{color:#b94a48;background-color:#f2dede;border-color:#b94a48}.has-success .help-block,.has-success .control-label{color:#468847}.has-success .form-control{border-color:#468847;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.has-success .form-control:focus{border-color:#356635;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b}.has-success .input-group-addon{color:#468847;background-color:#dff0d8;border-color:#468847}.form-control-static{padding-top:7px;margin-bottom:0}.help-block{display:block;margin-top:5px;margin-bottom:10px;color:#737373}@media(min-width:768px){.form-inline .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.form-inline .form-control{display:inline-block}.form-inline .radio,.form-inline .checkbox{display:inline-block;padding-left:0;margin-top:0;margin-bottom:0}.form-inline .radio input[type="radio"],.form-inline .checkbox input[type="checkbox"]{float:none;margin-left:0}}.form-horizontal .control-label,.form-horizontal .radio,.form-horizontal .checkbox,.form-horizontal .radio-inline,.form-horizontal .checkbox-inline{padding-top:7px;margin-top:0;margin-bottom:0}.form-horizontal .form-group{margin-right:-15px;margin-left:-15px}.form-horizontal .form-group:before,.form-horizontal .form-group:after{display:table;content:" "}.form-horizontal .form-group:after{clear:both}.form-horizontal .form-group:before,.form-horizontal .form-group:after{display:table;content:" "}.form-horizontal .form-group:after{clear:both}@media(min-width:768px){.form-horizontal .control-label{text-align:right}}.btn{display:inline-block;padding:6px 12px;margin-bottom:0;font-size:14px;font-weight:normal;line-height:1.428571429;text-align:center;white-space:nowrap;vertical-align:middle;cursor:pointer;border:1px solid transparent;border-radius:4px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn:hover,.btn:focus{color:#333;text-decoration:none}.btn:active,.btn.active{background-image:none;outline:0;-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,0.125);box-shadow:inset 0 3px 5px rgba(0,0,0,0.125)}.btn.disabled,.btn[disabled],fieldset[disabled] .btn{pointer-events:none;cursor:not-allowed;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;box-shadow:none}.btn-default{color:#333;background-color:#fff;border-color:#ccc}.btn-default:hover,.btn-default:focus,.btn-default:active,.btn-default.active,.open .dropdown-toggle.btn-default{color:#333;background-color:#ebebeb;border-color:#adadad}.btn-default:active,.btn-default.active,.open .dropdown-toggle.btn-default{background-image:none}.btn-default.disabled,.btn-default[disabled],fieldset[disabled] .btn-default,.btn-default.disabled:hover,.btn-default[disabled]:hover,fieldset[disabled] .btn-default:hover,.btn-default.disabled:focus,.btn-default[disabled]:focus,fieldset[disabled] .btn-default:focus,.btn-default.disabled:active,.btn-default[disabled]:active,fieldset[disabled] .btn-default:active,.btn-default.disabled.active,.btn-default[disabled].active,fieldset[disabled] .btn-default.active{background-color:#fff;border-color:#ccc}.btn-primary{color:#fff;background-color:#428bca;border-color:#357ebd}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.open .dropdown-toggle.btn-primary{color:#fff;background-color:#3276b1;border-color:#285e8e}.btn-primary:active,.btn-primary.active,.open .dropdown-toggle.btn-primary{background-image:none}.btn-primary.disabled,.btn-primary[disabled],fieldset[disabled] .btn-primary,.btn-primary.disabled:hover,.btn-primary[disabled]:hover,fieldset[disabled] .btn-primary:hover,.btn-primary.disabled:focus,.btn-primary[disabled]:focus,fieldset[disabled] .btn-primary:focus,.btn-primary.disabled:active,.btn-primary[disabled]:active,fieldset[disabled] .btn-primary:active,.btn-primary.disabled.active,.btn-primary[disabled].active,fieldset[disabled] .btn-primary.active{background-color:#428bca;border-color:#357ebd}.btn-warning{color:#fff;background-color:#f0ad4e;border-color:#eea236}.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.active,.open .dropdown-toggle.btn-warning{color:#fff;background-color:#ed9c28;border-color:#d58512}.btn-warning:active,.btn-warning.active,.open .dropdown-toggle.btn-warning{background-image:none}.btn-warning.disabled,.btn-warning[disabled],fieldset[disabled] .btn-warning,.btn-warning.disabled:hover,.btn-warning[disabled]:hover,fieldset[disabled] .btn-warning:hover,.btn-warning.disabled:focus,.btn-warning[disabled]:focus,fieldset[disabled] .btn-warning:focus,.btn-warning.disabled:active,.btn-warning[disabled]:active,fieldset[disabled] .btn-warning:active,.btn-warning.disabled.active,.btn-warning[disabled].active,fieldset[disabled] .btn-warning.active{background-color:#f0ad4e;border-color:#eea236}.btn-danger{color:#fff;background-color:#d9534f;border-color:#d43f3a}.btn-danger:hover,.btn-danger:focus,.btn-danger:active,.btn-danger.active,.open .dropdown-toggle.btn-danger{color:#fff;background-color:#d2322d;border-color:#ac2925}.btn-danger:active,.btn-danger.active,.open .dropdown-toggle.btn-danger{background-image:none}.btn-danger.disabled,.btn-danger[disabled],fieldset[disabled] .btn-danger,.btn-danger.disabled:hover,.btn-danger[disabled]:hover,fieldset[disabled] .btn-danger:hover,.btn-danger.disabled:focus,.btn-danger[disabled]:focus,fieldset[disabled] .btn-danger:focus,.btn-danger.disabled:active,.btn-danger[disabled]:active,fieldset[disabled] .btn-danger:active,.btn-danger.disabled.active,.btn-danger[disabled].active,fieldset[disabled] .btn-danger.active{background-color:#d9534f;border-color:#d43f3a}.btn-success{color:#fff;background-color:#5cb85c;border-color:#4cae4c}.btn-success:hover,.btn-success:focus,.btn-success:active,.btn-success.active,.open .dropdown-toggle.btn-success{color:#fff;background-color:#47a447;border-color:#398439}.btn-success:active,.btn-success.active,.open .dropdown-toggle.btn-success{background-image:none}.btn-success.disabled,.btn-success[disabled],fieldset[disabled] .btn-success,.btn-success.disabled:hover,.btn-success[disabled]:hover,fieldset[disabled] .btn-success:hover,.btn-success.disabled:focus,.btn-success[disabled]:focus,fieldset[disabled] .btn-success:focus,.btn-success.disabled:active,.btn-success[disabled]:active,fieldset[disabled] .btn-success:active,.btn-success.disabled.active,.btn-success[disabled].active,fieldset[disabled] .btn-success.active{background-color:#5cb85c;border-color:#4cae4c}.btn-info{color:#fff;background-color:#5bc0de;border-color:#46b8da}.btn-info:hover,.btn-info:focus,.btn-info:active,.btn-info.active,.open .dropdown-toggle.btn-info{color:#fff;background-color:#39b3d7;border-color:#269abc}.btn-info:active,.btn-info.active,.open .dropdown-toggle.btn-info{background-image:none}.btn-info.disabled,.btn-info[disabled],fieldset[disabled] .btn-info,.btn-info.disabled:hover,.btn-info[disabled]:hover,fieldset[disabled] .btn-info:hover,.btn-info.disabled:focus,.btn-info[disabled]:focus,fieldset[disabled] .btn-info:focus,.btn-info.disabled:active,.btn-info[disabled]:active,fieldset[disabled] .btn-info:active,.btn-info.disabled.active,.btn-info[disabled].active,fieldset[disabled] .btn-info.active{background-color:#5bc0de;border-color:#46b8da}.btn-link{font-weight:normal;color:#428bca;cursor:pointer;border-radius:0}.btn-link,.btn-link:active,.btn-link[disabled],fieldset[disabled] .btn-link{background-color:transparent;-webkit-box-shadow:none;box-shadow:none}.btn-link,.btn-link:hover,.btn-link:focus,.btn-link:active{border-color:transparent}.btn-link:hover,.btn-link:focus{color:#2a6496;text-decoration:underline;background-color:transparent}.btn-link[disabled]:hover,fieldset[disabled] .btn-link:hover,.btn-link[disabled]:focus,fieldset[disabled] .btn-link:focus{color:#999;text-decoration:none}.btn-lg{padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}.btn-sm,.btn-xs{padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.btn-xs{padding:1px 5px}.btn-block{display:block;width:100%;padding-right:0;padding-left:0}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.fade{opacity:0;-webkit-transition:opacity .15s linear;transition:opacity .15s linear}.fade.in{opacity:1}.collapse{display:none}.collapse.in{display:block}.collapsing{position:relative;height:0;overflow:hidden;-webkit-transition:height .35s ease;transition:height .35s ease}@font-face{font-family:'Glyphicons Halflings';src:url('../fonts/glyphicons-halflings-regular.eot');src:url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'),url('../fonts/glyphicons-halflings-regular.woff') format('woff'),url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'),url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg')}.glyphicon{position:relative;top:1px;display:inline-block;font-family:'Glyphicons Halflings';-webkit-font-smoothing:antialiased;font-style:normal;font-weight:normal;line-height:1}.glyphicon-asterisk:before{content:"\2a"}.glyphicon-plus:before{content:"\2b"}.glyphicon-euro:before{content:"\20ac"}.glyphicon-minus:before{content:"\2212"}.glyphicon-cloud:before{content:"\2601"}.glyphicon-envelope:before{content:"\2709"}.glyphicon-pencil:before{content:"\270f"}.glyphicon-glass:before{content:"\e001"}.glyphicon-music:before{content:"\e002"}.glyphicon-search:before{content:"\e003"}.glyphicon-heart:before{content:"\e005"}.glyphicon-star:before{content:"\e006"}.glyphicon-star-empty:before{content:"\e007"}.glyphicon-user:before{content:"\e008"}.glyphicon-film:before{content:"\e009"}.glyphicon-th-large:before{content:"\e010"}.glyphicon-th:before{content:"\e011"}.glyphicon-th-list:before{content:"\e012"}.glyphicon-ok:before{content:"\e013"}.glyphicon-remove:before{content:"\e014"}.glyphicon-zoom-in:before{content:"\e015"}.glyphicon-zoom-out:before{content:"\e016"}.glyphicon-off:before{content:"\e017"}.glyphicon-signal:before{content:"\e018"}.glyphicon-cog:before{content:"\e019"}.glyphicon-trash:before{content:"\e020"}.glyphicon-home:before{content:"\e021"}.glyphicon-file:before{content:"\e022"}.glyphicon-time:before{content:"\e023"}.glyphicon-road:before{content:"\e024"}.glyphicon-download-alt:before{content:"\e025"}.glyphicon-download:before{content:"\e026"}.glyphicon-upload:before{content:"\e027"}.glyphicon-inbox:before{content:"\e028"}.glyphicon-play-circle:before{content:"\e029"}.glyphicon-repeat:before{content:"\e030"}.glyphicon-refresh:before{content:"\e031"}.glyphicon-list-alt:before{content:"\e032"}.glyphicon-flag:before{content:"\e034"}.glyphicon-headphones:before{content:"\e035"}.glyphicon-volume-off:before{content:"\e036"}.glyphicon-volume-down:before{content:"\e037"}.glyphicon-volume-up:before{content:"\e038"}.glyphicon-qrcode:before{content:"\e039"}.glyphicon-barcode:before{content:"\e040"}.glyphicon-tag:before{content:"\e041"}.glyphicon-tags:before{content:"\e042"}.glyphicon-book:before{content:"\e043"}.glyphicon-print:before{content:"\e045"}.glyphicon-font:before{content:"\e047"}.glyphicon-bold:before{content:"\e048"}.glyphicon-italic:before{content:"\e049"}.glyphicon-text-height:before{content:"\e050"}.glyphicon-text-width:before{content:"\e051"}.glyphicon-align-left:before{content:"\e052"}.glyphicon-align-center:before{content:"\e053"}.glyphicon-align-right:before{content:"\e054"}.glyphicon-align-justify:before{content:"\e055"}.glyphicon-list:before{content:"\e056"}.glyphicon-indent-left:before{content:"\e057"}.glyphicon-indent-right:before{content:"\e058"}.glyphicon-facetime-video:before{content:"\e059"}.glyphicon-picture:before{content:"\e060"}.glyphicon-map-marker:before{content:"\e062"}.glyphicon-adjust:before{content:"\e063"}.glyphicon-tint:before{content:"\e064"}.glyphicon-edit:before{content:"\e065"}.glyphicon-share:before{content:"\e066"}.glyphicon-check:before{content:"\e067"}.glyphicon-move:before{content:"\e068"}.glyphicon-step-backward:before{content:"\e069"}.glyphicon-fast-backward:before{content:"\e070"}.glyphicon-backward:before{content:"\e071"}.glyphicon-play:before{content:"\e072"}.glyphicon-pause:before{content:"\e073"}.glyphicon-stop:before{content:"\e074"}.glyphicon-forward:before{content:"\e075"}.glyphicon-fast-forward:before{content:"\e076"}.glyphicon-step-forward:before{content:"\e077"}.glyphicon-eject:before{content:"\e078"}.glyphicon-chevron-left:before{content:"\e079"}.glyphicon-chevron-right:before{content:"\e080"}.glyphicon-plus-sign:before{content:"\e081"}.glyphicon-minus-sign:before{content:"\e082"}.glyphicon-remove-sign:before{content:"\e083"}.glyphicon-ok-sign:before{content:"\e084"}.glyphicon-question-sign:before{content:"\e085"}.glyphicon-info-sign:before{content:"\e086"}.glyphicon-screenshot:before{content:"\e087"}.glyphicon-remove-circle:before{content:"\e088"}.glyphicon-ok-circle:before{content:"\e089"}.glyphicon-ban-circle:before{content:"\e090"}.glyphicon-arrow-left:before{content:"\e091"}.glyphicon-arrow-right:before{content:"\e092"}.glyphicon-arrow-up:before{content:"\e093"}.glyphicon-arrow-down:before{content:"\e094"}.glyphicon-share-alt:before{content:"\e095"}.glyphicon-resize-full:before{content:"\e096"}.glyphicon-resize-small:before{content:"\e097"}.glyphicon-exclamation-sign:before{content:"\e101"}.glyphicon-gift:before{content:"\e102"}.glyphicon-leaf:before{content:"\e103"}.glyphicon-eye-open:before{content:"\e105"}.glyphicon-eye-close:before{content:"\e106"}.glyphicon-warning-sign:before{content:"\e107"}.glyphicon-plane:before{content:"\e108"}.glyphicon-random:before{content:"\e110"}.glyphicon-comment:before{content:"\e111"}.glyphicon-magnet:before{content:"\e112"}.glyphicon-chevron-up:before{content:"\e113"}.glyphicon-chevron-down:before{content:"\e114"}.glyphicon-retweet:before{content:"\e115"}.glyphicon-shopping-cart:before{content:"\e116"}.glyphicon-folder-close:before{content:"\e117"}.glyphicon-folder-open:before{content:"\e118"}.glyphicon-resize-vertical:before{content:"\e119"}.glyphicon-resize-horizontal:before{content:"\e120"}.glyphicon-hdd:before{content:"\e121"}.glyphicon-bullhorn:before{content:"\e122"}.glyphicon-certificate:before{content:"\e124"}.glyphicon-thumbs-up:before{content:"\e125"}.glyphicon-thumbs-down:before{content:"\e126"}.glyphicon-hand-right:before{content:"\e127"}.glyphicon-hand-left:before{content:"\e128"}.glyphicon-hand-up:before{content:"\e129"}.glyphicon-hand-down:before{content:"\e130"}.glyphicon-circle-arrow-right:before{content:"\e131"}.glyphicon-circle-arrow-left:before{content:"\e132"}.glyphicon-circle-arrow-up:before{content:"\e133"}.glyphicon-circle-arrow-down:before{content:"\e134"}.glyphicon-globe:before{content:"\e135"}.glyphicon-tasks:before{content:"\e137"}.glyphicon-filter:before{content:"\e138"}.glyphicon-fullscreen:before{content:"\e140"}.glyphicon-dashboard:before{content:"\e141"}.glyphicon-heart-empty:before{content:"\e143"}.glyphicon-link:before{content:"\e144"}.glyphicon-phone:before{content:"\e145"}.glyphicon-usd:before{content:"\e148"}.glyphicon-gbp:before{content:"\e149"}.glyphicon-sort:before{content:"\e150"}.glyphicon-sort-by-alphabet:before{content:"\e151"}.glyphicon-sort-by-alphabet-alt:before{content:"\e152"}.glyphicon-sort-by-order:before{content:"\e153"}.glyphicon-sort-by-order-alt:before{content:"\e154"}.glyphicon-sort-by-attributes:before{content:"\e155"}.glyphicon-sort-by-attributes-alt:before{content:"\e156"}.glyphicon-unchecked:before{content:"\e157"}.glyphicon-expand:before{content:"\e158"}.glyphicon-collapse-down:before{content:"\e159"}.glyphicon-collapse-up:before{content:"\e160"}.glyphicon-log-in:before{content:"\e161"}.glyphicon-flash:before{content:"\e162"}.glyphicon-log-out:before{content:"\e163"}.glyphicon-new-window:before{content:"\e164"}.glyphicon-record:before{content:"\e165"}.glyphicon-save:before{content:"\e166"}.glyphicon-open:before{content:"\e167"}.glyphicon-saved:before{content:"\e168"}.glyphicon-import:before{content:"\e169"}.glyphicon-export:before{content:"\e170"}.glyphicon-send:before{content:"\e171"}.glyphicon-floppy-disk:before{content:"\e172"}.glyphicon-floppy-saved:before{content:"\e173"}.glyphicon-floppy-remove:before{content:"\e174"}.glyphicon-floppy-save:before{content:"\e175"}.glyphicon-floppy-open:before{content:"\e176"}.glyphicon-credit-card:before{content:"\e177"}.glyphicon-transfer:before{content:"\e178"}.glyphicon-cutlery:before{content:"\e179"}.glyphicon-header:before{content:"\e180"}.glyphicon-compressed:before{content:"\e181"}.glyphicon-earphone:before{content:"\e182"}.glyphicon-phone-alt:before{content:"\e183"}.glyphicon-tower:before{content:"\e184"}.glyphicon-stats:before{content:"\e185"}.glyphicon-sd-video:before{content:"\e186"}.glyphicon-hd-video:before{content:"\e187"}.glyphicon-subtitles:before{content:"\e188"}.glyphicon-sound-stereo:before{content:"\e189"}.glyphicon-sound-dolby:before{content:"\e190"}.glyphicon-sound-5-1:before{content:"\e191"}.glyphicon-sound-6-1:before{content:"\e192"}.glyphicon-sound-7-1:before{content:"\e193"}.glyphicon-copyright-mark:before{content:"\e194"}.glyphicon-registration-mark:before{content:"\e195"}.glyphicon-cloud-download:before{content:"\e197"}.glyphicon-cloud-upload:before{content:"\e198"}.glyphicon-tree-conifer:before{content:"\e199"}.glyphicon-tree-deciduous:before{content:"\e200"}.glyphicon-briefcase:before{content:"\1f4bc"}.glyphicon-calendar:before{content:"\1f4c5"}.glyphicon-pushpin:before{content:"\1f4cc"}.glyphicon-paperclip:before{content:"\1f4ce"}.glyphicon-camera:before{content:"\1f4f7"}.glyphicon-lock:before{content:"\1f512"}.glyphicon-bell:before{content:"\1f514"}.glyphicon-bookmark:before{content:"\1f516"}.glyphicon-fire:before{content:"\1f525"}.glyphicon-wrench:before{content:"\1f527"}.caret{display:inline-block;width:0;height:0;margin-left:2px;vertical-align:middle;border-top:4px solid #000;border-right:4px solid transparent;border-bottom:0 dotted;border-left:4px solid transparent;content:""}.dropdown{position:relative}.dropdown-toggle:focus{outline:0}.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:160px;padding:5px 0;margin:2px 0 0;font-size:14px;list-style:none;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.15);border-radius:4px;-webkit-box-shadow:0 6px 12px rgba(0,0,0,0.175);box-shadow:0 6px 12px rgba(0,0,0,0.175);background-clip:padding-box}.dropdown-menu.pull-right{right:0;left:auto}.dropdown-menu .divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.dropdown-menu>li>a{display:block;padding:3px 20px;clear:both;font-weight:normal;line-height:1.428571429;color:#333;white-space:nowrap}.dropdown-menu>li>a:hover,.dropdown-menu>li>a:focus{color:#fff;text-decoration:none;background-color:#428bca}.dropdown-menu>.active>a,.dropdown-menu>.active>a:hover,.dropdown-menu>.active>a:focus{color:#fff;text-decoration:none;background-color:#428bca;outline:0}.dropdown-menu>.disabled>a,.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{color:#999}.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{text-decoration:none;cursor:not-allowed;background-color:transparent;background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.open>.dropdown-menu{display:block}.open>a{outline:0}.dropdown-header{display:block;padding:3px 20px;font-size:12px;line-height:1.428571429;color:#999}.dropdown-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:990}.pull-right>.dropdown-menu{right:0;left:auto}.dropup .caret,.navbar-fixed-bottom .dropdown .caret{border-top:0 dotted;border-bottom:4px solid #000;content:""}.dropup .dropdown-menu,.navbar-fixed-bottom .dropdown .dropdown-menu{top:auto;bottom:100%;margin-bottom:1px}@media(min-width:768px){.navbar-right .dropdown-menu{right:0;left:auto}}.btn-default .caret{border-top-color:#333}.btn-primary .caret,.btn-success .caret,.btn-warning .caret,.btn-danger .caret,.btn-info .caret{border-top-color:#fff}.dropup .btn-default .caret{border-bottom-color:#333}.dropup .btn-primary .caret,.dropup .btn-success .caret,.dropup .btn-warning .caret,.dropup .btn-danger .caret,.dropup .btn-info .caret{border-bottom-color:#fff}.btn-group,.btn-group-vertical{position:relative;display:inline-block;vertical-align:middle}.btn-group>.btn,.btn-group-vertical>.btn{position:relative;float:left}.btn-group>.btn:hover,.btn-group-vertical>.btn:hover,.btn-group>.btn:focus,.btn-group-vertical>.btn:focus,.btn-group>.btn:active,.btn-group-vertical>.btn:active,.btn-group>.btn.active,.btn-group-vertical>.btn.active{z-index:2}.btn-group>.btn:focus,.btn-group-vertical>.btn:focus{outline:0}.btn-group .btn+.btn,.btn-group .btn+.btn-group,.btn-group .btn-group+.btn,.btn-group .btn-group+.btn-group{margin-left:-1px}.btn-toolbar:before,.btn-toolbar:after{display:table;content:" "}.btn-toolbar:after{clear:both}.btn-toolbar:before,.btn-toolbar:after{display:table;content:" "}.btn-toolbar:after{clear:both}.btn-toolbar .btn-group{float:left}.btn-toolbar>.btn+.btn,.btn-toolbar>.btn-group+.btn,.btn-toolbar>.btn+.btn-group,.btn-toolbar>.btn-group+.btn-group{margin-left:5px}.btn-group>.btn:not(:first-child):not(:last-child):not(.dropdown-toggle){border-radius:0}.btn-group>.btn:first-child{margin-left:0}.btn-group>.btn:first-child:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn:last-child:not(:first-child),.btn-group>.dropdown-toggle:not(:first-child){border-bottom-left-radius:0;border-top-left-radius:0}.btn-group>.btn-group{float:left}.btn-group>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group>.btn-group:first-child>.btn:last-child,.btn-group>.btn-group:first-child>.dropdown-toggle{border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn-group:last-child>.btn:first-child{border-bottom-left-radius:0;border-top-left-radius:0}.btn-group .dropdown-toggle:active,.btn-group.open .dropdown-toggle{outline:0}.btn-group-xs>.btn{padding:5px 10px;padding:1px 5px;font-size:12px;line-height:1.5;border-radius:3px}.btn-group-sm>.btn{padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.btn-group-lg>.btn{padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}.btn-group>.btn+.dropdown-toggle{padding-right:8px;padding-left:8px}.btn-group>.btn-lg+.dropdown-toggle{padding-right:12px;padding-left:12px}.btn-group.open .dropdown-toggle{-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,0.125);box-shadow:inset 0 3px 5px rgba(0,0,0,0.125)}.btn .caret{margin-left:0}.btn-lg .caret{border-width:5px 5px 0;border-bottom-width:0}.dropup .btn-lg .caret{border-width:0 5px 5px}.btn-group-vertical>.btn,.btn-group-vertical>.btn-group{display:block;float:none;width:100%;max-width:100%}.btn-group-vertical>.btn-group:before,.btn-group-vertical>.btn-group:after{display:table;content:" "}.btn-group-vertical>.btn-group:after{clear:both}.btn-group-vertical>.btn-group:before,.btn-group-vertical>.btn-group:after{display:table;content:" "}.btn-group-vertical>.btn-group:after{clear:both}.btn-group-vertical>.btn-group>.btn{float:none}.btn-group-vertical>.btn+.btn,.btn-group-vertical>.btn+.btn-group,.btn-group-vertical>.btn-group+.btn,.btn-group-vertical>.btn-group+.btn-group{margin-top:-1px;margin-left:0}.btn-group-vertical>.btn:not(:first-child):not(:last-child){border-radius:0}.btn-group-vertical>.btn:first-child:not(:last-child){border-top-right-radius:4px;border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn:last-child:not(:first-child){border-top-right-radius:0;border-bottom-left-radius:4px;border-top-left-radius:0}.btn-group-vertical>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group-vertical>.btn-group:first-child>.btn:last-child,.btn-group-vertical>.btn-group:first-child>.dropdown-toggle{border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn-group:last-child>.btn:first-child{border-top-right-radius:0;border-top-left-radius:0}.btn-group-justified{display:table;width:100%;border-collapse:separate;table-layout:fixed}.btn-group-justified .btn{display:table-cell;float:none;width:1%}[data-toggle="buttons"]>.btn>input[type="radio"],[data-toggle="buttons"]>.btn>input[type="checkbox"]{display:none}.input-group{position:relative;display:table;border-collapse:separate}.input-group.col{float:none;padding-right:0;padding-left:0}.input-group .form-control{width:100%;margin-bottom:0}.input-group-lg>.form-control,.input-group-lg>.input-group-addon,.input-group-lg>.input-group-btn>.btn{height:45px;padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}select.input-group-lg>.form-control,select.input-group-lg>.input-group-addon,select.input-group-lg>.input-group-btn>.btn{height:45px;line-height:45px}textarea.input-group-lg>.form-control,textarea.input-group-lg>.input-group-addon,textarea.input-group-lg>.input-group-btn>.btn{height:auto}.input-group-sm>.form-control,.input-group-sm>.input-group-addon,.input-group-sm>.input-group-btn>.btn{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}select.input-group-sm>.form-control,select.input-group-sm>.input-group-addon,select.input-group-sm>.input-group-btn>.btn{height:30px;line-height:30px}textarea.input-group-sm>.form-control,textarea.input-group-sm>.input-group-addon,textarea.input-group-sm>.input-group-btn>.btn{height:auto}.input-group-addon,.input-group-btn,.input-group .form-control{display:table-cell}.input-group-addon:not(:first-child):not(:last-child),.input-group-btn:not(:first-child):not(:last-child),.input-group .form-control:not(:first-child):not(:last-child){border-radius:0}.input-group-addon,.input-group-btn{width:1%;white-space:nowrap;vertical-align:middle}.input-group-addon{padding:6px 12px;font-size:14px;font-weight:normal;line-height:1;text-align:center;background-color:#eee;border:1px solid #ccc;border-radius:4px}.input-group-addon.input-sm{padding:5px 10px;font-size:12px;border-radius:3px}.input-group-addon.input-lg{padding:10px 16px;font-size:18px;border-radius:6px}.input-group-addon input[type="radio"],.input-group-addon input[type="checkbox"]{margin-top:0}.input-group .form-control:first-child,.input-group-addon:first-child,.input-group-btn:first-child>.btn,.input-group-btn:first-child>.dropdown-toggle,.input-group-btn:last-child>.btn:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.input-group-addon:first-child{border-right:0}.input-group .form-control:last-child,.input-group-addon:last-child,.input-group-btn:last-child>.btn,.input-group-btn:last-child>.dropdown-toggle,.input-group-btn:first-child>.btn:not(:first-child){border-bottom-left-radius:0;border-top-left-radius:0}.input-group-addon:last-child{border-left:0}.input-group-btn{position:relative;white-space:nowrap}.input-group-btn>.btn{position:relative}.input-group-btn>.btn+.btn{margin-left:-4px}.input-group-btn>.btn:hover,.input-group-btn>.btn:active{z-index:2}.nav{padding-left:0;margin-bottom:0;list-style:none}.nav:before,.nav:after{display:table;content:" "}.nav:after{clear:both}.nav:before,.nav:after{display:table;content:" "}.nav:after{clear:both}.nav>li{position:relative;display:block}.nav>li>a{position:relative;display:block;padding:10px 15px}.nav>li>a:hover,.nav>li>a:focus{text-decoration:none;background-color:#eee}.nav>li.disabled>a{color:#999}.nav>li.disabled>a:hover,.nav>li.disabled>a:focus{color:#999;text-decoration:none;cursor:not-allowed;background-color:transparent}.nav .open>a,.nav .open>a:hover,.nav .open>a:focus{background-color:#eee;border-color:#428bca}.nav .nav-divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.nav>li>a>img{max-width:none}.nav-tabs{border-bottom:1px solid #ddd}.nav-tabs>li{float:left;margin-bottom:-1px}.nav-tabs>li>a{margin-right:2px;line-height:1.428571429;border:1px solid transparent;border-radius:4px 4px 0 0}.nav-tabs>li>a:hover{border-color:#eee #eee #ddd}.nav-tabs>li.active>a,.nav-tabs>li.active>a:hover,.nav-tabs>li.active>a:focus{color:#555;cursor:default;background-color:#fff;border:1px solid #ddd;border-bottom-color:transparent}.nav-tabs.nav-justified{width:100%;border-bottom:0}.nav-tabs.nav-justified>li{float:none}.nav-tabs.nav-justified>li>a{text-align:center}@media(min-width:768px){.nav-tabs.nav-justified>li{display:table-cell;width:1%}}.nav-tabs.nav-justified>li>a{margin-right:0;border-bottom:1px solid #ddd}.nav-tabs.nav-justified>.active>a{border-bottom-color:#fff}.nav-pills>li{float:left}.nav-pills>li>a{border-radius:5px}.nav-pills>li+li{margin-left:2px}.nav-pills>li.active>a,.nav-pills>li.active>a:hover,.nav-pills>li.active>a:focus{color:#fff;background-color:#428bca}.nav-stacked>li{float:none}.nav-stacked>li+li{margin-top:2px;margin-left:0}.nav-justified{width:100%}.nav-justified>li{float:none}.nav-justified>li>a{text-align:center}@media(min-width:768px){.nav-justified>li{display:table-cell;width:1%}}.nav-tabs-justified{border-bottom:0}.nav-tabs-justified>li>a{margin-right:0;border-bottom:1px solid #ddd}.nav-tabs-justified>.active>a{border-bottom-color:#fff}.tabbable:before,.tabbable:after{display:table;content:" "}.tabbable:after{clear:both}.tabbable:before,.tabbable:after{display:table;content:" "}.tabbable:after{clear:both}.tab-content>.tab-pane,.pill-content>.pill-pane{display:none}.tab-content>.active,.pill-content>.active{display:block}.nav .caret{border-top-color:#428bca;border-bottom-color:#428bca}.nav a:hover .caret{border-top-color:#2a6496;border-bottom-color:#2a6496}.nav-tabs .dropdown-menu{margin-top:-1px;border-top-right-radius:0;border-top-left-radius:0}.navbar{position:relative;z-index:1000;min-height:50px;margin-bottom:20px;border:1px solid transparent}.navbar:before,.navbar:after{display:table;content:" "}.navbar:after{clear:both}.navbar:before,.navbar:after{display:table;content:" "}.navbar:after{clear:both}@media(min-width:768px){.navbar{border-radius:4px}}.navbar-header:before,.navbar-header:after{display:table;content:" "}.navbar-header:after{clear:both}.navbar-header:before,.navbar-header:after{display:table;content:" "}.navbar-header:after{clear:both}@media(min-width:768px){.navbar-header{float:left}}.navbar-collapse{max-height:340px;padding-right:15px;padding-left:15px;overflow-x:visible;border-top:1px solid transparent;box-shadow:inset 0 1px 0 rgba(255,255,255,0.1);-webkit-overflow-scrolling:touch}.navbar-collapse:before,.navbar-collapse:after{display:table;content:" "}.navbar-collapse:after{clear:both}.navbar-collapse:before,.navbar-collapse:after{display:table;content:" "}.navbar-collapse:after{clear:both}.navbar-collapse.in{overflow-y:auto}@media(min-width:768px){.navbar-collapse{width:auto;border-top:0;box-shadow:none}.navbar-collapse.collapse{display:block!important;height:auto!important;padding-bottom:0;overflow:visible!important}.navbar-collapse.in{overflow-y:visible}.navbar-collapse .navbar-nav.navbar-left:first-child{margin-left:-15px}.navbar-collapse .navbar-nav.navbar-right:last-child{margin-right:-15px}.navbar-collapse .navbar-text:last-child{margin-right:0}}.container>.navbar-header,.container>.navbar-collapse{margin-right:-15px;margin-left:-15px}@media(min-width:768px){.container>.navbar-header,.container>.navbar-collapse{margin-right:0;margin-left:0}}.navbar-static-top{border-width:0 0 1px}@media(min-width:768px){.navbar-static-top{border-radius:0}}.navbar-fixed-top,.navbar-fixed-bottom{position:fixed;right:0;left:0;border-width:0 0 1px}@media(min-width:768px){.navbar-fixed-top,.navbar-fixed-bottom{border-radius:0}}.navbar-fixed-top{top:0;z-index:1030}.navbar-fixed-bottom{bottom:0;margin-bottom:0}.navbar-brand{float:left;padding:15px 15px;font-size:18px;line-height:20px}.navbar-brand:hover,.navbar-brand:focus{text-decoration:none}@media(min-width:768px){.navbar>.container .navbar-brand{margin-left:-15px}}.navbar-toggle{position:relative;float:right;padding:9px 10px;margin-top:8px;margin-right:15px;margin-bottom:8px;background-color:transparent;border:1px solid transparent;border-radius:4px}.navbar-toggle .icon-bar{display:block;width:22px;height:2px;border-radius:1px}.navbar-toggle .icon-bar+.icon-bar{margin-top:4px}@media(min-width:768px){.navbar-toggle{display:none}}.navbar-nav{margin:7.5px -15px}.navbar-nav>li>a{padding-top:10px;padding-bottom:10px;line-height:20px}@media(max-width:767px){.navbar-nav .open .dropdown-menu{position:static;float:none;width:auto;margin-top:0;background-color:transparent;border:0;box-shadow:none}.navbar-nav .open .dropdown-menu>li>a,.navbar-nav .open .dropdown-menu .dropdown-header{padding:5px 15px 5px 25px}.navbar-nav .open .dropdown-menu>li>a{line-height:20px}.navbar-nav .open .dropdown-menu>li>a:hover,.navbar-nav .open .dropdown-menu>li>a:focus{background-image:none}}@media(min-width:768px){.navbar-nav{float:left;margin:0}.navbar-nav>li{float:left}.navbar-nav>li>a{padding-top:15px;padding-bottom:15px}}@media(min-width:768px){.navbar-left{float:left!important}.navbar-right{float:right!important}}.navbar-form{padding:10px 15px;margin-top:8px;margin-right:-15px;margin-bottom:8px;margin-left:-15px;border-top:1px solid transparent;border-bottom:1px solid transparent;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.1);box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.1)}@media(min-width:768px){.navbar-form .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.navbar-form .form-control{display:inline-block}.navbar-form .radio,.navbar-form .checkbox{display:inline-block;padding-left:0;margin-top:0;margin-bottom:0}.navbar-form .radio input[type="radio"],.navbar-form .checkbox input[type="checkbox"]{float:none;margin-left:0}}@media(max-width:767px){.navbar-form .form-group{margin-bottom:5px}}@media(min-width:768px){.navbar-form{width:auto;padding-top:0;padding-bottom:0;margin-right:0;margin-left:0;border:0;-webkit-box-shadow:none;box-shadow:none}}.navbar-nav>li>.dropdown-menu{margin-top:0;border-top-right-radius:0;border-top-left-radius:0}.navbar-fixed-bottom .navbar-nav>li>.dropdown-menu{border-bottom-right-radius:0;border-bottom-left-radius:0}.navbar-nav.pull-right>li>.dropdown-menu,.navbar-nav>li>.dropdown-menu.pull-right{right:0;left:auto}.navbar-btn{margin-top:8px;margin-bottom:8px}.navbar-text{float:left;margin-top:15px;margin-bottom:15px}@media(min-width:768px){.navbar-text{margin-right:15px;margin-left:15px}}.navbar-default{background-color:#f8f8f8;border-color:#e7e7e7}.navbar-default .navbar-brand{color:#777}.navbar-default .navbar-brand:hover,.navbar-default .navbar-brand:focus{color:#5e5e5e;background-color:transparent}.navbar-default .navbar-text{color:#777}.navbar-default .navbar-nav>li>a{color:#777}.navbar-default .navbar-nav>li>a:hover,.navbar-default .navbar-nav>li>a:focus{color:#333;background-color:transparent}.navbar-default .navbar-nav>.active>a,.navbar-default .navbar-nav>.active>a:hover,.navbar-default .navbar-nav>.active>a:focus{color:#555;background-color:#e7e7e7}.navbar-default .navbar-nav>.disabled>a,.navbar-default .navbar-nav>.disabled>a:hover,.navbar-default .navbar-nav>.disabled>a:focus{color:#ccc;background-color:transparent}.navbar-default .navbar-toggle{border-color:#ddd}.navbar-default .navbar-toggle:hover,.navbar-default .navbar-toggle:focus{background-color:#ddd}.navbar-default .navbar-toggle .icon-bar{background-color:#ccc}.navbar-default .navbar-collapse,.navbar-default .navbar-form{border-color:#e6e6e6}.navbar-default .navbar-nav>.dropdown>a:hover .caret,.navbar-default .navbar-nav>.dropdown>a:focus .caret{border-top-color:#333;border-bottom-color:#333}.navbar-default .navbar-nav>.open>a,.navbar-default .navbar-nav>.open>a:hover,.navbar-default .navbar-nav>.open>a:focus{color:#555;background-color:#e7e7e7}.navbar-default .navbar-nav>.open>a .caret,.navbar-default .navbar-nav>.open>a:hover .caret,.navbar-default .navbar-nav>.open>a:focus .caret{border-top-color:#555;border-bottom-color:#555}.navbar-default .navbar-nav>.dropdown>a .caret{border-top-color:#777;border-bottom-color:#777}@media(max-width:767px){.navbar-default .navbar-nav .open .dropdown-menu>li>a{color:#777}.navbar-default .navbar-nav .open .dropdown-menu>li>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>li>a:focus{color:#333;background-color:transparent}.navbar-default .navbar-nav .open .dropdown-menu>.active>a,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:focus{color:#555;background-color:#e7e7e7}.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:focus{color:#ccc;background-color:transparent}}.navbar-default .navbar-link{color:#777}.navbar-default .navbar-link:hover{color:#333}.navbar-inverse{background-color:#222;border-color:#080808}.navbar-inverse .navbar-brand{color:#999}.navbar-inverse .navbar-brand:hover,.navbar-inverse .navbar-brand:focus{color:#fff;background-color:transparent}.navbar-inverse .navbar-text{color:#999}.navbar-inverse .navbar-nav>li>a{color:#999}.navbar-inverse .navbar-nav>li>a:hover,.navbar-inverse .navbar-nav>li>a:focus{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav>.active>a,.navbar-inverse .navbar-nav>.active>a:hover,.navbar-inverse .navbar-nav>.active>a:focus{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav>.disabled>a,.navbar-inverse .navbar-nav>.disabled>a:hover,.navbar-inverse .navbar-nav>.disabled>a:focus{color:#444;background-color:transparent}.navbar-inverse .navbar-toggle{border-color:#333}.navbar-inverse .navbar-toggle:hover,.navbar-inverse .navbar-toggle:focus{background-color:#333}.navbar-inverse .navbar-toggle .icon-bar{background-color:#fff}.navbar-inverse .navbar-collapse,.navbar-inverse .navbar-form{border-color:#101010}.navbar-inverse .navbar-nav>.open>a,.navbar-inverse .navbar-nav>.open>a:hover,.navbar-inverse .navbar-nav>.open>a:focus{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav>.dropdown>a:hover .caret{border-top-color:#fff;border-bottom-color:#fff}.navbar-inverse .navbar-nav>.dropdown>a .caret{border-top-color:#999;border-bottom-color:#999}.navbar-inverse .navbar-nav>.open>a .caret,.navbar-inverse .navbar-nav>.open>a:hover .caret,.navbar-inverse .navbar-nav>.open>a:focus .caret{border-top-color:#fff;border-bottom-color:#fff}@media(max-width:767px){.navbar-inverse .navbar-nav .open .dropdown-menu>.dropdown-header{border-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu>li>a{color:#999}.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:focus{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:focus{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:focus{color:#444;background-color:transparent}}.navbar-inverse .navbar-link{color:#999}.navbar-inverse .navbar-link:hover{color:#fff}.breadcrumb{padding:8px 15px;margin-bottom:20px;list-style:none;background-color:#f5f5f5;border-radius:4px}.breadcrumb>li{display:inline-block}.breadcrumb>li+li:before{padding:0 5px;color:#ccc;content:"/\00a0"}.breadcrumb>.active{color:#999}.pagination{display:inline-block;padding-left:0;margin:20px 0;border-radius:4px}.pagination>li{display:inline}.pagination>li>a,.pagination>li>span{position:relative;float:left;padding:6px 12px;margin-left:-1px;line-height:1.428571429;text-decoration:none;background-color:#fff;border:1px solid #ddd}.pagination>li:first-child>a,.pagination>li:first-child>span{margin-left:0;border-bottom-left-radius:4px;border-top-left-radius:4px}.pagination>li:last-child>a,.pagination>li:last-child>span{border-top-right-radius:4px;border-bottom-right-radius:4px}.pagination>li>a:hover,.pagination>li>span:hover,.pagination>li>a:focus,.pagination>li>span:focus{background-color:#eee}.pagination>.active>a,.pagination>.active>span,.pagination>.active>a:hover,.pagination>.active>span:hover,.pagination>.active>a:focus,.pagination>.active>span:focus{z-index:2;color:#fff;cursor:default;background-color:#428bca;border-color:#428bca}.pagination>.disabled>span,.pagination>.disabled>a,.pagination>.disabled>a:hover,.pagination>.disabled>a:focus{color:#999;cursor:not-allowed;background-color:#fff;border-color:#ddd}.pagination-lg>li>a,.pagination-lg>li>span{padding:10px 16px;font-size:18px}.pagination-lg>li:first-child>a,.pagination-lg>li:first-child>span{border-bottom-left-radius:6px;border-top-left-radius:6px}.pagination-lg>li:last-child>a,.pagination-lg>li:last-child>span{border-top-right-radius:6px;border-bottom-right-radius:6px}.pagination-sm>li>a,.pagination-sm>li>span{padding:5px 10px;font-size:12px}.pagination-sm>li:first-child>a,.pagination-sm>li:first-child>span{border-bottom-left-radius:3px;border-top-left-radius:3px}.pagination-sm>li:last-child>a,.pagination-sm>li:last-child>span{border-top-right-radius:3px;border-bottom-right-radius:3px}.pager{padding-left:0;margin:20px 0;text-align:center;list-style:none}.pager:before,.pager:after{display:table;content:" "}.pager:after{clear:both}.pager:before,.pager:after{display:table;content:" "}.pager:after{clear:both}.pager li{display:inline}.pager li>a,.pager li>span{display:inline-block;padding:5px 14px;background-color:#fff;border:1px solid #ddd;border-radius:15px}.pager li>a:hover,.pager li>a:focus{text-decoration:none;background-color:#eee}.pager .next>a,.pager .next>span{float:right}.pager .previous>a,.pager .previous>span{float:left}.pager .disabled>a,.pager .disabled>a:hover,.pager .disabled>a:focus,.pager .disabled>span{color:#999;cursor:not-allowed;background-color:#fff}.label{display:inline;padding:.2em .6em .3em;font-size:75%;font-weight:bold;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:baseline;border-radius:.25em}.label[href]:hover,.label[href]:focus{color:#fff;text-decoration:none;cursor:pointer}.label:empty{display:none}.label-default{background-color:#999}.label-default[href]:hover,.label-default[href]:focus{background-color:#808080}.label-primary{background-color:#428bca}.label-primary[href]:hover,.label-primary[href]:focus{background-color:#3071a9}.label-success{background-color:#5cb85c}.label-success[href]:hover,.label-success[href]:focus{background-color:#449d44}.label-info{background-color:#5bc0de}.label-info[href]:hover,.label-info[href]:focus{background-color:#31b0d5}.label-warning{background-color:#f0ad4e}.label-warning[href]:hover,.label-warning[href]:focus{background-color:#ec971f}.label-danger{background-color:#d9534f}.label-danger[href]:hover,.label-danger[href]:focus{background-color:#c9302c}.badge{display:inline-block;min-width:10px;padding:3px 7px;font-size:12px;font-weight:bold;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:baseline;background-color:#999;border-radius:10px}.badge:empty{display:none}a.badge:hover,a.badge:focus{color:#fff;text-decoration:none;cursor:pointer}.btn .badge{position:relative;top:-1px}a.list-group-item.active>.badge,.nav-pills>.active>a>.badge{color:#428bca;background-color:#fff}.nav-pills>li>a>.badge{margin-left:3px}.jumbotron{padding:30px;margin-bottom:30px;font-size:21px;font-weight:200;line-height:2.1428571435;color:inherit;background-color:#eee}.jumbotron h1{line-height:1;color:inherit}.jumbotron p{line-height:1.4}.container .jumbotron{border-radius:6px}@media screen and (min-width:768px){.jumbotron{padding-top:48px;padding-bottom:48px}.container .jumbotron{padding-right:60px;padding-left:60px}.jumbotron h1{font-size:63px}}.thumbnail{display:inline-block;display:block;height:auto;max-width:100%;padding:4px;line-height:1.428571429;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:all .2s ease-in-out;transition:all .2s ease-in-out}.thumbnail>img{display:block;height:auto;max-width:100%}a.thumbnail:hover,a.thumbnail:focus{border-color:#428bca}.thumbnail>img{margin-right:auto;margin-left:auto}.thumbnail .caption{padding:9px;color:#333}.alert{padding:15px;margin-bottom:20px;border:1px solid transparent;border-radius:4px}.alert h4{margin-top:0;color:inherit}.alert .alert-link{font-weight:bold}.alert>p,.alert>ul{margin-bottom:0}.alert>p+p{margin-top:5px}.alert-dismissable{padding-right:35px}.alert-dismissable .close{position:relative;top:-2px;right:-21px;color:inherit}.alert-success{color:#468847;background-color:#dff0d8;border-color:#d6e9c6}.alert-success hr{border-top-color:#c9e2b3}.alert-success .alert-link{color:#356635}.alert-info{color:#3a87ad;background-color:#d9edf7;border-color:#bce8f1}.alert-info hr{border-top-color:#a6e1ec}.alert-info .alert-link{color:#2d6987}.alert-warning{color:#c09853;background-color:#fcf8e3;border-color:#fbeed5}.alert-warning hr{border-top-color:#f8e5be}.alert-warning .alert-link{color:#a47e3c}.alert-danger{color:#b94a48;background-color:#f2dede;border-color:#eed3d7}.alert-danger hr{border-top-color:#e6c1c7}.alert-danger .alert-link{color:#953b39}@-webkit-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-moz-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-o-keyframes progress-bar-stripes{from{background-position:0 0}to{background-position:40px 0}}@keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}.progress{height:20px;margin-bottom:20px;overflow:hidden;background-color:#f5f5f5;border-radius:4px;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1);box-shadow:inset 0 1px 2px rgba(0,0,0,0.1)}.progress-bar{float:left;width:0;height:100%;font-size:12px;color:#fff;text-align:center;background-color:#428bca;-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);-webkit-transition:width .6s ease;transition:width .6s ease}.progress-striped .progress-bar{background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-size:40px 40px}.progress.active .progress-bar{-webkit-animation:progress-bar-stripes 2s linear infinite;-moz-animation:progress-bar-stripes 2s linear infinite;-ms-animation:progress-bar-stripes 2s linear infinite;-o-animation:progress-bar-stripes 2s linear infinite;animation:progress-bar-stripes 2s linear infinite}.progress-bar-success{background-color:#5cb85c}.progress-striped .progress-bar-success{background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-bar-info{background-color:#5bc0de}.progress-striped .progress-bar-info{background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-bar-warning{background-color:#f0ad4e}.progress-striped .progress-bar-warning{background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-bar-danger{background-color:#d9534f}.progress-striped .progress-bar-danger{background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.media,.media-body{overflow:hidden;zoom:1}.media,.media .media{margin-top:15px}.media:first-child{margin-top:0}.media-object{display:block}.media-heading{margin:0 0 5px}.media>.pull-left{margin-right:10px}.media>.pull-right{margin-left:10px}.media-list{padding-left:0;list-style:none}.list-group{padding-left:0;margin-bottom:20px}.list-group-item{position:relative;display:block;padding:10px 15px;margin-bottom:-1px;background-color:#fff;border:1px solid #ddd}.list-group-item:first-child{border-top-right-radius:4px;border-top-left-radius:4px}.list-group-item:last-child{margin-bottom:0;border-bottom-right-radius:4px;border-bottom-left-radius:4px}.list-group-item>.badge{float:right}.list-group-item>.badge+.badge{margin-right:5px}a.list-group-item{color:#555}a.list-group-item .list-group-item-heading{color:#333}a.list-group-item:hover,a.list-group-item:focus{text-decoration:none;background-color:#f5f5f5}.list-group-item.active,.list-group-item.active:hover,.list-group-item.active:focus{z-index:2;color:#fff;background-color:#428bca;border-color:#428bca}.list-group-item.active .list-group-item-heading,.list-group-item.active:hover .list-group-item-heading,.list-group-item.active:focus .list-group-item-heading{color:inherit}.list-group-item.active .list-group-item-text,.list-group-item.active:hover .list-group-item-text,.list-group-item.active:focus .list-group-item-text{color:#e1edf7}.list-group-item-heading{margin-top:0;margin-bottom:5px}.list-group-item-text{margin-bottom:0;line-height:1.3}.panel{margin-bottom:20px;background-color:#fff;border:1px solid transparent;border-radius:4px;-webkit-box-shadow:0 1px 1px rgba(0,0,0,0.05);box-shadow:0 1px 1px rgba(0,0,0,0.05)}.panel-body{padding:15px}.panel-body:before,.panel-body:after{display:table;content:" "}.panel-body:after{clear:both}.panel-body:before,.panel-body:after{display:table;content:" "}.panel-body:after{clear:both}.panel>.list-group{margin-bottom:0}.panel>.list-group .list-group-item{border-width:1px 0}.panel>.list-group .list-group-item:first-child{border-top-right-radius:0;border-top-left-radius:0}.panel>.list-group .list-group-item:last-child{border-bottom:0}.panel-heading+.list-group .list-group-item:first-child{border-top-width:0}.panel>.table{margin-bottom:0}.panel>.panel-body+.table{border-top:1px solid #ddd}.panel-heading{padding:10px 15px;border-bottom:1px solid transparent;border-top-right-radius:3px;border-top-left-radius:3px}.panel-title{margin-top:0;margin-bottom:0;font-size:16px}.panel-title>a{color:inherit}.panel-footer{padding:10px 15px;background-color:#f5f5f5;border-top:1px solid #ddd;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel-group .panel{margin-bottom:0;overflow:hidden;border-radius:4px}.panel-group .panel+.panel{margin-top:5px}.panel-group .panel-heading{border-bottom:0}.panel-group .panel-heading+.panel-collapse .panel-body{border-top:1px solid #ddd}.panel-group .panel-footer{border-top:0}.panel-group .panel-footer+.panel-collapse .panel-body{border-bottom:1px solid #ddd}.panel-default{border-color:#ddd}.panel-default>.panel-heading{color:#333;background-color:#f5f5f5;border-color:#ddd}.panel-default>.panel-heading+.panel-collapse .panel-body{border-top-color:#ddd}.panel-default>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#ddd}.panel-primary{border-color:#428bca}.panel-primary>.panel-heading{color:#fff;background-color:#428bca;border-color:#428bca}.panel-primary>.panel-heading+.panel-collapse .panel-body{border-top-color:#428bca}.panel-primary>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#428bca}.panel-success{border-color:#d6e9c6}.panel-success>.panel-heading{color:#468847;background-color:#dff0d8;border-color:#d6e9c6}.panel-success>.panel-heading+.panel-collapse .panel-body{border-top-color:#d6e9c6}.panel-success>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#d6e9c6}.panel-warning{border-color:#fbeed5}.panel-warning>.panel-heading{color:#c09853;background-color:#fcf8e3;border-color:#fbeed5}.panel-warning>.panel-heading+.panel-collapse .panel-body{border-top-color:#fbeed5}.panel-warning>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#fbeed5}.panel-danger{border-color:#eed3d7}.panel-danger>.panel-heading{color:#b94a48;background-color:#f2dede;border-color:#eed3d7}.panel-danger>.panel-heading+.panel-collapse .panel-body{border-top-color:#eed3d7}.panel-danger>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#eed3d7}.panel-info{border-color:#bce8f1}.panel-info>.panel-heading{color:#3a87ad;background-color:#d9edf7;border-color:#bce8f1}.panel-info>.panel-heading+.panel-collapse .panel-body{border-top-color:#bce8f1}.panel-info>.panel-footer+.panel-collapse .panel-body{border-bottom-color:#bce8f1}.well{min-height:20px;padding:19px;margin-bottom:20px;background-color:#f5f5f5;border:1px solid #e3e3e3;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.05);box-shadow:inset 0 1px 1px rgba(0,0,0,0.05)}.well blockquote{border-color:#ddd;border-color:rgba(0,0,0,0.15)}.well-lg{padding:24px;border-radius:6px}.well-sm{padding:9px;border-radius:3px}.close{float:right;font-size:21px;font-weight:bold;line-height:1;color:#000;text-shadow:0 1px 0 #fff;opacity:.2;filter:alpha(opacity=20)}.close:hover,.close:focus{color:#000;text-decoration:none;cursor:pointer;opacity:.5;filter:alpha(opacity=50)}button.close{padding:0;cursor:pointer;background:transparent;border:0;-webkit-appearance:none}.modal-open{overflow:hidden}body.modal-open,.modal-open .navbar-fixed-top,.modal-open .navbar-fixed-bottom{margin-right:15px}.modal{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;display:none;overflow:auto;overflow-y:scroll}.modal.fade .modal-dialog{-webkit-transform:translate(0,-25%);-ms-transform:translate(0,-25%);transform:translate(0,-25%);-webkit-transition:-webkit-transform .3s ease-out;-moz-transition:-moz-transform .3s ease-out;-o-transition:-o-transform .3s ease-out;transition:transform .3s ease-out}.modal.in .modal-dialog{-webkit-transform:translate(0,0);-ms-transform:translate(0,0);transform:translate(0,0)}.modal-dialog{z-index:1050;width:auto;padding:10px;margin-right:auto;margin-left:auto}.modal-content{position:relative;background-color:#fff;border:1px solid #999;border:1px solid rgba(0,0,0,0.2);border-radius:6px;outline:0;-webkit-box-shadow:0 3px 9px rgba(0,0,0,0.5);box-shadow:0 3px 9px rgba(0,0,0,0.5);background-clip:padding-box}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1030;background-color:#000}.modal-backdrop.fade{opacity:0;filter:alpha(opacity=0)}.modal-backdrop.in{opacity:.5;filter:alpha(opacity=50)}.modal-header{min-height:16.428571429px;padding:15px;border-bottom:1px solid #e5e5e5}.modal-header .close{margin-top:-2px}.modal-title{margin:0;line-height:1.428571429}.modal-body{position:relative;padding:20px}.modal-footer{padding:19px 20px 20px;margin-top:15px;text-align:right;border-top:1px solid #e5e5e5}.modal-footer:before,.modal-footer:after{display:table;content:" "}.modal-footer:after{clear:both}.modal-footer:before,.modal-footer:after{display:table;content:" "}.modal-footer:after{clear:both}.modal-footer .btn+.btn{margin-bottom:0;margin-left:5px}.modal-footer .btn-group .btn+.btn{margin-left:-1px}.modal-footer .btn-block+.btn-block{margin-left:0}@media screen and (min-width:768px){.modal-dialog{right:auto;left:50%;width:600px;padding-top:30px;padding-bottom:30px}.modal-content{-webkit-box-shadow:0 5px 15px rgba(0,0,0,0.5);box-shadow:0 5px 15px rgba(0,0,0,0.5)}}.tooltip{position:absolute;z-index:1030;display:block;font-size:12px;line-height:1.4;opacity:0;filter:alpha(opacity=0);visibility:visible}.tooltip.in{opacity:.9;filter:alpha(opacity=90)}.tooltip.top{padding:5px 0;margin-top:-3px}.tooltip.right{padding:0 5px;margin-left:3px}.tooltip.bottom{padding:5px 0;margin-top:3px}.tooltip.left{padding:0 5px;margin-left:-3px}.tooltip-inner{max-width:200px;padding:3px 8px;color:#fff;text-align:center;text-decoration:none;background-color:#000;border-radius:4px}.tooltip-arrow{position:absolute;width:0;height:0;border-color:transparent;border-style:solid}.tooltip.top .tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-top-color:#000;border-width:5px 5px 0}.tooltip.top-left .tooltip-arrow{bottom:0;left:5px;border-top-color:#000;border-width:5px 5px 0}.tooltip.top-right .tooltip-arrow{right:5px;bottom:0;border-top-color:#000;border-width:5px 5px 0}.tooltip.right .tooltip-arrow{top:50%;left:0;margin-top:-5px;border-right-color:#000;border-width:5px 5px 5px 0}.tooltip.left .tooltip-arrow{top:50%;right:0;margin-top:-5px;border-left-color:#000;border-width:5px 0 5px 5px}.tooltip.bottom .tooltip-arrow{top:0;left:50%;margin-left:-5px;border-bottom-color:#000;border-width:0 5px 5px}.tooltip.bottom-left .tooltip-arrow{top:0;left:5px;border-bottom-color:#000;border-width:0 5px 5px}.tooltip.bottom-right .tooltip-arrow{top:0;right:5px;border-bottom-color:#000;border-width:0 5px 5px}.popover{position:absolute;top:0;left:0;z-index:1010;display:none;max-width:276px;padding:1px;text-align:left;white-space:normal;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.2);border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,0.2);box-shadow:0 5px 10px rgba(0,0,0,0.2);background-clip:padding-box}.popover.top{margin-top:-10px}.popover.right{margin-left:10px}.popover.bottom{margin-top:10px}.popover.left{margin-left:-10px}.popover-title{padding:8px 14px;margin:0;font-size:14px;font-weight:normal;line-height:18px;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;border-radius:5px 5px 0 0}.popover-content{padding:9px 14px}.popover .arrow,.popover .arrow:after{position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}.popover .arrow{border-width:11px}.popover .arrow:after{border-width:10px;content:""}.popover.top .arrow{bottom:-11px;left:50%;margin-left:-11px;border-top-color:#999;border-top-color:rgba(0,0,0,0.25);border-bottom-width:0}.popover.top .arrow:after{bottom:1px;margin-left:-10px;border-top-color:#fff;border-bottom-width:0;content:" "}.popover.right .arrow{top:50%;left:-11px;margin-top:-11px;border-right-color:#999;border-right-color:rgba(0,0,0,0.25);border-left-width:0}.popover.right .arrow:after{bottom:-10px;left:1px;border-right-color:#fff;border-left-width:0;content:" "}.popover.bottom .arrow{top:-11px;left:50%;margin-left:-11px;border-bottom-color:#999;border-bottom-color:rgba(0,0,0,0.25);border-top-width:0}.popover.bottom .arrow:after{top:1px;margin-left:-10px;border-bottom-color:#fff;border-top-width:0;content:" "}.popover.left .arrow{top:50%;right:-11px;margin-top:-11px;border-left-color:#999;border-left-color:rgba(0,0,0,0.25);border-right-width:0}.popover.left .arrow:after{right:1px;bottom:-10px;border-left-color:#fff;border-right-width:0;content:" "}.carousel{position:relative}.carousel-inner{position:relative;width:100%;overflow:hidden}.carousel-inner>.item{position:relative;display:none;-webkit-transition:.6s ease-in-out left;transition:.6s ease-in-out left}.carousel-inner>.item>img,.carousel-inner>.item>a>img{display:block;height:auto;max-width:100%;line-height:1}.carousel-inner>.active,.carousel-inner>.next,.carousel-inner>.prev{display:block}.carousel-inner>.active{left:0}.carousel-inner>.next,.carousel-inner>.prev{position:absolute;top:0;width:100%}.carousel-inner>.next{left:100%}.carousel-inner>.prev{left:-100%}.carousel-inner>.next.left,.carousel-inner>.prev.right{left:0}.carousel-inner>.active.left{left:-100%}.carousel-inner>.active.right{left:100%}.carousel-control{position:absolute;top:0;bottom:0;left:0;width:15%;font-size:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,0.6);opacity:.5;filter:alpha(opacity=50)}.carousel-control.left{background-image:-webkit-gradient(linear,0 top,100% top,from(rgba(0,0,0,0.5)),to(rgba(0,0,0,0.0001)));background-image:-webkit-linear-gradient(left,color-stop(rgba(0,0,0,0.5) 0),color-stop(rgba(0,0,0,0.0001) 100%));background-image:-moz-linear-gradient(left,rgba(0,0,0,0.5) 0,rgba(0,0,0,0.0001) 100%);background-image:linear-gradient(to right,rgba(0,0,0,0.5) 0,rgba(0,0,0,0.0001) 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000',endColorstr='#00000000',GradientType=1)}.carousel-control.right{right:0;left:auto;background-image:-webkit-gradient(linear,0 top,100% top,from(rgba(0,0,0,0.0001)),to(rgba(0,0,0,0.5)));background-image:-webkit-linear-gradient(left,color-stop(rgba(0,0,0,0.0001) 0),color-stop(rgba(0,0,0,0.5) 100%));background-image:-moz-linear-gradient(left,rgba(0,0,0,0.0001) 0,rgba(0,0,0,0.5) 100%);background-image:linear-gradient(to right,rgba(0,0,0,0.0001) 0,rgba(0,0,0,0.5) 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000',endColorstr='#80000000',GradientType=1)}.carousel-control:hover,.carousel-control:focus{color:#fff;text-decoration:none;opacity:.9;filter:alpha(opacity=90)}.carousel-control .icon-prev,.carousel-control .icon-next,.carousel-control .glyphicon-chevron-left,.carousel-control .glyphicon-chevron-right{position:absolute;top:50%;left:50%;z-index:5;display:inline-block}.carousel-control .icon-prev,.carousel-control .icon-next{width:20px;height:20px;margin-top:-10px;margin-left:-10px;font-family:serif}.carousel-control .icon-prev:before{content:'\2039'}.carousel-control .icon-next:before{content:'\203a'}.carousel-indicators{position:absolute;bottom:10px;left:50%;z-index:15;width:60%;padding-left:0;margin-left:-30%;text-align:center;list-style:none}.carousel-indicators li{display:inline-block;width:10px;height:10px;margin:1px;text-indent:-999px;cursor:pointer;border:1px solid #fff;border-radius:10px}.carousel-indicators .active{width:12px;height:12px;margin:0;background-color:#fff}.carousel-caption{position:absolute;right:15%;bottom:20px;left:15%;z-index:10;padding-top:20px;padding-bottom:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,0.6)}.carousel-caption .btn{text-shadow:none}@media screen and (min-width:768px){.carousel-control .icon-prev,.carousel-control .icon-next{width:30px;height:30px;margin-top:-15px;margin-left:-15px;font-size:30px}.carousel-caption{right:20%;left:20%;padding-bottom:30px}.carousel-indicators{bottom:20px}}.clearfix:before,.clearfix:after{display:table;content:" "}.clearfix:after{clear:both}.pull-right{float:right!important}.pull-left{float:left!important}.hide{display:none!important}.show{display:block!important}.invisible{visibility:hidden}.text-hide{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.affix{position:fixed}@-ms-viewport{width:device-width}@media screen and (max-width:400px){@-ms-viewport{width:320px}}.hidden{display:none!important;visibility:hidden!important}.visible-xs{display:none!important}tr.visible-xs{display:none!important}th.visible-xs,td.visible-xs{display:none!important}@media(max-width:767px){.visible-xs{display:block!important}tr.visible-xs{display:table-row!important}th.visible-xs,td.visible-xs{display:table-cell!important}}@media(min-width:768px) and (max-width:991px){.visible-xs.visible-sm{display:block!important}tr.visible-xs.visible-sm{display:table-row!important}th.visible-xs.visible-sm,td.visible-xs.visible-sm{display:table-cell!important}}@media(min-width:992px) and (max-width:1199px){.visible-xs.visible-md{display:block!important}tr.visible-xs.visible-md{display:table-row!important}th.visible-xs.visible-md,td.visible-xs.visible-md{display:table-cell!important}}@media(min-width:1200px){.visible-xs.visible-lg{display:block!important}tr.visible-xs.visible-lg{display:table-row!important}th.visible-xs.visible-lg,td.visible-xs.visible-lg{display:table-cell!important}}.visible-sm{display:none!important}tr.visible-sm{display:none!important}th.visible-sm,td.visible-sm{display:none!important}@media(max-width:767px){.visible-sm.visible-xs{display:block!important}tr.visible-sm.visible-xs{display:table-row!important}th.visible-sm.visible-xs,td.visible-sm.visible-xs{display:table-cell!important}}@media(min-width:768px) and (max-width:991px){.visible-sm{display:block!important}tr.visible-sm{display:table-row!important}th.visible-sm,td.visible-sm{display:table-cell!important}}@media(min-width:992px) and (max-width:1199px){.visible-sm.visible-md{display:block!important}tr.visible-sm.visible-md{display:table-row!important}th.visible-sm.visible-md,td.visible-sm.visible-md{display:table-cell!important}}@media(min-width:1200px){.visible-sm.visible-lg{display:block!important}tr.visible-sm.visible-lg{display:table-row!important}th.visible-sm.visible-lg,td.visible-sm.visible-lg{display:table-cell!important}}.visible-md{display:none!important}tr.visible-md{display:none!important}th.visible-md,td.visible-md{display:none!important}@media(max-width:767px){.visible-md.visible-xs{display:block!important}tr.visible-md.visible-xs{display:table-row!important}th.visible-md.visible-xs,td.visible-md.visible-xs{display:table-cell!important}}@media(min-width:768px) and (max-width:991px){.visible-md.visible-sm{display:block!important}tr.visible-md.visible-sm{display:table-row!important}th.visible-md.visible-sm,td.visible-md.visible-sm{display:table-cell!important}}@media(min-width:992px) and (max-width:1199px){.visible-md{display:block!important}tr.visible-md{display:table-row!important}th.visible-md,td.visible-md{display:table-cell!important}}@media(min-width:1200px){.visible-md.visible-lg{display:block!important}tr.visible-md.visible-lg{display:table-row!important}th.visible-md.visible-lg,td.visible-md.visible-lg{display:table-cell!important}}.visible-lg{display:none!important}tr.visible-lg{display:none!important}th.visible-lg,td.visible-lg{display:none!important}@media(max-width:767px){.visible-lg.visible-xs{display:block!important}tr.visible-lg.visible-xs{display:table-row!important}th.visible-lg.visible-xs,td.visible-lg.visible-xs{display:table-cell!important}}@media(min-width:768px) and (max-width:991px){.visible-lg.visible-sm{display:block!important}tr.visible-lg.visible-sm{display:table-row!important}th.visible-lg.visible-sm,td.visible-lg.visible-sm{display:table-cell!important}}@media(min-width:992px) and (max-width:1199px){.visible-lg.visible-md{display:block!important}tr.visible-lg.visible-md{display:table-row!important}th.visible-lg.visible-md,td.visible-lg.visible-md{display:table-cell!important}}@media(min-width:1200px){.visible-lg{display:block!important}tr.visible-lg{display:table-row!important}th.visible-lg,td.visible-lg{display:table-cell!important}}.hidden-xs{display:block!important}tr.hidden-xs{display:table-row!important}th.hidden-xs,td.hidden-xs{display:table-cell!important}@media(max-width:767px){.hidden-xs{display:none!important}tr.hidden-xs{display:none!important}th.hidden-xs,td.hidden-xs{display:none!important}}@media(min-width:768px) and (max-width:991px){.hidden-xs.hidden-sm{display:none!important}tr.hidden-xs.hidden-sm{display:none!important}th.hidden-xs.hidden-sm,td.hidden-xs.hidden-sm{display:none!important}}@media(min-width:992px) and (max-width:1199px){.hidden-xs.hidden-md{display:none!important}tr.hidden-xs.hidden-md{display:none!important}th.hidden-xs.hidden-md,td.hidden-xs.hidden-md{display:none!important}}@media(min-width:1200px){.hidden-xs.hidden-lg{display:none!important}tr.hidden-xs.hidden-lg{display:none!important}th.hidden-xs.hidden-lg,td.hidden-xs.hidden-lg{display:none!important}}.hidden-sm{display:block!important}tr.hidden-sm{display:table-row!important}th.hidden-sm,td.hidden-sm{display:table-cell!important}@media(max-width:767px){.hidden-sm.hidden-xs{display:none!important}tr.hidden-sm.hidden-xs{display:none!important}th.hidden-sm.hidden-xs,td.hidden-sm.hidden-xs{display:none!important}}@media(min-width:768px) and (max-width:991px){.hidden-sm{display:none!important}tr.hidden-sm{display:none!important}th.hidden-sm,td.hidden-sm{display:none!important}}@media(min-width:992px) and (max-width:1199px){.hidden-sm.hidden-md{display:none!important}tr.hidden-sm.hidden-md{display:none!important}th.hidden-sm.hidden-md,td.hidden-sm.hidden-md{display:none!important}}@media(min-width:1200px){.hidden-sm.hidden-lg{display:none!important}tr.hidden-sm.hidden-lg{display:none!important}th.hidden-sm.hidden-lg,td.hidden-sm.hidden-lg{display:none!important}}.hidden-md{display:block!important}tr.hidden-md{display:table-row!important}th.hidden-md,td.hidden-md{display:table-cell!important}@media(max-width:767px){.hidden-md.hidden-xs{display:none!important}tr.hidden-md.hidden-xs{display:none!important}th.hidden-md.hidden-xs,td.hidden-md.hidden-xs{display:none!important}}@media(min-width:768px) and (max-width:991px){.hidden-md.hidden-sm{display:none!important}tr.hidden-md.hidden-sm{display:none!important}th.hidden-md.hidden-sm,td.hidden-md.hidden-sm{display:none!important}}@media(min-width:992px) and (max-width:1199px){.hidden-md{display:none!important}tr.hidden-md{display:none!important}th.hidden-md,td.hidden-md{display:none!important}}@media(min-width:1200px){.hidden-md.hidden-lg{display:none!important}tr.hidden-md.hidden-lg{display:none!important}th.hidden-md.hidden-lg,td.hidden-md.hidden-lg{display:none!important}}.hidden-lg{display:block!important}tr.hidden-lg{display:table-row!important}th.hidden-lg,td.hidden-lg{display:table-cell!important}@media(max-width:767px){.hidden-lg.hidden-xs{display:none!important}tr.hidden-lg.hidden-xs{display:none!important}th.hidden-lg.hidden-xs,td.hidden-lg.hidden-xs{display:none!important}}@media(min-width:768px) and (max-width:991px){.hidden-lg.hidden-sm{display:none!important}tr.hidden-lg.hidden-sm{display:none!important}th.hidden-lg.hidden-sm,td.hidden-lg.hidden-sm{display:none!important}}@media(min-width:992px) and (max-width:1199px){.hidden-lg.hidden-md{display:none!important}tr.hidden-lg.hidden-md{display:none!important}th.hidden-lg.hidden-md,td.hidden-lg.hidden-md{display:none!important}}@media(min-width:1200px){.hidden-lg{display:none!important}tr.hidden-lg{display:none!important}th.hidden-lg,td.hidden-lg{display:none!important}}.visible-print{display:none!important}tr.visible-print{display:none!important}th.visible-print,td.visible-print{display:none!important}@media print{.visible-print{display:block!important}tr.visible-print{display:table-row!important}th.visible-print,td.visible-print{display:table-cell!important}.hidden-print{display:none!important}tr.hidden-print{display:none!important}th.hidden-print,td.hidden-print{display:none!important}}
\ No newline at end of file
diff --git a/third-party/bootstrap-3.0.0/fonts/glyphicons-halflings-regular.eot b/third-party/bootstrap-3.0.0/fonts/glyphicons-halflings-regular.eot
new file mode 100644 (file)
index 0000000..87eaa43
Binary files /dev/null and b/third-party/bootstrap-3.0.0/fonts/glyphicons-halflings-regular.eot differ
diff --git a/third-party/bootstrap-3.0.0/fonts/glyphicons-halflings-regular.svg b/third-party/bootstrap-3.0.0/fonts/glyphicons-halflings-regular.svg
new file mode 100644 (file)
index 0000000..5fee068
--- /dev/null
@@ -0,0 +1,228 @@
+<?xml version="1.0" standalone="no"?>
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" >
+<svg xmlns="http://www.w3.org/2000/svg">
+<metadata></metadata>
+<defs>
+<font id="glyphicons_halflingsregular" horiz-adv-x="1200" >
+<font-face units-per-em="1200" ascent="960" descent="-240" />
+<missing-glyph horiz-adv-x="500" />
+<glyph />
+<glyph />
+<glyph unicode=" " />
+<glyph unicode="*" d="M1100 500h-259l183 -183l-141 -141l-183 183v-259h-200v259l-183 -183l-141 141l183 183h-259v200h259l-183 183l141 141l183 -183v259h200v-259l183 183l141 -141l-183 -183h259v-200z" />
+<glyph unicode="+" d="M1100 400h-400v-400h-300v400h-400v300h400v400h300v-400h400v-300z" />
+<glyph unicode="&#xa0;" />
+<glyph unicode="&#x2000;" horiz-adv-x="652" />
+<glyph unicode="&#x2001;" horiz-adv-x="1304" />
+<glyph unicode="&#x2002;" horiz-adv-x="652" />
+<glyph unicode="&#x2003;" horiz-adv-x="1304" />
+<glyph unicode="&#x2004;" horiz-adv-x="434" />
+<glyph unicode="&#x2005;" horiz-adv-x="326" />
+<glyph unicode="&#x2006;" horiz-adv-x="217" />
+<glyph unicode="&#x2007;" horiz-adv-x="217" />
+<glyph unicode="&#x2008;" horiz-adv-x="163" />
+<glyph unicode="&#x2009;" horiz-adv-x="260" />
+<glyph unicode="&#x200a;" horiz-adv-x="72" />
+<glyph unicode="&#x202f;" horiz-adv-x="260" />
+<glyph unicode="&#x205f;" horiz-adv-x="326" />
+<glyph unicode="&#x20ac;" d="M800 500h-300q9 -74 33 -132t52.5 -91t62 -54.5t59 -29t46.5 -7.5q29 0 66 13t75 37t63.5 67.5t25.5 96.5h174q-31 -172 -128 -278q-107 -117 -274 -117q-205 0 -324 158q-36 46 -69 131.5t-45 205.5h-217l100 100h113q0 47 5 100h-218l100 100h135q37 167 112 257 q117 141 297 141q242 0 354 -189q60 -103 66 -209h-181q0 55 -25.5 99t-63.5 68t-75 36.5t-67 12.5q-24 0 -52.5 -10t-62.5 -32t-65.5 -67t-50.5 -107h379l-100 -100h-300q-6 -46 -6 -100h406z" />
+<glyph unicode="&#x2212;" d="M1100 700h-900v-300h900v300z" />
+<glyph unicode="&#x2601;" d="M178 300h750q120 0 205 86t85 208q0 120 -85 206.5t-205 86.5q-46 0 -90 -14q-44 97 -134.5 156.5t-200.5 59.5q-152 0 -260 -107.5t-108 -260.5q0 -25 2 -37q-66 -14 -108.5 -67.5t-42.5 -122.5q0 -80 56.5 -137t135.5 -57z" />
+<glyph unicode="&#x2709;" d="M1200 1100h-1200l600 -603zM300 600l-300 -300v600zM1200 900v-600l-300 300zM800 500l400 -400h-1200l400 400l200 -200z" />
+<glyph unicode="&#x270f;" d="M1101 889l99 92q13 13 13 32.5t-13 33.5l-153 153q-15 13 -33 13t-33 -13l-94 -97zM401 189l614 614l-214 214l-614 -614zM-13 -13l333 112l-223 223z" />
+<glyph unicode="&#xe000;" horiz-adv-x="500" d="M0 0z" />
+<glyph unicode="&#xe001;" d="M700 100h300v-100h-800v100h300v550l-500 550h1200l-500 -550v-550z" />
+<glyph unicode="&#xe002;" d="M1000 934v-521q-64 16 -138 -7q-79 -26 -122.5 -83t-25.5 -111q17 -55 85.5 -75.5t147.5 4.5q70 23 111.5 63.5t41.5 95.5v881q0 10 -7 15.5t-17 2.5l-752 -193q-10 -3 -17 -12.5t-7 -19.5v-689q-64 17 -138 -7q-79 -25 -122.5 -82t-25.5 -112t86 -75.5t147 5.5 q65 21 109 69t44 90v606z" />
+<glyph unicode="&#xe003;" d="M913 432l300 -300q7 -8 7 -18t-7 -18l-109 -109q-8 -7 -18 -7t-18 7l-300 300q-119 -78 -261 -78q-200 0 -342 142t-142 342t142 342t342 142t342 -142t142 -342q0 -142 -78 -261zM176 693q0 -136 97 -233t234 -97t233.5 96.5t96.5 233.5t-96.5 233.5t-233.5 96.5 t-234 -97t-97 -233z" />
+<glyph unicode="&#xe005;" d="M649 949q48 69 109.5 105t121.5 38t118.5 -20.5t102.5 -64t71 -100.5t27 -123q0 -57 -33.5 -117.5t-94 -124.5t-126.5 -127.5t-150 -152.5t-146 -174q-62 85 -145.5 174t-149.5 152.5t-126.5 127.5t-94 124.5t-33.5 117.5q0 64 28 123t73 100.5t104.5 64t119 20.5 t120 -38.5t104.5 -104.5z" />
+<glyph unicode="&#xe006;" d="M791 522l145 -449l-384 275l-382 -275l146 447l-388 280h479l146 400h2l146 -400h472zM168 71l2 1z" />
+<glyph unicode="&#xe007;" d="M791 522l145 -449l-384 275l-382 -275l146 447l-388 280h479l146 400h2l146 -400h472zM747 331l-74 229l193 140h-235l-77 211l-78 -211h-239l196 -142l-73 -226l192 140zM168 71l2 1z" />
+<glyph unicode="&#xe008;" d="M1200 143v-143h-1200v143l400 257v100q-37 0 -68.5 74.5t-31.5 125.5v200q0 124 88 212t212 88t212 -88t88 -212v-200q0 -51 -31.5 -125.5t-68.5 -74.5v-100z" />
+<glyph unicode="&#xe009;" d="M1200 1100v-1100h-1200v1100h1200zM200 1000h-100v-100h100v100zM900 1000h-600v-400h600v400zM1100 1000h-100v-100h100v100zM200 800h-100v-100h100v100zM1100 800h-100v-100h100v100zM200 600h-100v-100h100v100zM1100 600h-100v-100h100v100zM900 500h-600v-400h600 v400zM200 400h-100v-100h100v100zM1100 400h-100v-100h100v100zM200 200h-100v-100h100v100zM1100 200h-100v-100h100v100z" />
+<glyph unicode="&#xe010;" d="M500 1050v-400q0 -21 -14.5 -35.5t-35.5 -14.5h-400q-21 0 -35.5 14.5t-14.5 35.5v400q0 21 14.5 35.5t35.5 14.5h400q21 0 35.5 -14.5t14.5 -35.5zM1100 1050v-400q0 -21 -14.5 -35.5t-35.5 -14.5h-400q-21 0 -35.5 14.5t-14.5 35.5v400q0 21 14.5 35.5t35.5 14.5h400 q21 0 35.5 -14.5t14.5 -35.5zM500 450v-400q0 -21 -14.5 -35.5t-35.5 -14.5h-400q-21 0 -35.5 14.5t-14.5 35.5v400q0 21 14.5 35.5t35.5 14.5h400q21 0 35.5 -14.5t14.5 -35.5zM1100 450v-400q0 -21 -14.5 -35.5t-35.5 -14.5h-400q-21 0 -35.5 14.5t-14.5 35.5v400 q0 21 14.5 35.5t35.5 14.5h400q21 0 35.5 -14.5t14.5 -35.5z" />
+<glyph unicode="&#xe011;" d="M300 1050v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5zM700 1050v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5v200q0 21 14.5 35.5t35.5 14.5h200 q21 0 35.5 -14.5t14.5 -35.5zM1100 1050v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5zM300 650v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5v200 q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5zM700 650v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5zM1100 650v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200 q-21 0 -35.5 14.5t-14.5 35.5v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5zM300 250v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5zM700 250v-200 q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5zM1100 250v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5 t14.5 -35.5z" />
+<glyph unicode="&#xe012;" d="M300 1050v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5zM1200 1050v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-700q-21 0 -35.5 14.5t-14.5 35.5v200q0 21 14.5 35.5t35.5 14.5h700 q21 0 35.5 -14.5t14.5 -35.5zM300 450v200q0 21 -14.5 35.5t-35.5 14.5h-200q-21 0 -35.5 -14.5t-14.5 -35.5v-200q0 -21 14.5 -35.5t35.5 -14.5h200q21 0 35.5 14.5t14.5 35.5zM1200 650v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-700q-21 0 -35.5 14.5t-14.5 35.5v200 q0 21 14.5 35.5t35.5 14.5h700q21 0 35.5 -14.5t14.5 -35.5zM300 250v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5zM1200 250v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-700 q-21 0 -35.5 14.5t-14.5 35.5v200q0 21 14.5 35.5t35.5 14.5h700q21 0 35.5 -14.5t14.5 -35.5z" />
+<glyph unicode="&#xe013;" d="M448 34l818 820l-212 212l-607 -607l-206 207l-212 -212z" />
+<glyph unicode="&#xe014;" d="M882 106l-282 282l-282 -282l-212 212l282 282l-282 282l212 212l282 -282l282 282l212 -212l-282 -282l282 -282z" />
+<glyph unicode="&#xe015;" d="M913 432l300 -300q7 -8 7 -18t-7 -18l-109 -109q-8 -7 -18 -7t-18 7l-300 300q-119 -78 -261 -78q-200 0 -342 142t-142 342t142 342t342 142t342 -142t142 -342q0 -142 -78 -261zM507 363q137 0 233.5 96.5t96.5 233.5t-96.5 233.5t-233.5 96.5t-234 -97t-97 -233 t97 -233t234 -97zM600 800h100v-200h-100v-100h-200v100h-100v200h100v100h200v-100z" />
+<glyph unicode="&#xe016;" d="M913 432l300 -299q7 -7 7 -18t-7 -18l-109 -109q-8 -8 -18 -8t-18 8l-300 299q-120 -77 -261 -77q-200 0 -342 142t-142 342t142 342t342 142t342 -142t142 -342q0 -141 -78 -262zM176 694q0 -136 97 -233t234 -97t233.5 97t96.5 233t-96.5 233t-233.5 97t-234 -97 t-97 -233zM300 801v-200h400v200h-400z" />
+<glyph unicode="&#xe017;" d="M700 750v400q0 21 -14.5 35.5t-35.5 14.5h-100q-21 0 -35.5 -14.5t-14.5 -35.5v-400q0 -21 14.5 -35.5t35.5 -14.5h100q21 0 35.5 14.5t14.5 35.5zM800 975v166q167 -62 272 -210t105 -331q0 -118 -45.5 -224.5t-123 -184t-184 -123t-224.5 -45.5t-224.5 45.5t-184 123 t-123 184t-45.5 224.5q0 183 105 331t272 210v-166q-103 -55 -165 -155t-62 -220q0 -177 125 -302t302 -125t302 125t125 302q0 120 -62 220t-165 155z" />
+<glyph unicode="&#xe018;" d="M1200 1h-200v1200h200v-1200zM900 1h-200v800h200v-800zM600 1h-200v500h200v-500zM300 301h-200v-300h200v300z" />
+<glyph unicode="&#xe019;" d="M488 183l38 -151q40 -5 74 -5q27 0 74 5l38 151l6 2q46 13 93 39l5 3l134 -81q56 44 104 105l-80 134l3 5q24 44 39 93l1 6l152 38q5 40 5 74q0 28 -5 73l-152 38l-1 6q-16 51 -39 93l-3 5l80 134q-44 58 -104 105l-134 -81l-5 3q-45 25 -93 39l-6 1l-38 152q-40 5 -74 5 q-27 0 -74 -5l-38 -152l-5 -1q-50 -14 -94 -39l-5 -3l-133 81q-59 -47 -105 -105l80 -134l-3 -5q-25 -47 -38 -93l-2 -6l-151 -38q-6 -48 -6 -73q0 -33 6 -74l151 -38l2 -6q14 -49 38 -93l3 -5l-80 -134q45 -59 105 -105l133 81l5 -3q45 -26 94 -39zM600 815q89 0 152 -63 t63 -151q0 -89 -63 -152t-152 -63t-152 63t-63 152q0 88 63 151t152 63z" />
+<glyph unicode="&#xe020;" d="M900 1100h275q10 0 17.5 -7.5t7.5 -17.5v-50q0 -11 -7 -18t-18 -7h-1050q-11 0 -18 7t-7 18v50q0 10 7.5 17.5t17.5 7.5h275v100q0 41 29.5 70.5t70.5 29.5h300q41 0 70.5 -29.5t29.5 -70.5v-100zM800 1100v100h-300v-100h300zM200 900h900v-800q0 -41 -29.5 -71 t-70.5 -30h-700q-41 0 -70.5 30t-29.5 71v800zM300 100h100v700h-100v-700zM500 100h100v700h-100v-700zM700 100h100v700h-100v-700zM900 100h100v700h-100v-700z" />
+<glyph unicode="&#xe021;" d="M1301 601h-200v-600h-300v400h-300v-400h-300v600h-200l656 644z" />
+<glyph unicode="&#xe022;" d="M600 700h400v-675q0 -11 -7 -18t-18 -7h-850q-11 0 -18 7t-7 18v1150q0 11 7 18t18 7h475v-500zM1000 800h-300v300z" />
+<glyph unicode="&#xe023;" d="M600 1196q162 0 299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299t80 299t217 217t299 80zM600 1014q-171 0 -292.5 -121.5t-121.5 -292.5t121.5 -292.5t292.5 -121.5t292.5 121.5t121.5 292.5t-121.5 292.5t-292.5 121.5zM600 600h200 v-100h-300v400h100v-300z" />
+<glyph unicode="&#xe024;" d="M721 400h-242l-40 -400h-539l431 1200h209l-21 -300h162l-20 300h208l431 -1200h-538zM712 500l-27 300h-170l-27 -300h224z" />
+<glyph unicode="&#xe025;" d="M1100 400v-400h-1100v400h490l-290 300h200v500h300v-500h200l-290 -300h490zM988 300h-175v-100h175v100z" />
+<glyph unicode="&#xe026;" d="M600 1199q122 0 233 -47.5t191 -127.5t127.5 -191t47.5 -233t-47.5 -233t-127.5 -191t-191 -127.5t-233 -47.5t-233 47.5t-191 127.5t-127.5 191t-47.5 233t47.5 233t127.5 191t191 127.5t233 47.5zM600 1012q-170 0 -291 -121t-121 -291t121 -291t291 -121t291 121 t121 291t-121 291t-291 121zM700 600h150l-250 -300l-250 300h150v300h200v-300z" />
+<glyph unicode="&#xe027;" d="M600 1196q162 0 299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299t80 299t217 217t299 80zM600 1014q-171 0 -292.5 -121.5t-121.5 -292.5t121.5 -292.5t292.5 -121.5t292.5 121.5t121.5 292.5t-121.5 292.5t-292.5 121.5zM850 600h-150 v-300h-200v300h-150l250 300z" />
+<glyph unicode="&#xe028;" d="M0 500l200 700h800q199 -700 200 -700v-475q0 -11 -7 -18t-18 -7h-1150q-11 0 -18 7t-7 18v475zM903 1000h-606l-97 -500h200l50 -200h300l50 200h200z" />
+<glyph unicode="&#xe029;" d="M600 1196q162 0 299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299t80 299t217 217t299 80zM600 1014q-171 0 -292.5 -121.5t-121.5 -292.5q0 -172 121.5 -293t292.5 -121t292.5 121t121.5 293q0 171 -121.5 292.5t-292.5 121.5zM797 598 l-297 -201v401z" />
+<glyph unicode="&#xe030;" d="M1177 600h-150q0 -177 -125 -302t-302 -125t-302 125t-125 302t125 302t302 125q136 0 246 -81l-146 -146h400v400l-145 -145q-157 122 -355 122q-118 0 -224.5 -45.5t-184 -123t-123 -184t-45.5 -224.5t45.5 -224.5t123 -184t184 -123t224.5 -45.5t224.5 45.5t184 123 t123 184t45.5 224.5z" />
+<glyph unicode="&#xe031;" d="M700 800l147 147q-112 80 -247 80q-177 0 -302 -125t-125 -302h-150q0 118 45.5 224.5t123 184t184 123t224.5 45.5q198 0 355 -122l145 145v-400h-400zM500 400l-147 -147q112 -80 247 -80q177 0 302 125t125 302h150q0 -118 -45.5 -224.5t-123 -184t-184 -123 t-224.5 -45.5q-198 0 -355 122l-145 -145v400h400z" />
+<glyph unicode="&#xe032;" d="M100 1200v-1200h1100v1200h-1100zM1100 100h-900v900h900v-900zM400 800h-100v100h100v-100zM1000 800h-500v100h500v-100zM400 600h-100v100h100v-100zM1000 600h-500v100h500v-100zM400 400h-100v100h100v-100zM1000 400h-500v100h500v-100zM400 200h-100v100h100v-100 zM1000 300h-500v-100h500v100z" />
+<glyph unicode="&#xe034;" d="M200 0h-100v1100h100v-1100zM1100 600v500q-40 -81 -101.5 -115.5t-127.5 -29.5t-138 25t-139.5 40t-125.5 25t-103 -29.5t-65 -115.5v-500q60 60 127.5 84t127.5 17.5t122 -23t119 -30t110 -11t103 42t91 120.5z" />
+<glyph unicode="&#xe035;" d="M1200 275v300q0 116 -49.5 227t-131 192.5t-192.5 131t-227 49.5t-227 -49.5t-192.5 -131t-131 -192.5t-49.5 -227v-300q0 -11 7 -18t18 -7h50q11 0 18 7t7 18v300q0 127 70.5 231.5t184.5 161.5t245 57t245 -57t184.5 -161.5t70.5 -231.5v-300q0 -11 7 -18t18 -7h50 q11 0 18 7t7 18zM400 480v-460q0 -8 -6 -14t-14 -6h-160q-8 0 -14 6t-6 14v460q0 8 6 14t14 6h160q8 0 14 -6t6 -14zM1000 480v-460q0 -8 -6 -14t-14 -6h-160q-8 0 -14 6t-6 14v460q0 8 6 14t14 6h160q8 0 14 -6t6 -14z" />
+<glyph unicode="&#xe036;" d="M0 800v-400h300l300 -200v800l-300 -200h-300zM971 600l141 -141l-71 -71l-141 141l-141 -141l-71 71l141 141l-141 141l71 71l141 -141l141 141l71 -71z" />
+<glyph unicode="&#xe037;" d="M0 800v-400h300l300 -200v800l-300 -200h-300zM700 857l69 53q111 -135 111 -310q0 -169 -106 -302l-67 54q86 110 86 248q0 146 -93 257z" />
+<glyph unicode="&#xe038;" d="M974 186l6 8q142 178 142 405q0 230 -144 408l-6 8l-83 -64l7 -8q123 -151 123 -344q0 -189 -119 -339l-7 -8zM300 801l300 200v-800l-300 200h-300v400h300zM702 858l69 53q111 -135 111 -310q0 -170 -106 -303l-67 55q86 110 86 248q0 145 -93 257z" />
+<glyph unicode="&#xe039;" d="M100 700h400v100h100v100h-100v300h-500v-600h100v100zM1200 700v500h-600v-200h100v-300h200v-300h300v200h-200v100h200zM100 1100h300v-300h-300v300zM800 800v300h300v-300h-300zM200 900h100v100h-100v-100zM900 1000h100v-100h-100v100zM300 600h-100v-100h-200 v-500h500v500h-200v100zM900 200v-100h-200v100h-100v100h100v200h-200v100h300v-300h200v-100h-100zM400 400v-300h-300v300h300zM300 200h-100v100h100v-100zM1100 300h100v-100h-100v100zM600 100h100v-100h-100v100zM1200 100v-100h-300v100h300z" />
+<glyph unicode="&#xe040;" d="M100 1200h-100v-1000h100v1000zM300 200h-100v1000h100v-1000zM700 200h-200v1000h200v-1000zM900 200h-100v1000h100v-1000zM1200 1200v-1000h-200v1000h200zM400 100v-100h-300v100h300zM500 91h100v-91h-100v91zM700 91h100v-91h-100v91zM1100 91v-91h-200v91h200z " />
+<glyph unicode="&#xe041;" d="M1200 500l-500 -500l-699 700v475q0 10 7.5 17.5t17.5 7.5h474zM320 882q29 29 29 71t-29 71q-30 30 -71.5 30t-71.5 -30q-29 -29 -29 -71t29 -71q30 -30 71.5 -30t71.5 30z" />
+<glyph unicode="&#xe042;" d="M1201 500l-500 -500l-699 700v475q0 11 7 18t18 7h474zM1501 500l-500 -500l-50 50l450 450l-700 700h100zM320 882q30 29 30 71t-30 71q-29 30 -71 30t-71 -30q-30 -29 -30 -71t30 -71q29 -30 71 -30t71 30z" />
+<glyph unicode="&#xe043;" d="M1200 1200v-1000l-100 -100v1000h-750l-100 -100h750v-1000h-900v1025l175 175h925z" />
+<glyph unicode="&#xe045;" d="M947 829l-94 346q-2 11 -10 18t-18 7h-450q-10 0 -18 -7t-10 -18l-94 -346l40 -124h592zM1200 800v-700h-200v200h-800v-200h-200v700h200l100 -200h600l100 200h200zM881 176l38 -152q2 -10 -3.5 -17t-15.5 -7h-600q-10 0 -15.5 7t-3.5 17l38 152q2 10 11.5 17t19.5 7 h500q10 0 19.5 -7t11.5 -17z" />
+<glyph unicode="&#xe047;" d="M1200 0v66q-34 1 -74 43q-18 19 -33 42t-21 37l-6 13l-385 998h-93l-399 -1006q-24 -48 -52 -75q-12 -12 -33 -25t-36 -20l-15 -7v-66h365v66q-41 0 -72 11t-49 38t1 71l92 234h391l82 -222q16 -45 -5.5 -88.5t-74.5 -43.5v-66h417zM416 521l178 457l46 -140l116 -317 h-340z" />
+<glyph unicode="&#xe048;" d="M100 1199h471q120 0 213 -88t93 -228q0 -55 -11.5 -101.5t-28 -74t-33.5 -47.5t-28 -28l-12 -7q8 -3 21.5 -9t48 -31.5t60.5 -58t47.5 -91.5t21.5 -129q0 -84 -59 -156.5t-142 -111t-162 -38.5h-500v89q41 7 70.5 32.5t29.5 65.5v827q0 28 -1 39.5t-5.5 26t-15.5 21 t-29 14t-49 14.5v70zM400 1079v-379h139q76 0 130 61.5t54 138.5q0 82 -84 130.5t-239 48.5zM400 200h161q89 0 153 48.5t64 132.5q0 90 -62.5 154.5t-156.5 64.5h-159v-400z" />
+<glyph unicode="&#xe049;" d="M877 1200l2 -57q-33 -8 -62 -25.5t-46 -37t-29.5 -38t-17.5 -30.5l-5 -12l-128 -825q-10 -52 14 -82t95 -36v-57h-500v57q77 7 134.5 40.5t65.5 80.5l173 849q10 56 -10 74t-91 37q-6 1 -10.5 2.5t-9.5 2.5v57h425z" />
+<glyph unicode="&#xe050;" d="M1150 1200h150v-300h-50q0 29 -8 48.5t-18.5 30t-33.5 15t-39.5 5.5t-50.5 1h-200v-850l100 -50v-100h-400v100l100 50v850h-200q-34 0 -50.5 -1t-40 -5.5t-33.5 -15t-18.5 -30t-8.5 -48.5h-49v300h150h700zM100 1000v-800h75l-125 -167l-125 167h75v800h-75l125 167 l125 -167h-75z" />
+<glyph unicode="&#xe051;" d="M950 1201h150v-300h-50q0 29 -8 48.5t-18 30t-33.5 15t-40 5.5t-50.5 1h-200v-650l100 -50v-100h-400v100l100 50v650h-200q-34 0 -50.5 -1t-39.5 -5.5t-33.5 -15t-18.5 -30t-8 -48.5h-50v300h150h700zM200 101h800v75l167 -125l-167 -125v75h-800v-75l-167 125l167 125 v-75z" />
+<glyph unicode="&#xe052;" d="M700 950v100q0 21 -14.5 35.5t-35.5 14.5h-600q-21 0 -35.5 -14.5t-14.5 -35.5v-100q0 -20 14.5 -35t35.5 -15h600q21 0 35.5 15t14.5 35zM1100 650v100q0 21 -14.5 35.5t-35.5 14.5h-1000q-21 0 -35.5 -14.5t-14.5 -35.5v-100q0 -20 14.5 -35t35.5 -15h1000 q21 0 35.5 15t14.5 35zM900 350v100q0 21 -14.5 35.5t-35.5 14.5h-800q-21 0 -35.5 -14.5t-14.5 -35.5v-100q0 -20 14.5 -35t35.5 -15h800q21 0 35.5 15t14.5 35zM1200 50v100q0 21 -14.5 35.5t-35.5 14.5h-1100q-21 0 -35.5 -14.5t-14.5 -35.5v-100q0 -20 14.5 -35 t35.5 -15h1100q21 0 35.5 15t14.5 35z" />
+<glyph unicode="&#xe053;" d="M1000 950v100q0 21 -14.5 35.5t-35.5 14.5h-700q-21 0 -35.5 -14.5t-14.5 -35.5v-100q0 -20 14.5 -35t35.5 -15h700q21 0 35.5 15t14.5 35zM1200 650v100q0 21 -14.5 35.5t-35.5 14.5h-1100q-21 0 -35.5 -14.5t-14.5 -35.5v-100q0 -20 14.5 -35t35.5 -15h1100 q21 0 35.5 15t14.5 35zM1000 350v100q0 21 -14.5 35.5t-35.5 14.5h-700q-21 0 -35.5 -14.5t-14.5 -35.5v-100q0 -20 14.5 -35t35.5 -15h700q21 0 35.5 15t14.5 35zM1200 50v100q0 21 -14.5 35.5t-35.5 14.5h-1100q-21 0 -35.5 -14.5t-14.5 -35.5v-100q0 -20 14.5 -35 t35.5 -15h1100q21 0 35.5 15t14.5 35z" />
+<glyph unicode="&#xe054;" d="M500 950v100q0 21 14.5 35.5t35.5 14.5h600q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-600q-21 0 -35.5 15t-14.5 35zM100 650v100q0 21 14.5 35.5t35.5 14.5h1000q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-1000q-21 0 -35.5 15 t-14.5 35zM300 350v100q0 21 14.5 35.5t35.5 14.5h800q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-800q-21 0 -35.5 15t-14.5 35zM0 50v100q0 21 14.5 35.5t35.5 14.5h1100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-1100 q-21 0 -35.5 15t-14.5 35z" />
+<glyph unicode="&#xe055;" d="M0 950v100q0 21 14.5 35.5t35.5 14.5h1100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-1100q-21 0 -35.5 15t-14.5 35zM0 650v100q0 21 14.5 35.5t35.5 14.5h1100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-1100q-21 0 -35.5 15 t-14.5 35zM0 350v100q0 21 14.5 35.5t35.5 14.5h1100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-1100q-21 0 -35.5 15t-14.5 35zM0 50v100q0 21 14.5 35.5t35.5 14.5h1100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-1100 q-21 0 -35.5 15t-14.5 35z" />
+<glyph unicode="&#xe056;" d="M0 950v100q0 21 14.5 35.5t35.5 14.5h100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-100q-21 0 -35.5 15t-14.5 35zM300 950v100q0 21 14.5 35.5t35.5 14.5h800q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-800q-21 0 -35.5 15 t-14.5 35zM0 650v100q0 21 14.5 35.5t35.5 14.5h100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-100q-21 0 -35.5 15t-14.5 35zM300 650v100q0 21 14.5 35.5t35.5 14.5h800q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-800 q-21 0 -35.5 15t-14.5 35zM0 350v100q0 21 14.5 35.5t35.5 14.5h100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-100q-21 0 -35.5 15t-14.5 35zM300 350v100q0 21 14.5 35.5t35.5 14.5h800q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15 h-800q-21 0 -35.5 15t-14.5 35zM0 50v100q0 21 14.5 35.5t35.5 14.5h100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-100q-21 0 -35.5 15t-14.5 35zM300 50v100q0 21 14.5 35.5t35.5 14.5h800q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15 h-800q-21 0 -35.5 15t-14.5 35z" />
+<glyph unicode="&#xe057;" d="M400 1100h-100v-1100h100v1100zM700 950v100q0 21 -15 35.5t-35 14.5h-100q-21 0 -35.5 -14.5t-14.5 -35.5v-100q0 -20 14.5 -35t35.5 -15h100q20 0 35 15t15 35zM1100 650v100q0 21 -15 35.5t-35 14.5h-500q-21 0 -35.5 -14.5t-14.5 -35.5v-100q0 -20 14.5 -35t35.5 -15 h500q20 0 35 15t15 35zM100 425v75h-201v100h201v75l166 -125zM900 350v100q0 21 -15 35.5t-35 14.5h-300q-21 0 -35.5 -14.5t-14.5 -35.5v-100q0 -20 14.5 -35t35.5 -15h300q20 0 35 15t15 35zM1200 50v100q0 21 -15 35.5t-35 14.5h-600q-21 0 -35.5 -14.5t-14.5 -35.5 v-100q0 -20 14.5 -35t35.5 -15h600q20 0 35 15t15 35z" />
+<glyph unicode="&#xe058;" d="M201 950v100q0 21 -15 35.5t-35 14.5h-100q-21 0 -35.5 -14.5t-14.5 -35.5v-100q0 -20 14.5 -35t35.5 -15h100q20 0 35 15t15 35zM801 1100h100v-1100h-100v1100zM601 650v100q0 21 -15 35.5t-35 14.5h-500q-21 0 -35.5 -14.5t-14.5 -35.5v-100q0 -20 14.5 -35t35.5 -15 h500q20 0 35 15t15 35zM1101 425v75h200v100h-200v75l-167 -125zM401 350v100q0 21 -15 35.5t-35 14.5h-300q-21 0 -35.5 -14.5t-14.5 -35.5v-100q0 -20 14.5 -35t35.5 -15h300q20 0 35 15t15 35zM701 50v100q0 21 -15 35.5t-35 14.5h-600q-21 0 -35.5 -14.5t-14.5 -35.5 v-100q0 -20 14.5 -35t35.5 -15h600q20 0 35 15t15 35z" />
+<glyph unicode="&#xe059;" d="M900 925v-650q0 -31 -22 -53t-53 -22h-750q-31 0 -53 22t-22 53v650q0 31 22 53t53 22h750q31 0 53 -22t22 -53zM1200 300l-300 300l300 300v-600z" />
+<glyph unicode="&#xe060;" d="M1200 1056v-1012q0 -18 -12.5 -31t-31.5 -13h-1112q-18 0 -31 13t-13 31v1012q0 18 13 31t31 13h1112q19 0 31.5 -13t12.5 -31zM1100 1000h-1000v-737l247 182l298 -131l-74 156l293 318l236 -288v500zM476 750q0 -56 -39 -95t-95 -39t-95 39t-39 95t39 95t95 39t95 -39 t39 -95z" />
+<glyph unicode="&#xe062;" d="M600 1213q123 0 227 -63t164.5 -169.5t60.5 -229.5t-73 -272q-73 -114 -166.5 -237t-150.5 -189l-57 -66q-10 9 -27 26t-66.5 70.5t-96 109t-104 135.5t-100.5 155q-63 139 -63 262q0 124 60.5 231.5t165 172t226.5 64.5zM599 514q107 0 182.5 75.5t75.5 182.5t-75.5 182 t-182.5 75t-182 -75.5t-75 -181.5q0 -107 75.5 -182.5t181.5 -75.5z" />
+<glyph unicode="&#xe063;" d="M600 1199q122 0 233 -47.5t191 -127.5t127.5 -191t47.5 -233t-47.5 -233t-127.5 -191t-191 -127.5t-233 -47.5t-233 47.5t-191 127.5t-127.5 191t-47.5 233t47.5 233t127.5 191t191 127.5t233 47.5zM600 173v854q-176 0 -301.5 -125t-125.5 -302t125.5 -302t301.5 -125z " />
+<glyph unicode="&#xe064;" d="M554 1295q21 -71 57.5 -142.5t76 -130.5t83 -118.5t82 -117t70 -116t50 -125.5t18.5 -136q0 -89 -39 -165.5t-102 -126.5t-140 -79.5t-156 -33.5q-114 6 -211.5 53t-161.5 138.5t-64 210.5q0 94 34 186t88.5 172.5t112 159t115 177t87.5 194.5zM455 296q-7 6 -18 17 t-34 48t-33 77q-15 73 -14 143.5t10 122.5l9 51q-92 -110 -119.5 -185t-12.5 -156q14 -82 59.5 -136t136.5 -80z" />
+<glyph unicode="&#xe065;" d="M1108 902l113 113l-21 85l-92 28l-113 -113zM1100 625v-225q0 -165 -117.5 -282.5t-282.5 -117.5h-300q-165 0 -282.5 117.5t-117.5 282.5v300q0 165 117.5 282.5t282.5 117.5q366 -6 397 -14l-186 -186h-311q-41 0 -70.5 -29.5t-29.5 -70.5v-500q0 -41 29.5 -70.5 t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5v125zM436 341l161 50l412 412l-114 113l-405 -405z" />
+<glyph unicode="&#xe066;" d="M1100 453v-53q0 -165 -117.5 -282.5t-282.5 -117.5h-300q-165 0 -282.5 117.5t-117.5 282.5v300q0 165 117.5 282.5t282.5 117.5h261l2 -80q-133 -32 -218 -120h-145q-41 0 -70.5 -29.5t-29.5 -70.5v-500q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5z M813 431l360 324l-359 318v-216q-7 0 -19 -1t-48 -8t-69.5 -18.5t-76.5 -37t-76.5 -59t-62 -88t-39.5 -121.5q30 38 81.5 64t103 35.5t99 14t77.5 3.5l29 -1v-209z" />
+<glyph unicode="&#xe067;" d="M1100 569v-169q0 -165 -117.5 -282.5t-282.5 -117.5h-300q-165 0 -282.5 117.5t-117.5 282.5v300q0 165 117.5 282.5t282.5 117.5h300q60 0 127 -23l-178 -177h-349q-41 0 -70.5 -29.5t-29.5 -70.5v-500q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5v69z M625 348l566 567l-136 137l-430 -431l-147 147l-136 -136z" />
+<glyph unicode="&#xe068;" d="M900 303v198h-200v-200h195l-295 -300l-300 300h200v200h-200v-198l-300 300l300 296v-198h200v200h-200l300 300l295 -300h-195v-200h200v198l300 -296z" />
+<glyph unicode="&#xe069;" d="M900 0l-500 488v-438q0 -21 -14.5 -35.5t-35.5 -14.5h-100q-21 0 -35.5 14.5t-14.5 35.5v1000q0 21 14.5 35.5t35.5 14.5h100q21 0 35.5 -14.5t14.5 -35.5v-437l500 487v-1100z" />
+<glyph unicode="&#xe070;" d="M1200 0l-500 488v-488l-500 488v-438q0 -21 -14.5 -35.5t-35.5 -14.5h-100q-21 0 -35.5 14.5t-14.5 35.5v1000q0 21 14.5 35.5t35.5 14.5h100q21 0 35.5 -14.5t14.5 -35.5v-437l500 487v-487l500 487v-1100z" />
+<glyph unicode="&#xe071;" d="M1200 0l-500 488v-488l-564 550l564 550v-487l500 487v-1100z" />
+<glyph unicode="&#xe072;" d="M1100 550l-900 550v-1100z" />
+<glyph unicode="&#xe073;" d="M500 150v800q0 21 -14.5 35.5t-35.5 14.5h-200q-21 0 -35.5 -14.5t-14.5 -35.5v-800q0 -21 14.5 -35.5t35.5 -14.5h200q21 0 35.5 14.5t14.5 35.5zM900 150v800q0 21 -14.5 35.5t-35.5 14.5h-200q-21 0 -35.5 -14.5t-14.5 -35.5v-800q0 -21 14.5 -35.5t35.5 -14.5h200 q21 0 35.5 14.5t14.5 35.5z" />
+<glyph unicode="&#xe074;" d="M1100 150v800q0 21 -14.5 35.5t-35.5 14.5h-800q-21 0 -35.5 -14.5t-14.5 -35.5v-800q0 -20 14.5 -35t35.5 -15h800q21 0 35.5 15t14.5 35z" />
+<glyph unicode="&#xe075;" d="M500 0v488l-500 -488v1100l500 -487v487l564 -550z" />
+<glyph unicode="&#xe076;" d="M1050 1100h100q21 0 35.5 -14.5t14.5 -35.5v-1000q0 -21 -14.5 -35.5t-35.5 -14.5h-100q-21 0 -35.5 14.5t-14.5 35.5v438l-500 -488v488l-500 -488v1100l500 -487v487l500 -487v437q0 21 14.5 35.5t35.5 14.5z" />
+<glyph unicode="&#xe077;" d="M850 1100h100q21 0 35.5 -14.5t14.5 -35.5v-1000q0 -21 -14.5 -35.5t-35.5 -14.5h-100q-21 0 -35.5 14.5t-14.5 35.5v438l-500 -488v1100l500 -487v437q0 21 14.5 35.5t35.5 14.5z" />
+<glyph unicode="&#xe078;" d="M650 1064l-550 -564h1100zM1200 350v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-1000q-21 0 -35.5 14.5t-14.5 35.5v100q0 21 14.5 35.5t35.5 14.5h1000q21 0 35.5 -14.5t14.5 -35.5z" />
+<glyph unicode="&#xe079;" d="M777 7l240 240l-353 353l353 353l-240 240l-592 -594z" />
+<glyph unicode="&#xe080;" d="M513 -46l-241 240l353 353l-353 353l241 240l572 -571l21 -22l-1 -1v-1z" />
+<glyph unicode="&#xe081;" d="M600 1197q162 0 299.5 -80t217.5 -217.5t80 -299.5t-80 -299.5t-217.5 -217.5t-299.5 -80t-299.5 80t-217.5 217.5t-80 299.5t80 299.5t217.5 217.5t299.5 80zM500 900v-200h-200v-200h200v-200h200v200h200v200h-200v200h-200z" />
+<glyph unicode="&#xe082;" d="M600 1197q162 0 299.5 -80t217.5 -217.5t80 -299.5t-80 -299.5t-217.5 -217.5t-299.5 -80t-299.5 80t-217.5 217.5t-80 299.5t80 299.5t217.5 217.5t299.5 80zM300 700v-200h600v200h-600z" />
+<glyph unicode="&#xe083;" d="M600 1197q162 0 299.5 -80t217.5 -217.5t80 -299.5t-80 -299.5t-217.5 -217.5t-299.5 -80t-299.5 80t-217.5 217.5t-80 299.5t80 299.5t217.5 217.5t299.5 80zM247 741l141 -141l-142 -141l213 -213l141 142l141 -142l213 213l-142 141l142 141l-213 212l-141 -141 l-141 142z" />
+<glyph unicode="&#xe084;" d="M600 1197q162 0 299.5 -80t217.5 -217.5t80 -299.5t-80 -299.5t-217.5 -217.5t-299.5 -80t-299.5 80t-217.5 217.5t-80 299.5t80 299.5t217.5 217.5t299.5 80zM546 623l-102 102l-174 -174l276 -277l411 411l-175 174z" />
+<glyph unicode="&#xe085;" d="M600 1197q162 0 299.5 -80t217.5 -217.5t80 -299.5t-80 -299.5t-217.5 -217.5t-299.5 -80t-299.5 80t-217.5 217.5t-80 299.5t80 299.5t217.5 217.5t299.5 80zM500 500h200q5 3 14 8t31.5 25.5t39.5 45.5t31 69t14 94q0 51 -17.5 89t-42 58t-58.5 32t-58.5 15t-51.5 3 q-105 0 -172 -56t-67 -183h144q4 0 11.5 -1t11 -1t6.5 3t3 9t1 11t3.5 8.5t3.5 6t5.5 4t6.5 2.5t9 1.5t9 0.5h11.5h12.5q19 0 30 -10t11 -26q0 -22 -4 -28t-27 -22q-5 -1 -12.5 -3t-27 -13.5t-34 -27t-26.5 -46t-11 -68.5zM500 400v-100h200v100h-200z" />
+<glyph unicode="&#xe086;" d="M600 1197q162 0 299.5 -80t217.5 -217.5t80 -299.5t-80 -299.5t-217.5 -217.5t-299.5 -80t-299.5 80t-217.5 217.5t-80 299.5t80 299.5t217.5 217.5t299.5 80zM500 900v-100h200v100h-200zM400 700v-100h100v-200h-100v-100h400v100h-100v300h-300z" />
+<glyph unicode="&#xe087;" d="M1200 700v-200h-203q-25 -102 -116.5 -186t-180.5 -117v-197h-200v197q-140 27 -208 102.5t-98 200.5h-194v200h194q15 60 36 104.5t55.5 86t88 69t126.5 40.5v200h200v-200q54 -20 113 -60t112.5 -105.5t71.5 -134.5h203zM700 500v-206q149 48 201 206h-201v200h200 q-25 74 -76 127.5t-124 76.5v-204h-200v203q-75 -24 -130 -77.5t-79 -125.5h209v-200h-210q24 -73 79.5 -127.5t130.5 -78.5v206h200z" />
+<glyph unicode="&#xe088;" d="M600 1196q162 0 299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299t80 299t217 217t299 80zM600 1014q-171 0 -292.5 -121.5t-121.5 -292.5t121.5 -292.5t292.5 -121.5t292.5 121.5t121.5 292.5t-121.5 292.5t-292.5 121.5zM844 735 l-135 -135l135 -135l-109 -109l-135 135l-135 -135l-109 109l135 135l-135 135l109 109l135 -135l135 135z" />
+<glyph unicode="&#xe089;" d="M600 1196q162 0 299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299t80 299t217 217t299 80zM600 1014q-171 0 -292.5 -121.5t-121.5 -292.5t121.5 -292.5t292.5 -121.5t292.5 121.5t121.5 292.5t-121.5 292.5t-292.5 121.5zM896 654 l-346 -345l-228 228l141 141l87 -87l204 205z" />
+<glyph unicode="&#xe090;" d="M600 1196q162 0 299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299t80 299t217 217t299 80zM248 385l568 567q-100 62 -216 62q-171 0 -292.5 -121.5t-121.5 -292.5q0 -115 62 -215zM955 809l-564 -564q97 -59 209 -59q171 0 292.5 121.5 t121.5 292.5q0 112 -59 209z" />
+<glyph unicode="&#xe091;" d="M1200 400h-600v-301l-600 448l600 453v-300h600v-300z" />
+<glyph unicode="&#xe092;" d="M600 400h-600v300h600v300l600 -453l-600 -448v301z" />
+<glyph unicode="&#xe093;" d="M1098 600h-298v-600h-300v600h-296l450 600z" />
+<glyph unicode="&#xe094;" d="M998 600l-449 -600l-445 600h296v600h300v-600h298z" />
+<glyph unicode="&#xe095;" d="M600 199v301q-95 -2 -183 -20t-170 -52t-147 -92.5t-100 -135.5q6 132 41 238.5t103.5 193t184 138t271.5 59.5v271l600 -453z" />
+<glyph unicode="&#xe096;" d="M1200 1200h-400l129 -129l-294 -294l142 -142l294 294l129 -129v400zM565 423l-294 -294l129 -129h-400v400l129 -129l294 294z" />
+<glyph unicode="&#xe097;" d="M871 730l129 -130h-400v400l129 -129l295 295l142 -141zM200 600h400v-400l-129 130l-295 -295l-142 141l295 295z" />
+<glyph unicode="&#xe101;" d="M600 1177q118 0 224.5 -45.5t184 -123t123 -184t45.5 -224.5t-45.5 -224.5t-123 -184t-184 -123t-224.5 -45.5t-224.5 45.5t-184 123t-123 184t-45.5 224.5t45.5 224.5t123 184t184 123t224.5 45.5zM686 549l58 302q4 20 -8 34.5t-33 14.5h-207q-20 0 -32 -14.5t-8 -34.5 l58 -302q4 -20 21.5 -34.5t37.5 -14.5h54q20 0 37.5 14.5t21.5 34.5zM700 400h-200v-100h200v100z" />
+<glyph unicode="&#xe102;" d="M1200 900h-111v6t-1 15t-3 18l-34 172q-11 39 -41.5 63t-69.5 24q-32 0 -61 -17l-239 -144q-22 -13 -40 -35q-19 24 -40 36l-238 144q-33 18 -62 18q-39 0 -69.5 -23t-40.5 -61l-35 -177q-2 -8 -3 -18t-1 -15v-6h-111v-100h100v-200h400v300h200v-300h400v200h100v100z M731 900l202 197q5 -12 12 -32.5t23 -64t25 -72t7 -28.5h-269zM481 900h-281q-3 0 14 48t35 96l18 47zM100 0h400v400h-400v-400zM700 400h400v-400h-400v400z" />
+<glyph unicode="&#xe103;" d="M0 121l216 193q-9 53 -13 83t-5.5 94t9 113t38.5 114t74 124q47 60 99.5 102.5t103 68t127.5 48t145.5 37.5t184.5 43.5t220 58.5q0 -189 -22 -343t-59 -258t-89 -181.5t-108.5 -120t-122 -68t-125.5 -30t-121.5 -1.5t-107.5 12.5t-87.5 17t-56.5 7.5l-99 -55l-201 -202 v143zM692 611q70 38 118.5 69.5t102 79t99 111.5t86.5 148q22 50 24 60t-6 19q-7 5 -17 5t-26.5 -14.5t-33.5 -39.5q-35 -51 -113.5 -108.5t-139.5 -89.5l-61 -32q-369 -197 -458 -401q-48 -111 -28.5 -117.5t86.5 76.5q55 66 367 234z" />
+<glyph unicode="&#xe105;" d="M1261 600l-26 -40q-6 -10 -20 -30t-49 -63.5t-74.5 -85.5t-97 -90t-116.5 -83.5t-132.5 -59t-145.5 -23.5t-145.5 23.5t-132.5 59t-116.5 83.5t-97 90t-74.5 85.5t-49 63.5t-20 30l-26 40l26 40q6 10 20 30t49 63.5t74.5 85.5t97 90t116.5 83.5t132.5 59t145.5 23.5 t145.5 -23.5t132.5 -59t116.5 -83.5t97 -90t74.5 -85.5t49 -63.5t20 -30zM600 240q64 0 123.5 20t100.5 45.5t85.5 71.5t66.5 75.5t58 81.5t47 66q-1 1 -28.5 37.5t-42 55t-43.5 53t-57.5 63.5t-58.5 54q49 -74 49 -163q0 -124 -88 -212t-212 -88t-212 88t-88 212 q0 85 46 158q-102 -87 -226 -258q7 -10 40.5 -58t56 -78.5t68 -77.5t87.5 -75t103 -49.5t125 -21.5zM484 762l-107 -106q49 -124 154 -191l105 105q-37 24 -75 72t-57 84z" />
+<glyph unicode="&#xe106;" d="M906 1200l-314 -1200h-148l37 143q-82 21 -165 71.5t-140 102t-109.5 112t-72 88.5t-29.5 43l-26 40l26 40q6 10 20 30t49 63.5t74.5 85.5t97 90t116.5 83.5t132.5 59t145.5 23.5q61 0 121 -17l37 142h148zM1261 600l-26 -40q-7 -12 -25.5 -38t-63.5 -79.5t-95.5 -102.5 t-124 -100t-146.5 -79l38 145q22 15 44.5 34t46 44t40.5 44t41 50.5t33.5 43.5t33 44t24.5 34q-97 127 -140 175l39 146q67 -54 131.5 -125.5t87.5 -103.5t36 -52zM513 264l37 141q-107 18 -178.5 101.5t-71.5 193.5q0 85 46 158q-102 -87 -226 -258q210 -282 393 -336z M484 762l-107 -106q49 -124 154 -191l47 47l23 87q-30 28 -59 69t-44 68z" />
+<glyph unicode="&#xe107;" d="M-47 0h1294q37 0 50.5 35.5t-7.5 67.5l-642 1056q-20 33 -48 36t-48 -29l-642 -1066q-21 -32 -7.5 -66t50.5 -34zM700 200v100h-200v-100h-345l445 723l445 -723h-345zM700 700h-200v-100l100 -300l100 300v100z" />
+<glyph unicode="&#xe108;" d="M800 711l363 -325q15 -14 26 -38.5t11 -44.5v-41q0 -20 -12 -26.5t-29 5.5l-359 249v-263q100 -91 100 -113v-64q0 -21 -13 -29t-32 1l-94 78h-222l-94 -78q-19 -9 -32 -1t-13 29v64q0 22 100 113v263l-359 -249q-17 -12 -29 -5.5t-12 26.5v41q0 20 11 44.5t26 38.5 l363 325v339q0 62 44 106t106 44t106 -44t44 -106v-339z" />
+<glyph unicode="&#xe110;" d="M941 800l-600 -600h-341v200h259l600 600h241v198l300 -295l-300 -300v197h-159zM381 678l141 142l-181 180h-341v-200h259zM1100 598l300 -295l-300 -300v197h-241l-181 181l141 142l122 -123h159v198z" />
+<glyph unicode="&#xe111;" d="M100 1100h1000q41 0 70.5 -29.5t29.5 -70.5v-600q0 -41 -29.5 -70.5t-70.5 -29.5h-596l-304 -300v300h-100q-41 0 -70.5 29.5t-29.5 70.5v600q0 41 29.5 70.5t70.5 29.5z" />
+<glyph unicode="&#xe112;" d="M400 900h-300v300h300v-300zM1100 900h-300v300h300v-300zM1100 800v-200q0 -42 -3 -83t-15 -104t-31.5 -116t-58 -109.5t-89 -96.5t-129 -65.5t-174.5 -25.5t-174.5 25.5t-129 65.5t-89 96.5t-58 109.5t-31.5 116t-15 104t-3 83v200h300v-250q0 -113 6 -145 q17 -92 102 -117q39 -11 92 -11q37 0 66.5 5.5t50 15.5t36 24t24 31.5t14 37.5t7 42t2.5 45t0 47v25v250h300z" />
+<glyph unicode="&#xe113;" d="M902 184l226 227l-578 579l-580 -579l227 -227l352 353z" />
+<glyph unicode="&#xe114;" d="M650 218l578 579l-226 227l-353 -353l-352 353l-227 -227z" />
+<glyph unicode="&#xe115;" d="M1198 400v600h-796l215 -200h381v-400h-198l299 -283l299 283h-200zM-198 700l299 283l300 -283h-203v-400h385l215 -200h-800v600h-196z" />
+<glyph unicode="&#xe116;" d="M1050 1200h94q20 0 35 -14.5t15 -35.5t-15 -35.5t-35 -14.5h-54l-201 -961q-2 -4 -6 -10.5t-19 -17.5t-33 -11h-31v-50q0 -20 -14.5 -35t-35.5 -15t-35.5 15t-14.5 35v50h-300v-50q0 -20 -14.5 -35t-35.5 -15t-35.5 15t-14.5 35v50h-50q-21 0 -35.5 15t-14.5 35 q0 21 14.5 35.5t35.5 14.5h535l48 200h-633q-32 0 -54.5 21t-27.5 43l-100 475q-5 24 10 42q14 19 39 19h896l38 162q5 17 18.5 27.5t30.5 10.5z" />
+<glyph unicode="&#xe117;" d="M1200 1000v-100h-1200v100h200q0 41 29.5 70.5t70.5 29.5h300q41 0 70.5 -29.5t29.5 -70.5h500zM0 800h1200v-800h-1200v800z" />
+<glyph unicode="&#xe118;" d="M201 800l-200 -400v600h200q0 41 29.5 70.5t70.5 29.5h300q41 0 70.5 -29.5t29.5 -70.5h500v-200h-1000zM1501 700l-300 -700h-1200l300 700h1200z" />
+<glyph unicode="&#xe119;" d="M302 300h198v600h-198l298 300l298 -300h-198v-600h198l-298 -300z" />
+<glyph unicode="&#xe120;" d="M900 303v197h-600v-197l-300 297l300 298v-198h600v198l300 -298z" />
+<glyph unicode="&#xe121;" d="M31 400l172 739q5 22 23 41.5t38 19.5h672q19 0 37.5 -22.5t23.5 -45.5l172 -732h-1138zM100 300h1000q41 0 70.5 -29.5t29.5 -70.5v-100q0 -41 -29.5 -70.5t-70.5 -29.5h-1000q-41 0 -70.5 29.5t-29.5 70.5v100q0 41 29.5 70.5t70.5 29.5zM900 200h-100v-100h100v100z M1100 200h-100v-100h100v100z" />
+<glyph unicode="&#xe122;" d="M1100 200v850q0 21 14.5 35.5t35.5 14.5q20 0 35 -14.5t15 -35.5v-850q0 -20 -15 -35t-35 -15q-21 0 -35.5 15t-14.5 35zM325 800l675 250v-850l-675 200h-38l47 -276q2 -12 -3 -17.5t-11 -6t-21 -0.5h-8h-83q-20 0 -34.5 14t-18.5 35q-56 337 -56 351v250v5 q0 13 0.5 18.5t2.5 13t8 10.5t15 3h200zM-101 600v50q0 24 25 49t50 38l25 13v-250l-11 5.5t-24 14t-30 21.5t-24 27.5t-11 31.5z" />
+<glyph unicode="&#xe124;" d="M445 1180l-45 -233l-224 78l78 -225l-233 -44l179 -156l-179 -155l233 -45l-78 -224l224 78l45 -233l155 179l155 -179l45 233l224 -78l-78 224l234 45l-180 155l180 156l-234 44l78 225l-224 -78l-45 233l-155 -180z" />
+<glyph unicode="&#xe125;" d="M700 1200h-50q-27 0 -51 -20t-38 -48l-96 -198l-145 -196q-20 -26 -20 -63v-400q0 -75 100 -75h61q123 -100 139 -100h250q46 0 83 57l238 344q29 31 29 74v100q0 44 -30.5 84.5t-69.5 40.5h-328q28 118 28 125v150q0 44 -30.5 84.5t-69.5 40.5zM700 925l-50 -225h450 v-125l-250 -375h-214l-136 100h-100v375l150 212l100 213h50v-175zM0 800v-600h200v600h-200z" />
+<glyph unicode="&#xe126;" d="M700 0h-50q-27 0 -51 20t-38 48l-96 198l-145 196q-20 26 -20 63v400q0 75 100 75h61q123 100 139 100h250q46 0 83 -57l238 -344q29 -31 29 -74v-100q0 -44 -30.5 -84.5t-69.5 -40.5h-328q28 -118 28 -125v-150q0 -44 -30.5 -84.5t-69.5 -40.5zM200 400h-200v600h200 v-600zM700 275l-50 225h450v125l-250 375h-214l-136 -100h-100v-375l150 -212l100 -213h50v175z" />
+<glyph unicode="&#xe127;" d="M364 873l362 230q14 6 25 6q17 0 29 -12l109 -112q14 -14 14 -34q0 -18 -11 -32l-85 -121h302q85 0 138.5 -38t53.5 -110t-54.5 -111t-138.5 -39h-107l-130 -339q-7 -22 -20.5 -41.5t-28.5 -19.5h-341q-7 0 -90 81t-83 94v525q0 17 14 35.5t28 28.5zM408 792v-503 l100 -89h293l131 339q6 21 19.5 41t28.5 20h203q16 0 25 15t9 36q0 20 -9 34.5t-25 14.5h-457h-6.5h-7.5t-6.5 0.5t-6 1t-5 1.5t-5.5 2.5t-4 4t-4 5.5q-5 12 -5 20q0 14 10 27l147 183l-86 83zM208 200h-200v600h200v-600z" />
+<glyph unicode="&#xe128;" d="M475 1104l365 -230q7 -4 16.5 -10.5t26 -26t16.5 -36.5v-526q0 -13 -85.5 -93.5t-93.5 -80.5h-342q-15 0 -28.5 20t-19.5 41l-131 339h-106q-84 0 -139 39t-55 111t54 110t139 37h302l-85 121q-11 16 -11 32q0 21 14 34l109 113q13 12 29 12q11 0 25 -6zM370 946 l145 -184q10 -11 10 -26q0 -11 -5 -20q-1 -3 -3.5 -5.5l-4 -4t-5 -2.5t-5.5 -1.5t-6.5 -1t-6.5 -0.5h-7.5h-6.5h-476v-100h222q15 0 28.5 -20.5t19.5 -40.5l131 -339h293l106 89v502l-342 237zM1199 201h-200v600h200v-600z" />
+<glyph unicode="&#xe129;" d="M1100 473v342q0 15 -20 28.5t-41 19.5l-339 131v106q0 84 -39 139t-111 55t-110 -53.5t-38 -138.5v-302l-121 84q-15 12 -33.5 11.5t-32.5 -13.5l-112 -110q-22 -22 -6 -53l230 -363q4 -6 10.5 -15.5t26 -25t36.5 -15.5h525q13 0 94 83t81 90zM911 400h-503l-236 339 l83 86l183 -146q22 -18 47 -5q3 1 5.5 3.5l4 4t2.5 5t1.5 5.5t1 6.5t0.5 6v7.5v7v456q0 22 25 31t50 -0.5t25 -30.5v-202q0 -16 20 -29.5t41 -19.5l339 -130v-294zM1000 200v-200h-600v200h600z" />
+<glyph unicode="&#xe130;" d="M305 1104v200h600v-200h-600zM605 310l339 131q20 6 40.5 19.5t20.5 28.5v342q0 7 -81 90t-94 83h-525q-17 0 -35.5 -14t-28.5 -28l-10 -15l-230 -362q-15 -31 7 -53l112 -110q13 -13 32 -13.5t34 10.5l121 85l-1 -302q0 -84 38.5 -138t110.5 -54t111 55t39 139v106z M905 804v-294l-340 -130q-20 -6 -40 -20t-20 -29v-202q0 -22 -25 -31t-50 0t-25 31v456v14.5t-1.5 11.5t-5 12t-9.5 7q-24 13 -46 -5l-184 -146l-83 86l237 339h503z" />
+<glyph unicode="&#xe131;" d="M603 1195q162 0 299.5 -80t217.5 -218t80 -300t-80 -299.5t-217.5 -217.5t-299.5 -80t-300 80t-218 217.5t-80 299.5q0 122 47.5 232.5t127.5 190.5t190.5 127.5t232.5 47.5zM598 701h-298v-201h300l-2 -194l402 294l-402 298v-197z" />
+<glyph unicode="&#xe132;" d="M597 1195q122 0 232.5 -47.5t190.5 -127.5t127.5 -190.5t47.5 -232.5q0 -162 -80 -299.5t-218 -217.5t-300 -80t-299.5 80t-217.5 217.5t-80 299.5q0 122 47.5 232.5t127.5 190.5t190.5 127.5t231.5 47.5zM200 600l400 -294v194h302v201h-300v197z" />
+<glyph unicode="&#xe133;" d="M603 1195q121 0 231.5 -47.5t190.5 -127.5t127.5 -190.5t47.5 -232.5q0 -162 -80 -299.5t-217.5 -217.5t-299.5 -80t-300 80t-218 217.5t-80 299.5q0 122 47.5 232.5t127.5 190.5t190.5 127.5t232.5 47.5zM300 600h200v-300h200v300h200l-300 400z" />
+<glyph unicode="&#xe134;" d="M603 1195q121 0 231.5 -47.5t190.5 -127.5t127.5 -190.5t47.5 -232.5q0 -162 -80 -299.5t-217.5 -217.5t-299.5 -80t-300 80t-218 217.5t-80 299.5q0 122 47.5 232.5t127.5 190.5t190.5 127.5t232.5 47.5zM500 900v-300h-200l300 -400l300 400h-200v300h-200z" />
+<glyph unicode="&#xe135;" d="M603 1195q121 0 231.5 -47.5t190.5 -127.5t127.5 -190.5t47.5 -232.5q0 -162 -80 -299.5t-217.5 -217.5t-299.5 -80t-300 80t-218 217.5t-80 299.5q0 122 47.5 232.5t127.5 190.5t190.5 127.5t232.5 47.5zM627 1101q-15 -12 -36.5 -21t-34.5 -12t-44 -8t-39 -6 q-15 -3 -45.5 0.5t-45.5 -2.5q-21 -7 -52 -26.5t-34 -34.5q-3 -11 6.5 -22.5t8.5 -18.5q-3 -34 -27.5 -90.5t-29.5 -79.5q-8 -33 5.5 -92.5t7.5 -87.5q0 -9 17 -44t16 -60q12 0 23 -5.5t23 -15t20 -13.5q24 -12 108 -42q22 -8 53 -31.5t59.5 -38.5t57.5 -11q8 -18 -15 -55 t-20 -57q42 -71 87 -80q0 -6 -3 -15.5t-3.5 -14.5t4.5 -17q102 -2 221 112q30 29 47 47t34.5 49t20.5 62q-14 9 -37 9.5t-36 7.5q-14 7 -49 15t-52 19q-9 0 -39.5 -0.5t-46.5 -1.5t-39 -6.5t-39 -16.5q-50 -35 -66 -12q-4 2 -3.5 25.5t0.5 25.5q-6 13 -26.5 17t-24.5 7 q2 22 -2 41t-16.5 28t-38.5 -20q-23 -25 -42 4q-19 28 -8 58q6 16 22 22q6 -1 26 -1.5t33.5 -4t19.5 -13.5q12 -19 32 -37.5t34 -27.5l14 -8q0 3 9.5 39.5t5.5 57.5q-4 23 14.5 44.5t22.5 31.5q5 14 10 35t8.5 31t15.5 22.5t34 21.5q-6 18 10 37q8 0 23.5 -1.5t24.5 -1.5 t20.5 4.5t20.5 15.5q-10 23 -30.5 42.5t-38 30t-49 26.5t-43.5 23q11 41 1 44q31 -13 58.5 -14.5t39.5 3.5l11 4q6 36 -17 53.5t-64 28.5t-56 23q-19 -3 -37 0zM613 994q0 -18 8 -42.5t16.5 -44t9.5 -23.5q-9 2 -31 5t-36 5t-32 8t-30 14q3 12 16 30t16 25q10 -10 18.5 -10 t14 6t14.5 14.5t16 12.5z" />
+<glyph unicode="&#xe137;" horiz-adv-x="1220" d="M100 1196h1000q41 0 70.5 -29.5t29.5 -70.5v-100q0 -41 -29.5 -70.5t-70.5 -29.5h-1000q-41 0 -70.5 29.5t-29.5 70.5v100q0 41 29.5 70.5t70.5 29.5zM1100 1096h-200v-100h200v100zM100 796h1000q41 0 70.5 -29.5t29.5 -70.5v-100q0 -41 -29.5 -70.5t-70.5 -29.5h-1000 q-41 0 -70.5 29.5t-29.5 70.5v100q0 41 29.5 70.5t70.5 29.5zM1100 696h-500v-100h500v100zM100 396h1000q41 0 70.5 -29.5t29.5 -70.5v-100q0 -41 -29.5 -70.5t-70.5 -29.5h-1000q-41 0 -70.5 29.5t-29.5 70.5v100q0 41 29.5 70.5t70.5 29.5zM1100 296h-300v-100h300v100z " />
+<glyph unicode="&#xe138;" d="M1100 1200v-100h-1000v100h1000zM150 1000h900l-350 -500v-300l-200 -200v500z" />
+<glyph unicode="&#xe140;" d="M329 729l142 142l-200 200l129 129h-400v-400l129 129zM1200 1200v-400l-129 129l-200 -200l-142 142l200 200l-129 129h400zM271 129l129 -129h-400v400l129 -129l200 200l142 -142zM1071 271l129 129v-400h-400l129 129l-200 200l142 142z" />
+<glyph unicode="&#xe141;" d="M596 1192q162 0 299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299t80 299t217 217t299 80zM596 1010q-171 0 -292.5 -121.5t-121.5 -292.5q0 -172 121.5 -293t292.5 -121t292.5 121t121.5 293q0 171 -121.5 292.5t-292.5 121.5zM455 905 q22 0 38 -16t16 -39t-16 -39t-38 -16q-23 0 -39 16.5t-16 38.5t16 38.5t39 16.5zM708 821l1 1q-9 14 -9 28q0 22 16 38.5t39 16.5q22 0 38 -16t16 -39t-16 -39t-38 -16q-14 0 -29 10l-55 -145q17 -22 17 -51q0 -36 -25.5 -61.5t-61.5 -25.5t-61.5 25.5t-25.5 61.5 q0 32 20.5 56.5t51.5 29.5zM855 709q23 0 38.5 -15.5t15.5 -38.5t-16 -39t-38 -16q-23 0 -39 16t-16 39q0 22 16 38t39 16zM345 709q23 0 39 -16t16 -38q0 -23 -16 -39t-39 -16q-22 0 -38 16t-16 39t15.5 38.5t38.5 15.5z" />
+<glyph unicode="&#xe143;" d="M649 54l-16 22q-90 125 -293 323q-71 70 -104.5 105.5t-77 89.5t-61 99t-17.5 91q0 131 98.5 229.5t230.5 98.5q143 0 241 -129q103 129 246 129q129 0 226 -98.5t97 -229.5q0 -46 -17.5 -91t-61 -99t-77 -89.5t-104.5 -105.5q-203 -198 -293 -323zM844 524l12 12 q64 62 97.5 97t64.5 79t31 72q0 71 -48 119t-105 48q-74 0 -132 -82l-118 -171l-114 174q-51 79 -123 79q-60 0 -109.5 -49t-49.5 -118q0 -27 30.5 -70t61.5 -75.5t95 -94.5l22 -22q93 -90 190 -201q82 92 195 203z" />
+<glyph unicode="&#xe144;" d="M476 406l19 -17l105 105l-212 212l389 389l247 -247l-95 -96l18 -18q46 -46 77 -99l29 29q35 35 62.5 88t27.5 96q0 93 -66 159l-141 141q-66 66 -159 66q-95 0 -159 -66l-283 -283q-66 -64 -66 -159q0 -93 66 -159zM123 193l141 -141q66 -66 159 -66q95 0 159 66 l283 283q66 66 66 159t-66 159l-141 141q-12 12 -19 17l-105 -105l212 -212l-389 -389l-247 248l95 95l-18 18q-46 45 -75 101l-55 -55q-66 -66 -66 -159q0 -94 66 -160z" />
+<glyph unicode="&#xe145;" d="M200 100v953q0 21 30 46t81 48t129 38t163 15t162 -15t127 -38t79 -48t29 -46v-953q0 -41 -29.5 -70.5t-70.5 -29.5h-600q-41 0 -70.5 29.5t-29.5 70.5zM900 1000h-600v-700h600v700zM600 46q43 0 73.5 30.5t30.5 73.5t-30.5 73.5t-73.5 30.5t-73.5 -30.5t-30.5 -73.5 t30.5 -73.5t73.5 -30.5z" />
+<glyph unicode="&#xe148;" d="M700 1029v-307l64 -14q34 -7 64 -16.5t70 -31.5t67.5 -52t47.5 -80.5t20 -112.5q0 -139 -89 -224t-244 -96v-77h-100v78q-152 17 -237 104q-40 40 -52.5 93.5t-15.5 139.5h139q5 -77 48.5 -126.5t117.5 -64.5v335l-27 7q-46 14 -79 26.5t-72 36t-62.5 52t-40 72.5 t-16.5 99q0 92 44 159.5t109 101t144 40.5v78h100v-79q38 -4 72.5 -13.5t75.5 -31.5t71 -53.5t51.5 -84t24.5 -118.5h-159q-8 72 -35 109.5t-101 50.5zM600 755v274q-61 -8 -97.5 -37.5t-36.5 -102.5q0 -29 8 -51t16.5 -34t29.5 -22.5t31 -13.5t38 -10q7 -2 11 -3zM700 548 v-311q170 18 170 151q0 64 -44 99.5t-126 60.5z" />
+<glyph unicode="&#xe149;" d="M866 300l50 -147q-41 -25 -80.5 -36.5t-59 -13t-61.5 -1.5q-23 0 -128 33t-155 29q-39 -4 -82 -17t-66 -25l-24 -11l-55 145l16.5 11t15.5 10t13.5 9.5t14.5 12t14.5 14t17.5 18.5q48 55 54 126.5t-30 142.5h-221v100h166q-24 49 -44 104q-10 26 -14.5 55.5t-3 72.5 t25 90t68.5 87q97 88 263 88q129 0 230 -89t101 -208h-153q0 52 -34 89.5t-74 51.5t-76 14q-37 0 -79 -14.5t-62 -35.5q-41 -44 -41 -101q0 -11 2.5 -24.5t5.5 -24t9.5 -26.5t10.5 -25t14 -27.5t14 -25.5t15.5 -27t13.5 -24h242v-100h-197q8 -50 -2.5 -115t-31.5 -94 q-41 -59 -99 -113q35 11 84 18t70 7q32 1 102 -16t104 -17q76 0 136 30z" />
+<glyph unicode="&#xe150;" d="M300 0l298 300h-198v900h-200v-900h-198zM900 1200l298 -300h-198v-900h-200v900h-198z" />
+<glyph unicode="&#xe151;" d="M400 300h198l-298 -300l-298 300h198v900h200v-900zM1000 1200v-500h-100v100h-100v-100h-100v500h300zM901 1100h-100v-200h100v200zM700 500h300v-200h-99v-100h-100v100h99v100h-200v100zM800 100h200v-100h-300v200h100v-100z" />
+<glyph unicode="&#xe152;" d="M400 300h198l-298 -300l-298 300h198v900h200v-900zM1000 1200v-200h-99v-100h-100v100h99v100h-200v100h300zM800 800h200v-100h-300v200h100v-100zM700 500h300v-500h-100v100h-100v-100h-100v500zM801 200h100v200h-100v-200z" />
+<glyph unicode="&#xe153;" d="M300 0l298 300h-198v900h-200v-900h-198zM900 1100h-100v100h200v-500h-100v400zM1100 500v-500h-100v100h-200v400h300zM1001 400h-100v-200h100v200z" />
+<glyph unicode="&#xe154;" d="M300 0l298 300h-198v900h-200v-900h-198zM1100 1200v-500h-100v100h-200v400h300zM1001 1100h-100v-200h100v200zM900 400h-100v100h200v-500h-100v400z" />
+<glyph unicode="&#xe155;" d="M300 0l298 300h-198v900h-200v-900h-198zM900 1000h-200v200h200v-200zM1000 700h-300v200h300v-200zM1100 400h-400v200h400v-200zM1200 100h-500v200h500v-200z" />
+<glyph unicode="&#xe156;" d="M300 0l298 300h-198v900h-200v-900h-198zM1200 1000h-500v200h500v-200zM1100 700h-400v200h400v-200zM1000 400h-300v200h300v-200zM900 100h-200v200h200v-200z" />
+<glyph unicode="&#xe157;" d="M400 1100h300q162 0 281 -118.5t119 -281.5v-300q0 -165 -118.5 -282.5t-281.5 -117.5h-300q-165 0 -282.5 117.5t-117.5 282.5v300q0 165 117.5 282.5t282.5 117.5zM800 900h-500q-41 0 -70.5 -29.5t-29.5 -70.5v-500q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5 t29.5 70.5v500q0 41 -29.5 70.5t-70.5 29.5z" />
+<glyph unicode="&#xe158;" d="M700 0h-300q-163 0 -281.5 117.5t-118.5 282.5v300q0 163 119 281.5t281 118.5h300q165 0 282.5 -117.5t117.5 -282.5v-300q0 -165 -117.5 -282.5t-282.5 -117.5zM800 900h-500q-41 0 -70.5 -29.5t-29.5 -70.5v-500q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5 t29.5 70.5v500q0 41 -29.5 70.5t-70.5 29.5zM400 800v-500l333 250z" />
+<glyph unicode="&#xe159;" d="M0 400v300q0 163 117.5 281.5t282.5 118.5h300q163 0 281.5 -119t118.5 -281v-300q0 -165 -117.5 -282.5t-282.5 -117.5h-300q-165 0 -282.5 117.5t-117.5 282.5zM900 300v500q0 41 -29.5 70.5t-70.5 29.5h-500q-41 0 -70.5 -29.5t-29.5 -70.5v-500q0 -41 29.5 -70.5 t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5zM800 700h-500l250 -333z" />
+<glyph unicode="&#xe160;" d="M1100 700v-300q0 -162 -118.5 -281t-281.5 -119h-300q-165 0 -282.5 118.5t-117.5 281.5v300q0 165 117.5 282.5t282.5 117.5h300q165 0 282.5 -117.5t117.5 -282.5zM900 300v500q0 41 -29.5 70.5t-70.5 29.5h-500q-41 0 -70.5 -29.5t-29.5 -70.5v-500q0 -41 29.5 -70.5 t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5zM550 733l-250 -333h500z" />
+<glyph unicode="&#xe161;" d="M500 1100h400q165 0 282.5 -117.5t117.5 -282.5v-300q0 -165 -117.5 -282.5t-282.5 -117.5h-400v200h500q41 0 70.5 29.5t29.5 70.5v500q0 41 -29.5 70.5t-70.5 29.5h-500v200zM700 550l-400 -350v200h-300v300h300v200z" />
+<glyph unicode="&#xe162;" d="M403 2l9 -1q13 0 26 16l538 630q15 19 6 36q-8 18 -32 16h-300q1 4 78 219.5t79 227.5q2 17 -6 27l-8 8h-9q-16 0 -25 -15q-4 -5 -98.5 -111.5t-228 -257t-209.5 -238.5q-17 -19 -7 -40q10 -19 32 -19h302q-155 -438 -160 -458q-5 -21 4 -32z" />
+<glyph unicode="&#xe163;" d="M800 200h-500q-41 0 -70.5 29.5t-29.5 70.5v500q0 41 29.5 70.5t70.5 29.5h500v185q-14 4 -114 7.5t-193 5.5l-93 2q-165 0 -282.5 -117.5t-117.5 -282.5v-300q0 -165 117.5 -282.5t282.5 -117.5h300q47 0 100 15v185zM900 200v200h-300v300h300v200l400 -350z" />
+<glyph unicode="&#xe164;" d="M1200 700l-149 149l-342 -353l-213 213l353 342l-149 149h500v-500zM1022 571l-122 -123v-148q0 -41 -29.5 -70.5t-70.5 -29.5h-500q-41 0 -70.5 29.5t-29.5 70.5v500q0 41 29.5 70.5t70.5 29.5h156l118 122l-74 78h-100q-165 0 -282.5 -117.5t-117.5 -282.5v-300 q0 -165 117.5 -282.5t282.5 -117.5h300q163 0 281.5 117.5t118.5 282.5v98z" />
+<glyph unicode="&#xe165;" d="M600 1196q162 0 299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299t80 299t217 217t299 80zM600 1014q-171 0 -292.5 -121.5t-121.5 -292.5t121.5 -292.5t292.5 -121.5t292.5 121.5t121.5 292.5t-121.5 292.5t-292.5 121.5zM600 794 q80 0 137 -57t57 -137t-57 -137t-137 -57t-137 57t-57 137t57 137t137 57z" />
+<glyph unicode="&#xe166;" d="M700 800v400h-300v-400h-300l445 -500l450 500h-295zM25 300h1048q11 0 19 -7.5t8 -17.5v-275h-1100v275q0 11 7 18t18 7zM1000 200h-100v-50h100v50z" />
+<glyph unicode="&#xe167;" d="M400 700v-300h300v300h295l-445 500l-450 -500h300zM25 300h1048q11 0 19 -7.5t8 -17.5v-275h-1100v275q0 11 7 18t18 7zM1000 200h-100v-50h100v50z" />
+<glyph unicode="&#xe168;" d="M405 400l596 596l-154 155l-442 -442l-150 151l-155 -155zM25 300h1048q11 0 19 -7.5t8 -17.5v-275h-1100v275q0 11 7 18t18 7zM1000 200h-100v-50h100v50z" />
+<glyph unicode="&#xe169;" d="M409 1103l-97 97l-212 -212l97 -98zM650 861l-149 149l-212 -212l149 -149l-238 -248h700v699zM25 300h1048q11 0 19 -7.5t8 -17.5v-275h-1100v275q0 11 7 18t18 7zM1000 200h-100v-50h100v50z" />
+<glyph unicode="&#xe170;" d="M539 950l-149 -149l212 -212l149 148l248 -237v700h-699zM297 709l-97 -97l212 -212l98 97zM25 300h1048q11 0 19 -7.5t8 -17.5v-275h-1100v275q0 11 7 18t18 7zM1000 200h-100v-50h100v50z" />
+<glyph unicode="&#xe171;" d="M1200 1199v-1079l-475 272l-310 -393v416h-392zM1166 1148l-672 -712v-226z" />
+<glyph unicode="&#xe172;" d="M1100 1000v-850q0 -21 -15 -35.5t-35 -14.5h-150v400h-700v-400h-150q-21 0 -35.5 14.5t-14.5 35.5v1000q0 20 14.5 35t35.5 15h250v-300h500v300h100zM700 1200h-100v-200h100v200z" />
+<glyph unicode="&#xe173;" d="M578 500h-378v-400h-150q-21 0 -35.5 14.5t-14.5 35.5v1000q0 20 14.5 35t35.5 15h250v-300h500v300h100l200 -200v-218l-276 -275l-120 120zM700 1200h-100v-200h100v200zM1300 538l-475 -476l-244 244l123 123l120 -120l353 352z" />
+<glyph unicode="&#xe174;" d="M529 500h-329v-400h-150q-21 0 -35.5 14.5t-14.5 35.5v1000q0 20 14.5 35t35.5 15h250v-300h500v300h100l200 -200v-269l-103 -103l-170 170zM700 1200h-100v-200h100v200zM1167 6l-170 170l-170 -170l-127 127l170 170l-170 170l127 127l170 -170l170 170l127 -128 l-170 -169l170 -170z" />
+<glyph unicode="&#xe175;" d="M700 500h-500v-400h-150q-21 0 -35.5 14.5t-14.5 35.5v1000q0 20 14.5 35t35.5 15h250v-300h500v300h100l200 -200v-300h-400v-200zM700 1000h-100v200h100v-200zM1000 600h-200v-300h-200l300 -300l300 300h-200v300z" />
+<glyph unicode="&#xe176;" d="M602 500h-402v-400h-150q-21 0 -35.5 14.5t-14.5 35.5v1000q0 20 14.5 35t35.5 15h250v-300h500v300h100l200 -200v-402l-200 200zM700 1000h-100v200h100v-200zM1000 300h200l-300 300l-300 -300h200v-300h200v300z" />
+<glyph unicode="&#xe177;" d="M1200 900v150q0 21 -14.5 35.5t-35.5 14.5h-1100q-21 0 -35.5 -14.5t-14.5 -35.5v-150h1200zM0 800v-550q0 -21 14.5 -35.5t35.5 -14.5h1100q21 0 35.5 14.5t14.5 35.5v550h-1200zM100 500h400v-200h-400v200z" />
+<glyph unicode="&#xe178;" d="M500 1000h400v198l300 -298l-300 -298v198h-400v200zM100 800v200h100v-200h-100zM400 800h-100v200h100v-200zM700 300h-400v-198l-300 298l300 298v-198h400v-200zM800 500h100v-200h-100v200zM1000 500v-200h100v200h-100z" />
+<glyph unicode="&#xe179;" d="M1200 50v1106q0 31 -18 40.5t-44 -7.5l-276 -117q-25 -16 -43.5 -50.5t-18.5 -65.5v-359q0 -29 10.5 -55.5t25 -43t29 -28.5t25.5 -18l10 -5v-397q0 -21 14.5 -35.5t35.5 -14.5h200q21 0 35.5 14.5t14.5 35.5zM550 1200l50 -100v-400l-100 -203v-447q0 -21 -14.5 -35.5 t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5v447l-100 203v400l50 100l50 -100v-300h100v300l50 100l50 -100v-300h100v300z" />
+<glyph unicode="&#xe180;" d="M1100 106v888q0 22 25 34.5t50 13.5l25 2v56h-400v-56q75 0 87.5 -6t12.5 -44v-394h-500v394q0 38 12.5 44t87.5 6v56h-400v-56q4 0 11 -0.5t24 -3t30 -7t24 -15t11 -24.5v-888q0 -22 -25 -34.5t-50 -13.5l-25 -2v-56h400v56q-75 0 -87.5 6t-12.5 44v394h500v-394 q0 -38 -12.5 -44t-87.5 -6v-56h400v56q-4 0 -11 0.5t-24 3t-30 7t-24 15t-11 24.5z" />
+<glyph unicode="&#xe181;" d="M675 1000l-100 100h-375l-100 -100h400l200 -200v-98l295 98h105v200h-425zM500 300v500q0 41 -29.5 70.5t-70.5 29.5h-300q-41 0 -70.5 -29.5t-29.5 -70.5v-500q0 -41 29.5 -70.5t70.5 -29.5h300q41 0 70.5 29.5t29.5 70.5zM100 800h300v-200h-300v200zM700 565l400 133 v-163l-400 -133v163zM100 500h300v-200h-300v200zM805 300l295 98v-298h-425l-100 -100h-375l-100 100h400l200 200h105z" />
+<glyph unicode="&#xe182;" d="M179 1169l-162 -162q-1 -11 -0.5 -32.5t16 -90t46.5 -140t104 -177.5t175 -208q103 -103 207.5 -176t180 -103.5t137 -47t92.5 -16.5l31 1l163 162q16 17 13 40.5t-22 37.5l-192 136q-19 14 -45 12t-42 -19l-119 -118q-143 103 -267 227q-126 126 -227 268l118 118 q17 17 20 41.5t-11 44.5l-139 194q-14 19 -36.5 22t-40.5 -14z" />
+<glyph unicode="&#xe183;" d="M1200 712v200q-6 8 -19 20.5t-63 45t-112 57t-171 45t-235 20.5q-92 0 -175 -10.5t-141.5 -27t-108.5 -36.5t-81.5 -40t-53.5 -36.5t-31 -27.5l-9 -10v-200q0 -21 14.5 -33.5t34.5 -8.5l202 33q20 4 34.5 21t14.5 38v146q141 24 300 24t300 -24v-146q0 -21 14.5 -38 t34.5 -21l202 -33q20 -4 34.5 8.5t14.5 33.5zM800 650l365 -303q14 -14 24.5 -39.5t10.5 -45.5v-212q0 -21 -15 -35.5t-35 -14.5h-1100q-21 0 -35.5 14.5t-14.5 35.5v212q0 20 10.5 45.5t24.5 39.5l365 303v50q0 4 1 10.5t12 22.5t30 28.5t60 23t97 10.5t97 -10t60 -23.5 t30 -27.5t12 -24l1 -10v-50z" />
+<glyph unicode="&#xe184;" d="M175 200h950l-125 150v250l100 100v400h-100v-200h-100v200h-200v-200h-100v200h-200v-200h-100v200h-100v-400l100 -100v-250zM1200 100v-100h-1100v100h1100z" />
+<glyph unicode="&#xe185;" d="M600 1100h100q41 0 70.5 -29.5t29.5 -70.5v-1000h-300v1000q0 41 29.5 70.5t70.5 29.5zM1000 800h100q41 0 70.5 -29.5t29.5 -70.5v-700h-300v700q0 41 29.5 70.5t70.5 29.5zM400 0v400q0 41 -29.5 70.5t-70.5 29.5h-100q-41 0 -70.5 -29.5t-29.5 -70.5v-400h300z" />
+<glyph unicode="&#xe186;" d="M1200 800v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212v500q0 124 88 212t212 88h700q124 0 212 -88t88 -212zM1000 900h-900v-700h900v700zM200 800v-300h200v-100h-200v-100h300v300h-200v100h200v100h-300zM800 800h-200v-500h200v100h100v300h-100 v100zM800 700v-300h-100v300h100z" />
+<glyph unicode="&#xe187;" d="M1200 800v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212v500q0 124 88 212t212 88h700q124 0 212 -88t88 -212zM1000 900h-900v-700h900v700zM400 600h-100v200h-100v-500h100v200h100v-200h100v500h-100v-200zM800 800h-200v-500h200v100h100v300h-100 v100zM800 700v-300h-100v300h100z" />
+<glyph unicode="&#xe188;" d="M1200 800v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212v500q0 124 88 212t212 88h700q124 0 212 -88t88 -212zM1000 900h-900v-700h900v700zM200 800v-500h300v100h-200v300h200v100h-300zM600 800v-500h300v100h-200v300h200v100h-300z" />
+<glyph unicode="&#xe189;" d="M1200 800v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212v500q0 124 88 212t212 88h700q124 0 212 -88t88 -212zM1000 900h-900v-700h900v700zM500 700l-300 -150l300 -150v300zM600 400l300 150l-300 150v-300z" />
+<glyph unicode="&#xe190;" d="M1200 800v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212v500q0 124 88 212t212 88h700q124 0 212 -88t88 -212zM1000 900h-900v-700h900v700zM900 800v-500h-700v500h700zM300 400h130q41 0 68 42t27 107t-28.5 108t-66.5 43h-130v-300zM800 700h-130 q-38 0 -66.5 -43t-28.5 -108t27 -107t68 -42h130v300z" />
+<glyph unicode="&#xe191;" d="M1200 800v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212v500q0 124 88 212t212 88h700q124 0 212 -88t88 -212zM1000 900h-900v-700h900v700zM200 800v-300h200v-100h-200v-100h300v300h-200v100h200v100h-300zM800 300h100v500h-200v-100h100v-400z M601 300h100v100h-100v-100z" />
+<glyph unicode="&#xe192;" d="M1200 800v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212v500q0 124 88 212t212 88h700q124 0 212 -88t88 -212zM1000 900h-900v-700h900v700zM300 700v100h-100v-500h300v400h-200zM800 300h100v500h-200v-100h100v-400zM401 400h-100v200h100v-200z M601 300h100v100h-100v-100z" />
+<glyph unicode="&#xe193;" d="M200 1100h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212v500q0 124 88 212t212 88zM1000 900h-900v-700h900v700zM400 700h-200v100h300v-300h-99v-100h-100v100h99v200zM800 700h-100v100h200v-500h-100v400zM201 400h100v-100 h-100v100zM701 300h-100v100h100v-100z" />
+<glyph unicode="&#xe194;" d="M600 1196q162 0 299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299t80 299t217 217t299 80zM600 1014q-171 0 -292.5 -121.5t-121.5 -292.5t121.5 -292.5t292.5 -121.5t292.5 121.5t121.5 292.5t-121.5 292.5t-292.5 121.5zM800 700h-300 v-200h300v-100h-300l-100 100v200l100 100h300v-100z" />
+<glyph unicode="&#xe195;" d="M596 1196q162 0 299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299t80 299t217 217t299 80zM596 1014q-171 0 -292.5 -121.5t-121.5 -292.5t121.5 -292.5t292.5 -121.5t292.5 121.5t121.5 292.5t-121.5 292.5t-292.5 121.5zM800 700v-100 h-100v100h-200v-100h200v-100h-200v-100h-100v400h300zM800 400h-100v100h100v-100z" />
+<glyph unicode="&#xe197;" d="M800 300h128q120 0 205 86t85 208q0 120 -85 206.5t-205 86.5q-46 0 -90 -14q-44 97 -134.5 156.5t-200.5 59.5q-152 0 -260 -107.5t-108 -260.5q0 -25 2 -37q-66 -14 -108.5 -67.5t-42.5 -122.5q0 -80 56.5 -137t135.5 -57h222v300h400v-300zM700 200h200l-300 -300 l-300 300h200v300h200v-300z" />
+<glyph unicode="&#xe198;" d="M600 714l403 -403q94 26 154.5 104t60.5 178q0 121 -85 207.5t-205 86.5q-46 0 -90 -14q-44 97 -134.5 156.5t-200.5 59.5q-152 0 -260 -107.5t-108 -260.5q0 -25 2 -37q-66 -14 -108.5 -67.5t-42.5 -122.5q0 -80 56.5 -137t135.5 -57h8zM700 -100h-200v300h-200l300 300 l300 -300h-200v-300z" />
+<glyph unicode="&#xe199;" d="M700 200h400l-270 300h170l-270 300h170l-300 333l-300 -333h170l-270 -300h170l-270 -300h400v-155l-75 -45h350l-75 45v155z" />
+<glyph unicode="&#xe200;" d="M700 45v306q46 -30 100 -30q74 0 126.5 52.5t52.5 126.5q0 24 -9 55q50 32 79.5 83t29.5 112q0 90 -61.5 155.5t-150.5 71.5q-26 89 -99.5 145.5t-167.5 56.5q-116 0 -197.5 -81.5t-81.5 -197.5q0 -4 1 -12t1 -11q-14 2 -23 2q-74 0 -126.5 -52.5t-52.5 -126.5 q0 -53 28.5 -97t75.5 -65q-4 -16 -4 -38q0 -74 52.5 -126.5t126.5 -52.5q56 0 100 30v-306l-75 -45h350z" />
+<glyph unicode="&#x1f4bc;" d="M800 1000h300q41 0 70.5 -29.5t29.5 -70.5v-400h-500v100h-200v-100h-500v400q0 41 29.5 70.5t70.5 29.5h300v100q0 41 29.5 70.5t70.5 29.5h200q41 0 70.5 -29.5t29.5 -70.5v-100zM500 1000h200v100h-200v-100zM1200 400v-200q0 -41 -29.5 -70.5t-70.5 -29.5h-1000 q-41 0 -70.5 29.5t-29.5 70.5v200h1200z" />
+<glyph unicode="&#x1f4c5;" d="M1100 900v150q0 21 -14.5 35.5t-35.5 14.5h-150v100h-100v-100h-500v100h-100v-100h-150q-21 0 -35.5 -14.5t-14.5 -35.5v-150h1100zM0 800v-750q0 -20 14.5 -35t35.5 -15h1000q21 0 35.5 15t14.5 35v750h-1100zM100 600h100v-100h-100v100zM300 600h100v-100h-100v100z M500 600h100v-100h-100v100zM700 600h100v-100h-100v100zM900 600h100v-100h-100v100zM100 400h100v-100h-100v100zM300 400h100v-100h-100v100zM500 400h100v-100h-100v100zM700 400h100v-100h-100v100zM900 400h100v-100h-100v100zM100 200h100v-100h-100v100zM300 200 h100v-100h-100v100zM500 200h100v-100h-100v100zM700 200h100v-100h-100v100zM900 200h100v-100h-100v100z" />
+<glyph unicode="&#x1f4cc;" d="M902 1185l283 -282q15 -15 15 -36t-15 -35q-14 -15 -35 -15t-35 15l-36 35l-279 -267v-300l-212 210l-208 -207l-380 -303l303 380l207 208l-210 212h300l267 279l-35 36q-15 14 -15 35t15 35q14 15 35 15t35 -15z" />
+<glyph unicode="&#x1f4ce;" d="M518 119l69 -60l517 511q67 67 95 157t11 183q-16 87 -67 154t-130 103q-69 33 -152 33q-107 0 -197 -55q-40 -24 -111 -95l-512 -512q-68 -68 -81 -163t35 -173q35 -57 94 -89t129 -32q63 0 119 28q33 16 65 40.5t52.5 45.5t59.5 64q40 44 57 61l394 394q35 35 47 84 t-3 96q-27 87 -117 104q-20 2 -29 2q-46 0 -79.5 -17t-67.5 -51l-388 -396l-7 -7l69 -67l377 373q20 22 39 38q23 23 50 23q38 0 53 -36q16 -39 -20 -75l-547 -547q-52 -52 -125 -52q-55 0 -100 33t-54 96q-5 35 2.5 66t31.5 63t42 50t56 54q24 21 44 41l348 348 q52 52 82.5 79.5t84 54t107.5 26.5q25 0 48 -4q95 -17 154 -94.5t51 -175.5q-7 -101 -98 -192l-252 -249l-253 -256z" />
+<glyph unicode="&#x1f4f7;" d="M1200 200v600q0 41 -29.5 70.5t-70.5 29.5h-150q-4 8 -11.5 21.5t-33 48t-53 61t-69 48t-83.5 21.5h-200q-41 0 -82 -20.5t-70 -50t-52 -59t-34 -50.5l-12 -20h-150q-41 0 -70.5 -29.5t-29.5 -70.5v-600q0 -41 29.5 -70.5t70.5 -29.5h1000q41 0 70.5 29.5t29.5 70.5z M1000 700h-100v100h100v-100zM844 500q0 -100 -72 -172t-172 -72t-172 72t-72 172t72 172t172 72t172 -72t72 -172zM706 500q0 44 -31 75t-75 31t-75 -31t-31 -75t31 -75t75 -31t75 31t31 75z" />
+<glyph unicode="&#x1f512;" d="M900 800h100q41 0 70.5 -29.5t29.5 -70.5v-600q0 -41 -29.5 -70.5t-70.5 -29.5h-900q-41 0 -70.5 29.5t-29.5 70.5v600q0 41 29.5 70.5t70.5 29.5h100v200q0 82 59 141t141 59h300q82 0 141 -59t59 -141v-200zM400 800h300v150q0 21 -14.5 35.5t-35.5 14.5h-200 q-21 0 -35.5 -14.5t-14.5 -35.5v-150z" />
+<glyph unicode="&#x1f514;" d="M1062 400h17q20 0 33.5 -14.5t13.5 -35.5q0 -20 -13 -40t-31 -27q-22 -9 -63 -23t-167.5 -37t-251.5 -23t-245.5 20.5t-178.5 41.5l-58 20q-18 7 -31 27.5t-13 40.5q0 21 13.5 35.5t33.5 14.5h17l118 173l63 327q15 77 76 140t144 83l-18 32q-6 19 3 32t29 13h94 q20 0 29 -10.5t3 -29.5l-18 -37q83 -19 144 -82.5t76 -140.5l63 -327zM600 104q-54 0 -103 6q12 -49 40 -79.5t63 -30.5t63 30.5t39 79.5q-48 -6 -102 -6z" />
+<glyph unicode="&#x1f516;" d="M200 0l450 444l450 -443v1150q0 20 -14.5 35t-35.5 15h-800q-21 0 -35.5 -15t-14.5 -35v-1151z" />
+<glyph unicode="&#x1f525;" d="M400 755q2 -12 8 -41.5t8 -43t6 -39.5t3.5 -39.5t-1 -33.5t-6 -31.5t-13.5 -24t-21 -20.5t-31 -12q-38 -10 -67 13t-40.5 61.5t-15 81.5t10.5 75q-52 -46 -83.5 -101t-39 -107t-7.5 -85t5 -63q9 -56 44 -119.5t105 -108.5q31 -21 64 -16t62 23.5t57 49.5t48 61.5t35 60.5 q32 66 39 184.5t-13 157.5q79 -80 122 -164t26 -184q-5 -33 -20.5 -69.5t-37.5 -80.5q-10 -19 -14.5 -29t-12 -26t-9 -23.5t-3 -19t2.5 -15.5t11 -9.5t19.5 -5t30.5 2.5t42 8q57 20 91 34t87.5 44.5t87 64t65.5 88.5t47 122q38 172 -44.5 341.5t-246.5 278.5q22 -44 43 -129 q39 -159 -32 -154q-15 2 -33 9q-79 33 -120.5 100t-44 175.5t48.5 257.5q-13 -8 -34 -23.5t-72.5 -66.5t-88.5 -105.5t-60 -138t-8 -166.5z" />
+<glyph unicode="&#x1f527;" d="M948 778l251 126q13 -175 -151 -267q-123 -70 -253 -23l-596 -596q-15 -16 -36.5 -16t-36.5 16l-111 110q-15 15 -15 36.5t15 37.5l600 599q-33 101 6 201.5t135 154.5q164 92 306 -9l-259 -138z" />
+</font>
+</defs></svg> 
\ No newline at end of file
diff --git a/third-party/bootstrap-3.0.0/fonts/glyphicons-halflings-regular.ttf b/third-party/bootstrap-3.0.0/fonts/glyphicons-halflings-regular.ttf
new file mode 100644 (file)
index 0000000..be784dc
Binary files /dev/null and b/third-party/bootstrap-3.0.0/fonts/glyphicons-halflings-regular.ttf differ
diff --git a/third-party/bootstrap-3.0.0/fonts/glyphicons-halflings-regular.woff b/third-party/bootstrap-3.0.0/fonts/glyphicons-halflings-regular.woff
new file mode 100644 (file)
index 0000000..2cc3e48
Binary files /dev/null and b/third-party/bootstrap-3.0.0/fonts/glyphicons-halflings-regular.woff differ
diff --git a/third-party/bootstrap-3.0.0/js/bootstrap.js b/third-party/bootstrap-3.0.0/js/bootstrap.js
new file mode 100644 (file)
index 0000000..2c64257
--- /dev/null
@@ -0,0 +1,1999 @@
+/**
+* bootstrap.js v3.0.0 by @fat and @mdo
+* Copyright 2013 Twitter Inc.
+* http://www.apache.org/licenses/LICENSE-2.0
+*/
+if (!jQuery) { throw new Error("Bootstrap requires jQuery") }
+
+/* ========================================================================
+ * Bootstrap: transition.js v3.0.0
+ * http://twbs.github.com/bootstrap/javascript.html#transitions
+ * ========================================================================
+ * Copyright 2013 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";
+
+  // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
+  // ============================================================
+
+  function transitionEnd() {
+    var el = document.createElement('bootstrap')
+
+    var transEndEventNames = {
+      'WebkitTransition' : 'webkitTransitionEnd'
+    , 'MozTransition'    : 'transitionend'
+    , 'OTransition'      : 'oTransitionEnd otransitionend'
+    , 'transition'       : 'transitionend'
+    }
+
+    for (var name in transEndEventNames) {
+      if (el.style[name] !== undefined) {
+        return { end: transEndEventNames[name] }
+      }
+    }
+  }
+
+  // http://blog.alexmaccaw.com/css-transitions
+  $.fn.emulateTransitionEnd = function (duration) {
+    var called = false, $el = this
+    $(this).one($.support.transition.end, function () { called = true })
+    var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
+    setTimeout(callback, duration)
+    return this
+  }
+
+  $(function () {
+    $.support.transition = transitionEnd()
+  })
+
+}(window.jQuery);
+
+/* ========================================================================
+ * Bootstrap: alert.js v3.0.0
+ * http://twbs.github.com/bootstrap/javascript.html#alerts
+ * ========================================================================
+ * Copyright 2013 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";
+
+  // ALERT CLASS DEFINITION
+  // ======================
+
+  var dismiss = '[data-dismiss="alert"]'
+  var Alert   = function (el) {
+    $(el).on('click', dismiss, this.close)
+  }
+
+  Alert.prototype.close = function (e) {
+    var $this    = $(this)
+    var selector = $this.attr('data-target')
+
+    if (!selector) {
+      selector = $this.attr('href')
+      selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
+    }
+
+    var $parent = $(selector)
+
+    if (e) e.preventDefault()
+
+    if (!$parent.length) {
+      $parent = $this.hasClass('alert') ? $this : $this.parent()
+    }
+
+    $parent.trigger(e = $.Event('close.bs.alert'))
+
+    if (e.isDefaultPrevented()) return
+
+    $parent.removeClass('in')
+
+    function removeElement() {
+      $parent.trigger('closed.bs.alert').remove()
+    }
+
+    $.support.transition && $parent.hasClass('fade') ?
+      $parent
+        .one($.support.transition.end, removeElement)
+        .emulateTransitionEnd(150) :
+      removeElement()
+  }
+
+
+  // ALERT PLUGIN DEFINITION
+  // =======================
+
+  var old = $.fn.alert
+
+  $.fn.alert = function (option) {
+    return this.each(function () {
+      var $this = $(this)
+      var data  = $this.data('bs.alert')
+
+      if (!data) $this.data('bs.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.bs.alert.data-api', dismiss, Alert.prototype.close)
+
+}(window.jQuery);
+
+/* ========================================================================
+ * Bootstrap: button.js v3.0.0
+ * http://twbs.github.com/bootstrap/javascript.html#buttons
+ * ========================================================================
+ * Copyright 2013 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";
+
+  // BUTTON PUBLIC CLASS DEFINITION
+  // ==============================
+
+  var Button = function (element, options) {
+    this.$element = $(element)
+    this.options  = $.extend({}, Button.DEFAULTS, options)
+  }
+
+  Button.DEFAULTS = {
+    loadingText: 'loading...'
+  }
+
+  Button.prototype.setState = function (state) {
+    var d    = 'disabled'
+    var $el  = this.$element
+    var val  = $el.is('input') ? 'val' : 'html'
+    var data = $el.data()
+
+    state = state + 'Text'
+
+    if (!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"]')
+
+    if ($parent.length) {
+      var $input = this.$element.find('input')
+        .prop('checked', !this.$element.hasClass('active'))
+        .trigger('change')
+      if ($input.prop('type') === 'radio') $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)
+      var data    = $this.data('bs.button')
+      var options = typeof option == 'object' && option
+
+      if (!data) $this.data('bs.button', (data = new Button(this, options)))
+
+      if (option == 'toggle') data.toggle()
+      else if (option) data.setState(option)
+    })
+  }
+
+  $.fn.button.Constructor = Button
+
+
+  // BUTTON NO CONFLICT
+  // ==================
+
+  $.fn.button.noConflict = function () {
+    $.fn.button = old
+    return this
+  }
+
+
+  // BUTTON DATA-API
+  // ===============
+
+  $(document).on('click.bs.button.data-api', '[data-toggle^=button]', function (e) {
+    var $btn = $(e.target)
+    if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn')
+    $btn.button('toggle')
+    e.preventDefault()
+  })
+
+}(window.jQuery);
+
+/* ========================================================================
+ * Bootstrap: carousel.js v3.0.0
+ * http://twbs.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";
+
+  // CAROUSEL CLASS DEFINITION
+  // =========================
+
+  var Carousel = function (element, options) {
+    this.$element    = $(element)
+    this.$indicators = this.$element.find('.carousel-indicators')
+    this.options     = options
+    this.paused      =
+    this.sliding     =
+    this.interval    =
+    this.$active     =
+    this.$items      = null
+
+    this.options.pause == 'hover' && this.$element
+      .on('mouseenter', $.proxy(this.pause, this))
+      .on('mouseleave', $.proxy(this.cycle, this))
+  }
+
+  Carousel.DEFAULTS = {
+    interval: 5000
+  , pause: 'hover'
+  , wrap: true
+  }
+
+  Carousel.prototype.cycle =  function (e) {
+    e || (this.paused = false)
+
+    this.interval && clearInterval(this.interval)
+
+    this.options.interval
+      && !this.paused
+      && (this.interval = setInterval($.proxy(this.next, this), this.options.interval))
+
+    return this
+  }
+
+  Carousel.prototype.getActiveIndex = function () {
+    this.$active = this.$element.find('.item.active')
+    this.$items  = this.$active.parent().children()
+
+    return this.$items.index(this.$active)
+  }
+
+  Carousel.prototype.to = function (pos) {
+    var that        = this
+    var activeIndex = this.getActiveIndex()
+
+    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]))
+  }
+
+  Carousel.prototype.pause = function (e) {
+    e || (this.paused = true)
+
+    if (this.$element.find('.next, .prev').length && $.support.transition.end) {
+      this.$element.trigger($.support.transition.end)
+      this.cycle(true)
+    }
+
+    this.interval = clearInterval(this.interval)
+
+    return this
+  }
+
+  Carousel.prototype.next = function () {
+    if (this.sliding) return
+    return this.slide('next')
+  }
+
+  Carousel.prototype.prev = function () {
+    if (this.sliding) return
+    return this.slide('prev')
+  }
+
+  Carousel.prototype.slide = function (type, next) {
+    var $active   = this.$element.find('.item.active')
+    var $next     = next || $active[type]()
+    var isCycling = this.interval
+    var direction = type == 'next' ? 'left' : 'right'
+    var fallback  = type == 'next' ? 'first' : 'last'
+    var that      = this
+
+    if (!$next.length) {
+      if (!this.options.wrap) return
+      $next = this.$element.find('.item')[fallback]()
+    }
+
+    this.sliding = true
+
+    isCycling && this.pause()
+
+    var e = $.Event('slide.bs.carousel', { 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)
+      $active
+        .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)
+        })
+        .emulateTransitionEnd(600)
+    } 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)
+      var data    = $this.data('bs.carousel')
+      var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option)
+      var action  = typeof option == 'string' ? option : options.slide
+
+      if (!data) $this.data('bs.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.Constructor = Carousel
+
+
+  // CAROUSEL NO CONFLICT
+  // ====================
+
+  $.fn.carousel.noConflict = function () {
+    $.fn.carousel = old
+    return this
+  }
+
+
+  // CAROUSEL DATA-API
+  // =================
+
+  $(document).on('click.bs.carousel.data-api', '[data-slide], [data-slide-to]', function (e) {
+    var $this   = $(this), href
+    var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7
+    var options = $.extend({}, $target.data(), $this.data())
+    var slideIndex = $this.attr('data-slide-to')
+    if (slideIndex) options.interval = false
+
+    $target.carousel(options)
+
+    if (slideIndex = $this.attr('data-slide-to')) {
+      $target.data('bs.carousel').to(slideIndex)
+    }
+
+    e.preventDefault()
+  })
+
+  $(window).on('load', function () {
+    $('[data-ride="carousel"]').each(function () {
+      var $carousel = $(this)
+      $carousel.carousel($carousel.data())
+    })
+  })
+
+}(window.jQuery);
+
+/* ========================================================================
+ * Bootstrap: collapse.js v3.0.0
+ * http://twbs.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";
+
+  // COLLAPSE PUBLIC CLASS DEFINITION
+  // ================================
+
+  var Collapse = function (element, options) {
+    this.$element      = $(element)
+    this.options       = $.extend({}, Collapse.DEFAULTS, options)
+    this.transitioning = null
+
+    if (this.options.parent) this.$parent = $(this.options.parent)
+    if (this.options.toggle) this.toggle()
+  }
+
+  Collapse.DEFAULTS = {
+    toggle: true
+  }
+
+  Collapse.prototype.dimension = function () {
+    var hasWidth = this.$element.hasClass('width')
+    return hasWidth ? 'width' : 'height'
+  }
+
+  Collapse.prototype.show = function () {
+    if (this.transitioning || this.$element.hasClass('in')) return
+
+    var startEvent = $.Event('show.bs.collapse')
+    this.$element.trigger(startEvent)
+    if (startEvent.isDefaultPrevented()) return
+
+    var actives = this.$parent && this.$parent.find('> .panel > .in')
+
+    if (actives && actives.length) {
+      var hasData = actives.data('bs.collapse')
+      if (hasData && hasData.transitioning) return
+      actives.collapse('hide')
+      hasData || actives.data('bs.collapse', null)
+    }
+
+    var dimension = this.dimension()
+
+    this.$element
+      .removeClass('collapse')
+      .addClass('collapsing')
+      [dimension](0)
+
+    this.transitioning = 1
+
+    var complete = function () {
+      this.$element
+        .removeClass('collapsing')
+        .addClass('in')
+        [dimension]('auto')
+      this.transitioning = 0
+      this.$element.trigger('shown.bs.collapse')
+    }
+
+    if (!$.support.transition) return complete.call(this)
+
+    var scrollSize = $.camelCase(['scroll', dimension].join('-'))
+
+    this.$element
+      .one($.support.transition.end, $.proxy(complete, this))
+      .emulateTransitionEnd(350)
+      [dimension](this.$element[0][scrollSize])
+  }
+
+  Collapse.prototype.hide = function () {
+    if (this.transitioning || !this.$element.hasClass('in')) return
+
+    var startEvent = $.Event('hide.bs.collapse')
+    this.$element.trigger(startEvent)
+    if (startEvent.isDefaultPrevented()) return
+
+    var dimension = this.dimension()
+
+    this.$element
+      [dimension](this.$element[dimension]())
+      [0].offsetHeight
+
+    this.$element
+      .addClass('collapsing')
+      .removeClass('collapse')
+      .removeClass('in')
+
+    this.transitioning = 1
+
+    var complete = function () {
+      this.transitioning = 0
+      this.$element
+        .trigger('hidden.bs.collapse')
+        .removeClass('collapsing')
+        .addClass('collapse')
+    }
+
+    if (!$.support.transition) return complete.call(this)
+
+    this.$element
+      [dimension](0)
+      .one($.support.transition.end, $.proxy(complete, this))
+      .emulateTransitionEnd(350)
+  }
+
+  Collapse.prototype.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)
+      var data    = $this.data('bs.collapse')
+      var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option)
+
+      if (!data) $this.data('bs.collapse', (data = new Collapse(this, options)))
+      if (typeof option == 'string') data[option]()
+    })
+  }
+
+  $.fn.collapse.Constructor = Collapse
+
+
+  // COLLAPSE NO CONFLICT
+  // ====================
+
+  $.fn.collapse.noConflict = function () {
+    $.fn.collapse = old
+    return this
+  }
+
+
+  // COLLAPSE DATA-API
+  // =================
+
+  $(document).on('click.bs.collapse.data-api', '[data-toggle=collapse]', function (e) {
+    var $this   = $(this), href
+    var target  = $this.attr('data-target')
+        || e.preventDefault()
+        || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7
+    var $target = $(target)
+    var data    = $target.data('bs.collapse')
+    var option  = data ? 'toggle' : $this.data()
+    var parent  = $this.attr('data-parent')
+    var $parent = parent && $(parent)
+
+    if (!data || !data.transitioning) {
+      if ($parent) $parent.find('[data-toggle=collapse][data-parent="' + parent + '"]').not($this).addClass('collapsed')
+      $this[$target.hasClass('in') ? 'addClass' : 'removeClass']('collapsed')
+    }
+
+    $target.collapse(option)
+  })
+
+}(window.jQuery);
+
+/* ========================================================================
+ * Bootstrap: dropdown.js v3.0.0
+ * http://twbs.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";
+
+  // DROPDOWN CLASS DEFINITION
+  // =========================
+
+  var backdrop = '.dropdown-backdrop'
+  var toggle   = '[data-toggle=dropdown]'
+  var Dropdown = function (element) {
+    var $el = $(element).on('click.bs.dropdown', this.toggle)
+  }
+
+  Dropdown.prototype.toggle = function (e) {
+    var $this = $(this)
+
+    if ($this.is('.disabled, :disabled')) return
+
+    var $parent  = getParent($this)
+    var isActive = $parent.hasClass('open')
+
+    clearMenus()
+
+    if (!isActive) {
+      if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) {
+        // if mobile we we use a backdrop because click events don't delegate
+        $('<div class="dropdown-backdrop"/>').insertAfter($(this)).on('click', clearMenus)
+      }
+
+      $parent.trigger(e = $.Event('show.bs.dropdown'))
+
+      if (e.isDefaultPrevented()) return
+
+      $parent
+        .toggleClass('open')
+        .trigger('shown.bs.dropdown')
+
+      $this.focus()
+    }
+
+    return false
+  }
+
+  Dropdown.prototype.keydown = function (e) {
+    if (!/(38|40|27)/.test(e.keyCode)) return
+
+    var $this = $(this)
+
+    e.preventDefault()
+    e.stopPropagation()
+
+    if ($this.is('.disabled, :disabled')) return
+
+    var $parent  = getParent($this)
+    var isActive = $parent.hasClass('open')
+
+    if (!isActive || (isActive && e.keyCode == 27)) {
+      if (e.which == 27) $parent.find(toggle).focus()
+      return $this.click()
+    }
+
+    var $items = $('[role=menu] li:not(.divider):visible a', $parent)
+
+    if (!$items.length) return
+
+    var 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() {
+    $(backdrop).remove()
+    $(toggle).each(function (e) {
+      var $parent = getParent($(this))
+      if (!$parent.hasClass('open')) return
+      $parent.trigger(e = $.Event('hide.bs.dropdown'))
+      if (e.isDefaultPrevented()) return
+      $parent.removeClass('open').trigger('hidden.bs.dropdown')
+    })
+  }
+
+  function getParent($this) {
+    var selector = $this.attr('data-target')
+
+    if (!selector) {
+      selector = $this.attr('href')
+      selector = selector && /#/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
+    }
+
+    var $parent = selector && $(selector)
+
+    return $parent && $parent.length ? $parent : $this.parent()
+  }
+
+
+  // DROPDOWN PLUGIN DEFINITION
+  // ==========================
+
+  var old = $.fn.dropdown
+
+  $.fn.dropdown = function (option) {
+    return this.each(function () {
+      var $this = $(this)
+      var 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.bs.dropdown.data-api', clearMenus)
+    .on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })
+    .on('click.bs.dropdown.data-api'  , toggle, Dropdown.prototype.toggle)
+    .on('keydown.bs.dropdown.data-api', toggle + ', [role=menu]' , Dropdown.prototype.keydown)
+
+}(window.jQuery);
+
+/* ========================================================================
+ * Bootstrap: modal.js v3.0.0
+ * http://twbs.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";
+
+  // MODAL CLASS DEFINITION
+  // ======================
+
+  var Modal = function (element, options) {
+    this.options   = options
+    this.$element  = $(element)
+    this.$backdrop =
+    this.isShown   = null
+
+    if (this.options.remote) this.$element.load(this.options.remote)
+  }
+
+  Modal.DEFAULTS = {
+      backdrop: true
+    , keyboard: true
+    , show: true
+  }
+
+  Modal.prototype.toggle = function (_relatedTarget) {
+    return this[!this.isShown ? 'show' : 'hide'](_relatedTarget)
+  }
+
+  Modal.prototype.show = function (_relatedTarget) {
+    var that = this
+    var e    = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })
+
+    this.$element.trigger(e)
+
+    if (this.isShown || e.isDefaultPrevented()) return
+
+    this.isShown = true
+
+    this.escape()
+
+    this.$element.on('click.dismiss.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this))
+
+    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()
+
+      var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget })
+
+      transition ?
+        that.$element.find('.modal-dialog') // wait for modal to slide in
+          .one($.support.transition.end, function () {
+            that.$element.focus().trigger(e)
+          })
+          .emulateTransitionEnd(300) :
+        that.$element.focus().trigger(e)
+    })
+  }
+
+  Modal.prototype.hide = function (e) {
+    if (e) e.preventDefault()
+
+    e = $.Event('hide.bs.modal')
+
+    this.$element.trigger(e)
+
+    if (!this.isShown || e.isDefaultPrevented()) return
+
+    this.isShown = false
+
+    this.escape()
+
+    $(document).off('focusin.bs.modal')
+
+    this.$element
+      .removeClass('in')
+      .attr('aria-hidden', true)
+      .off('click.dismiss.modal')
+
+    $.support.transition && this.$element.hasClass('fade') ?
+      this.$element
+        .one($.support.transition.end, $.proxy(this.hideModal, this))
+        .emulateTransitionEnd(300) :
+      this.hideModal()
+  }
+
+  Modal.prototype.enforceFocus = function () {
+    $(document)
+      .off('focusin.bs.modal') // guard against infinite focus loop
+      .on('focusin.bs.modal', $.proxy(function (e) {
+        if (this.$element[0] !== e.target && !this.$element.has(e.target).length) {
+          this.$element.focus()
+        }
+      }, this))
+  }
+
+  Modal.prototype.escape = function () {
+    if (this.isShown && this.options.keyboard) {
+      this.$element.on('keyup.dismiss.bs.modal', $.proxy(function (e) {
+        e.which == 27 && this.hide()
+      }, this))
+    } else if (!this.isShown) {
+      this.$element.off('keyup.dismiss.bs.modal')
+    }
+  }
+
+  Modal.prototype.hideModal = function () {
+    var that = this
+    this.$element.hide()
+    this.backdrop(function () {
+      that.removeBackdrop()
+      that.$element.trigger('hidden.bs.modal')
+    })
+  }
+
+  Modal.prototype.removeBackdrop = function () {
+    this.$backdrop && this.$backdrop.remove()
+    this.$backdrop = null
+  }
+
+  Modal.prototype.backdrop = function (callback) {
+    var that    = this
+    var 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.$element.on('click.dismiss.modal', $.proxy(function (e) {
+        if (e.target !== e.currentTarget) return
+        this.options.backdrop == 'static'
+          ? this.$element[0].focus.call(this.$element[0])
+          : this.hide.call(this)
+      }, this))
+
+      if (doAnimate) this.$backdrop[0].offsetWidth // force reflow
+
+      this.$backdrop.addClass('in')
+
+      if (!callback) return
+
+      doAnimate ?
+        this.$backdrop
+          .one($.support.transition.end, callback)
+          .emulateTransitionEnd(150) :
+        callback()
+
+    } else if (!this.isShown && this.$backdrop) {
+      this.$backdrop.removeClass('in')
+
+      $.support.transition && this.$element.hasClass('fade')?
+        this.$backdrop
+          .one($.support.transition.end, callback)
+          .emulateTransitionEnd(150) :
+        callback()
+
+    } else if (callback) {
+      callback()
+    }
+  }
+
+
+  // MODAL PLUGIN DEFINITION
+  // =======================
+
+  var old = $.fn.modal
+
+  $.fn.modal = function (option, _relatedTarget) {
+    return this.each(function () {
+      var $this   = $(this)
+      var data    = $this.data('bs.modal')
+      var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option)
+
+      if (!data) $this.data('bs.modal', (data = new Modal(this, options)))
+      if (typeof option == 'string') data[option](_relatedTarget)
+      else if (options.show) data.show(_relatedTarget)
+    })
+  }
+
+  $.fn.modal.Constructor = Modal
+
+
+  // MODAL NO CONFLICT
+  // =================
+
+  $.fn.modal.noConflict = function () {
+    $.fn.modal = old
+    return this
+  }
+
+
+  // MODAL DATA-API
+  // ==============
+
+  $(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) {
+    var $this   = $(this)
+    var href    = $this.attr('href')
+    var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7
+    var option  = $target.data('modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())
+
+    e.preventDefault()
+
+    $target
+      .modal(option, this)
+      .one('hide', function () {
+        $this.is(':visible') && $this.focus()
+      })
+  })
+
+  $(document)
+    .on('show.bs.modal',  '.modal', function () { $(document.body).addClass('modal-open') })
+    .on('hidden.bs.modal', '.modal', function () { $(document.body).removeClass('modal-open') })
+
+}(window.jQuery);
+
+/* ========================================================================
+ * Bootstrap: tooltip.js v3.0.0
+ * http://twbs.github.com/bootstrap/javascript.html#tooltip
+ * 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";
+
+  // TOOLTIP PUBLIC CLASS DEFINITION
+  // ===============================
+
+  var Tooltip = function (element, options) {
+    this.type       =
+    this.options    =
+    this.enabled    =
+    this.timeout    =
+    this.hoverState =
+    this.$element   = null
+
+    this.init('tooltip', element, options)
+  }
+
+  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.prototype.init = function (type, element, options) {
+    this.enabled  = true
+    this.type     = type
+    this.$element = $(element)
+    this.options  = this.getOptions(options)
+
+    var triggers = this.options.trigger.split(' ')
+
+    for (var i = triggers.length; i--;) {
+      var trigger = triggers[i]
+
+      if (trigger == 'click') {
+        this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
+      } else if (trigger != 'manual') {
+        var eventIn  = trigger == 'hover' ? 'mouseenter' : 'focus'
+        var 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()
+  }
+
+  Tooltip.prototype.getDefaults = function () {
+    return Tooltip.DEFAULTS
+  }
+
+  Tooltip.prototype.getOptions = function (options) {
+    options = $.extend({}, this.getDefaults(), this.$element.data(), options)
+
+    if (options.delay && typeof options.delay == 'number') {
+      options.delay = {
+        show: options.delay
+      , hide: options.delay
+      }
+    }
+
+    return options
+  }
+
+  Tooltip.prototype.getDelegateOptions = function () {
+    var options  = {}
+    var defaults = this.getDefaults()
+
+    this._options && $.each(this._options, function (key, value) {
+      if (defaults[key] != value) options[key] = value
+    })
+
+    return options
+  }
+
+  Tooltip.prototype.enter = function (obj) {
+    var self = obj instanceof this.constructor ?
+      obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type)
+
+    clearTimeout(self.timeout)
+
+    self.hoverState = 'in'
+
+    if (!self.options.delay || !self.options.delay.show) return self.show()
+
+    self.timeout = setTimeout(function () {
+      if (self.hoverState == 'in') self.show()
+    }, self.options.delay.show)
+  }
+
+  Tooltip.prototype.leave = function (obj) {
+    var self = obj instanceof this.constructor ?
+      obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type)
+
+    clearTimeout(self.timeout)
+
+    self.hoverState = 'out'
+
+    if (!self.options.delay || !self.options.delay.hide) return self.hide()
+
+    self.timeout = setTimeout(function () {
+      if (self.hoverState == 'out') self.hide()
+    }, self.options.delay.hide)
+  }
+
+  Tooltip.prototype.show = function () {
+    var e = $.Event('show.bs.'+ this.type)
+
+    if (this.hasContent() && this.enabled) {
+      this.$element.trigger(e)
+
+      if (e.isDefaultPrevented()) return
+
+      var $tip = this.tip()
+
+      this.setContent()
+
+      if (this.options.animation) $tip.addClass('fade')
+
+      var placement = typeof this.options.placement == 'function' ?
+        this.options.placement.call(this, $tip[0], this.$element[0]) :
+        this.options.placement
+
+      var autoToken = /\s?auto?\s?/i
+      var autoPlace = autoToken.test(placement)
+      if (autoPlace) placement = placement.replace(autoToken, '') || 'top'
+
+      $tip
+        .detach()
+        .css({ top: 0, left: 0, display: 'block' })
+        .addClass(placement)
+
+      this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)
+
+      var pos          = this.getPosition()
+      var actualWidth  = $tip[0].offsetWidth
+      var actualHeight = $tip[0].offsetHeight
+
+      if (autoPlace) {
+        var $parent = this.$element.parent()
+
+        var orgPlacement = placement
+        var docScroll    = document.documentElement.scrollTop || document.body.scrollTop
+        var parentWidth  = this.options.container == 'body' ? window.innerWidth  : $parent.outerWidth()
+        var parentHeight = this.options.container == 'body' ? window.innerHeight : $parent.outerHeight()
+        var parentLeft   = this.options.container == 'body' ? 0 : $parent.offset().left
+
+        placement = placement == 'bottom' && pos.top   + pos.height  + actualHeight - docScroll > parentHeight  ? 'top'    :
+                    placement == 'top'    && pos.top   - docScroll   - actualHeight < 0                         ? 'bottom' :
+                    placement == 'right'  && pos.right + actualWidth > parentWidth                              ? 'left'   :
+                    placement == 'left'   && pos.left  - actualWidth < parentLeft                               ? 'right'  :
+                    placement
+
+        $tip
+          .removeClass(orgPlacement)
+          .addClass(placement)
+      }
+
+      var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight)
+
+      this.applyPlacement(calculatedOffset, placement)
+      this.$element.trigger('shown.bs.' + this.type)
+    }
+  }
+
+  Tooltip.prototype.applyPlacement = function(offset, placement) {
+    var replace
+    var $tip   = this.tip()
+    var width  = $tip[0].offsetWidth
+    var height = $tip[0].offsetHeight
+
+    // manually read margins because getBoundingClientRect includes difference
+    var marginTop = parseInt($tip.css('margin-top'), 10)
+    var marginLeft = parseInt($tip.css('margin-left'), 10)
+
+    // we must check for NaN for ie 8/9
+    if (isNaN(marginTop))  marginTop  = 0
+    if (isNaN(marginLeft)) marginLeft = 0
+
+    offset.top  = offset.top  + marginTop
+    offset.left = offset.left + marginLeft
+
+    $tip
+      .offset(offset)
+      .addClass('in')
+
+    // check to see if placing tip in new offset caused the tip to resize itself
+    var actualWidth  = $tip[0].offsetWidth
+    var actualHeight = $tip[0].offsetHeight
+
+    if (placement == 'top' && actualHeight != height) {
+      replace = true
+      offset.top = offset.top + height - actualHeight
+    }
+
+    if (/bottom|top/.test(placement)) {
+      var 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)
+  }
+
+  Tooltip.prototype.replaceArrow = function(delta, dimension, position) {
+    this.arrow().css(position, delta ? (50 * (1 - delta / dimension) + "%") : '')
+  }
+
+  Tooltip.prototype.setContent = function () {
+    var $tip  = this.tip()
+    var title = this.getTitle()
+
+    $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
+    $tip.removeClass('fade in top bottom left right')
+  }
+
+  Tooltip.prototype.hide = function () {
+    var that = this
+    var $tip = this.tip()
+    var e    = $.Event('hide.bs.' + this.type)
+
+    function complete() {
+      if (that.hoverState != 'in') $tip.detach()
+    }
+
+    this.$element.trigger(e)
+
+    if (e.isDefaultPrevented()) return
+
+    $tip.removeClass('in')
+
+    $.support.transition && this.$tip.hasClass('fade') ?
+      $tip
+        .one($.support.transition.end, complete)
+        .emulateTransitionEnd(150) :
+      complete()
+
+    this.$element.trigger('hidden.bs.' + this.type)
+
+    return this
+  }
+
+  Tooltip.prototype.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', '')
+    }
+  }
+
+  Tooltip.prototype.hasContent = function () {
+    return this.getTitle()
+  }
+
+  Tooltip.prototype.getPosition = function () {
+    var el = this.$element[0]
+    return $.extend({}, (typeof el.getBoundingClientRect == 'function') ? el.getBoundingClientRect() : {
+      width: el.offsetWidth
+    , height: el.offsetHeight
+    }, this.$element.offset())
+  }
+
+  Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) {
+    return placement == 'bottom' ? { top: pos.top + pos.height,   left: pos.left + pos.width / 2 - actualWidth / 2  } :
+           placement == 'top'    ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2  } :
+           placement == 'left'   ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } :
+        /* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width   }
+  }
+
+  Tooltip.prototype.getTitle = function () {
+    var title
+    var $e = this.$element
+    var o  = this.options
+
+    title = $e.attr('data-original-title')
+      || (typeof o.title == 'function' ? o.title.call($e[0]) :  o.title)
+
+    return title
+  }
+
+  Tooltip.prototype.tip = function () {
+    return this.$tip = this.$tip || $(this.options.template)
+  }
+
+  Tooltip.prototype.arrow = function () {
+    return this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow')
+  }
+
+  Tooltip.prototype.validate = function () {
+    if (!this.$element[0].parentNode) {
+      this.hide()
+      this.$element = null
+      this.options  = null
+    }
+  }
+
+  Tooltip.prototype.enable = function () {
+    this.enabled = true
+  }
+
+  Tooltip.prototype.disable = function () {
+    this.enabled = false
+  }
+
+  Tooltip.prototype.toggleEnabled = function () {
+    this.enabled = !this.enabled
+  }
+
+  Tooltip.prototype.toggle = function (e) {
+    var self = e ? $(e.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type) : this
+    self.tip().hasClass('in') ? self.leave(self) : self.enter(self)
+  }
+
+  Tooltip.prototype.destroy = function () {
+    this.hide().$element.off('.' + this.type).removeData('bs.' + this.type)
+  }
+
+
+  // TOOLTIP PLUGIN DEFINITION
+  // =========================
+
+  var old = $.fn.tooltip
+
+  $.fn.tooltip = function (option) {
+    return this.each(function () {
+      var $this   = $(this)
+      var data    = $this.data('bs.tooltip')
+      var options = typeof option == 'object' && option
+
+      if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options)))
+      if (typeof option == 'string') data[option]()
+    })
+  }
+
+  $.fn.tooltip.Constructor = Tooltip
+
+
+  // TOOLTIP NO CONFLICT
+  // ===================
+
+  $.fn.tooltip.noConflict = function () {
+    $.fn.tooltip = old
+    return this
+  }
+
+}(window.jQuery);
+
+/* ========================================================================
+ * Bootstrap: popover.js v3.0.0
+ * http://twbs.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";
+
+  // POPOVER PUBLIC CLASS DEFINITION
+  // ===============================
+
+  var Popover = function (element, options) {
+    this.init('popover', element, options)
+  }
+
+  if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js')
+
+  Popover.DEFAULTS = $.extend({} , $.fn.tooltip.Constructor.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>'
+  })
+
+
+  // NOTE: POPOVER EXTENDS tooltip.js
+  // ================================
+
+  Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype)
+
+  Popover.prototype.constructor = Popover
+
+  Popover.prototype.getDefaults = function () {
+    return Popover.DEFAULTS
+  }
+
+  Popover.prototype.setContent = function () {
+    var $tip    = this.tip()
+    var title   = this.getTitle()
+    var 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')
+
+    // IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do
+    // this manually by checking the contents.
+    if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide()
+  }
+
+  Popover.prototype.hasContent = function () {
+    return this.getTitle() || this.getContent()
+  }
+
+  Popover.prototype.getContent = function () {
+    var $e = this.$element
+    var o  = this.options
+
+    return $e.attr('data-content')
+      || (typeof o.content == 'function' ?
+            o.content.call($e[0]) :
+            o.content)
+  }
+
+  Popover.prototype.arrow = function () {
+    return this.$arrow = this.$arrow || this.tip().find('.arrow')
+  }
+
+  Popover.prototype.tip = function () {
+    if (!this.$tip) this.$tip = $(this.options.template)
+    return this.$tip
+  }
+
+
+  // POPOVER PLUGIN DEFINITION
+  // =========================
+
+  var old = $.fn.popover
+
+  $.fn.popover = function (option) {
+    return this.each(function () {
+      var $this   = $(this)
+      var data    = $this.data('bs.popover')
+      var options = typeof option == 'object' && option
+
+      if (!data) $this.data('bs.popover', (data = new Popover(this, options)))
+      if (typeof option == 'string') data[option]()
+    })
+  }
+
+  $.fn.popover.Constructor = Popover
+
+
+  // POPOVER NO CONFLICT
+  // ===================
+
+  $.fn.popover.noConflict = function () {
+    $.fn.popover = old
+    return this
+  }
+
+}(window.jQuery);
+
+/* ========================================================================
+ * Bootstrap: scrollspy.js v3.0.0
+ * http://twbs.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";
+
+  // SCROLLSPY CLASS DEFINITION
+  // ==========================
+
+  function ScrollSpy(element, options) {
+    var href
+    var process  = $.proxy(this.process, this)
+
+    this.$element       = $(element).is('body') ? $(window) : $(element)
+    this.$body          = $('body')
+    this.$scrollElement = this.$element.on('scroll.bs.scroll-spy.data-api', process)
+    this.options        = $.extend({}, ScrollSpy.DEFAULTS, options)
+    this.selector       = (this.options.target
+      || ((href = $(element).attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7
+      || '') + ' .nav li > a'
+    this.offsets        = $([])
+    this.targets        = $([])
+    this.activeTarget   = null
+
+    this.refresh()
+    this.process()
+  }
+
+  ScrollSpy.DEFAULTS = {
+    offset: 10
+  }
+
+  ScrollSpy.prototype.refresh = function () {
+    var offsetMethod = this.$element[0] == window ? 'offset' : 'position'
+
+    this.offsets = $([])
+    this.targets = $([])
+
+    var self     = this
+    var $targets = this.$body
+      .find(this.selector)
+      .map(function () {
+        var $el   = $(this)
+        var href  = $el.data('target') || $el.attr('href')
+        var $href = /^#\w/.test(href) && $(href)
+
+        return ($href
+          && $href.length
+          && [[ $href[offsetMethod]().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])
+      })
+  }
+
+  ScrollSpy.prototype.process = function () {
+    var scrollTop    = this.$scrollElement.scrollTop() + this.options.offset
+    var scrollHeight = this.$scrollElement[0].scrollHeight || this.$body[0].scrollHeight
+    var maxScroll    = scrollHeight - this.$scrollElement.height()
+    var offsets      = this.offsets
+    var targets      = this.targets
+    var activeTarget = this.activeTarget
+    var 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] )
+    }
+  }
+
+  ScrollSpy.prototype.activate = function (target) {
+    this.activeTarget = target
+
+    $(this.selector)
+      .parents('.active')
+      .removeClass('active')
+
+    var selector = this.selector
+      + '[data-target="' + target + '"],'
+      + this.selector + '[href="' + target + '"]'
+
+    var active = $(selector)
+      .parents('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)
+      var data    = $this.data('bs.scrollspy')
+      var options = typeof option == 'object' && option
+
+      if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options)))
+      if (typeof option == 'string') data[option]()
+    })
+  }
+
+  $.fn.scrollspy.Constructor = ScrollSpy
+
+
+  // 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 v3.0.0
+ * http://twbs.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";
+
+  // TAB CLASS DEFINITION
+  // ====================
+
+  var Tab = function (element) {
+    this.element = $(element)
+  }
+
+  Tab.prototype.show = function () {
+    var $this    = this.element
+    var $ul      = $this.closest('ul:not(.dropdown-menu)')
+    var selector = $this.attr('data-target')
+
+    if (!selector) {
+      selector = $this.attr('href')
+      selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
+    }
+
+    if ($this.parent('li').hasClass('active')) return
+
+    var previous = $ul.find('.active:last a')[0]
+    var e        = $.Event('show.bs.tab', {
+      relatedTarget: previous
+    })
+
+    $this.trigger(e)
+
+    if (e.isDefaultPrevented()) return
+
+    var $target = $(selector)
+
+    this.activate($this.parent('li'), $ul)
+    this.activate($target, $target.parent(), function () {
+      $this.trigger({
+        type: 'shown.bs.tab'
+      , relatedTarget: previous
+      })
+    })
+  }
+
+  Tab.prototype.activate = function (element, container, callback) {
+    var $active    = container.find('> .active')
+    var 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)
+        .emulateTransitionEnd(150) :
+      next()
+
+    $active.removeClass('in')
+  }
+
+
+  // TAB PLUGIN DEFINITION
+  // =====================
+
+  var old = $.fn.tab
+
+  $.fn.tab = function ( option ) {
+    return this.each(function () {
+      var $this = $(this)
+      var data  = $this.data('bs.tab')
+
+      if (!data) $this.data('bs.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.bs.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) {
+    e.preventDefault()
+    $(this).tab('show')
+  })
+
+}(window.jQuery);
+
+/* ========================================================================
+ * Bootstrap: affix.js v3.0.0
+ * http://twbs.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";
+
+  // AFFIX CLASS DEFINITION
+  // ======================
+
+  var Affix = function (element, options) {
+    this.options = $.extend({}, Affix.DEFAULTS, options)
+    this.$window = $(window)
+      .on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this))
+      .on('click.bs.affix.data-api',  $.proxy(this.checkPositionWithEventLoop, this))
+
+    this.$element = $(element)
+    this.affixed  =
+    this.unpin    = null
+
+    this.checkPosition()
+  }
+
+  Affix.RESET = 'affix affix-top affix-bottom'
+
+  Affix.DEFAULTS = {
+    offset: 0
+  }
+
+  Affix.prototype.checkPositionWithEventLoop = function () {
+    setTimeout($.proxy(this.checkPosition, this), 1)
+  }
+
+  Affix.prototype.checkPosition = function () {
+    if (!this.$element.is(':visible')) return
+
+    var scrollHeight = $(document).height()
+    var scrollTop    = this.$window.scrollTop()
+    var position     = this.$element.offset()
+    var offset       = this.options.offset
+    var offsetTop    = offset.top
+    var offsetBottom = offset.bottom
+
+    if (typeof offset != 'object')         offsetBottom = offsetTop = offset
+    if (typeof offsetTop == 'function')    offsetTop    = offset.top()
+    if (typeof offsetBottom == 'function') offsetBottom = offset.bottom()
+
+    var 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
+    if (this.unpin) this.$element.css('top', '')
+
+    this.affixed = affix
+    this.unpin   = affix == 'bottom' ? position.top - scrollTop : null
+
+    this.$element.removeClass(Affix.RESET).addClass('affix' + (affix ? '-' + affix : ''))
+
+    if (affix == 'bottom') {
+      this.$element.offset({ top: document.body.offsetHeight - offsetBottom - this.$element.height() })
+    }
+  }
+
+
+  // AFFIX PLUGIN DEFINITION
+  // =======================
+
+  var old = $.fn.affix
+
+  $.fn.affix = function (option) {
+    return this.each(function () {
+      var $this   = $(this)
+      var data    = $this.data('bs.affix')
+      var options = typeof option == 'object' && option
+
+      if (!data) $this.data('bs.affix', (data = new Affix(this, options)))
+      if (typeof option == 'string') data[option]()
+    })
+  }
+
+  $.fn.affix.Constructor = Affix
+
+
+  // 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)
+      var data = $spy.data()
+
+      data.offset = data.offset || {}
+
+      if (data.offsetBottom) data.offset.bottom = data.offsetBottom
+      if (data.offsetTop)    data.offset.top    = data.offsetTop
+
+      $spy.affix(data)
+    })
+  })
+
+}(window.jQuery);
diff --git a/third-party/bootstrap-3.0.0/js/bootstrap.min.js b/third-party/bootstrap-3.0.0/js/bootstrap.min.js
new file mode 100644 (file)
index 0000000..1765631
--- /dev/null
@@ -0,0 +1,6 @@
+/**
+* bootstrap.js v3.0.0 by @fat and @mdo
+* Copyright 2013 Twitter Inc.
+* http://www.apache.org/licenses/LICENSE-2.0
+*/
+if(!jQuery)throw new Error("Bootstrap requires jQuery");+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]}}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one(a.support.transition.end,function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b()})}(window.jQuery),+function(a){"use strict";var b='[data-dismiss="alert"]',c=function(c){a(c).on("click",b,this.close)};c.prototype.close=function(b){function c(){f.trigger("closed.bs.alert").remove()}var d=a(this),e=d.attr("data-target");e||(e=d.attr("href"),e=e&&e.replace(/.*(?=#[^\s]*$)/,""));var f=a(e);b&&b.preventDefault(),f.length||(f=d.hasClass("alert")?d:d.parent()),f.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(f.removeClass("in"),a.support.transition&&f.hasClass("fade")?f.one(a.support.transition.end,c).emulateTransitionEnd(150):c())};var d=a.fn.alert;a.fn.alert=function(b){return this.each(function(){var d=a(this),e=d.data("bs.alert");e||d.data("bs.alert",e=new c(this)),"string"==typeof b&&e[b].call(d)})},a.fn.alert.Constructor=c,a.fn.alert.noConflict=function(){return a.fn.alert=d,this},a(document).on("click.bs.alert.data-api",b,c.prototype.close)}(window.jQuery),+function(a){"use strict";var b=function(c,d){this.$element=a(c),this.options=a.extend({},b.DEFAULTS,d)};b.DEFAULTS={loadingText:"loading..."},b.prototype.setState=function(a){var b="disabled",c=this.$element,d=c.is("input")?"val":"html",e=c.data();a+="Text",e.resetText||c.data("resetText",c[d]()),c[d](e[a]||this.options[a]),setTimeout(function(){"loadingText"==a?c.addClass(b).attr(b,b):c.removeClass(b).removeAttr(b)},0)},b.prototype.toggle=function(){var a=this.$element.closest('[data-toggle="buttons"]');if(a.length){var b=this.$element.find("input").prop("checked",!this.$element.hasClass("active")).trigger("change");"radio"===b.prop("type")&&a.find(".active").removeClass("active")}this.$element.toggleClass("active")};var c=a.fn.button;a.fn.button=function(c){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof c&&c;e||d.data("bs.button",e=new b(this,f)),"toggle"==c?e.toggle():c&&e.setState(c)})},a.fn.button.Constructor=b,a.fn.button.noConflict=function(){return a.fn.button=c,this},a(document).on("click.bs.button.data-api","[data-toggle^=button]",function(b){var c=a(b.target);c.hasClass("btn")||(c=c.closest(".btn")),c.button("toggle"),b.preventDefault()})}(window.jQuery),+function(a){"use strict";var b=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=this.sliding=this.interval=this.$active=this.$items=null,"hover"==this.options.pause&&this.$element.on("mouseenter",a.proxy(this.pause,this)).on("mouseleave",a.proxy(this.cycle,this))};b.DEFAULTS={interval:5e3,pause:"hover",wrap:!0},b.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},b.prototype.getActiveIndex=function(){return this.$active=this.$element.find(".item.active"),this.$items=this.$active.parent().children(),this.$items.index(this.$active)},b.prototype.to=function(b){var c=this,d=this.getActiveIndex();return b>this.$items.length-1||0>b?void 0:this.sliding?this.$element.one("slid",function(){c.to(b)}):d==b?this.pause().cycle():this.slide(b>d?"next":"prev",a(this.$items[b]))},b.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition.end&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},b.prototype.next=function(){return this.sliding?void 0:this.slide("next")},b.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},b.prototype.slide=function(b,c){var d=this.$element.find(".item.active"),e=c||d[b](),f=this.interval,g="next"==b?"left":"right",h="next"==b?"first":"last",i=this;if(!e.length){if(!this.options.wrap)return;e=this.$element.find(".item")[h]()}this.sliding=!0,f&&this.pause();var j=a.Event("slide.bs.carousel",{relatedTarget:e[0],direction:g});if(!e.hasClass("active")){if(this.$indicators.length&&(this.$indicators.find(".active").removeClass("active"),this.$element.one("slid",function(){var b=a(i.$indicators.children()[i.getActiveIndex()]);b&&b.addClass("active")})),a.support.transition&&this.$element.hasClass("slide")){if(this.$element.trigger(j),j.isDefaultPrevented())return;e.addClass(b),e[0].offsetWidth,d.addClass(g),e.addClass(g),d.one(a.support.transition.end,function(){e.removeClass([b,g].join(" ")).addClass("active"),d.removeClass(["active",g].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger("slid")},0)}).emulateTransitionEnd(600)}else{if(this.$element.trigger(j),j.isDefaultPrevented())return;d.removeClass("active"),e.addClass("active"),this.sliding=!1,this.$element.trigger("slid")}return f&&this.cycle(),this}};var c=a.fn.carousel;a.fn.carousel=function(c){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},b.DEFAULTS,d.data(),"object"==typeof c&&c),g="string"==typeof c?c:f.slide;e||d.data("bs.carousel",e=new b(this,f)),"number"==typeof c?e.to(c):g?e[g]():f.interval&&e.pause().cycle()})},a.fn.carousel.Constructor=b,a.fn.carousel.noConflict=function(){return a.fn.carousel=c,this},a(document).on("click.bs.carousel.data-api","[data-slide], [data-slide-to]",function(b){var c,d=a(this),e=a(d.attr("data-target")||(c=d.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"")),f=a.extend({},e.data(),d.data()),g=d.attr("data-slide-to");g&&(f.interval=!1),e.carousel(f),(g=d.attr("data-slide-to"))&&e.data("bs.carousel").to(g),b.preventDefault()}),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var b=a(this);b.carousel(b.data())})})}(window.jQuery),+function(a){"use strict";var b=function(c,d){this.$element=a(c),this.options=a.extend({},b.DEFAULTS,d),this.transitioning=null,this.options.parent&&(this.$parent=a(this.options.parent)),this.options.toggle&&this.toggle()};b.DEFAULTS={toggle:!0},b.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},b.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b=a.Event("show.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.$parent&&this.$parent.find("> .panel > .in");if(c&&c.length){var d=c.data("bs.collapse");if(d&&d.transitioning)return;c.collapse("hide"),d||c.data("bs.collapse",null)}var e=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[e](0),this.transitioning=1;var f=function(){this.$element.removeClass("collapsing").addClass("in")[e]("auto"),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return f.call(this);var g=a.camelCase(["scroll",e].join("-"));this.$element.one(a.support.transition.end,a.proxy(f,this)).emulateTransitionEnd(350)[e](this.$element[0][g])}}},b.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse").removeClass("in"),this.transitioning=1;var d=function(){this.transitioning=0,this.$element.trigger("hidden.bs.collapse").removeClass("collapsing").addClass("collapse")};return a.support.transition?(this.$element[c](0).one(a.support.transition.end,a.proxy(d,this)).emulateTransitionEnd(350),void 0):d.call(this)}}},b.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()};var c=a.fn.collapse;a.fn.collapse=function(c){return this.each(function(){var d=a(this),e=d.data("bs.collapse"),f=a.extend({},b.DEFAULTS,d.data(),"object"==typeof c&&c);e||d.data("bs.collapse",e=new b(this,f)),"string"==typeof c&&e[c]()})},a.fn.collapse.Constructor=b,a.fn.collapse.noConflict=function(){return a.fn.collapse=c,this},a(document).on("click.bs.collapse.data-api","[data-toggle=collapse]",function(b){var c,d=a(this),e=d.attr("data-target")||b.preventDefault()||(c=d.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,""),f=a(e),g=f.data("bs.collapse"),h=g?"toggle":d.data(),i=d.attr("data-parent"),j=i&&a(i);g&&g.transitioning||(j&&j.find('[data-toggle=collapse][data-parent="'+i+'"]').not(d).addClass("collapsed"),d[f.hasClass("in")?"addClass":"removeClass"]("collapsed")),f.collapse(h)})}(window.jQuery),+function(a){"use strict";function b(){a(d).remove(),a(e).each(function(b){var d=c(a(this));d.hasClass("open")&&(d.trigger(b=a.Event("hide.bs.dropdown")),b.isDefaultPrevented()||d.removeClass("open").trigger("hidden.bs.dropdown"))})}function c(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}var d=".dropdown-backdrop",e="[data-toggle=dropdown]",f=function(b){a(b).on("click.bs.dropdown",this.toggle)};f.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=c(e),g=f.hasClass("open");if(b(),!g){if("ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a('<div class="dropdown-backdrop"/>').insertAfter(a(this)).on("click",b),f.trigger(d=a.Event("show.bs.dropdown")),d.isDefaultPrevented())return;f.toggleClass("open").trigger("shown.bs.dropdown"),e.focus()}return!1}},f.prototype.keydown=function(b){if(/(38|40|27)/.test(b.keyCode)){var d=a(this);if(b.preventDefault(),b.stopPropagation(),!d.is(".disabled, :disabled")){var f=c(d),g=f.hasClass("open");if(!g||g&&27==b.keyCode)return 27==b.which&&f.find(e).focus(),d.click();var h=a("[role=menu] li:not(.divider):visible a",f);if(h.length){var i=h.index(h.filter(":focus"));38==b.keyCode&&i>0&&i--,40==b.keyCode&&i<h.length-1&&i++,~i||(i=0),h.eq(i).focus()}}}};var g=a.fn.dropdown;a.fn.dropdown=function(b){return this.each(function(){var c=a(this),d=c.data("dropdown");d||c.data("dropdown",d=new f(this)),"string"==typeof b&&d[b].call(c)})},a.fn.dropdown.Constructor=f,a.fn.dropdown.noConflict=function(){return a.fn.dropdown=g,this},a(document).on("click.bs.dropdown.data-api",b).on("click.bs.dropdown.data-api",".dropdown form",function(a){a.stopPropagation()}).on("click.bs.dropdown.data-api",e,f.prototype.toggle).on("keydown.bs.dropdown.data-api",e+", [role=menu]",f.prototype.keydown)}(window.jQuery),+function(a){"use strict";var b=function(b,c){this.options=c,this.$element=a(b),this.$backdrop=this.isShown=null,this.options.remote&&this.$element.load(this.options.remote)};b.DEFAULTS={backdrop:!0,keyboard:!0,show:!0},b.prototype.toggle=function(a){return this[this.isShown?"hide":"show"](a)},b.prototype.show=function(b){var c=this,d=a.Event("show.bs.modal",{relatedTarget:b});this.$element.trigger(d),this.isShown||d.isDefaultPrevented()||(this.isShown=!0,this.escape(),this.$element.on("click.dismiss.modal",'[data-dismiss="modal"]',a.proxy(this.hide,this)),this.backdrop(function(){var d=a.support.transition&&c.$element.hasClass("fade");c.$element.parent().length||c.$element.appendTo(document.body),c.$element.show(),d&&c.$element[0].offsetWidth,c.$element.addClass("in").attr("aria-hidden",!1),c.enforceFocus();var e=a.Event("shown.bs.modal",{relatedTarget:b});d?c.$element.find(".modal-dialog").one(a.support.transition.end,function(){c.$element.focus().trigger(e)}).emulateTransitionEnd(300):c.$element.focus().trigger(e)}))},b.prototype.hide=function(b){b&&b.preventDefault(),b=a.Event("hide.bs.modal"),this.$element.trigger(b),this.isShown&&!b.isDefaultPrevented()&&(this.isShown=!1,this.escape(),a(document).off("focusin.bs.modal"),this.$element.removeClass("in").attr("aria-hidden",!0).off("click.dismiss.modal"),a.support.transition&&this.$element.hasClass("fade")?this.$element.one(a.support.transition.end,a.proxy(this.hideModal,this)).emulateTransitionEnd(300):this.hideModal())},b.prototype.enforceFocus=function(){a(document).off("focusin.bs.modal").on("focusin.bs.modal",a.proxy(function(a){this.$element[0]===a.target||this.$element.has(a.target).length||this.$element.focus()},this))},b.prototype.escape=function(){this.isShown&&this.options.keyboard?this.$element.on("keyup.dismiss.bs.modal",a.proxy(function(a){27==a.which&&this.hide()},this)):this.isShown||this.$element.off("keyup.dismiss.bs.modal")},b.prototype.hideModal=function(){var a=this;this.$element.hide(),this.backdrop(function(){a.removeBackdrop(),a.$element.trigger("hidden.bs.modal")})},b.prototype.removeBackdrop=function(){this.$backdrop&&this.$backdrop.remove(),this.$backdrop=null},b.prototype.backdrop=function(b){var c=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var d=a.support.transition&&c;if(this.$backdrop=a('<div class="modal-backdrop '+c+'" />').appendTo(document.body),this.$element.on("click.dismiss.modal",a.proxy(function(a){a.target===a.currentTarget&&("static"==this.options.backdrop?this.$element[0].focus.call(this.$element[0]):this.hide.call(this))},this)),d&&this.$backdrop[0].offsetWidth,this.$backdrop.addClass("in"),!b)return;d?this.$backdrop.one(a.support.transition.end,b).emulateTransitionEnd(150):b()}else!this.isShown&&this.$backdrop?(this.$backdrop.removeClass("in"),a.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one(a.support.transition.end,b).emulateTransitionEnd(150):b()):b&&b()};var c=a.fn.modal;a.fn.modal=function(c,d){return this.each(function(){var e=a(this),f=e.data("bs.modal"),g=a.extend({},b.DEFAULTS,e.data(),"object"==typeof c&&c);f||e.data("bs.modal",f=new b(this,g)),"string"==typeof c?f[c](d):g.show&&f.show(d)})},a.fn.modal.Constructor=b,a.fn.modal.noConflict=function(){return a.fn.modal=c,this},a(document).on("click.bs.modal.data-api",'[data-toggle="modal"]',function(b){var c=a(this),d=c.attr("href"),e=a(c.attr("data-target")||d&&d.replace(/.*(?=#[^\s]+$)/,"")),f=e.data("modal")?"toggle":a.extend({remote:!/#/.test(d)&&d},e.data(),c.data());b.preventDefault(),e.modal(f,this).one("hide",function(){c.is(":visible")&&c.focus()})}),a(document).on("show.bs.modal",".modal",function(){a(document.body).addClass("modal-open")}).on("hidden.bs.modal",".modal",function(){a(document.body).removeClass("modal-open")})}(window.jQuery),+function(a){"use strict";var b=function(a,b){this.type=this.options=this.enabled=this.timeout=this.hoverState=this.$element=null,this.init("tooltip",a,b)};b.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},b.prototype.init=function(b,c,d){this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d);for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focus",i="hover"==g?"mouseleave":"blur";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},b.prototype.getDefaults=function(){return b.DEFAULTS},b.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},b.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},b.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget)[this.type](this.getDelegateOptions()).data("bs."+this.type);return clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show),void 0):c.show()},b.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget)[this.type](this.getDelegateOptions()).data("bs."+this.type);return clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide),void 0):c.hide()},b.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){if(this.$element.trigger(b),b.isDefaultPrevented())return;var c=this.tip();this.setContent(),this.options.animation&&c.addClass("fade");var d="function"==typeof this.options.placement?this.options.placement.call(this,c[0],this.$element[0]):this.options.placement,e=/\s?auto?\s?/i,f=e.test(d);f&&(d=d.replace(e,"")||"top"),c.detach().css({top:0,left:0,display:"block"}).addClass(d),this.options.container?c.appendTo(this.options.container):c.insertAfter(this.$element);var g=this.getPosition(),h=c[0].offsetWidth,i=c[0].offsetHeight;if(f){var j=this.$element.parent(),k=d,l=document.documentElement.scrollTop||document.body.scrollTop,m="body"==this.options.container?window.innerWidth:j.outerWidth(),n="body"==this.options.container?window.innerHeight:j.outerHeight(),o="body"==this.options.container?0:j.offset().left;d="bottom"==d&&g.top+g.height+i-l>n?"top":"top"==d&&g.top-l-i<0?"bottom":"right"==d&&g.right+h>m?"left":"left"==d&&g.left-h<o?"right":d,c.removeClass(k).addClass(d)}var p=this.getCalculatedOffset(d,g,h,i);this.applyPlacement(p,d),this.$element.trigger("shown.bs."+this.type)}},b.prototype.applyPlacement=function(a,b){var c,d=this.tip(),e=d[0].offsetWidth,f=d[0].offsetHeight,g=parseInt(d.css("margin-top"),10),h=parseInt(d.css("margin-left"),10);isNaN(g)&&(g=0),isNaN(h)&&(h=0),a.top=a.top+g,a.left=a.left+h,d.offset(a).addClass("in");var i=d[0].offsetWidth,j=d[0].offsetHeight;if("top"==b&&j!=f&&(c=!0,a.top=a.top+f-j),/bottom|top/.test(b)){var k=0;a.left<0&&(k=-2*a.left,a.left=0,d.offset(a),i=d[0].offsetWidth,j=d[0].offsetHeight),this.replaceArrow(k-e+i,i,"left")}else this.replaceArrow(j-f,j,"top");c&&d.offset(a)},b.prototype.replaceArrow=function(a,b,c){this.arrow().css(c,a?50*(1-a/b)+"%":"")},b.prototype.setContent=function(){var a=this.tip(),b=this.getTitle();a.find(".tooltip-inner")[this.options.html?"html":"text"](b),a.removeClass("fade in top bottom left right")},b.prototype.hide=function(){function b(){"in"!=c.hoverState&&d.detach()}var c=this,d=this.tip(),e=a.Event("hide.bs."+this.type);return this.$element.trigger(e),e.isDefaultPrevented()?void 0:(d.removeClass("in"),a.support.transition&&this.$tip.hasClass("fade")?d.one(a.support.transition.end,b).emulateTransitionEnd(150):b(),this.$element.trigger("hidden.bs."+this.type),this)},b.prototype.fixTitle=function(){var a=this.$element;(a.attr("title")||"string"!=typeof a.attr("data-original-title"))&&a.attr("data-original-title",a.attr("title")||"").attr("title","")},b.prototype.hasContent=function(){return this.getTitle()},b.prototype.getPosition=function(){var b=this.$element[0];return a.extend({},"function"==typeof b.getBoundingClientRect?b.getBoundingClientRect():{width:b.offsetWidth,height:b.offsetHeight},this.$element.offset())},b.prototype.getCalculatedOffset=function(a,b,c,d){return"bottom"==a?{top:b.top+b.height,left:b.left+b.width/2-c/2}:"top"==a?{top:b.top-d,left:b.left+b.width/2-c/2}:"left"==a?{top:b.top+b.height/2-d/2,left:b.left-c}:{top:b.top+b.height/2-d/2,left:b.left+b.width}},b.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},b.prototype.tip=function(){return this.$tip=this.$tip||a(this.options.template)},b.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},b.prototype.validate=function(){this.$element[0].parentNode||(this.hide(),this.$element=null,this.options=null)},b.prototype.enable=function(){this.enabled=!0},b.prototype.disable=function(){this.enabled=!1},b.prototype.toggleEnabled=function(){this.enabled=!this.enabled},b.prototype.toggle=function(b){var c=b?a(b.currentTarget)[this.type](this.getDelegateOptions()).data("bs."+this.type):this;c.tip().hasClass("in")?c.leave(c):c.enter(c)},b.prototype.destroy=function(){this.hide().$element.off("."+this.type).removeData("bs."+this.type)};var c=a.fn.tooltip;a.fn.tooltip=function(c){return this.each(function(){var d=a(this),e=d.data("bs.tooltip"),f="object"==typeof c&&c;e||d.data("bs.tooltip",e=new b(this,f)),"string"==typeof c&&e[c]()})},a.fn.tooltip.Constructor=b,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=c,this}}(window.jQuery),+function(a){"use strict";var b=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");b.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.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>'}),b.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),b.prototype.constructor=b,b.prototype.getDefaults=function(){return b.DEFAULTS},b.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content")[this.options.html?"html":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},b.prototype.hasContent=function(){return this.getTitle()||this.getContent()},b.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},b.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")},b.prototype.tip=function(){return this.$tip||(this.$tip=a(this.options.template)),this.$tip};var c=a.fn.popover;a.fn.popover=function(c){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof c&&c;e||d.data("bs.popover",e=new b(this,f)),"string"==typeof c&&e[c]()})},a.fn.popover.Constructor=b,a.fn.popover.noConflict=function(){return a.fn.popover=c,this}}(window.jQuery),+function(a){"use strict";function b(c,d){var e,f=a.proxy(this.process,this);this.$element=a(c).is("body")?a(window):a(c),this.$body=a("body"),this.$scrollElement=this.$element.on("scroll.bs.scroll-spy.data-api",f),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||(e=a(c).attr("href"))&&e.replace(/.*(?=#[^\s]+$)/,"")||"")+" .nav li > a",this.offsets=a([]),this.targets=a([]),this.activeTarget=null,this.refresh(),this.process()}b.DEFAULTS={offset:10},b.prototype.refresh=function(){var b=this.$element[0]==window?"offset":"position";this.offsets=a([]),this.targets=a([]);var c=this;this.$body.find(this.selector).map(function(){var d=a(this),e=d.data("target")||d.attr("href"),f=/^#\w/.test(e)&&a(e);return f&&f.length&&[[f[b]().top+(!a.isWindow(c.$scrollElement.get(0))&&c.$scrollElement.scrollTop()),e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){c.offsets.push(this[0]),c.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.$scrollElement[0].scrollHeight||this.$body[0].scrollHeight,d=c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(b>=d)return g!=(a=f.last()[0])&&this.activate(a);for(a=e.length;a--;)g!=f[a]&&b>=e[a]&&(!e[a+1]||b<=e[a+1])&&this.activate(f[a])},b.prototype.activate=function(b){this.activeTarget=b,a(this.selector).parents(".active").removeClass("active");var c=this.selector+'[data-target="'+b+'"],'+this.selector+'[href="'+b+'"]',d=a(c).parents("li").addClass("active");d.parent(".dropdown-menu").length&&(d=d.closest("li.dropdown").addClass("active")),d.trigger("activate")};var c=a.fn.scrollspy;a.fn.scrollspy=function(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})},a.fn.scrollspy.Constructor=b,a.fn.scrollspy.noConflict=function(){return a.fn.scrollspy=c,this},a(window).on("load",function(){a('[data-spy="scroll"]').each(function(){var b=a(this);b.scrollspy(b.data())})})}(window.jQuery),+function(a){"use strict";var b=function(b){this.element=a(b)};b.prototype.show=function(){var b=this.element,c=b.closest("ul:not(.dropdown-menu)"),d=b.attr("data-target");if(d||(d=b.attr("href"),d=d&&d.replace(/.*(?=#[^\s]*$)/,"")),!b.parent("li").hasClass("active")){var e=c.find(".active:last a")[0],f=a.Event("show.bs.tab",{relatedTarget:e});if(b.trigger(f),!f.isDefaultPrevented()){var g=a(d);this.activate(b.parent("li"),c),this.activate(g,g.parent(),function(){b.trigger({type:"shown.bs.tab",relatedTarget:e})})}}},b.prototype.activate=function(b,c,d){function e(){f.removeClass("active").find("> .dropdown-menu > .active").removeClass("active"),b.addClass("active"),g?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu")&&b.closest("li.dropdown").addClass("active"),d&&d()}var f=c.find("> .active"),g=d&&a.support.transition&&f.hasClass("fade");g?f.one(a.support.transition.end,e).emulateTransitionEnd(150):e(),f.removeClass("in")};var c=a.fn.tab;a.fn.tab=function(c){return this.each(function(){var d=a(this),e=d.data("bs.tab");e||d.data("bs.tab",e=new b(this)),"string"==typeof c&&e[c]()})},a.fn.tab.Constructor=b,a.fn.tab.noConflict=function(){return a.fn.tab=c,this},a(document).on("click.bs.tab.data-api",'[data-toggle="tab"], [data-toggle="pill"]',function(b){b.preventDefault(),a(this).tab("show")})}(window.jQuery),+function(a){"use strict";var b=function(c,d){this.options=a.extend({},b.DEFAULTS,d),this.$window=a(window).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(c),this.affixed=this.unpin=null,this.checkPosition()};b.RESET="affix affix-top affix-bottom",b.DEFAULTS={offset:0},b.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},b.prototype.checkPosition=function(){if(this.$element.is(":visible")){var c=a(document).height(),d=this.$window.scrollTop(),e=this.$element.offset(),f=this.options.offset,g=f.top,h=f.bottom;"object"!=typeof f&&(h=g=f),"function"==typeof g&&(g=f.top()),"function"==typeof h&&(h=f.bottom());var i=null!=this.unpin&&d+this.unpin<=e.top?!1:null!=h&&e.top+this.$element.height()>=c-h?"bottom":null!=g&&g>=d?"top":!1;this.affixed!==i&&(this.unpin&&this.$element.css("top",""),this.affixed=i,this.unpin="bottom"==i?e.top-d:null,this.$element.removeClass(b.RESET).addClass("affix"+(i?"-"+i:"")),"bottom"==i&&this.$element.offset({top:document.body.offsetHeight-h-this.$element.height()}))}};var c=a.fn.affix;a.fn.affix=function(c){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof c&&c;e||d.data("bs.affix",e=new b(this,f)),"string"==typeof c&&e[c]()})},a.fn.affix.Constructor=b,a.fn.affix.noConflict=function(){return a.fn.affix=c,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var b=a(this),c=b.data();c.offset=c.offset||{},c.offsetBottom&&(c.offset.bottom=c.offsetBottom),c.offsetTop&&(c.offset.top=c.offsetTop),b.affix(c)})})}(window.jQuery);
\ No newline at end of file
diff --git a/third-party/codemirror-3.15/.gitattributes b/third-party/codemirror-3.15/.gitattributes
new file mode 100644 (file)
index 0000000..f8bdd60
--- /dev/null
@@ -0,0 +1,8 @@
+*.txt   text
+*.js    text
+*.html  text
+*.md    text
+*.json  text
+*.yml   text
+*.css   text
+*.svg   text
diff --git a/third-party/codemirror-3.15/.gitignore b/third-party/codemirror-3.15/.gitignore
new file mode 100644 (file)
index 0000000..b471fe6
--- /dev/null
@@ -0,0 +1,6 @@
+/node_modules
+/npm-debug.log
+test.html
+.tern-*
+*~
+*.swp
diff --git a/third-party/codemirror-3.15/.travis.yml b/third-party/codemirror-3.15/.travis.yml
new file mode 100644 (file)
index 0000000..baa0031
--- /dev/null
@@ -0,0 +1,3 @@
+language: node_js
+node_js:
+  - 0.8
diff --git a/third-party/codemirror-3.15/CONTRIBUTING.md b/third-party/codemirror-3.15/CONTRIBUTING.md
new file mode 100644 (file)
index 0000000..4e040ff
--- /dev/null
@@ -0,0 +1,72 @@
+# How to contribute
+
+- [Getting help](#getting-help-)
+- [Submitting bug reports](#submitting-bug-reports-)
+- [Contributing code](#contributing-code-)
+
+## Getting help [^](#how-to-contribute)
+
+Community discussion, questions, and informal bug reporting is done on the
+[CodeMirror Google group](http://groups.google.com/group/codemirror).
+
+## Submitting bug reports [^](#how-to-contribute)
+
+The preferred way to report bugs is to use the
+[GitHub issue tracker](http://github.com/marijnh/CodeMirror/issues). Before
+reporting a bug, read these pointers.
+
+**Note:** The issue tracker is for *bugs*, not requests for help. Questions
+should be asked on the
+[CodeMirror Google group](http://groups.google.com/group/codemirror) instead.
+
+### Reporting bugs effectively
+
+- CodeMirror is maintained by volunteers. They don't owe you anything, so be
+  polite. Reports with an indignant or belligerent tone tend to be moved to the
+  bottom of the pile.
+
+- Include information about **the browser in which the problem occurred**. Even
+  if you tested several browsers, and the problem occurred in all of them,
+  mention this fact in the bug report. Also include browser version numbers and
+  the operating system that you're on.
+
+- Mention which release of CodeMirror you're using. Preferably, try also with
+  the current development snapshot, to ensure the problem has not already been
+  fixed.
+
+- Mention very precisely what went wrong. "X is broken" is not a good bug
+  report. What did you expect to happen? What happened instead? Describe the
+  exact steps a maintainer has to take to make the problem occur. We can not
+  fix something that we can not observe.
+
+- If the problem can not be reproduced in any of the demos included in the
+  CodeMirror distribution, please provide an HTML document that demonstrates
+  the problem. The best way to do this is to go to
+  [jsbin.com](http://jsbin.com/ihunin/edit), enter it there, press save, and
+  include the resulting link in your bug report.
+
+## Contributing code [^](#how-to-contribute)
+
+- Make sure you have a [GitHub Account](https://github.com/signup/free)
+- Fork [CodeMirror](https://github.com/marijnh/CodeMirror/)
+  ([how to fork a repo](https://help.github.com/articles/fork-a-repo))
+- Make your changes
+- If your changes are easy to test or likely to regress, add tests.
+  Tests for the core go into `test/test.js`, some modes have their own
+  test suite under `mode/XXX/test.js`. Feel free to add new test
+  suites to modes that don't have one yet (be sure to link the new
+  tests into `test/index.html`).
+- Follow the general code style of the rest of the project (see
+  below). Run `bin/lint` to verify that the linter is happy.
+- Make sure all tests pass. Visit `test/index.html` in your browser to
+  run them.
+- Submit a pull request
+([how to create a pull request](https://help.github.com/articles/fork-a-repo))
+
+### Coding standards
+
+- 2 spaces per indentation level, no tabs.
+- Include semicolons after statements.
+- Note that the linter (`bin/lint`) which is run after each commit
+  complains about unused variables and functions. Prefix their names
+  with an underscore to muffle it.
diff --git a/third-party/codemirror-3.15/LICENSE b/third-party/codemirror-3.15/LICENSE
new file mode 100644 (file)
index 0000000..482d55e
--- /dev/null
@@ -0,0 +1,23 @@
+Copyright (C) 2013 by Marijn Haverbeke <marijnh@gmail.com>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+Please note that some subdirectories of the CodeMirror distribution
+include their own LICENSE files, and are released under different
+licences.
diff --git a/third-party/codemirror-3.15/README.md b/third-party/codemirror-3.15/README.md
new file mode 100644 (file)
index 0000000..61f6b64
--- /dev/null
@@ -0,0 +1,11 @@
+# CodeMirror
+[![Build Status](https://secure.travis-ci.org/marijnh/CodeMirror.png?branch=master)](http://travis-ci.org/marijnh/CodeMirror)
+[![NPM version](https://badge.fury.io/js/codemirror.png)](http://badge.fury.io/js/codemirror)
+
+CodeMirror is a JavaScript component that provides a code editor in
+the browser. When a mode is available for the language you are coding
+in, it will color your code, and optionally help with indentation.
+
+The project page is http://codemirror.net  
+The manual is at http://codemirror.net/doc/manual.html  
+The contributing guidelines are in [CONTRIBUTING.md](https://github.com/marijnh/CodeMirror/blob/master/CONTRIBUTING.md)
diff --git a/third-party/codemirror-3.15/addon/comment/comment.js b/third-party/codemirror-3.15/addon/comment/comment.js
new file mode 100644 (file)
index 0000000..cd2123e
--- /dev/null
@@ -0,0 +1,145 @@
+(function() {
+  "use strict";
+
+  var noOptions = {};
+  var nonWS = /[^\s\u00a0]/;
+  var Pos = CodeMirror.Pos;
+
+  function firstNonWS(str) {
+    var found = str.search(nonWS);
+    return found == -1 ? 0 : found;
+  }
+
+  CodeMirror.commands.toggleComment = function(cm) {
+    var from = cm.getCursor("start"), to = cm.getCursor("end");
+    cm.uncomment(from, to) || cm.lineComment(from, to);
+  };
+
+  CodeMirror.defineExtension("lineComment", function(from, to, options) {
+    if (!options) options = noOptions;
+    var self = this, mode = self.getModeAt(from);
+    var commentString = options.lineComment || mode.lineComment;
+    if (!commentString) {
+      if (options.blockCommentStart || mode.blockCommentStart) {
+        options.fullLines = true;
+        self.blockComment(from, to, options);
+      }
+      return;
+    }
+    var firstLine = self.getLine(from.line);
+    if (firstLine == null) return;
+    var end = Math.min(to.ch != 0 || to.line == from.line ? to.line + 1 : to.line, self.lastLine() + 1);
+    var pad = options.padding == null ? " " : options.padding;
+    var blankLines = options.commentBlankLines || from.line == to.line;
+
+    self.operation(function() {
+      if (options.indent) {
+        var baseString = firstLine.slice(0, firstNonWS(firstLine));
+        for (var i = from.line; i < end; ++i) {
+          var line = self.getLine(i), cut = baseString.length;
+          if (!blankLines && !nonWS.test(line)) continue;
+          if (line.slice(0, cut) != baseString) cut = firstNonWS(line);
+          self.replaceRange(baseString + commentString + pad, Pos(i, 0), Pos(i, cut));
+        }
+      } else {
+        for (var i = from.line; i < end; ++i) {
+          if (blankLines || nonWS.test(self.getLine(i)))
+            self.replaceRange(commentString + pad, Pos(i, 0));
+        }
+      }
+    });
+  });
+
+  CodeMirror.defineExtension("blockComment", function(from, to, options) {
+    if (!options) options = noOptions;
+    var self = this, mode = self.getModeAt(from);
+    var startString = options.blockCommentStart || mode.blockCommentStart;
+    var endString = options.blockCommentEnd || mode.blockCommentEnd;
+    if (!startString || !endString) {
+      if ((options.lineComment || mode.lineComment) && options.fullLines != false)
+        self.lineComment(from, to, options);
+      return;
+    }
+
+    var end = Math.min(to.line, self.lastLine());
+    if (end != from.line && to.ch == 0 && nonWS.test(self.getLine(end))) --end;
+
+    var pad = options.padding == null ? " " : options.padding;
+    if (from.line > end) return;
+
+    self.operation(function() {
+      if (options.fullLines != false) {
+        var lastLineHasText = nonWS.test(self.getLine(end));
+        self.replaceRange(pad + endString, Pos(end));
+        self.replaceRange(startString + pad, Pos(from.line, 0));
+        var lead = options.blockCommentLead || mode.blockCommentLead;
+        if (lead != null) for (var i = from.line + 1; i <= end; ++i)
+          if (i != end || lastLineHasText)
+            self.replaceRange(lead + pad, Pos(i, 0));
+      } else {
+        self.replaceRange(endString, to);
+        self.replaceRange(startString, from);
+      }
+    });
+  });
+
+  CodeMirror.defineExtension("uncomment", function(from, to, options) {
+    if (!options) options = noOptions;
+    var self = this, mode = self.getModeAt(from);
+    var end = Math.min(to.line, self.lastLine()), start = Math.min(from.line, end);
+
+    // Try finding line comments
+    var lineString = options.lineComment || mode.lineComment, lines = [];
+    var pad = options.padding == null ? " " : options.padding, didSomething;
+    lineComment: {
+      if (!lineString) break lineComment;
+      for (var i = start; i <= end; ++i) {
+        var line = self.getLine(i);
+        var found = line.indexOf(lineString);
+        if (found == -1 && (i != end || i == start) && nonWS.test(line)) break lineComment;
+        if (i != start && found > -1 && nonWS.test(line.slice(0, found))) break lineComment;
+        lines.push(line);
+      }
+      self.operation(function() {
+        for (var i = start; i <= end; ++i) {
+          var line = lines[i - start];
+          var pos = line.indexOf(lineString), endPos = pos + lineString.length;
+          if (pos < 0) continue;
+          if (line.slice(endPos, endPos + pad.length) == pad) endPos += pad.length;
+          didSomething = true;
+          self.replaceRange("", Pos(i, pos), Pos(i, endPos));
+        }
+      });
+      if (didSomething) return true;
+    }
+
+    // Try block comments
+    var startString = options.blockCommentStart || mode.blockCommentStart;
+    var endString = options.blockCommentEnd || mode.blockCommentEnd;
+    if (!startString || !endString) return false;
+    var lead = options.blockCommentLead || mode.blockCommentLead;
+    var startLine = self.getLine(start), endLine = end == start ? startLine : self.getLine(end);
+    var open = startLine.indexOf(startString), close = endLine.lastIndexOf(endString);
+    if (close == -1 && start != end) {
+      endLine = self.getLine(--end);
+      close = endLine.lastIndexOf(endString);
+    }
+    if (open == -1 || close == -1) return false;
+
+    self.operation(function() {
+      self.replaceRange("", Pos(end, close - (pad && endLine.slice(close - pad.length, close) == pad ? pad.length : 0)),
+                        Pos(end, close + endString.length));
+      var openEnd = open + startString.length;
+      if (pad && startLine.slice(openEnd, openEnd + pad.length) == pad) openEnd += pad.length;
+      self.replaceRange("", Pos(start, open), Pos(start, openEnd));
+      if (lead) for (var i = start + 1; i <= end; ++i) {
+        var line = self.getLine(i), found = line.indexOf(lead);
+        if (found == -1 || nonWS.test(line.slice(0, found))) continue;
+        var foundEnd = found + lead.length;
+        if (pad && line.slice(foundEnd, foundEnd + pad.length) == pad) foundEnd += pad.length;
+        self.replaceRange("", Pos(i, found), Pos(i, foundEnd));
+      }
+    });
+    return true;
+  });
+})();
diff --git a/third-party/codemirror-3.15/addon/dialog/dialog.css b/third-party/codemirror-3.15/addon/dialog/dialog.css
new file mode 100644 (file)
index 0000000..2e7c0fc
--- /dev/null
@@ -0,0 +1,32 @@
+.CodeMirror-dialog {
+  position: absolute;
+  left: 0; right: 0;
+  background: white;
+  z-index: 15;
+  padding: .1em .8em;
+  overflow: hidden;
+  color: #333;
+}
+
+.CodeMirror-dialog-top {
+  border-bottom: 1px solid #eee;
+  top: 0;
+}
+
+.CodeMirror-dialog-bottom {
+  border-top: 1px solid #eee;
+  bottom: 0;
+}
+
+.CodeMirror-dialog input {
+  border: none;
+  outline: none;
+  background: transparent;
+  width: 20em;
+  color: inherit;
+  font-family: monospace;
+}
+
+.CodeMirror-dialog button {
+  font-size: 70%;
+}
diff --git a/third-party/codemirror-3.15/addon/dialog/dialog.js b/third-party/codemirror-3.15/addon/dialog/dialog.js
new file mode 100644 (file)
index 0000000..71e2287
--- /dev/null
@@ -0,0 +1,80 @@
+// Open simple dialogs on top of an editor. Relies on dialog.css.
+
+(function() {
+  function dialogDiv(cm, template, bottom) {
+    var wrap = cm.getWrapperElement();
+    var dialog;
+    dialog = wrap.appendChild(document.createElement("div"));
+    if (bottom) {
+      dialog.className = "CodeMirror-dialog CodeMirror-dialog-bottom";
+    } else {
+      dialog.className = "CodeMirror-dialog CodeMirror-dialog-top";
+    }
+    dialog.innerHTML = template;
+    return dialog;
+  }
+
+  CodeMirror.defineExtension("openDialog", function(template, callback, options) {
+    var dialog = dialogDiv(this, template, options && options.bottom);
+    var closed = false, me = this;
+    function close() {
+      if (closed) return;
+      closed = true;
+      dialog.parentNode.removeChild(dialog);
+    }
+    var inp = dialog.getElementsByTagName("input")[0], button;
+    if (inp) {
+      CodeMirror.on(inp, "keydown", function(e) {
+        if (options && options.onKeyDown && options.onKeyDown(e, inp.value, close)) { return; }
+        if (e.keyCode == 13 || e.keyCode == 27) {
+          CodeMirror.e_stop(e);
+          close();
+          me.focus();
+          if (e.keyCode == 13) callback(inp.value);
+        }
+      });
+      if (options && options.onKeyUp) {
+        CodeMirror.on(inp, "keyup", function(e) {options.onKeyUp(e, inp.value, close);});
+      }
+      if (options && options.value) inp.value = options.value;
+      inp.focus();
+      CodeMirror.on(inp, "blur", close);
+    } else if (button = dialog.getElementsByTagName("button")[0]) {
+      CodeMirror.on(button, "click", function() {
+        close();
+        me.focus();
+      });
+      button.focus();
+      CodeMirror.on(button, "blur", close);
+    }
+    return close;
+  });
+
+  CodeMirror.defineExtension("openConfirm", function(template, callbacks, options) {
+    var dialog = dialogDiv(this, template, options && options.bottom);
+    var buttons = dialog.getElementsByTagName("button");
+    var closed = false, me = this, blurring = 1;
+    function close() {
+      if (closed) return;
+      closed = true;
+      dialog.parentNode.removeChild(dialog);
+      me.focus();
+    }
+    buttons[0].focus();
+    for (var i = 0; i < buttons.length; ++i) {
+      var b = buttons[i];
+      (function(callback) {
+        CodeMirror.on(b, "click", function(e) {
+          CodeMirror.e_preventDefault(e);
+          close();
+          if (callback) callback(me);
+        });
+      })(callbacks[i]);
+      CodeMirror.on(b, "blur", function() {
+        --blurring;
+        setTimeout(function() { if (blurring <= 0) close(); }, 200);
+      });
+      CodeMirror.on(b, "focus", function() { ++blurring; });
+    }
+  });
+})();
diff --git a/third-party/codemirror-3.15/addon/display/placeholder.js b/third-party/codemirror-3.15/addon/display/placeholder.js
new file mode 100644 (file)
index 0000000..18f9dff
--- /dev/null
@@ -0,0 +1,54 @@
+(function() {
+  CodeMirror.defineOption("placeholder", "", function(cm, val, old) {
+    var prev = old && old != CodeMirror.Init;
+    if (val && !prev) {
+      cm.on("focus", onFocus);
+      cm.on("blur", onBlur);
+      cm.on("change", onChange);
+      onChange(cm);
+    } else if (!val && prev) {
+      cm.off("focus", onFocus);
+      cm.off("blur", onBlur);
+      cm.off("change", onChange);
+      clearPlaceholder(cm);
+      var wrapper = cm.getWrapperElement();
+      wrapper.className = wrapper.className.replace(" CodeMirror-empty", "");
+    }
+
+    if (val && !cm.hasFocus()) onBlur(cm);
+  });
+
+  function clearPlaceholder(cm) {
+    if (cm.state.placeholder) {
+      cm.state.placeholder.parentNode.removeChild(cm.state.placeholder);
+      cm.state.placeholder = null;
+    }
+  }
+  function setPlaceholder(cm) {
+    clearPlaceholder(cm);
+    var elt = cm.state.placeholder = document.createElement("pre");
+    elt.style.cssText = "height: 0; overflow: visible";
+    elt.className = "CodeMirror-placeholder";
+    elt.appendChild(document.createTextNode(cm.getOption("placeholder")));
+    cm.display.lineSpace.insertBefore(elt, cm.display.lineSpace.firstChild);
+  }
+
+  function onFocus(cm) {
+    clearPlaceholder(cm);
+  }
+  function onBlur(cm) {
+    if (isEmpty(cm)) setPlaceholder(cm);
+  }
+  function onChange(cm) {
+    var wrapper = cm.getWrapperElement(), empty = isEmpty(cm);
+    wrapper.className = wrapper.className.replace(" CodeMirror-empty", "") + (empty ? " CodeMirror-empty" : "");
+
+    if (cm.hasFocus()) return;
+    if (empty) setPlaceholder(cm);
+    else clearPlaceholder(cm);
+  }
+
+  function isEmpty(cm) {
+    return (cm.lineCount() === 1) && (cm.getLine(0) === "");
+  }
+})();
diff --git a/third-party/codemirror-3.15/addon/edit/closebrackets.js b/third-party/codemirror-3.15/addon/edit/closebrackets.js
new file mode 100644 (file)
index 0000000..88718b7
--- /dev/null
@@ -0,0 +1,82 @@
+(function() {
+  var DEFAULT_BRACKETS = "()[]{}''\"\"";
+  var DEFAULT_EXPLODE_ON_ENTER = "[]{}";
+  var SPACE_CHAR_REGEX = /\s/;
+
+  CodeMirror.defineOption("autoCloseBrackets", false, function(cm, val, old) {
+    if (old != CodeMirror.Init && old)
+      cm.removeKeyMap("autoCloseBrackets");
+    if (!val) return;
+    var pairs = DEFAULT_BRACKETS, explode = DEFAULT_EXPLODE_ON_ENTER;
+    if (typeof val == "string") pairs = val;
+    else if (typeof val == "object") {
+      if (val.pairs != null) pairs = val.pairs;
+      if (val.explode != null) explode = val.explode;
+    }
+    var map = buildKeymap(pairs);
+    if (explode) map.Enter = buildExplodeHandler(explode);
+    cm.addKeyMap(map);
+  });
+
+  function charsAround(cm, pos) {
+    var str = cm.getRange(CodeMirror.Pos(pos.line, pos.ch - 1),
+                          CodeMirror.Pos(pos.line, pos.ch + 1));
+    return str.length == 2 ? str : null;
+  }
+
+  function buildKeymap(pairs) {
+    var map = {
+      name : "autoCloseBrackets",
+      Backspace: function(cm) {
+        if (cm.somethingSelected()) return CodeMirror.Pass;
+        var cur = cm.getCursor(), around = charsAround(cm, cur);
+        if (around && pairs.indexOf(around) % 2 == 0)
+          cm.replaceRange("", CodeMirror.Pos(cur.line, cur.ch - 1), CodeMirror.Pos(cur.line, cur.ch + 1));
+        else
+          return CodeMirror.Pass;
+      }
+    };
+    var closingBrackets = "";
+    for (var i = 0; i < pairs.length; i += 2) (function(left, right) {
+      if (left != right) closingBrackets += right;
+      function surround(cm) {
+        var selection = cm.getSelection();
+        cm.replaceSelection(left + selection + right);
+      }
+      function maybeOverwrite(cm) {
+        var cur = cm.getCursor(), ahead = cm.getRange(cur, CodeMirror.Pos(cur.line, cur.ch + 1));
+        if (ahead != right || cm.somethingSelected()) return CodeMirror.Pass;
+        else cm.execCommand("goCharRight");
+      }
+      map["'" + left + "'"] = function(cm) {
+        if (left == "'" && cm.getTokenAt(cm.getCursor()).type == "comment")
+          return CodeMirror.Pass;
+        if (cm.somethingSelected()) return surround(cm);
+        if (left == right && maybeOverwrite(cm) != CodeMirror.Pass) return;
+        var cur = cm.getCursor(), ahead = CodeMirror.Pos(cur.line, cur.ch + 1);
+        var line = cm.getLine(cur.line), nextChar = line.charAt(cur.ch), curChar = cur.ch > 0 ? line.charAt(cur.ch - 1) : "";
+        if (left == right && CodeMirror.isWordChar(curChar))
+          return CodeMirror.Pass;
+        if (line.length == cur.ch || closingBrackets.indexOf(nextChar) >= 0 || SPACE_CHAR_REGEX.test(nextChar))
+          cm.replaceSelection(left + right, {head: ahead, anchor: ahead});
+        else
+          return CodeMirror.Pass;
+      };
+      if (left != right) map["'" + right + "'"] = maybeOverwrite;
+    })(pairs.charAt(i), pairs.charAt(i + 1));
+    return map;
+  }
+
+  function buildExplodeHandler(pairs) {
+    return function(cm) {
+      var cur = cm.getCursor(), around = charsAround(cm, cur);
+      if (!around || pairs.indexOf(around) % 2 != 0) return CodeMirror.Pass;
+      cm.operation(function() {
+        var newPos = CodeMirror.Pos(cur.line + 1, 0);
+        cm.replaceSelection("\n\n", {anchor: newPos, head: newPos}, "+input");
+        cm.indentLine(cur.line + 1, null, true);
+        cm.indentLine(cur.line + 2, null, true);
+      });
+    };
+  }
+})();
diff --git a/third-party/codemirror-3.15/addon/edit/closetag.js b/third-party/codemirror-3.15/addon/edit/closetag.js
new file mode 100644 (file)
index 0000000..454dfea
--- /dev/null
@@ -0,0 +1,86 @@
+/**
+ * Tag-closer extension for CodeMirror.
+ *
+ * This extension adds an "autoCloseTags" option that can be set to
+ * either true to get the default behavior, or an object to further
+ * configure its behavior.
+ *
+ * These are supported options:
+ *
+ * `whenClosing` (default true)
+ *   Whether to autoclose when the '/' of a closing tag is typed.
+ * `whenOpening` (default true)
+ *   Whether to autoclose the tag when the final '>' of an opening
+ *   tag is typed.
+ * `dontCloseTags` (default is empty tags for HTML, none for XML)
+ *   An array of tag names that should not be autoclosed.
+ * `indentTags` (default is block tags for HTML, none for XML)
+ *   An array of tag names that should, when opened, cause a
+ *   blank line to be added inside the tag, and the blank line and
+ *   closing line to be indented.
+ *
+ * See demos/closetag.html for a usage example.
+ */
+
+(function() {
+  CodeMirror.defineOption("autoCloseTags", false, function(cm, val, old) {
+    if (val && (old == CodeMirror.Init || !old)) {
+      var map = {name: "autoCloseTags"};
+      if (typeof val != "object" || val.whenClosing)
+        map["'/'"] = function(cm) { return autoCloseTag(cm, '/'); };
+      if (typeof val != "object" || val.whenOpening)
+        map["'>'"] = function(cm) { return autoCloseTag(cm, '>'); };
+      cm.addKeyMap(map);
+    } else if (!val && (old != CodeMirror.Init && old)) {
+      cm.removeKeyMap("autoCloseTags");
+    }
+  });
+
+  var htmlDontClose = ["area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "meta", "param",
+                       "source", "track", "wbr"];
+  var htmlIndent = ["applet", "blockquote", "body", "button", "div", "dl", "fieldset", "form", "frameset", "h1", "h2", "h3", "h4",
+                    "h5", "h6", "head", "html", "iframe", "layer", "legend", "object", "ol", "p", "select", "table", "ul"];
+
+  function autoCloseTag(cm, ch) {
+    var pos = cm.getCursor(), tok = cm.getTokenAt(pos);
+    var inner = CodeMirror.innerMode(cm.getMode(), tok.state), state = inner.state;
+    if (inner.mode.name != "xml") return CodeMirror.Pass;
+
+    var opt = cm.getOption("autoCloseTags"), html = inner.mode.configuration == "html";
+    var dontCloseTags = (typeof opt == "object" && opt.dontCloseTags) || (html && htmlDontClose);
+    var indentTags = (typeof opt == "object" && opt.indentTags) || (html && htmlIndent);
+
+    if (ch == ">" && state.tagName) {
+      var tagName = state.tagName;
+      if (tok.end > pos.ch) tagName = tagName.slice(0, tagName.length - tok.end + pos.ch);
+      var lowerTagName = tagName.toLowerCase();
+      // Don't process the '>' at the end of an end-tag or self-closing tag
+      if (tok.type == "tag" && state.type == "closeTag" ||
+          tok.string.indexOf("/") == (tok.string.length - 1) || // match something like <someTagName />
+          dontCloseTags && indexOf(dontCloseTags, lowerTagName) > -1)
+        return CodeMirror.Pass;
+
+      var doIndent = indentTags && indexOf(indentTags, lowerTagName) > -1;
+      var curPos = doIndent ? CodeMirror.Pos(pos.line + 1, 0) : CodeMirror.Pos(pos.line, pos.ch + 1);
+      cm.replaceSelection(">" + (doIndent ? "\n\n" : "") + "</" + tagName + ">",
+                          {head: curPos, anchor: curPos});
+      if (doIndent) {
+        cm.indentLine(pos.line + 1);
+        cm.indentLine(pos.line + 2);
+      }
+      return;
+    } else if (ch == "/" && tok.string == "<") {
+      var tagName = state.context && state.context.tagName;
+      if (tagName) cm.replaceSelection("/" + tagName + ">", "end");
+      return;
+    }
+    return CodeMirror.Pass;
+  }
+
+  function indexOf(collection, elt) {
+    if (collection.indexOf) return collection.indexOf(elt);
+    for (var i = 0, e = collection.length; i < e; ++i)
+      if (collection[i] == elt) return i;
+    return -1;
+  }
+})();
diff --git a/third-party/codemirror-3.15/addon/edit/continuecomment.js b/third-party/codemirror-3.15/addon/edit/continuecomment.js
new file mode 100644 (file)
index 0000000..3080262
--- /dev/null
@@ -0,0 +1,44 @@
+(function() {
+  var modes = ["clike", "css", "javascript"];
+  for (var i = 0; i < modes.length; ++i)
+    CodeMirror.extendMode(modes[i], {blockCommentStart: "/*",
+                                     blockCommentEnd: "*/",
+                                     blockCommentContinue: " * "});
+
+  function continueComment(cm) {
+    var pos = cm.getCursor(), token = cm.getTokenAt(pos);
+    var mode = CodeMirror.innerMode(cm.getMode(), token.state).mode;
+    var space;
+
+    if (token.type == "comment" && mode.blockCommentStart) {
+      var end = token.string.indexOf(mode.blockCommentEnd);
+      var full = cm.getRange(CodeMirror.Pos(pos.line, 0), CodeMirror.Pos(pos.line, token.end)), found;
+      if (end != -1 && end == token.string.length - mode.blockCommentEnd.length) {
+        // Comment ended, don't continue it
+      } else if (token.string.indexOf(mode.blockCommentStart) == 0) {
+        space = full.slice(0, token.start);
+        if (!/^\s*$/.test(space)) {
+          space = "";
+          for (var i = 0; i < token.start; ++i) space += " ";
+        }
+      } else if ((found = full.indexOf(mode.blockCommentContinue)) != -1 &&
+                 found + mode.blockCommentContinue.length > token.start &&
+                 /^\s*$/.test(full.slice(0, found))) {
+        space = full.slice(0, found);
+      }
+    }
+
+    if (space != null)
+      cm.replaceSelection("\n" + space + mode.blockCommentContinue, "end");
+    else
+      return CodeMirror.Pass;
+  }
+
+  CodeMirror.defineOption("continueComments", null, function(cm, val, prev) {
+    if (prev && prev != CodeMirror.Init)
+      cm.removeKeyMap("continueComment");
+    var map = {name: "continueComment"};
+    map[typeof val == "string" ? val : "Enter"] = continueComment;
+    cm.addKeyMap(map);
+  });
+})();
diff --git a/third-party/codemirror-3.15/addon/edit/continuelist.js b/third-party/codemirror-3.15/addon/edit/continuelist.js
new file mode 100644 (file)
index 0000000..fb1fc38
--- /dev/null
@@ -0,0 +1,25 @@
+(function() {
+  'use strict';
+
+  var listRE = /^(\s*)([*+-]|(\d+)\.)(\s*)/,
+      unorderedBullets = '*+-';
+
+  CodeMirror.commands.newlineAndIndentContinueMarkdownList = function(cm) {
+    var pos = cm.getCursor(),
+        inList = cm.getStateAfter(pos.line).list,
+        match;
+
+    if (!inList || !(match = cm.getLine(pos.line).match(listRE))) {
+      cm.execCommand('newlineAndIndent');
+      return;
+    }
+
+    var indent = match[1], after = match[4];
+    var bullet = unorderedBullets.indexOf(match[2]) >= 0
+      ? match[2]
+      : (parseInt(match[3], 10) + 1) + '.';
+
+    cm.replaceSelection('\n' + indent + bullet + after, 'end');
+  };
+
+}());
diff --git a/third-party/codemirror-3.15/addon/edit/matchbrackets.js b/third-party/codemirror-3.15/addon/edit/matchbrackets.js
new file mode 100644 (file)
index 0000000..131fe83
--- /dev/null
@@ -0,0 +1,86 @@
+(function() {
+  var ie_lt8 = /MSIE \d/.test(navigator.userAgent) &&
+    (document.documentMode == null || document.documentMode < 8);
+
+  var Pos = CodeMirror.Pos;
+
+  var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<"};
+  function findMatchingBracket(cm, where, strict) {
+    var state = cm.state.matchBrackets;
+    var maxScanLen = (state && state.maxScanLineLength) || 10000;
+
+    var cur = where || cm.getCursor(), line = cm.getLineHandle(cur.line), pos = cur.ch - 1;
+    var match = (pos >= 0 && matching[line.text.charAt(pos)]) || matching[line.text.charAt(++pos)];
+    if (!match) return null;
+    var forward = match.charAt(1) == ">", d = forward ? 1 : -1;
+    if (strict && forward != (pos == cur.ch)) return null;
+    var style = cm.getTokenTypeAt(Pos(cur.line, pos + 1));
+
+    var stack = [line.text.charAt(pos)], re = /[(){}[\]]/;
+    function scan(line, lineNo, start) {
+      if (!line.text) return;
+      var pos = forward ? 0 : line.text.length - 1, end = forward ? line.text.length : -1;
+      if (line.text.length > maxScanLen) return null;
+      if (start != null) pos = start + d;
+      for (; pos != end; pos += d) {
+        var ch = line.text.charAt(pos);
+        if (re.test(ch) && cm.getTokenTypeAt(Pos(lineNo, pos + 1)) == style) {
+          var match = matching[ch];
+          if (match.charAt(1) == ">" == forward) stack.push(ch);
+          else if (stack.pop() != match.charAt(0)) return {pos: pos, match: false};
+          else if (!stack.length) return {pos: pos, match: true};
+        }
+      }
+    }
+    for (var i = cur.line, found, e = forward ? Math.min(i + 100, cm.lineCount()) : Math.max(-1, i - 100); i != e; i+=d) {
+      if (i == cur.line) found = scan(line, i, pos);
+      else found = scan(cm.getLineHandle(i), i);
+      if (found) break;
+    }
+    return {from: Pos(cur.line, pos), to: found && Pos(i, found.pos),
+            match: found && found.match, forward: forward};
+  }
+
+  function matchBrackets(cm, autoclear) {
+    // Disable brace matching in long lines, since it'll cause hugely slow updates
+    var maxHighlightLen = cm.state.matchBrackets.maxHighlightLineLength || 1000;
+    var found = findMatchingBracket(cm);
+    if (!found || cm.getLine(found.from.line).length > maxHighlightLen ||
+       found.to && cm.getLine(found.to.line).length > maxHighlightLen)
+      return;
+
+    var style = found.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket";
+    var one = cm.markText(found.from, Pos(found.from.line, found.from.ch + 1), {className: style});
+    var two = found.to && cm.markText(found.to, Pos(found.to.line, found.to.ch + 1), {className: style});
+    // Kludge to work around the IE bug from issue #1193, where text
+    // input stops going to the textare whever this fires.
+    if (ie_lt8 && cm.state.focused) cm.display.input.focus();
+    var clear = function() {
+      cm.operation(function() { one.clear(); two && two.clear(); });
+    };
+    if (autoclear) setTimeout(clear, 800);
+    else return clear;
+  }
+
+  var currentlyHighlighted = null;
+  function doMatchBrackets(cm) {
+    cm.operation(function() {
+      if (currentlyHighlighted) {currentlyHighlighted(); currentlyHighlighted = null;}
+      if (!cm.somethingSelected()) currentlyHighlighted = matchBrackets(cm, false);
+    });
+  }
+
+  CodeMirror.defineOption("matchBrackets", false, function(cm, val, old) {
+    if (old && old != CodeMirror.Init)
+      cm.off("cursorActivity", doMatchBrackets);
+    if (val) {
+      cm.state.matchBrackets = typeof val == "object" ? val : {};
+      cm.on("cursorActivity", doMatchBrackets);
+    }
+  });
+
+  CodeMirror.defineExtension("matchBrackets", function() {matchBrackets(this, true);});
+  CodeMirror.defineExtension("findMatchingBracket", function(pos, strict){
+    return findMatchingBracket(this, pos, strict);
+  });
+})();
diff --git a/third-party/codemirror-3.15/addon/edit/matchtags.js b/third-party/codemirror-3.15/addon/edit/matchtags.js
new file mode 100644 (file)
index 0000000..3eabfeb
--- /dev/null
@@ -0,0 +1,51 @@
+(function() {
+  "use strict";
+
+  CodeMirror.defineOption("matchTags", false, function(cm, val, old) {
+    if (old && old != CodeMirror.Init) {
+      cm.off("cursorActivity", doMatchTags);
+      cm.off("viewportChange", maybeUpdateMatch);
+      clear(cm);
+    }
+    if (val) {
+      cm.on("cursorActivity", doMatchTags);
+      cm.on("viewportChange", maybeUpdateMatch);
+      doMatchTags(cm);
+    }
+  });
+
+  function clear(cm) {
+    if (cm.state.matchedTag) {
+      cm.state.matchedTag.clear();
+      cm.state.matchedTag = null;
+    }
+  }
+
+  function doMatchTags(cm) {
+    cm.state.failedTagMatch = false;
+    cm.operation(function() {
+      clear(cm);
+      var cur = cm.getCursor(), range = cm.getViewport();
+      range.from = Math.min(range.from, cur.line); range.to = Math.max(cur.line + 1, range.to);
+      var match = CodeMirror.findMatchingTag(cm, cur, range);
+      if (!match) return;
+      var other = match.at == "close" ? match.open : match.close;
+      if (other)
+        cm.state.matchedTag = cm.markText(other.from, other.to, {className: "CodeMirror-matchingtag"});
+      else
+        cm.state.failedTagMatch = true;
+    });
+  }
+
+  function maybeUpdateMatch(cm) {
+    if (cm.state.failedTagMatch) doMatchTags(cm);
+  }
+
+  CodeMirror.commands.toMatchingTag = function(cm) {
+    var found = CodeMirror.findMatchingTag(cm, cm.getCursor());
+    if (found) {
+      var other = found.at == "close" ? found.open : found.close;
+      if (other) cm.setSelection(other.to, other.from);
+    }
+  };
+})();
diff --git a/third-party/codemirror-3.15/addon/edit/trailingspace.js b/third-party/codemirror-3.15/addon/edit/trailingspace.js
new file mode 100644 (file)
index 0000000..f6bb026
--- /dev/null
@@ -0,0 +1,15 @@
+CodeMirror.defineOption("showTrailingSpace", false, function(cm, val, prev) {
+  if (prev == CodeMirror.Init) prev = false;
+  if (prev && !val)
+    cm.removeOverlay("trailingspace");
+  else if (!prev && val)
+    cm.addOverlay({
+      token: function(stream) {
+        for (var l = stream.string.length, i = l; i && /\s/.test(stream.string.charAt(i - 1)); --i) {}
+        if (i > stream.pos) { stream.pos = i; return null; }
+        stream.pos = l;
+        return "trailingspace";
+      },
+      name: "trailingspace"
+    });
+});
diff --git a/third-party/codemirror-3.15/addon/fold/brace-fold.js b/third-party/codemirror-3.15/addon/fold/brace-fold.js
new file mode 100644 (file)
index 0000000..0b4d7dc
--- /dev/null
@@ -0,0 +1,93 @@
+CodeMirror.registerHelper("fold", "brace", function(cm, start) {
+  var line = start.line, lineText = cm.getLine(line);
+  var startCh, tokenType;
+
+  function findOpening(openCh) {
+    for (var at = start.ch, pass = 0;;) {
+      var found = lineText.lastIndexOf(openCh, at - 1);
+      if (found == -1) {
+        if (pass == 1) break;
+        pass = 1;
+        at = lineText.length;
+        continue;
+      }
+      if (pass == 1 && found < start.ch) break;
+      tokenType = cm.getTokenAt(CodeMirror.Pos(line, found + 1)).type;
+      if (!/^(comment|string)/.test(tokenType)) return found + 1;
+      at = found - 1;
+    }
+  }
+
+  var startToken = "{", endToken = "}", startCh = findOpening("{");
+  if (startCh == null) {
+    startToken = "[", endToken = "]";
+    startCh = findOpening("[");
+  }
+
+  if (startCh == null) return;
+  var count = 1, lastLine = cm.lastLine(), end, endCh;
+  outer: for (var i = line; i <= lastLine; ++i) {
+    var text = cm.getLine(i), pos = i == line ? startCh : 0;
+    for (;;) {
+      var nextOpen = text.indexOf(startToken, pos), nextClose = text.indexOf(endToken, pos);
+      if (nextOpen < 0) nextOpen = text.length;
+      if (nextClose < 0) nextClose = text.length;
+      pos = Math.min(nextOpen, nextClose);
+      if (pos == text.length) break;
+      if (cm.getTokenAt(CodeMirror.Pos(i, pos + 1)).type == tokenType) {
+        if (pos == nextOpen) ++count;
+        else if (!--count) { end = i; endCh = pos; break outer; }
+      }
+      ++pos;
+    }
+  }
+  if (end == null || line == end && endCh == startCh) return;
+  return {from: CodeMirror.Pos(line, startCh),
+          to: CodeMirror.Pos(end, endCh)};
+});
+CodeMirror.braceRangeFinder = CodeMirror.fold.brace; // deprecated
+
+CodeMirror.registerHelper("fold", "import", function(cm, start) {
+  function hasImport(line) {
+    if (line < cm.firstLine() || line > cm.lastLine()) return null;
+    var start = cm.getTokenAt(CodeMirror.Pos(line, 1));
+    if (!/\S/.test(start.string)) start = cm.getTokenAt(CodeMirror.Pos(line, start.end + 1));
+    if (start.type != "keyword" || start.string != "import") return null;
+    // Now find closing semicolon, return its position
+    for (var i = line, e = Math.min(cm.lastLine(), line + 10); i <= e; ++i) {
+      var text = cm.getLine(i), semi = text.indexOf(";");
+      if (semi != -1) return {startCh: start.end, end: CodeMirror.Pos(i, semi)};
+    }
+  }
+
+  var start = start.line, has = hasImport(start), prev;
+  if (!has || hasImport(start - 1) || ((prev = hasImport(start - 2)) && prev.end.line == start - 1))
+    return null;
+  for (var end = has.end;;) {
+    var next = hasImport(end.line + 1);
+    if (next == null) break;
+    end = next.end;
+  }
+  return {from: cm.clipPos(CodeMirror.Pos(start, has.startCh + 1)), to: end};
+});
+CodeMirror.importRangeFinder = CodeMirror.fold["import"]; // deprecated
+
+CodeMirror.registerHelper("fold", "include", function(cm, start) {
+  function hasInclude(line) {
+    if (line < cm.firstLine() || line > cm.lastLine()) return null;
+    var start = cm.getTokenAt(CodeMirror.Pos(line, 1));
+    if (!/\S/.test(start.string)) start = cm.getTokenAt(CodeMirror.Pos(line, start.end + 1));
+    if (start.type == "meta" && start.string.slice(0, 8) == "#include") return start.start + 8;
+  }
+
+  var start = start.line, has = hasInclude(start);
+  if (has == null || hasInclude(start - 1) != null) return null;
+  for (var end = start;;) {
+    var next = hasInclude(end + 1);
+    if (next == null) break;
+    ++end;
+  }
+  return {from: CodeMirror.Pos(start, has + 1),
+          to: cm.clipPos(CodeMirror.Pos(end))};
+});
+CodeMirror.includeRangeFinder = CodeMirror.fold.include; // deprecated
diff --git a/third-party/codemirror-3.15/addon/fold/foldcode.js b/third-party/codemirror-3.15/addon/fold/foldcode.js
new file mode 100644 (file)
index 0000000..931c372
--- /dev/null
@@ -0,0 +1,73 @@
+(function() {
+  "use strict";
+
+  function doFold(cm, pos, options) {
+    var finder = options && (options.call ? options : options.rangeFinder);
+    if (!finder) finder = cm.getHelper(pos, "fold");
+    if (!finder) return;
+    if (typeof pos == "number") pos = CodeMirror.Pos(pos, 0);
+    var minSize = options && options.minFoldSize || 0;
+
+    function getRange(allowFolded) {
+      var range = finder(cm, pos);
+      if (!range || range.to.line - range.from.line < minSize) return null;
+      var marks = cm.findMarksAt(range.from);
+      for (var i = 0; i < marks.length; ++i) {
+        if (marks[i].__isFold) {
+          if (!allowFolded) return null;
+          range.cleared = true;
+          marks[i].clear();
+        }
+      }
+      return range;
+    }
+
+    var range = getRange(true);
+    if (options && options.scanUp) while (!range && pos.line > cm.firstLine()) {
+      pos = CodeMirror.Pos(pos.line - 1, 0);
+      range = getRange(false);
+    }
+    if (!range || range.cleared) return;
+
+    var myWidget = makeWidget(options);
+    CodeMirror.on(myWidget, "mousedown", function() { myRange.clear(); });
+    var myRange = cm.markText(range.from, range.to, {
+      replacedWith: myWidget,
+      clearOnEnter: true,
+      __isFold: true
+    });
+    myRange.on("clear", function(from, to) {
+      CodeMirror.signal(cm, "unfold", cm, from, to);
+    });
+    CodeMirror.signal(cm, "fold", cm, range.from, range.to);
+  }
+
+  function makeWidget(options) {
+    var widget = (options && options.widget) || "\u2194";
+    if (typeof widget == "string") {
+      var text = document.createTextNode(widget);
+      widget = document.createElement("span");
+      widget.appendChild(text);
+      widget.className = "CodeMirror-foldmarker";
+    }
+    return widget;
+  }
+
+  // Clumsy backwards-compatible interface
+  CodeMirror.newFoldFunction = function(rangeFinder, widget) {
+    return function(cm, pos) { doFold(cm, pos, {rangeFinder: rangeFinder, widget: widget}); };
+  };
+
+  // New-style interface
+  CodeMirror.defineExtension("foldCode", function(pos, options) { doFold(this, pos, options); });
+
+  CodeMirror.registerHelper("fold", "combine", function() {
+    var funcs = Array.prototype.slice.call(arguments, 0);
+    return function(cm, start) {
+      for (var i = 0; i < funcs.length; ++i) {
+        var found = funcs[i](cm, start);
+        if (found) return found;
+      }
+    };
+  });
+})();
diff --git a/third-party/codemirror-3.15/addon/fold/foldgutter.js b/third-party/codemirror-3.15/addon/fold/foldgutter.js
new file mode 100644 (file)
index 0000000..b809c93
--- /dev/null
@@ -0,0 +1,122 @@
+(function() {
+  "use strict";
+
+  CodeMirror.defineOption("foldGutter", false, function(cm, val, old) {
+    if (old && old != CodeMirror.Init) {
+      cm.clearGutter(cm.state.foldGutter.options.gutter);
+      cm.state.foldGutter = null;
+      cm.off("gutterClick", onGutterClick);
+      cm.off("change", onChange);
+      cm.off("viewportChange", onViewportChange);
+      cm.off("fold", onFold);
+      cm.off("unfold", onFold);
+    }
+    if (val) {
+      cm.state.foldGutter = new State(parseOptions(val));
+      updateInViewport(cm);
+      cm.on("gutterClick", onGutterClick);
+      cm.on("change", onChange);
+      cm.on("viewportChange", onViewportChange);
+      cm.on("fold", onFold);
+      cm.on("unfold", onFold);
+    }
+  });
+
+  var Pos = CodeMirror.Pos;
+
+  function State(options) {
+    this.options = options;
+    this.from = this.to = 0;
+  }
+
+  function parseOptions(opts) {
+    if (opts === true) opts = {};
+    if (opts.gutter == null) opts.gutter = "CodeMirror-foldgutter";
+    if (opts.indicatorOpen == null) opts.indicatorOpen = "CodeMirror-foldgutter-open";
+    if (opts.indicatorFolded == null) opts.indicatorFolded = "CodeMirror-foldgutter-folded";
+    return opts;
+  }
+
+  function isFolded(cm, line) {
+    var marks = cm.findMarksAt(Pos(line));
+    for (var i = 0; i < marks.length; ++i)
+      if (marks[i].__isFold && marks[i].find().from.line == line) return true;
+  }
+
+  function marker(spec) {
+    if (typeof spec == "string") {
+      var elt = document.createElement("div");
+      elt.className = spec;
+      return elt;
+    } else {
+      return spec.cloneNode(true);
+    }
+  }
+
+  function updateFoldInfo(cm, from, to) {
+    var opts = cm.state.foldGutter.options, cur = from;
+    cm.eachLine(from, to, function(line) {
+      var mark = null;
+      if (isFolded(cm, cur)) {
+        mark = marker(opts.indicatorFolded);
+      } else {
+        var pos = Pos(cur, 0), func = opts.rangeFinder || cm.getHelper(pos, "fold");
+        var range = func && func(cm, pos);
+        if (range && range.from.line + 1 < range.to.line)
+          mark = marker(opts.indicatorOpen);
+      }
+      cm.setGutterMarker(line, opts.gutter, mark);
+      ++cur;
+    });
+  }
+
+  function updateInViewport(cm) {
+    var vp = cm.getViewport(), state = cm.state.foldGutter;
+    if (!state) return;
+    cm.operation(function() {
+      updateFoldInfo(cm, vp.from, vp.to);
+    });
+    state.from = vp.from; state.to = vp.to;
+  }
+
+  function onGutterClick(cm, line, gutter) {
+    var opts = cm.state.foldGutter.options;
+    if (gutter != opts.gutter) return;
+    cm.foldCode(Pos(line, 0), opts.rangeFinder);
+  }
+
+  function onChange(cm) {
+    var state = cm.state.foldGutter;
+    state.from = state.to = 0;
+    clearTimeout(state.changeUpdate);
+    state.changeUpdate = setTimeout(function() { updateInViewport(cm); }, 600);
+  }
+
+  function onViewportChange(cm) {
+    var state = cm.state.foldGutter;
+    clearTimeout(state.changeUpdate);
+    state.changeUpdate = setTimeout(function() {
+      var vp = cm.getViewport();
+      if (state.from == state.to || vp.from - state.to > 20 || state.from - vp.to > 20) {
+        updateInViewport(cm);
+      } else {
+        cm.operation(function() {
+          if (vp.from < state.from) {
+            updateFoldInfo(cm, vp.from, state.from);
+            state.from = vp.from;
+          }
+          if (vp.to > state.to) {
+            updateFoldInfo(cm, state.to, vp.to);
+            state.to = vp.to;
+          }
+        });
+      }
+    }, 400);
+  }
+
+  function onFold(cm, from) {
+    var state = cm.state.foldGutter, line = from.line;
+    if (line >= state.from && line < state.to)
+      updateFoldInfo(cm, line, line + 1);
+  }
+})();
diff --git a/third-party/codemirror-3.15/addon/fold/indent-fold.js b/third-party/codemirror-3.15/addon/fold/indent-fold.js
new file mode 100644 (file)
index 0000000..fcbff96
--- /dev/null
@@ -0,0 +1,12 @@
+CodeMirror.registerHelper("fold", "indent", function(cm, start) {
+  var tabSize = cm.getOption("tabSize"), firstLine = cm.getLine(start.line);
+  var myIndent = CodeMirror.countColumn(firstLine, null, tabSize);
+  for (var i = start.line + 1, end = cm.lineCount(); i < end; ++i) {
+    var curLine = cm.getLine(i);
+    if (CodeMirror.countColumn(curLine, null, tabSize) < myIndent &&
+        CodeMirror.countColumn(cm.getLine(i-1), null, tabSize) > myIndent)
+      return {from: CodeMirror.Pos(start.line, firstLine.length),
+              to: CodeMirror.Pos(i, curLine.length)};
+  }
+});
+CodeMirror.indentRangeFinder = CodeMirror.fold.indent; // deprecated
diff --git a/third-party/codemirror-3.15/addon/fold/xml-fold.js b/third-party/codemirror-3.15/addon/fold/xml-fold.js
new file mode 100644 (file)
index 0000000..88a107c
--- /dev/null
@@ -0,0 +1,167 @@
+(function() {
+  "use strict";
+
+  var Pos = CodeMirror.Pos;
+  function cmp(a, b) { return a.line - b.line || a.ch - b.ch; }
+
+  var nameStartChar = "A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";
+  var nameChar = nameStartChar + "\-\:\.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
+  var xmlTagStart = new RegExp("<(/?)([" + nameStartChar + "][" + nameChar + "]*)", "g");
+
+  function Iter(cm, line, ch, range) {
+    this.line = line; this.ch = ch;
+    this.cm = cm; this.text = cm.getLine(line);
+    this.min = range ? range.from : cm.firstLine();
+    this.max = range ? range.to - 1 : cm.lastLine();
+  }
+
+  function tagAt(iter, ch) {
+    var type = iter.cm.getTokenTypeAt(Pos(iter.line, ch));
+    return type && /\btag\b/.test(type);
+  }
+
+  function nextLine(iter) {
+    if (iter.line >= iter.max) return;
+    iter.ch = 0;
+    iter.text = iter.cm.getLine(++iter.line);
+    return true;
+  }
+  function prevLine(iter) {
+    if (iter.line <= iter.min) return;
+    iter.text = iter.cm.getLine(--iter.line);
+    iter.ch = iter.text.length;
+    return true;
+  }
+
+  function toTagEnd(iter) {
+    for (;;) {
+      var gt = iter.text.indexOf(">", iter.ch);
+      if (gt == -1) { if (nextLine(iter)) continue; else return; }
+      if (!tagAt(iter, gt + 1)) { iter.ch = gt + 1; continue; }
+      var lastSlash = iter.text.lastIndexOf("/", gt);
+      var selfClose = lastSlash > -1 && !/\S/.test(iter.text.slice(lastSlash + 1, gt));
+      iter.ch = gt + 1;
+      return selfClose ? "selfClose" : "regular";
+    }
+  }
+  function toTagStart(iter) {
+    for (;;) {
+      var lt = iter.ch ? iter.text.lastIndexOf("<", iter.ch - 1) : -1;
+      if (lt == -1) { if (prevLine(iter)) continue; else return; }
+      if (!tagAt(iter, lt + 1)) { iter.ch = lt; continue; }
+      xmlTagStart.lastIndex = lt;
+      iter.ch = lt;
+      var match = xmlTagStart.exec(iter.text);
+      if (match && match.index == lt) return match;
+    }
+  }
+
+  function toNextTag(iter) {
+    for (;;) {
+      xmlTagStart.lastIndex = iter.ch;
+      var found = xmlTagStart.exec(iter.text);
+      if (!found) { if (nextLine(iter)) continue; else return; }
+      if (!tagAt(iter, found.index + 1)) { iter.ch = found.index + 1; continue; }
+      iter.ch = found.index + found[0].length;
+      return found;
+    }
+  }
+  function toPrevTag(iter) {
+    for (;;) {
+      var gt = iter.ch ? iter.text.lastIndexOf(">", iter.ch - 1) : -1;
+      if (gt == -1) { if (prevLine(iter)) continue; else return; }
+      if (!tagAt(iter, gt + 1)) { iter.ch = gt; continue; }
+      var lastSlash = iter.text.lastIndexOf("/", gt);
+      var selfClose = lastSlash > -1 && !/\S/.test(iter.text.slice(lastSlash + 1, gt));
+      iter.ch = gt + 1;
+      return selfClose ? "selfClose" : "regular";
+    }
+  }
+
+  function findMatchingClose(iter, tag) {
+    var stack = [];
+    for (;;) {
+      var next = toNextTag(iter), end, startLine = iter.line, startCh = iter.ch - (next ? next[0].length : 0);
+      if (!next || !(end = toTagEnd(iter))) return;
+      if (end == "selfClose") continue;
+      if (next[1]) { // closing tag
+        for (var i = stack.length - 1; i >= 0; --i) if (stack[i] == next[2]) {
+          stack.length = i;
+          break;
+        }
+        if (i < 0 && (!tag || tag == next[2])) return {
+          tag: next[2],
+          from: Pos(startLine, startCh),
+          to: Pos(iter.line, iter.ch)
+        };
+      } else { // opening tag
+        stack.push(next[2]);
+      }
+    }
+  }
+  function findMatchingOpen(iter, tag) {
+    var stack = [];
+    for (;;) {
+      var prev = toPrevTag(iter);
+      if (!prev) return;
+      if (prev == "selfClose") { toTagStart(iter); continue; }
+      var endLine = iter.line, endCh = iter.ch;
+      var start = toTagStart(iter);
+      if (!start) return;
+      if (start[1]) { // closing tag
+        stack.push(start[2]);
+      } else { // opening tag
+        for (var i = stack.length - 1; i >= 0; --i) if (stack[i] == start[2]) {
+          stack.length = i;
+          break;
+        }
+        if (i < 0 && (!tag || tag == start[2])) return {
+          tag: start[2],
+          from: Pos(iter.line, iter.ch),
+          to: Pos(endLine, endCh)
+        };
+      }
+    }
+  }
+
+  CodeMirror.registerHelper("fold", "xml", function(cm, start) {
+    var iter = new Iter(cm, start.line, 0);
+    for (;;) {
+      var openTag = toNextTag(iter), end;
+      if (!openTag || iter.line != start.line || !(end = toTagEnd(iter))) return;
+      if (!openTag[1] && end != "selfClose") {
+        var start = Pos(iter.line, iter.ch);
+        var close = findMatchingClose(iter, openTag[2]);
+        return close && {from: start, to: close.from};
+      }
+    }
+  });
+  CodeMirror.tagRangeFinder = CodeMirror.fold.xml; // deprecated
+
+  CodeMirror.findMatchingTag = function(cm, pos, range) {
+    var iter = new Iter(cm, pos.line, pos.ch, range);
+    if (iter.text.indexOf(">") == -1 && iter.text.indexOf("<") == -1) return;
+    var end = toTagEnd(iter), to = end && Pos(iter.line, iter.ch);
+    var start = end && toTagStart(iter);
+    if (!end || end == "selfClose" || !start || cmp(iter, pos) > 0) return;
+    var here = {from: Pos(iter.line, iter.ch), to: to, tag: start[2]};
+
+    if (start[1]) { // closing tag
+      return {open: findMatchingOpen(iter, start[2]), close: here, at: "close"};
+    } else { // opening tag
+      iter = new Iter(cm, to.line, to.ch, range);
+      return {open: here, close: findMatchingClose(iter, start[2]), at: "open"};
+    }
+  };
+
+  CodeMirror.findEnclosingTag = function(cm, pos, range) {
+    var iter = new Iter(cm, pos.line, pos.ch, range);
+    for (;;) {
+      var open = findMatchingOpen(iter);
+      if (!open) break;
+      var forward = new Iter(cm, pos.line, pos.ch, range);
+      var close = findMatchingClose(forward, open.tag);
+      if (close) return {open: open, close: close};
+    }
+  };
+})();
diff --git a/third-party/codemirror-3.15/addon/hint/anyword-hint.js b/third-party/codemirror-3.15/addon/hint/anyword-hint.js
new file mode 100644 (file)
index 0000000..36ff618
--- /dev/null
@@ -0,0 +1,34 @@
+(function() {
+  "use strict";
+
+  var WORD = /[\w$]+/, RANGE = 500;
+
+  CodeMirror.registerHelper("hint", "anyword", function(editor, options) {
+    var word = options && options.word || WORD;
+    var range = options && options.range || RANGE;
+    var cur = editor.getCursor(), curLine = editor.getLine(cur.line);
+    var start = cur.ch, end = start;
+    while (end < curLine.length && word.test(curLine.charAt(end))) ++end;
+    while (start && word.test(curLine.charAt(start - 1))) --start;
+    var curWord = start != end && curLine.slice(start, end);
+
+    var list = [], seen = {};
+    function scan(dir) {
+      var line = cur.line, end = Math.min(Math.max(line + dir * range, editor.firstLine()), editor.lastLine()) + dir;
+      for (; line != end; line += dir) {
+        var text = editor.getLine(line), m;
+        var re = new RegExp(word.source, "g");
+        while (m = re.exec(text)) {
+          if (line == cur.line && m[0] === curWord) continue;
+          if ((!curWord || m[0].indexOf(curWord) == 0) && !seen.hasOwnProperty(m[0])) {
+            seen[m[0]] = true;
+            list.push(m[0]);
+          }
+        }
+      }
+    }
+    scan(-1);
+    scan(1);
+    return {list: list, from: CodeMirror.Pos(cur.line, start), to: CodeMirror.Pos(cur.line, end)};
+  });
+})();
diff --git a/third-party/codemirror-3.15/addon/hint/html-hint.js b/third-party/codemirror-3.15/addon/hint/html-hint.js
new file mode 100755 (executable)
index 0000000..cf25685
--- /dev/null
@@ -0,0 +1,337 @@
+(function () {
+  var langs = "ab aa af ak sq am ar an hy as av ae ay az bm ba eu be bn bh bi bs br bg my ca ch ce ny zh cv kw co cr hr cs da dv nl dz en eo et ee fo fj fi fr ff gl ka de el gn gu ht ha he hz hi ho hu ia id ie ga ig ik io is it iu ja jv kl kn kr ks kk km ki rw ky kv kg ko ku kj la lb lg li ln lo lt lu lv gv mk mg ms ml mt mi mr mh mn na nv nb nd ne ng nn no ii nr oc oj cu om or os pa pi fa pl ps pt qu rm rn ro ru sa sc sd se sm sg sr gd sn si sk sl so st es su sw ss sv ta te tg th ti bo tk tl tn to tr ts tt tw ty ug uk ur uz ve vi vo wa cy wo fy xh yi yo za zu".split(" ");
+  var targets = ["_blank", "_self", "_top", "_parent"];
+  var charsets = ["ascii", "utf-8", "utf-16", "latin1", "latin1"];
+  var methods = ["get", "post", "put", "delete"];
+  var encs = ["application/x-www-form-urlencoded", "multipart/form-data", "text/plain"];
+  var media = ["all", "screen", "print", "embossed", "braille", "handheld", "print", "projection", "screen", "tty", "tv", "speech",
+               "3d-glasses", "resolution [>][<][=] [X]", "device-aspect-ratio: X/Y", "orientation:portrait",
+               "orientation:landscape", "device-height: [X]", "device-width: [X]"];
+  var s = { attrs: {} }; // Simple tag, reused for a whole lot of tags
+
+  var data = {
+    a: {
+      attrs: {
+        href: null, ping: null, type: null,
+        media: media,
+        target: targets,
+        hreflang: langs
+      }
+    },
+    abbr: s,
+    acronym: s,
+    address: s,
+    applet: s,
+    area: {
+      attrs: {
+        alt: null, coords: null, href: null, target: null, ping: null,
+        media: media, hreflang: langs, type: null,
+        shape: ["default", "rect", "circle", "poly"]
+      }
+    },
+    article: s,
+    aside: s,
+    audio: {
+      attrs: {
+        src: null, mediagroup: null,
+        crossorigin: ["anonymous", "use-credentials"],
+        preload: ["none", "metadata", "auto"],
+        autoplay: ["", "autoplay"],
+        loop: ["", "loop"],
+        controls: ["", "controls"]
+      }
+    },
+    b: s,
+    base: { attrs: { href: null, target: targets } },
+    basefont: s,
+    bdi: s,
+    bdo: s,
+    big: s,
+    blockquote: { attrs: { cite: null } },
+    body: s,
+    br: s,
+    button: {
+      attrs: {
+        form: null, formaction: null, name: null, value: null,
+        autofocus: ["", "autofocus"],
+        disabled: ["", "autofocus"],
+        formenctype: encs,
+        formmethod: methods,
+        formnovalidate: ["", "novalidate"],
+        formtarget: targets,
+        type: ["submit", "reset", "button"]
+      }
+    },
+    canvas: { attrs: { width: null, height: null } },
+    caption: s,
+    center: s,
+    cite: s,
+    code: s,
+    col: { attrs: { span: null } },
+    colgroup: { attrs: { span: null } },
+    command: {
+      attrs: {
+        type: ["command", "checkbox", "radio"],
+        label: null, icon: null, radiogroup: null, command: null, title: null,
+        disabled: ["", "disabled"],
+        checked: ["", "checked"]
+      }
+    },
+    data: { attrs: { value: null } },
+    datagrid: { attrs: { disabled: ["", "disabled"], multiple: ["", "multiple"] } },
+    datalist: { attrs: { data: null } },
+    dd: s,
+    del: { attrs: { cite: null, datetime: null } },
+    details: { attrs: { open: ["", "open"] } },
+    dfn: s,
+    dir: s,
+    div: s,
+    dl: s,
+    dt: s,
+    em: s,
+    embed: { attrs: { src: null, type: null, width: null, height: null } },
+    eventsource: { attrs: { src: null } },
+    fieldset: { attrs: { disabled: ["", "disabled"], form: null, name: null } },
+    figcaption: s,
+    figure: s,
+    font: s,
+    footer: s,
+    form: {
+      attrs: {
+        action: null, name: null,
+        "accept-charset": charsets,
+        autocomplete: ["on", "off"],
+        enctype: encs,
+        method: methods,
+        novalidate: ["", "novalidate"],
+        target: targets
+      }
+    },
+    frame: s,
+    frameset: s,
+    h1: s, h2: s, h3: s, h4: s, h5: s, h6: s,
+    head: {
+      attrs: {},
+      children: ["title", "base", "link", "style", "meta", "script", "noscript", "command"]
+    },
+    header: s,
+    hgroup: s,
+    hr: s,
+    html: {
+      attrs: { manifest: null },
+      children: ["head", "body"]
+    },
+    i: s,
+    iframe: {
+      attrs: {
+        src: null, srcdoc: null, name: null, width: null, height: null,
+        sandbox: ["allow-top-navigation", "allow-same-origin", "allow-forms", "allow-scripts"],
+        seamless: ["", "seamless"]
+      }
+    },
+    img: {
+      attrs: {
+        alt: null, src: null, ismap: null, usemap: null, width: null, height: null,
+        crossorigin: ["anonymous", "use-credentials"]
+      }
+    },
+    input: {
+      attrs: {
+        alt: null, dirname: null, form: null, formaction: null,
+        height: null, list: null, max: null, maxlength: null, min: null,
+        name: null, pattern: null, placeholder: null, size: null, src: null,
+        step: null, value: null, width: null,
+        accept: ["audio/*", "video/*", "image/*"],
+        autocomplete: ["on", "off"],
+        autofocus: ["", "autofocus"],
+        checked: ["", "checked"],
+        disabled: ["", "disabled"],
+        formenctype: encs,
+        formmethod: methods,
+        formnovalidate: ["", "novalidate"],
+        formtarget: targets,
+        multiple: ["", "multiple"],
+        readonly: ["", "readonly"],
+        required: ["", "required"],
+        type: ["hidden", "text", "search", "tel", "url", "email", "password", "datetime", "date", "month",
+               "week", "time", "datetime-local", "number", "range", "color", "checkbox", "radio",
+               "file", "submit", "image", "reset", "button"]
+      }
+    },
+    ins: { attrs: { cite: null, datetime: null } },
+    kbd: s,
+    keygen: {
+      attrs: {
+        challenge: null, form: null, name: null,
+        autofocus: ["", "autofocus"],
+        disabled: ["", "disabled"],
+        keytype: ["RSA"]
+      }
+    },
+    label: { attrs: { "for": null, form: null } },
+    legend: s,
+    li: { attrs: { value: null } },
+    link: {
+      attrs: {
+        href: null, type: null,
+        hreflang: langs,
+        media: media,
+        sizes: ["all", "16x16", "16x16 32x32", "16x16 32x32 64x64"]
+      }
+    },
+    map: { attrs: { name: null } },
+    mark: s,
+    menu: { attrs: { label: null, type: ["list", "context", "toolbar"] } },
+    meta: {
+      attrs: {
+        content: null,
+        charset: charsets,
+        name: ["viewport", "application-name", "author", "description", "generator", "keywords"],
+        "http-equiv": ["content-language", "content-type", "default-style", "refresh"]
+      }
+    },
+    meter: { attrs: { value: null, min: null, low: null, high: null, max: null, optimum: null } },
+    nav: s,
+    noframes: s,
+    noscript: s,
+    object: {
+      attrs: {
+        data: null, type: null, name: null, usemap: null, form: null, width: null, height: null,
+        typemustmatch: ["", "typemustmatch"]
+      }
+    },
+    ol: { attrs: { reversed: ["", "reversed"], start: null, type: ["1", "a", "A", "i", "I"] } },
+    optgroup: { attrs: { disabled: ["", "disabled"], label: null } },
+    option: { attrs: { disabled: ["", "disabled"], label: null, selected: ["", "selected"], value: null } },
+    output: { attrs: { "for": null, form: null, name: null } },
+    p: s,
+    param: { attrs: { name: null, value: null } },
+    pre: s,
+    progress: { attrs: { value: null, max: null } },
+    q: { attrs: { cite: null } },
+    rp: s,
+    rt: s,
+    ruby: s,
+    s: s,
+    samp: s,
+    script: {
+      attrs: {
+        type: ["text/javascript"],
+        src: null,
+        async: ["", "async"],
+        defer: ["", "defer"],
+        charset: charsets
+      }
+    },
+    section: s,
+    select: {
+      attrs: {
+        form: null, name: null, size: null,
+        autofocus: ["", "autofocus"],
+        disabled: ["", "disabled"],
+        multiple: ["", "multiple"]
+      }
+    },
+    small: s,
+    source: { attrs: { src: null, type: null, media: null } },
+    span: s,
+    strike: s,
+    strong: s,
+    style: {
+      attrs: {
+        type: ["text/css"],
+        media: media,
+        scoped: null
+      }
+    },
+    sub: s,
+    summary: s,
+    sup: s,
+    table: s,
+    tbody: s,
+    td: { attrs: { colspan: null, rowspan: null, headers: null } },
+    textarea: {
+      attrs: {
+        dirname: null, form: null, maxlength: null, name: null, placeholder: null,
+        rows: null, cols: null,
+        autofocus: ["", "autofocus"],
+        disabled: ["", "disabled"],
+        readonly: ["", "readonly"],
+        required: ["", "required"],
+        wrap: ["soft", "hard"]
+      }
+    },
+    tfoot: s,
+    th: { attrs: { colspan: null, rowspan: null, headers: null, scope: ["row", "col", "rowgroup", "colgroup"] } },
+    thead: s,
+    time: { attrs: { datetime: null } },
+    title: s,
+    tr: s,
+    track: {
+      attrs: {
+        src: null, label: null, "default": null,
+        kind: ["subtitles", "captions", "descriptions", "chapters", "metadata"],
+        srclang: langs
+      }
+    },
+    tt: s,
+    u: s,
+    ul: s,
+    "var": s,
+    video: {
+      attrs: {
+        src: null, poster: null, width: null, height: null,
+        crossorigin: ["anonymous", "use-credentials"],
+        preload: ["auto", "metadata", "none"],
+        autoplay: ["", "autoplay"],
+        mediagroup: ["movie"],
+        muted: ["", "muted"],
+        controls: ["", "controls"]
+      }
+    },
+    wbr: s
+  };
+
+  var globalAttrs = {
+    accesskey: ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
+    "class": null,
+    contenteditable: ["true", "false"],
+    contextmenu: null,
+    dir: ["ltr", "rtl", "auto"],
+    draggable: ["true", "false", "auto"],
+    dropzone: ["copy", "move", "link", "string:", "file:"],
+    hidden: ["hidden"],
+    id: null,
+    inert: ["inert"],
+    itemid: null,
+    itemprop: null,
+    itemref: null,
+    itemscope: ["itemscope"],
+    itemtype: null,
+    lang: ["en", "es"],
+    spellcheck: ["true", "false"],
+    style: null,
+    tabindex: ["1", "2", "3", "4", "5", "6", "7", "8", "9"],
+    title: null,
+    translate: ["yes", "no"],
+    onclick: null,
+    rel: ["stylesheet", "alternate", "author", "bookmark", "help", "license", "next", "nofollow", "noreferrer", "prefetch", "prev", "search", "tag"]
+  };
+  function populate(obj) {
+    for (var attr in globalAttrs) if (globalAttrs.hasOwnProperty(attr))
+      obj.attrs[attr] = globalAttrs[attr];
+  }
+
+  populate(s);
+  for (var tag in data) if (data.hasOwnProperty(tag) && data[tag] != s)
+    populate(data[tag]);
+
+  CodeMirror.htmlSchema = data;
+  function htmlHint(cm, options) {
+    var local = {schemaInfo: data};
+    if (options) for (var opt in options) local[opt] = options[opt];
+    return CodeMirror.hint.xml(cm, local);
+  }
+  CodeMirror.htmlHint = htmlHint; // deprecated
+  CodeMirror.registerHelper("hint", "html", htmlHint);
+})();
diff --git a/third-party/codemirror-3.15/addon/hint/javascript-hint.js b/third-party/codemirror-3.15/addon/hint/javascript-hint.js
new file mode 100644 (file)
index 0000000..042fe13
--- /dev/null
@@ -0,0 +1,146 @@
+(function () {
+  var Pos = CodeMirror.Pos;
+
+  function forEach(arr, f) {
+    for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]);
+  }
+
+  function arrayContains(arr, item) {
+    if (!Array.prototype.indexOf) {
+      var i = arr.length;
+      while (i--) {
+        if (arr[i] === item) {
+          return true;
+        }
+      }
+      return false;
+    }
+    return arr.indexOf(item) != -1;
+  }
+
+  function scriptHint(editor, keywords, getToken, options) {
+    // Find the token at the cursor
+    var cur = editor.getCursor(), token = getToken(editor, cur), tprop = token;
+    token.state = CodeMirror.innerMode(editor.getMode(), token.state).state;
+
+    // If it's not a 'word-style' token, ignore the token.
+    if (!/^[\w$_]*$/.test(token.string)) {
+      token = tprop = {start: cur.ch, end: cur.ch, string: "", state: token.state,
+                       type: token.string == "." ? "property" : null};
+    }
+    // If it is a property, find out what it is a property of.
+    while (tprop.type == "property") {
+      tprop = getToken(editor, Pos(cur.line, tprop.start));
+      if (tprop.string != ".") return;
+      tprop = getToken(editor, Pos(cur.line, tprop.start));
+      if (tprop.string == ')') {
+        var level = 1;
+        do {
+          tprop = getToken(editor, Pos(cur.line, tprop.start));
+          switch (tprop.string) {
+          case ')': level++; break;
+          case '(': level--; break;
+          default: break;
+          }
+        } while (level > 0);
+        tprop = getToken(editor, Pos(cur.line, tprop.start));
+        if (tprop.type.indexOf("variable") === 0)
+          tprop.type = "function";
+        else return; // no clue
+      }
+      if (!context) var context = [];
+      context.push(tprop);
+    }
+    return {list: getCompletions(token, context, keywords, options),
+            from: Pos(cur.line, token.start),
+            to: Pos(cur.line, token.end)};
+  }
+
+  function javascriptHint(editor, options) {
+    return scriptHint(editor, javascriptKeywords,
+                      function (e, cur) {return e.getTokenAt(cur);},
+                      options);
+  };
+  CodeMirror.javascriptHint = javascriptHint; // deprecated
+  CodeMirror.registerHelper("hint", "javascript", javascriptHint);
+
+  function getCoffeeScriptToken(editor, cur) {
+  // This getToken, it is for coffeescript, imitates the behavior of
+  // getTokenAt method in javascript.js, that is, returning "property"
+  // type and treat "." as indepenent token.
+    var token = editor.getTokenAt(cur);
+    if (cur.ch == token.start + 1 && token.string.charAt(0) == '.') {
+      token.end = token.start;
+      token.string = '.';
+      token.type = "property";
+    }
+    else if (/^\.[\w$_]*$/.test(token.string)) {
+      token.type = "property";
+      token.start++;
+      token.string = token.string.replace(/\./, '');
+    }
+    return token;
+  }
+
+  function coffeescriptHint(editor, options) {
+    return scriptHint(editor, coffeescriptKeywords, getCoffeeScriptToken, options);
+  }
+  CodeMirror.coffeescriptHint = coffeescriptHint; // deprecated
+  CodeMirror.registerHelper("hint", "coffeescript", coffeescriptHint);
+
+  var stringProps = ("charAt charCodeAt indexOf lastIndexOf substring substr slice trim trimLeft trimRight " +
+                     "toUpperCase toLowerCase split concat match replace search").split(" ");
+  var arrayProps = ("length concat join splice push pop shift unshift slice reverse sort indexOf " +
+                    "lastIndexOf every some filter forEach map reduce reduceRight ").split(" ");
+  var funcProps = "prototype apply call bind".split(" ");
+  var javascriptKeywords = ("break case catch continue debugger default delete do else false finally for function " +
+                  "if in instanceof new null return switch throw true try typeof var void while with").split(" ");
+  var coffeescriptKeywords = ("and break catch class continue delete do else extends false finally for " +
+                  "if in instanceof isnt new no not null of off on or return switch then throw true try typeof until void while with yes").split(" ");
+
+  function getCompletions(token, context, keywords, options) {
+    var found = [], start = token.string;
+    function maybeAdd(str) {
+      if (str.indexOf(start) == 0 && !arrayContains(found, str)) found.push(str);
+    }
+    function gatherCompletions(obj) {
+      if (typeof obj == "string") forEach(stringProps, maybeAdd);
+      else if (obj instanceof Array) forEach(arrayProps, maybeAdd);
+      else if (obj instanceof Function) forEach(funcProps, maybeAdd);
+      for (var name in obj) maybeAdd(name);
+    }
+
+    if (context) {
+      // If this is a property, see if it belongs to some object we can
+      // find in the current environment.
+      var obj = context.pop(), base;
+      if (obj.type.indexOf("variable") === 0) {
+        if (options && options.additionalContext)
+          base = options.additionalContext[obj.string];
+        base = base || window[obj.string];
+      } else if (obj.type == "string") {
+        base = "";
+      } else if (obj.type == "atom") {
+        base = 1;
+      } else if (obj.type == "function") {
+        if (window.jQuery != null && (obj.string == '$' || obj.string == 'jQuery') &&
+            (typeof window.jQuery == 'function'))
+          base = window.jQuery();
+        else if (window._ != null && (obj.string == '_') && (typeof window._ == 'function'))
+          base = window._();
+      }
+      while (base != null && context.length)
+        base = base[context.pop().string];
+      if (base != null) gatherCompletions(base);
+    }
+    else {
+      // If not, just look in the window object and any local scope
+      // (reading into JS mode internals to get at the local and global variables)
+      for (var v = token.state.localVars; v; v = v.next) maybeAdd(v.name);
+      for (var v = token.state.globalVars; v; v = v.next) maybeAdd(v.name);
+      gatherCompletions(window);
+      forEach(keywords, maybeAdd);
+    }
+    return found;
+  }
+})();
diff --git a/third-party/codemirror-3.15/addon/hint/pig-hint.js b/third-party/codemirror-3.15/addon/hint/pig-hint.js
new file mode 100644 (file)
index 0000000..155973f
--- /dev/null
@@ -0,0 +1,119 @@
+(function () {
+  function forEach(arr, f) {
+    for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]);
+  }
+
+  function arrayContains(arr, item) {
+    if (!Array.prototype.indexOf) {
+      var i = arr.length;
+      while (i--) {
+        if (arr[i] === item) {
+          return true;
+        }
+      }
+      return false;
+    }
+    return arr.indexOf(item) != -1;
+  }
+
+  function scriptHint(editor, _keywords, getToken) {
+    // Find the token at the cursor
+    var cur = editor.getCursor(), token = getToken(editor, cur), tprop = token;
+    // If it's not a 'word-style' token, ignore the token.
+
+    if (!/^[\w$_]*$/.test(token.string)) {
+        token = tprop = {start: cur.ch, end: cur.ch, string: "", state: token.state,
+                         className: token.string == ":" ? "pig-type" : null};
+    }
+
+    if (!context) var context = [];
+    context.push(tprop);
+
+    var completionList = getCompletions(token, context);
+    completionList = completionList.sort();
+    //prevent autocomplete for last word, instead show dropdown with one word
+    if(completionList.length == 1) {
+      completionList.push(" ");
+    }
+
+    return {list: completionList,
+            from: CodeMirror.Pos(cur.line, token.start),
+            to: CodeMirror.Pos(cur.line, token.end)};
+  }
+
+  function pigHint(editor) {
+    return scriptHint(editor, pigKeywordsU, function (e, cur) {return e.getTokenAt(cur);});
+  }
+  CodeMirror.pigHint = pigHint; // deprecated
+  CodeMirror.registerHelper("hint", "pig", hinter);
+
+  var pigKeywords = "VOID IMPORT RETURNS DEFINE LOAD FILTER FOREACH ORDER CUBE DISTINCT COGROUP "
+  + "JOIN CROSS UNION SPLIT INTO IF OTHERWISE ALL AS BY USING INNER OUTER ONSCHEMA PARALLEL "
+  + "PARTITION GROUP AND OR NOT GENERATE FLATTEN ASC DESC IS STREAM THROUGH STORE MAPREDUCE "
+  + "SHIP CACHE INPUT OUTPUT STDERROR STDIN STDOUT LIMIT SAMPLE LEFT RIGHT FULL EQ GT LT GTE LTE "
+  + "NEQ MATCHES TRUE FALSE";
+  var pigKeywordsU = pigKeywords.split(" ");
+  var pigKeywordsL = pigKeywords.toLowerCase().split(" ");
+
+  var pigTypes = "BOOLEAN INT LONG FLOAT DOUBLE CHARARRAY BYTEARRAY BAG TUPLE MAP";
+  var pigTypesU = pigTypes.split(" ");
+  var pigTypesL = pigTypes.toLowerCase().split(" ");
+
+  var pigBuiltins = "ABS ACOS ARITY ASIN ATAN AVG BAGSIZE BINSTORAGE BLOOM BUILDBLOOM CBRT CEIL "
+  + "CONCAT COR COS COSH COUNT COUNT_STAR COV CONSTANTSIZE CUBEDIMENSIONS DIFF DISTINCT DOUBLEABS "
+  + "DOUBLEAVG DOUBLEBASE DOUBLEMAX DOUBLEMIN DOUBLEROUND DOUBLESUM EXP FLOOR FLOATABS FLOATAVG "
+  + "FLOATMAX FLOATMIN FLOATROUND FLOATSUM GENERICINVOKER INDEXOF INTABS INTAVG INTMAX INTMIN "
+  + "INTSUM INVOKEFORDOUBLE INVOKEFORFLOAT INVOKEFORINT INVOKEFORLONG INVOKEFORSTRING INVOKER "
+  + "ISEMPTY JSONLOADER JSONMETADATA JSONSTORAGE LAST_INDEX_OF LCFIRST LOG LOG10 LOWER LONGABS "
+  + "LONGAVG LONGMAX LONGMIN LONGSUM MAX MIN MAPSIZE MONITOREDUDF NONDETERMINISTIC OUTPUTSCHEMA  "
+  + "PIGSTORAGE PIGSTREAMING RANDOM REGEX_EXTRACT REGEX_EXTRACT_ALL REPLACE ROUND SIN SINH SIZE "
+  + "SQRT STRSPLIT SUBSTRING SUM STRINGCONCAT STRINGMAX STRINGMIN STRINGSIZE TAN TANH TOBAG "
+  + "TOKENIZE TOMAP TOP TOTUPLE TRIM TEXTLOADER TUPLESIZE UCFIRST UPPER UTF8STORAGECONVERTER";
+  var pigBuiltinsU = pigBuiltins.split(" ").join("() ").split(" ");
+  var pigBuiltinsL = pigBuiltins.toLowerCase().split(" ").join("() ").split(" ");
+  var pigBuiltinsC = ("BagSize BinStorage Bloom BuildBloom ConstantSize CubeDimensions DoubleAbs "
+  + "DoubleAvg DoubleBase DoubleMax DoubleMin DoubleRound DoubleSum FloatAbs FloatAvg FloatMax "
+  + "FloatMin FloatRound FloatSum GenericInvoker IntAbs IntAvg IntMax IntMin IntSum "
+  + "InvokeForDouble InvokeForFloat InvokeForInt InvokeForLong InvokeForString Invoker "
+  + "IsEmpty JsonLoader JsonMetadata JsonStorage LongAbs LongAvg LongMax LongMin LongSum MapSize "
+  + "MonitoredUDF Nondeterministic OutputSchema PigStorage PigStreaming StringConcat StringMax "
+  + "StringMin StringSize TextLoader TupleSize Utf8StorageConverter").split(" ").join("() ").split(" ");
+
+  function getCompletions(token, context) {
+    var found = [], start = token.string;
+    function maybeAdd(str) {
+      if (str.indexOf(start) == 0 && !arrayContains(found, str)) found.push(str);
+    }
+
+    function gatherCompletions(obj) {
+      if(obj == ":") {
+        forEach(pigTypesL, maybeAdd);
+      }
+      else {
+        forEach(pigBuiltinsU, maybeAdd);
+        forEach(pigBuiltinsL, maybeAdd);
+        forEach(pigBuiltinsC, maybeAdd);
+        forEach(pigTypesU, maybeAdd);
+        forEach(pigTypesL, maybeAdd);
+        forEach(pigKeywordsU, maybeAdd);
+        forEach(pigKeywordsL, maybeAdd);
+      }
+    }
+
+    if (context) {
+      // If this is a property, see if it belongs to some object we can
+      // find in the current environment.
+      var obj = context.pop(), base;
+
+      if (obj.type == "variable")
+          base = obj.string;
+      else if(obj.type == "variable-3")
+          base = ":" + obj.string;
+
+      while (base != null && context.length)
+        base = base[context.pop().string];
+      if (base != null) gatherCompletions(base);
+    }
+    return found;
+  }
+})();
diff --git a/third-party/codemirror-3.15/addon/hint/python-hint.js b/third-party/codemirror-3.15/addon/hint/python-hint.js
new file mode 100644 (file)
index 0000000..98d2a58
--- /dev/null
@@ -0,0 +1,95 @@
+(function () {
+  function forEach(arr, f) {
+    for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]);
+  }
+
+  function arrayContains(arr, item) {
+    if (!Array.prototype.indexOf) {
+      var i = arr.length;
+      while (i--) {
+        if (arr[i] === item) {
+          return true;
+        }
+      }
+      return false;
+    }
+    return arr.indexOf(item) != -1;
+  }
+
+  function scriptHint(editor, _keywords, getToken) {
+    // Find the token at the cursor
+    var cur = editor.getCursor(), token = getToken(editor, cur), tprop = token;
+    // If it's not a 'word-style' token, ignore the token.
+
+    if (!/^[\w$_]*$/.test(token.string)) {
+        token = tprop = {start: cur.ch, end: cur.ch, string: "", state: token.state,
+                         className: token.string == ":" ? "python-type" : null};
+    }
+
+    if (!context) var context = [];
+    context.push(tprop);
+
+    var completionList = getCompletions(token, context);
+    completionList = completionList.sort();
+    //prevent autocomplete for last word, instead show dropdown with one word
+    if(completionList.length == 1) {
+      completionList.push(" ");
+    }
+
+    return {list: completionList,
+            from: CodeMirror.Pos(cur.line, token.start),
+            to: CodeMirror.Pos(cur.line, token.end)};
+  }
+
+  function pythonHint(editor) {
+    return scriptHint(editor, pythonKeywordsU, function (e, cur) {return e.getTokenAt(cur);});
+  }
+  CodeMirror.pythonHint = pythonHint; // deprecated
+  CodeMirror.registerHelper("hint", "python", pythonHint);
+
+  var pythonKeywords = "and del from not while as elif global or with assert else if pass yield"
++ "break except import print class exec in raise continue finally is return def for lambda try";
+  var pythonKeywordsL = pythonKeywords.split(" ");
+  var pythonKeywordsU = pythonKeywords.toUpperCase().split(" ");
+
+  var pythonBuiltins = "abs divmod input open staticmethod all enumerate int ord str "
++ "any eval isinstance pow sum basestring execfile issubclass print super"
++ "bin file iter property tuple bool filter len range type"
++ "bytearray float list raw_input unichr callable format locals reduce unicode"
++ "chr frozenset long reload vars classmethod getattr map repr xrange"
++ "cmp globals max reversed zip compile hasattr memoryview round __import__"
++ "complex hash min set apply delattr help next setattr buffer"
++ "dict hex object slice coerce dir id oct sorted intern ";
+  var pythonBuiltinsL = pythonBuiltins.split(" ").join("() ").split(" ");
+  var pythonBuiltinsU = pythonBuiltins.toUpperCase().split(" ").join("() ").split(" ");
+
+  function getCompletions(token, context) {
+    var found = [], start = token.string;
+    function maybeAdd(str) {
+      if (str.indexOf(start) == 0 && !arrayContains(found, str)) found.push(str);
+    }
+
+    function gatherCompletions(_obj) {
+        forEach(pythonBuiltinsL, maybeAdd);
+        forEach(pythonBuiltinsU, maybeAdd);
+        forEach(pythonKeywordsL, maybeAdd);
+        forEach(pythonKeywordsU, maybeAdd);
+    }
+
+    if (context) {
+      // If this is a property, see if it belongs to some object we can
+      // find in the current environment.
+      var obj = context.pop(), base;
+
+      if (obj.type == "variable")
+          base = obj.string;
+      else if(obj.type == "variable-3")
+          base = ":" + obj.string;
+
+      while (base != null && context.length)
+        base = base[context.pop().string];
+      if (base != null) gatherCompletions(base);
+    }
+    return found;
+  }
+})();
diff --git a/third-party/codemirror-3.15/addon/hint/show-hint.css b/third-party/codemirror-3.15/addon/hint/show-hint.css
new file mode 100644 (file)
index 0000000..8a4ff05
--- /dev/null
@@ -0,0 +1,38 @@
+.CodeMirror-hints {
+  position: absolute;
+  z-index: 10;
+  overflow: hidden;
+  list-style: none;
+
+  margin: 0;
+  padding: 2px;
+
+  -webkit-box-shadow: 2px 3px 5px rgba(0,0,0,.2);
+  -moz-box-shadow: 2px 3px 5px rgba(0,0,0,.2);
+  box-shadow: 2px 3px 5px rgba(0,0,0,.2);
+  border-radius: 3px;
+  border: 1px solid silver;
+
+  background: white;
+  font-size: 90%;
+  font-family: monospace;
+
+  max-height: 20em;
+  overflow-y: auto;
+}
+
+.CodeMirror-hint {
+  margin: 0;
+  padding: 0 4px;
+  border-radius: 2px;
+  max-width: 19em;
+  overflow: hidden;
+  white-space: pre;
+  color: black;
+  cursor: pointer;
+}
+
+.CodeMirror-hint-active {
+  background: #08f;
+  color: white;
+}
diff --git a/third-party/codemirror-3.15/addon/hint/show-hint.js b/third-party/codemirror-3.15/addon/hint/show-hint.js
new file mode 100644 (file)
index 0000000..300f688
--- /dev/null
@@ -0,0 +1,274 @@
+(function() {
+  "use strict";
+
+  CodeMirror.showHint = function(cm, getHints, options) {
+    // We want a single cursor position.
+    if (cm.somethingSelected()) return;
+    if (getHints == null) getHints = cm.getHelper(cm.getCursor(), "hint");
+    if (getHints == null) return;
+
+    if (cm.state.completionActive) cm.state.completionActive.close();
+
+    var completion = cm.state.completionActive = new Completion(cm, getHints, options || {});
+    CodeMirror.signal(cm, "startCompletion", cm);
+    if (completion.options.async)
+      getHints(cm, function(hints) { completion.showHints(hints); }, completion.options);
+    else
+      return completion.showHints(getHints(cm, completion.options));
+  };
+
+  function Completion(cm, getHints, options) {
+    this.cm = cm;
+    this.getHints = getHints;
+    this.options = options;
+    this.widget = this.onClose = null;
+  }
+
+  Completion.prototype = {
+    close: function() {
+      if (!this.active()) return;
+      this.cm.state.completionActive = null;
+
+      if (this.widget) this.widget.close();
+      if (this.onClose) this.onClose();
+      CodeMirror.signal(this.cm, "endCompletion", this.cm);
+    },
+
+    active: function() {
+      return this.cm.state.completionActive == this;
+    },
+
+    pick: function(data, i) {
+      var completion = data.list[i];
+      if (completion.hint) completion.hint(this.cm, data, completion);
+      else this.cm.replaceRange(getText(completion), data.from, data.to);
+      this.close();
+    },
+
+    showHints: function(data) {
+      if (!data || !data.list.length || !this.active()) return this.close();
+
+      if (this.options.completeSingle != false && data.list.length == 1)
+        this.pick(data, 0);
+      else
+        this.showWidget(data);
+    },
+
+    showWidget: function(data) {
+      this.widget = new Widget(this, data);
+      CodeMirror.signal(data, "shown");
+
+      var debounce = null, completion = this, finished;
+      var closeOn = this.options.closeCharacters || /[\s()\[\]{};:>,]/;
+      var startPos = this.cm.getCursor(), startLen = this.cm.getLine(startPos.line).length;
+
+      function done() {
+        if (finished) return;
+        finished = true;
+        completion.close();
+        completion.cm.off("cursorActivity", activity);
+        CodeMirror.signal(data, "close");
+      }
+      function isDone() {
+        if (finished) return true;
+        if (!completion.widget) { done(); return true; }
+      }
+
+      function update() {
+        if (isDone()) return;
+        CodeMirror.signal(data, "update");
+        if (completion.options.async)
+          completion.getHints(completion.cm, finishUpdate, completion.options);
+        else
+          finishUpdate(completion.getHints(completion.cm, completion.options));
+      }
+      function finishUpdate(data_) {
+        data = data_;
+        if (isDone()) return;
+        if (!data || !data.list.length) return done();
+        completion.widget.close();
+        completion.widget = new Widget(completion, data);
+      }
+
+      function activity() {
+        clearTimeout(debounce);
+        var pos = completion.cm.getCursor(), line = completion.cm.getLine(pos.line);
+        if (pos.line != startPos.line || line.length - pos.ch != startLen - startPos.ch ||
+            pos.ch < startPos.ch || completion.cm.somethingSelected() ||
+            (pos.ch && closeOn.test(line.charAt(pos.ch - 1))))
+          completion.close();
+        else
+          debounce = setTimeout(update, 170);
+      }
+      this.cm.on("cursorActivity", activity);
+      this.onClose = done;
+    }
+  };
+
+  function getText(completion) {
+    if (typeof completion == "string") return completion;
+    else return completion.text;
+  }
+
+  function buildKeyMap(options, handle) {
+    var baseMap = {
+      Up: function() {handle.moveFocus(-1);},
+      Down: function() {handle.moveFocus(1);},
+      PageUp: function() {handle.moveFocus(-handle.menuSize());},
+      PageDown: function() {handle.moveFocus(handle.menuSize());},
+      Home: function() {handle.setFocus(0);},
+      End: function() {handle.setFocus(handle.length);},
+      Enter: handle.pick,
+      Tab: handle.pick,
+      Esc: handle.close
+    };
+    var ourMap = options.customKeys ? {} : baseMap;
+    function addBinding(key, val) {
+      var bound;
+      if (typeof val != "string")
+        bound = function(cm) { return val(cm, handle); };
+      // This mechanism is deprecated
+      else if (baseMap.hasOwnProperty(val))
+        bound = baseMap[val];
+      else
+        bound = val;
+      ourMap[key] = bound;
+    }
+    if (options.customKeys)
+      for (var key in options.customKeys) if (options.customKeys.hasOwnProperty(key))
+        addBinding(key, options.customKeys[key]);
+    if (options.extraKeys)
+      for (var key in options.extraKeys) if (options.extraKeys.hasOwnProperty(key))
+        addBinding(key, options.extraKeys[key]);
+    return ourMap;
+  }
+
+  function Widget(completion, data) {
+    this.completion = completion;
+    this.data = data;
+    var widget = this, cm = completion.cm, options = completion.options;
+
+    var hints = this.hints = document.createElement("ul");
+    hints.className = "CodeMirror-hints";
+    this.selectedHint = 0;
+
+    var completions = data.list;
+    for (var i = 0; i < completions.length; ++i) {
+      var elt = hints.appendChild(document.createElement("li")), cur = completions[i];
+      var className = "CodeMirror-hint" + (i ? "" : " CodeMirror-hint-active");
+      if (cur.className != null) className = cur.className + " " + className;
+      elt.className = className;
+      if (cur.render) cur.render(elt, data, cur);
+      else elt.appendChild(document.createTextNode(cur.displayText || getText(cur)));
+      elt.hintId = i;
+    }
+
+    var pos = cm.cursorCoords(options.alignWithWord !== false ? data.from : null);
+    var left = pos.left, top = pos.bottom, below = true;
+    hints.style.left = left + "px";
+    hints.style.top = top + "px";
+    // If we're at the edge of the screen, then we want the menu to appear on the left of the cursor.
+    var winW = window.innerWidth || Math.max(document.body.offsetWidth, document.documentElement.offsetWidth);
+    var winH = window.innerHeight || Math.max(document.body.offsetHeight, document.documentElement.offsetHeight);
+    var box = hints.getBoundingClientRect();
+    var overlapX = box.right - winW, overlapY = box.bottom - winH;
+    if (overlapX > 0) {
+      if (box.right - box.left > winW) {
+        hints.style.width = (winW - 5) + "px";
+        overlapX -= (box.right - box.left) - winW;
+      }
+      hints.style.left = (left = pos.left - overlapX) + "px";
+    }
+    if (overlapY > 0) {
+      var height = box.bottom - box.top;
+      if (box.top - (pos.bottom - pos.top) - height > 0) {
+        overlapY = height + (pos.bottom - pos.top);
+        below = false;
+      } else if (height > winH) {
+        hints.style.height = (winH - 5) + "px";
+        overlapY -= height - winH;
+      }
+      hints.style.top = (top = pos.bottom - overlapY) + "px";
+    }
+    (options.container || document.body).appendChild(hints);
+
+    cm.addKeyMap(this.keyMap = buildKeyMap(options, {
+      moveFocus: function(n) { widget.changeActive(widget.selectedHint + n); },
+      setFocus: function(n) { widget.changeActive(n); },
+      menuSize: function() { return widget.screenAmount(); },
+      length: completions.length,
+      close: function() { completion.close(); },
+      pick: function() { widget.pick(); }
+    }));
+
+    if (options.closeOnUnfocus !== false) {
+      var closingOnBlur;
+      cm.on("blur", this.onBlur = function() { closingOnBlur = setTimeout(function() { completion.close(); }, 100); });
+      cm.on("focus", this.onFocus = function() { clearTimeout(closingOnBlur); });
+    }
+
+    var startScroll = cm.getScrollInfo();
+    cm.on("scroll", this.onScroll = function() {
+      var curScroll = cm.getScrollInfo(), editor = cm.getWrapperElement().getBoundingClientRect();
+      var newTop = top + startScroll.top - curScroll.top;
+      var point = newTop - (window.pageYOffset || (document.documentElement || document.body).scrollTop);
+      if (!below) point += hints.offsetHeight;
+      if (point <= editor.top || point >= editor.bottom) return completion.close();
+      hints.style.top = newTop + "px";
+      hints.style.left = (left + startScroll.left - curScroll.left) + "px";
+    });
+
+    CodeMirror.on(hints, "dblclick", function(e) {
+      var t = e.target || e.srcElement;
+      if (t.hintId != null) {widget.changeActive(t.hintId); widget.pick();}
+    });
+    CodeMirror.on(hints, "click", function(e) {
+      var t = e.target || e.srcElement;
+      if (t.hintId != null) widget.changeActive(t.hintId);
+    });
+    CodeMirror.on(hints, "mousedown", function() {
+      setTimeout(function(){cm.focus();}, 20);
+    });
+
+    CodeMirror.signal(data, "select", completions[0], hints.firstChild);
+    return true;
+  }
+
+  Widget.prototype = {
+    close: function() {
+      if (this.completion.widget != this) return;
+      this.completion.widget = null;
+      this.hints.parentNode.removeChild(this.hints);
+      this.completion.cm.removeKeyMap(this.keyMap);
+
+      var cm = this.completion.cm;
+      if (this.completion.options.closeOnUnfocus !== false) {
+        cm.off("blur", this.onBlur);
+        cm.off("focus", this.onFocus);
+      }
+      cm.off("scroll", this.onScroll);
+    },
+
+    pick: function() {
+      this.completion.pick(this.data, this.selectedHint);
+    },
+
+    changeActive: function(i) {
+      i = Math.max(0, Math.min(i, this.data.list.length - 1));
+      if (this.selectedHint == i) return;
+      var node = this.hints.childNodes[this.selectedHint];
+      node.className = node.className.replace(" CodeMirror-hint-active", "");
+      node = this.hints.childNodes[this.selectedHint = i];
+      node.className += " CodeMirror-hint-active";
+      if (node.offsetTop < this.hints.scrollTop)
+        this.hints.scrollTop = node.offsetTop - 3;
+      else if (node.offsetTop + node.offsetHeight > this.hints.scrollTop + this.hints.clientHeight)
+        this.hints.scrollTop = node.offsetTop + node.offsetHeight - this.hints.clientHeight + 3;
+      CodeMirror.signal(this.data, "select", this.data.list[this.selectedHint], node);
+    },
+
+    screenAmount: function() {
+      return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1;
+    }
+  };
+})();
diff --git a/third-party/codemirror-3.15/addon/hint/xml-hint.js b/third-party/codemirror-3.15/addon/hint/xml-hint.js
new file mode 100644 (file)
index 0000000..b6c1da2
--- /dev/null
@@ -0,0 +1,68 @@
+(function() {
+  "use strict";
+
+  var Pos = CodeMirror.Pos;
+
+  function getHints(cm, options) {
+    var tags = options && options.schemaInfo;
+    var quote = (options && options.quoteChar) || '"';
+    if (!tags) return;
+    var cur = cm.getCursor(), token = cm.getTokenAt(cur);
+    var inner = CodeMirror.innerMode(cm.getMode(), token.state);
+    if (inner.mode.name != "xml") return;
+    var result = [], replaceToken = false, prefix;
+    var isTag = token.string.charAt(0) == "<";
+    if (!inner.state.tagName || isTag) { // Tag completion
+      if (isTag) {
+        prefix = token.string.slice(1);
+        replaceToken = true;
+      }
+      var cx = inner.state.context, curTag = cx && tags[cx.tagName];
+      var childList = cx ? curTag && curTag.children : tags["!top"];
+      if (childList) {
+        for (var i = 0; i < childList.length; ++i) if (!prefix || childList[i].indexOf(prefix) == 0)
+          result.push("<" + childList[i]);
+      } else {
+        for (var name in tags) if (tags.hasOwnProperty(name) && name != "!top" && (!prefix || name.indexOf(prefix) == 0))
+          result.push("<" + name);
+      }
+      if (cx && (!prefix || ("/" + cx.tagName).indexOf(prefix) == 0))
+        result.push("</" + cx.tagName + ">");
+    } else {
+      // Attribute completion
+      var curTag = tags[inner.state.tagName], attrs = curTag && curTag.attrs;
+      if (!attrs) return;
+      if (token.type == "string" || token.string == "=") { // A value
+        var before = cm.getRange(Pos(cur.line, Math.max(0, cur.ch - 60)),
+                                 Pos(cur.line, token.type == "string" ? token.start : token.end));
+        var atName = before.match(/([^\s\u00a0=<>\"\']+)=$/), atValues;
+        if (!atName || !attrs.hasOwnProperty(atName[1]) || !(atValues = attrs[atName[1]])) return;
+        if (token.type == "string") {
+          prefix = token.string;
+          if (/['"]/.test(token.string.charAt(0))) {
+            quote = token.string.charAt(0);
+            prefix = token.string.slice(1);
+          }
+          replaceToken = true;
+        }
+        for (var i = 0; i < atValues.length; ++i) if (!prefix || atValues[i].indexOf(prefix) == 0)
+          result.push(quote + atValues[i] + quote);
+      } else { // An attribute name
+        if (token.type == "attribute") {
+          prefix = token.string;
+          replaceToken = true;
+        }
+        for (var attr in attrs) if (attrs.hasOwnProperty(attr) && (!prefix || attr.indexOf(prefix) == 0))
+          result.push(attr);
+      }
+    }
+    return {
+      list: result,
+      from: replaceToken ? Pos(cur.line, token.start) : cur,
+      to: replaceToken ? Pos(cur.line, token.end) : cur
+    };
+  }
+
+  CodeMirror.xmlHint = getHints; // deprecated
+  CodeMirror.registerHelper("hint", "xml", getHints);
+})();
diff --git a/third-party/codemirror-3.15/addon/lint/coffeescript-lint.js b/third-party/codemirror-3.15/addon/lint/coffeescript-lint.js
new file mode 100644 (file)
index 0000000..75f8db6
--- /dev/null
@@ -0,0 +1,25 @@
+// Depends on coffeelint.js from http://www.coffeelint.org/js/coffeelint.js
+
+CodeMirror.registerHelper("lint", "coffeescript", function(text) {
+  var found = [];
+  var parseError = function(err) {
+    var loc = err.lineNumber;
+    found.push({from: CodeMirror.Pos(loc-1, 0),
+                to: CodeMirror.Pos(loc, 0),
+                severity: err.level,
+                message: err.message});
+  };
+  try {
+    var res = coffeelint.lint(text);
+    for(var i = 0; i < res.length; i++) {
+      parseError(res[i]);
+    }
+  } catch(e) {
+    found.push({from: CodeMirror.Pos(e.location.first_line, 0),
+                to: CodeMirror.Pos(e.location.last_line, e.location.last_column),
+                severity: 'error',
+                message: e.message});
+  }
+  return found;
+});
+CodeMirror.coffeeValidator = CodeMirror.lint.coffeescript; // deprecated
diff --git a/third-party/codemirror-3.15/addon/lint/javascript-lint.js b/third-party/codemirror-3.15/addon/lint/javascript-lint.js
new file mode 100644 (file)
index 0000000..d7a6f6a
--- /dev/null
@@ -0,0 +1,124 @@
+(function() {
+
+  var bogus = [ "Dangerous comment" ];
+
+  var warnings = [ [ "Expected '{'",
+                     "Statement body should be inside '{ }' braces." ] ];
+
+  var errors = [ "Missing semicolon", "Extra comma", "Missing property name",
+                 "Unmatched ", " and instead saw", " is not defined",
+                 "Unclosed string", "Stopping, unable to continue" ];
+
+  function validator(text, options) {
+    JSHINT(text, options);
+    var errors = JSHINT.data().errors, result = [];
+    if (errors) parseErrors(errors, result);
+    return result;
+  }
+
+  CodeMirror.registerHelper("lint", "javascript", validator);
+  CodeMirror.javascriptValidator = CodeMirror.lint.javascript; // deprecated
+
+  function cleanup(error) {
+    // All problems are warnings by default
+    fixWith(error, warnings, "warning", true);
+    fixWith(error, errors, "error");
+
+    return isBogus(error) ? null : error;
+  }
+
+  function fixWith(error, fixes, severity, force) {
+    var description, fix, find, replace, found;
+
+    description = error.description;
+
+    for ( var i = 0; i < fixes.length; i++) {
+      fix = fixes[i];
+      find = (typeof fix === "string" ? fix : fix[0]);
+      replace = (typeof fix === "string" ? null : fix[1]);
+      found = description.indexOf(find) !== -1;
+
+      if (force || found) {
+        error.severity = severity;
+      }
+      if (found && replace) {
+        error.description = replace;
+      }
+    }
+  }
+
+  function isBogus(error) {
+    var description = error.description;
+    for ( var i = 0; i < bogus.length; i++) {
+      if (description.indexOf(bogus[i]) !== -1) {
+        return true;
+      }
+    }
+    return false;
+  }
+
+  function parseErrors(errors, output) {
+    for ( var i = 0; i < errors.length; i++) {
+      var error = errors[i];
+      if (error) {
+        var linetabpositions, index;
+
+        linetabpositions = [];
+
+        // This next block is to fix a problem in jshint. Jshint
+        // replaces
+        // all tabs with spaces then performs some checks. The error
+        // positions (character/space) are then reported incorrectly,
+        // not taking the replacement step into account. Here we look
+        // at the evidence line and try to adjust the character position
+        // to the correct value.
+        if (error.evidence) {
+          // Tab positions are computed once per line and cached
+          var tabpositions = linetabpositions[error.line];
+          if (!tabpositions) {
+            var evidence = error.evidence;
+            tabpositions = [];
+            // ugggh phantomjs does not like this
+            // forEachChar(evidence, function(item, index) {
+            Array.prototype.forEach.call(evidence, function(item,
+                                                            index) {
+              if (item === '\t') {
+                // First col is 1 (not 0) to match error
+                // positions
+                tabpositions.push(index + 1);
+              }
+            });
+            linetabpositions[error.line] = tabpositions;
+          }
+          if (tabpositions.length > 0) {
+            var pos = error.character;
+            tabpositions.forEach(function(tabposition) {
+              if (pos > tabposition) pos -= 1;
+            });
+            error.character = pos;
+          }
+        }
+
+        var start = error.character - 1, end = start + 1;
+        if (error.evidence) {
+          index = error.evidence.substring(start).search(/.\b/);
+          if (index > -1) {
+            end += index;
+          }
+        }
+
+        // Convert to format expected by validation service
+        error.description = error.reason;// + "(jshint)";
+        error.start = error.character;
+        error.end = end;
+        error = cleanup(error);
+
+        if (error)
+          output.push({message: error.description,
+                       severity: error.severity,
+                       from: CodeMirror.Pos(error.line - 1, start),
+                       to: CodeMirror.Pos(error.line - 1, end)});
+      }
+    }
+  }
+})();
diff --git a/third-party/codemirror-3.15/addon/lint/json-lint.js b/third-party/codemirror-3.15/addon/lint/json-lint.js
new file mode 100644 (file)
index 0000000..1dfc6b8
--- /dev/null
@@ -0,0 +1,15 @@
+// Depends on jsonlint.js from https://github.com/zaach/jsonlint
+
+CodeMirror.registerHelper("lint", "json", function(text) {
+  var found = [];
+  jsonlint.parseError = function(str, hash) {
+    var loc = hash.loc;
+    found.push({from: CodeMirror.Pos(loc.first_line - 1, loc.first_column),
+                to: CodeMirror.Pos(loc.last_line - 1, loc.last_column),
+                message: str});
+  };
+  try { jsonlint.parse(text); }
+  catch(e) {}
+  return found;
+});
+CodeMirror.jsonValidator = CodeMirror.lint.json; // deprecated
diff --git a/third-party/codemirror-3.15/addon/lint/lint.css b/third-party/codemirror-3.15/addon/lint/lint.css
new file mode 100644 (file)
index 0000000..eb15381
--- /dev/null
@@ -0,0 +1,96 @@
+/* The lint marker gutter */
+.CodeMirror-lint-markers {
+  width: 16px;
+}
+
+.CodeMirror-lint-tooltip {
+  background-color: infobackground;
+  border: 1px solid black;
+  border-radius: 4px 4px 4px 4px;
+  color: infotext;
+  font-family: monospace;
+  font-size: 10pt;
+  overflow: hidden;
+  padding: 2px 5px;
+  position: fixed;
+  white-space: pre;
+  z-index: 100;
+  max-width: 600px;
+  opacity: 0;
+  transition: opacity .4s;
+  -moz-transition: opacity .4s;
+  -webkit-transition: opacity .4s;
+  -o-transition: opacity .4s;
+  -ms-transition: opacity .4s;
+}
+
+.CodeMirror-lint-mark-error, .CodeMirror-lint-mark-warning {
+  background-position: left bottom;
+  background-repeat: repeat-x;
+}
+
+.CodeMirror-lint-mark-error {
+  background-image:
+  url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAYAAAC09K7GAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sJDw4cOCW1/KIAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAHElEQVQI12NggIL/DAz/GdA5/xkY/qPKMDAwAADLZwf5rvm+LQAAAABJRU5ErkJggg==")
+  ;
+}
+
+.CodeMirror-lint-mark-warning {
+  background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAYAAAC09K7GAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sJFhQXEbhTg7YAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAMklEQVQI12NkgIIvJ3QXMjAwdDN+OaEbysDA4MPAwNDNwMCwiOHLCd1zX07o6kBVGQEAKBANtobskNMAAAAASUVORK5CYII=");
+}
+
+.CodeMirror-lint-marker-error, .CodeMirror-lint-marker-warning {
+  background-position: center center;
+  background-repeat: no-repeat;
+  cursor: pointer;
+  display: inline-block;
+  height: 16px;
+  width: 16px;
+  vertical-align: middle;
+  position: relative;
+}
+
+.CodeMirror-lint-message-error, .CodeMirror-lint-message-warning {
+  padding-left: 18px;
+  background-position: top left;
+  background-repeat: no-repeat;
+}
+
+.CodeMirror-lint-marker-error, .CodeMirror-lint-message-error {
+  background-image: url("data:image/gif;base64,R0lGODlhEAAQANUAAPVvcvWHiPVucvRuc+ttcfV6f91KVN5LU99PV/FZY/JhaM4oN84pONE4Rd1ATfJLWutVYPRgbdxpcsgWKMgZKs4lNfE/UvE/U+artcpdSc5uXveimslHPuBhW/eJhfV5efaCgO2CgP+/v+PExP///////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAACUALAAAAAAQABAAAAZ+wJJwSCwaScgkySgkjTQZTkYzWhadnE5oE+pwqkSshwQqkzxfa4kkQXxEpA9J9EFI1KQGQQBAigYCBA14ExEWF0gXihETeA0QD3AkD5QQg0NsDnAJmwkOd5gYFSQKpXAFDBhqaxgLBwQBBAapq00YEg0UDRKqTGtKSL7Cw8JBADs=");
+}
+
+.CodeMirror-lint-marker-warning, .CodeMirror-lint-message-warning {
+  background-image: url("data:image/gif;base64,R0lGODlhEAAQANUAAP7bc//egf/ij/7ijv/jl/7kl//mnv7lnv/uwf7CTP7DTf7DT/7IW//Na/7Na//NbP7QdP/dmbltAIJNAF03AMSAJMSCLKqASa2DS6uBSquCSrGHTq6ETbCHT7WKUrKIUcCVXL+UXMOYX8GWXsSZYMiib6+ETbOIUcOXX86uhd3Muf///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAACsALAAAAAAQABAAAAZowJVwSCwaj0ihikRSJYcoBEL0XKlGkcjImQQhJBREKFnyICoThKeE/AAW6AXgdPyUAgrLJBEo0YsbAQyDhAEdRRwDDw8OaA4NDQImRBgFEJdglxAEGEQZKQcHBqOkKRpFF6mqq1WtrUEAOw==");
+}
+
+.CodeMirror-lint-marker-multiple {
+  background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAYAAADEUlfTAAAAAXNSR0IArs4c6QAAAAZiS0dEAAAAAAAA+UO7fwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sJEAQvB2JVdrAAAAAdaVRYdENvbW1lbnQAAAAAAENyZWF0ZWQgd2l0aCBHSU1QZC5lBwAAAD1JREFUCNdtjkESADAEAzemf69f66HMqGlOIhYiFRFRtSQBWAY7mzx+EDTL6sSgb1jTk7Q87rxyqe37fXsAa78gLyZnRgEAAAAASUVORK5CYII=");
+  background-repeat: no-repeat;
+  background-position: right bottom;
+  width: 100%; height: 100%;
+}
+
+/* Styles for the overview ruler  
+.annotationOverview {
+  cursor: pointer;
+  border-radius: 2px;
+  left: 2px;
+  width: 8px;
+}
+.annotationOverview.error {
+  background-color: lightcoral;
+  border: 1px solid darkred;
+}
+.annotationOverview.warning {
+  background-color: Gold;
+  border: 1px solid black;
+}
+
+.annotationHTML.overlay {
+  background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAYAAADEUlfTAAAAAXNSR0IArs4c6QAAAAZiS0dEAAAAAAAA+UO7fwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sJEAQvB2JVdrAAAAAdaVRYdENvbW1lbnQAAAAAAENyZWF0ZWQgd2l0aCBHSU1QZC5lBwAAAD1JREFUCNdtjkESADAEAzemf69f66HMqGlOIhYiFRFRtSQBWAY7mzx+EDTL6sSgb1jTk7Q87rxyqe37fXsAa78gLyZnRgEAAAAASUVORK5CYII=");
+  background-position: right bottom;
+  position: relative;
+  top: -16px;
+}
+*/
\ No newline at end of file
diff --git a/third-party/codemirror-3.15/addon/lint/lint.js b/third-party/codemirror-3.15/addon/lint/lint.js
new file mode 100644 (file)
index 0000000..67a9297
--- /dev/null
@@ -0,0 +1,203 @@
+(function() {
+  "use strict";
+  var GUTTER_ID = "CodeMirror-lint-markers";
+  var SEVERITIES = /^(?:error|warning)$/;
+
+  function showTooltip(e, content) {
+    var tt = document.createElement("div");
+    tt.className = "CodeMirror-lint-tooltip";
+    tt.appendChild(content.cloneNode(true));
+    document.body.appendChild(tt);
+
+    function position(e) {
+      if (!tt.parentNode) return CodeMirror.off(document, "mousemove", position);
+      tt.style.top = Math.max(0, e.clientY - tt.offsetHeight - 5) + "px";
+      tt.style.left = (e.clientX + 5) + "px";
+    }
+    CodeMirror.on(document, "mousemove", position);
+    position(e);
+    if (tt.style.opacity != null) tt.style.opacity = 1;
+    return tt;
+  }
+  function rm(elt) {
+    if (elt.parentNode) elt.parentNode.removeChild(elt);
+  }
+  function hideTooltip(tt) {
+    if (!tt.parentNode) return;
+    if (tt.style.opacity == null) rm(tt);
+    tt.style.opacity = 0;
+    setTimeout(function() { rm(tt); }, 600);
+  }
+
+  function showTooltipFor(e, content, node) {
+    var tooltip = showTooltip(e, content);
+    function hide() {
+      CodeMirror.off(node, "mouseout", hide);
+      if (tooltip) { hideTooltip(tooltip); tooltip = null; }
+    }
+    var poll = setInterval(function() {
+      if (tooltip) for (var n = node;; n = n.parentNode) {
+        if (n == document.body) return;
+        if (!n) { hide(); break; }
+      }
+      if (!tooltip) return clearInterval(poll);
+    }, 400);
+    CodeMirror.on(node, "mouseout", hide);
+  }
+
+  function LintState(cm, options, hasGutter) {
+    this.marked = [];
+    this.options = options;
+    this.timeout = null;
+    this.hasGutter = hasGutter;
+    this.onMouseOver = function(e) { onMouseOver(cm, e); };
+  }
+
+  function parseOptions(cm, options) {
+    if (options instanceof Function) return {getAnnotations: options};
+    if (!options || options === true) options = {};
+    if (!options.getAnnotations) options.getAnnotations = cm.getHelper(CodeMirror.Pos(0, 0), "lint");
+    if (!options.getAnnotations) throw new Error("Required option 'getAnnotations' missing (lint addon)");
+    return options;
+  }
+
+  function clearMarks(cm) {
+    var state = cm.state.lint;
+    if (state.hasGutter) cm.clearGutter(GUTTER_ID);
+    for (var i = 0; i < state.marked.length; ++i)
+      state.marked[i].clear();
+    state.marked.length = 0;
+  }
+
+  function makeMarker(labels, severity, multiple, tooltips) {
+    var marker = document.createElement("div"), inner = marker;
+    marker.className = "CodeMirror-lint-marker-" + severity;
+    if (multiple) {
+      inner = marker.appendChild(document.createElement("div"));
+      inner.className = "CodeMirror-lint-marker-multiple";
+    }
+
+    if (tooltips != false) CodeMirror.on(inner, "mouseover", function(e) {
+      showTooltipFor(e, labels, inner);
+    });
+
+    return marker;
+  }
+
+  function getMaxSeverity(a, b) {
+    if (a == "error") return a;
+    else return b;
+  }
+
+  function groupByLine(annotations) {
+    var lines = [];
+    for (var i = 0; i < annotations.length; ++i) {
+      var ann = annotations[i], line = ann.from.line;
+      (lines[line] || (lines[line] = [])).push(ann);
+    }
+    return lines;
+  }
+
+  function annotationTooltip(ann) {
+    var severity = ann.severity;
+    if (!SEVERITIES.test(severity)) severity = "error";
+    var tip = document.createElement("div");
+    tip.className = "CodeMirror-lint-message-" + severity;
+    tip.appendChild(document.createTextNode(ann.message));
+    return tip;
+  }
+
+  function startLinting(cm) {
+    var state = cm.state.lint, options = state.options;
+    if (options.async)
+      options.getAnnotations(cm, updateLinting, options);
+    else
+      updateLinting(cm, options.getAnnotations(cm.getValue()));
+  }
+
+  function updateLinting(cm, annotationsNotSorted) {
+    clearMarks(cm);
+    var state = cm.state.lint, options = state.options;
+
+    var annotations = groupByLine(annotationsNotSorted);
+
+    for (var line = 0; line < annotations.length; ++line) {
+      var anns = annotations[line];
+      if (!anns) continue;
+
+      var maxSeverity = null;
+      var tipLabel = state.hasGutter && document.createDocumentFragment();
+
+      for (var i = 0; i < anns.length; ++i) {
+        var ann = anns[i];
+        var severity = ann.severity;
+        if (!SEVERITIES.test(severity)) severity = "error";
+        maxSeverity = getMaxSeverity(maxSeverity, severity);
+
+        if (options.formatAnnotation) ann = options.formatAnnotation(ann);
+        if (state.hasGutter) tipLabel.appendChild(annotationTooltip(ann));
+
+        if (ann.to) state.marked.push(cm.markText(ann.from, ann.to, {
+          className: "CodeMirror-lint-mark-" + severity,
+          __annotation: ann
+        }));
+      }
+
+      if (state.hasGutter)
+        cm.setGutterMarker(line, GUTTER_ID, makeMarker(tipLabel, maxSeverity, anns.length > 1,
+                                                       state.options.tooltips));
+    }
+    if (options.onUpdateLinting) options.onUpdateLinting(annotationsNotSorted, annotations, cm);
+  }
+
+  function onChange(cm) {
+    var state = cm.state.lint;
+    clearTimeout(state.timeout);
+    state.timeout = setTimeout(function(){startLinting(cm);}, state.options.delay || 500);
+  }
+
+  function popupSpanTooltip(ann, e) {
+    var target = e.target || e.srcElement;
+    showTooltipFor(e, annotationTooltip(ann), target);
+  }
+
+  // When the mouseover fires, the cursor might not actually be over
+  // the character itself yet. These pairs of x,y offsets are used to
+  // probe a few nearby points when no suitable marked range is found.
+  var nearby = [0, 0, 0, 5, 0, -5, 5, 0, -5, 0];
+
+  function onMouseOver(cm, e) {
+    if (!/\bCodeMirror-lint-mark-/.test((e.target || e.srcElement).className)) return;
+    for (var i = 0; i < nearby.length; i += 2) {
+      var spans = cm.findMarksAt(cm.coordsChar({left: e.clientX + nearby[i],
+                                                top: e.clientY + nearby[i + 1]}));
+      for (var j = 0; j < spans.length; ++j) {
+        var span = spans[j], ann = span.__annotation;
+        if (ann) return popupSpanTooltip(ann, e);
+      }
+    }
+  }
+
+  function optionHandler(cm, val, old) {
+    if (old && old != CodeMirror.Init) {
+      clearMarks(cm);
+      cm.off("change", onChange);
+      CodeMirror.off(cm.getWrapperElement(), "mouseover", cm.state.lint.onMouseOver);
+      delete cm.state.lint;
+    }
+
+    if (val) {
+      var gutters = cm.getOption("gutters"), hasLintGutter = false;
+      for (var i = 0; i < gutters.length; ++i) if (gutters[i] == GUTTER_ID) hasLintGutter = true;
+      var state = cm.state.lint = new LintState(cm, parseOptions(cm, val), hasLintGutter);
+      cm.on("change", onChange);
+      if (state.options.tooltips != false)
+        CodeMirror.on(cm.getWrapperElement(), "mouseover", state.onMouseOver);
+
+      startLinting(cm);
+    }
+  }
+
+  CodeMirror.defineOption("lintWith", false, optionHandler); // deprecated
+  CodeMirror.defineOption("lint", false, optionHandler); // deprecated
+})();
diff --git a/third-party/codemirror-3.15/addon/merge/dep/diff_match_patch.js b/third-party/codemirror-3.15/addon/merge/dep/diff_match_patch.js
new file mode 100644 (file)
index 0000000..ac34105
--- /dev/null
@@ -0,0 +1,50 @@
+// From https://code.google.com/p/google-diff-match-patch/ , licensed under the Apache License 2.0
+(function(){function diff_match_patch(){this.Diff_Timeout=1;this.Diff_EditCost=4;this.Match_Threshold=0.5;this.Match_Distance=1E3;this.Patch_DeleteThreshold=0.5;this.Patch_Margin=4;this.Match_MaxBits=32}
+diff_match_patch.prototype.diff_main=function(a,b,c,d){"undefined"==typeof d&&(d=0>=this.Diff_Timeout?Number.MAX_VALUE:(new Date).getTime()+1E3*this.Diff_Timeout);if(null==a||null==b)throw Error("Null input. (diff_main)");if(a==b)return a?[[0,a]]:[];"undefined"==typeof c&&(c=!0);var e=c,f=this.diff_commonPrefix(a,b);c=a.substring(0,f);a=a.substring(f);b=b.substring(f);var f=this.diff_commonSuffix(a,b),g=a.substring(a.length-f);a=a.substring(0,a.length-f);b=b.substring(0,b.length-f);a=this.diff_compute_(a,
+b,e,d);c&&a.unshift([0,c]);g&&a.push([0,g]);this.diff_cleanupMerge(a);return a};
+diff_match_patch.prototype.diff_compute_=function(a,b,c,d){if(!a)return[[1,b]];if(!b)return[[-1,a]];var e=a.length>b.length?a:b,f=a.length>b.length?b:a,g=e.indexOf(f);return-1!=g?(c=[[1,e.substring(0,g)],[0,f],[1,e.substring(g+f.length)]],a.length>b.length&&(c[0][0]=c[2][0]=-1),c):1==f.length?[[-1,a],[1,b]]:(e=this.diff_halfMatch_(a,b))?(f=e[0],a=e[1],g=e[2],b=e[3],e=e[4],f=this.diff_main(f,g,c,d),c=this.diff_main(a,b,c,d),f.concat([[0,e]],c)):c&&100<a.length&&100<b.length?this.diff_lineMode_(a,b,
+d):this.diff_bisect_(a,b,d)};
+diff_match_patch.prototype.diff_lineMode_=function(a,b,c){var d=this.diff_linesToChars_(a,b);a=d.chars1;b=d.chars2;d=d.lineArray;a=this.diff_main(a,b,!1,c);this.diff_charsToLines_(a,d);this.diff_cleanupSemantic(a);a.push([0,""]);for(var e=d=b=0,f="",g="";b<a.length;){switch(a[b][0]){case 1:e++;g+=a[b][1];break;case -1:d++;f+=a[b][1];break;case 0:if(1<=d&&1<=e){a.splice(b-d-e,d+e);b=b-d-e;d=this.diff_main(f,g,!1,c);for(e=d.length-1;0<=e;e--)a.splice(b,0,d[e]);b+=d.length}d=e=0;g=f=""}b++}a.pop();return a};
+diff_match_patch.prototype.diff_bisect_=function(a,b,c){for(var d=a.length,e=b.length,f=Math.ceil((d+e)/2),g=f,h=2*f,j=Array(h),i=Array(h),k=0;k<h;k++)j[k]=-1,i[k]=-1;j[g+1]=0;i[g+1]=0;for(var k=d-e,q=0!=k%2,r=0,t=0,p=0,w=0,v=0;v<f&&!((new Date).getTime()>c);v++){for(var n=-v+r;n<=v-t;n+=2){var l=g+n,m;m=n==-v||n!=v&&j[l-1]<j[l+1]?j[l+1]:j[l-1]+1;for(var s=m-n;m<d&&s<e&&a.charAt(m)==b.charAt(s);)m++,s++;j[l]=m;if(m>d)t+=2;else if(s>e)r+=2;else if(q&&(l=g+k-n,0<=l&&l<h&&-1!=i[l])){var u=d-i[l];if(m>=
+u)return this.diff_bisectSplit_(a,b,m,s,c)}}for(n=-v+p;n<=v-w;n+=2){l=g+n;u=n==-v||n!=v&&i[l-1]<i[l+1]?i[l+1]:i[l-1]+1;for(m=u-n;u<d&&m<e&&a.charAt(d-u-1)==b.charAt(e-m-1);)u++,m++;i[l]=u;if(u>d)w+=2;else if(m>e)p+=2;else if(!q&&(l=g+k-n,0<=l&&(l<h&&-1!=j[l])&&(m=j[l],s=g+m-l,u=d-u,m>=u)))return this.diff_bisectSplit_(a,b,m,s,c)}}return[[-1,a],[1,b]]};
+diff_match_patch.prototype.diff_bisectSplit_=function(a,b,c,d,e){var f=a.substring(0,c),g=b.substring(0,d);a=a.substring(c);b=b.substring(d);f=this.diff_main(f,g,!1,e);e=this.diff_main(a,b,!1,e);return f.concat(e)};
+diff_match_patch.prototype.diff_linesToChars_=function(a,b){function c(a){for(var b="",c=0,f=-1,g=d.length;f<a.length-1;){f=a.indexOf("\n",c);-1==f&&(f=a.length-1);var r=a.substring(c,f+1),c=f+1;(e.hasOwnProperty?e.hasOwnProperty(r):void 0!==e[r])?b+=String.fromCharCode(e[r]):(b+=String.fromCharCode(g),e[r]=g,d[g++]=r)}return b}var d=[],e={};d[0]="";var f=c(a),g=c(b);return{chars1:f,chars2:g,lineArray:d}};
+diff_match_patch.prototype.diff_charsToLines_=function(a,b){for(var c=0;c<a.length;c++){for(var d=a[c][1],e=[],f=0;f<d.length;f++)e[f]=b[d.charCodeAt(f)];a[c][1]=e.join("")}};diff_match_patch.prototype.diff_commonPrefix=function(a,b){if(!a||!b||a.charAt(0)!=b.charAt(0))return 0;for(var c=0,d=Math.min(a.length,b.length),e=d,f=0;c<e;)a.substring(f,e)==b.substring(f,e)?f=c=e:d=e,e=Math.floor((d-c)/2+c);return e};
+diff_match_patch.prototype.diff_commonSuffix=function(a,b){if(!a||!b||a.charAt(a.length-1)!=b.charAt(b.length-1))return 0;for(var c=0,d=Math.min(a.length,b.length),e=d,f=0;c<e;)a.substring(a.length-e,a.length-f)==b.substring(b.length-e,b.length-f)?f=c=e:d=e,e=Math.floor((d-c)/2+c);return e};
+diff_match_patch.prototype.diff_commonOverlap_=function(a,b){var c=a.length,d=b.length;if(0==c||0==d)return 0;c>d?a=a.substring(c-d):c<d&&(b=b.substring(0,c));c=Math.min(c,d);if(a==b)return c;for(var d=0,e=1;;){var f=a.substring(c-e),f=b.indexOf(f);if(-1==f)return d;e+=f;if(0==f||a.substring(c-e)==b.substring(0,e))d=e,e++}};
+diff_match_patch.prototype.diff_halfMatch_=function(a,b){function c(a,b,c){for(var d=a.substring(c,c+Math.floor(a.length/4)),e=-1,g="",h,j,n,l;-1!=(e=b.indexOf(d,e+1));){var m=f.diff_commonPrefix(a.substring(c),b.substring(e)),s=f.diff_commonSuffix(a.substring(0,c),b.substring(0,e));g.length<s+m&&(g=b.substring(e-s,e)+b.substring(e,e+m),h=a.substring(0,c-s),j=a.substring(c+m),n=b.substring(0,e-s),l=b.substring(e+m))}return 2*g.length>=a.length?[h,j,n,l,g]:null}if(0>=this.Diff_Timeout)return null;
+var d=a.length>b.length?a:b,e=a.length>b.length?b:a;if(4>d.length||2*e.length<d.length)return null;var f=this,g=c(d,e,Math.ceil(d.length/4)),d=c(d,e,Math.ceil(d.length/2)),h;if(!g&&!d)return null;h=d?g?g[4].length>d[4].length?g:d:d:g;var j;a.length>b.length?(g=h[0],d=h[1],e=h[2],j=h[3]):(e=h[0],j=h[1],g=h[2],d=h[3]);h=h[4];return[g,d,e,j,h]};
+diff_match_patch.prototype.diff_cleanupSemantic=function(a){for(var b=!1,c=[],d=0,e=null,f=0,g=0,h=0,j=0,i=0;f<a.length;)0==a[f][0]?(c[d++]=f,g=j,h=i,i=j=0,e=a[f][1]):(1==a[f][0]?j+=a[f][1].length:i+=a[f][1].length,e&&(e.length<=Math.max(g,h)&&e.length<=Math.max(j,i))&&(a.splice(c[d-1],0,[-1,e]),a[c[d-1]+1][0]=1,d--,d--,f=0<d?c[d-1]:-1,i=j=h=g=0,e=null,b=!0)),f++;b&&this.diff_cleanupMerge(a);this.diff_cleanupSemanticLossless(a);for(f=1;f<a.length;){if(-1==a[f-1][0]&&1==a[f][0]){b=a[f-1][1];c=a[f][1];
+d=this.diff_commonOverlap_(b,c);e=this.diff_commonOverlap_(c,b);if(d>=e){if(d>=b.length/2||d>=c.length/2)a.splice(f,0,[0,c.substring(0,d)]),a[f-1][1]=b.substring(0,b.length-d),a[f+1][1]=c.substring(d),f++}else if(e>=b.length/2||e>=c.length/2)a.splice(f,0,[0,b.substring(0,e)]),a[f-1][0]=1,a[f-1][1]=c.substring(0,c.length-e),a[f+1][0]=-1,a[f+1][1]=b.substring(e),f++;f++}f++}};
+diff_match_patch.prototype.diff_cleanupSemanticLossless=function(a){function b(a,b){if(!a||!b)return 6;var c=a.charAt(a.length-1),d=b.charAt(0),e=c.match(diff_match_patch.nonAlphaNumericRegex_),f=d.match(diff_match_patch.nonAlphaNumericRegex_),g=e&&c.match(diff_match_patch.whitespaceRegex_),h=f&&d.match(diff_match_patch.whitespaceRegex_),c=g&&c.match(diff_match_patch.linebreakRegex_),d=h&&d.match(diff_match_patch.linebreakRegex_),i=c&&a.match(diff_match_patch.blanklineEndRegex_),j=d&&b.match(diff_match_patch.blanklineStartRegex_);
+return i||j?5:c||d?4:e&&!g&&h?3:g||h?2:e||f?1:0}for(var c=1;c<a.length-1;){if(0==a[c-1][0]&&0==a[c+1][0]){var d=a[c-1][1],e=a[c][1],f=a[c+1][1],g=this.diff_commonSuffix(d,e);if(g)var h=e.substring(e.length-g),d=d.substring(0,d.length-g),e=h+e.substring(0,e.length-g),f=h+f;for(var g=d,h=e,j=f,i=b(d,e)+b(e,f);e.charAt(0)===f.charAt(0);){var d=d+e.charAt(0),e=e.substring(1)+f.charAt(0),f=f.substring(1),k=b(d,e)+b(e,f);k>=i&&(i=k,g=d,h=e,j=f)}a[c-1][1]!=g&&(g?a[c-1][1]=g:(a.splice(c-1,1),c--),a[c][1]=
+h,j?a[c+1][1]=j:(a.splice(c+1,1),c--))}c++}};diff_match_patch.nonAlphaNumericRegex_=/[^a-zA-Z0-9]/;diff_match_patch.whitespaceRegex_=/\s/;diff_match_patch.linebreakRegex_=/[\r\n]/;diff_match_patch.blanklineEndRegex_=/\n\r?\n$/;diff_match_patch.blanklineStartRegex_=/^\r?\n\r?\n/;
+diff_match_patch.prototype.diff_cleanupEfficiency=function(a){for(var b=!1,c=[],d=0,e=null,f=0,g=!1,h=!1,j=!1,i=!1;f<a.length;){if(0==a[f][0])a[f][1].length<this.Diff_EditCost&&(j||i)?(c[d++]=f,g=j,h=i,e=a[f][1]):(d=0,e=null),j=i=!1;else if(-1==a[f][0]?i=!0:j=!0,e&&(g&&h&&j&&i||e.length<this.Diff_EditCost/2&&3==g+h+j+i))a.splice(c[d-1],0,[-1,e]),a[c[d-1]+1][0]=1,d--,e=null,g&&h?(j=i=!0,d=0):(d--,f=0<d?c[d-1]:-1,j=i=!1),b=!0;f++}b&&this.diff_cleanupMerge(a)};
+diff_match_patch.prototype.diff_cleanupMerge=function(a){a.push([0,""]);for(var b=0,c=0,d=0,e="",f="",g;b<a.length;)switch(a[b][0]){case 1:d++;f+=a[b][1];b++;break;case -1:c++;e+=a[b][1];b++;break;case 0:1<c+d?(0!==c&&0!==d&&(g=this.diff_commonPrefix(f,e),0!==g&&(0<b-c-d&&0==a[b-c-d-1][0]?a[b-c-d-1][1]+=f.substring(0,g):(a.splice(0,0,[0,f.substring(0,g)]),b++),f=f.substring(g),e=e.substring(g)),g=this.diff_commonSuffix(f,e),0!==g&&(a[b][1]=f.substring(f.length-g)+a[b][1],f=f.substring(0,f.length-
+g),e=e.substring(0,e.length-g))),0===c?a.splice(b-d,c+d,[1,f]):0===d?a.splice(b-c,c+d,[-1,e]):a.splice(b-c-d,c+d,[-1,e],[1,f]),b=b-c-d+(c?1:0)+(d?1:0)+1):0!==b&&0==a[b-1][0]?(a[b-1][1]+=a[b][1],a.splice(b,1)):b++,c=d=0,f=e=""}""===a[a.length-1][1]&&a.pop();c=!1;for(b=1;b<a.length-1;)0==a[b-1][0]&&0==a[b+1][0]&&(a[b][1].substring(a[b][1].length-a[b-1][1].length)==a[b-1][1]?(a[b][1]=a[b-1][1]+a[b][1].substring(0,a[b][1].length-a[b-1][1].length),a[b+1][1]=a[b-1][1]+a[b+1][1],a.splice(b-1,1),c=!0):a[b][1].substring(0,
+a[b+1][1].length)==a[b+1][1]&&(a[b-1][1]+=a[b+1][1],a[b][1]=a[b][1].substring(a[b+1][1].length)+a[b+1][1],a.splice(b+1,1),c=!0)),b++;c&&this.diff_cleanupMerge(a)};diff_match_patch.prototype.diff_xIndex=function(a,b){var c=0,d=0,e=0,f=0,g;for(g=0;g<a.length;g++){1!==a[g][0]&&(c+=a[g][1].length);-1!==a[g][0]&&(d+=a[g][1].length);if(c>b)break;e=c;f=d}return a.length!=g&&-1===a[g][0]?f:f+(b-e)};
+diff_match_patch.prototype.diff_prettyHtml=function(a){for(var b=[],c=/&/g,d=/</g,e=/>/g,f=/\n/g,g=0;g<a.length;g++){var h=a[g][0],j=a[g][1],j=j.replace(c,"&amp;").replace(d,"&lt;").replace(e,"&gt;").replace(f,"&para;<br>");switch(h){case 1:b[g]='<ins style="background:#e6ffe6;">'+j+"</ins>";break;case -1:b[g]='<del style="background:#ffe6e6;">'+j+"</del>";break;case 0:b[g]="<span>"+j+"</span>"}}return b.join("")};
+diff_match_patch.prototype.diff_text1=function(a){for(var b=[],c=0;c<a.length;c++)1!==a[c][0]&&(b[c]=a[c][1]);return b.join("")};diff_match_patch.prototype.diff_text2=function(a){for(var b=[],c=0;c<a.length;c++)-1!==a[c][0]&&(b[c]=a[c][1]);return b.join("")};diff_match_patch.prototype.diff_levenshtein=function(a){for(var b=0,c=0,d=0,e=0;e<a.length;e++){var f=a[e][0],g=a[e][1];switch(f){case 1:c+=g.length;break;case -1:d+=g.length;break;case 0:b+=Math.max(c,d),d=c=0}}return b+=Math.max(c,d)};
+diff_match_patch.prototype.diff_toDelta=function(a){for(var b=[],c=0;c<a.length;c++)switch(a[c][0]){case 1:b[c]="+"+encodeURI(a[c][1]);break;case -1:b[c]="-"+a[c][1].length;break;case 0:b[c]="="+a[c][1].length}return b.join("\t").replace(/%20/g," ")};
+diff_match_patch.prototype.diff_fromDelta=function(a,b){for(var c=[],d=0,e=0,f=b.split(/\t/g),g=0;g<f.length;g++){var h=f[g].substring(1);switch(f[g].charAt(0)){case "+":try{c[d++]=[1,decodeURI(h)]}catch(j){throw Error("Illegal escape in diff_fromDelta: "+h);}break;case "-":case "=":var i=parseInt(h,10);if(isNaN(i)||0>i)throw Error("Invalid number in diff_fromDelta: "+h);h=a.substring(e,e+=i);"="==f[g].charAt(0)?c[d++]=[0,h]:c[d++]=[-1,h];break;default:if(f[g])throw Error("Invalid diff operation in diff_fromDelta: "+
+f[g]);}}if(e!=a.length)throw Error("Delta length ("+e+") does not equal source text length ("+a.length+").");return c};diff_match_patch.prototype.match_main=function(a,b,c){if(null==a||null==b||null==c)throw Error("Null input. (match_main)");c=Math.max(0,Math.min(c,a.length));return a==b?0:a.length?a.substring(c,c+b.length)==b?c:this.match_bitap_(a,b,c):-1};
+diff_match_patch.prototype.match_bitap_=function(a,b,c){function d(a,d){var e=a/b.length,g=Math.abs(c-d);return!f.Match_Distance?g?1:e:e+g/f.Match_Distance}if(b.length>this.Match_MaxBits)throw Error("Pattern too long for this browser.");var e=this.match_alphabet_(b),f=this,g=this.Match_Threshold,h=a.indexOf(b,c);-1!=h&&(g=Math.min(d(0,h),g),h=a.lastIndexOf(b,c+b.length),-1!=h&&(g=Math.min(d(0,h),g)));for(var j=1<<b.length-1,h=-1,i,k,q=b.length+a.length,r,t=0;t<b.length;t++){i=0;for(k=q;i<k;)d(t,c+
+k)<=g?i=k:q=k,k=Math.floor((q-i)/2+i);q=k;i=Math.max(1,c-k+1);var p=Math.min(c+k,a.length)+b.length;k=Array(p+2);for(k[p+1]=(1<<t)-1;p>=i;p--){var w=e[a.charAt(p-1)];k[p]=0===t?(k[p+1]<<1|1)&w:(k[p+1]<<1|1)&w|((r[p+1]|r[p])<<1|1)|r[p+1];if(k[p]&j&&(w=d(t,p-1),w<=g))if(g=w,h=p-1,h>c)i=Math.max(1,2*c-h);else break}if(d(t+1,c)>g)break;r=k}return h};
+diff_match_patch.prototype.match_alphabet_=function(a){for(var b={},c=0;c<a.length;c++)b[a.charAt(c)]=0;for(c=0;c<a.length;c++)b[a.charAt(c)]|=1<<a.length-c-1;return b};
+diff_match_patch.prototype.patch_addContext_=function(a,b){if(0!=b.length){for(var c=b.substring(a.start2,a.start2+a.length1),d=0;b.indexOf(c)!=b.lastIndexOf(c)&&c.length<this.Match_MaxBits-this.Patch_Margin-this.Patch_Margin;)d+=this.Patch_Margin,c=b.substring(a.start2-d,a.start2+a.length1+d);d+=this.Patch_Margin;(c=b.substring(a.start2-d,a.start2))&&a.diffs.unshift([0,c]);(d=b.substring(a.start2+a.length1,a.start2+a.length1+d))&&a.diffs.push([0,d]);a.start1-=c.length;a.start2-=c.length;a.length1+=
+c.length+d.length;a.length2+=c.length+d.length}};
+diff_match_patch.prototype.patch_make=function(a,b,c){var d;if("string"==typeof a&&"string"==typeof b&&"undefined"==typeof c)d=a,b=this.diff_main(d,b,!0),2<b.length&&(this.diff_cleanupSemantic(b),this.diff_cleanupEfficiency(b));else if(a&&"object"==typeof a&&"undefined"==typeof b&&"undefined"==typeof c)b=a,d=this.diff_text1(b);else if("string"==typeof a&&b&&"object"==typeof b&&"undefined"==typeof c)d=a;else if("string"==typeof a&&"string"==typeof b&&c&&"object"==typeof c)d=a,b=c;else throw Error("Unknown call format to patch_make.");
+if(0===b.length)return[];c=[];a=new diff_match_patch.patch_obj;for(var e=0,f=0,g=0,h=d,j=0;j<b.length;j++){var i=b[j][0],k=b[j][1];!e&&0!==i&&(a.start1=f,a.start2=g);switch(i){case 1:a.diffs[e++]=b[j];a.length2+=k.length;d=d.substring(0,g)+k+d.substring(g);break;case -1:a.length1+=k.length;a.diffs[e++]=b[j];d=d.substring(0,g)+d.substring(g+k.length);break;case 0:k.length<=2*this.Patch_Margin&&e&&b.length!=j+1?(a.diffs[e++]=b[j],a.length1+=k.length,a.length2+=k.length):k.length>=2*this.Patch_Margin&&
+e&&(this.patch_addContext_(a,h),c.push(a),a=new diff_match_patch.patch_obj,e=0,h=d,f=g)}1!==i&&(f+=k.length);-1!==i&&(g+=k.length)}e&&(this.patch_addContext_(a,h),c.push(a));return c};diff_match_patch.prototype.patch_deepCopy=function(a){for(var b=[],c=0;c<a.length;c++){var d=a[c],e=new diff_match_patch.patch_obj;e.diffs=[];for(var f=0;f<d.diffs.length;f++)e.diffs[f]=d.diffs[f].slice();e.start1=d.start1;e.start2=d.start2;e.length1=d.length1;e.length2=d.length2;b[c]=e}return b};
+diff_match_patch.prototype.patch_apply=function(a,b){if(0==a.length)return[b,[]];a=this.patch_deepCopy(a);var c=this.patch_addPadding(a);b=c+b+c;this.patch_splitMax(a);for(var d=0,e=[],f=0;f<a.length;f++){var g=a[f].start2+d,h=this.diff_text1(a[f].diffs),j,i=-1;if(h.length>this.Match_MaxBits){if(j=this.match_main(b,h.substring(0,this.Match_MaxBits),g),-1!=j&&(i=this.match_main(b,h.substring(h.length-this.Match_MaxBits),g+h.length-this.Match_MaxBits),-1==i||j>=i))j=-1}else j=this.match_main(b,h,g);
+if(-1==j)e[f]=!1,d-=a[f].length2-a[f].length1;else if(e[f]=!0,d=j-g,g=-1==i?b.substring(j,j+h.length):b.substring(j,i+this.Match_MaxBits),h==g)b=b.substring(0,j)+this.diff_text2(a[f].diffs)+b.substring(j+h.length);else if(g=this.diff_main(h,g,!1),h.length>this.Match_MaxBits&&this.diff_levenshtein(g)/h.length>this.Patch_DeleteThreshold)e[f]=!1;else{this.diff_cleanupSemanticLossless(g);for(var h=0,k,i=0;i<a[f].diffs.length;i++){var q=a[f].diffs[i];0!==q[0]&&(k=this.diff_xIndex(g,h));1===q[0]?b=b.substring(0,
+j+k)+q[1]+b.substring(j+k):-1===q[0]&&(b=b.substring(0,j+k)+b.substring(j+this.diff_xIndex(g,h+q[1].length)));-1!==q[0]&&(h+=q[1].length)}}}b=b.substring(c.length,b.length-c.length);return[b,e]};
+diff_match_patch.prototype.patch_addPadding=function(a){for(var b=this.Patch_Margin,c="",d=1;d<=b;d++)c+=String.fromCharCode(d);for(d=0;d<a.length;d++)a[d].start1+=b,a[d].start2+=b;var d=a[0],e=d.diffs;if(0==e.length||0!=e[0][0])e.unshift([0,c]),d.start1-=b,d.start2-=b,d.length1+=b,d.length2+=b;else if(b>e[0][1].length){var f=b-e[0][1].length;e[0][1]=c.substring(e[0][1].length)+e[0][1];d.start1-=f;d.start2-=f;d.length1+=f;d.length2+=f}d=a[a.length-1];e=d.diffs;0==e.length||0!=e[e.length-1][0]?(e.push([0,
+c]),d.length1+=b,d.length2+=b):b>e[e.length-1][1].length&&(f=b-e[e.length-1][1].length,e[e.length-1][1]+=c.substring(0,f),d.length1+=f,d.length2+=f);return c};
+diff_match_patch.prototype.patch_splitMax=function(a){for(var b=this.Match_MaxBits,c=0;c<a.length;c++)if(!(a[c].length1<=b)){var d=a[c];a.splice(c--,1);for(var e=d.start1,f=d.start2,g="";0!==d.diffs.length;){var h=new diff_match_patch.patch_obj,j=!0;h.start1=e-g.length;h.start2=f-g.length;""!==g&&(h.length1=h.length2=g.length,h.diffs.push([0,g]));for(;0!==d.diffs.length&&h.length1<b-this.Patch_Margin;){var g=d.diffs[0][0],i=d.diffs[0][1];1===g?(h.length2+=i.length,f+=i.length,h.diffs.push(d.diffs.shift()),
+j=!1):-1===g&&1==h.diffs.length&&0==h.diffs[0][0]&&i.length>2*b?(h.length1+=i.length,e+=i.length,j=!1,h.diffs.push([g,i]),d.diffs.shift()):(i=i.substring(0,b-h.length1-this.Patch_Margin),h.length1+=i.length,e+=i.length,0===g?(h.length2+=i.length,f+=i.length):j=!1,h.diffs.push([g,i]),i==d.diffs[0][1]?d.diffs.shift():d.diffs[0][1]=d.diffs[0][1].substring(i.length))}g=this.diff_text2(h.diffs);g=g.substring(g.length-this.Patch_Margin);i=this.diff_text1(d.diffs).substring(0,this.Patch_Margin);""!==i&&
+(h.length1+=i.length,h.length2+=i.length,0!==h.diffs.length&&0===h.diffs[h.diffs.length-1][0]?h.diffs[h.diffs.length-1][1]+=i:h.diffs.push([0,i]));j||a.splice(++c,0,h)}}};diff_match_patch.prototype.patch_toText=function(a){for(var b=[],c=0;c<a.length;c++)b[c]=a[c];return b.join("")};
+diff_match_patch.prototype.patch_fromText=function(a){var b=[];if(!a)return b;a=a.split("\n");for(var c=0,d=/^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/;c<a.length;){var e=a[c].match(d);if(!e)throw Error("Invalid patch string: "+a[c]);var f=new diff_match_patch.patch_obj;b.push(f);f.start1=parseInt(e[1],10);""===e[2]?(f.start1--,f.length1=1):"0"==e[2]?f.length1=0:(f.start1--,f.length1=parseInt(e[2],10));f.start2=parseInt(e[3],10);""===e[4]?(f.start2--,f.length2=1):"0"==e[4]?f.length2=0:(f.start2--,f.length2=
+parseInt(e[4],10));for(c++;c<a.length;){e=a[c].charAt(0);try{var g=decodeURI(a[c].substring(1))}catch(h){throw Error("Illegal escape in patch_fromText: "+g);}if("-"==e)f.diffs.push([-1,g]);else if("+"==e)f.diffs.push([1,g]);else if(" "==e)f.diffs.push([0,g]);else if("@"==e)break;else if(""!==e)throw Error('Invalid patch mode "'+e+'" in: '+g);c++}}return b};diff_match_patch.patch_obj=function(){this.diffs=[];this.start2=this.start1=null;this.length2=this.length1=0};
+diff_match_patch.patch_obj.prototype.toString=function(){var a,b;a=0===this.length1?this.start1+",0":1==this.length1?this.start1+1:this.start1+1+","+this.length1;b=0===this.length2?this.start2+",0":1==this.length2?this.start2+1:this.start2+1+","+this.length2;a=["@@ -"+a+" +"+b+" @@\n"];var c;for(b=0;b<this.diffs.length;b++){switch(this.diffs[b][0]){case 1:c="+";break;case -1:c="-";break;case 0:c=" "}a[b+1]=c+encodeURI(this.diffs[b][1])+"\n"}return a.join("").replace(/%20/g," ")};
+this.diff_match_patch=diff_match_patch;this.DIFF_DELETE=-1;this.DIFF_INSERT=1;this.DIFF_EQUAL=0;})()
diff --git a/third-party/codemirror-3.15/addon/merge/merge.css b/third-party/codemirror-3.15/addon/merge/merge.css
new file mode 100644 (file)
index 0000000..63237fc
--- /dev/null
@@ -0,0 +1,92 @@
+.CodeMirror-merge {
+  position: relative;
+  border: 1px solid #ddd;
+  white-space: pre;
+}
+
+.CodeMirror-merge, .CodeMirror-merge .CodeMirror {
+  height: 350px;
+}
+
+.CodeMirror-merge-2pane .CodeMirror-merge-pane { width: 47%; }
+.CodeMirror-merge-2pane .CodeMirror-merge-gap { width: 6%; }
+.CodeMirror-merge-3pane .CodeMirror-merge-pane { width: 31%; }
+.CodeMirror-merge-3pane .CodeMirror-merge-gap { width: 3.5%; }
+
+.CodeMirror-merge-pane {
+  display: inline-block;
+  white-space: normal;
+  vertical-align: top;
+}
+.CodeMirror-merge-pane-rightmost {
+  position: absolute;
+  right: 0px;
+  z-index: 1;
+}
+
+.CodeMirror-merge-gap {
+  z-index: 2;
+  display: inline-block;
+  height: 100%;
+  -moz-box-sizing: border-box;
+  box-sizing: border-box;
+  overflow: hidden;
+  border-left: 1px solid #ddd;
+  border-right: 1px solid #ddd;
+  position: relative;
+  background: #f8f8f8;
+}
+
+.CodeMirror-merge-scrolllock-wrap {
+  position: absolute;
+  bottom: 0; left: 50%;
+}
+.CodeMirror-merge-scrolllock {
+  position: relative;
+  left: -50%;
+  cursor: pointer;
+  color: #555;
+  line-height: 1;
+}
+
+.CodeMirror-merge-copybuttons-left, .CodeMirror-merge-copybuttons-right {
+  position: absolute;
+  left: 0; top: 0;
+  right: 0; bottom: 0;
+  line-height: 1;
+}
+
+.CodeMirror-merge-copy {
+  position: absolute;
+  cursor: pointer;
+  color: #44c;
+}
+
+.CodeMirror-merge-copybuttons-left .CodeMirror-merge-copy { left: 2px; }
+.CodeMirror-merge-copybuttons-right .CodeMirror-merge-copy { right: 2px; }
+
+.CodeMirror-merge-r-inserted, .CodeMirror-merge-l-inserted {
+  background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAACCAYAAACddGYaAAAAGUlEQVQI12MwuCXy3+CWyH8GBgYGJgYkAABZbAQ9ELXurwAAAABJRU5ErkJggg==);
+  background-position: bottom left;
+  background-repeat: repeat-x;
+}
+
+.CodeMirror-merge-r-deleted, .CodeMirror-merge-l-deleted {
+  background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAACCAYAAACddGYaAAAAGUlEQVQI12M4Kyb2/6yY2H8GBgYGJgYkAABURgPz6Ks7wQAAAABJRU5ErkJggg==);
+  background-position: bottom left;
+  background-repeat: repeat-x;
+}
+
+.CodeMirror-merge-r-chunk { background: #ffffe0; }
+.CodeMirror-merge-r-chunk-start { border-top: 1px solid #ee8; }
+.CodeMirror-merge-r-chunk-end { border-bottom: 1px solid #ee8; }
+.CodeMirror-merge-r-connect { fill: #ffffe0; stroke: #ee8; stroke-width: 1px; }
+
+.CodeMirror-merge-l-chunk { background: #eef; }
+.CodeMirror-merge-l-chunk-start { border-top: 1px solid #88e; }
+.CodeMirror-merge-l-chunk-end { border-bottom: 1px solid #88e; }
+.CodeMirror-merge-l-connect { fill: #eef; stroke: #88e; stroke-width: 1px; }
+
+.CodeMirror-merge-l-chunk.CodeMirror-merge-r-chunk { background: #dfd; }
+.CodeMirror-merge-l-chunk-start.CodeMirror-merge-r-chunk-start { border-top: 1px solid #4e4; }
+.CodeMirror-merge-l-chunk-end.CodeMirror-merge-r-chunk-end { border-bottom: 1px solid #4e4; }
diff --git a/third-party/codemirror-3.15/addon/merge/merge.js b/third-party/codemirror-3.15/addon/merge/merge.js
new file mode 100644 (file)
index 0000000..16c3356
--- /dev/null
@@ -0,0 +1,447 @@
+(function() {
+  "use strict";
+
+  var Pos = CodeMirror.Pos;
+  var svgNS = "http://www.w3.org/2000/svg";
+
+  function DiffView(mv, type) {
+    this.mv = mv;
+    this.type = type;
+    this.classes = type == "left"
+      ? {chunk: "CodeMirror-merge-l-chunk",
+         start: "CodeMirror-merge-l-chunk-start",
+         end: "CodeMirror-merge-l-chunk-end",
+         insert: "CodeMirror-merge-l-inserted",
+         del: "CodeMirror-merge-l-deleted",
+         connect: "CodeMirror-merge-l-connect"}
+      : {chunk: "CodeMirror-merge-r-chunk",
+         start: "CodeMirror-merge-r-chunk-start",
+         end: "CodeMirror-merge-r-chunk-end",
+         insert: "CodeMirror-merge-r-inserted",
+         del: "CodeMirror-merge-r-deleted",
+         connect: "CodeMirror-merge-r-connect"};
+  }
+
+  DiffView.prototype = {
+    constructor: DiffView,
+    init: function(pane, orig, options) {
+      this.edit = this.mv.edit;
+      this.orig = CodeMirror(pane, copyObj({value: orig, readOnly: true}, copyObj(options)));
+
+      this.diff = getDiff(orig, options.value);
+      this.diffOutOfDate = false;
+
+      this.forceUpdate = registerUpdate(this);
+      setScrollLock(this, true, false);
+      registerScroll(this);
+    }
+  };
+
+  function registerUpdate(dv) {
+    var edit = {from: 0, to: 0, marked: []};
+    var orig = {from: 0, to: 0, marked: []};
+    var debounceChange;
+    function update() {
+      if (dv.diffOutOfDate) {
+        dv.diff = getDiff(dv.orig.getValue(), dv.edit.getValue());
+        dv.diffOutOfDate = false;
+      }
+      updateMarks(dv.edit, dv.diff, edit, DIFF_INSERT, dv.classes);
+      updateMarks(dv.orig, dv.diff, orig, DIFF_DELETE, dv.classes);
+      drawConnectors(dv);
+    }
+    function set(slow) {
+      clearTimeout(debounceChange);
+      debounceChange = setTimeout(update, slow == true ? 250 : 100);
+    }
+    dv.edit.on("change", function() {
+      if (!dv.diffOutOfDate) {
+        dv.diffOutOfDate = true;
+        edit.from = edit.to = orig.from = orig.to = 0;
+      }
+      set(true);
+    });
+    dv.edit.on("viewportChange", set);
+    dv.orig.on("viewportChange", set);
+    update();
+    return update;
+  }
+
+  function registerScroll(dv) {
+    dv.edit.on("scroll", function() {
+      syncScroll(dv, DIFF_INSERT) && drawConnectors(dv);
+    });
+    dv.orig.on("scroll", function() {
+      syncScroll(dv, DIFF_DELETE) && drawConnectors(dv);
+    });
+  }
+
+  function syncScroll(dv, type) {
+    // Change handler will do a refresh after a timeout when diff is out of date
+    if (dv.diffOutOfDate) return false;
+    if (!dv.lockScroll) return true;
+    var editor, other, now = +new Date;
+    if (type == DIFF_INSERT) { editor = dv.edit; other = dv.orig; }
+    else { editor = dv.orig; other = dv.edit; }
+    // Don't take action if the position of this editor was recently set
+    // (to prevent feedback loops)
+    if (editor.state.scrollSetBy == dv && (editor.state.scrollSetAt || 0) + 50 > now) return false;
+
+    var sInfo = editor.getScrollInfo(), halfScreen = .5 * sInfo.clientHeight, midY = sInfo.top + halfScreen;
+    var mid = editor.lineAtHeight(midY, "local");
+    var around = chunkBoundariesAround(dv.diff, mid, type == DIFF_INSERT);
+    var off = getOffsets(editor, type == DIFF_INSERT ? around.edit : around.orig);
+    var offOther = getOffsets(other, type == DIFF_INSERT ? around.orig : around.edit);
+    var ratio = (midY - off.top) / (off.bot - off.top);
+    var targetPos = (offOther.top - halfScreen) + ratio * (offOther.bot - offOther.top);
+
+    var botDist, mix;
+    // Some careful tweaking to make sure no space is left out of view
+    // when scrolling to top or bottom.
+    if (targetPos > sInfo.top && (mix = sInfo.top / halfScreen) < 1) {
+      targetPos = targetPos * mix + sInfo.top * (1 - mix);
+    } else if ((botDist = sInfo.height - sInfo.clientHeight - sInfo.top) < halfScreen) {
+      var otherInfo = other.getScrollInfo();
+      var botDistOther = otherInfo.height - otherInfo.clientHeight - targetPos;
+      if (botDistOther > botDist && (mix = botDist / halfScreen) < 1)
+        targetPos = targetPos * mix + (otherInfo.height - otherInfo.clientHeight - botDist) * (1 - mix);
+    }
+
+    other.scrollTo(sInfo.left, targetPos);
+    other.state.scrollSetAt = now;
+    other.state.scrollSetBy = dv;
+    return true;
+  }
+
+  function getOffsets(editor, around) {
+    var bot = around.after;
+    if (bot == null) bot = editor.lastLine() + 1;
+    return {top: editor.heightAtLine(around.before || 0, "local"),
+            bot: editor.heightAtLine(bot, "local")};
+  }
+
+  function setScrollLock(dv, val, action) {
+    dv.lockScroll = val;
+    if (val && action != false) syncScroll(dv, DIFF_INSERT) && drawConnectors(dv);
+    dv.lockButton.innerHTML = val ? "\u21db\u21da" : "\u21db&nbsp;&nbsp;\u21da";
+  }
+
+  // Updating the marks for editor content
+
+  function clearMarks(editor, arr, classes) {
+    for (var i = 0; i < arr.length; ++i) {
+      var mark = arr[i];
+      if (mark instanceof CodeMirror.TextMarker) {
+        mark.clear();
+      } else {
+        editor.removeLineClass(mark, "background", classes.chunk);
+        editor.removeLineClass(mark, "background", classes.start);
+        editor.removeLineClass(mark, "background", classes.end);
+      }
+    }
+    arr.length = 0;
+  }
+
+  // FIXME maybe add a margin around viewport to prevent too many updates
+  function updateMarks(editor, diff, state, type, classes) {
+    var vp = editor.getViewport();
+    editor.operation(function() {
+      if (state.from == state.to || vp.from - state.to > 20 || state.from - vp.to > 20) {
+        clearMarks(editor, state.marked, classes);
+        markChanges(editor, diff, type, state.marked, vp.from, vp.to, classes);
+        state.from = vp.from; state.to = vp.to;
+      } else {
+        if (vp.from < state.from) {
+          markChanges(editor, diff, type, state.marked, vp.from, state.from, classes);
+          state.from = vp.from;
+        }
+        if (vp.to > state.to) {
+          markChanges(editor, diff, type, state.marked, state.to, vp.to, classes);
+          state.to = vp.to;
+        }
+      }
+    });
+  }
+
+  function markChanges(editor, diff, type, marks, from, to, classes) {
+    var pos = Pos(0, 0);
+    var top = Pos(from, 0), bot = editor.clipPos(Pos(to - 1));
+    var cls = type == DIFF_DELETE ? classes.del : classes.insert;
+    function markChunk(start, end) {
+      var bfrom = Math.max(from, start), bto = Math.min(to, end);
+      for (var i = bfrom; i < bto; ++i) {
+        var line = editor.addLineClass(i, "background", classes.chunk);
+        if (i == start) editor.addLineClass(line, "background", classes.start);
+        if (i == end - 1) editor.addLineClass(line, "background", classes.end);
+        marks.push(line);
+      }
+      // When the chunk is empty, make sure a horizontal line shows up
+      if (start == end && bfrom == end && bto == end) {
+        if (bfrom)
+          marks.push(editor.addLineClass(bfrom - 1, "background", classes.end));
+        else
+          marks.push(editor.addLineClass(bfrom, "background", classes.start));
+      }
+    }
+
+    var chunkStart = 0;
+    for (var i = 0; i < diff.length; ++i) {
+      var part = diff[i], tp = part[0], str = part[1];
+      if (tp == DIFF_EQUAL) {
+        var cleanFrom = pos.line + (startOfLineClean(diff, i) ? 0 : 1);
+        moveOver(pos, str);
+        var cleanTo = pos.line + (endOfLineClean(diff, i) ? 1 : 0);
+        if (cleanTo > cleanFrom) {
+          if (i) markChunk(chunkStart, cleanFrom);
+          chunkStart = cleanTo;
+        }
+      } else {
+        if (tp == type) {
+          var end = moveOver(pos, str, true);
+          var a = posMax(top, pos), b = posMin(bot, end);
+          if (!posEq(a, b))
+            marks.push(editor.markText(a, b, {className: cls}));
+          pos = end;
+        }
+      }
+    }
+    if (chunkStart <= pos.line) markChunk(chunkStart, pos.line + 1);
+  }
+
+  // Updating the gap between editor and original
+
+  function drawConnectors(dv) {
+    if (dv.svg) {
+      clear(dv.svg);
+      var w = dv.gap.offsetWidth;
+      attrs(dv.svg, "width", w, "height", dv.gap.offsetHeight);
+    }
+    clear(dv.copyButtons);
+
+    var flip = dv.type == "left";
+    var vpEdit = dv.edit.getViewport(), vpOrig = dv.orig.getViewport();
+    var sTopEdit = dv.edit.getScrollInfo().top, sTopOrig = dv.orig.getScrollInfo().top;
+    iterateChunks(dv.diff, function(topOrig, botOrig, topEdit, botEdit) {
+      if (topEdit > vpEdit.to || botEdit < vpEdit.from ||
+          topOrig > vpOrig.to || botOrig < vpOrig.from)
+        return;
+      var topLpx = dv.orig.heightAtLine(topOrig, "local") - sTopOrig, top = topLpx;
+      if (dv.svg) {
+        var topRpx = dv.edit.heightAtLine(topEdit, "local") - sTopEdit;
+        if (flip) { var tmp = topLpx; topLpx = topRpx; topRpx = tmp; }
+        var botLpx = dv.orig.heightAtLine(botOrig, "local") - sTopOrig;
+        var botRpx = dv.edit.heightAtLine(botEdit, "local") - sTopEdit;
+        if (flip) { var tmp = botLpx; botLpx = botRpx; botRpx = tmp; }
+        var curveTop = " C " + w/2 + " " + topRpx + " " + w/2 + " " + topLpx + " " + (w + 2) + " " + topLpx;
+        var curveBot = " C " + w/2 + " " + botLpx + " " + w/2 + " " + botRpx + " -1 " + botRpx;
+        attrs(dv.svg.appendChild(document.createElementNS(svgNS, "path")),
+              "d", "M -1 " + topRpx + curveTop + " L " + (w + 2) + " " + botLpx + curveBot + " z",
+              "class", dv.classes.connect);
+      }
+      var copy = dv.copyButtons.appendChild(elt("div", dv.type == "left" ? "\u21dd" : "\u21dc",
+                                                "CodeMirror-merge-copy"));
+      copy.title = "Revert chunk";
+      copy.chunk = {topEdit: topEdit, botEdit: botEdit, topOrig: topOrig, botOrig: botOrig};
+      copy.style.top = top + "px";
+    });
+  }
+
+  function copyChunk(dv, chunk) {
+    if (dv.diffOutOfDate) return;
+    dv.edit.replaceRange(dv.orig.getRange(Pos(chunk.topOrig, 0), Pos(chunk.botOrig, 0)),
+                         Pos(chunk.topEdit, 0), Pos(chunk.botEdit, 0));
+  }
+
+  // Merge view, containing 0, 1, or 2 diff views.
+
+  var MergeView = CodeMirror.MergeView = function(node, options) {
+    if (!(this instanceof MergeView)) return new MergeView(node, options);
+
+    var origLeft = options.origLeft, origRight = options.origRight == null ? options.orig : options.origRight;
+    var hasLeft = origLeft != null, hasRight = origRight != null;
+    var panes = 1 + (hasLeft ? 1 : 0) + (hasRight ? 1 : 0);
+    var wrap = [], left = this.left = null, right = this.right = null;
+
+    if (hasLeft) {
+      left = this.left = new DiffView(this, "left");
+      var leftPane = elt("div", null, "CodeMirror-merge-pane");
+      wrap.push(leftPane);
+      wrap.push(buildGap(left));
+    }
+
+    var editPane = elt("div", null, "CodeMirror-merge-pane");
+    wrap.push(editPane);
+
+    if (hasRight) {
+      right = this.right = new DiffView(this, "right");
+      wrap.push(buildGap(right));
+      var rightPane = elt("div", null, "CodeMirror-merge-pane");
+      wrap.push(rightPane);
+    }
+
+    (hasRight ? rightPane : editPane).className += " CodeMirror-merge-pane-rightmost";
+
+    wrap.push(elt("div", null, null, "height: 0; clear: both;"));
+    var wrapElt = this.wrap = node.appendChild(elt("div", wrap, "CodeMirror-merge CodeMirror-merge-" + panes + "pane"));
+    this.edit = CodeMirror(editPane, copyObj(options));
+
+    if (left) left.init(leftPane, origLeft, options);
+    if (right) right.init(rightPane, origRight, options);
+
+    var onResize = function() {
+      if (left) drawConnectors(left);
+      if (right) drawConnectors(right);
+    };
+    CodeMirror.on(window, "resize", onResize);
+    var resizeInterval = setInterval(function() {
+      for (var p = wrapElt.parentNode; p && p != document.body; p = p.parentNode) {}
+      if (!p) { clearInterval(resizeInterval); CodeMirror.off(window, "resize", onResize); }
+    }, 5000);
+  };
+
+  function buildGap(dv) {
+    var lock = dv.lockButton = elt("div", null, "CodeMirror-merge-scrolllock");
+    lock.title = "Toggle locked scrolling";
+    var lockWrap = elt("div", [lock], "CodeMirror-merge-scrolllock-wrap");
+    CodeMirror.on(lock, "click", function() { setScrollLock(dv, !dv.lockScroll); });
+    dv.copyButtons = elt("div", null, "CodeMirror-merge-copybuttons-" + dv.type);
+    CodeMirror.on(dv.copyButtons, "click", function(e) {
+      var node = e.target || e.srcElement;
+      if (node.chunk) copyChunk(dv, node.chunk);
+    });
+    var gapElts = [dv.copyButtons, lockWrap];
+    var svg = document.createElementNS && document.createElementNS(svgNS, "svg");
+    if (svg && !svg.createSVGRect) svg = null;
+    dv.svg = svg;
+    if (svg) gapElts.push(svg);
+
+    return dv.gap = elt("div", gapElts, "CodeMirror-merge-gap");
+  }
+
+  MergeView.prototype = {
+    constuctor: MergeView,
+    editor: function() { return this.edit; },
+    rightOriginal: function() { return this.right && this.right.orig; },
+    leftOriginal: function() { return this.left && this.left.orig; }
+  };
+
+  // Operations on diffs
+
+  var dmp = new diff_match_patch();
+  function getDiff(a, b) {
+    var diff = dmp.diff_main(a, b);
+    dmp.diff_cleanupSemantic(diff);
+    // The library sometimes leaves in empty parts, which confuse the algorithm
+    for (var i = 0; i < diff.length; ++i) {
+      var part = diff[i];
+      if (!part[1]) {
+        diff.splice(i--, 1);
+      } else if (i && diff[i - 1][0] == part[0]) {
+        diff.splice(i--, 1);
+        diff[i][1] += part[1];
+      }
+    }
+    return diff;
+  }
+
+  function iterateChunks(diff, f) {
+    var startEdit = 0, startOrig = 0;
+    var edit = Pos(0, 0), orig = Pos(0, 0);
+    for (var i = 0; i < diff.length; ++i) {
+      var part = diff[i], tp = part[0];
+      if (tp == DIFF_EQUAL) {
+        var startOff = startOfLineClean(diff, i) ? 0 : 1;
+        var cleanFromEdit = edit.line + startOff, cleanFromOrig = orig.line + startOff;
+        moveOver(edit, part[1], null, orig);
+        var endOff = endOfLineClean(diff, i) ? 1 : 0;
+        var cleanToEdit = edit.line + endOff, cleanToOrig = orig.line + endOff;
+        if (cleanToEdit > cleanFromEdit) {
+          if (i) f(startOrig, cleanFromOrig, startEdit, cleanFromEdit);
+          startEdit = cleanToEdit; startOrig = cleanToOrig;
+        }
+      } else {
+        moveOver(tp == DIFF_INSERT ? edit : orig, part[1]);
+      }
+    }
+    if (startEdit <= edit.line || startOrig <= orig.line)
+      f(startOrig, orig.line + 1, startEdit, edit.line + 1);
+  }
+
+  function endOfLineClean(diff, i) {
+    if (i == diff.length - 1) return true;
+    var next = diff[i + 1][1];
+    if (next.length == 1 || next.charCodeAt(0) != 10) return false;
+    if (i == diff.length - 2) return true;
+    next = diff[i + 2][1];
+    return next.length > 1 && next.charCodeAt(0) == 10;
+  }
+
+  function startOfLineClean(diff, i) {
+    if (i == 0) return true;
+    var last = diff[i - 1][1];
+    if (last.charCodeAt(last.length - 1) != 10) return false;
+    if (i == 1) return true;
+    last = diff[i - 2][1];
+    return last.charCodeAt(last.length - 1) == 10;
+  }
+
+  function chunkBoundariesAround(diff, n, nInEdit) {
+    var beforeE, afterE, beforeO, afterO;
+    iterateChunks(diff, function(fromOrig, toOrig, fromEdit, toEdit) {
+      var fromLocal = nInEdit ? fromEdit : fromOrig;
+      var toLocal = nInEdit ? toEdit : toOrig;
+      if (afterE == null) {
+        if (fromLocal > n) { afterE = fromEdit; afterO = fromOrig; }
+        else if (toLocal > n) { afterE = toEdit; afterO = toOrig; }
+      }
+      if (toLocal <= n) { beforeE = toEdit; beforeO = toOrig; }
+      else if (fromLocal <= n) { beforeE = fromEdit; beforeO = fromOrig; }
+    });
+    return {edit: {before: beforeE, after: afterE}, orig: {before: beforeO, after: afterO}};
+  }
+
+  // General utilities
+
+  function elt(tag, content, className, style) {
+    var e = document.createElement(tag);
+    if (className) e.className = className;
+    if (style) e.style.cssText = style;
+    if (typeof content == "string") e.appendChild(document.createTextNode(content));
+    else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
+    return e;
+  }
+
+  function clear(node) {
+    for (var count = node.childNodes.length; count > 0; --count)
+      node.removeChild(node.firstChild);
+  }
+
+  function attrs(elt) {
+    for (var i = 1; i < arguments.length; i += 2)
+      elt.setAttribute(arguments[i], arguments[i+1]);
+  }
+
+  function copyObj(obj, target) {
+    if (!target) target = {};
+    for (var prop in obj) if (obj.hasOwnProperty(prop)) target[prop] = obj[prop];
+    return target;
+  }
+
+  function moveOver(pos, str, copy, other) {
+    var out = copy ? Pos(pos.line, pos.ch) : pos, at = 0;
+    for (;;) {
+      var nl = str.indexOf("\n", at);
+      if (nl == -1) break;
+      ++out.line;
+      if (other) ++other.line;
+      at = nl + 1;
+    }
+    out.ch = (at ? 0 : out.ch) + (str.length - at);
+    if (other) other.ch = (at ? 0 : other.ch) + (str.length - at);
+    return out;
+  }
+
+  function posMin(a, b) { return (a.line - b.line || a.ch - b.ch) < 0 ? a : b; }
+  function posMax(a, b) { return (a.line - b.line || a.ch - b.ch) > 0 ? a : b; }
+  function posEq(a, b) { return a.line == b.line && a.ch == b.ch; }
+})();
diff --git a/third-party/codemirror-3.15/addon/mode/loadmode.js b/third-party/codemirror-3.15/addon/mode/loadmode.js
new file mode 100644 (file)
index 0000000..60fafbb
--- /dev/null
@@ -0,0 +1,51 @@
+(function() {
+  if (!CodeMirror.modeURL) CodeMirror.modeURL = "../mode/%N/%N.js";
+
+  var loading = {};
+  function splitCallback(cont, n) {
+    var countDown = n;
+    return function() { if (--countDown == 0) cont(); };
+  }
+  function ensureDeps(mode, cont) {
+    var deps = CodeMirror.modes[mode].dependencies;
+    if (!deps) return cont();
+    var missing = [];
+    for (var i = 0; i < deps.length; ++i) {
+      if (!CodeMirror.modes.hasOwnProperty(deps[i]))
+        missing.push(deps[i]);
+    }
+    if (!missing.length) return cont();
+    var split = splitCallback(cont, missing.length);
+    for (var i = 0; i < missing.length; ++i)
+      CodeMirror.requireMode(missing[i], split);
+  }
+
+  CodeMirror.requireMode = function(mode, cont) {
+    if (typeof mode != "string") mode = mode.name;
+    if (CodeMirror.modes.hasOwnProperty(mode)) return ensureDeps(mode, cont);
+    if (loading.hasOwnProperty(mode)) return loading[mode].push(cont);
+
+    var script = document.createElement("script");
+    script.src = CodeMirror.modeURL.replace(/%N/g, mode);
+    var others = document.getElementsByTagName("script")[0];
+    others.parentNode.insertBefore(script, others);
+    var list = loading[mode] = [cont];
+    var count = 0, poll = setInterval(function() {
+      if (++count > 100) return clearInterval(poll);
+      if (CodeMirror.modes.hasOwnProperty(mode)) {
+        clearInterval(poll);
+        loading[mode] = null;
+        ensureDeps(mode, function() {
+          for (var i = 0; i < list.length; ++i) list[i]();
+        });
+      }
+    }, 200);
+  };
+
+  CodeMirror.autoLoadMode = function(instance, mode) {
+    if (!CodeMirror.modes.hasOwnProperty(mode))
+      CodeMirror.requireMode(mode, function() {
+        instance.setOption("mode", instance.getOption("mode"));
+      });
+  };
+}());
diff --git a/third-party/codemirror-3.15/addon/mode/multiplex.js b/third-party/codemirror-3.15/addon/mode/multiplex.js
new file mode 100644 (file)
index 0000000..32cc579
--- /dev/null
@@ -0,0 +1,101 @@
+CodeMirror.multiplexingMode = function(outer /*, others */) {
+  // Others should be {open, close, mode [, delimStyle] [, innerStyle]} objects
+  var others = Array.prototype.slice.call(arguments, 1);
+  var n_others = others.length;
+
+  function indexOf(string, pattern, from) {
+    if (typeof pattern == "string") return string.indexOf(pattern, from);
+    var m = pattern.exec(from ? string.slice(from) : string);
+    return m ? m.index + from : -1;
+  }
+
+  return {
+    startState: function() {
+      return {
+        outer: CodeMirror.startState(outer),
+        innerActive: null,
+        inner: null
+      };
+    },
+
+    copyState: function(state) {
+      return {
+        outer: CodeMirror.copyState(outer, state.outer),
+        innerActive: state.innerActive,
+        inner: state.innerActive && CodeMirror.copyState(state.innerActive.mode, state.inner)
+      };
+    },
+
+    token: function(stream, state) {
+      if (!state.innerActive) {
+        var cutOff = Infinity, oldContent = stream.string;
+        for (var i = 0; i < n_others; ++i) {
+          var other = others[i];
+          var found = indexOf(oldContent, other.open, stream.pos);
+          if (found == stream.pos) {
+            stream.match(other.open);
+            state.innerActive = other;
+            state.inner = CodeMirror.startState(other.mode, outer.indent ? outer.indent(state.outer, "") : 0);
+            return other.delimStyle;
+          } else if (found != -1 && found < cutOff) {
+            cutOff = found;
+          }
+        }
+        if (cutOff != Infinity) stream.string = oldContent.slice(0, cutOff);
+        var outerToken = outer.token(stream, state.outer);
+        if (cutOff != Infinity) stream.string = oldContent;
+        return outerToken;
+      } else {
+        var curInner = state.innerActive, oldContent = stream.string;
+        var found = indexOf(oldContent, curInner.close, stream.pos);
+        if (found == stream.pos) {
+          stream.match(curInner.close);
+          state.innerActive = state.inner = null;
+          return curInner.delimStyle;
+        }
+        if (found > -1) stream.string = oldContent.slice(0, found);
+        var innerToken = curInner.mode.token(stream, state.inner);
+        if (found > -1) stream.string = oldContent;
+        var cur = stream.current(), found = cur.indexOf(curInner.close);
+        if (found > -1) stream.backUp(cur.length - found);
+
+        if (curInner.innerStyle) {
+          if (innerToken) innerToken = innerToken + ' ' + curInner.innerStyle;
+          else innerToken = curInner.innerStyle;
+        }
+
+        return innerToken;
+      }
+    },
+
+    indent: function(state, textAfter) {
+      var mode = state.innerActive ? state.innerActive.mode : outer;
+      if (!mode.indent) return CodeMirror.Pass;
+      return mode.indent(state.innerActive ? state.inner : state.outer, textAfter);
+    },
+
+    blankLine: function(state) {
+      var mode = state.innerActive ? state.innerActive.mode : outer;
+      if (mode.blankLine) {
+        mode.blankLine(state.innerActive ? state.inner : state.outer);
+      }
+      if (!state.innerActive) {
+        for (var i = 0; i < n_others; ++i) {
+          var other = others[i];
+          if (other.open === "\n") {
+            state.innerActive = other;
+            state.inner = CodeMirror.startState(other.mode, mode.indent ? mode.indent(state.outer, "") : 0);
+          }
+        }
+      } else if (state.innerActive.close === "\n") {
+        state.innerActive = state.inner = null;
+      }
+    },
+
+    electricChars: outer.electricChars,
+
+    innerMode: function(state) {
+      return state.inner ? {state: state.inner, mode: state.innerActive.mode} : {state: state.outer, mode: outer};
+    }
+  };
+};
diff --git a/third-party/codemirror-3.15/addon/mode/multiplex_test.js b/third-party/codemirror-3.15/addon/mode/multiplex_test.js
new file mode 100644 (file)
index 0000000..c065635
--- /dev/null
@@ -0,0 +1,30 @@
+(function() {
+  CodeMirror.defineMode("markdown_with_stex", function(){
+    var inner = CodeMirror.getMode({}, "stex");
+    var outer = CodeMirror.getMode({}, "markdown");
+
+    var innerOptions = {
+      open: '$',
+      close: '$',
+      mode: inner,
+      delimStyle: 'delim',
+      innerStyle: 'inner'
+    };
+
+    return CodeMirror.multiplexingMode(outer, innerOptions);
+  });
+
+  var mode = CodeMirror.getMode({}, "markdown_with_stex");
+
+  function MT(name) {
+    test.mode(
+      name,
+      mode,
+      Array.prototype.slice.call(arguments, 1),
+      'multiplexing');
+  }
+
+  MT(
+    "stexInsideMarkdown",
+    "[strong **Equation:**] [delim $][inner&tag \\pi][delim $]");
+})();
diff --git a/third-party/codemirror-3.15/addon/mode/overlay.js b/third-party/codemirror-3.15/addon/mode/overlay.js
new file mode 100644 (file)
index 0000000..b7928a7
--- /dev/null
@@ -0,0 +1,59 @@
+// Utility function that allows modes to be combined. The mode given
+// as the base argument takes care of most of the normal mode
+// functionality, but a second (typically simple) mode is used, which
+// can override the style of text. Both modes get to parse all of the
+// text, but when both assign a non-null style to a piece of code, the
+// overlay wins, unless the combine argument was true, in which case
+// the styles are combined.
+
+// overlayParser is the old, deprecated name
+CodeMirror.overlayMode = CodeMirror.overlayParser = function(base, overlay, combine) {
+  return {
+    startState: function() {
+      return {
+        base: CodeMirror.startState(base),
+        overlay: CodeMirror.startState(overlay),
+        basePos: 0, baseCur: null,
+        overlayPos: 0, overlayCur: null
+      };
+    },
+    copyState: function(state) {
+      return {
+        base: CodeMirror.copyState(base, state.base),
+        overlay: CodeMirror.copyState(overlay, state.overlay),
+        basePos: state.basePos, baseCur: null,
+        overlayPos: state.overlayPos, overlayCur: null
+      };
+    },
+
+    token: function(stream, state) {
+      if (stream.start == state.basePos) {
+        state.baseCur = base.token(stream, state.base);
+        state.basePos = stream.pos;
+      }
+      if (stream.start == state.overlayPos) {
+        stream.pos = stream.start;
+        state.overlayCur = overlay.token(stream, state.overlay);
+        state.overlayPos = stream.pos;
+      }
+      stream.pos = Math.min(state.basePos, state.overlayPos);
+      if (stream.eol()) state.basePos = state.overlayPos = 0;
+
+      if (state.overlayCur == null) return state.baseCur;
+      if (state.baseCur != null && combine) return state.baseCur + " " + state.overlayCur;
+      else return state.overlayCur;
+    },
+
+    indent: base.indent && function(state, textAfter) {
+      return base.indent(state.base, textAfter);
+    },
+    electricChars: base.electricChars,
+
+    innerMode: function(state) { return {state: state.base, mode: base}; },
+
+    blankLine: function(state) {
+      if (base.blankLine) base.blankLine(state.base);
+      if (overlay.blankLine) overlay.blankLine(state.overlay);
+    }
+  };
+};
diff --git a/third-party/codemirror-3.15/addon/runmode/colorize.js b/third-party/codemirror-3.15/addon/runmode/colorize.js
new file mode 100644 (file)
index 0000000..62286d2
--- /dev/null
@@ -0,0 +1,29 @@
+CodeMirror.colorize = (function() {
+
+  var isBlock = /^(p|li|div|h\\d|pre|blockquote|td)$/;
+
+  function textContent(node, out) {
+    if (node.nodeType == 3) return out.push(node.nodeValue);
+    for (var ch = node.firstChild; ch; ch = ch.nextSibling) {
+      textContent(ch, out);
+      if (isBlock.test(node.nodeType)) out.push("\n");
+    }
+  }
+
+  return function(collection, defaultMode) {
+    if (!collection) collection = document.body.getElementsByTagName("pre");
+
+    for (var i = 0; i < collection.length; ++i) {
+      var node = collection[i];
+      var mode = node.getAttribute("data-lang") || defaultMode;
+      if (!mode) continue;
+
+      var text = [];
+      textContent(node, text);
+      node.innerHTML = "";
+      CodeMirror.runMode(text.join(""), mode, node);
+
+      node.className += " cm-s-default";
+    }
+  };
+})();
diff --git a/third-party/codemirror-3.15/addon/runmode/runmode-standalone.js b/third-party/codemirror-3.15/addon/runmode/runmode-standalone.js
new file mode 100644 (file)
index 0000000..5be7d74
--- /dev/null
@@ -0,0 +1,132 @@
+/* Just enough of CodeMirror to run runMode under node.js */
+
+window.CodeMirror = {};
+
+function splitLines(string){ return string.split(/\r?\n|\r/); };
+
+function StringStream(string) {
+  this.pos = this.start = 0;
+  this.string = string;
+}
+StringStream.prototype = {
+  eol: function() {return this.pos >= this.string.length;},
+  sol: function() {return this.pos == 0;},
+  peek: function() {return this.string.charAt(this.pos) || null;},
+  next: function() {
+    if (this.pos < this.string.length)
+      return this.string.charAt(this.pos++);
+  },
+  eat: function(match) {
+    var ch = this.string.charAt(this.pos);
+    if (typeof match == "string") var ok = ch == match;
+    else var ok = ch && (match.test ? match.test(ch) : match(ch));
+    if (ok) {++this.pos; return ch;}
+  },
+  eatWhile: function(match) {
+    var start = this.pos;
+    while (this.eat(match)){}
+    return this.pos > start;
+  },
+  eatSpace: function() {
+    var start = this.pos;
+    while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
+    return this.pos > start;
+  },
+  skipToEnd: function() {this.pos = this.string.length;},
+  skipTo: function(ch) {
+    var found = this.string.indexOf(ch, this.pos);
+    if (found > -1) {this.pos = found; return true;}
+  },
+  backUp: function(n) {this.pos -= n;},
+  column: function() {return this.start;},
+  indentation: function() {return 0;},
+  match: function(pattern, consume, caseInsensitive) {
+    if (typeof pattern == "string") {
+      var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
+      var substr = this.string.substr(this.pos, pattern.length);
+      if (cased(substr) == cased(pattern)) {
+        if (consume !== false) this.pos += pattern.length;
+        return true;
+      }
+    } else {
+      var match = this.string.slice(this.pos).match(pattern);
+      if (match && match.index > 0) return null;
+      if (match && consume !== false) this.pos += match[0].length;
+      return match;
+    }
+  },
+  current: function(){return this.string.slice(this.start, this.pos);}
+};
+CodeMirror.StringStream = StringStream;
+
+CodeMirror.startState = function (mode, a1, a2) {
+  return mode.startState ? mode.startState(a1, a2) : true;
+};
+
+var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
+CodeMirror.defineMode = function (name, mode) { modes[name] = mode; };
+CodeMirror.defineMIME = function (mime, spec) { mimeModes[mime] = spec; };
+CodeMirror.getMode = function (options, spec) {
+  if (typeof spec == "string" && mimeModes.hasOwnProperty(spec))
+    spec = mimeModes[spec];
+  if (typeof spec == "string")
+    var mname = spec, config = {};
+  else if (spec != null)
+    var mname = spec.name, config = spec;
+  var mfactory = modes[mname];
+  if (!mfactory) throw new Error("Unknown mode: " + spec);
+  return mfactory(options, config || {});
+};
+
+CodeMirror.runMode = function (string, modespec, callback, options) {
+  var mode = CodeMirror.getMode({ indentUnit: 2 }, modespec);
+
+  if (callback.nodeType == 1) {
+    var tabSize = (options && options.tabSize) || 4;
+    var node = callback, col = 0;
+    node.innerHTML = "";
+    callback = function (text, style) {
+      if (text == "\n") {
+        node.appendChild(document.createElement("br"));
+        col = 0;
+        return;
+      }
+      var content = "";
+      // replace tabs
+      for (var pos = 0; ;) {
+        var idx = text.indexOf("\t", pos);
+        if (idx == -1) {
+          content += text.slice(pos);
+          col += text.length - pos;
+          break;
+        } else {
+          col += idx - pos;
+          content += text.slice(pos, idx);
+          var size = tabSize - col % tabSize;
+          col += size;
+          for (var i = 0; i < size; ++i) content += " ";
+          pos = idx + 1;
+        }
+      }
+
+      if (style) {
+        var sp = node.appendChild(document.createElement("span"));
+        sp.className = "cm-" + style.replace(/ +/g, " cm-");
+        sp.appendChild(document.createTextNode(content));
+      } else {
+        node.appendChild(document.createTextNode(content));
+      }
+    };
+  }
+
+  var lines = splitLines(string), state = CodeMirror.startState(mode);
+  for (var i = 0, e = lines.length; i < e; ++i) {
+    if (i) callback("\n");
+    var stream = new CodeMirror.StringStream(lines[i]);
+    while (!stream.eol()) {
+      var style = mode.token(stream, state);
+      callback(stream.current(), style, i, stream.start);
+      stream.start = stream.pos;
+    }
+  }
+};
diff --git a/third-party/codemirror-3.15/addon/runmode/runmode.js b/third-party/codemirror-3.15/addon/runmode/runmode.js
new file mode 100644 (file)
index 0000000..a7da6d7
--- /dev/null
@@ -0,0 +1,56 @@
+CodeMirror.runMode = function(string, modespec, callback, options) {
+  var mode = CodeMirror.getMode(CodeMirror.defaults, modespec);
+  var ie = /MSIE \d/.test(navigator.userAgent);
+  var ie_lt9 = ie && (document.documentMode == null || document.documentMode < 9);
+
+  if (callback.nodeType == 1) {
+    var tabSize = (options && options.tabSize) || CodeMirror.defaults.tabSize;
+    var node = callback, col = 0;
+    node.innerHTML = "";
+    callback = function(text, style) {
+      if (text == "\n") {
+        // Emitting LF or CRLF on IE8 or earlier results in an incorrect display.
+        // Emitting a carriage return makes everything ok.
+        node.appendChild(document.createTextNode(ie_lt9 ? '\r' : text));
+        col = 0;
+        return;
+      }
+      var content = "";
+      // replace tabs
+      for (var pos = 0;;) {
+        var idx = text.indexOf("\t", pos);
+        if (idx == -1) {
+          content += text.slice(pos);
+          col += text.length - pos;
+          break;
+        } else {
+          col += idx - pos;
+          content += text.slice(pos, idx);
+          var size = tabSize - col % tabSize;
+          col += size;
+          for (var i = 0; i < size; ++i) content += " ";
+          pos = idx + 1;
+        }
+      }
+
+      if (style) {
+        var sp = node.appendChild(document.createElement("span"));
+        sp.className = "cm-" + style.replace(/ +/g, " cm-");
+        sp.appendChild(document.createTextNode(content));
+      } else {
+        node.appendChild(document.createTextNode(content));
+      }
+    };
+  }
+
+  var lines = CodeMirror.splitLines(string), state = CodeMirror.startState(mode);
+  for (var i = 0, e = lines.length; i < e; ++i) {
+    if (i) callback("\n");
+    var stream = new CodeMirror.StringStream(lines[i]);
+    while (!stream.eol()) {
+      var style = mode.token(stream, state);
+      callback(stream.current(), style, i, stream.start);
+      stream.start = stream.pos;
+    }
+  }
+};
diff --git a/third-party/codemirror-3.15/addon/runmode/runmode.node.js b/third-party/codemirror-3.15/addon/runmode/runmode.node.js
new file mode 100644 (file)
index 0000000..ffdcc16
--- /dev/null
@@ -0,0 +1,103 @@
+/* Just enough of CodeMirror to run runMode under node.js */
+
+function splitLines(string){ return string.split(/\r?\n|\r/); };
+
+function StringStream(string) {
+  this.pos = this.start = 0;
+  this.string = string;
+}
+StringStream.prototype = {
+  eol: function() {return this.pos >= this.string.length;},
+  sol: function() {return this.pos == 0;},
+  peek: function() {return this.string.charAt(this.pos) || null;},
+  next: function() {
+    if (this.pos < this.string.length)
+      return this.string.charAt(this.pos++);
+  },
+  eat: function(match) {
+    var ch = this.string.charAt(this.pos);
+    if (typeof match == "string") var ok = ch == match;
+    else var ok = ch && (match.test ? match.test(ch) : match(ch));
+    if (ok) {++this.pos; return ch;}
+  },
+  eatWhile: function(match) {
+    var start = this.pos;
+    while (this.eat(match)){}
+    return this.pos > start;
+  },
+  eatSpace: function() {
+    var start = this.pos;
+    while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
+    return this.pos > start;
+  },
+  skipToEnd: function() {this.pos = this.string.length;},
+  skipTo: function(ch) {
+    var found = this.string.indexOf(ch, this.pos);
+    if (found > -1) {this.pos = found; return true;}
+  },
+  backUp: function(n) {this.pos -= n;},
+  column: function() {return this.start;},
+  indentation: function() {return 0;},
+  match: function(pattern, consume, caseInsensitive) {
+    if (typeof pattern == "string") {
+      var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
+      var substr = this.string.substr(this.pos, pattern.length);
+      if (cased(substr) == cased(pattern)) {
+        if (consume !== false) this.pos += pattern.length;
+        return true;
+      }
+    } else {
+      var match = this.string.slice(this.pos).match(pattern);
+      if (match && match.index > 0) return null;
+      if (match && consume !== false) this.pos += match[0].length;
+      return match;
+    }
+  },
+  current: function(){return this.string.slice(this.start, this.pos);}
+};
+exports.StringStream = StringStream;
+
+exports.startState = function(mode, a1, a2) {
+  return mode.startState ? mode.startState(a1, a2) : true;
+};
+
+var modes = exports.modes = {}, mimeModes = exports.mimeModes = {};
+exports.defineMode = function(name, mode) {
+  if (arguments.length > 2) {
+    mode.dependencies = [];
+    for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]);
+  }
+  modes[name] = mode;
+};
+exports.defineMIME = function(mime, spec) { mimeModes[mime] = spec; };
+
+exports.defineMode("null", function() {
+  return {token: function(stream) {stream.skipToEnd();}};
+});
+exports.defineMIME("text/plain", "null");
+
+exports.getMode = function(options, spec) {
+  if (typeof spec == "string" && mimeModes.hasOwnProperty(spec))
+    spec = mimeModes[spec];
+  if (typeof spec == "string")
+    var mname = spec, config = {};
+  else if (spec != null)
+    var mname = spec.name, config = spec;
+  var mfactory = modes[mname];
+  if (!mfactory) throw new Error("Unknown mode: " + spec);
+  return mfactory(options, config || {});
+};
+
+exports.runMode = function(string, modespec, callback) {
+  var mode = exports.getMode({indentUnit: 2}, modespec);
+  var lines = splitLines(string), state = exports.startState(mode);
+  for (var i = 0, e = lines.length; i < e; ++i) {
+    if (i) callback("\n");
+    var stream = new exports.StringStream(lines[i]);
+    while (!stream.eol()) {
+      var style = mode.token(stream, state);
+      callback(stream.current(), style, i, stream.start);
+      stream.start = stream.pos;
+    }
+  }
+};
diff --git a/third-party/codemirror-3.15/addon/search/match-highlighter.js b/third-party/codemirror-3.15/addon/search/match-highlighter.js
new file mode 100644 (file)
index 0000000..3df6985
--- /dev/null
@@ -0,0 +1,88 @@
+// Highlighting text that matches the selection
+//
+// Defines an option highlightSelectionMatches, which, when enabled,
+// will style strings that match the selection throughout the
+// document.
+//
+// The option can be set to true to simply enable it, or to a
+// {minChars, style, showToken} object to explicitly configure it.
+// minChars is the minimum amount of characters that should be
+// selected for the behavior to occur, and style is the token style to
+// apply to the matches. This will be prefixed by "cm-" to create an
+// actual CSS class name. showToken, when enabled, will cause the
+// current token to be highlighted when nothing is selected.
+
+(function() {
+  var DEFAULT_MIN_CHARS = 2;
+  var DEFAULT_TOKEN_STYLE = "matchhighlight";
+
+  function State(options) {
+    if (typeof options == "object") {
+      this.minChars = options.minChars;
+      this.style = options.style;
+      this.showToken = options.showToken;
+    }
+    if (this.style == null) this.style = DEFAULT_TOKEN_STYLE;
+    if (this.minChars == null) this.minChars = DEFAULT_MIN_CHARS;
+    this.overlay = this.timeout = null;
+  }
+
+  CodeMirror.defineOption("highlightSelectionMatches", false, function(cm, val, old) {
+    if (old && old != CodeMirror.Init) {
+      var over = cm.state.matchHighlighter.overlay;
+      if (over) cm.removeOverlay(over);
+      clearTimeout(cm.state.matchHighlighter.timeout);
+      cm.state.matchHighlighter = null;
+      cm.off("cursorActivity", cursorActivity);
+    }
+    if (val) {
+      cm.state.matchHighlighter = new State(val);
+      highlightMatches(cm);
+      cm.on("cursorActivity", cursorActivity);
+    }
+  });
+
+  function cursorActivity(cm) {
+    var state = cm.state.matchHighlighter;
+    clearTimeout(state.timeout);
+    state.timeout = setTimeout(function() {highlightMatches(cm);}, 100);
+  }
+
+  function highlightMatches(cm) {
+    cm.operation(function() {
+      var state = cm.state.matchHighlighter;
+      if (state.overlay) {
+        cm.removeOverlay(state.overlay);
+        state.overlay = null;
+      }
+      if (!cm.somethingSelected() && state.showToken) {
+        var re = state.showToken === true ? /[\w$]/ : state.showToken;
+        var cur = cm.getCursor(), line = cm.getLine(cur.line), start = cur.ch, end = start;
+        while (start && re.test(line.charAt(start - 1))) --start;
+        while (end < line.length && re.test(line.charAt(end))) ++end;
+        if (start < end)
+          cm.addOverlay(state.overlay = makeOverlay(line.slice(start, end), re, state.style));
+        return;
+      }
+      if (cm.getCursor("head").line != cm.getCursor("anchor").line) return;
+      var selection = cm.getSelection().replace(/^\s+|\s+$/g, "");
+      if (selection.length >= state.minChars)
+        cm.addOverlay(state.overlay = makeOverlay(selection, false, state.style));
+    });
+  }
+
+  function boundariesAround(stream, re) {
+    return (!stream.start || !re.test(stream.string.charAt(stream.start - 1))) &&
+      (stream.pos == stream.string.length || !re.test(stream.string.charAt(stream.pos)));
+  }
+
+  function makeOverlay(query, hasBoundary, style) {
+    return {token: function(stream) {
+      if (stream.match(query) &&
+          (!hasBoundary || boundariesAround(stream, hasBoundary)))
+        return style;
+      stream.next();
+      stream.skipTo(query.charAt(0)) || stream.skipToEnd();
+    }};
+  }
+})();
diff --git a/third-party/codemirror-3.15/addon/search/search.js b/third-party/codemirror-3.15/addon/search/search.js
new file mode 100644 (file)
index 0000000..c30922d
--- /dev/null
@@ -0,0 +1,131 @@
+// Define search commands. Depends on dialog.js or another
+// implementation of the openDialog method.
+
+// Replace works a little oddly -- it will do the replace on the next
+// Ctrl-G (or whatever is bound to findNext) press. You prevent a
+// replace by making sure the match is no longer selected when hitting
+// Ctrl-G.
+
+(function() {
+  function searchOverlay(query) {
+    if (typeof query == "string") return {token: function(stream) {
+      if (stream.match(query)) return "searching";
+      stream.next();
+      stream.skipTo(query.charAt(0)) || stream.skipToEnd();
+    }};
+    return {token: function(stream) {
+      if (stream.match(query)) return "searching";
+      while (!stream.eol()) {
+        stream.next();
+        if (stream.match(query, false)) break;
+      }
+    }};
+  }
+
+  function SearchState() {
+    this.posFrom = this.posTo = this.query = null;
+    this.overlay = null;
+  }
+  function getSearchState(cm) {
+    return cm.state.search || (cm.state.search = new SearchState());
+  }
+  function getSearchCursor(cm, query, pos) {
+    // Heuristic: if the query string is all lowercase, do a case insensitive search.
+    return cm.getSearchCursor(query, pos, typeof query == "string" && query == query.toLowerCase());
+  }
+  function dialog(cm, text, shortText, f) {
+    if (cm.openDialog) cm.openDialog(text, f);
+    else f(prompt(shortText, ""));
+  }
+  function confirmDialog(cm, text, shortText, fs) {
+    if (cm.openConfirm) cm.openConfirm(text, fs);
+    else if (confirm(shortText)) fs[0]();
+  }
+  function parseQuery(query) {
+    var isRE = query.match(/^\/(.*)\/([a-z]*)$/);
+    return isRE ? new RegExp(isRE[1], isRE[2].indexOf("i") == -1 ? "" : "i") : query;
+  }
+  var queryDialog =
+    'Search: <input type="text" style="width: 10em"/> <span style="color: #888">(Use /re/ syntax for regexp search)</span>';
+  function doSearch(cm, rev) {
+    var state = getSearchState(cm);
+    if (state.query) return findNext(cm, rev);
+    dialog(cm, queryDialog, "Search for:", function(query) {
+      cm.operation(function() {
+        if (!query || state.query) return;
+        state.query = parseQuery(query);
+        cm.removeOverlay(state.overlay);
+        state.overlay = searchOverlay(state.query);
+        cm.addOverlay(state.overlay);
+        state.posFrom = state.posTo = cm.getCursor();
+        findNext(cm, rev);
+      });
+    });
+  }
+  function findNext(cm, rev) {cm.operation(function() {
+    var state = getSearchState(cm);
+    var cursor = getSearchCursor(cm, state.query, rev ? state.posFrom : state.posTo);
+    if (!cursor.find(rev)) {
+      cursor = getSearchCursor(cm, state.query, rev ? CodeMirror.Pos(cm.lastLine()) : CodeMirror.Pos(cm.firstLine(), 0));
+      if (!cursor.find(rev)) return;
+    }
+    cm.setSelection(cursor.from(), cursor.to());
+    state.posFrom = cursor.from(); state.posTo = cursor.to();
+  });}
+  function clearSearch(cm) {cm.operation(function() {
+    var state = getSearchState(cm);
+    if (!state.query) return;
+    state.query = null;
+    cm.removeOverlay(state.overlay);
+  });}
+
+  var replaceQueryDialog =
+    'Replace: <input type="text" style="width: 10em"/> <span style="color: #888">(Use /re/ syntax for regexp search)</span>';
+  var replacementQueryDialog = 'With: <input type="text" style="width: 10em"/>';
+  var doReplaceConfirm = "Replace? <button>Yes</button> <button>No</button> <button>Stop</button>";
+  function replace(cm, all) {
+    dialog(cm, replaceQueryDialog, "Replace:", function(query) {
+      if (!query) return;
+      query = parseQuery(query);
+      dialog(cm, replacementQueryDialog, "Replace with:", function(text) {
+        if (all) {
+          cm.operation(function() {
+            for (var cursor = getSearchCursor(cm, query); cursor.findNext();) {
+              if (typeof query != "string") {
+                var match = cm.getRange(cursor.from(), cursor.to()).match(query);
+                cursor.replace(text.replace(/\$(\d)/, function(_, i) {return match[i];}));
+              } else cursor.replace(text);
+            }
+          });
+        } else {
+          clearSearch(cm);
+          var cursor = getSearchCursor(cm, query, cm.getCursor());
+          var advance = function() {
+            var start = cursor.from(), match;
+            if (!(match = cursor.findNext())) {
+              cursor = getSearchCursor(cm, query);
+              if (!(match = cursor.findNext()) ||
+                  (start && cursor.from().line == start.line && cursor.from().ch == start.ch)) return;
+            }
+            cm.setSelection(cursor.from(), cursor.to());
+            confirmDialog(cm, doReplaceConfirm, "Replace?",
+                          [function() {doReplace(match);}, advance]);
+          };
+          var doReplace = function(match) {
+            cursor.replace(typeof query == "string" ? text :
+                           text.replace(/\$(\d)/, function(_, i) {return match[i];}));
+            advance();
+          };
+          advance();
+        }
+      });
+    });
+  }
+
+  CodeMirror.commands.find = function(cm) {clearSearch(cm); doSearch(cm);};
+  CodeMirror.commands.findNext = doSearch;
+  CodeMirror.commands.findPrev = function(cm) {doSearch(cm, true);};
+  CodeMirror.commands.clearSearch = clearSearch;
+  CodeMirror.commands.replace = replace;
+  CodeMirror.commands.replaceAll = function(cm) {replace(cm, true);};
+})();
diff --git a/third-party/codemirror-3.15/addon/search/searchcursor.js b/third-party/codemirror-3.15/addon/search/searchcursor.js
new file mode 100644 (file)
index 0000000..3da3f04
--- /dev/null
@@ -0,0 +1,143 @@
+(function(){
+  var Pos = CodeMirror.Pos;
+
+  function SearchCursor(doc, query, pos, caseFold) {
+    this.atOccurrence = false; this.doc = doc;
+    if (caseFold == null && typeof query == "string") caseFold = false;
+
+    pos = pos ? doc.clipPos(pos) : Pos(0, 0);
+    this.pos = {from: pos, to: pos};
+
+    // The matches method is filled in based on the type of query.
+    // It takes a position and a direction, and returns an object
+    // describing the next occurrence of the query, or null if no
+    // more matches were found.
+    if (typeof query != "string") { // Regexp match
+      if (!query.global) query = new RegExp(query.source, query.ignoreCase ? "ig" : "g");
+      this.matches = function(reverse, pos) {
+        if (reverse) {
+          query.lastIndex = 0;
+          var line = doc.getLine(pos.line).slice(0, pos.ch), cutOff = 0, match, start;
+          for (;;) {
+            query.lastIndex = cutOff;
+            var newMatch = query.exec(line);
+            if (!newMatch) break;
+            match = newMatch;
+            start = match.index;
+            cutOff = match.index + (match[0].length || 1);
+            if (cutOff == line.length) break;
+          }
+          var matchLen = (match && match[0].length) || 0;
+          if (!matchLen) {
+            if (start == 0 && line.length == 0) {match = undefined;}
+            else if (start != doc.getLine(pos.line).length) {
+              matchLen++;
+            }
+          }
+        } else {
+          query.lastIndex = pos.ch;
+          var line = doc.getLine(pos.line), match = query.exec(line);
+          var matchLen = (match && match[0].length) || 0;
+          var start = match && match.index;
+          if (start + matchLen != line.length && !matchLen) matchLen = 1;
+        }
+        if (match && matchLen)
+          return {from: Pos(pos.line, start),
+                  to: Pos(pos.line, start + matchLen),
+                  match: match};
+      };
+    } else { // String query
+      if (caseFold) query = query.toLowerCase();
+      var fold = caseFold ? function(str){return str.toLowerCase();} : function(str){return str;};
+      var target = query.split("\n");
+      // Different methods for single-line and multi-line queries
+      if (target.length == 1) {
+        if (!query.length) {
+          // Empty string would match anything and never progress, so
+          // we define it to match nothing instead.
+          this.matches = function() {};
+        } else {
+          this.matches = function(reverse, pos) {
+            var line = fold(doc.getLine(pos.line)), len = query.length, match;
+            if (reverse ? (pos.ch >= len && (match = line.lastIndexOf(query, pos.ch - len)) != -1)
+                        : (match = line.indexOf(query, pos.ch)) != -1)
+              return {from: Pos(pos.line, match),
+                      to: Pos(pos.line, match + len)};
+          };
+        }
+      } else {
+        this.matches = function(reverse, pos) {
+          var ln = pos.line, idx = (reverse ? target.length - 1 : 0), match = target[idx], line = fold(doc.getLine(ln));
+          var offsetA = (reverse ? line.indexOf(match) + match.length : line.lastIndexOf(match));
+          if (reverse ? offsetA >= pos.ch || offsetA != match.length
+              : offsetA <= pos.ch || offsetA != line.length - match.length)
+            return;
+          for (;;) {
+            if (reverse ? !ln : ln == doc.lineCount() - 1) return;
+            line = fold(doc.getLine(ln += reverse ? -1 : 1));
+            match = target[reverse ? --idx : ++idx];
+            if (idx > 0 && idx < target.length - 1) {
+              if (line != match) return;
+              else continue;
+            }
+            var offsetB = (reverse ? line.lastIndexOf(match) : line.indexOf(match) + match.length);
+            if (reverse ? offsetB != line.length - match.length : offsetB != match.length)
+              return;
+            var start = Pos(pos.line, offsetA), end = Pos(ln, offsetB);
+            return {from: reverse ? end : start, to: reverse ? start : end};
+          }
+        };
+      }
+    }
+  }
+
+  SearchCursor.prototype = {
+    findNext: function() {return this.find(false);},
+    findPrevious: function() {return this.find(true);},
+
+    find: function(reverse) {
+      var self = this, pos = this.doc.clipPos(reverse ? this.pos.from : this.pos.to);
+      function savePosAndFail(line) {
+        var pos = Pos(line, 0);
+        self.pos = {from: pos, to: pos};
+        self.atOccurrence = false;
+        return false;
+      }
+
+      for (;;) {
+        if (this.pos = this.matches(reverse, pos)) {
+          if (!this.pos.from || !this.pos.to) { console.log(this.matches, this.pos); }
+          this.atOccurrence = true;
+          return this.pos.match || true;
+        }
+        if (reverse) {
+          if (!pos.line) return savePosAndFail(0);
+          pos = Pos(pos.line-1, this.doc.getLine(pos.line-1).length);
+        }
+        else {
+          var maxLine = this.doc.lineCount();
+          if (pos.line == maxLine - 1) return savePosAndFail(maxLine);
+          pos = Pos(pos.line + 1, 0);
+        }
+      }
+    },
+
+    from: function() {if (this.atOccurrence) return this.pos.from;},
+    to: function() {if (this.atOccurrence) return this.pos.to;},
+
+    replace: function(newText) {
+      if (!this.atOccurrence) return;
+      var lines = CodeMirror.splitLines(newText);
+      this.doc.replaceRange(lines, this.pos.from, this.pos.to);
+      this.pos.to = Pos(this.pos.from.line + lines.length - 1,
+                        lines[lines.length - 1].length + (lines.length == 1 ? this.pos.from.ch : 0));
+    }
+  };
+
+  CodeMirror.defineExtension("getSearchCursor", function(query, pos, caseFold) {
+    return new SearchCursor(this.doc, query, pos, caseFold);
+  });
+  CodeMirror.defineDocExtension("getSearchCursor", function(query, pos, caseFold) {
+    return new SearchCursor(this, query, pos, caseFold);
+  });
+})();
diff --git a/third-party/codemirror-3.15/addon/selection/active-line.js b/third-party/codemirror-3.15/addon/selection/active-line.js
new file mode 100644 (file)
index 0000000..e505086
--- /dev/null
@@ -0,0 +1,39 @@
+// Because sometimes you need to style the cursor's line.
+//
+// Adds an option 'styleActiveLine' which, when enabled, gives the
+// active line's wrapping <div> the CSS class "CodeMirror-activeline",
+// and gives its background <div> the class "CodeMirror-activeline-background".
+
+(function() {
+  "use strict";
+  var WRAP_CLASS = "CodeMirror-activeline";
+  var BACK_CLASS = "CodeMirror-activeline-background";
+
+  CodeMirror.defineOption("styleActiveLine", false, function(cm, val, old) {
+    var prev = old && old != CodeMirror.Init;
+    if (val && !prev) {
+      updateActiveLine(cm);
+      cm.on("cursorActivity", updateActiveLine);
+    } else if (!val && prev) {
+      cm.off("cursorActivity", updateActiveLine);
+      clearActiveLine(cm);
+      delete cm.state.activeLine;
+    }
+  });
+
+  function clearActiveLine(cm) {
+    if ("activeLine" in cm.state) {
+      cm.removeLineClass(cm.state.activeLine, "wrap", WRAP_CLASS);
+      cm.removeLineClass(cm.state.activeLine, "background", BACK_CLASS);
+    }
+  }
+
+  function updateActiveLine(cm) {
+    var line = cm.getLineHandleVisualStart(cm.getCursor().line);
+    if (cm.state.activeLine == line) return;
+    clearActiveLine(cm);
+    cm.addLineClass(line, "wrap", WRAP_CLASS);
+    cm.addLineClass(line, "background", BACK_CLASS);
+    cm.state.activeLine = line;
+  }
+})();
diff --git a/third-party/codemirror-3.15/addon/selection/mark-selection.js b/third-party/codemirror-3.15/addon/selection/mark-selection.js
new file mode 100644 (file)
index 0000000..c97776e
--- /dev/null
@@ -0,0 +1,108 @@
+// Because sometimes you need to mark the selected *text*.
+//
+// Adds an option 'styleSelectedText' which, when enabled, gives
+// selected text the CSS class given as option value, or
+// "CodeMirror-selectedtext" when the value is not a string.
+
+(function() {
+  "use strict";
+
+  CodeMirror.defineOption("styleSelectedText", false, function(cm, val, old) {
+    var prev = old && old != CodeMirror.Init;
+    if (val && !prev) {
+      cm.state.markedSelection = [];
+      cm.state.markedSelectionStyle = typeof val == "string" ? val : "CodeMirror-selectedtext";
+      reset(cm);
+      cm.on("cursorActivity", onCursorActivity);
+      cm.on("change", onChange);
+    } else if (!val && prev) {
+      cm.off("cursorActivity", onCursorActivity);
+      cm.off("change", onChange);
+      clear(cm);
+      cm.state.markedSelection = cm.state.markedSelectionStyle = null;
+    }
+  });
+
+  function onCursorActivity(cm) {
+    cm.operation(function() { update(cm); });
+  }
+
+  function onChange(cm) {
+    if (cm.state.markedSelection.length)
+      cm.operation(function() { clear(cm); });
+  }
+
+  var CHUNK_SIZE = 8;
+  var Pos = CodeMirror.Pos;
+
+  function cmp(pos1, pos2) {
+    return pos1.line - pos2.line || pos1.ch - pos2.ch;
+  }
+
+  function coverRange(cm, from, to, addAt) {
+    if (cmp(from, to) == 0) return;
+    var array = cm.state.markedSelection;
+    var cls = cm.state.markedSelectionStyle;
+    for (var line = from.line;;) {
+      var start = line == from.line ? from : Pos(line, 0);
+      var endLine = line + CHUNK_SIZE, atEnd = endLine >= to.line;
+      var end = atEnd ? to : Pos(endLine, 0);
+      var mark = cm.markText(start, end, {className: cls});
+      if (addAt == null) array.push(mark);
+      else array.splice(addAt++, 0, mark);
+      if (atEnd) break;
+      line = endLine;
+    }
+  }
+
+  function clear(cm) {
+    var array = cm.state.markedSelection;
+    for (var i = 0; i < array.length; ++i) array[i].clear();
+    array.length = 0;
+  }
+
+  function reset(cm) {
+    clear(cm);
+    var from = cm.getCursor("start"), to = cm.getCursor("end");
+    coverRange(cm, from, to);
+  }
+
+  function update(cm) {
+    var from = cm.getCursor("start"), to = cm.getCursor("end");
+    if (cmp(from, to) == 0) return clear(cm);
+
+    var array = cm.state.markedSelection;
+    if (!array.length) return coverRange(cm, from, to);
+
+    var coverStart = array[0].find(), coverEnd = array[array.length - 1].find();
+    if (!coverStart || !coverEnd || to.line - from.line < CHUNK_SIZE ||
+        cmp(from, coverEnd.to) >= 0 || cmp(to, coverStart.from) <= 0)
+      return reset(cm);
+
+    while (cmp(from, coverStart.from) > 0) {
+      array.shift().clear();
+      coverStart = array[0].find();
+    }
+    if (cmp(from, coverStart.from) < 0) {
+      if (coverStart.to.line - from.line < CHUNK_SIZE) {
+        array.shift().clear();
+        coverRange(cm, from, coverStart.to, 0);
+      } else {
+        coverRange(cm, from, coverStart.from, 0);
+      }
+    }
+
+    while (cmp(to, coverEnd.to) < 0) {
+      array.pop().clear();
+      coverEnd = array[array.length - 1].find();
+    }
+    if (cmp(to, coverEnd.to) > 0) {
+      if (to.line - coverEnd.from.line < CHUNK_SIZE) {
+        array.pop().clear();
+        coverRange(cm, coverEnd.from, to);
+      } else {
+        coverRange(cm, coverEnd.to, to);
+      }
+    }
+  }
+})();
diff --git a/third-party/codemirror-3.15/addon/tern/tern.css b/third-party/codemirror-3.15/addon/tern/tern.css
new file mode 100644 (file)
index 0000000..eacc2f0
--- /dev/null
@@ -0,0 +1,85 @@
+.CodeMirror-Tern-completion {
+  padding-left: 22px;
+  position: relative;
+}
+.CodeMirror-Tern-completion:before {
+  position: absolute;
+  left: 2px;
+  bottom: 2px;
+  border-radius: 50%;
+  font-size: 12px;
+  font-weight: bold;
+  height: 15px;
+  width: 15px;
+  line-height: 16px;
+  text-align: center;
+  color: white;
+  -moz-box-sizing: border-box;
+  box-sizing: border-box;
+}
+.CodeMirror-Tern-completion-unknown:before {
+  content: "?";
+  background: #4bb;
+}
+.CodeMirror-Tern-completion-object:before {
+  content: "O";
+  background: #77c;
+}
+.CodeMirror-Tern-completion-fn:before {
+  content: "F";
+  background: #7c7;
+}
+.CodeMirror-Tern-completion-array:before {
+  content: "A";
+  background: #c66;
+}
+.CodeMirror-Tern-completion-number:before {
+  content: "1";
+  background: #999;
+}
+.CodeMirror-Tern-completion-string:before {
+  content: "S";
+  background: #999;
+}
+.CodeMirror-Tern-completion-bool:before {
+  content: "B";
+  background: #999;
+}
+
+.CodeMirror-Tern-completion-guess {
+  color: #999;
+}
+
+.CodeMirror-Tern-tooltip {
+  border: 1px solid silver;
+  border-radius: 3px;
+  color: #444;
+  padding: 2px 5px;
+  font-size: 90%;
+  font-family: monospace;
+  background-color: white;
+  white-space: pre-wrap;
+
+  max-width: 40em;
+  position: absolute;
+  z-index: 10;
+  -webkit-box-shadow: 2px 3px 5px rgba(0,0,0,.2);
+  -moz-box-shadow: 2px 3px 5px rgba(0,0,0,.2);
+  box-shadow: 2px 3px 5px rgba(0,0,0,.2);
+
+  transition: opacity 1s;
+  -moz-transition: opacity 1s;
+  -webkit-transition: opacity 1s;
+  -o-transition: opacity 1s;
+  -ms-transition: opacity 1s;
+}
+
+.CodeMirror-Tern-hint-doc {
+  max-width: 25em;
+}
+
+.CodeMirror-Tern-fname { color: black; }
+.CodeMirror-Tern-farg { color: #70a; }
+.CodeMirror-Tern-farg-current { text-decoration: underline; }
+.CodeMirror-Tern-type { color: #07c; }
+.CodeMirror-Tern-fhint-guess { opacity: .7; }
diff --git a/third-party/codemirror-3.15/addon/tern/tern.js b/third-party/codemirror-3.15/addon/tern/tern.js
new file mode 100644 (file)
index 0000000..1be5ba7
--- /dev/null
@@ -0,0 +1,608 @@
+// Glue code between CodeMirror and Tern.
+//
+// Create a CodeMirror.TernServer to wrap an actual Tern server,
+// register open documents (CodeMirror.Doc instances) with it, and
+// call its methods to activate the assisting functions that Tern
+// provides.
+//
+// Options supported (all optional):
+// * defs: An array of JSON definition data structures.
+// * plugins: An object mapping plugin names to configuration
+//   options.
+// * getFile: A function(name, c) that can be used to access files in
+//   the project that haven't been loaded yet. Simply do c(null) to
+//   indicate that a file is not available.
+// * fileFilter: A function(value, docName, doc) that will be applied
+//   to documents before passing them on to Tern.
+// * switchToDoc: A function(name) that should, when providing a
+//   multi-file view, switch the view or focus to the named file.
+// * showError: A function(editor, message) that can be used to
+//   override the way errors are displayed.
+// * completionTip: Customize the content in tooltips for completions.
+//   Is passed a single argument—the completion's data as returned by
+//   Tern—and may return a string, DOM node, or null to indicate that
+//   no tip should be shown. By default the docstring is shown.
+// * typeTip: Like completionTip, but for the tooltips shown for type
+//   queries.
+//
+// It is possible to run the Tern server in a web worker by specifying
+// these additional options:
+// * useWorker: Set to true to enable web worker mode. You'll probably
+//   want to feature detect the actual value you use here, for example
+//   !!window.Worker.
+// * workerScript: The main script of the worker. Point this to
+//   wherever you are hosting worker.js from this directory.
+// * workerDeps: An array of paths pointing (relative to workerScript)
+//   to the Acorn and Tern libraries and any Tern plugins you want to
+//   load. Or, if you minified those into a single script and included
+//   them in the workerScript, simply leave this undefined.
+
+(function() {
+  "use strict";
+
+  CodeMirror.TernServer = function(options) {
+    var self = this;
+    this.options = options || {};
+    var plugins = this.options.plugins || (this.options.plugins = {});
+    if (!plugins.doc_comment) plugins.doc_comment = true;
+    if (this.options.useWorker) {
+      this.server = new WorkerServer(this);
+    } else {
+      this.server = new tern.Server({
+        getFile: function(name, c) { return getFile(self, name, c); },
+        async: true,
+        defs: this.options.defs || [],
+        plugins: plugins
+      });
+    }
+    this.docs = Object.create(null);
+    this.trackChange = function(doc, change) { trackChange(self, doc, change); };
+
+    this.cachedArgHints = null;
+    this.activeArgHints = null;
+    this.jumpStack = [];
+  };
+
+  CodeMirror.TernServer.prototype = {
+    addDoc: function(name, doc) {
+      var data = {doc: doc, name: name, changed: null};
+      this.server.addFile(name, docValue(this, data));
+      CodeMirror.on(doc, "change", this.trackChange);
+      return this.docs[name] = data;
+    },
+
+    delDoc: function(name) {
+      var found = this.docs[name];
+      if (!found) return;
+      CodeMirror.off(found.doc, "change", this.trackChange);
+      delete this.docs[name];
+      this.server.delFile(name);
+    },
+
+    hideDoc: function(name) {
+      closeArgHints(this);
+      var found = this.docs[name];
+      if (found && found.changed) sendDoc(this, found);
+    },
+
+    complete: function(cm) {
+      var self = this;
+      CodeMirror.showHint(cm, function(cm, c) { return hint(self, cm, c); }, {async: true});
+    },
+
+    getHint: function(cm, c) { return hint(this, cm, c); },
+
+    showType: function(cm) { showType(this, cm); },
+
+    updateArgHints: function(cm) { updateArgHints(this, cm); },
+
+    jumpToDef: function(cm) { jumpToDef(this, cm); },
+
+    jumpBack: function(cm) { jumpBack(this, cm); },
+
+    rename: function(cm) { rename(this, cm); },
+
+    request: function(cm, query, c) {
+      this.server.request(buildRequest(this, findDoc(this, cm.getDoc()), query), c);
+    }
+  };
+
+  var Pos = CodeMirror.Pos;
+  var cls = "CodeMirror-Tern-";
+  var bigDoc = 250;
+
+  function getFile(ts, name, c) {
+    var buf = ts.docs[name];
+    if (buf)
+      c(docValue(ts, buf));
+    else if (ts.options.getFile)
+      ts.options.getFile(name, c);
+    else
+      c(null);
+  }
+
+  function findDoc(ts, doc, name) {
+    for (var n in ts.docs) {
+      var cur = ts.docs[n];
+      if (cur.doc == doc) return cur;
+    }
+    if (!name) for (var i = 0;; ++i) {
+      n = "[doc" + (i || "") + "]";
+      if (!ts.docs[n]) { name = n; break; }
+    }
+    return ts.addDoc(name, doc);
+  }
+
+  function trackChange(ts, doc, change) {
+    var data = findDoc(ts, doc);
+
+    var argHints = ts.cachedArgHints;
+    if (argHints && argHints.doc == doc && cmpPos(argHints.start, change.to) <= 0)
+      ts.cachedArgHints = null;
+
+    var changed = data.changed;
+    if (changed == null)
+      data.changed = changed = {from: change.from.line, to: change.from.line};
+    var end = change.from.line + (change.text.length - 1);
+    if (change.from.line < changed.to) changed.to = changed.to - (change.to.line - end);
+    if (end >= changed.to) changed.to = end + 1;
+    if (changed.from > change.from.line) changed.from = change.from.line;
+
+    if (doc.lineCount() > bigDoc && change.to - changed.from > 100) setTimeout(function() {
+      if (data.changed && data.changed.to - data.changed.from > 100) sendDoc(ts, data);
+    }, 200);
+  }
+
+  function sendDoc(ts, doc) {
+    ts.server.request({files: [{type: "full", name: doc.name, text: docValue(ts, doc)}]}, function(error) {
+      if (error) console.error(error);
+      else doc.changed = null;
+    });
+  }
+
+  // Completion
+
+  function hint(ts, cm, c) {
+    ts.request(cm, {type: "completions", types: true, docs: true, urls: true}, function(error, data) {
+      if (error) return showError(ts, cm, error);
+      var completions = [], after = "";
+      var from = data.start, to = data.end;
+      if (cm.getRange(Pos(from.line, from.ch - 2), from) == "[\"" &&
+          cm.getRange(to, Pos(to.line, to.ch + 2)) != "\"]")
+        after = "\"]";
+
+      for (var i = 0; i < data.completions.length; ++i) {
+        var completion = data.completions[i], className = typeToIcon(completion.type);
+        if (data.guess) className += " " + cls + "guess";
+        completions.push({text: completion.name + after,
+                          displayText: completion.name,
+                          className: className,
+                          data: completion});
+      }
+
+      var obj = {from: from, to: to, list: completions};
+      var tooltip = null;
+      CodeMirror.on(obj, "close", function() { remove(tooltip); });
+      CodeMirror.on(obj, "update", function() { remove(tooltip); });
+      CodeMirror.on(obj, "select", function(cur, node) {
+        remove(tooltip);
+        var content = ts.options.completionTip ? ts.options.completionTip(cur.data) : cur.data.doc;
+        if (content) {
+          tooltip = makeTooltip(node.parentNode.getBoundingClientRect().right + window.pageXOffset,
+                                node.getBoundingClientRect().top + window.pageYOffset, content);
+          tooltip.className += " " + cls + "hint-doc";
+        }
+      });
+      c(obj);
+    });
+  }
+
+  function typeToIcon(type) {
+    var suffix;
+    if (type == "?") suffix = "unknown";
+    else if (type == "number" || type == "string" || type == "bool") suffix = type;
+    else if (/^fn\(/.test(type)) suffix = "fn";
+    else if (/^\[/.test(type)) suffix = "array";
+    else suffix = "object";
+    return cls + "completion " + cls + "completion-" + suffix;
+  }
+
+  // Type queries
+
+  function showType(ts, cm) {
+    ts.request(cm, "type", function(error, data) {
+      if (error) return showError(ts, cm, error);
+      if (ts.options.typeTip) {
+        var tip = ts.options.typeTip(data);
+      } else {
+        var tip = elt("span", null, elt("strong", null, data.type || "not found"));
+        if (data.doc)
+          tip.appendChild(document.createTextNode(" — " + data.doc));
+        if (data.url) {
+          tip.appendChild(document.createTextNode(" "));
+          tip.appendChild(elt("a", null, "[docs]")).href = data.url;
+        }
+      }
+      tempTooltip(cm, tip);
+    });
+  }
+
+  // Maintaining argument hints
+
+  function updateArgHints(ts, cm) {
+    closeArgHints(ts);
+
+    if (cm.somethingSelected()) return;
+    var lex = cm.getTokenAt(cm.getCursor()).state.lexical;
+    if (lex.info != "call") return;
+
+    var ch = lex.column, pos = lex.pos || 0;
+    for (var line = cm.getCursor().line, e = Math.max(0, line - 9), found = false; line >= e; --line)
+      if (cm.getLine(line).charAt(ch) == "(") {found = true; break;}
+    if (!found) return;
+
+    var start = Pos(line, ch);
+    var cache = ts.cachedArgHints;
+    if (cache && cache.doc == cm.getDoc() && cmpPos(start, cache.start) == 0)
+      return showArgHints(ts, cm, pos);
+
+    ts.request(cm, {type: "type", preferFunction: true, end: start}, function(error, data) {
+      if (error || !data.type || !(/^fn\(/).test(data.type)) return;
+      ts.cachedArgHints = {
+        start: pos,
+        type: parseFnType(data.type),
+        name: data.exprName || data.name || "fn",
+        guess: data.guess,
+        doc: cm.getDoc()
+      };
+      showArgHints(ts, cm, pos);
+    });
+  }
+
+  function showArgHints(ts, cm, pos) {
+    closeArgHints(ts);
+
+    var cache = ts.cachedArgHints, tp = cache.type;
+    var tip = elt("span", cache.guess ? cls + "fhint-guess" : null,
+                  elt("span", cls + "fname", cache.name), "(");
+    for (var i = 0; i < tp.args.length; ++i) {
+      if (i) tip.appendChild(document.createTextNode(", "));
+      var arg = tp.args[i];
+      tip.appendChild(elt("span", cls + "farg" + (i == pos ? " " + cls + "farg-current" : ""), arg.name || "?"));
+      if (arg.type != "?") {
+        tip.appendChild(document.createTextNode(":\u00a0"));
+        tip.appendChild(elt("span", cls + "type", arg.type));
+      }
+    }
+    tip.appendChild(document.createTextNode(tp.rettype ? ") ->\u00a0" : ")"));
+    if (tp.rettype) tip.appendChild(elt("span", cls + "type", tp.rettype));
+    var place = cm.cursorCoords(null, "page");
+    ts.activeArgHints = makeTooltip(place.right + 1, place.bottom, tip);
+  }
+
+  function parseFnType(text) {
+    var args = [], pos = 3;
+
+    function skipMatching(upto) {
+      var depth = 0, start = pos;
+      for (;;) {
+        var next = text.charAt(pos);
+        if (upto.test(next) && !depth) return text.slice(start, pos);
+        if (/[{\[\(]/.test(next)) ++depth;
+        else if (/[}\]\)]/.test(next)) --depth;
+        ++pos;
+      }
+    }
+
+    // Parse arguments
+    if (text.charAt(pos) != ")") for (;;) {
+      var name = text.slice(pos).match(/^([^, \(\[\{]+): /);
+      if (name) {
+        pos += name[0].length;
+        name = name[1];
+      }
+      args.push({name: name, type: skipMatching(/[\),]/)});
+      if (text.charAt(pos) == ")") break;
+      pos += 2;
+    }
+
+    var rettype = text.slice(pos).match(/^\) -> (.*)$/);
+
+    return {args: args, rettype: rettype && rettype[1]};
+  }
+
+  // Moving to the definition of something
+
+  function jumpToDef(ts, cm) {
+    function inner(varName) {
+      var req = {type: "definition", variable: varName || null};
+      var doc = findDoc(ts, cm.getDoc());
+      ts.server.request(buildRequest(ts, doc, req), function(error, data) {
+        if (error) return showError(ts, cm, error);
+        if (!data.file && data.url) { window.open(data.url); return; }
+
+        if (data.file) {
+          var localDoc = ts.docs[data.file], found;
+          if (localDoc && (found = findContext(localDoc.doc, data))) {
+            ts.jumpStack.push({file: doc.name,
+                               start: cm.getCursor("from"),
+                               end: cm.getCursor("to")});
+            moveTo(ts, doc, localDoc, found.start, found.end);
+            return;
+          }
+        }
+        showError(ts, cm, "Could not find a definition.");
+      });
+    }
+
+    if (!atInterestingExpression(cm))
+      dialog(cm, "Jump to variable", function(name) { if (name) inner(name); });
+    else
+      inner();
+  }
+
+  function jumpBack(ts, cm) {
+    var pos = ts.jumpStack.pop(), doc = pos && ts.docs[pos.file];
+    if (!doc) return;
+    moveTo(ts, findDoc(ts, cm.getDoc()), doc, pos.start, pos.end);
+  }
+
+  function moveTo(ts, curDoc, doc, start, end) {
+    doc.doc.setSelection(end, start);
+    if (curDoc != doc && ts.options.switchToDoc) {
+      closeArgHints(ts);
+      ts.options.switchToDoc(doc.name);
+    }
+  }
+
+  // The {line,ch} representation of positions makes this rather awkward.
+  function findContext(doc, data) {
+    var before = data.context.slice(0, data.contextOffset).split("\n");
+    var startLine = data.start.line - (before.length - 1);
+    var start = Pos(startLine, (before.length == 1 ? data.start.ch : doc.getLine(startLine).length) - before[0].length);
+
+    var text = doc.getLine(startLine).slice(start.ch);
+    for (var cur = startLine + 1; cur < doc.lineCount() && text.length < data.context.length; ++cur)
+      text += "\n" + doc.getLine(cur);
+    if (text.slice(0, data.context.length) == data.context) return data;
+
+    var cursor = doc.getSearchCursor(data.context, 0, false);
+    var nearest, nearestDist = Infinity;
+    while (cursor.findNext()) {
+      var from = cursor.from(), dist = Math.abs(from.line - start.line) * 10000;
+      if (!dist) dist = Math.abs(from.ch - start.ch);
+      if (dist < nearestDist) { nearest = from; nearestDist = dist; }
+    }
+    if (!nearest) return null;
+
+    if (before.length == 1)
+      nearest.ch += before[0].length;
+    else
+      nearest = Pos(nearest.line + (before.length - 1), before[before.length - 1].length);
+    if (data.start.line == data.end.line)
+      var end = Pos(nearest.line, nearest.ch + (data.end.ch - data.start.ch));
+    else
+      var end = Pos(nearest.line + (data.end.line - data.start.line), data.end.ch);
+    return {start: nearest, end: end};
+  }
+
+  function atInterestingExpression(cm) {
+    var pos = cm.getCursor("end"), tok = cm.getTokenAt(pos);
+    if (tok.start < pos.ch && (tok.type == "comment" || tok.type == "string")) return false;
+    return /\w/.test(cm.getLine(pos.line).slice(Math.max(pos.ch - 1, 0), pos.ch + 1));
+  }
+
+  // Variable renaming
+
+  function rename(ts, cm) {
+    var token = cm.getTokenAt(cm.getCursor());
+    if (!/\w/.test(token.string)) showError(ts, cm, "Not at a variable");
+    dialog(cm, "New name for " + token.string, function(newName) {
+      ts.request(cm, {type: "rename", newName: newName, fullDocs: true}, function(error, data) {
+        if (error) return showError(ts, cm, error);
+        applyChanges(ts, data.changes);
+      });
+    });
+  }
+
+  var nextChangeOrig = 0;
+  function applyChanges(ts, changes) {
+    var perFile = Object.create(null);
+    for (var i = 0; i < changes.length; ++i) {
+      var ch = changes[i];
+      (perFile[ch.file] || (perFile[ch.file] = [])).push(ch);
+    }
+    for (var file in perFile) {
+      var known = ts.docs[file], chs = perFile[file];;
+      if (!known) continue;
+      chs.sort(function(a, b) { return cmpPos(b, a); });
+      var origin = "*rename" + (++nextChangeOrig);
+      for (var i = 0; i < chs.length; ++i) {
+        var ch = chs[i];
+        known.doc.replaceRange(ch.text, ch.start, ch.end, origin);
+      }
+    }
+  }
+
+  // Generic request-building helper
+
+  function buildRequest(ts, doc, query) {
+    var files = [], offsetLines = 0, allowFragments = !query.fullDocs;
+    if (!allowFragments) delete query.fullDocs;
+    if (typeof query == "string") query = {type: query};
+    query.lineCharPositions = true;
+    if (query.end == null) {
+      query.end = doc.doc.getCursor("end");
+      if (doc.doc.somethingSelected())
+        query.start = doc.doc.getCursor("start");
+    }
+    var startPos = query.start || query.end;
+
+    if (doc.changed) {
+      if (doc.doc.lineCount() > bigDoc && allowFragments !== false &&
+          doc.changed.to - doc.changed.from < 100 &&
+          doc.changed.from <= startPos.line && doc.changed.to > query.end.line) {
+        files.push(getFragmentAround(doc, startPos, query.end));
+        query.file = "#0";
+        var offsetLines = files[0].offsetLines;
+        if (query.start != null) query.start = Pos(query.start.line - -offsetLines, query.start.ch);
+        query.end = Pos(query.end.line - offsetLines, query.end.ch);
+      } else {
+        files.push({type: "full",
+                    name: doc.name,
+                    text: docValue(ts, doc)});
+        query.file = doc.name;
+        doc.changed = null;
+      }
+    } else {
+      query.file = doc.name;
+    }
+    for (var name in ts.docs) {
+      var cur = ts.docs[name];
+      if (cur.changed && cur != doc) {
+        files.push({type: "full", name: cur.name, text: docValue(ts, cur)});
+        cur.changed = null;
+      }
+    }
+
+    return {query: query, files: files};
+  }
+
+  function getFragmentAround(data, start, end) {
+    var doc = data.doc;
+    var minIndent = null, minLine = null, endLine, tabSize = 4;
+    for (var p = start.line - 1, min = Math.max(0, p - 50); p >= min; --p) {
+      var line = doc.getLine(p), fn = line.search(/\bfunction\b/);
+      if (fn < 0) continue;
+      var indent = CodeMirror.countColumn(line, null, tabSize);
+      if (minIndent != null && minIndent <= indent) continue;
+      minIndent = indent;
+      minLine = p;
+    }
+    if (minLine == null) minLine = min;
+    var max = Math.min(doc.lastLine(), end.line + 20);
+    if (minIndent == null || minIndent == CodeMirror.countColumn(doc.getLine(start.line), null, tabSize))
+      endLine = max;
+    else for (endLine = end.line + 1; endLine < max; ++endLine) {
+      var indent = CodeMirror.countColumn(doc.getLine(endLine), null, tabSize);
+      if (indent <= minIndent) break;
+    }
+    var from = Pos(minLine, 0);
+
+    return {type: "part",
+            name: data.name,
+            offsetLines: from.line,
+            text: doc.getRange(from, Pos(endLine, 0))};
+  }
+
+  // Generic utilities
+
+  function cmpPos(a, b) { return a.line - b.line || a.ch - b.ch; }
+
+  function elt(tagname, cls /*, ... elts*/) {
+    var e = document.createElement(tagname);
+    if (cls) e.className = cls;
+    for (var i = 2; i < arguments.length; ++i) {
+      var elt = arguments[i];
+      if (typeof elt == "string") elt = document.createTextNode(elt);
+      e.appendChild(elt);
+    }
+    return e;
+  }
+
+  function dialog(cm, text, f) {
+    if (cm.openDialog)
+      cm.openDialog(text + ": <input type=text>", f);
+    else
+      f(prompt(text, ""));
+  }
+
+  // Tooltips
+
+  function tempTooltip(cm, content) {
+    var where = cm.cursorCoords();
+    var tip = makeTooltip(where.right + 1, where.bottom, content);
+    function clear() {
+      if (!tip.parentNode) return;
+      cm.off("cursorActivity", clear);
+      fadeOut(tip);
+    }
+    setTimeout(clear, 1700);
+    cm.on("cursorActivity", clear);
+  }
+
+  function makeTooltip(x, y, content) {
+    var node = elt("div", cls + "tooltip", content);
+    node.style.left = x + "px";
+    node.style.top = y + "px";
+    document.body.appendChild(node);
+    return node;
+  }
+
+  function remove(node) {
+    var p = node && node.parentNode;
+    if (p) p.removeChild(node);
+  }
+
+  function fadeOut(tooltip) {
+    tooltip.style.opacity = "0";
+    setTimeout(function() { remove(tooltip); }, 1100);
+  }
+
+  function showError(ts, cm, msg) {
+    if (ts.options.showError)
+      ts.options.showError(cm, msg);
+    else
+      tempTooltip(cm, String(msg));
+  }
+
+  function closeArgHints(ts) {
+    if (ts.activeArgHints) { remove(ts.activeArgHints); ts.activeArgHints = null; }
+  }
+
+  function docValue(ts, doc) {
+    var val = doc.doc.getValue();
+    if (ts.options.fileFilter) val = ts.options.fileFilter(val, doc.name, doc.doc);
+    return val;
+  }
+
+  // Worker wrapper
+
+  function WorkerServer(ts) {
+    var worker = new Worker(ts.options.workerScript);
+    worker.postMessage({type: "init",
+                        defs: ts.options.defs,
+                        plugins: ts.options.plugins,
+                        scripts: ts.options.workerDeps});
+    var msgId = 0, pending = {};
+
+    function send(data, c) {
+      if (c) {
+        data.id = ++msgId;
+        pending[msgId] = c;
+      }
+      worker.postMessage(data);
+    }
+    worker.onmessage = function(e) {
+      var data = e.data;
+      if (data.type == "getFile") {
+        getFile(ts, name, function(err, text) {
+          send({type: "getFile", err: String(err), text: text, id: data.id});
+        });
+      } else if (data.type == "debug") {
+        console.log(data.message);
+      } else if (data.id && pending[data.id]) {
+        pending[data.id](data.err, data.body);
+        delete pending[data.id];
+      }
+    };
+    worker.onerror = function(e) {
+      for (var id in pending) pending[id](e);
+      pending = {};
+    };
+
+    this.addFile = function(name, text) { send({type: "add", name: name, text: text}); };
+    this.delFile = function(name) { send({type: "del", name: name}); };
+    this.request = function(body, c) { send({type: "req", body: body}, c); };
+  }
+})();
diff --git a/third-party/codemirror-3.15/addon/tern/worker.js b/third-party/codemirror-3.15/addon/tern/worker.js
new file mode 100644 (file)
index 0000000..0164762
--- /dev/null
@@ -0,0 +1,39 @@
+var server;
+
+this.onmessage = function(e) {
+  var data = e.data;
+  switch (data.type) {
+  case "init": return startServer(data.defs, data.plugins, data.scripts);
+  case "add": return server.addFile(data.name, data.text);
+  case "del": return server.delFile(data.name);
+  case "req": return server.request(data.body, function(err, reqData) {
+    postMessage({id: data.id, body: reqData, err: err && String(err)});
+  });
+  case "getFile":
+    var c = pending[data.id];
+    delete pending[data.id];
+    return c(data.err, data.text);
+  default: throw new Error("Unknown message type: " + data.type);
+  }
+};
+
+var nextId = 0, pending = {};
+function getFile(file, c) {
+  postMessage({type: "getFile", name: file, id: ++nextId});
+  pending[nextId] = c;
+}
+
+function startServer(defs, plugins, scripts) {
+  if (scripts) importScripts.apply(null, scripts);
+
+  server = new tern.Server({
+    getFile: getFile,
+    async: true,
+    defs: defs,
+    plugins: plugins
+  });
+}
+
+var console = {
+  log: function(v) { postMessage({type: "debug", message: v}); }
+};
diff --git a/third-party/codemirror-3.15/bin/compress b/third-party/codemirror-3.15/bin/compress
new file mode 100755 (executable)
index 0000000..809fbe8
--- /dev/null
@@ -0,0 +1,92 @@
+#!/usr/bin/env node
+
+// Compression helper for CodeMirror
+//
+// Example:
+//
+//   bin/compress codemirror runmode javascript xml
+//
+// Will take lib/codemirror.js, addon/runmode/runmode.js,
+// mode/javascript/javascript.js, and mode/xml/xml.js, run them though
+// the online minifier at http://marijnhaverbeke.nl/uglifyjs, and spit
+// out the result.
+//
+//   bin/compress codemirror --local /path/to/bin/UglifyJS
+//
+// Will use a local minifier instead of the online default one.
+//
+// Script files are specified without .js ending. Prefixing them with
+// their full (local) path is optional. So you may say lib/codemirror
+// or mode/xml/xml to be more precise. In fact, even the .js suffix
+// may be speficied, if wanted.
+
+"use strict";
+
+var fs = require("fs");
+
+function help(ok) {
+  console.log("usage: " + process.argv[1] + " [--local /path/to/uglifyjs] files...");
+  process.exit(ok ? 0 : 1);
+}
+
+var local = null, args = [], extraArgs = null, files = [], blob = "";
+
+for (var i = 2; i < process.argv.length; ++i) {
+  var arg = process.argv[i];
+  if (arg == "--local" && i + 1 < process.argv.length) {
+    var parts = process.argv[++i].split(/\s+/);
+    local = parts[0];
+    extraArgs = parts.slice(1);
+    if (!extraArgs.length) extraArgs = ["-c", "-m"];
+  } else if (arg == "--help") {
+    help(true);
+  } else if (arg[0] != "-") {
+    files.push({name: arg, re: new RegExp("(?:\\/|^)" + arg + (/\.js$/.test(arg) ? "$" : "\\.js$"))});
+  } else help(false);
+}
+
+function walk(dir) {
+  fs.readdirSync(dir).forEach(function(fname) {
+    if (/^[_\.]/.test(fname)) return;
+    var file = dir + fname;
+    if (fs.statSync(file).isDirectory()) return walk(file + "/");
+    if (files.some(function(spec, i) {
+      var match = spec.re.test(file);
+      if (match) files.splice(i, 1);
+      return match;
+    })) {
+      if (local) args.push(file);
+      else blob += fs.readFileSync(file, "utf8");
+    }
+  });
+}
+
+walk("lib/");
+walk("addon/");
+walk("mode/");
+
+if (!local && !blob) help(false);
+
+if (files.length) {
+  console.log("Some speficied files were not found: " +
+              files.map(function(a){return a.name;}).join(", "));
+  process.exit(1);
+}
+  
+if (local) {
+  require("child_process").spawn(local, args.concat(extraArgs), {stdio: ["ignore", process.stdout, process.stderr]});
+} else {
+  var data = new Buffer("js_code=" + require("querystring").escape(blob), "utf8");
+  var req = require("http").request({
+    host: "marijnhaverbeke.nl",
+    port: 80,
+    method: "POST",
+    path: "/uglifyjs",
+    headers: {"content-type": "application/x-www-form-urlencoded",
+              "content-length": data.length}
+  });
+  req.on("response", function(resp) {
+    resp.on("data", function (chunk) { process.stdout.write(chunk); });
+  });
+  req.end(data);
+}
diff --git a/third-party/codemirror-3.15/bin/lint b/third-party/codemirror-3.15/bin/lint
new file mode 100755 (executable)
index 0000000..bbb85b6
--- /dev/null
@@ -0,0 +1,15 @@
+#!/usr/bin/env node
+
+var lint = require("../test/lint/lint");
+
+if (process.argv.length > 2) {
+  lint.checkDir(process.argv[2]);
+} else {
+  process.chdir(__dirname.slice(0, __dirname.lastIndexOf("/")));
+  lint.checkDir("lib");
+  lint.checkDir("mode");
+  lint.checkDir("addon");
+  lint.checkDir("keymap");
+}
+
+process.exit(lint.success() ? 0 : 1);
diff --git a/third-party/codemirror-3.15/bin/source-highlight b/third-party/codemirror-3.15/bin/source-highlight
new file mode 100755 (executable)
index 0000000..7596ed7
--- /dev/null
@@ -0,0 +1,61 @@
+#!/usr/bin/env node
+
+// Simple command-line code highlighting tool. Reads code from stdin,
+// spits html to stdout. For example:
+//
+//   echo 'function foo(a) { return a; }' | bin/source-highlight -s javascript
+//   bin/source-highlight -s 
+
+var fs = require("fs");
+
+CodeMirror = require("../addon/runmode/runmode.node.js");
+require("../mode/meta.js");
+
+var sPos = process.argv.indexOf("-s");
+if (sPos == -1 || sPos == process.argv.length - 1) {
+   console.error("Usage: source-highlight -s language");
+   process.exit(1);
+}
+var lang = process.argv[sPos + 1].toLowerCase(), modeName = lang;
+CodeMirror.modeInfo.forEach(function(info) {
+  if (info.mime == lang) {
+    modeName = info.mode;
+  } else if (info.name.toLowerCase() == lang) {
+    modeName = info.mode;
+    lang = info.mime;
+  }
+});
+
+function ensureMode(name) {
+  if (CodeMirror.modes[name] || name == "null") return;
+  try {
+    require("../mode/" + name + "/" + name + ".js");
+  } catch(e) {
+    console.error("Could not load mode " + name + ".");
+    process.exit(1);
+  }
+  var obj = CodeMirror.modes[name];
+  if (obj.dependencies) obj.dependencies.forEach(ensureMode);
+}
+ensureMode(modeName);
+
+function esc(str) {
+  return str.replace(/[<&]/, function(ch) { return ch == "&" ? "&amp;" : "&lt;"; });
+}
+
+var code = fs.readFileSync("/dev/stdin", "utf8");
+var curStyle = null, accum = "";
+function flush() {
+  if (curStyle) process.stdout.write("<span class=\"" + curStyle.replace(/(^|\s+)/g, "$1cm-") + "\">" + esc(accum) + "</span>");
+  else process.stdout.write(esc(accum));
+}
+
+CodeMirror.runMode(code, lang, function(text, style) {
+  if (style != curStyle) {
+    flush();
+    curStyle = style; accum = text;
+  } else {
+    accum += text;
+  }
+});
+flush();
diff --git a/third-party/codemirror-3.15/bower.json b/third-party/codemirror-3.15/bower.json
new file mode 100644 (file)
index 0000000..fae2426
--- /dev/null
@@ -0,0 +1,16 @@
+{
+  "name": "CodeMirror",
+  "version": "3.15.0",
+  "main": ["lib/codemirror.js", "lib/codemirror.css"],
+  "ignore": [
+    "**/.*",
+    "node_modules",
+    "components",
+    "bin",
+    "demo",
+    "doc",
+    "test",
+    "index.html",
+    "package.json"
+  ]
+}
diff --git a/third-party/codemirror-3.15/demo/activeline.html b/third-party/codemirror-3.15/demo/activeline.html
new file mode 100644 (file)
index 0000000..b0ea9b9
--- /dev/null
@@ -0,0 +1,70 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Active Line Demo</title>
+    <link rel="stylesheet" href="../lib/codemirror.css">
+    <script src="../lib/codemirror.js"></script>
+    <script src="../mode/xml/xml.js"></script>
+    <script src="../addon/selection/active-line.js"></script>
+    <link rel="stylesheet" href="../doc/docs.css">
+
+    <style type="text/css">
+      .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}
+      .CodeMirror-activeline-background {background: #e8f2ff !important;}
+    </style>
+  </head>
+  <body>
+    <h1>CodeMirror: Active Line Demo</h1>
+
+    <form><textarea id="code" name="code">
+<?xml version="1.0" encoding="UTF-8"?>
+<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"
+     xmlns:georss="http://www.georss.org/georss"
+     xmlns:twitter="http://api.twitter.com">
+  <channel>
+    <title>Twitter / codemirror</title>
+    <link>http://twitter.com/codemirror</link>
+    <atom:link type="application/rss+xml"
+               href="http://twitter.com/statuses/user_timeline/242283288.rss" rel="self"/>
+    <description>Twitter updates from CodeMirror / codemirror.</description>
+    <language>en-us</language>
+    <ttl>40</ttl>
+  <item>
+    <title>codemirror: http://cloud-ide.com &#8212; they're springing up like mushrooms. This one
+      uses CodeMirror as its editor.</title>
+    <description>codemirror: http://cloud-ide.com &#8212; they're springing up like mushrooms. This
+      one uses CodeMirror as its editor.</description>
+    <pubDate>Thu, 17 Mar 2011 23:34:47 +0000</pubDate>
+    <guid>http://twitter.com/codemirror/statuses/48527733722058752</guid>
+    <link>http://twitter.com/codemirror/statuses/48527733722058752</link>
+    <twitter:source>web</twitter:source>
+    <twitter:place/>
+  </item>
+  <item>
+    <title>codemirror: Posted a description of the CodeMirror 2 internals at
+      http://codemirror.net/2/internals.html</title>
+    <description>codemirror: Posted a description of the CodeMirror 2 internals at
+      http://codemirror.net/2/internals.html</description>
+    <pubDate>Wed, 02 Mar 2011 12:15:09 +0000</pubDate>
+    <guid>http://twitter.com/codemirror/statuses/42920879788789760</guid>
+    <link>http://twitter.com/codemirror/statuses/42920879788789760</link>
+    <twitter:source>web</twitter:source>
+    <twitter:place/>
+  </item>
+  </channel>
+</rss></textarea></form>
+
+    <script>
+var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+  mode: "application/xml",
+  styleActiveLine: true,
+  lineNumbers: true,
+  lineWrapping: true
+});
+</script>
+
+    <p>Styling the current cursor line.</p>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/demo/anywordhint.html b/third-party/codemirror-3.15/demo/anywordhint.html
new file mode 100644 (file)
index 0000000..5bb0a62
--- /dev/null
@@ -0,0 +1,69 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Any Word Completion Demo</title>
+    <link rel="stylesheet" href="../lib/codemirror.css">
+    <script src="../lib/codemirror.js"></script>
+    <script src="../addon/hint/show-hint.js"></script>
+    <link rel="stylesheet" href="../addon/hint/show-hint.css">
+    <script src="../addon/hint/anyword-hint.js"></script>
+    <script src="../mode/javascript/javascript.js"></script>
+    <link rel="stylesheet" href="../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Any Word Completion Demo</h1>
+
+    <form><textarea id="code" name="code">
+(function() {
+  "use strict";
+
+  var WORD = /[\w$]+/g, RANGE = 500;
+
+  CodeMirror.registerHelper("hint", "anyword", function(editor, options) {
+    var word = options && options.word || WORD;
+    var range = options && options.range || RANGE;
+    var cur = editor.getCursor(), curLine = editor.getLine(cur.line);
+    var start = cur.ch, end = start;
+    while (end < curLine.length && word.test(curLine.charAt(end))) ++end;
+    while (start && word.test(curLine.charAt(start - 1))) --start;
+    var curWord = start != end && curLine.slice(start, end);
+
+    var list = [], seen = {};
+    function scan(dir) {
+      var line = cur.line, end = Math.min(Math.max(line + dir * range, editor.firstLine()), editor.lastLine()) + dir;
+      for (; line != end; line += dir) {
+        var text = editor.getLine(line), m;
+        word.lastIndex = 0;
+        while (m = word.exec(text)) {
+          if ((!curWord || m[0].indexOf(curWord) == 0) && !seen.hasOwnProperty(m[0])) {
+            seen[m[0]] = true;
+            list.push(m[0]);
+          }
+        }
+      }
+    }
+    scan(-1);
+    scan(1);
+    return {list: list, from: CodeMirror.Pos(cur.line, start), to: CodeMirror.Pos(cur.line, end)};
+  });
+})();
+</textarea></form>
+
+<p>Press <strong>ctrl-space</strong> to activate autocompletion. The
+completion uses
+the <a href="../doc/manual.html#addon_anyword-hint">anyword-hint.js</a>
+module, which simply looks at nearby words in the buffer and completes
+to those.</p>
+
+    <script>
+      CodeMirror.commands.autocomplete = function(cm) {
+        CodeMirror.showHint(cm, CodeMirror.hint.anyword);
+      }
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        extraKeys: {"Ctrl-Space": "autocomplete"}
+      });
+    </script>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/demo/bidi.html b/third-party/codemirror-3.15/demo/bidi.html
new file mode 100644 (file)
index 0000000..47feb8c
--- /dev/null
@@ -0,0 +1,61 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Bi-directional Text Demo</title>
+    <link rel="stylesheet" href="../lib/codemirror.css">
+    <script src="../lib/codemirror.js"></script>
+    <script src="../mode/xml/xml.js"></script>
+    <link rel="stylesheet" href="../doc/docs.css">
+
+    <style type="text/css">
+      .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}
+    </style>
+  </head>
+  <body>
+    <h1>CodeMirror: Bi-directional Text Demo</h1>
+
+    <form><textarea id="code" name="code"><!-- Piece of the CodeMirror manual, 'translated' into Arabic by
+     Google Translate -->
+
+<dl>
+  <dt id=option_value><code>value (string or Doc)</code></dt>
+  <dd>قيمة البداية المحرر. يمكن أن تكون سلسلة، أو. كائن مستند.</dd>
+  <dt id=option_mode><code>mode (string or object)</code></dt>
+  <dd>وضع الاستخدام. عندما لا تعطى، وهذا الافتراضي إلى الطريقة الاولى
+  التي تم تحميلها. قد يكون من سلسلة، والتي إما أسماء أو ببساطة هو وضع
+  MIME نوع المرتبطة اسطة. بدلا من ذلك، قد يكون من كائن يحتوي على
+  خيارات التكوين لواسطة، مع <code>name</code> الخاصية التي وضع أسماء
+  (على سبيل المثال <code>{name: "javascript", json: true}</code>).
+  صفحات التجريبي لكل وضع تحتوي على معلومات حول ما معلمات تكوين وضع
+  يدعمها. يمكنك أن تطلب CodeMirror التي تم تعريفها طرق وأنواع MIME
+  الكشف على <code>CodeMirror.modes</code>
+  و <code>CodeMirror.mimeModes</code> الكائنات. وضع خرائط الأسماء
+  الأولى لمنشئات الخاصة بهم، وخرائط لأنواع MIME 2 المواصفات
+  واسطة.</dd>
+  <dt id=option_theme><code>theme (string)</code></dt>
+  <dd>موضوع لنمط المحرر مع. يجب عليك التأكد من الملف CSS تحديد
+  المقابلة <code>.cm-s-[name]</code> يتم تحميل أنماط (انظر
+  <a href=../theme/><code>theme</code></a> الدليل في التوزيع).
+  الافتراضي هو <code>"default"</code> ، والتي تم تضمينها في
+  الألوان <code>codemirror.css</code>. فمن الممكن استخدام فئات متعددة
+  في تطبيق السمات مرة واحدة على سبيل المثال <code>"foo bar"</code>
+  سيتم تعيين كل من <code>cm-s-foo</code> و <code>cm-s-bar</code>
+  الطبقات إلى المحرر.</dd>
+</dl>
+</textarea></form>
+
+    <script>
+var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+  mode: "text/html",
+  lineNumbers: true,
+  lineWrapping: true
+});
+</script>
+
+  <p>Demonstration of bi-directional text support. See
+  the <a href="http://marijnhaverbeke.nl/blog/cursor-in-bidi-text.html">related
+  blog post</a> for more background.</p>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/demo/btree.html b/third-party/codemirror-3.15/demo/btree.html
new file mode 100644 (file)
index 0000000..5e5ce0a
--- /dev/null
@@ -0,0 +1,87 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: B-Tree visualization</title>
+    <link rel="stylesheet" href="../lib/codemirror.css">
+    <script src="../lib/codemirror.js"></script>
+    <link rel="stylesheet" href="../doc/docs.css">
+
+    <style type="text/css">
+      .lineblock { display: inline-block; margin: 1px; height: 5px; }
+      .CodeMirror {border: 1px solid #aaa; height: 400px}
+    </style>
+  </head>
+  <body>
+    <h1>CodeMirror: B-Tree visualization</h1>
+
+    <p>Shows a visual representation of the b-tree that CodeMirror
+    uses to store its document. See
+    the <a href="http://marijnhaverbeke.nl/blog/codemirror-line-tree.html">corresponding
+    blog post</a> for a description of this format. The gray blocks
+    under each leaf show the lines it holds (with their width
+    representing the line height). Add and remove content to see how
+    the nodes are split and merged to keep the tree balanced.</p>
+
+    <div style="position: relative">
+      <div style="width: 60%; display: inline-block; vertical-align: top">
+        <form><textarea id="code" name="code">type here, see a summary of the document b-tree to the right</textarea></form>
+      </div>
+      <div style="display: inline-block; height: 402px; overflow-y: auto" id="output"></div>
+    </div>
+
+    <script id="me">
+var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+  lineNumbers: true,
+  lineWrapping: true
+});
+var updateTimeout;
+editor.on("change", function(cm) {
+  clearTimeout(updateTimeout);
+  updateTimeout = setTimeout(updateVisual, 200);
+});
+updateVisual();
+
+function updateVisual() {
+  var out = document.getElementById("output");
+  out.innerHTML = "";
+
+  function drawTree(out, node) {
+    if (node.lines) {
+      out.appendChild(document.createElement("div")).innerHTML =
+        "<b>leaf</b>: " + node.lines.length + " lines, " + Math.round(node.height) + " px";
+      var lines = out.appendChild(document.createElement("div"));
+      lines.style.lineHeight = "6px"; lines.style.marginLeft = "10px";
+      for (var i = 0; i < node.lines.length; ++i) {
+        var line = node.lines[i], lineElt = lines.appendChild(document.createElement("div"));
+        lineElt.className = "lineblock";
+        var gray = Math.min(line.text.length * 3, 230), col = gray.toString(16);
+        if (col.length == 1) col = "0" + col;
+        lineElt.style.background = "#" + col + col + col;
+                          console.log(line.height, line);
+        lineElt.style.width = Math.max(Math.round(line.height / 3), 1) + "px";
+      }
+    } else {
+      out.appendChild(document.createElement("div")).innerHTML =
+        "<b>node</b>: " + node.size + " lines, " + Math.round(node.height) + " px";
+      var sub = out.appendChild(document.createElement("div"));
+      sub.style.paddingLeft = "20px";
+      for (var i = 0; i < node.children.length; ++i)
+        drawTree(sub, node.children[i]);
+    }
+  }
+  drawTree(out, editor.getDoc());
+}
+
+function fillEditor() {
+  var sc = document.getElementById("me");
+  var doc = (sc.textContent || sc.innerText || sc.innerHTML).replace(/^\s*/, "") + "\n";
+  doc += doc; doc += doc; doc += doc; doc += doc; doc += doc; doc += doc;
+  editor.setValue(doc);
+}
+    </script>
+
+<p><button onclick="fillEditor()">Add a lot of content</button></p>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/demo/buffers.html b/third-party/codemirror-3.15/demo/buffers.html
new file mode 100644 (file)
index 0000000..bfd8248
--- /dev/null
@@ -0,0 +1,98 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Multiple Buffer & Split View Demo</title>
+    <link rel="stylesheet" href="../lib/codemirror.css">
+    <script src="../lib/codemirror.js"></script>
+    <script src="../mode/javascript/javascript.js"></script>
+    <script src="../mode/css/css.js"></script>
+    <link rel="stylesheet" href="../doc/docs.css">
+
+    <style type="text/css" id=style>
+      .CodeMirror {border: 1px solid black; height: 250px;}
+    </style>
+  </head>
+  <body>
+    <h1>CodeMirror: Multiple Buffer & Split View Demo</h1>
+
+    <div id=code_top></div>
+    <div>
+      Select buffer: <select id=buffers_top></select>
+      &nbsp; &nbsp; <button onclick="newBuf('top')">New buffer</button>
+    </div>
+    <div id=code_bot></div>
+    <div>
+      Select buffer: <select id=buffers_bot></select>
+      &nbsp; &nbsp; <button onclick="newBuf('bot')">New buffer</button>
+    </div>
+
+    <script id=script>
+var sel_top = document.getElementById("buffers_top");
+CodeMirror.on(sel_top, "change", function() {
+  selectBuffer(ed_top, sel_top.options[sel_top.selectedIndex].value);
+});
+
+var sel_bot = document.getElementById("buffers_bot");
+CodeMirror.on(sel_bot, "change", function() {
+  selectBuffer(ed_bot, sel_bot.options[sel_bot.selectedIndex].value);
+});
+
+var buffers = {};
+
+function openBuffer(name, text, mode) {
+  buffers[name] = CodeMirror.Doc(text, mode);
+  var opt = document.createElement("option");
+  opt.appendChild(document.createTextNode(name));
+  sel_top.appendChild(opt);
+  sel_bot.appendChild(opt.cloneNode(true));
+}
+
+function newBuf(where) {
+  var name = prompt("Name for the buffer", "*scratch*");
+  if (name == null) return;
+  if (buffers.hasOwnProperty(name)) {
+    alert("There's already a buffer by that name.");
+    return;
+  }
+  openBuffer(name, "", "javascript");
+  selectBuffer(where == "top" ? ed_top : ed_bot, name);
+  var sel = where == "top" ? sel_top : sel_bot;
+  sel.value = name;
+}
+
+function selectBuffer(editor, name) {
+  var buf = buffers[name];
+  if (buf.getEditor()) buf = buf.linkedDoc({sharedHist: true});
+  var old = editor.swapDoc(buf);
+  var linked = old.iterLinkedDocs(function(doc) {linked = doc;});
+  if (linked) {
+    // Make sure the document in buffers is the one the other view is looking at
+    for (var name in buffers) if (buffers[name] == old) buffers[name] = linked;
+    old.unlinkDoc(linked);
+  }
+  editor.focus();
+}
+
+function nodeContent(id) {
+  var node = document.getElementById(id), val = node.textContent || node.innerText;
+  val = val.slice(val.match(/^\s*/)[0].length, val.length - val.match(/\s*$/)[0].length) + "\n";
+  return val;
+}
+openBuffer("js", nodeContent("script"), "javascript");
+openBuffer("css", nodeContent("style"), "css");
+
+var ed_top = CodeMirror(document.getElementById("code_top"), {lineNumbers: true});
+selectBuffer(ed_top, "js");
+var ed_bot = CodeMirror(document.getElementById("code_bot"), {lineNumbers: true});
+selectBuffer(ed_bot, "js");
+</script>
+
+    <p>Demonstration of
+    using <a href="../doc/manual.html#linkedDoc">linked documents</a>
+    to provide a split view on a document, and
+    using <a href="../doc/manual.html#swapDoc"><code>swapDoc</code></a>
+    to use a single editor to display multiple documents.</p>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/demo/changemode.html b/third-party/codemirror-3.15/demo/changemode.html
new file mode 100644 (file)
index 0000000..364c5cd
--- /dev/null
@@ -0,0 +1,50 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Mode-Changing Demo</title>
+    <link rel="stylesheet" href="../lib/codemirror.css">
+    <script src="../lib/codemirror.js"></script>
+    <script src="../mode/javascript/javascript.js"></script>
+    <script src="../mode/scheme/scheme.js"></script>
+    <link rel="stylesheet" href="../doc/docs.css">
+
+    <style type="text/css">
+      .CodeMirror {border: 1px solid black;}
+    </style>
+  </head>
+  <body>
+    <h1>CodeMirror: Mode-Changing demo</h1>
+
+    <form><textarea id="code" name="code">
+;; If there is Scheme code in here, the editor will be in Scheme mode.
+;; If you put in JS instead, it'll switch to JS mode.
+
+(define (double x)
+  (* x x))
+</textarea></form>
+
+<p>On changes to the content of the above editor, a (crude) script
+tries to auto-detect the language used, and switches the editor to
+either JavaScript or Scheme mode based on that.</p>
+
+<script>
+  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+    mode: "scheme",
+    lineNumbers: true,
+    tabMode: "indent"
+  });
+  editor.on("change", function() {
+    clearTimeout(pending);
+    setTimeout(update, 400);
+  });
+  var pending;
+  function looksLikeScheme(code) {
+    return !/^\s*\(\s*function\b/.test(code) && /^\s*[;\(]/.test(code);
+  }
+  function update() {
+    editor.setOption("mode", looksLikeScheme(editor.getValue()) ? "scheme" : "javascript");
+  }
+</script>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/demo/closebrackets.html b/third-party/codemirror-3.15/demo/closebrackets.html
new file mode 100644 (file)
index 0000000..47304ea
--- /dev/null
@@ -0,0 +1,63 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Closebrackets Demo</title>
+    <link rel="stylesheet" href="../lib/codemirror.css">
+    <script src="../lib/codemirror.js"></script>
+    <script src="../addon/edit/closebrackets.js"></script>
+    <script src="../mode/javascript/javascript.js"></script>
+    <link rel="stylesheet" href="../doc/docs.css">
+    <style type="text/css">
+      .CodeMirror {border-top: 1px solid #888; border-bottom: 1px solid #888;}
+    </style>
+  </head>
+  <body>
+
+    <h1>CodeMirror: Closebrackets Demo</h1>
+
+    <p>Type a bracket like '[', '(', '{', '&quot;', or '''
+    and <a href="../doc/manual.html#addon_closebrackets">the addon</a>
+    will auto-close it. Type the closing variant when directly in
+    front of a matching character and it will overwrite it.</p>
+
+    <p>If you backspace over a starting bracket while inside empty brackets
+    (e.g. <code>{|}</code>), it will delete the closing bracket for you.</p>
+
+
+    <form><textarea id="code" name="code">(function() {
+  var DEFAULT_BRACKETS = "()[]{}''\"\"";
+
+  CodeMirror.defineOption("autoCloseBrackets", false, function(cm, val, old) {
+    var wasOn = old && old != CodeMirror.Init;
+    if (val && !wasOn)
+      cm.addKeyMap(buildKeymap(typeof val == "string" ? val : DEFAULT_BRACKETS));
+    else if (!val && wasOn)
+      cm.removeKeyMap("autoCloseBrackets");
+  });
+
+  function buildKeymap(pairs) {
+    var map = {name : "autoCloseBrackets"};
+    for (var i = 0; i < pairs.length; i += 2) (function(left, right) {
+      function maybeOverwrite(cm) {
+        var cur = cm.getCursor(), ahead = cm.getRange(cur, CodeMirror.Pos(cur.line, cur.ch + 1));
+        if (ahead != right) return CodeMirror.Pass;
+        else cm.execCommand("goCharRight");
+      }
+      map["'" + left + "'"] = function(cm) {
+        if (left == right && maybeOverwrite(cm) != CodeMirror.Pass) return;
+        var cur = cm.getCursor(), ahead = CodeMirror.Pos(cur.line, cur.ch + 1);
+        cm.replaceSelection(left + right, {head: ahead, anchor: ahead});
+      };
+      if (left != right) map["'" + right + "'"] = maybeOverwrite;
+    })(pairs.charAt(i), pairs.charAt(i + 1));
+    return map;
+  }
+})();
+</textarea></form>
+
+    <script type="text/javascript">
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {autoCloseBrackets: true});
+    </script>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/demo/closetag.html b/third-party/codemirror-3.15/demo/closetag.html
new file mode 100644 (file)
index 0000000..87f4f01
--- /dev/null
@@ -0,0 +1,37 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Close-Tag Demo</title>
+    <link rel="stylesheet" href="../lib/codemirror.css">
+    <script src="../lib/codemirror.js"></script>
+    <script src="../addon/edit/closetag.js"></script>
+    <script src="../mode/xml/xml.js"></script>
+    <script src="../mode/javascript/javascript.js"></script>
+    <script src="../mode/css/css.js"></script>
+    <script src="../mode/htmlmixed/htmlmixed.js"></script>
+    <link rel="stylesheet" href="../doc/docs.css">
+    <style type="text/css">
+      .CodeMirror {border-top: 1px solid #888; border-bottom: 1px solid #888;}
+    </style>
+  </head>
+  <body>
+    
+    <h1>Close-Tag Demo</h1>
+    <ul>
+      <li>Type an html tag.  When you type '>' or '/', the tag will auto-close/complete.  Block-level tags will indent.</li>
+      <li>There are options for disabling tag closing or customizing the list of tags to indent.</li>
+      <li>Works with "text/html" (based on htmlmixed.js or xml.js) mode.</li>
+      <li>View source for key binding details.</li>
+    </ul>
+
+    <form><textarea id="code" name="code"><html</textarea></form>
+
+    <script type="text/javascript">
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        mode: 'text/html',
+        autoCloseTags: true
+      });
+    </script>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/demo/complete.html b/third-party/codemirror-3.15/demo/complete.html
new file mode 100644 (file)
index 0000000..1a65f6e
--- /dev/null
@@ -0,0 +1,70 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Autocomplete Demo</title>
+    <link rel="stylesheet" href="../lib/codemirror.css">
+    <script src="../lib/codemirror.js"></script>
+    <script src="../addon/hint/show-hint.js"></script>
+    <link rel="stylesheet" href="../addon/hint/show-hint.css">
+    <script src="../addon/hint/javascript-hint.js"></script>
+    <script src="../mode/javascript/javascript.js"></script>
+    <link rel="stylesheet" href="../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Autocomplete demo</h1>
+
+    <form><textarea id="code" name="code">
+function getCompletions(token, context) {
+  var found = [], start = token.string;
+  function maybeAdd(str) {
+    if (str.indexOf(start) == 0) found.push(str);
+  }
+  function gatherCompletions(obj) {
+    if (typeof obj == "string") forEach(stringProps, maybeAdd);
+    else if (obj instanceof Array) forEach(arrayProps, maybeAdd);
+    else if (obj instanceof Function) forEach(funcProps, maybeAdd);
+    for (var name in obj) maybeAdd(name);
+  }
+
+  if (context) {
+    // If this is a property, see if it belongs to some object we can
+    // find in the current environment.
+    var obj = context.pop(), base;
+    if (obj.className == "js-variable")
+      base = window[obj.string];
+    else if (obj.className == "js-string")
+      base = "";
+    else if (obj.className == "js-atom")
+      base = 1;
+    while (base != null && context.length)
+      base = base[context.pop().string];
+    if (base != null) gatherCompletions(base);
+  }
+  else {
+    // If not, just look in the window object and any local scope
+    // (reading into JS mode internals to get at the local variables)
+    for (var v = token.state.localVars; v; v = v.next) maybeAdd(v.name);
+    gatherCompletions(window);
+    forEach(keywords, maybeAdd);
+  }
+  return found;
+}
+</textarea></form>
+
+<p>Press <strong>ctrl-space</strong> to activate autocompletion. See
+the code (<a href="../addon/hint/show-hint.js">here</a>
+and <a href="../addon/hint/javascript-hint.js">here</a>) to figure out
+how it works.</p>
+
+    <script>
+      CodeMirror.commands.autocomplete = function(cm) {
+        CodeMirror.showHint(cm, CodeMirror.hint.javascript);
+      }
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        extraKeys: {"Ctrl-Space": "autocomplete"}
+      });
+    </script>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/demo/emacs.html b/third-party/codemirror-3.15/demo/emacs.html
new file mode 100644 (file)
index 0000000..0a8cfc5
--- /dev/null
@@ -0,0 +1,66 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Emacs bindings demo</title>
+    <link rel="stylesheet" href="../lib/codemirror.css">
+    <script src="../lib/codemirror.js"></script>
+    <script src="../mode/clike/clike.js"></script>
+    <script src="../keymap/emacs.js"></script>
+    <script src="../addon/edit/matchbrackets.js"></script>
+    <script src="../addon/comment/comment.js"></script>
+    <script src="../addon/dialog/dialog.js"></script>
+    <script src="../addon/search/searchcursor.js"></script>
+    <script src="../addon/search/search.js"></script>
+    <link rel="stylesheet" href="../addon/dialog/dialog.css">
+    <link rel="stylesheet" href="../doc/docs.css">
+
+    <style type="text/css">
+      .CodeMirror {border-top: 1px solid #eee; border-bottom: 1px solid #eee;}
+    </style>
+  </head>
+  <body>
+    <h1>CodeMirror: Emacs bindings demo</h1>
+
+    <form><textarea id="code" name="code">
+#include "syscalls.h"
+/* getchar:  simple buffered version */
+int getchar(void)
+{
+  static char buf[BUFSIZ];
+  static char *bufp = buf;
+  static int n = 0;
+  if (n == 0) {  /* buffer is empty */
+    n = read(0, buf, sizeof buf);
+    bufp = buf;
+  }
+  return (--n >= 0) ? (unsigned char) *bufp++ : EOF;
+}
+</textarea></form>
+
+<p>The emacs keybindings are enabled by
+including <a href="../keymap/emacs.js">keymap/emacs.js</a> and setting
+the <code>keyMap</code> option to <code>"emacs"</code>. Because
+CodeMirror's internal API is quite different from Emacs, they are only
+a loose approximation of actual emacs bindings, though.</p>
+
+<p>Also note that a lot of browsers disallow certain keys from being
+captured. For example, Chrome blocks both Ctrl-W and Ctrl-N, with the
+result that idiomatic use of Emacs keys will constantly close your tab
+or open a new window.</p>
+
+    <script>
+      CodeMirror.commands.save = function() {
+        var elt = editor.getWrapperElement();
+        elt.style.background = "#def";
+        setTimeout(function() { elt.style.background = ""; }, 300);
+      };
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        mode: "text/x-csrc",
+        keyMap: "emacs"
+      });
+    </script>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/demo/folding.html b/third-party/codemirror-3.15/demo/folding.html
new file mode 100644 (file)
index 0000000..e6cecf2
--- /dev/null
@@ -0,0 +1,85 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Code Folding Demo</title>
+    <link rel="stylesheet" href="../lib/codemirror.css">
+    <script src="../lib/codemirror.js"></script>
+    <script src="../addon/fold/foldcode.js"></script>
+    <script src="../addon/fold/foldgutter.js"></script>
+    <script src="../addon/fold/brace-fold.js"></script>
+    <script src="../addon/fold/xml-fold.js"></script>
+    <script src="../mode/javascript/javascript.js"></script>
+    <script src="../mode/xml/xml.js"></script>
+    <link rel="stylesheet" href="../doc/docs.css">
+
+    <style type="text/css">
+      .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}
+      .CodeMirror-foldmarker {
+        color: blue;
+        text-shadow: #b9f 1px 1px 2px, #b9f -1px -1px 2px, #b9f 1px -1px 2px, #b9f -1px 1px 2px;
+        font-family: arial;
+        line-height: .3;
+        cursor: pointer;
+      }
+      .CodeMirror-foldgutter {
+        width: .7em;
+      }
+      .CodeMirror-foldgutter-open,
+      .CodeMirror-foldgutter-folded {
+        color: #555;
+        cursor: pointer;
+      }
+      .CodeMirror-foldgutter-open:after {
+        content: "\25BE";
+      }
+      .CodeMirror-foldgutter-folded:after {
+        content: "\25B8";
+      }
+    </style>
+  </head>
+  <body>
+    <h1>CodeMirror: Code Folding Demo</h1>
+
+    <p>Demonstration of code folding using the code
+    in <a href="../doc/manual.html#addon_foldcode"><code>foldcode.js</code></a>
+    and <a href="../doc/manual.html#addon_foldgutter"><code>foldgutter.js</code></a>.
+    Press ctrl-q or click on the gutter markers to fold a block, again
+    to unfold.</p>
+    <form>
+      <div style="max-width: 50em; margin-bottom: 1em">JavaScript:<br><textarea id="code" name="code"></textarea></div>
+      <div style="max-width: 50em">HTML:<br><textarea id="code-html" name="code-html"></textarea></div>
+    </form>
+    <script id="script">
+window.onload = function() {
+  var te = document.getElementById("code");
+  var sc = document.getElementById("script");
+  te.value = (sc.textContent || sc.innerText || sc.innerHTML).replace(/^\s*/, "");
+  sc.innerHTML = "";
+  var te_html = document.getElementById("code-html");
+  te_html.value = "<html>\n  " + document.documentElement.innerHTML + "\n</html>";
+
+  window.editor = CodeMirror.fromTextArea(te, {
+    mode: "javascript",
+    lineNumbers: true,
+    lineWrapping: true,
+    extraKeys: {"Ctrl-Q": function(cm){ cm.foldCode(cm.getCursor()); }},
+    foldGutter: true,
+    gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"]
+  });
+  editor.foldCode(CodeMirror.Pos(8, 0));
+
+  window.editor_html = CodeMirror.fromTextArea(te_html, {
+    mode: "text/html",
+    lineNumbers: true,
+    lineWrapping: true,
+    extraKeys: {"Ctrl-Q": function(cm){ cm.foldCode(cm.getCursor()); }},
+    foldGutter: true,
+    gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"]
+  });
+  editor_html.foldCode(CodeMirror.Pos(13, 0));
+  editor_html.foldCode(CodeMirror.Pos(1, 0));
+};
+</script>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/demo/fullscreen.html b/third-party/codemirror-3.15/demo/fullscreen.html
new file mode 100644 (file)
index 0000000..2709ebb
--- /dev/null
@@ -0,0 +1,147 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Full Screen Editing</title>
+    <link rel="stylesheet" href="../lib/codemirror.css">
+    <script src="../lib/codemirror.js"></script>
+    <link rel="stylesheet" href="../theme/night.css">
+    <script src="../mode/xml/xml.js"></script>
+    <link rel="stylesheet" href="../doc/docs.css">
+
+    <style type="text/css">
+      .CodeMirror-fullscreen {
+        display: block;
+        position: absolute;
+        top: 0; left: 0;
+        width: 100%;
+        z-index: 9999;
+      }
+    </style>
+  </head>
+  <body>
+    <h1>CodeMirror: Full Screen Editing</h1>
+
+    <form><textarea id="code" name="code" rows="5">
+  <dt id="option_indentWithTabs"><code>indentWithTabs (boolean)</code></dt>
+  <dd>Whether, when indenting, the first N*8 spaces should be
+  replaced by N tabs. Default is false.</dd>
+
+  <dt id="option_tabMode"><code>tabMode (string)</code></dt>
+  <dd>Determines what happens when the user presses the tab key.
+  Must be one of the following:
+    <dl>
+      <dt><code>"classic" (the default)</code></dt>
+      <dd>When nothing is selected, insert a tab. Otherwise,
+      behave like the <code>"shift"</code> mode. (When shift is
+      held, this behaves like the <code>"indent"</code> mode.)</dd>
+      <dt><code>"shift"</code></dt>
+      <dd>Indent all selected lines by
+      one <a href="#option_indentUnit"><code>indentUnit</code></a>.
+      If shift was held while pressing tab, un-indent all selected
+      lines one unit.</dd>
+      <dt><code>"indent"</code></dt>
+      <dd>Indent the line the 'correctly', based on its syntactic
+      context. Only works if the
+      mode <a href="#indent">supports</a> it.</dd>
+      <dt><code>"default"</code></dt>
+      <dd>Do not capture tab presses, let the browser apply its
+      default behaviour (which usually means it skips to the next
+      control).</dd>
+    </dl></dd>
+
+  <dt id="option_enterMode"><code>enterMode (string)</code></dt>
+  <dd>Determines whether and how new lines are indented when the
+  enter key is pressed. The following modes are supported:
+    <dl>
+      <dt><code>"indent" (the default)</code></dt>
+      <dd>Use the mode's indentation rules to give the new line
+      the correct indentation.</dd>
+      <dt><code>"keep"</code></dt>
+      <dd>Indent the line the same as the previous line.</dd>
+      <dt><code>"flat"</code></dt>
+      <dd>Do not indent the new line.</dd>
+    </dl></dd>
+
+  <dt id="option_enterMode"><code>enterMode (string)</code></dt>
+  <dd>Determines whether and how new lines are indented when the
+  enter key is pressed. The following modes are supported:
+    <dl>
+      <dt><code>"indent" (the default)</code></dt>
+      <dd>Use the mode's indentation rules to give the new line
+      the correct indentation.</dd>
+      <dt><code>"keep"</code></dt>
+      <dd>Indent the line the same as the previous line.</dd>
+      <dt><code>"flat"</code></dt>
+      <dd>Do not indent the new line.</dd>
+    </dl></dd>
+
+  <dt id="option_enterMode"><code>enterMode (string)</code></dt>
+  <dd>Determines whether and how new lines are indented when the
+  enter key is pressed. The following modes are supported:
+    <dl>
+      <dt><code>"indent" (the default)</code></dt>
+      <dd>Use the mode's indentation rules to give the new line
+      the correct indentation.</dd>
+      <dt><code>"keep"</code></dt>
+      <dd>Indent the line the same as the previous line.</dd>
+      <dt><code>"flat"</code></dt>
+      <dd>Do not indent the new line.</dd>
+    </dl></dd>
+
+  <dt id="option_enterMode"><code>enterMode (string)</code></dt>
+  <dd>Determines whether and how new lines are indented when the
+  enter key is pressed. The following modes are supported:
+    <dl>
+      <dt><code>"indent" (the default)</code></dt>
+      <dd>Use the mode's indentation rules to give the new line
+      the correct indentation.</dd>
+      <dt><code>"keep"</code></dt>
+      <dd>Indent the line the same as the previous line.</dd>
+      <dt><code>"flat"</code></dt>
+      <dd>Do not indent the new line.</dd>
+    </dl></dd>
+
+</textarea></form>
+  <script>
+    function isFullScreen(cm) {
+      return /\bCodeMirror-fullscreen\b/.test(cm.getWrapperElement().className);
+    }
+    function winHeight() {
+      return window.innerHeight || (document.documentElement || document.body).clientHeight;
+    }
+    function setFullScreen(cm, full) {
+      var wrap = cm.getWrapperElement();
+      if (full) {
+        wrap.className += " CodeMirror-fullscreen";
+        wrap.style.height = winHeight() + "px";
+        document.documentElement.style.overflow = "hidden";
+      } else {
+        wrap.className = wrap.className.replace(" CodeMirror-fullscreen", "");
+        wrap.style.height = "";
+        document.documentElement.style.overflow = "";
+      }
+      cm.refresh();
+    }
+    CodeMirror.on(window, "resize", function() {
+      var showing = document.body.getElementsByClassName("CodeMirror-fullscreen")[0];
+      if (!showing) return;
+      showing.CodeMirror.getWrapperElement().style.height = winHeight() + "px";
+    });
+    var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+      lineNumbers: true,
+      theme: "night",
+      extraKeys: {
+        "F11": function(cm) {
+          setFullScreen(cm, !isFullScreen(cm));
+        },
+        "Esc": function(cm) {
+          if (isFullScreen(cm)) setFullScreen(cm, false);
+        }
+      }
+    });
+  </script>
+
+    <p>Press <strong>F11</strong> when cursor is in the editor to toggle full screen editing. <strong>Esc</strong> can also be used to <i>exit</i> full screen editing.</p>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/demo/html5complete.html b/third-party/codemirror-3.15/demo/html5complete.html
new file mode 100644 (file)
index 0000000..9ea9182
--- /dev/null
@@ -0,0 +1,44 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: HTML completion demo</title>
+    <link rel="stylesheet" href="../lib/codemirror.css">
+    <script src="../lib/codemirror.js"></script>
+    <script src="../addon/hint/show-hint.js"></script>
+    <link rel="stylesheet" href="../addon/hint/show-hint.css">
+    <script src="../addon/hint/xml-hint.js"></script>
+    <script src="../addon/hint/html-hint.js"></script>
+    <script src="../mode/xml/xml.js"></script>
+    <script src="../mode/javascript/javascript.js"></script>
+    <script src="../mode/css/css.js"></script>
+    <script src="../mode/htmlmixed/htmlmixed.js"></script>
+        
+    <link rel="stylesheet" href="../doc/docs.css">
+    <style type="text/css">
+      .CodeMirror {border-top: 1px solid #888; border-bottom: 1px solid #888;}
+    </style>
+  </head>
+  <body>
+    
+    <h1>HTML completion demo</h1>
+    <p>Shows the <a href="xmlcomplete.html">XML completer</a>
+    parameterized with information about the tags in HTML.
+    Press <strong>ctrl-space</strong> to activate completion.</p>
+
+    <div id="code"></div>
+
+    <script type="text/javascript">
+      CodeMirror.commands.autocomplete = function(cm) {
+          CodeMirror.showHint(cm, CodeMirror.hint.html);
+      }
+      window.onload = function() {
+        editor = CodeMirror(document.getElementById("code"), {
+          mode: "text/html",
+          extraKeys: {"Ctrl-Space": "autocomplete"},
+          value: "<!doctype html>\n<html>\n  " + document.documentElement.innerHTML + "\n</html>"
+        });
+      };
+    </script>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/demo/indentwrap.html b/third-party/codemirror-3.15/demo/indentwrap.html
new file mode 100644 (file)
index 0000000..c367c94
--- /dev/null
@@ -0,0 +1,49 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Indented wrapped line demo</title>
+    <link rel="stylesheet" href="../lib/codemirror.css">
+    <script src="../lib/codemirror.js"></script>
+    <script src="../mode/xml/xml.js"></script>
+    <link rel="stylesheet" href="../doc/docs.css">
+
+    <style type="text/css">
+      .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}
+    </style>
+  </head>
+  <body>
+    <h1>CodeMirror: Indented wrapped line demo</h1>
+
+    <form><textarea id="code" name="code">
+<!doctype html>
+<body>
+  <h2 id="overview">Overview</h2>
+
+  <p>CodeMirror is a code-editor component that can be embedded in Web pages. The core library provides <em>only</em> the editor component, no accompanying buttons, auto-completion, or other IDE functionality. It does provide a rich API on top of which such functionality can be straightforwardly implemented. See the <a href="#addons">add-ons</a> included in the distribution, and the <a href="https://github.com/jagthedrummer/codemirror-ui">CodeMirror UI</a> project, for reusable implementations of extra features.</p>
+
+  <p>CodeMirror works with language-specific modes. Modes are JavaScript programs that help color (and optionally indent) text written in a given language. The distribution comes with a number of modes (see the <a href="../mode/"><code>mode/</code></a> directory), and it isn't hard to <a href="#modeapi">write new ones</a> for other languages.</p>
+</body>
+</textarea></form>
+
+    <p>This page uses a hack on top of the <code>"renderLine"</code>
+    event to make wrapped text line up with the base indentation of
+    the line.</p>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        lineWrapping: true,
+        mode: "text/html"
+      });
+      var charWidth = editor.defaultCharWidth(), basePadding = 4;
+      editor.on("renderLine", function(cm, line, elt) {
+        var off = CodeMirror.countColumn(line.text, null, cm.getOption("tabSize")) * charWidth;
+        elt.style.textIndent = "-" + off + "px";
+        elt.style.paddingLeft = (basePadding + off) + "px";
+      });
+      editor.refresh();
+    </script>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/demo/lint.html b/third-party/codemirror-3.15/demo/lint.html
new file mode 100644 (file)
index 0000000..d379c31
--- /dev/null
@@ -0,0 +1,90 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Linter Demo</title>
+    <link rel="stylesheet" href="../lib/codemirror.css">
+    <script src="../lib/codemirror.js"></script>
+    <script src="../mode/javascript/javascript.js"></script>
+    <script src="http://ajax.aspnetcdn.com/ajax/jshint/r07/jshint.js"></script>
+    <script src="https://rawgithub.com/zaach/jsonlint/79b553fb65c192add9066da64043458981b3972b/lib/jsonlint.js"></script>
+    <link rel="stylesheet" href="../doc/docs.css">
+    <link rel="stylesheet" href="../addon/lint/lint.css">
+    <script src="../addon/lint/lint.js"></script>
+    <script src="../addon/lint/javascript-lint.js"></script>
+    <script src="../addon/lint/json-lint.js"></script>
+
+    <style type="text/css">
+      .CodeMirror {border: 1px solid black;}
+    </style>
+  </head>
+  <body>
+    <h1>CodeMirror: Linter Demo</h1>
+
+    <p><textarea id="code-js">var widgets = []
+function updateHints() {
+  editor.operation(function(){
+    for (var i = 0; i < widgets.length; ++i)
+      editor.removeLineWidget(widgets[i]);
+    widgets.length = 0;
+
+    JSHINT(editor.getValue());
+    for (var i = 0; i < JSHINT.errors.length; ++i) {
+      var err = JSHINT.errors[i];
+      if (!err) continue;
+      var msg = document.createElement("div");
+      var icon = msg.appendChild(document.createElement("span"));
+      icon.innerHTML = "!!";
+      icon.className = "lint-error-icon";
+      msg.appendChild(document.createTextNode(err.reason));
+      msg.className = "lint-error";
+      widgets.push(editor.addLineWidget(err.line - 1, msg, {coverGutter: false, noHScroll: true}));
+    }
+  });
+  var info = editor.getScrollInfo();
+  var after = editor.charCoords({line: editor.getCursor().line + 1, ch: 0}, "local").top;
+  if (info.top + info.clientHeight < after)
+    editor.scrollTo(null, after - info.clientHeight + 3);
+}
+</textarea></p>
+
+    <p><textarea id="code-json">[
+ {
+  _id: "post 1",
+  "author": "Bob",
+  "content": "...",
+  "page_views": 5
+ },
+ {
+  "_id": "post 2",
+  "author": "Bob",
+  "content": "...",
+  "page_views": 9
+ },
+ {
+  "_id": "post 3",
+  "author": "Bob",
+  "content": "...",
+  "page_views": 8
+ }
+]
+</textarea></p>
+
+<script>
+  var editor = CodeMirror.fromTextArea(document.getElementById("code-js"), {
+    lineNumbers: true,
+    mode: "javascript",
+    gutters: ["CodeMirror-lint-markers"],
+    lint: true
+  });
+
+  var editor_json = CodeMirror.fromTextArea(document.getElementById("code-json"), {
+    lineNumbers: true,
+    mode: "application/json",
+    gutters: ["CodeMirror-lint-markers"],
+    lint: true
+  });
+</script>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/demo/loadmode.html b/third-party/codemirror-3.15/demo/loadmode.html
new file mode 100644 (file)
index 0000000..1bd958f
--- /dev/null
@@ -0,0 +1,40 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Lazy Mode Loading Demo</title>
+    <link rel="stylesheet" href="../lib/codemirror.css">
+    <script src="../lib/codemirror.js"></script>
+    <script src="../addon/mode/loadmode.js"></script>
+    <link rel="stylesheet" href="../doc/docs.css">
+
+    <style type="text/css">
+      .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}
+    </style>
+  </head>
+  <body>
+    <h1>CodeMirror: Lazy Mode Loading</h1>
+
+    <form><textarea id="code" name="code">This is the editor.
+// It starts out in plain text mode,
+#  use the control below to load and apply a mode
+  "you'll see the highlighting of" this text /*change*/.
+</textarea></form>
+<p><input type=text value=javascript id=mode> <button type=button onclick="change()">change mode</button></p>
+
+    <script>
+CodeMirror.modeURL = "../mode/%N/%N.js";
+var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+  lineNumbers: true
+});
+var modeInput = document.getElementById("mode");
+CodeMirror.on(modeInput, "keypress", function(e) {
+  if (e.keyCode == 13) change();
+});
+function change() {
+   editor.setOption("mode", modeInput.value);
+   CodeMirror.autoLoadMode(editor, modeInput.value);
+}
+</script>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/demo/marker.html b/third-party/codemirror-3.15/demo/marker.html
new file mode 100644 (file)
index 0000000..f0981e4
--- /dev/null
@@ -0,0 +1,59 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Breakpoint Demo</title>
+    <link rel="stylesheet" href="../lib/codemirror.css">
+    <script src="../lib/codemirror.js"></script>
+    <script src="../mode/javascript/javascript.js"></script>
+    <link rel="stylesheet" href="../doc/docs.css">
+
+    <style type="text/css">
+      .breakpoints {width: .8em;}
+      .breakpoint { color: #822; }
+      .CodeMirror {border: 1px solid #aaa;}
+    </style>
+  </head>
+  <body>
+    <h1>CodeMirror: Breakpoint demo</h1>
+
+    <form><textarea id="code" name="code">
+var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+  lineNumbers: true,
+  gutters: ["CodeMirror-linenumbers", "breakpoints"]
+});
+editor.on("gutterClick", function(cm, n) {
+  var info = cm.lineInfo(n);
+  cm.setGutterMarker(n, "breakpoints", info.markers ? null : makeMarker());
+});
+
+function makeMarker() {
+  var marker = document.createElement("div");
+  marker.innerHTML = "●";
+  marker.className = "breakpoint";
+  return marker;
+}
+</textarea></form>
+
+<p>Click the line-number gutter to add or remove 'breakpoints'.</p>
+
+    <script>
+var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+  lineNumbers: true,
+  gutters: ["CodeMirror-linenumbers", "breakpoints"]
+});
+editor.on("gutterClick", function(cm, n) {
+  var info = cm.lineInfo(n);
+  cm.setGutterMarker(n, "breakpoints", info.gutterMarkers ? null : makeMarker());
+});
+
+function makeMarker() {
+  var marker = document.createElement("div");
+  marker.style.color = "#822";
+  marker.innerHTML = "●";
+  return marker;
+}
+    </script>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/demo/markselection.html b/third-party/codemirror-3.15/demo/markselection.html
new file mode 100644 (file)
index 0000000..e1c0548
--- /dev/null
@@ -0,0 +1,36 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Match Highlighter Demo</title>
+    <link rel="stylesheet" href="../lib/codemirror.css">
+    <script src="../lib/codemirror.js"></script>
+    <script src="../addon/search/searchcursor.js"></script>
+    <script src="../addon/selection/mark-selection.js"></script>
+    <link rel="stylesheet" href="../doc/docs.css">
+
+    <style type="text/css">
+      .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}
+      .CodeMirror-selected  { background-color: blue !important; }
+      .CodeMirror-selectedtext { color: white; }
+    </style>
+  </head>
+  <body>
+    <h1>CodeMirror: Mark Selection Demo</h1>
+
+    <form><textarea id="code" name="code">Select something from here.
+You'll see that the selection's foreground color changes to white!
+Since, by default, CodeMirror only puts an independent "marker" layer
+behind the text, you'll need something like this to change its colour.</textarea></form>
+
+    <script>
+var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+  lineNumbers: true,
+  styleSelectedText: true
+});
+</script>
+
+    <p>Simple addon to easily mark (and style) selected text.</p>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/demo/matchhighlighter.html b/third-party/codemirror-3.15/demo/matchhighlighter.html
new file mode 100644 (file)
index 0000000..9d2fdd0
--- /dev/null
@@ -0,0 +1,38 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Match Highlighter Demo</title>
+    <link rel="stylesheet" href="../lib/codemirror.css">
+    <script src="../lib/codemirror.js"></script>
+    <script src="../addon/search/searchcursor.js"></script>
+    <script src="../addon/search/match-highlighter.js"></script>
+    <link rel="stylesheet" href="../doc/docs.css">
+
+    <style type="text/css">
+      .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}
+      .CodeMirror-focused .cm-matchhighlight {
+        background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAAFklEQVQI12NgYGBgkKzc8x9CMDAwAAAmhwSbidEoSQAAAABJRU5ErkJggg==);
+        background-position: bottom;
+        background-repeat: repeat-x;
+      }
+    </style>
+  </head>
+  <body>
+    <h1>CodeMirror: Match Highlighter Demo</h1>
+
+    <form><textarea id="code" name="code">Select this text: hardToSpotVar
+       And everywhere else in your code where hardToSpotVar appears will automatically illuminate.
+Give it a try!  No more hardToSpotVars.</textarea></form>
+
+    <script>
+var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+  lineNumbers: true,
+  highlightSelectionMatches: {showToken: /\w/}
+});
+</script>
+
+    <p>Search and highlight occurences of the selected text.</p>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/demo/matchtags.html b/third-party/codemirror-3.15/demo/matchtags.html
new file mode 100644 (file)
index 0000000..8f4217d
--- /dev/null
@@ -0,0 +1,38 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Tag Matcher Demo</title>
+    <link rel="stylesheet" href="../lib/codemirror.css">
+    <script src="../lib/codemirror.js"></script>
+    <script src="../addon/fold/xml-fold.js"></script>
+    <script src="../addon/edit/matchtags.js"></script>
+    <script src="../mode/xml/xml.js"></script>
+    <link rel="stylesheet" href="../doc/docs.css">
+
+    <style type="text/css">
+      .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}
+      .CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); }
+    </style>
+  </head>
+  <body>
+    <h1>CodeMirror: Tag Matcher Demo</h1>
+
+    <div id="editor"></div>
+
+    <script>
+window.onload = function() {
+  editor = CodeMirror(document.getElementById("editor"), {
+    value: "<html>\n  " + document.documentElement.innerHTML + "\n</html>",
+    mode: "text/html",
+    matchTags: true,
+    extraKeys: {"Ctrl-J": "toMatchingTag"}
+  });
+};
+    </script>
+
+    <p>Put the cursor on or inside a pair of tags to highlight them.
+    Press Ctrl-J to jump to the tag that matches the one under the
+    cursor.</p>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/demo/merge.html b/third-party/codemirror-3.15/demo/merge.html
new file mode 100644 (file)
index 0000000..907f769
--- /dev/null
@@ -0,0 +1,63 @@
+<!doctype html>
+<head>
+  <meta charset="utf-8">
+  <link rel=stylesheet href="../lib/codemirror.css">
+  <script src="../lib/codemirror.js"></script>
+  <script src="../mode/xml/xml.js"></script>
+  <script src="../addon/merge/dep/diff_match_patch.js"></script>
+  <link rel=stylesheet href="../addon/merge/merge.css">
+  <script src="../addon/merge/merge.js"></script>
+  <link rel="stylesheet" href="../doc/docs.css">
+  <title>CodeMirror: merge view demo</title>
+  <style>
+    .CodeMirror { line-height: 1.2; }
+    body { max-width: 80em; }
+    span.clicky {
+      cursor: pointer;
+      background: #d70;
+      color: white;
+      padding: 0 3px;
+      border-radius: 3px;
+    }
+  </style>
+</head>
+
+<h1>CodeMirror: merge view demo</h1>
+
+<div id=view></div>
+
+<p>The <a href="../doc/manual.html#addon_merge"><code>merge</code></a>
+addon provides an interface for displaying and merging diffs,
+either <span class=clicky onclick="initUI(2)">two-way</span>
+or <span class=clicky onclick="initUI(3)">three-way</span>. The left
+(or center) pane is editable, and the differences with the other
+pane(s) are shown live as you edit it.</p>
+
+<p>This addon depends on
+the <a href="https://code.google.com/p/google-diff-match-patch/">google-diff-match-patch</a>
+library to compute the diffs.</p>
+
+<script>
+var value, orig1, orig2, dv;
+
+function initUI(panes) {
+  if (value == null) return;
+  var target = document.getElementById("view");
+  target.innerHTML = "";
+  dv = CodeMirror.MergeView(target, {
+    value: value,
+    origLeft: panes == 3 ? orig1 : null,
+    orig: orig2,
+    lineNumbers: true,
+    mode: "text/html"
+  });
+}
+
+window.onload = function() {
+  value = document.documentElement.innerHTML;
+  orig1 = value.replace(/\.\.\//g, "codemirror/").replace("yellow", "orange");
+  orig2 = value.replace(/\u003cscript/g, "\u003cscript type=text/javascript ")
+    .replace("white", "purple;\n      font: comic sans;\n      text-decoration: underline;\n      height: 15em");
+  initUI(2);
+};
+</script>
diff --git a/third-party/codemirror-3.15/demo/multiplex.html b/third-party/codemirror-3.15/demo/multiplex.html
new file mode 100644 (file)
index 0000000..ec0519c
--- /dev/null
@@ -0,0 +1,66 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Multiplexing Parser Demo</title>
+    <link rel="stylesheet" href="../lib/codemirror.css">
+    <script src="../lib/codemirror.js"></script>
+    <script src="../addon/mode/multiplex.js"></script>
+    <script src="../mode/xml/xml.js"></script>
+    <link rel="stylesheet" href="../doc/docs.css">
+
+    <style type="text/css">
+      .CodeMirror {border: 1px solid black;}
+      .cm-delimit {color: #fa4;}
+    </style>
+  </head>
+  <body>
+    <h1>CodeMirror: Multiplexing Parser Demo</h1>
+
+    <form><textarea id="code" name="code">
+<html>
+  <body style="<<magic>>">
+    <h1><< this is not <html >></h1>
+    <<
+        multiline
+        not html
+        at all : &amp;amp; <link/>
+    >>
+    <p>this is html again</p>
+  </body>
+</html>
+</textarea></form>
+
+    <script>
+CodeMirror.defineMode("demo", function(config) {
+  return CodeMirror.multiplexingMode(
+    CodeMirror.getMode(config, "text/html"),
+    {open: "<<", close: ">>",
+     mode: CodeMirror.getMode(config, "text/plain"),
+     delimStyle: "delimit"}
+    // .. more multiplexed styles can follow here
+  );
+});
+var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+  mode: "demo",
+  lineNumbers: true,
+  lineWrapping: true
+});
+</script>
+
+    <p>Demonstration of a multiplexing mode, which, at certain
+    boundary strings, switches to one or more inner modes. The out
+    (HTML) mode does not get fed the content of the <code>&lt;&lt;
+    >></code> blocks. See
+    the <a href="../doc/manual.html#addon_multiplex">manual</a> and
+    the <a href="../addon/mode/multiplex.js">source</a> for more
+    information.</p>
+
+    <p>
+      <strong>Parsing/Highlighting Tests:</strong>
+      <a href="../test/index.html#multiplexing_*">normal</a>,
+      <a href="../test/index.html#verbose,multiplexing_*">verbose</a>.
+    </p>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/demo/mustache.html b/third-party/codemirror-3.15/demo/mustache.html
new file mode 100644 (file)
index 0000000..9d2081d
--- /dev/null
@@ -0,0 +1,59 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Overlay Parser Demo</title>
+    <link rel="stylesheet" href="../lib/codemirror.css">
+    <script src="../lib/codemirror.js"></script>
+    <script src="../addon/mode/overlay.js"></script>
+    <script src="../mode/xml/xml.js"></script>
+    <link rel="stylesheet" href="../doc/docs.css">
+
+    <style type="text/css">
+      .CodeMirror {border: 1px solid black;}
+      .cm-mustache {color: #0ca;}
+    </style>
+  </head>
+  <body>
+    <h1>CodeMirror: Overlay Parser Demo</h1>
+
+    <form><textarea id="code" name="code">
+<html>
+  <body>
+    <h1>{{title}}</h1>
+    <p>These are links to {{things}}:</p>
+    <ul>{{#links}}
+      <li><a href="{{url}}">{{text}}</a></li>
+    {{/links}}</ul>
+  </body>
+</html>
+</textarea></form>
+
+    <script>
+CodeMirror.defineMode("mustache", function(config, parserConfig) {
+  var mustacheOverlay = {
+    token: function(stream, state) {
+      var ch;
+      if (stream.match("{{")) {
+        while ((ch = stream.next()) != null)
+          if (ch == "}" && stream.next() == "}") break;
+        stream.eat("}");
+        return "mustache";
+      }
+      while (stream.next() != null && !stream.match("{{", false)) {}
+      return null;
+    }
+  };
+  return CodeMirror.overlayMode(CodeMirror.getMode(config, parserConfig.backdrop || "text/html"), mustacheOverlay);
+});
+var editor = CodeMirror.fromTextArea(document.getElementById("code"), {mode: "mustache"});
+</script>
+
+    <p>Demonstration of a mode that parses HTML, highlighting
+    the <a href="http://mustache.github.com/">Mustache</a> templating
+    directives inside of it by using the code
+    in <a href="../addon/mode/overlay.js"><code>overlay.js</code></a>. View
+    source to see the 15 lines of code needed to accomplish this.</p>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/demo/placeholder.html b/third-party/codemirror-3.15/demo/placeholder.html
new file mode 100644 (file)
index 0000000..b0f2456
--- /dev/null
@@ -0,0 +1,36 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Placeholder demo</title>
+    <link rel="stylesheet" href="../lib/codemirror.css">
+    <script src="../lib/codemirror.js"></script>
+    <script src="../addon/display/placeholder.js"></script>
+    <link rel="stylesheet" href="../doc/docs.css">
+
+    <style type="text/css">
+      .CodeMirror { border: 1px solid silver; }
+      .CodeMirror-empty { outline: 1px solid #c22; }
+      .CodeMirror-empty.CodeMirror-focused { outline: none; }
+      .CodeMirror pre.CodeMirror-placeholder { color: #999; }
+    </style>
+  </head>
+  <body>
+    <h1>CodeMirror: Placeholder demo</h1>
+
+    <form><textarea id="code" name="code" placeholder="Code goes here..."></textarea></form>
+
+    <p>The <a href="../doc/manual.html#addon_placeholder">placeholder</a>
+    plug-in adds an option <code>placeholder</code> that can be set to
+    make text appear in the editor when it is empty and not focused.
+    If the source textarea has a <code>placeholder</code> attribute,
+    it will automatically be inherited.</p>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true
+      });
+    </script>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/demo/preview.html b/third-party/codemirror-3.15/demo/preview.html
new file mode 100644 (file)
index 0000000..f70cdb0
--- /dev/null
@@ -0,0 +1,76 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: HTML5 preview</title>
+    <script src=../lib/codemirror.js></script>
+    <script src=../mode/xml/xml.js></script>
+    <script src=../mode/javascript/javascript.js></script>
+    <script src=../mode/css/css.js></script>
+    <script src=../mode/htmlmixed/htmlmixed.js></script>
+    <link rel=stylesheet href=../lib/codemirror.css>
+    <link rel=stylesheet href=../doc/docs.css>
+    <style type=text/css>
+      .CodeMirror {
+        float: left;
+        width: 50%;
+        border: 1px solid black;
+      }
+      iframe {
+        width: 49%;
+        float: left;
+        height: 300px;
+        border: 1px solid black;
+        border-left: 0px;
+      }
+    </style>
+  </head>
+  <body>
+    <h1>CodeMirror: HTML5 preview</h1>
+    <textarea id=code name=code>
+<!doctype html>
+<html>
+  <head>
+    <meta charset=utf-8>
+    <title>HTML5 canvas demo</title>
+    <style>p {font-family: monospace;}</style>
+  </head>
+  <body>
+    <p>Canvas pane goes here:</p>
+    <canvas id=pane width=300 height=200></canvas>
+    <script>
+      var canvas = document.getElementById('pane');
+      var context = canvas.getContext('2d');
+
+      context.fillStyle = 'rgb(250,0,0)';
+      context.fillRect(10, 10, 55, 50);
+
+      context.fillStyle = 'rgba(0, 0, 250, 0.5)';
+      context.fillRect(30, 30, 55, 50);
+    </script>
+  </body>
+</html></textarea>
+    <iframe id=preview></iframe>
+    <script>
+      var delay;
+      // Initialize CodeMirror editor with a nice html5 canvas demo.
+      var editor = CodeMirror.fromTextArea(document.getElementById('code'), {
+        mode: 'text/html',
+        tabMode: 'indent'
+      });
+      editor.on("change", function() {
+        clearTimeout(delay);
+        delay = setTimeout(updatePreview, 300);
+      });
+      
+      function updatePreview() {
+        var previewFrame = document.getElementById('preview');
+        var preview =  previewFrame.contentDocument ||  previewFrame.contentWindow.document;
+        preview.open();
+        preview.write(editor.getValue());
+        preview.close();
+      }
+      setTimeout(updatePreview, 300);
+    </script>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/demo/resize.html b/third-party/codemirror-3.15/demo/resize.html
new file mode 100644 (file)
index 0000000..7badc2b
--- /dev/null
@@ -0,0 +1,49 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Autoresize Demo</title>
+    <link rel="stylesheet" href="../lib/codemirror.css">
+    <script src="../lib/codemirror.js"></script>
+    <script src="../mode/css/css.js"></script>
+    <link rel="stylesheet" href="../doc/docs.css">
+
+    <style type="text/css">
+      .CodeMirror {
+        border: 1px solid #eee;
+        height: auto;
+      }
+      .CodeMirror-scroll {
+        overflow-y: hidden;
+        overflow-x: auto;
+      }
+    </style>
+  </head>
+  <body>
+    <h1>CodeMirror: Autoresize demo</h1>
+
+    <form><textarea id="code" name="code">
+.CodeMirror {
+  border: 1px solid #eee;
+  height: auto;
+}
+.CodeMirror-scroll {
+  overflow-y: hidden;
+  overflow-x: auto;
+}
+</textarea></form>
+
+<p>By setting a few CSS properties, and giving
+the <a href="../doc/manual.html#option_viewportMargin"><code>viewportMargin</code></a>
+a value of <code>Infinity</code>, CodeMirror can be made to
+automatically resize to fit its content.</p>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        viewportMargin: Infinity
+      });
+    </script>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/demo/runmode.html b/third-party/codemirror-3.15/demo/runmode.html
new file mode 100644 (file)
index 0000000..dba808b
--- /dev/null
@@ -0,0 +1,50 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Mode Runner Demo</title>
+    <link rel="stylesheet" href="../lib/codemirror.css">
+    <script src="../lib/codemirror.js"></script>
+    <script src="../addon/runmode/runmode.js"></script>
+    <script src="../mode/xml/xml.js"></script>
+    <link rel="stylesheet" href="../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Mode Runner Demo</h1>
+
+    <textarea id="code" style="width: 90%; height: 7em; border: 1px solid black; padding: .2em .4em;">
+<foobar>
+  <blah>Enter your xml here and press the button below to display
+    it as highlighted by the CodeMirror XML mode</blah>
+  <tag2 foo="2" bar="&amp;quot;bar&amp;quot;"/>
+</foobar></textarea><br>
+    <button onclick="doHighlight();">Highlight!</button>
+    <pre id="output" class="cm-s-default"></pre>
+
+    <script>
+function doHighlight() {
+  CodeMirror.runMode(document.getElementById("code").value, "application/xml",
+                     document.getElementById("output"));
+}
+</script>
+
+    <p>Running a CodeMirror mode outside of the editor.
+    The <code>CodeMirror.runMode</code> function, defined
+    in <code><a href="../addon/runmode/runmode.js">lib/runmode.js</a></code> takes the following arguments:</p>
+
+    <dl>
+      <dt><code>text (string)</code></dt>
+      <dd>The document to run through the highlighter.</dd>
+      <dt><code>mode (<a href="../doc/manual.html#option_mode">mode spec</a>)</code></dt>
+      <dd>The mode to use (must be loaded as normal).</dd>
+      <dt><code>output (function or DOM node)</code></dt>
+      <dd>If this is a function, it will be called for each token with
+      two arguments, the token's text and the token's style class (may
+      be <code>null</code> for unstyled tokens). If it is a DOM node,
+      the tokens will be converted to <code>span</code> elements as in
+      an editor, and inserted into the node
+      (through <code>innerHTML</code>).</dd>
+    </dl>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/demo/search.html b/third-party/codemirror-3.15/demo/search.html
new file mode 100644 (file)
index 0000000..d721071
--- /dev/null
@@ -0,0 +1,85 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Search/Replace Demo</title>
+    <link rel="stylesheet" href="../lib/codemirror.css">
+    <script src="../lib/codemirror.js"></script>
+    <script src="../mode/xml/xml.js"></script>
+    <script src="../addon/dialog/dialog.js"></script>
+    <link rel="stylesheet" href="../addon/dialog/dialog.css">
+    <script src="../addon/search/searchcursor.js"></script>
+    <script src="../addon/search/search.js"></script>
+    <link rel="stylesheet" href="../doc/docs.css">
+
+    <style type="text/css">
+      .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}
+      dt {font-family: monospace; color: #666;}
+    </style>
+  </head>
+  <body>
+    <h1>CodeMirror: Search/Replace Demo</h1>
+
+    <form><textarea id="code" name="code">
+  <dt id="option_indentWithTabs"><code>indentWithTabs (boolean)</code></dt>
+  <dd>Whether, when indenting, the first N*8 spaces should be
+  replaced by N tabs. Default is false.</dd>
+
+  <dt id="option_tabMode"><code>tabMode (string)</code></dt>
+  <dd>Determines what happens when the user presses the tab key.
+  Must be one of the following:
+    <dl>
+      <dt><code>"classic" (the default)</code></dt>
+      <dd>When nothing is selected, insert a tab. Otherwise,
+      behave like the <code>"shift"</code> mode. (When shift is
+      held, this behaves like the <code>"indent"</code> mode.)</dd>
+      <dt><code>"shift"</code></dt>
+      <dd>Indent all selected lines by
+      one <a href="#option_indentUnit"><code>indentUnit</code></a>.
+      If shift was held while pressing tab, un-indent all selected
+      lines one unit.</dd>
+      <dt><code>"indent"</code></dt>
+      <dd>Indent the line the 'correctly', based on its syntactic
+      context. Only works if the
+      mode <a href="#indent">supports</a> it.</dd>
+      <dt><code>"default"</code></dt>
+      <dd>Do not capture tab presses, let the browser apply its
+      default behaviour (which usually means it skips to the next
+      control).</dd>
+    </dl></dd>
+
+  <dt id="option_enterMode"><code>enterMode (string)</code></dt>
+  <dd>Determines whether and how new lines are indented when the
+  enter key is pressed. The following modes are supported:
+    <dl>
+      <dt><code>"indent" (the default)</code></dt>
+      <dd>Use the mode's indentation rules to give the new line
+      the correct indentation.</dd>
+      <dt><code>"keep"</code></dt>
+      <dd>Indent the line the same as the previous line.</dd>
+      <dt><code>"flat"</code></dt>
+      <dd>Do not indent the new line.</dd>
+    </dl></dd>
+</textarea></form>
+
+    <script>
+var editor = CodeMirror.fromTextArea(document.getElementById("code"), {mode: "text/html", lineNumbers: true});
+</script>
+
+    <p>Demonstration of primitive search/replace functionality. The
+    keybindings (which can be overridden by custom keymaps) are:</p>
+    <dl>
+      <dt>Ctrl-F / Cmd-F</dt><dd>Start searching</dd>
+      <dt>Ctrl-G / Cmd-G</dt><dd>Find next</dd>
+      <dt>Shift-Ctrl-G / Shift-Cmd-G</dt><dd>Find previous</dd>
+      <dt>Shift-Ctrl-F / Cmd-Option-F</dt><dd>Replace</dd>
+      <dt>Shift-Ctrl-R / Shift-Cmd-Option-F</dt><dd>Replace all</dd>
+    </dl>
+    <p>Searching is enabled by
+    including <a href="../addon/search/search.js">addon/search/search.js</a>
+    and <a href="../addon/search/searchcursor.js">addon/search/searchcursor.js</a>.
+    For good-looking input dialogs, you also want to include
+    <a href="../addon/dialog/dialog.js">addon/dialog/dialog.js</a>
+    and <a href="../addon/dialog/dialog.css">addon/dialog/dialog.css</a>.</p>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/demo/spanaffectswrapping_shim.html b/third-party/codemirror-3.15/demo/spanaffectswrapping_shim.html
new file mode 100644 (file)
index 0000000..733db06
--- /dev/null
@@ -0,0 +1,73 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Automatically derive odd wrapping behavior for your browser</title>
+    <link rel="stylesheet" href="../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: odd wrapping shim</h1>
+
+    <p>This is a hack to automatically derive
+    a <code>spanAffectsWrapping</code> regexp for a browser. See the
+    comments above that variable
+    in <a href="../lib/codemirror.js"><code>lib/codemirror.js</code></a>
+    for some more details.</p>
+
+    <div style="white-space: pre-wrap; width: 50px;" id="area"></div>
+    <pre id="output"></pre>
+
+    <script id="script">
+      var a = document.getElementById("area"), bad = Object.create(null);
+      var chars = "a~`!@#$%^&*()-_=+}{[]\|'\"/?.>,<:;", l = chars.length;
+      for (var x = 0; x < l; ++x) for (var y = 0; y < l; ++y) {
+        var s1 = "foooo" + chars.charAt(x), s2 = chars.charAt(y) + "br";
+        a.appendChild(document.createTextNode(s1 + s2));
+        var h1 = a.offsetHeight;
+        a.innerHTML = "";
+        a.appendChild(document.createElement("span")).appendChild(document.createTextNode(s1));
+        a.appendChild(document.createElement("span")).appendChild(document.createTextNode(s2));
+        if (a.offsetHeight != h1)
+          bad[chars.charAt(x)] = (bad[chars.charAt(x)] || "") + chars.charAt(y);
+        a.innerHTML = "";
+      }
+
+      var re = "";
+      function toREElt(str) {
+        if (str.length > 1) {
+          var invert = false;
+          if (str.length > chars.length * .6) {
+            invert = true;
+            var newStr = "";
+            for (var i = 0; i < l; ++i) if (str.indexOf(chars.charAt(i)) == -1) newStr += chars.charAt(i);
+            str = newStr;
+          }
+          str = str.replace(/[\-\.\]\"\'\\\/\^a]/g, function(orig) { return orig == "a" ? "\\w" : "\\" + orig; });
+          return "[" + (invert ? "^" : "") + str + "]";
+        } else if (str == "a") {
+          return "\\w";
+        } else if (/[?$*()+{}[\]\.|/\'\"]/.test(str)) {
+          return "\\" + str;
+        } else {
+          return str;
+        }
+      }
+
+      var newRE = "";
+      for (;;) {
+        var left = null;
+        for (var left in bad) break;
+        if (left == null) break;
+        var right = bad[left];
+        delete bad[left];
+        for (var other in bad) if (bad[other] == right) {
+          left += other;
+          delete bad[other];
+        }
+        newRE += (newRE ? "|" : "") + toREElt(left) + toREElt(right);
+      }
+
+      document.getElementById("output").appendChild(document.createTextNode("Your regexp is: " + (newRE || "^$")));
+    </script>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/demo/tern.html b/third-party/codemirror-3.15/demo/tern.html
new file mode 100644 (file)
index 0000000..bbc5e47
--- /dev/null
@@ -0,0 +1,122 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Tern Demo</title>
+    <link rel="stylesheet" href="../lib/codemirror.css">
+    <script src="../lib/codemirror.js"></script>
+    <script src="../mode/javascript/javascript.js"></script>
+    <link rel="stylesheet" href="../doc/docs.css">
+    <script src="../addon/dialog/dialog.js"></script>
+    <link rel="stylesheet" href="../addon/dialog/dialog.css">
+    <script src="../addon/hint/show-hint.js"></script>
+    <link rel="stylesheet" href="../addon/hint/show-hint.css">
+    <script src="../addon/tern/tern.js"></script>
+    <link rel="stylesheet" href="../addon/tern/tern.css">
+
+    <!-- NOTE: if you are going to actually deploy this in production,
+         DO NOT hot-link these files. Host them yourself. -->
+    <script src="http://marijnhaverbeke.nl/acorn/acorn.js"></script>
+    <script src="http://marijnhaverbeke.nl/acorn/acorn_loose.js"></script>
+    <script src="http://marijnhaverbeke.nl/acorn/util/walk.js"></script>
+    <script src="http://ternjs.net/lib/signal.js"></script>
+    <script src="http://ternjs.net/lib/tern.js"></script>
+    <script src="http://ternjs.net/lib/def.js"></script>
+    <script src="http://ternjs.net/lib/comment.js"></script>
+    <script src="http://ternjs.net/lib/infer.js"></script>
+    <script src="http://ternjs.net/plugin/doc_comment.js"></script>
+
+    <style>
+      .CodeMirror {border: 1px solid #ddd;}
+    </style>
+  </head>
+  <body>
+    <h1>CodeMirror: Tern Demo</h1>
+
+    <form><textarea id="code" name="code">// Use ctrl-space to complete something
+// Put the cursor in or after an expression, press ctrl-i to
+// find its type
+
+var foo = ["array", "of", "strings"];
+var bar = foo.slice(0, 2).join("").split("a")[0];
+
+// Works for locally defined types too.
+
+function CTor() { this.size = 10; }
+CTor.prototype.hallo = "hallo";
+
+var baz = new CTor;
+baz.
+
+// You can press ctrl-q when the cursor is on a variable name to
+// rename it. Try it with CTor...
+
+// When the cursor is in an argument list, the arguments are
+// shown below the editor.
+
+[1].reduce(  );
+
+// And a little more advanced code...
+
+(function(exports) {
+  exports.randomElt = function(arr) {
+    return arr[Math.floor(arr.length * Math.random())];
+  };
+  exports.strList = "foo".split("");
+  exports.intList = exports.strList.map(function(s) { return s.charCodeAt(0); });
+})(window.myMod = {});
+
+var randomStr = myMod.randomElt(myMod.strList);
+var randomInt = myMod.randomElt(myMod.intList);
+</textarea></p>
+
+<p>Demonstrates integration of <a href="http://ternjs.net/">Tern</a>
+and CodeMirror. The following keys are bound:</p>
+
+<dl>
+  <dt>Ctrl-Space</dt><dd>Autocomplete</dd>
+  <dt>Ctrl-I</dt><dd>Find type at cursor</dd>
+  <dt>Alt-.</dt><dd>Jump to definition (Alt-, to jump back)</dd>
+  <dt>Ctrl-Q</dt><dd>Rename variable</dd>
+</dl>
+
+<p>Documentation is sparse for now. See the top of
+the <a href="../addon/tern/tern.js">script</a> for a rough API
+overview.</p>
+
+<script>
+  function getURL(url, c) {
+    var xhr = new XMLHttpRequest();
+    xhr.open("get", url, true);
+    xhr.send();
+    xhr.onreadystatechange = function() {
+      if (xhr.readyState != 4) return;
+      if (xhr.status < 400) return c(null, xhr.responseText);
+      var e = new Error(xhr.responseText || "No response");
+      e.status = xhr.status;
+      c(e);
+    };
+  }
+
+  var server;
+  getURL("http://ternjs.net/defs/ecma5.json", function(err, code) {
+    if (err) throw new Error("Request for ecma5.json: " + err);
+    server = new CodeMirror.TernServer({defs: [JSON.parse(code)]});
+    editor.setOption("extraKeys", {
+      "Ctrl-Space": function(cm) { server.complete(cm); },
+      "Ctrl-I": function(cm) { server.showType(cm); },
+      "Alt-.": function(cm) { server.jumpToDef(cm); },
+      "Alt-,": function(cm) { server.jumpBack(cm); },
+      "Ctrl-Q": function(cm) { server.rename(cm); },
+    })
+    editor.on("cursorActivity", function(cm) { server.updateArgHints(cm); });
+  });
+
+  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+    lineNumbers: true,
+    mode: "javascript"
+  });
+</script>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/demo/theme.html b/third-party/codemirror-3.15/demo/theme.html
new file mode 100644 (file)
index 0000000..62544be
--- /dev/null
@@ -0,0 +1,100 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Theme Demo</title>
+    <link rel="stylesheet" href="../lib/codemirror.css">
+    <script src="../lib/codemirror.js"></script>
+    <link rel="stylesheet" href="../theme/neat.css">
+    <link rel="stylesheet" href="../theme/elegant.css">
+    <link rel="stylesheet" href="../theme/erlang-dark.css">
+    <link rel="stylesheet" href="../theme/night.css">
+    <link rel="stylesheet" href="../theme/monokai.css">
+    <link rel="stylesheet" href="../theme/cobalt.css">
+    <link rel="stylesheet" href="../theme/eclipse.css">
+    <link rel="stylesheet" href="../theme/rubyblue.css">
+    <link rel="stylesheet" href="../theme/lesser-dark.css">
+    <link rel="stylesheet" href="../theme/xq-dark.css">
+    <link rel="stylesheet" href="../theme/xq-light.css">
+    <link rel="stylesheet" href="../theme/ambiance.css">
+    <link rel="stylesheet" href="../theme/blackboard.css">
+    <link rel="stylesheet" href="../theme/vibrant-ink.css">
+    <link rel="stylesheet" href="../theme/solarized.css">
+    <link rel="stylesheet" href="../theme/twilight.css">
+    <link rel="stylesheet" href="../theme/midnight.css">
+    <link rel="stylesheet" href="../theme/3024-day.css">
+    <link rel="stylesheet" href="../theme/3024-night.css">
+    <link rel="stylesheet" href="../theme/base16-light.css">
+    <link rel="stylesheet" href="../theme/base16-dark.css">
+    <link rel="stylesheet" href="../theme/tomorrow-night-eighties.css">
+    <script src="../mode/javascript/javascript.js"></script>
+    <script src="../keymap/extra.js"></script>
+    <link rel="stylesheet" href="../doc/docs.css">
+
+    <style type="text/css">
+      .CodeMirror {border: 1px solid black; font-size:13px}
+    </style>
+  </head>
+  <body>
+    <h1>CodeMirror: Theme demo</h1>
+
+    <form><textarea id="code" name="code">
+function findSequence(goal) {
+  function find(start, history) {
+    if (start == goal)
+      return history;
+    else if (start > goal)
+      return null;
+    else
+      return find(start + 5, "(" + history + " + 5)") ||
+             find(start * 3, "(" + history + " * 3)");
+  }
+  return find(1, "1");
+}</textarea></form>
+
+<p>Select a theme: <select onchange="selectTheme()" id=select>
+    <option selected>default</option>
+    <option>3024-day</option>
+    <option>3024-night</option>
+    <option>ambiance</option>
+    <option>base16-dark</option>
+    <option>base16-light</option>
+    <option>blackboard</option>
+    <option>cobalt</option>
+    <option>eclipse</option>
+    <option>elegant</option>
+    <option>erlang-dark</option>
+    <option>lesser-dark</option>
+    <option>midnight</option>
+    <option>monokai</option>
+    <option>neat</option>
+    <option>night</option>
+    <option>rubyblue</option>
+    <option>solarized dark</option>
+    <option>solarized light</option>
+    <option>tomorrow-night-eighties</option>
+    <option>twilight</option>
+    <option>vibrant-ink</option>
+    <option>xq-dark</option>
+    <option>xq-light</option>
+</select>
+</p>
+
+<script>
+  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+    lineNumbers: true
+  });
+  var input = document.getElementById("select");
+  function selectTheme() {
+    var theme = input.options[input.selectedIndex].innerHTML;
+    editor.setOption("theme", theme);
+  }
+  var choice = document.location.search &&
+               decodeURIComponent(document.location.search.slice(1));
+  if (choice) {
+    input.value = choice;
+    editor.setOption("theme", choice);
+  }
+</script>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/demo/trailingspace.html b/third-party/codemirror-3.15/demo/trailingspace.html
new file mode 100644 (file)
index 0000000..ca74152
--- /dev/null
@@ -0,0 +1,39 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Trailing Whitespace Demo</title>
+    <link rel="stylesheet" href="../lib/codemirror.css">
+    <script src="../lib/codemirror.js"></script>
+    <script src="../addon/edit/trailingspace.js"></script>
+    <link rel="stylesheet" href="../doc/docs.css">
+
+    <style type="text/css">
+      .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}
+      .cm-trailingspace {
+        background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAACCAYAAAB/qH1jAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3QUXCToH00Y1UgAAACFJREFUCNdjPMDBUc/AwNDAAAFMTAwMDA0OP34wQgX/AQBYgwYEx4f9lQAAAABJRU5ErkJggg==);
+        background-position: bottom left;
+        background-repeat: repeat-x;
+      }
+    </style>
+  </head>
+  <body>
+    <h1>CodeMirror: Trailing Whitespace Demo</h1>
+
+    <form><textarea id="code" name="code">This text  
+ has some       
+trailing whitespace!</textarea></form>
+
+    <script>
+var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+  lineNumbers: true,
+  showTrailingSpace: true
+});
+</script>
+
+<p>Uses
+the <a href="../doc/manual.html#addon_trailingspace">trailingspace</a>
+addon to highlight trailing whitespace.</p>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/demo/variableheight.html b/third-party/codemirror-3.15/demo/variableheight.html
new file mode 100644 (file)
index 0000000..b00f7e4
--- /dev/null
@@ -0,0 +1,52 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Variable Height Demo</title>
+    <link rel="stylesheet" href="../lib/codemirror.css">
+    <script src="../lib/codemirror.js"></script>
+    <script src="../mode/markdown/markdown.js"></script>
+    <script src="../mode/xml/xml.js"></script>
+    <link rel="stylesheet" href="../doc/docs.css">
+
+    <style type="text/css">
+      .CodeMirror {border: 1px solid silver; border-width: 1px 2px; }
+      .cm-header { font-size: 150%; font-family: arial; }
+      .cm-strong { font-size: 140%; }
+    </style>
+  </head>
+  <body>
+    <h1>CodeMirror: Variable Height Demo</h1>
+
+    <form><textarea id="code" name="code"># A First Level Header
+
+**Bold** text in a normal-size paragraph.
+
+And a very long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long, wrapped line with a piece of **big** text inside of it.
+
+## A Second Level Header
+
+Now is the time for all good men to come to
+the aid of their country. This is just a
+regular paragraph.
+
+The quick brown fox jumped over the lazy
+dog's back.
+
+### Header 3
+
+> This is a blockquote.
+> 
+> This is the second paragraph in the blockquote.
+>
+> ## This is an H2 in a blockquote       
+</textarea></form>
+    <script id="script">
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        lineWrapping: true,
+        mode: "markdown"
+      });
+    </script>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/demo/vim.html b/third-party/codemirror-3.15/demo/vim.html
new file mode 100644 (file)
index 0000000..9b7a432
--- /dev/null
@@ -0,0 +1,65 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Vim bindings demo</title>
+    <link rel="stylesheet" href="../lib/codemirror.css">
+    <script src="../lib/codemirror.js"></script>
+    <script src="../addon/dialog/dialog.js"></script>
+    <script src="../addon/search/searchcursor.js"></script>
+    <script src="../mode/clike/clike.js"></script>
+    <script src="../keymap/vim.js"></script>
+    <link rel="stylesheet" href="../doc/docs.css">
+    <link rel="stylesheet" href="../addon/dialog/dialog.css">
+
+    <style type="text/css">
+      .CodeMirror {border-top: 1px solid #eee; border-bottom: 1px solid #eee;}
+    </style>
+  </head>
+  <body>
+    <h1>CodeMirror: Vim bindings demo</h1>
+
+    <form><textarea id="code" name="code">
+#include "syscalls.h"
+/* getchar:  simple buffered version */
+int getchar(void)
+{
+  static char buf[BUFSIZ];
+  static char *bufp = buf;
+  static int n = 0;
+  if (n == 0) {  /* buffer is empty */
+    n = read(0, buf, sizeof buf);
+    bufp = buf;
+  }
+  return (--n >= 0) ? (unsigned char) *bufp++ : EOF;
+}
+</textarea></form>
+
+    <form><textarea id="code2" name="code2">
+        I am another file! You can yank from my neighbor and paste here.
+</textarea></form>
+
+<p>The vim keybindings are enabled by
+including <a href="../keymap/vim.js">keymap/vim.js</a> and setting
+the <code>keyMap</code> option to <code>"vim"</code>. Because
+CodeMirror's internal API is quite different from Vim, they are only
+a loose approximation of actual vim bindings, though.</p>
+
+    <script>
+      CodeMirror.commands.save = function(){ alert("Saving"); };
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        mode: "text/x-csrc",
+        vimMode: true,
+        showCursorWhenSelecting: true
+      });
+      var editor2 = CodeMirror.fromTextArea(document.getElementById("code2"), {
+        lineNumbers: true,
+        mode: "text/x-csrc",
+        vimMode: true,
+        showCursorWhenSelecting: true
+      });
+    </script>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/demo/visibletabs.html b/third-party/codemirror-3.15/demo/visibletabs.html
new file mode 100644 (file)
index 0000000..109d1a6
--- /dev/null
@@ -0,0 +1,53 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Visible tabs demo</title>
+    <link rel="stylesheet" href="../lib/codemirror.css">
+    <script src="../lib/codemirror.js"></script>
+    <script src="../mode/clike/clike.js"></script>
+    <link rel="stylesheet" href="../doc/docs.css">
+
+    <style type="text/css">
+      .CodeMirror {border-top: 1px solid #eee; border-bottom: 1px solid #eee;}
+      .cm-tab {
+         background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAMCAYAAAAkuj5RAAAAAXNSR0IArs4c6QAAAGFJREFUSMft1LsRQFAQheHPowAKoACx3IgEKtaEHujDjORSgWTH/ZOdnZOcM/sgk/kFFWY0qV8foQwS4MKBCS3qR6ixBJvElOobYAtivseIE120FaowJPN75GMu8j/LfMwNjh4HUpwg4LUAAAAASUVORK5CYII=);
+         background-position: right;
+         background-repeat: no-repeat;
+      }
+    </style>
+  </head>
+  <body>
+    <h1>CodeMirror: Visible tabs demo</h1>
+
+    <form><textarea id="code" name="code">
+#include "syscalls.h"
+/* getchar:  simple buffered version */
+int getchar(void)
+{
+       static char buf[BUFSIZ];
+       static char *bufp = buf;
+       static int n = 0;
+       if (n == 0) {  /* buffer is empty */
+               n = read(0, buf, sizeof buf);
+               bufp = buf;
+       }
+       return (--n >= 0) ? (unsigned char) *bufp++ : EOF;
+}
+</textarea></form>
+
+<p>Tabs inside the editor are spans with the
+class <code>cm-tab</code>, and can be styled.</p>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        tabSize: 4,
+        indentUnit: 4,
+        indentWithTabs: true,
+        mode: "text/x-csrc"
+      });
+    </script>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/demo/widget.html b/third-party/codemirror-3.15/demo/widget.html
new file mode 100644 (file)
index 0000000..a3b27a9
--- /dev/null
@@ -0,0 +1,74 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Inline Widget Demo</title>
+    <link rel="stylesheet" href="../lib/codemirror.css">
+    <script src="../lib/codemirror.js"></script>
+    <script src="../mode/javascript/javascript.js"></script>
+    <script src="http://ajax.aspnetcdn.com/ajax/jshint/r07/jshint.js"></script>
+    <link rel="stylesheet" href="../doc/docs.css">
+
+    <style type="text/css">
+      .CodeMirror {border: 1px solid black;}
+      .lint-error {font-family: arial; font-size: 70%; background: #ffa; color: #a00; padding: 2px 5px 3px; }
+      .lint-error-icon {color: white; background-color: red; font-weight: bold; border-radius: 50%; padding: 0 3px; margin-right: 7px;}
+    </style>
+  </head>
+  <body>
+    <h1>CodeMirror: Inline Widget Demo</h1>
+
+    <div id=code></div>
+    <script id="script">var widgets = []
+function updateHints() {
+  editor.operation(function(){
+    for (var i = 0; i < widgets.length; ++i)
+      editor.removeLineWidget(widgets[i]);
+    widgets.length = 0;
+
+    JSHINT(editor.getValue());
+    for (var i = 0; i < JSHINT.errors.length; ++i) {
+      var err = JSHINT.errors[i];
+      if (!err) continue;
+      var msg = document.createElement("div");
+      var icon = msg.appendChild(document.createElement("span"));
+      icon.innerHTML = "!!";
+      icon.className = "lint-error-icon";
+      msg.appendChild(document.createTextNode(err.reason));
+      msg.className = "lint-error";
+      widgets.push(editor.addLineWidget(err.line - 1, msg, {coverGutter: false, noHScroll: true}));
+    }
+  });
+  var info = editor.getScrollInfo();
+  var after = editor.charCoords({line: editor.getCursor().line + 1, ch: 0}, "local").top;
+  if (info.top + info.clientHeight < after)
+    editor.scrollTo(null, after - info.clientHeight + 3);
+}
+
+window.onload = function() {
+  var sc = document.getElementById("script");
+  var content = sc.textContent || sc.innerText || sc.innerHTML;
+
+  window.editor = CodeMirror(document.getElementById("code"), {
+    lineNumbers: true,
+    mode: "javascript",
+    value: content
+  });
+
+  var waiting;
+  editor.on("change", function() {
+    clearTimeout(waiting);
+    waiting = setTimeout(updateHints, 500);
+  });
+
+  setTimeout(updateHints, 100);
+};
+
+"long line to create a horizontal scrollbar, in order to test whether the (non-inline) widgets stay in place when scrolling to the right";
+</script>
+<p>This demo runs <a href="http://jshint.com">JSHint</a> over the code
+in the editor (which is the script used on this page), and
+inserts <a href="../doc/manual.html#addLineWidget">line widgets</a> to
+display the warnings that JSHint comes up with.</p>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/demo/xmlcomplete.html b/third-party/codemirror-3.15/demo/xmlcomplete.html
new file mode 100644 (file)
index 0000000..007893b
--- /dev/null
@@ -0,0 +1,106 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: XML Autocomplete Demo</title>
+    <link rel="stylesheet" href="../lib/codemirror.css">
+    <script src="../lib/codemirror.js"></script>
+    <script src="../addon/hint/show-hint.js"></script>
+    <link rel="stylesheet" href="../addon/hint/show-hint.css">
+    <script src="../addon/hint/xml-hint.js"></script>
+    <script src="../mode/xml/xml.js"></script>
+    <link rel="stylesheet" href="../doc/docs.css">
+    <style type="text/css">
+      .CodeMirror { border: 1px solid #eee; }
+    </style>
+  </head>
+  <body>
+    <h1>CodeMirror: XML Autocomplete demo</h1>
+
+    <form><textarea id="code" name="code"><!-- write some xml below -->
+</textarea></form>
+
+    <p>Press <strong>ctrl-space</strong>, or type a '<' character to
+    activate autocompletion. This demo defines a simple schema that
+    guides completion. The schema can be customized—see
+    the <a href="../doc/manual.html#addon_xml-hint">manual</a>.</p>
+
+    <p>Development of the <code>xml-hint</code> addon was kindly
+    sponsored
+    by <a href="http://www.xperiment.mobi">www.xperiment.mobi</a>.</p>
+
+    <script>
+      var dummy = {
+        attrs: {
+          color: ["red", "green", "blue", "purple", "white", "black", "yellow"],
+          size: ["large", "medium", "small"],
+          description: null
+        },
+        children: []
+      };
+
+      var tags = {
+        "!top": ["top"],
+        top: {
+          attrs: {
+            lang: ["en", "de", "fr", "nl"],
+            freeform: null
+          },
+          children: ["animal", "plant"]
+        },
+        animal: {
+          attrs: {
+            name: null,
+            isduck: ["yes", "no"]
+          },
+          children: ["wings", "feet", "body", "head", "tail"]
+        },
+        plant: {
+          attrs: {name: null},
+          children: ["leaves", "stem", "flowers"]
+        },
+        wings: dummy, feet: dummy, body: dummy, head: dummy, tail: dummy,
+        leaves: dummy, stem: dummy, flowers: dummy
+      };
+
+      function completeAfter(cm, pred) {
+        var cur = cm.getCursor();
+        if (!pred || pred()) setTimeout(function() {
+          if (!cm.state.completionActive)
+            CodeMirror.showHint(cm, CodeMirror.hint.xml, {schemaInfo: tags, completeSingle: false});
+        }, 100);
+        return CodeMirror.Pass;
+      }
+
+      function completeIfAfterLt(cm) {
+        return completeAfter(cm, function() {
+          var cur = cm.getCursor();
+          return cm.getRange(CodeMirror.Pos(cur.line, cur.ch - 1), cur) == "<";
+        });
+      }
+
+      function completeIfInTag(cm) {
+        return completeAfter(cm, function() {
+          var tok = cm.getTokenAt(cm.getCursor());
+          if (tok.type == "string" && (!/['"]/.test(tok.string.charAt(tok.string.length - 1)) || tok.string.length == 1)) return false;
+          var inner = CodeMirror.innerMode(cm.getMode(), tok.state).state;
+          return inner.tagName;
+        });
+      }
+
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        mode: "xml",
+        lineNumbers: true,
+        extraKeys: {
+          "'<'": completeAfter,
+          "'/'": completeIfAfterLt,
+          "' '": completeIfInTag,
+          "'='": completeIfInTag,
+          "Ctrl-Space": function(cm) {
+            CodeMirror.showHint(cm, CodeMirror.hint.xml, {schemaInfo: tags});
+          }
+        }
+      });
+    </script>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/doc/baboon.png b/third-party/codemirror-3.15/doc/baboon.png
new file mode 100644 (file)
index 0000000..55d97f7
Binary files /dev/null and b/third-party/codemirror-3.15/doc/baboon.png differ
diff --git a/third-party/codemirror-3.15/doc/baboon_vector.svg b/third-party/codemirror-3.15/doc/baboon_vector.svg
new file mode 100644 (file)
index 0000000..dc1667a
--- /dev/null
@@ -0,0 +1,153 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<!-- Created with Inkscape (http://www.inkscape.org/) -->
+
+<svg
+   xmlns:dc="http://purl.org/dc/elements/1.1/"
+   xmlns:cc="http://creativecommons.org/ns#"
+   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+   xmlns:svg="http://www.w3.org/2000/svg"
+   xmlns="http://www.w3.org/2000/svg"
+   xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
+   xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
+   id="svg3181"
+   version="1.1"
+   inkscape:version="0.48.0 r9654"
+   width="1750"
+   height="960"
+   xml:space="preserve"
+   sodipodi:docname="baboon_vector.svg"><metadata
+     id="metadata3187"><rdf:RDF><cc:Work
+         rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
+           rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title></dc:title></cc:Work></rdf:RDF></metadata><defs
+     id="defs3185"><clipPath
+       clipPathUnits="userSpaceOnUse"
+       id="clipPath3195"><path
+         d="M 0,768 1400,768 1400,0 0,0 0,768 z"
+         id="path3197" /></clipPath><clipPath
+       clipPathUnits="userSpaceOnUse"
+       id="clipPath3215"><path
+         d="M 0,768 1400,768 1400,0 0,0 0,768 z"
+         id="path3217" /></clipPath></defs><sodipodi:namedview
+     pagecolor="#ffffff"
+     bordercolor="#666666"
+     borderopacity="1"
+     objecttolerance="10"
+     gridtolerance="10"
+     guidetolerance="10"
+     inkscape:pageopacity="0"
+     inkscape:pageshadow="2"
+     inkscape:window-width="1440"
+     inkscape:window-height="851"
+     id="namedview3183"
+     showgrid="false"
+     inkscape:zoom="0.20550291"
+     inkscape:cx="1534.1667"
+     inkscape:cy="795.78156"
+     inkscape:window-x="0"
+     inkscape:window-y="0"
+     inkscape:window-maximized="1"
+     inkscape:current-layer="g3189" /><g
+     id="g3189"
+     inkscape:groupmode="layer"
+     inkscape:label="baboon_vector"
+     transform="matrix(1.25,0,0,-1.25,0,960)"><g
+       id="g3191"><g
+         id="g3193"
+         clip-path="url(#clipPath3195)"><g
+           id="g3199"
+           transform="translate(458.9561,569.9678)"><path
+             d="m 0,0 59.835,69.355 87.034,26.518 133.949,-7.479 c 0,0 74.116,-32.639 74.795,-34.678 0.68,-2.04 84.314,-59.155 84.314,-59.155 l 12.238,-74.795 5.439,-97.912 -13.598,-25.159 -4.76,-40.797 -18.358,-23.118 24.39,-5.561 0.501,-5.192 -14.012,-60.641 16.477,-93.368 7.223,-49.972 -208.295,-51.754 -18.552,4.005 -37.468,8.325 -10.036,4.036 -66.885,10.101 c 0,0 -14.959,74.793 -16.999,73.433 -2.039,-1.359 -42.836,56.437 -42.836,56.437 l -19.719,65.274 12.48,74.571 -7.961,9.643 -26.479,16.187 -12.716,38.309 4.08,48.277 8.769,38.985 L 6.608,-74.308 0,0 z"
+             style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none"
+             id="path3201" /></g><g
+           id="g3203"
+           transform="translate(78.8657,682.1582)"><path
+             d="M 0,0 142.789,40.797 259.74,52.355 313.457,-232.543 204.665,-291.698 78.194,-293.738 0,0 z"
+             style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none"
+             id="path3205" /></g><g
+           id="g3207"
+           transform="translate(269.5122,345.2344)"><path
+             d="M 0,0 18.801,-74.425 40.728,-85.408 59.539,-59.541 40.259,13.503 36.821,15.669 0,0 z"
+             style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none"
+             id="path3209" /></g></g></g><g
+       id="g3223"
+       transform="translate(741.918,109.0332)"><path
+         d="m 0,0 -17.236,-9.401 -16.452,-22.721 -0.783,12.537 6.268,17.234 13.317,6.268 L 0,7.833 14.884,3.917 0,0 z m 172.622,-21.824 c -0.031,0.271 -0.081,0.535 -0.117,0.804 -20.85,7.653 -49.59,7.327 -66.874,10.927 -13.849,2.886 -23.047,9.119 -27.032,12.298 -9.863,-8.494 -12.025,-14.377 -12.025,-14.377 0,0 -9.816,15.309 -30.17,25.76 -7.05,3.621 -17.767,5.691 -29.341,5.691 -24.297,0 -52.384,-9.155 -58.339,-32.223 -10.458,-40.511 9.697,-76.594 49.814,-77.623 1.325,-0.034 2.623,-0.12 3.894,-0.12 36.131,0 48.855,8.572 58.323,15.478 0.027,0.021 0.104,0 0.104,0 0,0 25.126,-11.506 53.529,-11.506 4.419,0 9.156,0.415 14.249,1.063 31.641,4.018 47.989,28.124 43.985,63.828"
+         style="fill:#df0019;fill-opacity:1;fill-rule:nonzero;stroke:none"
+         id="path3225"
+         inkscape:connector-curvature="0" /></g><g
+       id="g3227"
+       transform="translate(300.8481,270.0254)"><path
+         d="m 0,0 c -3.063,-0.691 -12.535,0.784 -12.535,0.784 l 6.267,-25.853 43.481,13.319 -9.01,27.418 C 28.203,15.668 7.867,1.777 0,0"
+         style="fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
+         id="path3229"
+         inkscape:connector-curvature="0" /></g><g
+       id="g3231"
+       transform="translate(211.66052,615.85984)"><path
+         d="m 0,0 -16.243,-2.871 -15.462,-9.4 4.323,-10.938 14.568,9.89 L 2.75,-8.771 0,0 z"
+         style="fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
+         id="path3233"
+         inkscape:connector-curvature="0" /></g><g
+       id="g3235"
+       transform="translate(274.15732,626.4084)"><path
+         d="m 0,0 -15.64,0.407 -14.279,-3.608 2.008,-9.747 14.756,4.208 L 1.111,-8.215 0,0 z"
+         style="fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
+         id="path3237"
+         inkscape:connector-curvature="0" /></g><path
+       style="fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
+       d="M 436.65625 22.28125 C 436.65625 22.28125 338.18375 25.385 251 42.8125 C 163.24875 60.35375 70.40625 99.65625 70.40625 99.65625 L 175.1875 495.28125 L 327.96875 492.34375 L 337.75 527.59375 C 337.75 527.59375 365.095 523.25875 373 518.78125 C 376.31375 516.90375 383.78125 508 383.78125 508 L 377.75 484.65625 L 504.21875 407.15625 L 436.65625 22.28125 z M 410.53125 55.1875 L 465.6875 393.3125 L 346.59375 456.625 L 202.75 466.46875 L 112 114.40625 L 263 79.1875 L 410.53125 55.1875 z "
+       transform="matrix(0.8,0,0,-0.8,0,768)"
+       id="path3253" /><g
+       id="g3247"
+       transform="matrix(1.199238,-0.02879331,0.02673084,1.0520756,172.41935,498.37339)"><path
+         d="m 0,0 c 0,0 -1.861,1.481 -9.143,-1.457 9.712,18.867 9.439,39.989 9.439,39.989 0,0 -3.106,-2.465 -11.311,-8.47 9.241,23.044 5.338,72.525 5.338,72.525 0,0 -17.493,40.746 -13.657,45.799 8.841,11.65 23.834,23.968 44.295,25.594 17.935,1.424 44.606,-4.953 55.865,-15.284 4.536,-4.161 23.367,-47.493 23.367,-47.493 0,0 6.104,-35.271 11.619,-54.108 5.513,-18.839 11.054,-26.674 21.284,-34.825 17.831,-14.207 27.076,-29.938 27.076,-29.938 L 143.399,3.945 c 3.655,-17.356 14.875,-34.28 27.39,-47.672 -12.863,1.507 -19.61,8.783 -19.61,8.783 0,0 2.151,-12.664 9.109,-26.554 l 28.712,15.264 -1.762,10.805 c -5.128,9.304 -9.336,15.534 -9.336,15.534 0,0 2.089,0.956 7.385,-3.572 l -2.005,12.296 c -4.814,9.391 -11.773,16.752 -25.115,31.113 5.944,-6.087 15.438,-5.379 20.751,-4.356 l -0.572,3.512 c -2.231,1.278 -5.494,3.171 -10.241,5.957 -12.43,7.299 -22.326,21.049 -22.326,21.049 0,0 12.85,1.815 20.513,11.022 -7.316,-2.641 -18.585,0.799 -18.585,0.799 -17.086,6.772 -15.022,30.217 -17.687,50.587 -2.667,20.37 -9.299,34.125 -9.299,34.125 0,0 -0.243,2.149 11.91,-5.906 -7.744,33.215 -35.545,44.94 -35.545,44.94 0,0 2.223,2.79 22.843,0.044 -16.469,15.817 -32.303,16.896 -32.303,16.896 0,0 10.077,2.25 23.611,0.24 0,0 -3.327,3.508 -7.549,6.453 L 35.985,194.291 -77.543,167.815 -8.211,-101.17 17.481,-99.413 C 8.602,-85.114 -0.371,-63.837 -2.15,-40.857 -4.911,-5.208 0,0 0,0"
+         style="fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
+         id="path3249"
+         inkscape:connector-curvature="0" /></g><g
+       id="g3255"
+       transform="translate(204.22134,580.88353)"><path
+         d="m 0,0 c 0,-1.418 0.43,-2.736 1.168,-3.83 1.523,0.677 3.551,1.094 5.786,1.094 2.164,0 4.133,-0.39 5.639,-1.029 0.711,1.081 1.129,2.374 1.129,3.765 0,3.79 -3.072,6.861 -6.861,6.861 C 3.071,6.861 0,3.79 0,0"
+         style="fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
+         id="path3257"
+         inkscape:connector-curvature="0" /></g><g
+       id="g3259"
+       transform="translate(256.3311,595.31646)"><path
+         d="m 0,0 c 0,-1.418 0.43,-2.736 1.168,-3.83 1.524,0.677 3.552,1.094 5.787,1.094 2.163,0 4.132,-0.39 5.638,-1.029 0.712,1.081 1.129,2.373 1.129,3.765 0,3.79 -3.072,6.861 -6.861,6.861 C 3.071,6.861 0,3.79 0,0"
+         style="fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
+         id="path3261"
+         inkscape:connector-curvature="0" /></g><g
+       id="g4174"
+       transform="matrix(0.99694509,0.07810563,-0.07810563,0.99694509,47.348748,-15.348299)"><g
+         transform="translate(222.5098,610.1558)"
+         id="g3219"><path
+           inkscape:connector-curvature="0"
+           id="path3221"
+           style="fill:#df0019;fill-opacity:1;fill-rule:nonzero;stroke:none"
+           d="m 0,0 4.45,2.752 5.34,3.785 7.05,-8.226 7.093,-33.359 17.801,-51.259 13.86,-30.215 26.261,-1.55 -6.685,-35.653 c 0,0 -49.98,-21.871 -49.545,-21.911 -42.657,4.001 -12.553,43.066 -8.631,47.301 L 3.666,-47.869 0,0 z" /></g><g
+         transform="translate(247.626,467.3545)"
+         id="g3239"><path
+           inkscape:connector-curvature="0"
+           id="path3241"
+           style="fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
+           d="M 0,0 C -3.044,-0.345 -5.232,-3.092 -4.888,-6.136 -4.543,-9.18 1.576,-2.254 13.308,-4.961 13.971,-1.97 3.044,0.344 0,0" /></g><g
+         transform="translate(279.4419,476.5762)"
+         id="g3243"><path
+           inkscape:connector-curvature="0"
+           id="path3245"
+           style="fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
+           d="M 0,0 C 3.271,1.08 6.798,-0.697 7.88,-3.969 8.96,-7.24 -0.55,-3.044 -11.258,-11.329 -13.345,-8.586 -3.272,-1.081 0,0" /></g><g
+         transform="translate(284.1929,525.9082)"
+         id="g3263"><path
+           inkscape:connector-curvature="0"
+           id="path3265"
+           style="fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
+           d="M 0,0 C 0,0 -6.972,28.671 -6.972,29.355 L 1.585,2.864 9.999,-10.564 13.634,-32.697 7.922,-11.098 0,0 z M -0.633,-15.036 -9.19,-4.86 -16.478,25.776 c -0.202,0.684 9.106,-28.811 9.106,-28.811 l 8.64,-11.642 2.469,-17.336 -4.37,16.977 z m -6.339,-6.085 -10.457,16.826 -5.444,28.646 6.614,-27.842 11.311,-18.026 1.413,-9.583 -3.437,9.979 z m -53.462,-13.246 -1.437,24.944 -2.682,28.754 5.106,-29.895 1.212,-21.677 4.139,-18.236 -6.338,16.11 z m -4.265,-19.55 -6.665,15.516 0.404,29.205 -0.882,28.169 3.104,-28.396 0.808,-26.697 4.242,-15.972 2.423,-6.617 -3.434,4.792 z m -9.695,-2.967 -7.117,16.885 1.318,32.01 0,25.223 2.115,-25.061 -0.581,-31.259 5.869,-16.429 5.056,-8.671 -6.66,7.302 z m 103.144,-7.97 -6.676,20.38 2.141,11.54 L 16.499,-9.376 4.557,13.104 -5.879,53.97 c 0,0 -8.325,-7.41 -16.781,-8.08 -8.455,-0.671 -15.09,4.018 -15.09,4.018 0,0 3.592,-17.761 8.659,-37.597 5.069,-19.836 17.528,-44.866 17.528,-44.866 0,0 21.578,-8.197 24.302,-16.587 2.724,-8.391 -3.508,-22.911 -14.102,-26.551 -10.593,-3.64 -32.284,-8.262 -32.284,-8.262 0,0 -19,1.512 -20.438,14.26 0,0 4.131,16.406 10.418,19.225 6.285,2.819 21.362,11.174 21.362,11.174 l -8.254,1.332 -7.664,-1.332 c 0,0 -4.784,11.295 -10.973,35.086 -6.19,23.79 -8.967,42.485 -8.967,42.485 0,0 -3.912,-4.391 -14.199,-4.885 -10.286,-0.494 -16.031,7.988 -16.031,7.988 l 1.027,-30.185 -1.049,-25.83 -0.15,-29.22 5.102,-15.99 19.818,-30.448 c 0,0 14.102,-9.293 31.728,-9.293 16.453,1.328 51.131,18.047 51.131,18.047 l 9.536,16.687 z" /></g></g><g
+       id="g3267"
+       transform="translate(847.2637,321.5059)"><path
+         d="m 0,0 c 2.252,3.516 6.693,15.3 6.693,15.3 0,0 3.778,-13.306 1.912,-17.213 -3.056,-6.404 -23.905,-15.3 -23.905,-15.3 0,0 12.196,12.364 15.3,17.213 m -33.514,23.16 -0.757,56.352 c 0,0 11.136,-14.028 11.843,-19.739 1.176,-9.491 -11.086,-36.613 -11.086,-36.613 m -17.575,236.921 c 0,0 12.453,-15.338 14.854,-21.39 1.424,-3.591 2.286,-15.287 2.286,-15.287 l -17.14,36.677 z M -98.574,-86.136 c -9.757,-0.906 -29.836,1.016 -38.912,4.708 -7.499,3.05 -25.734,19.656 -25.734,19.656 l 24.187,-10.86 -4.701,17.627 15.272,-22.009 41.813,-5.356 c 0,0 -8.812,-3.477 -11.925,-3.766 m -74.428,157.941 c -4.518,10.057 -1.763,44.065 -1.763,44.065 0,0 7.544,-31.093 12.338,-40.541 6.978,-13.754 37.015,-49.352 37.015,-49.352 0,0 -40.824,30.759 -47.59,45.828 m -17.833,-149.47 -40.407,24.724 1.636,-17.575 0.026,-0.035 -5.178,-29.811 -2.056,-10.701 0.383,-33.34 -4.982,36.406 6.41,41.45 -11.063,8.338 -17.532,43.159 23.502,-38.779 2.351,14.101 40.634,-25.695 11.924,-5.651 13.809,-28.871 -19.457,22.28 z m -85.522,138.863 17.212,-34.424 c 0,0 -12.972,11.185 -15.299,16.257 -1.905,4.152 -1.913,18.167 -1.913,18.167 m -2.367,66.042 c 0,0 -6.206,15.581 -6.323,21.082 -0.168,7.817 4.568,23.148 7.695,30.315 0.755,1.73 4.103,6.341 4.103,6.341 0,0 -4.654,-24.542 -5.347,-32.829 -0.518,-6.205 -0.128,-24.909 -0.128,-24.909 m -7.195,-114.809 c -0.334,3.363 1.912,13.387 1.912,13.387 l 3.825,-29.643 c 0,0 -5.313,11.967 -5.737,16.256 m -20.082,53.549 c -1.394,3.571 -0.956,15.301 -0.956,15.301 l 13.388,-30.6 c 0,0 -10.639,10.71 -12.432,15.299 m -6.03,106.795 c 0,0 -0.315,35.831 4.637,46.379 4.531,9.647 29.936,30.356 29.936,30.356 0,0 -17.824,-22.47 -21.503,-31.2 -5.089,-12.077 -10.119,-51.437 -10.119,-51.437 l -2.951,5.902 z M 50.121,205.01 c 3.335,-9.155 1.168,-38.956 1.168,-38.956 0,0 -5.451,29.987 -9.221,39.366 -4.214,10.487 -23.014,38.907 -23.014,38.907 0,0 26.78,-27.546 31.067,-39.317 M 54.506,95.624 c 0,0 6.884,-18.586 5.738,-24.861 -0.773,-4.241 -9.562,-14.345 -9.562,-14.345 0,0 2.414,12.874 2.868,17.212 0.573,5.474 0.956,21.994 0.956,21.994 M 19.125,-13.389 c 0,0 9.656,22.183 11.062,30.068 1.235,6.941 0,28.203 0,28.203 0,0 8.477,-22.819 7.106,-30.538 C 35.845,6.183 19.125,-13.389 19.125,-13.389 m 441.487,-40.965 c -3.249,8.935 -6.587,17.23 -10.01,24.928 l -1.862,28.873 -8.857,-4.876 -25.862,49.457 -4.828,-10.34 c -32.69,31.48 -70.457,34.284 -111.982,31.646 -65.568,-4.163 -91.587,-41.63 -79.098,-57.241 12.49,-15.613 18.733,-5.205 40.589,5.203 21.858,10.407 74.937,26.017 110.323,-2.082 35.386,-28.1 86.383,-109.281 50.997,-169.646 -35.386,-60.365 -105.626,-105.385 -182.135,-88.465 -86.422,19.112 -126.078,60.082 -177.675,74.811 -8.311,1.334 -18.347,2.789 -24.791,3.191 -12.671,0.792 -21.6,14.727 -21.6,14.727 l 17.181,-9.327 25.763,-2.36 c 2.331,14 9.395,49.054 9.395,49.054 l -8.688,87.29 -18.668,-27.06 -7.246,10.184 -21.349,-22.915 -15.473,-1.959 14.67,6.596 21.38,29.409 6.7,-13.754 19.485,24.691 0.004,-0.011 16.47,9.525 -3.123,68.69 10.407,-10.407 -4.163,40.59 22.173,71.502 -34.662,91.899 16.652,-4.162 -19.773,35.386 -40.591,38.509 9.368,17.693 -93.671,9.368 -20.229,-7.165 -18.437,38.292 13.22,8.813 -69.039,14.69 2.938,19.095 -80.791,-23.303 -26.147,-19.191 -116.339,0 8.814,-10.188 -42.501,-40.641 -8.911,-78.491 7.344,-1.494 8.814,-45.548 23.502,-24.978 19.096,45.533 -14.689,-4.409 41.13,48.474 30.848,26.44 -14.69,-1.469 19.096,16.158 105.763,2.938 72.917,15.799 -41.623,-14.742 -30.181,-7.285 -104.079,-1.043 1.04,-11.449 -64.526,-61.403 14.571,2.081 -27.844,-63.28 c -15.017,-13.719 -28.06,-55.016 -36.687,-75.145 -9.367,-21.856 -20.816,-39.55 -20.816,-39.55 0,0 -30.182,-6.244 -61.405,-18.734 -31.224,-12.489 -43.713,4.163 -43.713,4.163 l -3.122,-8.326 c 0,0 -18.28,-9.057 -39.303,-11.825 -16.43,-2.162 -9.967,-20.946 -9.613,-26.684 0.405,-6.57 4.294,-19.774 8.325,-24.978 3.227,-4.165 12.525,-10.425 17.694,-11.448 12.039,-2.385 28.101,5.204 45.794,17.693 74.936,-6.245 103.241,-10.321 126.974,8.326 14.572,11.448 29.142,22.897 41.631,40.59 l -15.611,42.671 -8.327,-14.569 -5.807,44.931 1.841,17.863 5.547,-51.234 7.789,9.257 35.387,-70.772 11.448,4.164 c 0,0 13.515,-18.583 23.057,-32.881 l -26.02,25.006 -10.224,-5.964 -11.076,22.152 c 0,0 -13.383,-2.353 -24.727,-18.027 -15.862,-21.915 -23.503,-24.678 -17.627,-78.735 5.876,-54.055 16.452,-54.055 64.632,-121.039 11.752,-16.452 14.601,-18.465 14.601,-18.465 l -51.03,-27.365 -22.327,-5.876 -21.384,-11.28 c 0,0 4.744,-8.174 7.495,-9.369 4.739,-2.062 20.613,1.56 20.613,1.56 0,0 15.603,-6.763 36.756,-6.763 21.152,0 32.903,8.225 47.005,8.225 14.101,0 38.78,-8.225 57.582,-5.876 18.802,2.351 22.328,12.927 22.328,12.927 l -51.706,54.057 -4.675,47.096 -56.605,75.769 -3.038,9.437 65.791,-82.24 5.107,-46.75 55.161,-61.405 37.468,-8.325 c 0,0 -0.257,1.226 -0.625,3.114 -6.146,15.664 -6.986,34.894 -1.999,54.214 6.975,27.012 38.85,36.596 64.029,36.596 12.506,0 24.179,-2.312 32.025,-6.341 12.912,-6.63 21.851,-15.076 27.029,-20.917 3.673,4.516 7.133,7.194 11.833,11.11 0,0 12.143,-11.751 45.047,-14.101 27.14,-1.939 45.048,-8.226 70.901,-19.585 53.676,-23.584 102.5,-61.785 207.618,-45.132 105.119,16.651 206.073,113.444 164.442,227.929"
+         style="fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
+         id="path3269"
+         inkscape:connector-curvature="0" /></g><path
+       inkscape:connector-curvature="0"
+       style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none"
+       d="m 329.26398,723.3082 -118.025,-19.2 -120.800003,-28.175 72.600003,-281.65 115.075,7.875 95.275,50.65 -44.125,270.5 z m -6.55,-10.575 40.675,-252.4 -87.85,-47.275 -106.125,-7.325 -66.95,262.8 111.4,26.275 108.85,17.925 z"
+       id="path3253-3" /></g></svg>
\ No newline at end of file
diff --git a/third-party/codemirror-3.15/doc/compress.html b/third-party/codemirror-3.15/doc/compress.html
new file mode 100644 (file)
index 0000000..864f4f2
--- /dev/null
@@ -0,0 +1,214 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8"/>
+    <title>CodeMirror: Compression Helper</title>
+    <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Droid+Sans|Droid+Sans:bold"/>
+    <link rel="stylesheet" type="text/css" href="docs.css"/>
+  </head>
+  <body>
+
+<h1><span class="logo-braces">{ }</span> <a href="http://codemirror.net/">CodeMirror</a></h1>
+
+<div class="grey">
+<img src="baboon.png" class="logo" alt="logo"/>
+<pre>
+/* Script compression
+   helper */
+</pre>
+</div>
+
+    <p>To optimize loading CodeMirror, especially when including a
+    bunch of different modes, it is recommended that you combine and
+    minify (and preferably also gzip) the scripts. This page makes
+    those first two steps very easy. Simply select the version and
+    scripts you need in the form below, and
+    click <strong>Compress</strong> to download the minified script
+    file.</p>
+
+    <form id="form" action="http://marijnhaverbeke.nl/uglifyjs" method="post">
+      <input type="hidden" id="download" name="download" value="codemirror-compressed.js"/>
+      <p>Version: <select id="version" onchange="setVersion(this);" style="padding: 1px">
+        <option value="http://codemirror.net/">HEAD</option>
+        <option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=3.15.0;f=">3.15</option>
+        <option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=3.14.0;f=">3.14</option>
+        <option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=3.13.0;f=">3.13</option>
+        <option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v3.12;f=">3.12</option>
+        <option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v3.11;f=">3.11</option>
+        <option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v3.1;f=">3.1</option>
+        <option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v3.02;f=">3.02</option>
+        <option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v3.01;f=">3.01</option>
+        <option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v3.0;f=">3.0</option>
+        <option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.38;f=">2.38</option>
+        <option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.37;f=">2.37</option>
+        <option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.36;f=">2.36</option>
+        <option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.35;f=">2.35</option>
+        <option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.34;f=">2.34</option>
+        <option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.33;f=">2.33</option>
+        <option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.32;f=">2.32</option>
+        <option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.31;f=">2.31</option>
+        <option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.3;f=">2.3</option>
+        <option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.25;f=">2.25</option>
+        <option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.24;f=">2.24</option>
+        <option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.23;f=">2.23</option>
+        <option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.22;f=">2.22</option>
+        <option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.21;f=">2.21</option>
+        <option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.2;f=">2.2</option>
+        <option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.18;f=">2.18</option>
+        <option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.16;f=">2.16</option>
+        <option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.15;f=">2.15</option>
+        <option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.13;f=">2.13</option>
+        <option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.12;f=">2.12</option>
+        <option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.11;f=">2.11</option>
+        <option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.1;f=">2.1</option>
+        <option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.02;f=">2.02</option>
+        <option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.01;f=">2.01</option>
+        <option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.0;f=">2.0</option>
+        <option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=beta2;f=">beta2</option>
+        <option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=beta1;f=">beta1</option>
+      </select></p>
+
+      <select multiple="multiple" size="20" name="code_url" style="width: 40em;" class="field" id="files">
+        <optgroup label="CodeMirror Library">
+          <option value="http://codemirror.net/lib/codemirror.js" selected>codemirror.js</option>
+        </optgroup>
+        <optgroup label="Modes">
+          <option value="http://codemirror.net/mode/apl/apl.js">apl.js</option>
+          <option value="http://codemirror.net/mode/clike/clike.js">clike.js</option>
+          <option value="http://codemirror.net/mode/clojure/clojure.js">clojure.js</option>
+          <option value="http://codemirror.net/mode/cobol/cobol.js">cobol.js</option>
+          <option value="http://codemirror.net/mode/coffeescript/coffeescript.js">coffeescript.js</option>
+          <option value="http://codemirror.net/mode/commonlisp/commonlisp.js">commonlisp.js</option>
+          <option value="http://codemirror.net/mode/css/css.js">css.js</option>
+          <option value="http://codemirror.net/mode/d/d.js">d.js</option>
+          <option value="http://codemirror.net/mode/diff/diff.js">diff.js</option>
+          <option value="http://codemirror.net/mode/ecl/ecl.js">ecl.js</option>
+          <option value="http://codemirror.net/mode/erlang/erlang.js">erlang.js</option>
+          <option value="http://codemirror.net/mode/gfm/gfm.js">gfm.js</option>
+          <option value="http://codemirror.net/mode/gas/gas.js">gas.js</option>
+          <option value="http://codemirror.net/mode/go/go.js">go.js</option>
+          <option value="http://codemirror.net/mode/groovy/groovy.js">groovy.js</option>
+          <option value="http://codemirror.net/mode/haml/haml.js">haml.js</option>
+          <option value="http://codemirror.net/mode/haskell/haskell.js">haskell.js</option>
+          <option value="http://codemirror.net/mode/haxe/haxe.js">haxe.js</option>
+          <option value="http://codemirror.net/mode/htmlembedded/htmlembedded.js">htmlembedded.js</option>
+          <option value="http://codemirror.net/mode/htmlmixed/htmlmixed.js">htmlmixed.js</option>
+          <option value="http://codemirror.net/mode/http/http.js">http.js</option>
+          <option value="http://codemirror.net/mode/jade/jade.js">jade.js</option>
+          <option value="http://codemirror.net/mode/javascript/javascript.js">javascript.js</option>
+          <option value="http://codemirror.net/mode/jinja2/jinja2.js">jinja2.js</option>
+          <option value="http://codemirror.net/mode/less/less.js">less.js</option>
+          <option value="http://codemirror.net/mode/livescript/livescript.js">livescript.js</option>
+          <option value="http://codemirror.net/mode/lua/lua.js">lua.js</option>
+          <option value="http://codemirror.net/mode/markdown/markdown.js">markdown.js</option>
+          <option value="http://codemirror.net/mode/mirc/mirc.js">mirc.js</option>
+          <option value="http://codemirror.net/mode/nginx/nginx.js">nginx.js</option>
+          <option value="http://codemirror.net/mode/ntriples/ntriples.js">ntriples.js</option>
+          <option value="http://codemirror.net/mode/ocaml/ocaml.js">ocaml.js</option>
+          <option value="http://codemirror.net/mode/pascal/pascal.js">pascal.js</option>
+          <option value="http://codemirror.net/mode/perl/perl.js">perl.js</option>
+          <option value="http://codemirror.net/mode/php/php.js">php.js</option>
+          <option value="http://codemirror.net/mode/pig/pig.js">pig.js</option>
+          <option value="http://codemirror.net/mode/properties/properties.js">properties.js</option>
+          <option value="http://codemirror.net/mode/python/python.js">python.js</option>
+          <option value="http://codemirror.net/mode/q/q.js">q.js</option>
+          <option value="http://codemirror.net/mode/r/r.js">r.js</option>
+          <option value="http://codemirror.net/mode/rpm/changes/changes.js">rpm/changes.js</option>
+          <option value="http://codemirror.net/mode/rpm/spec/spec.js">rpm/spec.js</option>
+          <option value="http://codemirror.net/mode/rst/rst.js">rst.js</option>
+          <option value="http://codemirror.net/mode/ruby/ruby.js">ruby.js</option>
+          <option value="http://codemirror.net/mode/rust/rust.js">rust.js</option>
+          <option value="http://codemirror.net/mode/sass/sass.js">sass.js</option>
+          <option value="http://codemirror.net/mode/scala/scala.js">scala.js</option>
+          <option value="http://codemirror.net/mode/scheme/scheme.js">scheme.js</option>
+          <option value="http://codemirror.net/mode/shell/shell.js">shell.js</option>
+          <option value="http://codemirror.net/mode/sieve/sieve.js">sieve.js</option>
+          <option value="http://codemirror.net/mode/smalltalk/smalltalk.js">smalltalk.js</option>
+          <option value="http://codemirror.net/mode/smarty/smarty.js">smarty.js</option>
+          <option value="http://codemirror.net/mode/smartymixed/smartymixed.js">smartymixed.js</option>
+          <option value="http://codemirror.net/mode/sql/sql.js">sql.js</option>
+          <option value="http://codemirror.net/mode/sparql/sparql.js">sparql.js</option>
+          <option value="http://codemirror.net/mode/stex/stex.js">stex.js</option>
+          <option value="http://codemirror.net/mode/tcl/tcl.js">tcl.js</option>
+          <option value="http://codemirror.net/mode/tiddlywiki/tiddlywiki.js">tiddlywiki.js</option>
+          <option value="http://codemirror.net/mode/tiki/tiki.js">tiki.js</option>
+          <option value="http://codemirror.net/mode/turtle/turtle.js">turtle.js</option>
+          <option value="http://codemirror.net/mode/vb/vb.js">vb.js</option>
+          <option value="http://codemirror.net/mode/vbscript/vbscript.js">vbscript.js</option>
+          <option value="http://codemirror.net/mode/velocity/velocity.js">velocity.js</option>
+          <option value="http://codemirror.net/mode/verilog/verilog.js">verilog.js</option>
+          <option value="http://codemirror.net/mode/xml/xml.js">xml.js</option>
+          <option value="http://codemirror.net/mode/xquery/xquery.js">xquery.js</option>
+          <option value="http://codemirror.net/mode/yaml/yaml.js">yaml.js</option>
+          <option value="http://codemirror.net/mode/z80/z80.js">z80.js</option>
+        </optgroup>
+        <optgroup label="Add-ons">
+          <option value="http://codemirror.net/addon/selection/active-line.js">active-line.js</option>
+          <option value="http://codemirror.net/addon/fold/brace-fold.js">brace-fold.js</option>
+          <option value="http://codemirror.net/addon/edit/closebrackets.js">closebrackets.js</option>
+          <option value="http://codemirror.net/addon/edit/closetag.js">closetag.js</option>
+          <option value="http://codemirror.net/addon/runmode/colorize.js">colorize.js</option>
+          <option value="http://codemirror.net/addon/edit/comment.js">comment.js</option>
+          <option value="http://codemirror.net/addon/edit/continuecomment.js">continuecomment.js</option>
+          <option value="http://codemirror.net/addon/edit/continuelist.js">continuelist.js</option>
+          <option value="http://codemirror.net/addon/dialog/dialog.js">dialog.js</option>
+          <option value="http://codemirror.net/addon/fold/foldcode.js">foldcode.js</option>
+          <option value="http://codemirror.net/addon/hint/html-hint.js">html-hint.js</option>
+          <option value="http://codemirror.net/addon/fold/indent-fold.js">indent-fold.js</option>
+          <option value="http://codemirror.net/addon/hint/javascript-hint.js">javascript-hint.js</option>
+          <option value="http://codemirror.net/addon/lint/javascript-lint.js">javascript-lint.js</option>
+          <option value="http://codemirror.net/addon/lint/json-lint.js">json-lint.js</option>
+          <option value="http://codemirror.net/addon/lint/lint.js">lint.js</option>
+          <option value="http://codemirror.net/addon/mode/loadmode.js">loadmode.js</option>
+          <option value="http://codemirror.net/addon/selection/mark-selection.js">mark-selection.js</option>
+          <option value="http://codemirror.net/addon/search/match-highlighter.js">match-highlighter.js</option>
+          <option value="http://codemirror.net/addon/edit/matchbrackets.js">matchbrackets.js</option>
+          <option value="http://codemirror.net/addon/edit/matchtags.js">matchtags.js</option>
+          <option value="http://codemirror.net/addon/merge/merge.js">merge.js</option>
+          <option value="http://codemirror.net/addon/mode/multiplex.js">multiplex.js</option>
+          <option value="http://codemirror.net/addon/mode/overlay.js">overlay.js</option>
+          <option value="http://codemirror.net/addon/hint/pig-hint.js">pig-hint.js</option>
+          <option value="http://codemirror.net/addon/display/placeholder.js">placeholder.js</option>
+          <option value="http://codemirror.net/addon/hint/python-hint.js">python-hint.js</option>
+          <option value="http://codemirror.net/addon/runmode/runmode.js">runmode.js</option>
+          <option value="http://codemirror.net/addon/runmode/runmode.node.js">runmode.node.js</option>
+          <option value="http://codemirror.net/addon/runmode/runmode-standalone.js">runmode-standalone.js</option>
+          <option value="http://codemirror.net/addon/search/search.js">search.js</option>
+          <option value="http://codemirror.net/addon/search/searchcursor.js">searchcursor.js</option>
+          <option value="http://codemirror.net/addon/hint/show-hint.js">show-hint.js</option>
+          <option value="http://codemirror.net/addon/edit/trailingspace.js">trailingspace.js</option>
+          <option value="http://codemirror.net/addon/tern/tern.js">tern.js</option>
+          <option value="http://codemirror.net/addon/fold/xml-fold.js">xml-fold.js</option>
+          <option value="http://codemirror.net/addon/hint/xml-hint.js">xml-hint.js</option>
+        </optgroup>
+        <optgroup label="Keymaps">
+          <option value="http://codemirror.net/keymap/emacs.js">emacs.js</option>
+          <option value="http://codemirror.net/keymap/vim.js">vim.js</option>
+        </optgroup>
+      </select>
+
+      <p>
+        <button type="submit">Compress</button> with <a href="http://github.com/mishoo/UglifyJS/">UglifyJS</a>
+      </p>
+
+      <p>Custom code to add to the compressed file:<textarea name="js_code" style="width: 100%; height: 15em;" class="field"></textarea></p>
+    </form>
+
+    <script type="text/javascript">
+      function setVersion(ver) {
+        var urlprefix = ver.options[ver.selectedIndex].value;
+        var select = document.getElementById("files"), m;
+        for (var optgr = select.firstChild; optgr; optgr = optgr.nextSibling)
+          for (var opt = optgr.firstChild; opt; opt = opt.nextSibling) {
+            if (opt.nodeName != "OPTION")
+              continue;
+            else if (m = opt.value.match(/^http:\/\/codemirror.net\/(.*)$/))
+              opt.value = urlprefix + m[1];
+            else if (m = opt.value.match(/http:\/\/marijnhaverbeke.nl\/git\/codemirror\?a=blob_plain;hb=[^;]+;f=(.*)$/))
+              opt.value = urlprefix + m[1];
+          }
+       }
+    </script>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/doc/docs.css b/third-party/codemirror-3.15/doc/docs.css
new file mode 100644 (file)
index 0000000..170cd41
--- /dev/null
@@ -0,0 +1,167 @@
+body {
+  font-family: Droid Sans, Arial, sans-serif;
+  line-height: 1.5;
+  max-width: 64.3em;
+  margin: 3em auto;
+  padding: 0 1em;
+}
+
+h1 {
+  letter-spacing: -3px;
+  font-size: 3.23em;
+  font-weight: bold;
+  margin: 0;
+}
+
+h2 {
+  font-size: 1.23em;
+  font-weight: bold;
+  margin: .5em 0;
+  letter-spacing: -1px;
+}
+
+h3 {
+  font-size: 1.1em;
+  font-weight: bold;
+  margin: .4em 0;
+}
+
+pre {
+  background-color: #eee;
+  -moz-border-radius: 6px;
+  -webkit-border-radius: 6px;
+  border-radius: 6px;
+  padding: 1em;
+}
+
+pre.code {
+  margin: 0 1em;
+}
+
+.grey {
+  background-color: #eee;
+  border-radius: 6px;
+  margin-bottom: 1.65em;
+  margin-top: 0.825em;
+  padding: 0.825em 1.65em;
+  position: relative;
+}
+
+img.logo {
+  position: absolute;
+  right: -1em;
+  bottom: 4px;
+  max-width: 23.6875em; /* Scale image down with text to prevent clipping */
+}
+
+.grey > pre {
+  background:none;
+  border-radius:0;
+  padding:0;
+  margin:0;
+  font-size:2.2em;
+  line-height:1.2em;
+}
+
+a:link, a:visited, .quasilink {
+  color: #df0019;
+  cursor: pointer;
+  text-decoration: none;
+}
+
+a:hover, .quasilink:hover {
+  color: #800004;
+}
+
+h1 a:link, h1 a:visited, h1 a:hover {
+  color: black;
+}
+
+ul {
+  margin: 0;
+  padding-left: 1.2em;
+}
+
+a.download {
+  color: white;
+  background-color: #df0019;
+  width: 100%;
+  display: block;
+  text-align: center;
+  font-size: 1.23em;
+  font-weight: bold;
+  text-decoration: none;
+  -moz-border-radius: 6px;
+  -webkit-border-radius: 6px;
+  border-radius: 6px;
+  padding: .5em 0;
+  margin-bottom: 1em;
+}
+
+a.download:hover {
+  background-color: #bb0010;
+}
+
+.rel {
+  margin-bottom: 0;
+}
+
+.rel-note {
+  color: #777;
+  font-size: .9em;
+  margin-top: .1em;
+}
+
+.logo-braces {
+  color: #df0019;
+  position: relative;
+  top: -4px;
+}
+
+.blk {
+  float: left;
+}
+
+.left {
+  margin-right: 20.68em;
+  max-width: 37em;
+  padding-right: 6.53em;
+  padding-bottom: 1em;
+}
+
+.left1 {
+  width: 15.24em;
+  padding-right: 6.45em;
+}
+
+.left2 {
+  max-width: 15.24em;
+}
+
+.right {
+  width: 20.68em;
+  margin-left: -20.68em;
+}
+
+.leftbig {
+  width: 42.44em;
+  padding-right: 6.53em;
+}
+
+.rightsmall {
+  width: 15.24em;
+}
+
+.clear:after {
+  visibility: hidden;
+  display: block;
+  font-size: 0;
+  content: " ";
+  clear: both;
+  height: 0;
+}
+.clear { display: inline-block; }
+/* start commented backslash hack \*/
+* html .clear { height: 1%; }
+.clear { display: block; }
+/* close commented backslash hack */
diff --git a/third-party/codemirror-3.15/doc/internals.html b/third-party/codemirror-3.15/doc/internals.html
new file mode 100644 (file)
index 0000000..4336ba4
--- /dev/null
@@ -0,0 +1,505 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8"/>
+    <title>CodeMirror: Internals</title>
+    <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Droid+Sans|Droid+Sans:bold"/>
+    <link rel="stylesheet" type="text/css" href="docs.css"/>
+    <style>dl dl {margin: 0;} .update {color: #d40 !important}</style>
+  </head>
+  <body>
+
+<h1><span class="logo-braces">{ }</span> <a href="http://codemirror.net/">CodeMirror</a></h1>
+
+<div class="grey">
+<img src="baboon.png" class="logo" alt="logo"/>
+<pre>
+/* (Re-) Implementing A Syntax-
+   Highlighting Editor in JavaScript */
+</pre>
+</div>
+
+<div class="clear"><div class="leftbig blk">
+
+<p style="font-size: 85%" id="intro">
+  <strong>Topic:</strong> JavaScript, code editor implementation<br>
+  <strong>Author:</strong> Marijn Haverbeke<br>
+  <strong>Date:</strong> March 2nd 2011 (updated November 13th 2011)
+</p>
+
+<p style="padding: 0 3em 0 2em"><strong>Caution</strong>: this text was written briefly after
+version 2 was initially written. It no longer (even including the
+update at the bottom) fully represents the current implementation. I'm
+leaving it here as a historic document. For more up-to-date
+information, look at the entries
+tagged <a href="http://marijnhaverbeke.nl/blog/#cm-internals">cm-internals</a>
+on my blog.</p>
+
+<p>This is a followup to
+my <a href="http://codemirror.net/story.html">Brutal Odyssey to the
+Dark Side of the DOM Tree</a> story. That one describes the
+mind-bending process of implementing (what would become) CodeMirror 1.
+This one describes the internals of CodeMirror 2, a complete rewrite
+and rethink of the old code base. I wanted to give this piece another
+Hunter Thompson copycat subtitle, but somehow that would be out of
+place—the process this time around was one of straightforward
+engineering, requiring no serious mind-bending whatsoever.</p>
+
+<p>So, what is wrong with CodeMirror 1? I'd estimate, by mailing list
+activity and general search-engine presence, that it has been
+integrated into about a thousand systems by now. The most prominent
+one, since a few weeks,
+being <a href="http://googlecode.blogspot.com/2011/01/make-quick-fixes-quicker-on-google.html">Google
+code's project hosting</a>. It works, and it's being used widely.</p>
+
+<p>Still, I did not start replacing it because I was bored. CodeMirror
+1 was heavily reliant on <code>designMode</code>
+or <code>contentEditable</code> (depending on the browser). Neither of
+these are well specified (HTML5 tries
+to <a href="http://www.w3.org/TR/html5/editing.html#contenteditable">specify</a>
+their basics), and, more importantly, they tend to be one of the more
+obscure and buggy areas of browser functionality—CodeMirror, by using
+this functionality in a non-typical way, was constantly running up
+against browser bugs. WebKit wouldn't show an empty line at the end of
+the document, and in some releases would suddenly get unbearably slow.
+Firefox would show the cursor in the wrong place. Internet Explorer
+would insist on linkifying everything that looked like a URL or email
+address, a behaviour that can't be turned off. Some bugs I managed to
+work around (which was often a frustrating, painful process), others,
+such as the Firefox cursor placement, I gave up on, and had to tell
+user after user that they were known problems, but not something I
+could help.</p>
+
+<p>Also, there is the fact that <code>designMode</code> (which seemed
+to be less buggy than <code>contentEditable</code> in Webkit and
+Firefox, and was thus used by CodeMirror 1 in those browsers) requires
+a frame. Frames are another tricky area. It takes some effort to
+prevent getting tripped up by domain restrictions, they don't
+initialize synchronously, behave strangely in response to the back
+button, and, on several browsers, can't be moved around the DOM
+without having them re-initialize. They did provide a very nice way to
+namespace the library, though—CodeMirror 1 could freely pollute the
+namespace inside the frame.</p>
+
+<p>Finally, working with an editable document means working with
+selection in arbitrary DOM structures. Internet Explorer (8 and
+before) has an utterly different (and awkward) selection API than all
+of the other browsers, and even among the different implementations of
+<code>document.selection</code>, details about how exactly a selection
+is represented vary quite a bit. Add to that the fact that Opera's
+selection support tended to be very buggy until recently, and you can
+imagine why CodeMirror 1 contains 700 lines of selection-handling
+code.</p>
+
+<p>And that brings us to the main issue with the CodeMirror 1
+code base: The proportion of browser-bug-workarounds to real
+application code was getting dangerously high. By building on top of a
+few dodgy features, I put the system in a vulnerable position—any
+incompatibility and bugginess in these features, I had to paper over
+with my own code. Not only did I have to do some serious stunt-work to
+get it to work on older browsers (as detailed in the
+previous <a href="http://codemirror.net/story.html">story</a>), things
+also kept breaking in newly released versions, requiring me to come up
+with <em>new</em> scary hacks in order to keep up. This was starting
+to lose its appeal.</p>
+
+<h2 id="approach">General Approach</h2>
+
+<p>What CodeMirror 2 does is try to sidestep most of the hairy hacks
+that came up in version 1. I owe a lot to the
+<a href="http://ace.ajax.org">ACE</a> editor for inspiration on how to
+approach this.</p>
+
+<p>I absolutely did not want to be completely reliant on key events to
+generate my input. Every JavaScript programmer knows that key event
+information is horrible and incomplete. Some people (most awesomely
+Mihai Bazon with <a href="http://ymacs.org">Ymacs</a>) have been able
+to build more or less functioning editors by directly reading key
+events, but it takes a lot of work (the kind of never-ending, fragile
+work I described earlier), and will never be able to properly support
+things like multi-keystoke international character
+input. <a href="#keymap" class="update">[see below for caveat]</a></p>
+
+<p>So what I do is focus a hidden textarea, and let the browser
+believe that the user is typing into that. What we show to the user is
+a DOM structure we built to represent his document. If this is updated
+quickly enough, and shows some kind of believable cursor, it feels
+like a real text-input control.</p>
+
+<p>Another big win is that this DOM representation does not have to
+span the whole document. Some CodeMirror 1 users insisted that they
+needed to put a 30 thousand line XML document into CodeMirror. Putting
+all that into the DOM takes a while, especially since, for some
+reason, an editable DOM tree is slower than a normal one on most
+browsers. If we have full control over what we show, we must only
+ensure that the visible part of the document has been added, and can
+do the rest only when needed. (Fortunately, the <code>onscroll</code>
+event works almost the same on all browsers, and lends itself well to
+displaying things only as they are scrolled into view.)</p>
+
+<h2 id="input">Input</h2>
+
+<p>ACE uses its hidden textarea only as a text input shim, and does
+all cursor movement and things like text deletion itself by directly
+handling key events. CodeMirror's way is to let the browser do its
+thing as much as possible, and not, for example, define its own set of
+key bindings. One way to do this would have been to have the whole
+document inside the hidden textarea, and after each key event update
+the display DOM to reflect what's in that textarea.</p>
+
+<p>That'd be simple, but it is not realistic. For even medium-sized
+document the editor would be constantly munging huge strings, and get
+terribly slow. What CodeMirror 2 does is put the current selection,
+along with an extra line on the top and on the bottom, into the
+textarea.</p>
+
+<p>This means that the arrow keys (and their ctrl-variations), home,
+end, etcetera, do not have to be handled specially. We just read the
+cursor position in the textarea, and update our cursor to match it.
+Also, copy and paste work pretty much for free, and people get their
+native key bindings, without any special work on my part. For example,
+I have emacs key bindings configured for Chrome and Firefox. There is
+no way for a script to detect this. <a class="update"
+href="#keymap">[no longer the case]</a></p>
+
+<p>Of course, since only a small part of the document sits in the
+textarea, keys like page up and ctrl-end won't do the right thing.
+CodeMirror is catching those events and handling them itself.</p>
+
+<h2 id="selection">Selection</h2>
+
+<p>Getting and setting the selection range of a textarea in modern
+browsers is trivial—you just use the <code>selectionStart</code>
+and <code>selectionEnd</code> properties. On IE you have to do some
+insane stuff with temporary ranges and compensating for the fact that
+moving the selection by a 'character' will treat \r\n as a single
+character, but even there it is possible to build functions that
+reliably set and get the selection range.</p>
+
+<p>But consider this typical case: When I'm somewhere in my document,
+press shift, and press the up arrow, something gets selected. Then, if
+I, still holding shift, press the up arrow again, the top of my
+selection is adjusted. The selection remembers where its <em>head</em>
+and its <em>anchor</em> are, and moves the head when we shift-move.
+This is a generally accepted property of selections, and done right by
+every editing component built in the past twenty years.</p>
+
+<p>But not something that the browser selection APIs expose.</p>
+
+<p>Great. So when someone creates an 'upside-down' selection, the next
+time CodeMirror has to update the textarea, it'll re-create the
+selection as an 'upside-up' selection, with the anchor at the top, and
+the next cursor motion will behave in an unexpected way—our second
+up-arrow press in the example above will not do anything, since it is
+interpreted in exactly the same way as the first.</p>
+
+<p>No problem. We'll just, ehm, detect that the selection is
+upside-down (you can tell by the way it was created), and then, when
+an upside-down selection is present, and a cursor-moving key is
+pressed in combination with shift, we quickly collapse the selection
+in the textarea to its start, allow the key to take effect, and then
+combine its new head with its old anchor to get the <em>real</em>
+selection.</p>
+
+<p>In short, scary hacks could not be avoided entirely in CodeMirror
+2.</p>
+
+<p>And, the observant reader might ask, how do you even know that a
+key combo is a cursor-moving combo, if you claim you support any
+native key bindings? Well, we don't, but we can learn. The editor
+keeps a set known cursor-movement combos (initialized to the
+predictable defaults), and updates this set when it observes that
+pressing a certain key had (only) the effect of moving the cursor.
+This, of course, doesn't work if the first time the key is used was
+for extending an inverted selection, but it works most of the
+time.</p>
+
+<h2 id="update">Intelligent Updating</h2>
+
+<p>One thing that always comes up when you have a complicated internal
+state that's reflected in some user-visible external representation
+(in this case, the displayed code and the textarea's content) is
+keeping the two in sync. The naive way is to just update the display
+every time you change your state, but this is not only error prone
+(you'll forget), it also easily leads to duplicate work on big,
+composite operations. Then you start passing around flags indicating
+whether the display should be updated in an attempt to be efficient
+again and, well, at that point you might as well give up completely.</p>
+
+<p>I did go down that road, but then switched to a much simpler model:
+simply keep track of all the things that have been changed during an
+action, and then, only at the end, use this information to update the
+user-visible display.</p>
+
+<p>CodeMirror uses a concept of <em>operations</em>, which start by
+calling a specific set-up function that clears the state and end by
+calling another function that reads this state and does the required
+updating. Most event handlers, and all the user-visible methods that
+change state are wrapped like this. There's a method
+called <code>operation</code> that accepts a function, and returns
+another function that wraps the given function as an operation.</p>
+
+<p>It's trivial to extend this (as CodeMirror does) to detect nesting,
+and, when an operation is started inside an operation, simply
+increment the nesting count, and only do the updating when this count
+reaches zero again.</p>
+
+<p>If we have a set of changed ranges and know the currently shown
+range, we can (with some awkward code to deal with the fact that
+changes can add and remove lines, so we're dealing with a changing
+coordinate system) construct a map of the ranges that were left
+intact. We can then compare this map with the part of the document
+that's currently visible (based on scroll offset and editor height) to
+determine whether something needs to be updated.</p>
+
+<p>CodeMirror uses two update algorithms—a full refresh, where it just
+discards the whole part of the DOM that contains the edited text and
+rebuilds it, and a patch algorithm, where it uses the information
+about changed and intact ranges to update only the out-of-date parts
+of the DOM. When more than 30 percent (which is the current heuristic,
+might change) of the lines need to be updated, the full refresh is
+chosen (since it's faster to do than painstakingly finding and
+updating all the changed lines), in the other case it does the
+patching (so that, if you scroll a line or select another character,
+the whole screen doesn't have to be
+re-rendered). <span class="update">[the full-refresh
+algorithm was dropped, it wasn't really faster than the patching
+one]</span></p>
+
+<p>All updating uses <code>innerHTML</code> rather than direct DOM
+manipulation, since that still seems to be by far the fastest way to
+build documents. There's a per-line function that combines the
+highlighting, <a href="manual.html#markText">marking</a>, and
+selection info for that line into a snippet of HTML. The patch updater
+uses this to reset individual lines, the refresh updater builds an
+HTML chunk for the whole visible document at once, and then uses a
+single <code>innerHTML</code> update to do the refresh.</p>
+
+<h2 id="parse">Parsers can be Simple</h2>
+
+<p>When I wrote CodeMirror 1, I
+thought <a href="http://codemirror.net/story.html#parser">interruptable
+parsers</a> were a hugely scary and complicated thing, and I used a
+bunch of heavyweight abstractions to keep this supposed complexity
+under control: parsers
+were <a href="http://bob.pythonmac.org/archives/2005/07/06/iteration-in-javascript/">iterators</a>
+that consumed input from another iterator, and used funny
+closure-resetting tricks to copy and resume themselves.</p>
+
+<p>This made for a rather nice system, in that parsers formed strictly
+separate modules, and could be composed in predictable ways.
+Unfortunately, it was quite slow (stacking three or four iterators on
+top of each other), and extremely intimidating to people not used to a
+functional programming style.</p>
+
+<p>With a few small changes, however, we can keep all those
+advantages, but simplify the API and make the whole thing less
+indirect and inefficient. CodeMirror
+2's <a href="manual.html#modeapi">mode API</a> uses explicit state
+objects, and makes the parser/tokenizer a function that simply takes a
+state and a character stream abstraction, advances the stream one
+token, and returns the way the token should be styled. This state may
+be copied, optionally in a mode-defined way, in order to be able to
+continue a parse at a given point. Even someone who's never touched a
+lambda in his life can understand this approach. Additionally, far
+fewer objects are allocated in the course of parsing now.</p>
+
+<p>The biggest speedup comes from the fact that the parsing no longer
+has to touch the DOM though. In CodeMirror 1, on an older browser, you
+could <em>see</em> the parser work its way through the document,
+managing some twenty lines in each 50-millisecond time slice it got. It
+was reading its input from the DOM, and updating the DOM as it went
+along, which any experienced JavaScript programmer will immediately
+spot as a recipe for slowness. In CodeMirror 2, the parser usually
+finishes the whole document in a single 100-millisecond time slice—it
+manages some 1500 lines during that time on Chrome. All it has to do
+is munge strings, so there is no real reason for it to be slow
+anymore.</p>
+
+<h2 id="summary">What Gives?</h2>
+
+<p>Given all this, what can you expect from CodeMirror 2?</p>
+
+<ul>
+
+<li><strong>Small.</strong> the base library is
+some <span class="update">45k</span> when minified
+now, <span class="update">17k</span> when gzipped. It's smaller than
+its own logo.</li>
+
+<li><strong>Lightweight.</strong> CodeMirror 2 initializes very
+quickly, and does almost no work when it is not focused. This means
+you can treat it almost like a textarea, have multiple instances on a
+page without trouble.</li>
+
+<li><strong>Huge document support.</strong> Since highlighting is
+really fast, and no DOM structure is being built for non-visible
+content, you don't have to worry about locking up your browser when a
+user enters a megabyte-sized document.</li>
+
+<li><strong>Extended API.</strong> Some things kept coming up in the
+mailing list, such as marking pieces of text or lines, which were
+extremely hard to do with CodeMirror 1. The new version has proper
+support for these built in.</li>
+
+<li><strong>Tab support.</strong> Tabs inside editable documents were,
+for some reason, a no-go. At least six different people announced they
+were going to add tab support to CodeMirror 1, none survived (I mean,
+none delivered a working version). CodeMirror 2 no longer removes tabs
+from your document.</li>
+
+<li><strong>Sane styling.</strong> <code>iframe</code> nodes aren't
+really known for respecting document flow. Now that an editor instance
+is a plain <code>div</code> element, it is much easier to size it to
+fit the surrounding elements. You don't even have to make it scroll if
+you do not <a href="../demo/resize.html">want to</a>.</li>
+
+</ul>
+
+<p>On the downside, a CodeMirror 2 instance is <em>not</em> a native
+editable component. Though it does its best to emulate such a
+component as much as possible, there is functionality that browsers
+just do not allow us to hook into. Doing select-all from the context
+menu, for example, is not currently detected by CodeMirror.</p>
+
+<p id="changes" style="margin-top: 2em;"><span style="font-weight:
+bold">[Updates from November 13th 2011]</span> Recently, I've made
+some changes to the codebase that cause some of the text above to no
+longer be current. I've left the text intact, but added markers at the
+passages that are now inaccurate. The new situation is described
+below.</p>
+
+<h2 id="btree">Content Representation</h2>
+
+<p>The original implementation of CodeMirror 2 represented the
+document as a flat array of line objects. This worked well—splicing
+arrays will require the part of the array after the splice to be
+moved, but this is basically just a simple <code>memmove</code> of a
+bunch of pointers, so it is cheap even for huge documents.</p>
+
+<p>However, I recently added line wrapping and code folding (line
+collapsing, basically). Once lines start taking up a non-constant
+amount of vertical space, looking up a line by vertical position
+(which is needed when someone clicks the document, and to determine
+the visible part of the document during scrolling) can only be done
+with a linear scan through the whole array, summing up line heights as
+you go. Seeing how I've been going out of my way to make big documents
+fast, this is not acceptable.</p>
+
+<p>The new representation is based on a B-tree. The leaves of the tree
+contain arrays of line objects, with a fixed minimum and maximum size,
+and the non-leaf nodes simply hold arrays of child nodes. Each node
+stores both the amount of lines that live below them and the vertical
+space taken up by these lines. This allows the tree to be indexed both
+by line number and by vertical position, and all access has
+logarithmic complexity in relation to the document size.</p>
+
+<p>I gave line objects and tree nodes parent pointers, to the node
+above them. When a line has to update its height, it can simply walk
+these pointers to the top of the tree, adding or subtracting the
+difference in height from each node it encounters. The parent pointers
+also make it cheaper (in complexity terms, the difference is probably
+tiny in normal-sized documents) to find the current line number when
+given a line object. In the old approach, the whole document array had
+to be searched. Now, we can just walk up the tree and count the sizes
+of the nodes coming before us at each level.</p>
+
+<p>I chose B-trees, not regular binary trees, mostly because they
+allow for very fast bulk insertions and deletions. When there is a big
+change to a document, it typically involves adding, deleting, or
+replacing a chunk of subsequent lines. In a regular balanced tree, all
+these inserts or deletes would have to be done separately, which could
+be really expensive. In a B-tree, to insert a chunk, you just walk
+down the tree once to find where it should go, insert them all in one
+shot, and then break up the node if needed. This breaking up might
+involve breaking up nodes further up, but only requires a single pass
+back up the tree. For deletion, I'm somewhat lax in keeping things
+balanced—I just collapse nodes into a leaf when their child count goes
+below a given number. This means that there are some weird editing
+patterns that may result in a seriously unbalanced tree, but even such
+an unbalanced tree will perform well, unless you spend a day making
+strangely repeating edits to a really big document.</p>
+
+<h2 id="keymap">Keymaps</h2>
+
+<p><a href="#approach">Above</a>, I claimed that directly catching key
+events for things like cursor movement is impractical because it
+requires some browser-specific kludges. I then proceeded to explain
+some awful <a href="#selection">hacks</a> that were needed to make it
+possible for the selection changes to be detected through the
+textarea. In fact, the second hack is about as bad as the first.</p>
+
+<p>On top of that, in the presence of user-configurable tab sizes and
+collapsed and wrapped lines, lining up cursor movement in the textarea
+with what's visible on the screen becomes a nightmare. Thus, I've
+decided to move to a model where the textarea's selection is no longer
+depended on.</p>
+
+<p>So I moved to a model where all cursor movement is handled by my
+own code. This adds support for a goal column, proper interaction of
+cursor movement with collapsed lines, and makes it possible for
+vertical movement to move through wrapped lines properly, instead of
+just treating them like non-wrapped lines.</p>
+
+<p>The key event handlers now translate the key event into a string,
+something like <code>Ctrl-Home</code> or <code>Shift-Cmd-R</code>, and
+use that string to look up an action to perform. To make keybinding
+customizable, this lookup goes through
+a <a href="manual.html#option_keyMap">table</a>, using a scheme that
+allows such tables to be chained together (for example, the default
+Mac bindings fall through to a table named 'emacsy', which defines
+basic Emacs-style bindings like <code>Ctrl-F</code>, and which is also
+used by the custom Emacs bindings).</p>
+
+<p>A new
+option <a href="manual.html#option_extraKeys"><code>extraKeys</code></a>
+allows ad-hoc keybindings to be defined in a much nicer way than what
+was possible with the
+old <a href="manual.html#option_onKeyEvent"><code>onKeyEvent</code></a>
+callback. You simply provide an object mapping key identifiers to
+functions, instead of painstakingly looking at raw key events.</p>
+
+<p>Built-in commands map to strings, rather than functions, for
+example <code>"goLineUp"</code> is the default action bound to the up
+arrow key. This allows new keymaps to refer to them without
+duplicating any code. New commands can be defined by assigning to
+the <code>CodeMirror.commands</code> object, which maps such commands
+to functions.</p>
+
+<p>The hidden textarea now only holds the current selection, with no
+extra characters around it. This has a nice advantage: polling for
+input becomes much, much faster. If there's a big selection, this text
+does not have to be read from the textarea every time—when we poll,
+just noticing that something is still selected is enough to tell us
+that no new text was typed.</p>
+
+<p>The reason that cheap polling is important is that many browsers do
+not fire useful events on IME (input method engine) input, which is
+the thing where people inputting a language like Japanese or Chinese
+use multiple keystrokes to create a character or sequence of
+characters. Most modern browsers fire <code>input</code> when the
+composing is finished, but many don't fire anything when the character
+is updated <em>during</em> composition. So we poll, whenever the
+editor is focused, to provide immediate updates of the display.</p>
+
+</div><div class="rightsmall blk">
+
+    <h2>Contents</h2>
+
+    <ul>
+      <li><a href="#intro">Introduction</a></li>
+      <li><a href="#approach">General Approach</a></li>
+      <li><a href="#input">Input</a></li>
+      <li><a href="#selection">Selection</a></li>
+      <li><a href="#update">Intelligent Updating</a></li>
+      <li><a href="#parse">Parsing</a></li>
+      <li><a href="#summary">What Gives?</a></li>
+      <li><a href="#btree">Content Representation</a></li>
+      <li><a href="#keymap">Key Maps</a></li>
+    </ul>
+
+</div></div>
+
+<div style="height: 2em">&nbsp;</div>
+
+</body></html>
diff --git a/third-party/codemirror-3.15/doc/manual.html b/third-party/codemirror-3.15/doc/manual.html
new file mode 100644 (file)
index 0000000..dc4100f
--- /dev/null
@@ -0,0 +1,2360 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: User Manual</title>
+    <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Droid+Sans|Droid+Sans:bold">
+    <link rel="stylesheet" type="text/css" href="docs.css">
+    <style>dl dl {margin: 0;}</style>
+    <script src="../lib/codemirror.js"></script>
+    <link rel="stylesheet" href="../lib/codemirror.css">
+    <script src="../addon/runmode/runmode.js"></script>
+    <script src="../addon/runmode/colorize.js"></script>
+    <script src="../mode/javascript/javascript.js"></script>
+    <script src="../mode/xml/xml.js"></script>
+    <script src="../mode/css/css.js"></script>
+    <script src="../mode/htmlmixed/htmlmixed.js"></script>
+    <style>
+      dt { text-indent: -1.5em; padding-left: 1.5em; }
+    </style>
+  </head>
+  <body>
+
+<h1><span class="logo-braces">{ }</span> <a href="http://codemirror.net/">CodeMirror</a></h1>
+
+<div class="grey">
+<img src="baboon.png" class="logo" alt="logo">
+<pre>
+/* User manual and
+   reference guide */
+</pre>
+</div>
+
+<div class="clear"><div class="leftbig blk">
+
+    <h2 id="overview">Overview</h2>
+
+    <p>CodeMirror is a code-editor component that can be embedded in
+    Web pages. The core library provides <em>only</em> the editor
+    component, no accompanying buttons, auto-completion, or other IDE
+    functionality. It does provide a rich API on top of which such
+    functionality can be straightforwardly implemented. See
+    the <a href="#addons">addons</a> included in the distribution,
+    and the <a href="https://github.com/marijnh/CodeMirror/wiki/CodeMirror-addons">list
+    of externally hosted addons</a>, for reusable
+    implementations of extra features.</p>
+
+    <p>CodeMirror works with language-specific modes. Modes are
+    JavaScript programs that help color (and optionally indent) text
+    written in a given language. The distribution comes with a number
+    of modes (see the <a href="../mode/"><code>mode/</code></a>
+    directory), and it isn't hard to <a href="#modeapi">write new
+    ones</a> for other languages.</p>
+
+    <h2 id="usage">Basic Usage</h2>
+
+    <p>The easiest way to use CodeMirror is to simply load the script
+    and style sheet found under <code>lib/</code> in the distribution,
+    plus a mode script from one of the <code>mode/</code> directories.
+    (See <a href="compress.html">the compression helper</a> for an
+    easy way to combine scripts.) For example:</p>
+
+    <pre data-lang="text/html">&lt;script src="lib/codemirror.js">&lt;/script>
+&lt;link rel="stylesheet" href="../lib/codemirror.css">
+&lt;script src="mode/javascript/javascript.js">&lt;/script></pre>
+
+    <p>Having done this, an editor instance can be created like
+    this:</p>
+
+    <pre data-lang="javascript">var myCodeMirror = CodeMirror(document.body);</pre>
+
+    <p>The editor will be appended to the document body, will start
+    empty, and will use the mode that we loaded. To have more control
+    over the new editor, a configuration object can be passed
+    to <a href="#CodeMirror"><code>CodeMirror</code></a> as a second
+    argument:</p>
+
+    <pre data-lang="javascript">var myCodeMirror = CodeMirror(document.body, {
+  value: "function myScript(){return 100;}\n",
+  mode:  "javascript"
+});</pre>
+
+    <p>This will initialize the editor with a piece of code already in
+    it, and explicitly tell it to use the JavaScript mode (which is
+    useful when multiple modes are loaded).
+    See <a href="#config">below</a> for a full discussion of the
+    configuration options that CodeMirror accepts.</p>
+
+    <p>In cases where you don't want to append the editor to an
+    element, and need more control over the way it is inserted, the
+    first argument to the <code>CodeMirror</code> function can also
+    be a function that, when given a DOM element, inserts it into the
+    document somewhere. This could be used to, for example, replace a
+    textarea with a real editor:</p>
+
+    <pre data-lang="javascript">var myCodeMirror = CodeMirror(function(elt) {
+  myTextArea.parentNode.replaceChild(elt, myTextArea);
+}, {value: myTextArea.value});</pre>
+
+    <p>However, for this use case, which is a common way to use
+    CodeMirror, the library provides a much more powerful
+    shortcut:</p>
+
+    <pre data-lang="javascript">var myCodeMirror = CodeMirror.fromTextArea(myTextArea);</pre>
+
+    <p>This will, among other things, ensure that the textarea's value
+    is updated with the editor's contents when the form (if it is part
+    of a form) is submitted. See the <a href="#fromTextArea">API
+    reference</a> for a full description of this method.</p>
+
+    <h2 id="config">Configuration</h2>
+
+    <p>Both the <a href="#CodeMirror"><code>CodeMirror</code></a>
+    function and its <code>fromTextArea</code> method take as second
+    (optional) argument an object containing configuration options.
+    Any option not supplied like this will be taken
+    from <a href="#defaults"><code>CodeMirror.defaults</code></a>, an
+    object containing the default options. You can update this object
+    to change the defaults on your page.</p>
+
+    <p>Options are not checked in any way, so setting bogus option
+    values is bound to lead to odd errors.</p>
+
+    <p>These are the supported options:</p>
+
+    <dl>
+      <dt id="option_value"><code><strong>value</strong>: string|CodeMirror.Doc</code></dt>
+      <dd>The starting value of the editor. Can be a string, or
+      a <a href="#api_doc">document object</a>.</dd>
+
+      <dt id="option_mode"><code><strong>mode</strong>: string|object</code></dt>
+      <dd>The mode to use. When not given, this will default to the
+      first mode that was loaded. It may be a string, which either
+      simply names the mode or is
+      a <a href="http://en.wikipedia.org/wiki/MIME">MIME</a> type
+      associated with the mode. Alternatively, it may be an object
+      containing configuration options for the mode, with
+      a <code>name</code> property that names the mode (for
+      example <code>{name: "javascript", json: true}</code>). The demo
+      pages for each mode contain information about what configuration
+      parameters the mode supports. You can ask CodeMirror which modes
+      and MIME types have been defined by inspecting
+      the <code>CodeMirror.modes</code>
+      and <code>CodeMirror.mimeModes</code> objects. The first maps
+      mode names to their constructors, and the second maps MIME types
+      to mode specs.</dd>
+
+      <dt id="option_theme"><code><strong>theme</strong>: string</code></dt>
+      <dd>The theme to style the editor with. You must make sure the
+      CSS file defining the corresponding <code>.cm-s-[name]</code>
+      styles is loaded (see
+      the <a href="../theme/"><code>theme</code></a> directory in the
+      distribution). The default is <code>"default"</code>, for which
+      colors are included in <code>codemirror.css</code>. It is
+      possible to use multiple theming classes at once—for
+      example <code>"foo bar"</code> will assign both
+      the <code>cm-s-foo</code> and the <code>cm-s-bar</code> classes
+      to the editor.</dd>
+
+      <dt id="option_indentUnit"><code><strong>indentUnit</strong>: integer</code></dt>
+      <dd>How many spaces a block (whatever that means in the edited
+      language) should be indented. The default is 2.</dd>
+
+      <dt id="option_smartIndent"><code><strong>smartIndent</strong>: boolean</code></dt>
+      <dd>Whether to use the context-sensitive indentation that the
+      mode provides (or just indent the same as the line before).
+      Defaults to true.</dd>
+
+      <dt id="option_tabSize"><code><strong>tabSize</strong>: integer</code></dt>
+      <dd>The width of a tab character. Defaults to 4.</dd>
+
+      <dt id="option_indentWithTabs"><code><strong>indentWithTabs</strong>: boolean</code></dt>
+      <dd>Whether, when indenting, the first N*<code>tabSize</code>
+      spaces should be replaced by N tabs. Default is false.</dd>
+
+      <dt id="option_electricChars"><code><strong>electricChars</strong>: boolean</code></dt>
+      <dd>Configures whether the editor should re-indent the current
+      line when a character is typed that might change its proper
+      indentation (only works if the mode supports indentation).
+      Default is true.</dd>
+
+      <dt id="option_rtlMoveVisually"><code><strong>rtlMoveVisually</strong>: boolean</code></dt>
+      <dd>Determines whether horizontal cursor movement through
+      right-to-left (Arabic, Hebrew) text is visual (pressing the left
+      arrow moves the cursor left) or logical (pressing the left arrow
+      moves to the next lower index in the string, which is visually
+      right in right-to-left text). The default is <code>false</code>
+      on Windows, and <code>true</code> on other platforms.</dd>
+
+      <dt id="option_keyMap"><code><strong>keyMap</strong>: string</code></dt>
+      <dd>Configures the keymap to use. The default
+      is <code>"default"</code>, which is the only keymap defined
+      in <code>codemirror.js</code> itself. Extra keymaps are found in
+      the <a href="../keymap/"><code>keymap</code></a> directory. See
+      the <a href="#keymaps">section on keymaps</a> for more
+      information.</dd>
+
+      <dt id="option_extraKeys"><code><strong>extraKeys</strong>: object</code></dt>
+      <dd>Can be used to specify extra keybindings for the editor,
+      alongside the ones defined
+      by <a href="#option_keyMap"><code>keyMap</code></a>. Should be
+      either null, or a valid <a href="#keymaps">keymap</a> value.</dd>
+
+      <dt id="option_lineWrapping"><code><strong>lineWrapping</strong>: boolean</code></dt>
+      <dd>Whether CodeMirror should scroll or wrap for long lines.
+      Defaults to <code>false</code> (scroll).</dd>
+
+      <dt id="option_lineNumbers"><code><strong>lineNumbers</strong>: boolean</code></dt>
+      <dd>Whether to show line numbers to the left of the editor.</dd>
+
+      <dt id="option_firstLineNumber"><code><strong>firstLineNumber</strong>: integer</code></dt>
+      <dd>At which number to start counting lines. Default is 1.</dd>
+
+      <dt id="option_lineNumberFormatter"><code><strong>lineNumberFormatter</strong>: function(line: integer) → string</code></dt>
+      <dd>A function used to format line numbers. The function is
+      passed the line number, and should return a string that will be
+      shown in the gutter.</dd>
+
+      <dt id="option_gutters"><code><strong>gutters</strong>: array&lt;string&gt;</code></dt>
+      <dd>Can be used to add extra gutters (beyond or instead of the
+      line number gutter). Should be an array of CSS class names, each
+      of which defines a <code>width</code> (and optionally a
+      background), and which will be used to draw the background of
+      the gutters. <em>May</em> include
+      the <code>CodeMirror-linenumbers</code> class, in order to
+      explicitly set the position of the line number gutter (it will
+      default to be to the right of all other gutters). These class
+      names are the keys passed
+      to <a href="#setGutterMarker"><code>setGutterMarker</code></a>.</dd>
+
+      <dt id="option_fixedGutter"><code><strong>fixedGutter</strong>: boolean</code></dt>
+      <dd>Determines whether the gutter scrolls along with the content
+      horizontally (false) or whether it stays fixed during horizontal
+      scrolling (true, the default).</dd>
+
+      <dt id="option_coverGutterNextToScrollbar"><code><strong>coverGutterNextToScrollbar</strong>: boolean</code></dt>
+      <dd>When <a href="#option_fixedGutter"><code>fixedGutter</code></a>
+      is on, and there is a horizontal scrollbar, by default the
+      gutter will be visible to the left of this scrollbar. If this
+      option is set to true, it will be covered by an element with
+      class <code>CodeMirror-gutter-filler</code>.</dd>
+
+      <dt id="option_readOnly"><code><strong>readOnly</strong>: boolean|string</code></dt>
+      <dd>This disables editing of the editor content by the user. If
+      the special value <code>"nocursor"</code> is given (instead of
+      simply <code>true</code>), focusing of the editor is also
+      disallowed.</dd>
+
+      <dt id="option_showCursorWhenSelecting"><code><strong>showCursorWhenSelecting</strong>: boolean</code></dt>
+      <dd>Whether the cursor should be drawn when a selection is
+      active. Defaults to false.</dd>
+
+      <dt id="option_undoDepth"><code><strong>undoDepth</strong>: integer</code></dt>
+      <dd>The maximum number of undo levels that the editor stores.
+      Defaults to 40.</dd>
+
+      <dt id="option_historyEventDelay"><code><strong>historyEventDelay</strong>: integer</code></dt>
+      <dd>The period of inactivity (in milliseconds) that will cause a
+      new history event to be started when typing or deleting.
+      Defaults to 500.</dd>
+
+      <dt id="option_tabindex"><code><strong>tabindex</strong>: integer</code></dt>
+      <dd>The <a href="http://www.w3.org/TR/html401/interact/forms.html#adef-tabindex">tab
+      index</a> to assign to the editor. If not given, no tab index
+      will be assigned.</dd>
+
+      <dt id="option_autofocus"><code><strong>autofocus</strong>: boolean</code></dt>
+      <dd>Can be used to make CodeMirror focus itself on
+      initialization. Defaults to off.
+      When <a href="#fromTextArea"><code>fromTextArea</code></a> is
+      used, and no explicit value is given for this option, it will be
+      set to true when either the source textarea is focused, or it
+      has an <code>autofocus</code> attribute and no other element is
+      focused.</dd>
+    </dl>
+
+    <p>Below this a few more specialized, low-level options are
+    listed. These are only useful in very specific situations, you
+    might want to skip them the first time you read this manual.</p>
+
+    <dl>
+      <dt id="option_dragDrop"><code><strong>dragDrop</strong>: boolean</code></dt>
+      <dd>Controls whether drag-and-drop is enabled. On by default.</dd>
+
+      <dt id="option_onDragEvent"><code><strong>onDragEvent</strong>: function(instance: CodeMirror, event: Event) → boolean</code></dt>
+      <dd><em>Deprecated! See <a href="#event_dom">these</a> event
+      handlers for the current recommended approach.</em><br>When given,
+      this will be called when the editor is handling
+      a <code>dragenter</code>, <code>dragover</code>,
+      or <code>drop</code> event. It will be passed the editor
+      instance and the event object as arguments. The callback can
+      choose to handle the event itself, in which case it should
+      return <code>true</code> to indicate that CodeMirror should not
+      do anything further.</dd>
+
+      <dt id="option_onKeyEvent"><code><strong>onKeyEvent</strong>: function(instance: CodeMirror, event: Event) → boolean</code></dt>
+      <dd><em>Deprecated! See <a href="#event_dom">these</a> event
+      handlers for the current recommended approach.</em><br>This
+      provides a rather low-level hook into CodeMirror's key handling.
+      If provided, this function will be called on
+      every <code>keydown</code>, <code>keyup</code>,
+      and <code>keypress</code> event that CodeMirror captures. It
+      will be passed two arguments, the editor instance and the key
+      event. This key event is pretty much the raw key event, except
+      that a <code>stop()</code> method is always added to it. You
+      could feed it to, for example, <code>jQuery.Event</code> to
+      further normalize it.<br>This function can inspect the key
+      event, and handle it if it wants to. It may return true to tell
+      CodeMirror to ignore the event. Be wary that, on some browsers,
+      stopping a <code>keydown</code> does not stop
+      the <code>keypress</code> from firing, whereas on others it
+      does. If you respond to an event, you should probably inspect
+      its <code>type</code> property and only do something when it
+      is <code>keydown</code> (or <code>keypress</code> for actions
+      that need character data).</dd>
+
+      <dt id="option_cursorBlinkRate"><code><strong>cursorBlinkRate</strong>: number</code></dt>
+      <dd>Half-period in milliseconds used for cursor blinking. The default blink
+      rate is 530ms.</dd>
+
+      <dt id="option_cursorScrollMargin"><code><strong>cursorScrollMargin</strong>: number</code></dt>
+      <dd>How much extra space to always keep above and below the
+      cursor when approaching the top or bottom of the visible view in
+      a scrollable document. Default is 0.</dd>
+
+      <dt id="option_cursorHeight"><code><strong>cursorHeight</strong>: number</code></dt>
+      <dd>Determines the height of the cursor. Default is 1, meaning
+      it spans the whole height of the line. For some fonts (and by
+      some tastes) a smaller height (for example <code>0.85</code>),
+      which causes the cursor to not reach all the way to the bottom
+      of the line, looks better</dd>
+
+      <dt id="option_workTime"><code><strong>workTime</strong>, <strong>workDelay</strong>: number</code></dt>
+      <dd>Highlighting is done by a pseudo background-thread that will
+      work for <code>workTime</code> milliseconds, and then use
+      timeout to sleep for <code>workDelay</code> milliseconds. The
+      defaults are 200 and 300, you can change these options to make
+      the highlighting more or less aggressive.</dd>
+
+      <dt id="option_workDelay"><code><strong>workDelay</strong>: number</code></dt>
+      <dd>See <a href="#option_workTime"><code>workTime</code></a>.</dd>
+
+      <dt id="option_pollInterval"><code><strong>pollInterval</strong>: number</code></dt>
+      <dd>Indicates how quickly CodeMirror should poll its input
+      textarea for changes (when focused). Most input is captured by
+      events, but some things, like IME input on some browsers, don't
+      generate events that allow CodeMirror to properly detect it.
+      Thus, it polls. Default is 100 milliseconds.</dd>
+
+      <dt id="option_flattenSpans"><code><strong>flattenSpans</strong>: boolean</code></dt>
+      <dd>By default, CodeMirror will combine adjacent tokens into a
+      single span if they have the same class. This will result in a
+      simpler DOM tree, and thus perform better. With some kinds of
+      styling (such as rounded corners), this will change the way the
+      document looks. You can set this option to false to disable this
+      behavior.</dd>
+
+      <dt id="option_maxHighlightLength"><code><strong>maxHighlightLength</strong>: number</code></dt>
+      <dd>When highlighting long lines, in order to stay responsive,
+      the editor will give up and simply style the rest of the line as
+      plain text when it reaches a certain position. The default is
+      10000. You can set this to <code>Infinity</code> to turn off
+      this behavior.</dd>
+
+      <dt id="option_viewportMargin"><code><strong>viewportMargin</strong>: integer</code></dt>
+      <dd>Specifies the amount of lines that are rendered above and
+      below the part of the document that's currently scrolled into
+      view. This affects the amount of updates needed when scrolling,
+      and the amount of work that such an update does. You should
+      usually leave it at its default, 10. Can be set
+      to <code>Infinity</code> to make sure the whole document is
+      always rendered, and thus the browser's text search works on it.
+      This <em>will</em> have bad effects on performance of big
+      documents.</dd>
+    </dl>
+
+    <h2 id="events">Events</h2>
+
+    <p>Various CodeMirror-related objects emit events, which allow
+    client code to react to various situations. Handlers for such
+    events can be registed with the <a href="#on"><code>on</code></a>
+    and <a href="#off"><code>off</code></a> methods on the objects
+    that the event fires on. To fire your own events,
+    use <code>CodeMirror.signal(target, name, args...)</code>,
+    where <code>target</code> is a non-DOM-node object.</p>
+
+    <p>An editor instance fires the following events.
+    The <code>instance</code> argument always refers to the editor
+    itself.</p>
+
+    <dl>
+      <dt id="event_change"><code><strong>"change"</strong> (instance: CodeMirror, changeObj: object)</code></dt>
+      <dd>Fires every time the content of the editor is changed.
+      The <code>changeObj</code> is a <code>{from, to, text, removed,
+      next}</code> object containing information about the changes
+      that occurred as second argument. <code>from</code>
+      and <code>to</code> are the positions (in the pre-change
+      coordinate system) where the change started and ended (for
+      example, it might be <code>{ch:0, line:18}</code> if the
+      position is at the beginning of line #19). <code>text</code> is
+      an array of strings representing the text that replaced the
+      changed range (split by line). <code>removed</code> is the text
+      that used to be between <code>from</code> and <code>to</code>,
+      which is overwritten by this change. If multiple changes
+      happened during a single operation, the object will have
+      a <code>next</code> property pointing to another change object
+      (which may point to another, etc).</dd>
+
+      <dt id="event_beforeChange"><code><strong>"beforeChange"</strong> (instance: CodeMirror, changeObj: object)</code></dt>
+      <dd>This event is fired before a change is applied, and its
+      handler may choose to modify or cancel the change.
+      The <code>changeObj</code> object
+      has <code>from</code>, <code>to</code>, and <code>text</code>
+      properties, as with
+      the <a href="#event_change"><code>"change"</code></a> event, but
+      never a <code>next</code> property, since this is fired for each
+      individual change, and not batched per operation. It also has
+      a <code>cancel()</code> method, which can be called to cancel
+      the change, and, <strong>if</strong> the change isn't coming
+      from an undo or redo event, an <code>update(from, to,
+      text)</code> method, which may be used to modify the change.
+      Undo or redo changes can't be modified, because they hold some
+      metainformation for restoring old marked ranges that is only
+      valid for that specific change. All three arguments
+      to <code>update</code> are optional, and can be left off to
+      leave the existing value for that field
+      intact. <strong>Note:</strong> you may not do anything from
+      a <code>"beforeChange"</code> handler that would cause changes
+      to the document or its visualization. Doing so will, since this
+      handler is called directly from the bowels of the CodeMirror
+      implementation, probably cause the editor to become
+      corrupted.</dd>
+
+      <dt id="event_cursorActivity"><code><strong>"cursorActivity"</strong> (instance: CodeMirror)</code></dt>
+      <dd>Will be fired when the cursor or selection moves, or any
+      change is made to the editor content.</dd>
+
+      <dt id="event_keyHandled"><code><strong>"keyHandled"</strong> (instance: CodeMirror, name: string, event: Event)</code></dt>
+      <dd>Fired after a key is handled through a
+      keymap. <code>name</code> is the name of the handled key (for
+      example <code>"Ctrl-X"</code> or <code>"'q'"</code>),
+      and <code>event</code> is the DOM <code>keydown</code>
+      or <code>keypress</code> event.</dd>
+
+      <dt id="event_inputRead"><code><strong>"inputRead"</strong> (instance: CodeMirror, changeObj: object)</code></dt>
+      <dd>Fired whenever new input is read from the hidden textarea
+      (typed or pasted by the user).</dd>
+
+      <dt id="event_beforeSelectionChange"><code><strong>"beforeSelectionChange"</strong> (instance: CodeMirror, selection: {head, anchor})</code></dt>
+      <dd>This event is fired before the selection is moved. Its
+      handler may modify the resulting selection head and anchor.
+      The <code>selection</code> parameter is an object
+      with <code>head</code> and <code>anchor</code> properties
+      holding <code>{line, ch}</code> objects, which the handler can
+      read and update. Handlers for this event have the same
+      restriction
+      as <a href="#event_beforeChange"><code>"beforeChange"</code></a>
+      handlers — they should not do anything to directly update the
+      state of the editor.</dd>
+
+      <dt id="event_viewportChange"><code><strong>"viewportChange"</strong> (instance: CodeMirror, from: number, to: number)</code></dt>
+      <dd>Fires whenever the <a href="#getViewport">view port</a> of
+      the editor changes (due to scrolling, editing, or any other
+      factor). The <code>from</code> and <code>to</code> arguments
+      give the new start and end of the viewport.</dd>
+
+      <dt id="event_gutterClick"><code><strong>"gutterClick"</strong> (instance: CodeMirror, line: integer, gutter: string, clickEvent: Event)</code></dt>
+      <dd>Fires when the editor gutter (the line-number area) is
+      clicked. Will pass the editor instance as first argument, the
+      (zero-based) number of the line that was clicked as second
+      argument, the CSS class of the gutter that was clicked as third
+      argument, and the raw <code>mousedown</code> event object as
+      fourth argument.</dd>
+
+      <dt id="event_focus"><code><strong>"focus"</strong> (instance: CodeMirror)</code></dt>
+      <dd>Fires whenever the editor is focused.</dd>
+
+      <dt id="event_blur"><code><strong>"blur"</strong> (instance: CodeMirror)</code></dt>
+      <dd>Fires whenever the editor is unfocused.</dd>
+
+      <dt id="event_scroll"><code><strong>"scroll"</strong> (instance: CodeMirror)</code></dt>
+      <dd>Fires when the editor is scrolled.</dd>
+
+      <dt id="event_update"><code><strong>"update"</strong> (instance: CodeMirror)</code></dt>
+      <dd>Will be fired whenever CodeMirror updates its DOM display.</dd>
+
+      <dt id="event_renderLine"><code><strong>"renderLine"</strong> (instance: CodeMirror, line: LineHandle, element: Element)</code></dt>
+      <dd>Fired whenever a line is (re-)rendered to the DOM. Fired
+      right after the DOM element is built, <em>before</em> it is
+      added to the document. The handler may mess with the style of
+      the resulting element, or add event handlers, but
+      should <em>not</em> try to change the state of the editor.</dd>
+
+      <dt id="event_dom"><code><strong>"mousedown"</strong>,
+      <strong>"dblclick"</strong>, <strong>"contextmenu"</strong>, <strong>"keydown"</strong>, <strong>"keypress"</strong>,
+      <strong>"keyup"</strong>, <strong>"dragstart"</strong>, <strong>"dragenter"</strong>,
+      <strong>"dragover"</strong>, <strong>"drop"</strong>
+      (instance: CodeMirror, event: Event)</code></dt>
+      <dd>Fired when CodeMirror is handling a DOM event of this type.
+      You can <code>preventDefault</code> the event, or give it a
+      truthy <code>codemirrorIgnore</code> property, to signal that
+      CodeMirror should do no further handling.</dd>
+    </dl>
+
+    <p>Document objects (instances
+    of <a href="#Doc"><code>CodeMirror.Doc</code></a>) emit the
+    following events:</p>
+
+    <dl>
+      <dt id="event_doc_change"><code><strong>"change"</strong> (doc: CodeMirror.Doc, changeObj: object)</code></dt>
+      <dd>Fired whenever a change occurs to the
+      document. <code>changeObj</code> has a similar type as the
+      object passed to the
+      editor's <a href="#event_change"><code>"change"</code></a>
+      event, but it never has a <code>next</code> property, because
+      document change events are not batched (whereas editor change
+      events are).</dd>
+
+      <dt id="event_doc_beforeChange"><code><strong>"beforeChange"</strong> (doc: CodeMirror.Doc, change: object)</code></dt>
+      <dd>See the <a href="#event_beforeChange">description of the
+      same event</a> on editor instances.</dd>
+
+      <dt id="event_doc_cursorActivity"><code><strong>"cursorActivity"</strong> (doc: CodeMirror.Doc)</code></dt>
+      <dd>Fired whenever the cursor or selection in this document
+      changes.</dd>
+
+      <dt id="event_doc_beforeSelectionChange"><code><strong>"beforeSelectionChange"</strong> (doc: CodeMirror.Doc, selection: {head, anchor})</code></dt>
+      <dd>Equivalent to
+      the <a href="#event_beforeSelectionChange">event by the same
+      name</a> as fired on editor instances.</dd>
+    </dl>
+
+    <p>Line handles (as returned by, for
+    example, <a href="#getLineHandle"><code>getLineHandle</code></a>)
+    support these events:</p>
+
+    <dl>
+      <dt id="event_delete"><code><strong>"delete"</strong> ()</code></dt>
+      <dd>Will be fired when the line object is deleted. A line object
+      is associated with the <em>start</em> of the line. Mostly useful
+      when you need to find out when your <a href="#setGutterMarker">gutter
+      markers</a> on a given line are removed.</dd>
+      <dt id="event_line_change"><code><strong>"change"</strong> (line: LineHandle, changeObj: object)</code></dt>
+      <dd>Fires when the line's text content is changed in any way
+      (but the line is not deleted outright). The <code>change</code>
+      object is similar to the one passed
+      to <a href="#event_change">change event</a> on the editor
+      object.</dd>
+    </dl>
+
+    <p>Marked range handles (<code>CodeMirror.TextMarker</code>), as returned
+    by <a href="#markText"><code>markText</code></a>
+    and <a href="#setBookmark"><code>setBookmark</code></a>, emit the
+    following events:</p>
+
+    <dl>
+      <dt id="event_beforeCursorEnter"><code><strong>"beforeCursorEnter"</strong> ()</code></dt>
+      <dd>Fired when the cursor enters the marked range. From this
+      event handler, the editor state may be inspected
+      but <em>not</em> modified, with the exception that the range on
+      which the event fires may be cleared.</dd>
+      <dt id="event_clear"><code><strong>"clear"</strong> (from: {line, ch}, to: {line, ch})</code></dt>
+      <dd>Fired when the range is cleared, either through cursor
+      movement in combination
+      with <a href="#mark_clearOnEnter"><code>clearOnEnter</code></a>
+      or through a call to its <code>clear()</code> method. Will only
+      be fired once per handle. Note that deleting the range through
+      text editing does not fire this event, because an undo action
+      might bring the range back into existence. <code>from</code>
+      and <code>to</code> give the part of the document that the range
+      spanned when it was cleared.</dd>
+      <dt id="event_hide"><code><strong>"hide"</strong> ()</code></dt>
+      <dd>Fired when the last part of the marker is removed from the
+      document by editing operations.</dd>
+      <dt id="event_unhide"><code><strong>"unhide"</strong> ()</code></dt>
+      <dd>Fired when, after the marker was removed by editing, a undo
+      operation brought the marker back.</dd>
+    </dl>
+
+    <p>Line widgets (<code>CodeMirror.LineWidget</code>), returned
+    by <a href="#addLineWidget"><code>addLineWidget</code></a>, fire
+    these events:</p>
+
+    <dl>
+      <dt id="event_redraw"><code><strong>"redraw"</strong> ()</code></dt>
+      <dd>Fired whenever the editor re-adds the widget to the DOM.
+      This will happen once right after the widget is added (if it is
+      scrolled into view), and then again whenever it is scrolled out
+      of view and back in again, or when changes to the editor options
+      or the line the widget is on require the widget to be
+      redrawn.</dd>
+    </dl>
+
+    <h2 id="keymaps">Keymaps</h2>
+
+    <p>Keymaps are ways to associate keys with functionality. A keymap
+    is an object mapping strings that identify the keys to functions
+    that implement their functionality.</p>
+
+    <p>Keys are identified either by name or by character.
+    The <code>CodeMirror.keyNames</code> object defines names for
+    common keys and associates them with their key codes. Examples of
+    names defined here are <code>Enter</code>, <code>F5</code>,
+    and <code>Q</code>. These can be prefixed
+    with <code>Shift-</code>, <code>Cmd-</code>, <code>Ctrl-</code>,
+    and <code>Alt-</code> (in that order!) to specify a modifier. So
+    for example, <code>Shift-Ctrl-Space</code> would be a valid key
+    identifier.</p>
+
+    <p>Common example: map the Tab key to insert spaces instead of a tab
+    character.</p>
+
+    <pre data-lang="javascript">
+{
+  Tab: function(cm) {
+    var spaces = Array(cm.getOption("indentUnit") + 1).join(" ");
+    cm.replaceSelection(spaces, "end", "+input");
+  }
+}</pre>
+
+    <p>Alternatively, a character can be specified directly by
+    surrounding it in single quotes, for example <code>'$'</code>
+    or <code>'q'</code>. Due to limitations in the way browsers fire
+    key events, these may not be prefixed with modifiers.</p>
+
+    <p>The <code>CodeMirror.keyMap</code> object associates keymaps
+    with names. User code and keymap definitions can assign extra
+    properties to this object. Anywhere where a keymap is expected, a
+    string can be given, which will be looked up in this object. It
+    also contains the <code>"default"</code> keymap holding the
+    default bindings.</p>
+
+    <p id="commands">The values of properties in keymaps can be either functions of
+    a single argument (the CodeMirror instance), strings, or
+    <code>false</code>. Such strings refer to properties of the
+    <code>CodeMirror.commands</code> object, which defines a number of
+    common commands that are used by the default keybindings, and maps
+    them to functions. If the property is set to <code>false</code>,
+    CodeMirror leaves handling of the key up to the browser. A key
+    handler function may return <code>CodeMirror.Pass</code> to indicate
+    that it has decided not to handle the key, and other handlers (or
+    the default behavior) should be given a turn.</p>
+
+    <p>Keys mapped to command names that start with the
+    characters <code>"go"</code> (which should be used for
+    cursor-movement actions) will be fired even when an
+    extra <code>Shift</code> modifier is present (i.e. <code>"Up":
+    "goLineUp"</code> matches both up and shift-up). This is used to
+    easily implement shift-selection.</p>
+
+    <p>Keymaps can defer to each other by defining
+    a <code>fallthrough</code> property. This indicates that when a
+    key is not found in the map itself, one or more other maps should
+    be searched. It can hold either a single keymap or an array of
+    keymaps.</p>
+
+    <p>When a keymap contains a <code>nofallthrough</code> property
+    set to <code>true</code>, keys matched against that map will be
+    ignored if they don't match any of the bindings in the map (no
+    further child maps will be tried). When
+    the <code>disableInput</code> property is set
+    to <code>true</code>, the default effect of inserting a character
+    will be suppressed when the keymap is active as the top-level
+    map.</p>
+
+    <h2 id="styling">Customized Styling</h2>
+
+    <p>Up to a certain extent, CodeMirror's look can be changed by
+    modifying style sheet files. The style sheets supplied by modes
+    simply provide the colors for that mode, and can be adapted in a
+    very straightforward way. To style the editor itself, it is
+    possible to alter or override the styles defined
+    in <a href="../lib/codemirror.css"><code>codemirror.css</code></a>.</p>
+
+    <p>Some care must be taken there, since a lot of the rules in this
+    file are necessary to have CodeMirror function properly. Adjusting
+    colors should be safe, of course, and with some care a lot of
+    other things can be changed as well. The CSS classes defined in
+    this file serve the following roles:</p>
+
+    <dl>
+      <dt id="class_CodeMirror"><code><strong>CodeMirror</strong></code></dt>
+      <dd>The outer element of the editor. This should be used for the
+      editor width, height, borders and positioning. Can also be used
+      to set styles that should hold for everything inside the editor
+      (such as font and font size), or to set a background.</dd>
+
+      <dt id="class_CodeMirror_scroll"><code><strong>CodeMirror-scroll</strong></code></dt>
+      <dd>Whether the editor scrolls (<code>overflow: auto</code> +
+      fixed height). By default, it does. Setting
+      the <code>CodeMirror</code> class to have <code>height:
+      auto</code> and giving this class <code>overflow-x: auto;
+      overflow-y: hidden;</code> will cause the editor
+      to <a href="../demo/resize.html">resize to fit its
+      content</a>.</dd>
+
+      <dt id="class_CodeMirror_focused"><code><strong>CodeMirror-focused</strong></code></dt>
+      <dd>Whenever the editor is focused, the top element gets this
+      class. This is used to hide the cursor and give the selection a
+      different color when the editor is not focused.</dd>
+
+      <dt id="class_CodeMirror_gutters"><code><strong>CodeMirror-gutters</strong></code></dt>
+      <dd>This is the backdrop for all gutters. Use it to set the
+      default gutter background color, and optionally add a border on
+      the right of the gutters.</dd>
+
+      <dt id="class_CodeMirror_linenumbers"><code><strong>CodeMirror-linenumbers</strong></code></dt>
+      <dd>Use this for giving a background or width to the line number
+      gutter.</dd>
+
+      <dt id="class_CodeMirror_linenumber"><code><strong>CodeMirror-linenumber</strong></code></dt>
+      <dd>Used to style the actual individual line numbers. These
+      won't be children of the <code>CodeMirror-linenumbers</code>
+      (plural) element, but rather will be absolutely positioned to
+      overlay it. Use this to set alignment and text properties for
+      the line numbers.</dd>
+
+      <dt id="class_CodeMirror_lines"><code><strong>CodeMirror-lines</strong></code></dt>
+      <dd>The visible lines. This is where you specify vertical
+      padding for the editor content.</dd>
+
+      <dt id="class_CodeMirror_cursor"><code><strong>CodeMirror-cursor</strong></code></dt>
+      <dd>The cursor is a block element that is absolutely positioned.
+      You can make it look whichever way you want.</dd>
+
+      <dt id="class_CodeMirror_selected"><code><strong>CodeMirror-selected</strong></code></dt>
+      <dd>The selection is represented by <code>span</code> elements
+      with this class.</dd>
+
+      <dt id="class_CodeMirror_matchingbracket"><code><strong>CodeMirror-matchingbracket</strong></code>,
+        <code><strong>CodeMirror-nonmatchingbracket</strong></code></dt>
+      <dd>These are used to style matched (or unmatched) brackets.</dd>
+    </dl>
+
+    <p>If your page's style sheets do funky things to
+    all <code>div</code> or <code>pre</code> elements (you probably
+    shouldn't do that), you'll have to define rules to cancel these
+    effects out again for elements under the <code>CodeMirror</code>
+    class.</p>
+
+    <p>Themes are also simply CSS files, which define colors for
+    various syntactic elements. See the files in
+    the <a href="../theme/"><code>theme</code></a> directory.</p>
+
+    <h2 id="api">Programming API</h2>
+
+    <p>A lot of CodeMirror features are only available through its
+    API. Thus, you need to write code (or
+    use <a href="#addons">addons</a>) if you want to expose them to
+    your users.</p>
+
+    <p>Whenever points in the document are represented, the API uses
+    objects with <code>line</code> and <code>ch</code> properties.
+    Both are zero-based. CodeMirror makes sure to 'clip' any positions
+    passed by client code so that they fit inside the document, so you
+    shouldn't worry too much about sanitizing your coordinates. If you
+    give <code>ch</code> a value of <code>null</code>, or don't
+    specify it, it will be replaced with the length of the specified
+    line.</p>
+
+    <p>Methods prefixed with <code>doc.</code> can, unless otherwise
+    specified, be called both on <code>CodeMirror</code> (editor)
+    instances and <code>CodeMirror.Doc</code> instances. Methods
+    prefixed with <code>cm.</code> are <em>only</em> available
+    on <code>CodeMirror</code> instances.</p>
+
+    <h3 id="api_constructor">Constructor</h3>
+
+    <p id="CodeMirror">Constructing an editor instance is done with
+    the <code><strong>CodeMirror</strong>(place: Element|fn(Element),
+    ?option: object)</code> constructor. If the <code>place</code>
+    argument is a DOM element, the editor will be appended to it. If
+    it is a function, it will be called, and is expected to place the
+    editor into the document. <code>options</code> may be an element
+    mapping <a href="#config">option names</a> to values. The options
+    that it doesn't explicitly specify (or all options, if it is not
+    passed) will be taken
+    from <a href="#defaults"><code>CodeMirror.defaults</code></a>.</p>
+
+    <p>Note that the options object passed to the constructor will be
+    mutated when the instance's options
+    are <a href="#setOption">changed</a>, so you shouldn't share such
+    objects between instances.</p>
+
+    <p>See <a href="#fromTextArea"><code>CodeMirror.fromTextArea</code></a>
+    for another way to construct an editor instance.</p>
+
+    <h3 id="api_content">Content manipulation methods</h3>
+
+    <dl>
+      <dt id="getValue"><code><strong>doc.getValue</strong>(?separator: string) → string</code></dt>
+      <dd>Get the current editor content. You can pass it an optional
+      argument to specify the string to be used to separate lines
+      (defaults to <code>"\n"</code>).</dd>
+      <dt id="setValue"><code><strong>doc.setValue</strong>(content: string)</code></dt>
+      <dd>Set the editor content.</dd>
+
+      <dt id="getRange"><code><strong>doc.getRange</strong>(from: {line, ch}, to: {line, ch}, ?separator: string) → string</code></dt>
+      <dd>Get the text between the given points in the editor, which
+      should be <code>{line, ch}</code> objects. An optional third
+      argument can be given to indicate the line separator string to
+      use (defaults to <code>"\n"</code>).</dd>
+      <dt id="replaceRange"><code><strong>doc.replaceRange</strong>(replacement: string, from: {line, ch}, to: {line, ch})</code></dt>
+      <dd>Replace the part of the document between <code>from</code>
+      and <code>to</code> with the given string. <code>from</code>
+      and <code>to</code> must be <code>{line, ch}</code>
+      objects. <code>to</code> can be left off to simply insert the
+      string at position <code>from</code>.</dd>
+
+      <dt id="getLine"><code><strong>doc.getLine</strong>(n: integer) → string</code></dt>
+      <dd>Get the content of line <code>n</code>.</dd>
+      <dt id="setLine"><code><strong>doc.setLine</strong>(n: integer, text: string)</code></dt>
+      <dd>Set the content of line <code>n</code>.</dd>
+      <dt id="removeLine"><code><strong>doc.removeLine</strong>(n: integer)</code></dt>
+      <dd>Remove the given line from the document.</dd>
+
+      <dt id="lineCount"><code><strong>doc.lineCount</strong>() → integer</code></dt>
+      <dd>Get the number of lines in the editor.</dd>
+      <dt id="firstLine"><code><strong>doc.firstLine</strong>() → integer</code></dt>
+      <dd>Get the first line of the editor. This will
+      usually be zero but for <a href="#linkedDoc_from">linked sub-views</a>,
+      or <a href="#api_doc">documents</a> instantiated with a non-zero
+      first line, it might return other values.</dd>
+      <dt id="lastLine"><code><strong>doc.lastLine</strong>() → integer</code></dt>
+      <dd>Get the last line of the editor. This will
+      usually be <code>doc.lineCount() - 1</code>,
+      but for <a href="#linkedDoc_from">linked sub-views</a>,
+      it might return other values.</dd>
+
+      <dt id="getLineHandle"><code><strong>doc.getLineHandle</strong>(num: integer) → LineHandle</code></dt>
+      <dd>Fetches the line handle for the given line number.</dd>
+      <dt id="getLineNumber"><code><strong>doc.getLineNumber</strong>(handle: LineHandle) → integer</code></dt>
+      <dd>Given a line handle, returns the current position of that
+      line (or <code>null</code> when it is no longer in the
+      document).</dd>
+      <dt id="eachLine"><code><strong>doc.eachLine</strong>(f: (line: LineHandle))</code></dt>
+      <dt><code><strong>doc.eachLine</strong>(start: integer, end: integer, f: (line: LineHandle))</code></dt>
+      <dd>Iterate over the whole document, or if <code>start</code>
+      and <code>end</code> line numbers are given, the range
+      from <code>start</code> up to (not including) <code>end</code>,
+      and call <code>f</code> for each line, passing the line handle.
+      This is a faster way to visit a range of line handlers than
+      calling <a href="#getLineHandle"><code>getLineHandle</code></a>
+      for each of them. Note that line handles have
+      a <code>text</code> property containing the line's content (as a
+      string).</dd>
+
+      <dt id="markClean"><code><strong>doc.markClean</strong>()</code></dt>
+      <dd>Set the editor content as 'clean', a flag that it will
+      retain until it is edited, and which will be set again when such
+      an edit is undone again. Useful to track whether the content
+      needs to be saved. This function is deprecated in favor
+      of <a href="#changeGeneration"><code>changeGeneration</code></a>,
+      which allows multiple subsystems to track different notions of
+      cleanness without interfering.</dd>
+      <dt id="changeGeneration"><code><strong>doc.changeGeneration</strong>() → integer</code></dt>
+      <dd>Returns a number that can later be passed
+      to <a href="#isClean"><code>isClean</code></a> to test whether
+      any edits were made (and not undone) in the meantime.</dd>
+      <dt id="isClean"><code><strong>doc.isClean</strong>(?generation: integer) → boolean</code></dt>
+      <dd>Returns whether the document is currently clean — not
+      modified since initialization or the last call
+      to <a href="#markClean"><code>markClean</code></a> if no
+      argument is passed, or since the matching call
+      to <a href="#changeGeneration"><code>changeGeneration</code></a>
+      if a generation value is given.</dd>
+    </dl>
+
+    <h3 id="api_selection">Cursor and selection methods</h3>
+
+    <dl>
+      <dt id="getSelection"><code><strong>doc.getSelection</strong>() → string</code></dt>
+      <dd>Get the currently selected code.</dd>
+      <dt id="replaceSelection"><code><strong>doc.replaceSelection</strong>(replacement: string, ?collapse: string)</code></dt>
+      <dd>Replace the selection with the given string. By default, the
+      new selection will span the inserted text. The
+      optional <code>collapse</code> argument can be used to change
+      this—passing <code>"start"</code> or <code>"end"</code> will
+      collapse the selection to the start or end of the inserted
+      text.</dd>
+
+      <dt id="getCursor"><code><strong>doc.getCursor</strong>(?start: string) → {line, ch}</code></dt>
+      <dd><code>start</code> is a an optional string indicating which
+      end of the selection to return. It may
+      be <code>"start"</code>, <code>"end"</code>, <code>"head"</code>
+      (the side of the selection that moves when you press
+      shift+arrow), or <code>"anchor"</code> (the fixed side of the
+      selection). Omitting the argument is the same as
+      passing <code>"head"</code>. A <code>{line, ch}</code> object
+      will be returned.</dd>
+      <dt id="somethingSelected"><code><strong>doc.somethingSelected</strong>() → boolean</code></dt>
+      <dd>Return true if any text is selected.</dd>
+      <dt id="setCursor"><code><strong>doc.setCursor</strong>(pos: {line, ch})</code></dt>
+      <dd>Set the cursor position. You can either pass a
+      single <code>{line, ch}</code> object, or the line and the
+      character as two separate parameters.</dd>
+      <dt id="setSelection"><code><strong>doc.setSelection</strong>(anchor: {line, ch}, head: {line, ch})</code></dt>
+      <dd>Set the selection range. <code>anchor</code>
+      and <code>head</code> should be <code>{line, ch}</code>
+      objects. <code>head</code> defaults to <code>anchor</code> when
+      not given.</dd>
+      <dt id="extendSelection"><code><strong>doc.extendSelection</strong>(from: {line, ch}, ?to: {line, ch})</code></dt>
+      <dd>Similar
+      to <a href="#setSelection"><code>setSelection</code></a>, but
+      will, if shift is held or
+      the <a href="#setExtending">extending</a> flag is set, move the
+      head of the selection while leaving the anchor at its current
+      place. <code>pos2</code> is optional, and can be passed to
+      ensure a region (for example a word or paragraph) will end up
+      selected (in addition to whatever lies between that region and
+      the current anchor).</dd>
+      <dt id="setExtending"><code><strong>doc.setExtending</strong>(value: boolean)</code></dt>
+      <dd>Sets or clears the 'extending' flag, which acts similar to
+      the shift key, in that it will cause cursor movement and calls
+      to <a href="#extendSelection"><code>extendSelection</code></a>
+      to leave the selection anchor in place.</dd>
+
+      <dt id="hasFocus"><code><strong>cm.hasFocus</strong>() → boolean</code></dt>
+      <dd>Tells you whether the editor currently has focus.</dd>
+
+      <dt id="findPosH"><code><strong>cm.findPosH</strong>(start: {line, ch}, amount: integer, unit: string, visually: boolean) → {line, ch, ?hitSide: boolean}</code></dt>
+      <dd>Used to find the target position for horizontal cursor
+      motion. <code>start</code> is a <code>{line, ch}</code>
+      object, <code>amount</code> an integer (may be negative),
+      and <code>unit</code> one of the
+      string <code>"char"</code>, <code>"column"</code>,
+      or <code>"word"</code>. Will return a position that is produced
+      by moving <code>amount</code> times the distance specified
+      by <code>unit</code>. When <code>visually</code> is true, motion
+      in right-to-left text will be visual rather than logical. When
+      the motion was clipped by hitting the end or start of the
+      document, the returned value will have a <code>hitSide</code>
+      property set to true.</dd>
+      <dt id="findPosV"><code><strong>cm.findPosV</strong>(start: {line, ch}, amount: integer, unit: string) → {line, ch, ?hitSide: boolean}</code></dt>
+      <dd>Similar to <a href="#findPosH"><code>findPosH</code></a>,
+      but used for vertical motion. <code>unit</code> may
+      be <code>"line"</code> or <code>"page"</code>. The other
+      arguments and the returned value have the same interpretation as
+      they have in <code>findPosH</code>.</dd>
+    </dl>
+
+    <h3 id="api_configuration">Configuration methods</h3>
+
+    <dl>
+      <dt id="setOption"><code><strong>cm.setOption</strong>(option: string, value: any)</code></dt>
+      <dd>Change the configuration of the editor. <code>option</code>
+      should the name of an <a href="#config">option</a>,
+      and <code>value</code> should be a valid value for that
+      option.</dd>
+      <dt id="getOption"><code><strong>cm.getOption</strong>(option: string) → any</code></dt>
+      <dd>Retrieves the current value of the given option for this
+      editor instance.</dd>
+
+      <dt id="addKeyMap"><code><strong>cm.addKeyMap</strong>(map: object, bottom: boolean)</code></dt>
+      <dd>Attach an additional <a href="#keymaps">keymap</a> to the
+      editor. This is mostly useful for addons that need to register
+      some key handlers without trampling on
+      the <a href="#option_extraKeys"><code>extraKeys</code></a>
+      option. Maps added in this way have a higher precedence than
+      the <code>extraKeys</code>
+      and <a href="#option_keyMap"><code>keyMap</code></a> options,
+      and between them, the maps added earlier have a lower precedence
+      than those added later, unless the <code>bottom</code> argument
+      was passed, in which case they end up below other keymaps added
+      with this method.</dd>
+      <dt id="removeKeyMap"><code><strong>cm.removeKeyMap</strong>(map: object)</code></dt>
+      <dd>Disable a keymap added
+      with <a href="#addKeyMap"><code>addKeyMap</code></a>. Either
+      pass in the keymap object itself, or a string, which will be
+      compared against the <code>name</code> property of the active
+      keymaps.</dd>
+
+      <dt id="addOverlay"><code><strong>cm.addOverlay</strong>(mode: string|object, ?options: object)</code></dt>
+      <dd>Enable a highlighting overlay. This is a stateless mini-mode
+      that can be used to add extra highlighting. For example,
+      the <a href="../demo/search.html">search addon</a> uses it to
+      highlight the term that's currently being
+      searched. <code>mode</code> can be a <a href="#option_mode">mode
+      spec</a> or a mode object (an object with
+      a <a href="#token"><code>token</code></a> method).
+      The <code>options</code> parameter is optional. If given, it
+      should be an object. Currently, only the <code>opaque</code>
+      option is recognized. This defaults to off, but can be given to
+      allow the overlay styling, when not <code>null</code>, to
+      override the styling of the base mode entirely, instead of the
+      two being applied together.</dd>
+      <dt id="removeOverlay"><code><strong>cm.removeOverlay</strong>(mode: string|object)</code></dt>
+      <dd>Pass this the exact value passed for the <code>mode</code>
+      parameter to <a href="#addOverlay"><code>addOverlay</code></a>,
+      or a string that corresponds to the <code>name</code> propery of
+      that value, to remove an overlay again.</dd>
+
+      <dt id="on"><code><strong>cm.on</strong>(type: string, func: (...args))</code></dt>
+      <dd>Register an event handler for the given event type (a
+      string) on the editor instance. There is also
+      a <code>CodeMirror.on(object, type, func)</code> version
+      that allows registering of events on any object.</dd>
+      <dt id="off"><code><strong>cm.off</strong>(type: string, func: (...args))</code></dt>
+      <dd>Remove an event handler on the editor instance. An
+      equivalent <code>CodeMirror.off(object, type,
+      func)</code> also exists.</dd>
+    </dl>
+
+    <h3 id="api_doc">Document management methods</h3>
+
+    <p id="Doc">Each editor is associated with an instance
+    of <code>CodeMirror.Doc</code>, its document. A document
+    represents the editor content, plus a selection, an undo history,
+    and a <a href="#option_mode">mode</a>. A document can only be
+    associated with a single editor at a time. You can create new
+    documents by calling the <code>CodeMirror.Doc(text, mode,
+    firstLineNumber)</code> constructor. The last two arguments are
+    optional and can be used to set a mode for the document and make
+    it start at a line number other than 0, respectively.</p>
+
+    <dl>
+      <dt id="getDoc"><code><strong>cm.getDoc</strong>() → Doc</code></dt>
+      <dd>Retrieve the currently active document from an editor.</dd>
+      <dt id="getEditor"><code><strong>doc.getEditor</strong>() → CodeMirror</code></dt>
+      <dd>Retrieve the editor associated with a document. May
+      return <code>null</code>.</dd>
+
+      <dt id="swapDoc"><code><strong>cm.swapDoc</strong>(doc: CodeMirror.Doc) → Doc</code></dt>
+      <dd>Attach a new document to the editor. Returns the old
+      document, which is now no longer associated with an editor.</dd>
+
+      <dt id="copy"><code><strong>doc.copy</strong>(copyHistory: boolean) → Doc</code></dt>
+      <dd>Create an identical copy of the given doc.
+      When <code>copyHistory</code> is true, the history will also be
+      copied. Can not be called directly on an editor.</dd>
+
+      <dt id="linkedDoc"><code><strong>doc.linkedDoc</strong>(options: object) → Doc</code></dt>
+      <dd>Create a new document that's linked to the target document.
+      Linked documents will stay in sync (changes to one are also
+      applied to the other) until <a href="#unlinkDoc">unlinked</a>.
+      These are the options that are supported:
+        <dl>
+          <dt id="linkedDoc_sharedHist"><code><strong>sharedHist</strong>: boolean</code></dt>
+          <dd>When turned on, the linked copy will share an undo
+          history with the original. Thus, something done in one of
+          the two can be undone in the other, and vice versa.</dd>
+          <dt id="linkedDoc_from"><code><strong>from</strong>: integer</code></dt>
+          <dt id="linkedDoc_to"><code><strong>to</strong>: integer</code></dt>
+          <dd>Can be given to make the new document a subview of the
+          original. Subviews only show a given range of lines. Note
+          that line coordinates inside the subview will be consistent
+          with those of the parent, so that for example a subview
+          starting at line 10 will refer to its first line as line 10,
+          not 0.</dd>
+          <dt id="linkedDoc_mode"><code><strong>mode</strong>: string|object</code></dt>
+          <dd>By default, the new document inherits the mode of the
+          parent. This option can be set to
+          a <a href="#option_mode">mode spec</a> to give it a
+          different mode.</dd>
+        </dl></dd>
+      <dt id="unlinkDoc"><code><strong>doc.unlinkDoc</strong>(doc: CodeMirror.Doc)</code></dt>
+      <dd>Break the link between two documents. After calling this,
+      changes will no longer propagate between the documents, and, if
+      they had a shared history, the history will become
+      separate.</dd>
+      <dt id="iterLinkedDocs"><code><strong>doc.iterLinkedDocs</strong>(function: (doc: CodeMirror.Doc, sharedHist: boolean))</code></dt>
+      <dd>Will call the given function for all documents linked to the
+      target document. It will be passed two arguments, the linked document
+      and a boolean indicating whether that document shares history
+      with the target.</dd>
+    </dl>
+
+    <h3 id="api_history">History-related methods</h3>
+
+    <dl>
+      <dt id="undo"><code><strong>doc.undo</strong>()</code></dt>
+      <dd>Undo one edit (if any undo events are stored).</dd>
+      <dt id="redo"><code><strong>doc.redo</strong>()</code></dt>
+      <dd>Redo one undone edit.</dd>
+
+      <dt id="historySize"><code><strong>doc.historySize</strong>() → {undo: integer, redo: integer}</code></dt>
+      <dd>Returns an object with <code>{undo, redo}</code> properties,
+      both of which hold integers, indicating the amount of stored
+      undo and redo operations.</dd>
+      <dt id="clearHistory"><code><strong>doc.clearHistory</strong>()</code></dt>
+      <dd>Clears the editor's undo history.</dd>
+      <dt id="getHistory"><code><strong>doc.getHistory</strong>() → object</code></dt>
+      <dd>Get a (JSON-serializeable) representation of the undo history.</dd>
+      <dt id="setHistory"><code><strong>doc.setHistory</strong>(history: object)</code></dt>
+      <dd>Replace the editor's undo history with the one provided,
+      which must be a value as returned
+      by <a href="#getHistory"><code>getHistory</code></a>. Note that
+      this will have entirely undefined results if the editor content
+      isn't also the same as it was when <code>getHistory</code> was
+      called.</dd>
+    </dl>
+
+    <h3 id="api_marker">Text-marking methods</h3>
+
+    <dl>
+      <dt id="markText"><code><strong>doc.markText</strong>(from: {line, ch}, to: {line, ch}, ?options: object) → TextMarker</code></dt>
+      <dd>Can be used to mark a range of text with a specific CSS
+      class name. <code>from</code> and <code>to</code> should
+      be <code>{line, ch}</code> objects. The <code>options</code>
+      parameter is optional. When given, it should be an object that
+      may contain the following configuration options:
+      <dl>
+        <dt id="mark_className"><code><strong>className</strong>: string</code></dt>
+        <dd>Assigns a CSS class to the marked stretch of text.</dd>
+        <dt id="mark_inclusiveLeft"><code><strong>inclusiveLeft</strong>: boolean</code></dt>
+        <dd>Determines whether
+        text inserted on the left of the marker will end up inside
+        or outside of it.</dd>
+        <dt id="mark_inclusiveRight"><code><strong>inclusiveRight</strong>: boolean</code></dt>
+        <dd>Like <code>inclusiveLeft</code>,
+        but for the right side.</dd>
+        <dt id="mark_atomic"><code><strong>atomic</strong>: boolean</code></dt>
+        <dd>Atomic ranges act as a single unit when cursor movement is
+        concerned—i.e. it is impossible to place the cursor inside of
+        them. In atomic ranges, <code>inclusiveLeft</code>
+        and <code>inclusiveRight</code> have a different meaning—they
+        will prevent the cursor from being placed respectively
+        directly before and directly after the range.</dd>
+        <dt id="mark_collapsed"><code><strong>collapsed</strong>: boolean</code></dt>
+        <dd>Collapsed ranges do not show up in the display. Setting a
+        range to be collapsed will automatically make it atomic.</dd>
+        <dt id="mark_clearOnEnter"><code><strong>clearOnEnter</strong>: boolean</code></dt>
+        <dd>When enabled, will cause the mark to clear itself whenever
+        the cursor enters its range. This is mostly useful for
+        text-replacement widgets that need to 'snap open' when the
+        user tries to edit them. The
+        <a href="#event_clear"><code>"clear"</code></a> event
+        fired on the range handle can be used to be notified when this
+        happens.</dd>
+        <dt id="mark_replacedWith"><code><strong>replacedWith</strong>: Element</code></dt>
+        <dd>Use a given node to display this range. Implies both
+        collapsed and atomic. The given DOM node <em>must</em> be an
+        inline element (as opposed to a block element).</dd>
+        <dt><code><strong>handleMouseEvents</strong>: boolean</code></dt>
+        <dd>When <code>replacedWith</code> is given, this determines
+        whether the editor will capture mouse and drag events
+        occurring in this widget. Default is false—the events will be
+        left alone for the default browser handler, or specific
+        handlers on the widget, to capture.</dd>
+        <dt id="mark_readOnly"><code><strong>readOnly</strong>: boolean</code></dt>
+        <dd>A read-only span can, as long as it is not cleared, not be
+        modified except by
+        calling <a href="#setValue"><code>setValue</code></a> to reset
+        the whole document. <em>Note:</em> adding a read-only span
+        currently clears the undo history of the editor, because
+        existing undo events being partially nullified by read-only
+        spans would corrupt the history (in the current
+        implementation).</dd>
+        <dt id="mark_addToHistory"><code><strong>addToHistory</strong>: boolean</code></dt>
+        <dd>When set to true (default is false), adding this marker
+        will create an event in the undo history that can be
+        individually undone (clearing the marker).</dd>
+        <dt id="mark_startStyle"><code><strong>startStyle</strong>: string</code></dt><dd>Can be used to specify
+        an extra CSS class to be applied to the leftmost span that
+        is part of the marker.</dd>
+        <dt id="mark_endStyle"><code><strong>endStyle</strong>: string</code></dt><dd>Equivalent
+        to <code>startStyle</code>, but for the rightmost span.</dd>
+        <dt id="mark_title"><code><strong>title</strong>:
+        string</code></dt><dd>When given, will give the nodes created
+        for this span a HTML <code>title</code> attribute with the
+        given value.</dd>
+        <dt id="mark_shared"><code><strong>shared</strong>: boolean</code></dt><dd>When the
+        target document is <a href="#linkedDoc">linked</a> to other
+        documents, you can set <code>shared</code> to true to make the
+        marker appear in all documents. By default, a marker appears
+        only in its target document.</dd>
+      </dl>
+      The method will return an object that represents the marker
+      (with constuctor <code>CodeMirror.TextMarker</code>), which
+      exposes three methods:
+      <code><strong>clear</strong>()</code>, to remove the mark,
+      <code><strong>find</strong>()</code>, which returns
+      a <code>{from, to}</code> object (both holding document
+      positions), indicating the current position of the marked range,
+      or <code>undefined</code> if the marker is no longer in the
+      document, and finally <code><strong>changed</strong>()</code>,
+      which you can call if you've done something that might change
+      the size of the marker (for example changing the content of
+      a <a href="#mark_replacedWith"><code>replacedWith</code></a>
+      node), and want to cheaply update the display.</dd>
+
+      <dt id="setBookmark"><code><strong>doc.setBookmark</strong>(pos: {line, ch}, ?options: object) → TextMarker</code></dt>
+      <dd>Inserts a bookmark, a handle that follows the text around it
+      as it is being edited, at the given position. A bookmark has two
+      methods <code>find()</code> and <code>clear()</code>. The first
+      returns the current position of the bookmark, if it is still in
+      the document, and the second explicitly removes the bookmark.
+      The options argument is optional. If given, the following
+      properties are recognized:
+      <dl>
+        <dt><code><strong>widget</strong>: Element</code></dt><dd>Can be used to display a DOM
+        node at the current location of the bookmark (analogous to
+        the <a href="#mark_replacedWith"><code>replacedWith</code></a>
+        option to <code>markText</code>).</dd>
+        <dt><code><strong>insertLeft</strong>: boolean</code></dt><dd>By default, text typed
+        when the cursor is on top of the bookmark will end up to the
+        right of the bookmark. Set this option to true to make it go
+        to the left instead.</dd>
+      </dl></dd>
+
+      <dt id="findMarksAt"><code><strong>doc.findMarksAt</strong>(pos: {line, ch}) → array&lt;TextMarker&gt;</code></dt>
+      <dd>Returns an array of all the bookmarks and marked ranges
+      present at the given position.</dd>
+      <dt id="getAllMarks"><code><strong>doc.getAllMarks</strong>() → array&lt;TextMarker&gt;</code></dt>
+      <dd>Returns an array containing all marked ranges in the document.</dd>
+    </dl>
+
+    <h3 id="api_decoration">Widget, gutter, and decoration methods</h3>
+
+    <dl>
+      <dt id="setGutterMarker"><code><strong>cm.setGutterMarker</strong>(line: integer|LineHandle, gutterID: string, value: Element) → LineHandle</code></dt>
+      <dd>Sets the gutter marker for the given gutter (identified by
+      its CSS class, see
+      the <a href="#option_gutters"><code>gutters</code></a> option)
+      to the given value. Value can be either <code>null</code>, to
+      clear the marker, or a DOM element, to set it. The DOM element
+      will be shown in the specified gutter next to the specified
+      line.</dd>
+
+      <dt id="clearGutter"><code><strong>cm.clearGutter</strong>(gutterID: string)</code></dt>
+      <dd>Remove all gutter markers in
+      the <a href="#option_gutters">gutter</a> with the given ID.</dd>
+
+      <dt id="addLineClass"><code><strong>cm.addLineClass</strong>(line: integer|LineHandle, where: string, class: string) → LineHandle</code></dt>
+      <dd>Set a CSS class name for the given line. <code>line</code>
+      can be a number or a line handle. <code>where</code> determines
+      to which element this class should be applied, can can be one
+      of <code>"text"</code> (the text element, which lies in front of
+      the selection), <code>"background"</code> (a background element
+      that will be behind the selection), or <code>"wrap"</code> (the
+      wrapper node that wraps all of the line's elements, including
+      gutter elements). <code>class</code> should be the name of the
+      class to apply.</dd>
+
+      <dt id="removeLineClass"><code><strong>cm.removeLineClass</strong>(line: integer|LineHandle, where: string, class: string) → LineHandle</code></dt>
+      <dd>Remove a CSS class from a line. <code>line</code> can be a
+      line handle or number. <code>where</code> should be one
+      of <code>"text"</code>, <code>"background"</code>,
+      or <code>"wrap"</code>
+      (see <a href="#addLineClass"><code>addLineClass</code></a>). <code>class</code>
+      can be left off to remove all classes for the specified node, or
+      be a string to remove only a specific class.</dd>
+
+      <dt id="lineInfo"><code><strong>cm.lineInfo</strong>(line: integer|LineHandle) → object</code></dt>
+      <dd>Returns the line number, text content, and marker status of
+      the given line, which can be either a number or a line handle.
+      The returned object has the structure <code>{line, handle, text,
+      gutterMarkers, textClass, bgClass, wrapClass, widgets}</code>,
+      where <code>gutterMarkers</code> is an object mapping gutter IDs
+      to marker elements, and <code>widgets</code> is an array
+      of <a href="#addLineWidget">line widgets</a> attached to this
+      line, and the various class properties refer to classes added
+      with <a href="#addLineClass"><code>addLineClass</code></a>.</dd>
+
+      <dt id="addWidget"><code><strong>cm.addWidget</strong>(pos: {line, ch}, node: Element, scrollIntoView: boolean)</code></dt>
+      <dd>Puts <code>node</code>, which should be an absolutely
+      positioned DOM node, into the editor, positioned right below the
+      given <code>{line, ch}</code> position.
+      When <code>scrollIntoView</code> is true, the editor will ensure
+      that the entire node is visible (if possible). To remove the
+      widget again, simply use DOM methods (move it somewhere else, or
+      call <code>removeChild</code> on its parent).</dd>
+
+      <dt id="addLineWidget"><code><strong>cm.addLineWidget</strong>(line: integer|LineHandle, node: Element, ?options: object) → LineWidget</code></dt>
+      <dd>Adds a line widget, an element shown below a line, spanning
+      the whole of the editor's width, and moving the lines below it
+      downwards. <code>line</code> should be either an integer or a
+      line handle, and <code>node</code> should be a DOM node, which
+      will be displayed below the given line. <code>options</code>,
+      when given, should be an object that configures the behavior of
+      the widget. The following options are supported (all default to
+      false):
+        <dl>
+          <dt><code><strong>coverGutter</strong>: boolean</code></dt>
+          <dd>Whether the widget should cover the gutter.</dd>
+          <dt><code><strong>noHScroll</strong>: boolean</code></dt>
+          <dd>Whether the widget should stay fixed in the face of
+          horizontal scrolling.</dd>
+          <dt><code><strong>above</strong>: boolean</code></dt>
+          <dd>Causes the widget to be placed above instead of below
+          the text of the line.</dd>
+          <dt><code><strong>showIfHidden</strong>: boolean</code></dt>
+          <dd>When true, will cause the widget to be rendered even if
+          the line it is associated with is hidden.</dd>
+          <dt><code><strong>handleMouseEvents</strong>: boolean</code></dt>
+          <dd>Determines whether the editor will capture mouse and
+          drag events occurring in this widget. Default is false—the
+          events will be left alone for the default browser handler,
+          or specific handlers on the widget, to capture.</dd>
+          <dt><code><strong>insertAt</strong>: integer</code></dt>
+          <dd>By default, the widget is added below other widgets for
+          the line. This option can be used to place it at a different
+          position (zero for the top, N to put it after the Nth other
+          widget). Note that this only has effect once, when the
+          widget is created.
+        </dl>
+      Note that the widget node will become a descendant of nodes with
+      CodeMirror-specific CSS classes, and those classes might in some
+      cases affect it. This method returns an object that represents
+      the widget placement. It'll have a <code>line</code> property
+      pointing at the line handle that it is associated with, and the following methods:
+        <dl>
+          <dt id="widget_clear"><code><strong>clear</strong>()</code></dt><dd>Removes the widget.</dd>
+          <dt id="widget_changed"><code><strong>changed</strong>()</code></dt><dd>Call
+          this if you made some change to the widget's DOM node that
+          might affect its height. It'll force CodeMirror to update
+          the height of the line that contains the widget.</dd>
+        </dl>
+      </dd>
+    </dl>
+
+    <h3 id="api_sizing">Sizing, scrolling and positioning methods</h3>
+
+    <dl>
+      <dt id="setSize"><code><strong>cm.setSize</strong>(width: number|string, height: number|string)</code></dt>
+      <dd>Programatically set the size of the editor (overriding the
+      applicable <a href="#css-resize">CSS
+      rules</a>). <code>width</code> and <code>height</code> height
+      can be either numbers (interpreted as pixels) or CSS units
+      (<code>"100%"</code>, for example). You can
+      pass <code>null</code> for either of them to indicate that that
+      dimension should not be changed.</dd>
+
+      <dt id="scrollTo"><code><strong>cm.scrollTo</strong>(x: number, y: number)</code></dt>
+      <dd>Scroll the editor to a given (pixel) position. Both
+      arguments may be left as <code>null</code>
+      or <code>undefined</code> to have no effect.</dd>
+      <dt id="getScrollInfo"><code><strong>cm.getScrollInfo</strong>() → {left, top, width, height, clientWidth, clientHeight}</code></dt>
+      <dd>Get an <code>{left, top, width, height, clientWidth,
+      clientHeight}</code> object that represents the current scroll
+      position, the size of the scrollable area, and the size of the
+      visible area (minus scrollbars).</dd>
+      <dt id="scrollIntoView"><code><strong>cm.scrollIntoView</strong>(pos: {line, ch}|{left, top, right, bottom}, ?margin: number)</code></dt>
+      <dd>Scrolls the given element into view. <code>pos</code> may be
+      either a <code>{line, ch}</code> position, referring to a given
+      character, <code>null</code>, to refer to the cursor, or
+      a <code>{left, top, right, bottom}</code> object, in
+      editor-local coordinates. The <code>margin</code> parameter is
+      optional. When given, it indicates the amount of pixels around
+      the given area that should be made visible as well.</dd>
+
+      <dt id="cursorCoords"><code><strong>cm.cursorCoords</strong>(where: boolean|{line, ch}, mode: string) → {left, top, bottom}</code></dt>
+      <dd>Returns an <code>{left, top, bottom}</code> object
+      containing the coordinates of the cursor position.
+      If <code>mode</code> is <code>"local"</code>, they will be
+      relative to the top-left corner of the editable document. If it
+      is <code>"page"</code> or not given, they are relative to the
+      top-left corner of the page. <code>where</code> can be a boolean
+      indicating whether you want the start (<code>true</code>) or the
+      end (<code>false</code>) of the selection, or, if a <code>{line,
+      ch}</code> object is given, it specifies the precise position at
+      which you want to measure.</dd>
+      <dt id="charCoords"><code><strong>cm.charCoords</strong>(pos: {line, ch}, ?mode: string) → {left, right, top, bottom}</code></dt>
+      <dd>Returns the position and dimensions of an arbitrary
+      character. <code>pos</code> should be a <code>{line, ch}</code>
+      object. This differs from <code>cursorCoords</code> in that
+      it'll give the size of the whole character, rather than just the
+      position that the cursor would have when it would sit at that
+      position.</dd>
+      <dt id="coordsChar"><code><strong>cm.coordsChar</strong>(object: {left, top}, ?mode: string) → {line, ch}</code></dt>
+      <dd>Given an <code>{left, top}</code> object, returns
+      the <code>{line, ch}</code> position that corresponds to it. The
+      optional <code>mode</code> parameter determines relative to what
+      the coordinates are interpreted. It may
+      be <code>"window"</code>, <code>"page"</code> (the default),
+      or <code>"local"</code>.</dd>
+      <dt id="lineAtHeight"><code><strong>cm.lineAtHeight</strong>(height: number, ?mode: string) → number</code></dt>
+      <dd>Computes the line at the given pixel
+      height. <code>mode</code> can be one of the same strings
+      that <a href="#coordsChar"><code>coordsChar</code></a>
+      accepts.</dd>
+      <dt id="heightAtLine"><code><strong>cm.heightAtLine</strong>(line: number, ?mode: string) → number</code></dt>
+      <dd>Computes the height of the top of a line, in the coordinate
+      system specified by <code>mode</code>
+      (see <a href="#coordsChar"><code>coordsChar</code></a>), which
+      defaults to <code>"page"</code>. When a line below the bottom of
+      the document is specified, the returned value is the bottom of
+      the last line in the document.</dd>
+      <dt id="defaultTextHeight"><code><strong>cm.defaultTextHeight</strong>() → number</code></dt>
+      <dd>Returns the line height of the default font for the editor.</dd>
+      <dt id="defaultCharWidth"><code><strong>cm.defaultCharWidth</strong>() → number</code></dt>
+      <dd>Returns the pixel width of an 'x' in the default font for
+      the editor. (Note that for non-monospace fonts, this is mostly
+      useless, and even for monospace fonts, non-ascii characters
+      might have a different width).</dd>
+
+      <dt id="getViewport"><code><strong>cm.getViewport</strong>() → {from: number, to: number}</code></dt>
+      <dd>Returns a <code>{from, to}</code> object indicating the
+      start (inclusive) and end (exclusive) of the currently rendered
+      part of the document. In big documents, when most content is
+      scrolled out of view, CodeMirror will only render the visible
+      part, and a margin around it. See also
+      the <a href="#event_viewportChange"><code>viewportChange</code></a>
+      event.</dd>
+
+      <dt id="refresh"><code><strong>cm.refresh</strong>()</code></dt>
+      <dd>If your code does something to change the size of the editor
+      element (window resizes are already listened for), or unhides
+      it, you should probably follow up by calling this method to
+      ensure CodeMirror is still looking as intended.</dd>
+    </dl>
+
+    <h3 id="api_mode">Mode, state, and token-related methods</h3>
+
+    <p>When writing language-aware functionality, it can often be
+    useful to hook into the knowledge that the CodeMirror language
+    mode has. See <a href="#modeapi">the section on modes</a> for a
+    more detailed description of how these work.</p>
+
+    <dl>
+      <dt id="getMode"><code><strong>doc.getMode</strong>() → object</code></dt>
+      <dd>Gets the (outer) mode object for the editor. Note that this
+      is distinct from <code>getOption("mode")</code>, which gives you
+      the mode specification, rather than the resolved, instantiated
+      <a href="#defineMode">mode object</a>.</dd>
+
+      <dt id="getModeAt"><code><strong>doc.getModeAt</strong>(pos: {line, ch}) → object</code></dt>
+      <dd>Gets the inner mode at a given position. This will return
+      the same as <a href="#getMode"><code>getMode</code></a> for
+      simple modes, but will return an inner mode for nesting modes
+      (such as <code>htmlmixed</code>).</dd>
+
+      <dt id="getTokenAt"><code><strong>cm.getTokenAt</strong>(pos: {line, ch}, ?precise: boolean) → object</code></dt>
+      <dd>Retrieves information about the token the current mode found
+      before the given position (a <code>{line, ch}</code> object). The
+      returned object has the following properties:
+      <dl>
+        <dt><code><strong>start</strong></code></dt><dd>The character (on the given line) at which the token starts.</dd>
+        <dt><code><strong>end</strong></code></dt><dd>The character at which the token ends.</dd>
+        <dt><code><strong>string</strong></code></dt><dd>The token's string.</dd>
+        <dt><code><strong>type</strong></code></dt><dd>The token type the mode assigned
+        to the token, such as <code>"keyword"</code>
+        or <code>"comment"</code> (may also be null).</dd>
+        <dt><code><strong>state</strong></code></dt><dd>The mode's state at the end of this token.</dd>
+      </dl>
+      If <code>precise</code> is true, the token will be guaranteed to be accurate based on recent edits. If false or
+      not specified, the token will use cached state information, which will be faster but might not be accurate if
+      edits were recently made and highlighting has not yet completed.
+      </dd>
+
+      <dt id="getTokenTypeAt"><code><strong>cm.getTokenTypeAt</strong>(pos: {line, ch}) → string</code></dt>
+      <dd>This is a (much) cheaper version
+      of <a href="#getTokenAt"><code>getTokenAt</code></a> useful for
+      when you just need the type of the token at a given position,
+      and no other information. Will return <code>null</code> for
+      unstyled tokens, and a string, potentially containing multiple
+      space-separated style names, otherwise.</dd>
+
+      <dt id="getHelper"><code><strong>cm.getHelper</strong>(pos: {line, ch}, type: string) → helper</code></dt>
+      <dd>Fetch appropriate helper for the given position. Helpers
+      provide a way to look up functionality appropriate for a mode.
+      The <code>type</code> argument provides the helper namespace
+      (see
+      also <a href="#registerHelper"><code>registerHelper</code></a>),
+      in which the value will be looked up. The key that is used
+      depends on the <a href="#getMode">mode</a> active at the given
+      position. If the mode object contains a property with the same
+      name as the <code>type</code> argument, that is tried first.
+      Next, the mode's <code>helperType</code>, if any, is tried. And
+      finally, the mode's name.</dd>
+
+      <dt id="getStateAfter"><code><strong>cm.getStateAfter</strong>(?line: integer, ?precise: boolean) → object</code></dt>
+      <dd>Returns the mode's parser state, if any, at the end of the
+      given line number. If no line number is given, the state at the
+      end of the document is returned. This can be useful for storing
+      parsing errors in the state, or getting other kinds of
+      contextual information for a line. <code>precise</code> is defined
+      as in <code>getTokenAt()</code>.</dd>
+    </dl>
+
+    <h3 id="api_misc">Miscellaneous methods</h3>
+
+    <dl>
+      <dt id="operation"><code><strong>cm.operation</strong>(func: () → any) → any</code></dt>
+      <dd>CodeMirror internally buffers changes and only updates its
+      DOM structure after it has finished performing some operation.
+      If you need to perform a lot of operations on a CodeMirror
+      instance, you can call this method with a function argument. It
+      will call the function, buffering up all changes, and only doing
+      the expensive update after the function returns. This can be a
+      lot faster. The return value from this method will be the return
+      value of your function.</dd>
+
+      <dt id="indentLine"><code><strong>cm.indentLine</strong>(line: integer, ?dir: string|integer)</code></dt>
+      <dd>Adjust the indentation of the given line. The second
+      argument (which defaults to <code>"smart"</code>) may be one of:
+        <dl>
+          <dt><code><strong>"prev"</strong></code></dt>
+          <dd>Base indentation on the indentation of the previous line.</dd>
+          <dt><code><strong>"smart"</strong></code></dt>
+          <dd>Use the mode's smart indentation if available, behave
+          like <code>"prev"</code> otherwise.</dd>
+          <dt><code><strong>"add"</strong></code></dt>
+          <dd>Increase the indentation of the line by
+          one <a href="#option_indentUnit">indent unit</a>.</dd>
+          <dt><code><strong>"subtract"</strong></code></dt>
+          <dd>Reduce the indentation of the line.</dd>
+          <dt><code><strong>&lt;integer></strong></code></dt>
+          <dd>Add (positive number) or reduce (negative number) the
+          indentation by the given amount of spaces.</dd>
+        </dl></dd>
+
+      <dt id="toggleOverwrite"><code><strong>cm.toggleOverwrite</strong>(?value: bool)</code></dt>
+      <dd>Switches between overwrite and normal insert mode (when not
+      given an argument), or sets the overwrite mode to a specific
+      state (when given an argument).</dd>
+
+      <dt id="posFromIndex"><code><strong>doc.posFromIndex</strong>(index: integer) → {line, ch}</code></dt>
+      <dd>Calculates and returns a <code>{line, ch}</code> object for a
+      zero-based <code>index</code> who's value is relative to the start of the
+      editor's text. If the <code>index</code> is out of range of the text then
+      the returned object is clipped to start or end of the text
+      respectively.</dd>
+      <dt id="indexFromPos"><code><strong>doc.indexFromPos</strong>(object: {line, ch}) → integer</code></dt>
+      <dd>The reverse of <a href="#posFromIndex"><code>posFromIndex</code></a>.</dd>
+
+      <dt id="focus"><code><strong>cm.focus</strong>()</code></dt>
+      <dd>Give the editor focus.</dd>
+
+      <dt id="getInputField"><code><strong>cm.getInputField</strong>() → TextAreaElement</code></dt>
+      <dd>Returns the hidden textarea used to read input.</dd>
+      <dt id="getWrapperElement"><code><strong>cm.getWrapperElement</strong>() → Element</code></dt>
+      <dd>Returns the DOM node that represents the editor, and
+      controls its size. Remove this from your tree to delete an
+      editor instance.</dd>
+      <dt id="getScrollerElement"><code><strong>cm.getScrollerElement</strong>() → Element</code></dt>
+      <dd>Returns the DOM node that is responsible for the scrolling
+      of the editor.</dd>
+      <dt id="getGutterElement"><code><strong>cm.getGutterElement</strong>() → Element</code></dt>
+      <dd>Fetches the DOM node that contains the editor gutters.</dd>
+    </dl>
+
+    <h3 id="api_static">Static properties</h3>
+    <p>The <code>CodeMirror</code> object itself provides
+    several useful properties.</p>
+
+    <dl>
+      <dt id="version"><code><strong>CodeMirror.version</strong>: string</code></dt>
+      <dd>It contains a string that indicates the version of the
+      library. This is a triple of
+      integers <code>"major.minor.patch"</code>,
+      where <code>patch</code> is zero for releases, and something
+      else (usually one) for dev snapshots.</dd>
+
+      <dt id="fromTextArea"><code><strong>CodeMirror.fromTextArea</strong>(textArea: TextAreaElement, ?config: object)</code></dt>
+      <dd>
+        The method provides another way to initialize an editor. It takes a
+        textarea DOM node as first argument and an optional configuration
+        object as second. It will replace the textarea with a CodeMirror
+        instance, and wire up the form of that textarea (if any) to make
+        sure the editor contents are put into the textarea when the form
+        is submitted. A CodeMirror instance created this way has three
+        additional methods:
+        <dl>
+          <dt id="save"><code><strong>cm.save</strong>()</code></dt>
+          <dd>Copy the content of the editor into the textarea.</dd>
+
+          <dt id="toTextArea"><code><strong>cm.toTextArea</strong>()</code></dt>
+          <dd>Remove the editor, and restore the original textarea (with
+          the editor's current content).</dd>
+
+          <dt id="getTextArea"><code><strong>cm.getTextArea</strong>() → TextAreaElement</code></dt>
+          <dd>Returns the textarea that the instance was based on.</dd>
+        </dl>
+      </dd>
+
+      <dt id="defaults"><code><strong>CodeMirror.defaults</strong>: object</code></dt>
+      <dd>An object containing default values for
+      all <a href="#config">options</a>. You can assign to its
+      properties to modify defaults (though this won't affect editors
+      that have already been created).</dd>
+
+      <dt id="defineExtension"><code><strong>CodeMirror.defineExtension</strong>(name: string, value: any)</code></dt>
+      <dd>If you want to define extra methods in terms of the
+      CodeMirror API, it is possible to
+      use <code>defineExtension</code>. This will cause the given
+      value (usually a method) to be added to all CodeMirror instances
+      created from then on.</dd>
+
+      <dt id="defineDocExtension"><code><strong>CodeMirror.defineDocExtension</strong>(name: string, value: any)</code></dt>
+      <dd>Like <a href="#defineExtenstion"><code>defineExtension</code></a>,
+      but the method will be added to the interface
+      for <a href="#Doc"><code>Doc</code></a> objects instead.</dd>
+
+      <dt id="defineOption"><code><strong>CodeMirror.defineOption</strong>(name: string,
+      default: any, updateFunc: function)</code></dt>
+      <dd>Similarly, <code>defineOption</code> can be used to define new options for
+      CodeMirror. The <code>updateFunc</code> will be called with the
+      editor instance and the new value when an editor is initialized,
+      and whenever the option is modified
+      through <a href="#setOption"><code>setOption</code></a>.</dd>
+
+      <dt id="defineInitHook"><code><strong>CodeMirror.defineInitHook</strong>(func: function)</code></dt>
+      <dd>If your extention just needs to run some
+      code whenever a CodeMirror instance is initialized,
+      use <code>CodeMirror.defineInitHook</code>. Give it a function as
+      its only argument, and from then on, that function will be called
+      (with the instance as argument) whenever a new CodeMirror instance
+      is initialized.</dd>
+
+      <dt id="registerHelper"><code><strong>CodeMirror.registerHelper</strong>(type: string, name: string, value: helper)</code></dt>
+      <dd>Registers a helper value with the given <code>name</code> in
+      the given namespace (<code>type</code>). This is used to define
+      functionality that may be looked up by mode. Will create (if it
+      doesn't already exist) a property on the <code>CodeMirror</code>
+      object for the given <code>type</code>, pointing to an object
+      that maps names to values. I.e. after
+      doing <code>CodeMirror.registerHelper("hint", "foo",
+      myFoo)</code>, the value <code>CodeMirror.hint.foo</code> will
+      point to <code>myFoo</code>.</dd>
+
+      <dt id="Pos"><code><strong>CodeMirror.Pos</strong>(line: integer, ?ch: integer)</code></dt>
+      <dd>A constructor for the <code>{line, ch}</code> objects that
+      are used to represent positions in editor documents.</dd>
+
+      <dt id="changeEnd"><code><strong>CodeMirror.changeEnd</strong>(change: object) → {line, ch}</code></dt>
+      <dd>Utility function that computes an end position from a change
+      (an object with <code>from</code>, <code>to</code>,
+      and <code>text</code> properties, as passed to
+      various <a href="#event_change">event handlers</a>). The
+      returned position will be the end of the changed
+      range, <em>after</em> the change is applied.</dd>
+    </dl>
+
+    <h2 id="addons">Addons</h2>
+
+    <p>The <code>addon</code> directory in the distribution contains a
+    number of reusable components that implement extra editor
+    functionality. In brief, they are:</p>
+
+    <dl>
+      <dt id="addon_dialog"><a href="../addon/dialog/dialog.js"><code>dialog/dialog.js</code></a></dt>
+      <dd>Provides a very simple way to query users for text input.
+      Adds an <code>openDialog</code> method to CodeMirror instances,
+      which can be called with an HTML fragment that provides the
+      prompt (should include an <code>input</code> tag), and a
+      callback function that is called when text has been entered.
+      Depends on <code>addon/dialog/dialog.css</code>.</dd>
+
+      <dt id="addon_searchcursor"><a href="../addon/search/searchcursor.js"><code>search/searchcursor.js</code></a></dt>
+      <dd>Adds the <code>getSearchCursor(query, start, caseFold) →
+      cursor</code> method to CodeMirror instances, which can be used
+      to implement search/replace functionality. <code>query</code>
+      can be a regular expression or a string (only strings will match
+      across lines—if they contain newlines). <code>start</code>
+      provides the starting position of the search. It can be
+      a <code>{line, ch}</code> object, or can be left off to default
+      to the start of the document. <code>caseFold</code> is only
+      relevant when matching a string. It will cause the search to be
+      case-insensitive. A search cursor has the following methods:
+        <dl>
+          <dt><code><strong>findNext</strong>() → boolean</code></dt>
+          <dt><code><strong>findPrevious</strong>() → boolean</code></dt>
+          <dd>Search forward or backward from the current position.
+          The return value indicates whether a match was found. If
+          matching a regular expression, the return value will be the
+          array returned by the <code>match</code> method, in case you
+          want to extract matched groups.</dd>
+          <dt><code><strong>from</strong>() → {line, ch}</code></dt>
+          <dt><code><strong>to</strong>() → {line, ch}</code></dt>
+          <dd>These are only valid when the last call
+          to <code>findNext</code> or <code>findPrevious</code> did
+          not return false. They will return <code>{line, ch}</code>
+          objects pointing at the start and end of the match.</dd>
+          <dt><code><strong>replace</strong>(text: string)</code></dt>
+          <dd>Replaces the currently found match with the given text
+          and adjusts the cursor position to reflect the
+          replacement.</dd>
+        </dl></dd>
+
+      <dt id="addon_search"><a href="../addon/search/search.js"><code>search/search.js</code></a></dt>
+      <dd>Implements the search commands. CodeMirror has keys bound to
+      these by default, but will not do anything with them unless an
+      implementation is provided. Depends
+      on <code>searchcursor.js</code>, and will make use
+      of <a href="#addon_dialog"><code>openDialog</code></a> when
+      available to make prompting for search queries less ugly.</dd>
+
+      <dt id="addon_matchbrackets"><a href="../addon/edit/matchbrackets.js"><code>edit/matchbrackets.js</code></a></dt>
+      <dd>Defines an option <code>matchBrackets</code> which, when set
+      to true, causes matching brackets to be highlighted whenever the
+      cursor is next to them. It also adds a
+      method <code>matchBrackets</code> that forces this to happen
+      once, and a method <code>findMatchingBracket</code> that can be
+      used to run the bracket-finding algorithm that this uses
+      internally.</dd>
+
+      <dt id="addon_closebrackets"><a href="../addon/edit/closebrackets.js"><code>edit/closebrackets.js</code></a></dt>
+      <dd>Defines an option <code>autoCloseBrackets</code> that will
+      auto-close brackets and quotes when typed. By default, it'll
+      auto-close <code>()[]{}''""</code>, but you can pass it a string
+      similar to that (containing pairs of matching characters), or an
+      object with <code>pairs</code> and
+      optionally <code>explode</code> properties to customize
+      it. <code>explode</code> should be a similar string that gives
+      the pairs of characters that, when enter is pressed between
+      them, should have the second character also moved to its own
+      line. <a href="../demo/closebrackets.html">Demo here</a>.</dd>
+
+      <dt id="addon_matchtags"><a href="../addon/edit/matchtags.js"><code>edit/matchtags.js</code></a></dt>
+      <dd>Defines an option <code>matchTags</code> that, when enabled,
+      will cause the tags around the cursor to be highlighted (using
+      the <code>CodeMirror-matchingbrackets</code> class). Also
+      defines
+      a <a href="#commands">command</a> <code>toMatchingTag</code>,
+      which you can bind a key to in order to jump to the tag mathing
+      the one under the cursor. Depends on
+      the <code>addon/fold/xml-fold.js</code>
+      addon. <a href="../demo/matchtags.html">Demo here.</a></dd>
+
+      <dt id="addon_trailingspace"><a href="../addon/edit/trailingspace.js"><code>edit/trailingspace.js</code></a></dt>
+      <dd>Adds an option <code>showTrailingSpace</code> which, when
+      enabled, adds the CSS class <code>cm-trailingspace</code> to
+      stretches of whitespace at the end of lines.
+      The <a href="../demo/trailingspace.html">demo</a> has a nice
+      squiggly underline style for this class.</dd>
+
+      <dt id="addon_comment"><a href="../addon/comment/comment.js"><code>comment/comment.js</code></a></dt>
+      <dd>Addon for commenting and uncommenting code. Adds three
+      methods to CodeMirror instances:
+      <dl>
+        <dt id="lineComment"><code><strong>lineComment</strong>(from: {line, ch}, to: {line, ch}, ?options: object)</code></dt>
+        <dd>Set the lines in the given range to be line comments. Will
+        fall back to <code>blockComment</code> when no line comment
+        style is defined for the mode.</dd>
+        <dt id="blockComment"><code><strong>blockComment</strong>(from: {line, ch}, to: {line, ch}, ?options: object)</code></dt>
+        <dd>Wrap the code in the given range in a block comment. Will
+        fall back to <code>lineComment</code> when no block comment
+        style is defined for the mode.</dd>
+        <dt id="uncomment"><code><strong>uncomment</strong>(from: {line, ch}, to: {line, ch}, ?options: object) → boolean</code></dt>
+        <dd>Try to uncomment the given range.
+          Returns <code>true</code> if a comment range was found and
+          removed, <code>false</code> otherwise.</dd>
+      </dl>
+      The <code>options</code> object accepted by these methods may
+      have the following properties:
+      <dl>
+        <dt><code>blockCommentStart, blockCommentEnd, blockCommentLead, lineComment: string</code></dt>
+        <dd>Override the <a href="#mode_comment">comment string
+        properties</a> of the mode with custom comment strings.</dd>
+        <dt><code><strong>padding</strong>: string</code></dt>
+        <dd>A string that will be inserted after opening and before
+        closing comment markers. Defaults to a single space.</dd>
+        <dt><code><strong>commentBlankLines</strong>: boolean</code></dt>
+        <dd>Whether, when adding line comments, to also comment lines
+        that contain only whitespace.</dd>
+        <dt><code><strong>indent</strong>: boolean</code></dt>
+        <dd>When adding line comments and this is turned on, it will
+        align the comment block to the current indentation of the
+        first line of the block.</dd>
+        <dt><code><strong>fullLines</strong>: boolean</code></dt>
+        <dd>When block commenting, this controls whether the whole
+        lines are indented, or only the precise range that is given.
+        Defaults to <code>true</code>.</dd>
+      </dl>
+      The addon also defines
+      a <code>toggleComment</code> <a href="#commands">command</a>,
+      which will try to uncomment the current selection, and if that
+      fails, line-comments it.</dd>
+
+      <dt id="addon_foldcode"><a href="../addon/fold/foldcode.js"><code>fold/foldcode.js</code></a></dt>
+      <dd>Helps with code folding. Adds a <code>foldCode</code> method
+      to editor instances, which will try to do a code fold starting
+      at the given line, or unfold the fold that is already present.
+      The method takes as first argument the position that should be
+      folded (may be a line number or
+      a <a href="#Pos"><code>Pos</code></a>), and as second optional
+      argument either a range-finder function, or an options object,
+      supporting the following properties:
+      <dl>
+        <dt><code><strong>rangeFinder</strong>: fn(CodeMirror, Pos)</code></dt>
+        <dd>The function that is used to find foldable ranges. If this
+        is not directly passed, it will
+        call <a href="#getHelper"><code>getHelper</code></a> with
+        a <code>"fold"</code> type to find one that's appropriate for
+        the mode. There are files in
+        the <a href="../addon/fold/"><code>addon/fold/</code></a>
+        directory providing <code>CodeMirror.fold.brace</code>, which
+        finds blocks in brace languages (JavaScript, C, Java,
+        etc), <code>CodeMirror.fold.indent</code>, for languages where
+        indentation determines block structure (Python, Haskell),
+        and <code>CodeMirror.fold.xml</code>, for XML-style
+        languages.</dd>
+        <dt><code><strong>widget</strong>: string|Element</code></dt>
+        <dd>The widget to show for folded ranges. Can be either a
+        string, in which case it'll become a span with
+        class <code>CodeMirror-foldmarker</code>, or a DOM node.</dd>
+        <dt><code><strong>scanUp</strong>: boolean</code></dt>
+        <dd>When true (default is false), the addon will try to find
+        foldable ranges on the lines above the current one if there
+        isn't an eligible one on the given line.</dd>
+        <dt><code><strong>minFoldSize</strong>: integer</code></dt>
+        <dd>The minimum amount of lines that a fold should span to be
+        accepted. Defaults to 0, which also allows single-line
+        folds.</dd>
+      </dl>
+      See <a href="../demo/folding.html">the demo</a> for an
+      example.</dd>
+
+      <dt id="addon_foldgutter"><a href="../addon/fold/foldgutter.js"><code>fold/foldgutter.js</code></a></dt>
+      <dd>Provides an option <code>foldGutter</code>, which can be
+      used to create a gutter with markers indicating the blocks that
+      can be folded. Create a gutter using
+      the <a href="#option_gutters"><code>gutters</code></a> option,
+      giving it the class <code>CodeMirror-foldgutter</code> or
+      something else if you configure the addon to use a different
+      class, and this addon will show markers next to folded and
+      foldable blocks, and handle clicks in this gutter. The option
+      can be either set to <code>true</code>, or an object containing
+      the following optional option fields:
+      <dl>
+        <dt><code><strong>gutter</strong>: string</code></dt>
+        <dd>The CSS class of the gutter. Defaults
+        to <code>"CodeMirror-foldgutter"</code>. You will have to
+        style this yourself to give it a width (and possibly a
+        background).</dd>
+        <dt><code><strong>indicatorOpen</strong>: string | Element</code></dt>
+        <dd>A CSS class or DOM element to be used as the marker for
+        open, foldable blocks. Defaults
+        to <code>"CodeMirror-foldgutter-open"</code>.</dd>
+        <dt><code><strong>indicatorFolded</strong>: string | Element</code></dt>
+        <dd>A CSS class or DOM element to be used as the marker for
+        folded blocks. Defaults to <code>"CodeMirror-foldgutter-folded"</code>.</dd>
+        <dt><code><strong>rangeFinder</strong>: fn(CodeMirror, Pos)</code></dt>
+        <dd>The range-finder function to use when determining whether
+        something can be folded. When not
+        given, <a href="#getHelper"><code>getHelper</code></a> will be
+        used to determine a default.</dd>
+      </dl>
+      Demo <a href="../demo/folding.html">here</a>.</dd>
+
+      <dt id="addon_runmode"><a href="../addon/runmode/runmode.js"><code>runmode/runmode.js</code></a></dt>
+      <dd>Can be used to run a CodeMirror mode over text without
+      actually opening an editor instance.
+      See <a href="../demo/runmode.html">the demo</a> for an example.
+      There are alternate versions of the file avaible for
+      running <a href="../addon/runmode/runmode-standalone.js">stand-alone</a>
+      (without including all of CodeMirror) and
+      for <a href="../addon/runmode/runmode.node.js">running under
+      node.js</a>.</dd>
+
+      <dt id="addon_overlay"><a href="../addon/mode/overlay.js"><code>mode/overlay.js</code></a></dt>
+      <dd>Mode combinator that can be used to extend a mode with an
+      'overlay' — a secondary mode is run over the stream, along with
+      the base mode, and can color specific pieces of text without
+      interfering with the base mode.
+      Defines <code>CodeMirror.overlayMode</code>, which is used to
+      create such a mode. See <a href="../demo/mustache.html">this
+      demo</a> for a detailed example.</dd>
+
+      <dt id="addon_multiplex"><a href="../addon/mode/multiplex.js"><code>mode/multiplex.js</code></a></dt>
+      <dd>Mode combinator that can be used to easily 'multiplex'
+      between several modes.
+      Defines <code>CodeMirror.multiplexingMode</code> which, when
+      given as first argument a mode object, and as other arguments
+      any number of <code>{open, close, mode [, delimStyle, innerStyle]}</code>
+      objects, will return a mode object that starts parsing using the
+      mode passed as first argument, but will switch to another mode
+      as soon as it encounters a string that occurs in one of
+      the <code>open</code> fields of the passed objects. When in a
+      sub-mode, it will go back to the top mode again when
+      the <code>close</code> string is encountered.
+      Pass <code>"\n"</code> for <code>open</code> or <code>close</code>
+      if you want to switch on a blank line.
+      <ul><li>When <code>delimStyle</code> is specified, it will be the token
+      style returned for the delimiter tokens.</li>
+      <li>When <code>innerStyle</code> is specified, it will be the token
+      style added for each inner mode token.</li></ul>
+      The outer mode will not see the content between the delimiters.
+      See <a href="../demo/multiplex.html">this demo</a> for an
+      example.</dd>
+
+      <dt id="addon_show-hint"><a href="../addon/hint/show-hint.js"><code>hint/show-hint.js</code></a></dt>
+      <dd>Provides a framework for showing autocompletion hints.
+      Defines <code>CodeMirror.showHint</code>, which takes a
+      CodeMirror instance, a hinting function, and optionally an
+      options object, and pops up a widget that allows the user to
+      select a completion. Hinting functions are function that take an
+      editor instance and an optional options object, and return
+      a <code>{list, from, to}</code> object, where <code>list</code>
+      is an array of strings or objects (the completions),
+      and <code>from</code> and <code>to</code> give the start and end
+      of the token that is being completed as <code>{line, ch}</code>
+      objects. If no hinting function is given, the addon will try to
+      use <a href="#getHelper"><code>getHelper</code></a> with
+      the <code>"hint"</code> type to find one. When completions
+      aren't simple strings, they should be objects with the folowing
+      properties:
+      <dl>
+        <dt><code><strong>text</strong>: string</code></dt>
+        <dd>The completion text. This is the only required
+        property.</dd>
+        <dt><code><strong>displayText</strong>: string</code></dt>
+        <dd>The text that should be displayed in the menu.</dd>
+        <dt><code><strong>className</strong>: string</code></dt>
+        <dd>A CSS class name to apply to the completion's line in the
+        menu.</dd>
+        <dt><code><strong>render</strong>: fn(Element, self, data)</code></dt>
+        <dd>A method used to create the DOM structure for showing the
+        completion by appending it to its first argument.</dd>
+        <dt><code><strong>hint</strong>: fn(CodeMirror, self, data)</code></dt>
+        <dd>A method used to actually apply the completion, instead of
+        the default behavior.</dd>
+      </dl>
+      The plugin understands the following options (the options object
+      will also be passed along to the hinting function, which may
+      understand additional options):
+      <dl>
+        <dt><code><strong>async</strong>: boolean</code></dt>
+        <dd>When set to true, the hinting function's signature should
+        be <code>(cm, callback, ?options)</code>, and the completion
+        interface will only be popped up when the hinting function
+        calls the callback, passing it the object holding the
+        completions.</dd>
+        <dt><code><strong>completeSingle</strong>: boolean</code></dt>
+        <dd>Determines whether, when only a single completion is
+        available, it is completed without showing the dialog.
+        Defaults to true.</dd>
+        <dt><code><strong>alignWithWord</strong>: boolean</code></dt>
+        <dd>Whether the pop-up should be horizontally aligned with the
+        start of the word (true, default), or with the cursor (false).</dd>
+        <dt><code><strong>closeOnUnfocus</strong>: boolean</code></dt>
+        <dd>When enabled (which is the default), the pop-up will close
+        when the editor is unfocused.</dd>
+        <dt><code><strong>customKeys</strong>: keymap</code></dt>
+        <dd>Allows you to provide a custom keymap of keys to be active
+        when the pop-up is active. The handlers will be called with an
+        extra argument, a handle to the completion menu, which
+        has <code>moveFocus(n)</code>, <code>setFocus(n)</code>, <code>pick()</code>,
+        and <code>close()</code> methods (see the source for details),
+        that can be used to change the focused element, pick the
+        current element or close the menu.</dd>
+        <dt><code><strong>extraKeys</strong>: keymap</code></dt>
+        <dd>Like <code>customKeys</code> above, but the bindings will
+        be added to the set of default bindings, instead of replacing
+        them.</dd>
+      </dl>
+      The following events will be fired on the completions object
+      during completion:
+      <dl>
+        <dt><code><strong>"shown"</strong> ()</code></dt>
+        <dd>Fired when the pop-up is shown.</dd>
+        <dt><code><strong>"select"</strong> (completion, Element)</code></dt>
+        <dd>Fired when a completion is selected. Passed the completion
+        value (string or object) and the DOM node that represents it
+        in the menu.</dd>
+        <dt><code><strong>"close"</strong> ()</code></dt>
+        <dd>Fired when the completion is finished.</dd>
+      </dl>
+      This addon depends styles
+      from <code>addon/hint/show-hint.css</code>. Check
+      out <a href="../demo/complete.html">the demo</a> for an
+      example.</dd>
+
+      <dt id="addon_javascript-hint"><a href="../addon/hint/javascript-hint.js"><code>hint/javascript-hint.js</code></a></dt>
+      <dd>Defines a simple hinting function for JavaScript
+      (<code>CodeMirror.hint.javascript</code>) and CoffeeScript
+      (<code>CodeMirror.hint.coffeescript</code>) code. This will
+      simply use the JavaScript environment that the editor runs in as
+      a source of information about objects and their properties.</dd>
+
+      <dt id="addon_xml-hint"><a href="../addon/hint/xml-hint.js"><code>hint/xml-hint.js</code></a></dt>
+      <dd>Defines <code>CodeMirror.hint.xml</code>, which produces
+      hints for XML tagnames, attribute names, and attribute values,
+      guided by a <code>schemaInfo</code> option (a property of the
+      second argument passed to the hinting function, or the third
+      argument passed to <code>CodeMirror.showHint</code>).<br>The
+      schema info should be an object mapping tag names to information
+      about these tags, with optionally a <code>"!top"</code> property
+      containing a list of the names of valid top-level tags. The
+      values of the properties should be objects with optional
+      properties <code>children</code> (an array of valid child
+      element names, omit to simply allow all tags to appear)
+      and <code>attrs</code> (an object mapping attribute names
+      to <code>null</code> for free-form attributes, and an array of
+      valid values for restricted
+      attributes). <a href="../demo/xmlcomplete.html">Demo
+      here.</a></dd>
+
+      <dt id="addon_html-hint"><a href="../addon/hint/html-hint.js"><code>hint/html-hint.js</code></a></dt>
+      <dd>Provides schema info to
+      the <a href="#addon_xml-hint">xml-hint</a> addon for HTML
+      documents. Defines a schema
+      object <code>CodeMirror.htmlSchema</code> that you can pass to
+      as a <code>schemaInfo</code> option, and
+      a <code>CodeMirror.hint.html</code> hinting function that
+      automatically calls <code>CodeMirror.hint.xml</code> with this
+      schema data. See
+      the <a href="../demo/html5complete.html">demo</a>.</dd>
+
+      <dt id="addon_python-hint"><a href="../addon/hint/python-hint.js"><code>hint/python-hint.js</code></a></dt>
+      <dd>A very simple hinting function for Python code.
+      Defines <code>CodeMirror.hint.python</code>.</dd>
+
+      <dt id="addon_anyword-hint"><a href="../addon/hint/anyword-hint.js"><code>hint/anyword-hint.js</code></a></dt>
+      <dd>A very simple hinting function
+      (<code>CodeMirror.hint.anyword</code>) that simply looks for
+      words in the nearby code and completes to those. Takes two
+      optional options, <code>word</code>, a regular expression that
+      matches words (sequences of one or more character),
+      and <code>range</code>, which defines how many lines the addon
+      should scan when completing (defaults to 500).</dd>
+
+      <dt id="addon_match-highlighter"><a href="../addon/search/match-highlighter.js"><code>match-highlighter.js</code></a></dt>
+      <dd>Adds a <code>highlightSelectionMatches</code> option that
+      can be enabled to highlight all instances of a currently
+      selected word. Can be set either to true or to an object
+      containing the following options: <code>minChars</code>, for the
+      minimum amount of selected characters that triggers a highlight
+      (default 2), <code>style</code>, for the style to be used to
+      highlight the matches (default <code>"matchhighlight"</code>,
+      which will correspond to CSS
+      class <code>cm-matchhighlight</code>),
+      and <code>showToken</code> which can be set to <code>true</code>
+      or to a regexp matching the characters that make up a word. When
+      enabled, it causes the current word to be highlighted when
+      nothing is selected (defaults to off).
+      Demo <a href="../demo/matchhighlighter.html">here</a>.</dd>
+
+      <dt id="addon_lint"><a href="../addon/lint/lint.js"><code>lint/lint.js</code></a></dt>
+      <dd>Defines an interface component for showing linting warnings,
+      with pluggable warning sources
+      (see <a href="../addon/lint/json-lint.js"><code>json-lint.js</code></a>
+      and <a href="../addon/lint/javascript-lint.js"><code>javascript-lint.js</code></a>
+      in the same directory). Defines a <code>lint</code> option that
+      can be set to a warning source (for
+      example <code>CodeMirror.lint.javascript</code>), or
+      to <code>true</code>, in which
+      case <a href="#getHelper"><code>getHelper</code></a> with
+      type <code>"lint"</code> is used to determined a validator
+      function. Depends on <code>addon/lint/lint.css</code>. A demo
+      can be found <a href="../demo/lint.html">here</a>.</dd>
+
+      <dt id="addon_mark-selection"><a href="../addon/selection/mark-selection.js"><code>selection/mark-selection.js</code></a></dt>
+      <dd>Causes the selected text to be marked with the CSS class
+      <code>CodeMirror-selectedtext</code> when the <code>styleSelectedText</code> option
+      is enabled. Useful to change the colour of the selection (in addition to the background),
+      like in <a href="../demo/markselection.html">this demo</a>.</dd>
+
+      <dt id="addon_active-line"><a href="../addon/selection/active-line.js"><code>selection/active-line.js</code></a></dt>
+      <dd>Defines a <code>styleActiveLine</code> option that, when enabled,
+      gives the wrapper of the active line the class <code>CodeMirror-activeline</code>,
+      and adds a background with the class <code>CodeMirror-activeline-background</code>.
+      is enabled. See the <a href="../demo/activeline.html">demo</a>.</dd>
+
+      <dt id="addon_closetag"><a href="../addon/edit/closetag.js"><code>edit/closetag.js</code></a></dt>
+      <dd>Provides utility functions for adding automatic tag closing
+      to XML modes. See
+      the <a href="../demo/closetag.html">demo</a>.</dd>
+
+      <dt id="addon_loadmode"><a href="../addon/mode/loadmode.js"><code>mode/loadmode.js</code></a></dt>
+      <dd>Defines a <code>CodeMirror.requireMode(modename,
+      callback)</code> function that will try to load a given mode and
+      call the callback when it succeeded. You'll have to
+      set <code>CodeMirror.modeURL</code> to a string that mode paths
+      can be constructed from, for
+      example <code>"mode/%N/%N.js"</code>—the <code>%N</code>'s will
+      be replaced with the mode name. Also
+      defines <code>CodeMirror.autoLoadMode(instance, mode)</code>,
+      which will ensure the given mode is loaded and cause the given
+      editor instance to refresh its mode when the loading
+      succeeded. See the <a href="../demo/loadmode.html">demo</a>.</dd>
+
+      <dt id="addon_continuecomment"><a href="../addon/edit/continuecomment.js"><code>edit/continuecomment.js</code></a></dt>
+      <dd>Adds an <code>continueComments</code> option, which can be
+      set to true to have the editor prefix new lines inside C-like
+      block comments with an asterisk when Enter is pressed. It can
+      also be set to a string in order to bind this functionality to a
+      specific key..</dd>
+
+      <dt id="addon_placeholder"><a href="../addon/display/placeholder.js"><code>display/placeholder.js</code></a></dt>
+      <dd>Adds a <code>placeholder</code> option that can be used to
+      make text appear in the editor when it is empty and not focused.
+      Also gives the editor a <code>CodeMirror-empty</code> CSS class
+      whenever it doesn't contain any text.
+      See <a href="../demo/placeholder.html">the demo</a>.</dd>
+
+      <dt id="addon_merge"><a href="../addon/merge/merge.js"><code>merge/merge.js</code></a></dt>
+      <dd>Implements an interface for merging changes, using either a
+      2-way or a 3-way view. The <code>CodeMirror.MergeView</code>
+      constructor takes arguments similar to
+      the <a href="#CodeMirror"><code>CodeMirror</code></a>
+      constructor, first a node to append the interface to, and then
+      an options object. Two extra optional options are
+      recognized, <code>origLeft</code> and <code>origRight</code>,
+      which may be strings that provide original versions of the
+      document, which will be shown to the left and right of the
+      editor in non-editable CodeMirror instances. The merge interface
+      will highlight changes between the editable document and the
+      original(s) (<a href="../demo/merge.html">demo</a>).</dd>
+    </dl>
+
+    <h2 id="modeapi">Writing CodeMirror Modes</h2>
+
+    <p>Modes typically consist of a single JavaScript file. This file
+    defines, in the simplest case, a lexer (tokenizer) for your
+    language—a function that takes a character stream as input,
+    advances it past a token, and returns a style for that token. More
+    advanced modes can also handle indentation for the language.</p>
+
+    <p id="defineMode">The mode script should
+    call <code>CodeMirror.defineMode</code> to register itself with
+    CodeMirror. This function takes two arguments. The first should be
+    the name of the mode, for which you should use a lowercase string,
+    preferably one that is also the name of the files that define the
+    mode (i.e. <code>"xml"</code> is defined in <code>xml.js</code>). The
+    second argument should be a function that, given a CodeMirror
+    configuration object (the thing passed to
+    the <code>CodeMirror</code> function) and an optional mode
+    configuration object (as in
+    the <a href="#option_mode"><code>mode</code></a> option), returns
+    a mode object.</p>
+
+    <p>Typically, you should use this second argument
+    to <code>defineMode</code> as your module scope function (modes
+    should not leak anything into the global scope!), i.e. write your
+    whole mode inside this function.</p>
+
+    <p>The main responsibility of a mode script is <em>parsing</em>
+    the content of the editor. Depending on the language and the
+    amount of functionality desired, this can be done in really easy
+    or extremely complicated ways. Some parsers can be stateless,
+    meaning that they look at one element (<em>token</em>) of the code
+    at a time, with no memory of what came before. Most, however, will
+    need to remember something. This is done by using a <em>state
+    object</em>, which is an object that is always passed when
+    reading a token, and which can be mutated by the tokenizer.</p>
+
+    <p id="startState">Modes that use a state must define
+    a <code>startState</code> method on their mode object. This is a
+    function of no arguments that produces a state object to be used
+    at the start of a document.</p>
+
+    <p id="token">The most important part of a mode object is
+    its <code>token(stream, state)</code> method. All modes must
+    define this method. It should read one token from the stream it is
+    given as an argument, optionally update its state, and return a
+    style string, or <code>null</code> for tokens that do not have to
+    be styled. For your styles, you are encouraged to use the
+    'standard' names defined in the themes (without
+    the <code>cm-</code> prefix). If that fails, it is also possible
+    to come up with your own and write your own CSS theme file.<p>
+
+    <p id="StringStream">The stream object that's passed
+    to <code>token</code> encapsulates a line of code (tokens may
+    never span lines) and our current position in that line. It has
+    the following API:</p>
+
+    <dl>
+      <dt><code><strong></strong><strong>eol</strong>() → boolean</code></dt>
+      <dd>Returns true only if the stream is at the end of the
+      line.</dd>
+      <dt><code><strong></strong><strong>sol</strong>() → boolean</code></dt>
+      <dd>Returns true only if the stream is at the start of the
+      line.</dd>
+
+      <dt><code><strong>peek</strong>() → string</code></dt>
+      <dd>Returns the next character in the stream without advancing
+      it. Will return an <code>null</code> at the end of the
+      line.</dd>
+      <dt><code><strong>next</strong>() → string</code></dt>
+      <dd>Returns the next character in the stream and advances it.
+      Also returns <code>null</code> when no more characters are
+      available.</dd>
+
+      <dt><code><strong>eat</strong>(match: string|regexp|function(char: string) → boolean) → string</code></dt>
+      <dd><code>match</code> can be a character, a regular expression,
+      or a function that takes a character and returns a boolean. If
+      the next character in the stream 'matches' the given argument,
+      it is consumed and returned. Otherwise, <code>undefined</code>
+      is returned.</dd>
+      <dt><code><strong>eatWhile</strong>(match: string|regexp|function(char: string) → boolean) → boolean</code></dt>
+      <dd>Repeatedly calls <code>eat</code> with the given argument,
+      until it fails. Returns true if any characters were eaten.</dd>
+      <dt><code><strong>eatSpace</strong>() → boolean</code></dt>
+      <dd>Shortcut for <code>eatWhile</code> when matching
+      white-space.</dd>
+      <dt><code><strong>skipToEnd</strong>()</code></dt>
+      <dd>Moves the position to the end of the line.</dd>
+      <dt><code><strong>skipTo</strong>(ch: string) → boolean</code></dt>
+      <dd>Skips to the next occurrence of the given character, if
+      found on the current line (doesn't advance the stream if the
+      character does not occur on the line). Returns true if the
+      character was found.</dd>
+      <dt><code><strong>match</strong>(pattern: string, ?consume: boolean, ?caseFold: boolean) → boolean</code></dt>
+      <dt><code><strong>match</strong>(pattern: regexp, ?consume: boolean) → array&lt;string&gt;</code></dt>
+      <dd>Act like a
+      multi-character <code>eat</code>—if <code>consume</code> is true
+      or not given—or a look-ahead that doesn't update the stream
+      position—if it is false. <code>pattern</code> can be either a
+      string or a regular expression starting with <code>^</code>.
+      When it is a string, <code>caseFold</code> can be set to true to
+      make the match case-insensitive. When successfully matching a
+      regular expression, the returned value will be the array
+      returned by <code>match</code>, in case you need to extract
+      matched groups.</dd>
+
+      <dt><code><strong>backUp</strong>(n: integer)</code></dt>
+      <dd>Backs up the stream <code>n</code> characters. Backing it up
+      further than the start of the current token will cause things to
+      break, so be careful.</dd>
+      <dt><code><strong>column</strong>() → integer</code></dt>
+      <dd>Returns the column (taking into account tabs) at which the
+      current token starts.</dd>
+      <dt><code><strong>indentation</strong>() → integer</code></dt>
+      <dd>Tells you how far the current line has been indented, in
+      spaces. Corrects for tab characters.</dd>
+
+      <dt><code><strong>current</strong>() → string</code></dt>
+      <dd>Get the string between the start of the current token and
+      the current stream position.</dd>
+    </dl>
+
+    <p id="blankLine">By default, blank lines are simply skipped when
+    tokenizing a document. For languages that have significant blank
+    lines, you can define a <code>blankLine(state)</code> method on
+    your mode that will get called whenever a blank line is passed
+    over, so that it can update the parser state.</p>
+
+    <p id="copyState">Because state object are mutated, and CodeMirror
+    needs to keep valid versions of a state around so that it can
+    restart a parse at any line, copies must be made of state objects.
+    The default algorithm used is that a new state object is created,
+    which gets all the properties of the old object. Any properties
+    which hold arrays get a copy of these arrays (since arrays tend to
+    be used as mutable stacks). When this is not correct, for example
+    because a mode mutates non-array properties of its state object, a
+    mode object should define a <code>copyState</code> method,
+    which is given a state and should return a safe copy of that
+    state.</p>
+
+    <p id="indent">If you want your mode to provide smart indentation
+    (through the <a href="#indentLine"><code>indentLine</code></a>
+    method and the <code>indentAuto</code>
+    and <code>newlineAndIndent</code> commands, to which keys can be
+    <a href="#option_extraKeys">bound</a>), you must define
+    an <code>indent(state, textAfter)</code> method on your mode
+    object.</p>
+
+    <p>The indentation method should inspect the given state object,
+    and optionally the <code>textAfter</code> string, which contains
+    the text on the line that is being indented, and return an
+    integer, the amount of spaces to indent. It should usually take
+    the <a href="#option_indentUnit"><code>indentUnit</code></a>
+    option into account. An indentation method may
+    return <code>CodeMirror.Pass</code> to indicate that it
+    could not come up with a precise indentation.</p>
+
+    <p id="mode_comment">To work well with
+    the <a href="#addon_comment">commenting addon</a>, a mode may
+    define <code>lineComment</code> (string that starts a line
+    comment), <code>blockCommentStart</code>, <code>blockCommentEnd</code>
+    (strings that start and end block comments),
+    and <code>blockCommentLead</code> (a string to put at the start of
+    continued lines in a block comment). All of these are
+    optional.</p>
+
+    <p id="electricChars">Finally, a mode may define
+    an <code>electricChars</code> property, which should hold a string
+    containing all the characters that should trigger the behaviour
+    described for
+    the <a href="#option_electricChars"><code>electricChars</code></a>
+    option.</p>
+
+    <p>So, to summarize, a mode <em>must</em> provide
+    a <code>token</code> method, and it <em>may</em>
+    provide <code>startState</code>, <code>copyState</code>,
+    and <code>indent</code> methods. For an example of a trivial mode,
+    see the <a href="../mode/diff/diff.js">diff mode</a>, for a more
+    involved example, see the <a href="../mode/clike/clike.js">C-like
+    mode</a>.</p>
+
+    <p>Sometimes, it is useful for modes to <em>nest</em>—to have one
+    mode delegate work to another mode. An example of this kind of
+    mode is the <a href="../mode/htmlmixed/htmlmixed.js">mixed-mode HTML
+    mode</a>. To implement such nesting, it is usually necessary to
+    create mode objects and copy states yourself. To create a mode
+    object, there are <code>CodeMirror.getMode(options,
+    parserConfig)</code>, where the first argument is a configuration
+    object as passed to the mode constructor function, and the second
+    argument is a mode specification as in
+    the <a href="#option_mode"><code>mode</code></a> option. To copy a
+    state object, call <code>CodeMirror.copyState(mode, state)</code>,
+    where <code>mode</code> is the mode that created the given
+    state.</p>
+
+    <p id="innerMode">In a nested mode, it is recommended to add an
+    extra methods, <code>innerMode</code> which, given a state object,
+    returns a <code>{state, mode}</code> object with the inner mode
+    and its state for the current position. These are used by utility
+    scripts such as the <a href="#addon_closetag">tag closer</a> to
+    get context information. Use the <code>CodeMirror.innerMode</code>
+    helper function to, starting from a mode and a state, recursively
+    walk down to the innermost mode and state.</p>
+
+    <p>To make indentation work properly in a nested parser, it is
+    advisable to give the <code>startState</code> method of modes that
+    are intended to be nested an optional argument that provides the
+    base indentation for the block of code. The JavaScript and CSS
+    parser do this, for example, to allow JavaScript and CSS code
+    inside the mixed-mode HTML mode to be properly indented.</p>
+
+    <p>It is possible, and encouraged, to associate your mode, or a
+    certain configuration of your mode, with
+    a <a href="http://en.wikipedia.org/wiki/MIME">MIME</a> type. For
+    example, the JavaScript mode associates itself
+    with <code>text/javascript</code>, and its JSON variant
+    with <code>application/json</code>. To do this,
+    call <code>CodeMirror.defineMIME(mime, modeSpec)</code>,
+    where <code>modeSpec</code> can be a string or object specifying a
+    mode, as in the <a href="#option_mode"><code>mode</code></a>
+    option.</p>
+
+    <p id="extendMode">Sometimes, it is useful to add or override mode
+    object properties from external code.
+    The <code>CodeMirror.extendMode</code> can be used to add
+    properties to mode objects produced for a specific mode. Its first
+    argument is the name of the mode, its second an object that
+    specifies the properties that should be added. This is mostly
+    useful to add utilities that can later be looked
+    up through <a href="#getMode"><code>getMode</code></a>.</p>
+
+</div><div class="rightsmall blk">
+
+    <h2>Contents</h2>
+
+    <ul>
+      <li><a href="#overview">Overview</a></li>
+      <li><a href="#usage">Basic Usage</a></li>
+      <li><a href="#config">Configuration</a></li>
+      <li><a href="#events">Events</a></li>
+      <li><a href="#keymaps">Keymaps</a></li>
+      <li><a href="#styling">Customized Styling</a></li>
+      <li><a href="#api">Programming API</a>
+        <ul>
+          <li><a href="#constructor">Constructor</a></li>
+          <li><a href="#api_content">Content manipulation</a></li>
+          <li><a href="#api_selection">Selection</a></li>
+          <li><a href="#api_configuration">Configuration</a></li>
+          <li><a href="#api_doc">Document management</a></li>
+          <li><a href="#api_history">History</a></li>
+          <li><a href="#api_marker">Text-marking</a></li>
+          <li><a href="#api_decoration">Widget, gutter, and decoration</a></li>
+          <li><a href="#api_sizing">Sizing, scrolling, and positioning</a></li>
+          <li><a href="#api_mode">Mode, state, and tokens</a></li>
+          <li><a href="#api_misc">Miscellaneous methods</a></li>
+          <li><a href="#api_static">Static properties</a></li>
+        </ul>
+      </li>
+      <li><a href="#addons">Addons</a></li>
+      <li><a href="#modeapi">Writing CodeMirror Modes</a></li>
+    </ul>
+
+</div></div>
+
+<div style="height: 2em">&nbsp;</div>
+
+<script>setTimeout(function(){CodeMirror.colorize();}, 20);</script>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/doc/modes.html b/third-party/codemirror-3.15/doc/modes.html
new file mode 100644 (file)
index 0000000..82738f1
--- /dev/null
@@ -0,0 +1,100 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8"/>
+    <title>CodeMirror: Mode list</title>
+    <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Droid+Sans|Droid+Sans:bold"/>
+    <link rel="stylesheet" type="text/css" href="docs.css"/>
+  </head>
+  <body>
+
+<h1><span class="logo-braces">{ }</span> <a href="http://codemirror.net/">CodeMirror</a></h1>
+
+<div class="grey">
+<img src="baboon.png" class="logo" alt="logo"/>
+<pre>
+/* Full list of
+   modes */
+</pre>
+</div>
+
+<p>Every mode in the distribution. The list on the front-page leaves
+out some of the more obscure ones.</p>
+
+<div style="-webkit-columns: 50px 3; -moz-columns: 50px 3; columns: 50px 3;">
+    <ul>
+      <li><a href="../mode/apl/index.html">APL</a></li>
+      <li><a href="../mode/asterisk/index.html">Asterisk dialplan</a></li>
+      <li><a href="../mode/clike/index.html">C, C++, C#</a></li>
+      <li><a href="../mode/clojure/index.html">Clojure</a></li>
+      <li><a href="../mode/cobol/index.html">COBOL</a></li>
+      <li><a href="../mode/coffeescript/index.html">CoffeeScript</a></li>
+      <li><a href="../mode/commonlisp/index.html">Common Lisp</a></li>
+      <li><a href="../mode/css/index.html">CSS</a></li>
+      <li><a href="../mode/python/index.html">Cython</a></li>
+      <li><a href="../mode/d/index.html">D</a></li>
+      <li><a href="../mode/diff/index.html">diff</a></li>
+      <li><a href="../mode/ecl/index.html">ECL</a></li>
+      <li><a href="../mode/erlang/index.html">Erlang</a></li>
+      <li><a href="../mode/gas/index.html">Gas</a> (AT&amp;T-style assembly)</li>
+      <li><a href="../mode/go/index.html">Go</a></li>
+      <li><a href="../mode/groovy/index.html">Groovy</a></li>
+      <li><a href="../mode/haml/index.html">HAML</a></li>
+      <li><a href="../mode/haskell/index.html">Haskell</a></li>
+      <li><a href="../mode/haxe/index.html">Haxe</a></li>
+      <li><a href="../mode/htmlembedded/index.html">HTML embedded scripts</a></li>
+      <li><a href="../mode/htmlmixed/index.html">HTML mixed-mode</a></li>
+      <li><a href="../mode/http/index.html">HTTP</a></li>
+      <li><a href="../mode/clike/index.html">Java</a></li>
+      <li><a href="../mode/jade/index.html">Jade</a></li>
+      <li><a href="../mode/javascript/index.html">JavaScript</a></li>
+      <li><a href="../mode/jinja2/index.html">Jinja2</a></li>
+      <li><a href="../mode/less/index.html">LESS</a></li>
+      <li><a href="../mode/livescript/index.html">LiveScript</a></li>
+      <li><a href="../mode/lua/index.html">Lua</a></li>
+      <li><a href="../mode/markdown/index.html">Markdown</a> (<a href="../mode/gfm/index.html">GitHub-flavour</a>)</li>
+      <li><a href="../mode/mirc/index.html">mIRC</a></li>
+      <li><a href="../mode/nginx/index.html">Nginx</a></li>
+      <li><a href="../mode/ntriples/index.html">NTriples</a></li>
+      <li><a href="../mode/ocaml/index.html">OCaml</a></li>
+      <li><a href="../mode/pascal/index.html">Pascal</a></li>
+      <li><a href="../mode/perl/index.html">Perl</a></li>
+      <li><a href="../mode/php/index.html">PHP</a></li>
+      <li><a href="../mode/pig/index.html">Pig Latin</a></li>
+      <li><a href="../mode/properties/index.html">Properties files</a></li>
+      <li><a href="../mode/python/index.html">Python</a></li>
+      <li><a href="../mode/q/index.html">Q</a></li>
+      <li><a href="../mode/r/index.html">R</a></li>
+      <li>RPM <a href="../mode/rpm/spec/index.html">spec</a> and <a href="../mode/rpm/changes/index.html">changelog</a></li>
+      <li><a href="../mode/rst/index.html">reStructuredText</a></li>
+      <li><a href="../mode/ruby/index.html">Ruby</a></li>
+      <li><a href="../mode/rust/index.html">Rust</a></li>
+      <li><a href="../mode/sass/index.html">Sass</a></li>
+      <li><a href="../mode/clike/scala.html">Scala</a></li>
+      <li><a href="../mode/scheme/index.html">Scheme</a></li>
+      <li><a href="../mode/css/scss.html">SCSS</a></li>
+      <li><a href="../mode/shell/index.html">Shell</a></li>
+      <li><a href="../mode/sieve/index.html">Sieve</a></li>
+      <li><a href="../mode/smalltalk/index.html">Smalltalk</a></li>
+      <li><a href="../mode/smarty/index.html">Smarty</a></li>
+      <li><a href="../mode/smartymixed/index.html">Smarty/HTML mixed</a></li>
+      <li><a href="../mode/sql/index.html">SQL</a> (several dialects)</li>
+      <li><a href="../mode/sparql/index.html">SPARQL</a></li>
+      <li><a href="../mode/stex/index.html">sTeX, LaTeX</a></li>
+      <li><a href="../mode/tcl/index.html">Tcl</a></li>
+      <li><a href="../mode/tiddlywiki/index.html">Tiddlywiki</a></li>
+      <li><a href="../mode/tiki/index.html">Tiki wiki</a></li>
+      <li><a href="../mode/turtle/index.html">Turtle</a></li>
+      <li><a href="../mode/vb/index.html">VB.NET</a></li>
+      <li><a href="../mode/vbscript/index.html">VBScript</a></li>
+      <li><a href="../mode/velocity/index.html">Velocity</a></li>
+      <li><a href="../mode/verilog/index.html">Verilog</a></li>
+      <li><a href="../mode/xml/index.html">XML/HTML</a></li>
+      <li><a href="../mode/xquery/index.html">XQuery</a></li>
+      <li><a href="../mode/yaml/index.html">YAML</a></li>
+      <li><a href="../mode/z80/index.html">Z80</a></li>
+    </ul>
+  </div>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/doc/oldrelease.html b/third-party/codemirror-3.15/doc/oldrelease.html
new file mode 100644 (file)
index 0000000..c72dc8f
--- /dev/null
@@ -0,0 +1,546 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8"/>
+    <title>CodeMirror</title>
+    <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Droid+Sans|Droid+Sans:bold"/>
+    <link rel="stylesheet" type="text/css" href="docs.css"/>
+    <link rel="alternate" href="http://twitter.com/statuses/user_timeline/242283288.rss" type="application/rss+xml"/>
+  </head>
+  <body>
+
+<h1><span class="logo-braces">{ }</span> <a href="http://codemirror.net/">CodeMirror</a></h1>
+
+<div class="grey">
+<img src="baboon.png" class="logo" alt="logo"/>
+<pre>
+/* Old release
+   history */
+</pre>
+</div>
+
+  <p class="rel">20-11-2012: <a href="http://codemirror.net/codemirror-3.0rc2.zip">Version 3.0, release candidate 2</a>:</p>
+
+  <ul class="rel-note">
+    <li>New mode: <a href="../mode/http/index.html">HTTP</a>.</li>
+    <li>Improved handling of selection anchor position.</li>
+    <li>Improve IE performance on longer lines.</li>
+    <li>Reduce gutter glitches during horiz. scrolling.</li>
+    <li>Add <a href="manual.html#addKeyMap"><code>addKeyMap</code></a> and <a href="manual.html#removeKeyMap"><code>removeKeyMap</code></a> methods.</li>
+    <li>Rewrite <code>formatting</code> and <code>closetag</code> add-ons.</li>
+    <li>Full <a href="https://github.com/marijnh/CodeMirror/compare/v3.0rc1...v3.0rc2">list of patches</a>.</li>
+  </ul>
+
+  <p class="rel">20-11-2012: <a href="http://codemirror.net/codemirror-2.36.zip">Version 2.36</a>:</p>
+
+  <ul class="rel-note">
+    <li>New mode: <a href="../mode/z80/index.html">Z80 assembly</a>.</li>
+    <li>New theme: <a href="../demo/theme.html?twilight">Twilight</a>.</li>
+    <li>Add command-line compression helper.</li>
+    <li>Make <a href="manual.html#scrollIntoView"><code>scrollIntoView</code></a> public.</li>
+    <li>Add <a href="manual.html#defaultTextHeight"><code>defaultTextHeight</code></a> method.</li>
+    <li>Various extensions to the vim keymap.</li>
+    <li>Make <a href="../mode/php/index.html">PHP mode</a> build on <a href="../mode/htmlmixed/index.html">mixed HTML mode</a>.</li>
+    <li>Add <a href="manual.html#addon_continuecomment">comment-continuing</a> add-on.</li>
+    <li>Full <a href="../https://github.com/marijnh/CodeMirror/compare/v2.35...v2.36">list of patches</a>.</li>
+  </ul>
+
+  <p class="rel">20-11-2012: <a href="http://codemirror.net/codemirror-3.0rc1.zip">Version 3.0, release candidate 1</a>:</p>
+
+  <ul class="rel-note">
+    <li>New theme: <a href="../demo/theme.html?solarized%20light">Solarized</a>.</li>
+    <li>Introduce <a href="manual.html#addLineClass"><code>addLineClass</code></a>
+    and <a href="manual.html#removeLineClass"><code>removeLineClass</code></a>,
+    drop <code>setLineClass</code>.</li>
+    <li>Add a <em>lot</em> of
+    new <a href="manual.html#markText">options for marked text</a>
+    (read-only, atomic, collapsed, widget replacement).</li>
+    <li>Remove the old code folding interface in favour of these new ranges.</li>
+    <li>Add <a href="manual.html#isClean"><code>isClean</code></a>/<a href="manual.html#markClean"><code>markClean</code></a> methods.</li>
+    <li>Remove <code>compoundChange</code> method, use better undo-event-combining heuristic.</li>
+    <li>Improve scrolling performance smoothness.</li>
+    <li>Full <a href="https://github.com/marijnh/CodeMirror/compare/v3.0beta2...v3.0rc1">list of patches</a>.</li>
+  </ul>
+
+  <p class="rel">22-10-2012: <a href="http://codemirror.net/codemirror-2.35.zip">Version 2.35</a>:</p>
+
+  <ul class="rel-note">
+    <li>New (sub) mode: <a href="../mode/javascript/typescript.html">TypeScript</a>.</li>
+    <li>Don't overwrite (insert key) when pasting.</li>
+    <li>Fix several bugs in <a href="manual.html#markText"><code>markText</code></a>/undo interaction.</li>
+    <li>Better indentation of JavaScript code without semicolons.</li>
+    <li>Add <a href="manual.html#defineInitHook"><code>defineInitHook</code></a> function.</li>
+    <li>Full <a href="https://github.com/marijnh/CodeMirror/compare/v2.34...v2.35">list of patches</a>.</li>
+  </ul>
+
+  <p class="rel">22-10-2012: <a href="http://codemirror.net/codemirror-3.0beta2.zip">Version 3.0, beta 2</a>:</p>
+
+  <ul class="rel-note">
+    <li>Fix page-based coordinate computation.</li>
+    <li>Fix firing of <a href="manual.html#event_gutterClick"><code>gutterClick</code></a> event.</li>
+    <li>Add <a href="manual.html#option_cursorHeight"><code>cursorHeight</code></a> option.</li>
+    <li>Fix bi-directional text regression.</li>
+    <li>Add <a href="manual.html#option_viewportMargin"><code>viewportMargin</code></a> option.</li>
+    <li>Directly handle mousewheel events (again, hopefully better).</li>
+    <li>Make vertical cursor movement more robust (through widgets, big line gaps).</li>
+    <li>Add <a href="manual.html#option_flattenSpans"><code>flattenSpans</code></a> option.</li>
+    <li>Many optimizations. Poor responsiveness should be fixed.</li>
+    <li>Initialization in hidden state works again.</li>
+    <li>Full <a href="https://github.com/marijnh/CodeMirror/compare/v3.0beta1...v3.0beta2">list of patches</a>.</li>
+  </ul>
+
+  <p class="rel">19-09-2012: <a href="http://codemirror.net/codemirror-2.34.zip">Version 2.34</a>:</p>
+
+  <ul class="rel-note">
+    <li>New mode: <a href="../mode/commonlisp/index.html">Common Lisp</a>.</li>
+    <li>Fix right-click select-all on most browsers.</li>
+    <li>Change the way highlighting happens:<br>&nbsp; Saves memory and CPU cycles.<br>&nbsp; <code>compareStates</code> is no longer needed.<br>&nbsp; <code>onHighlightComplete</code> no longer works.</li>
+    <li>Integrate mode (Markdown, XQuery, CSS, sTex) tests in central testsuite.</li>
+    <li>Add a <a href="manual.html#version"><code>CodeMirror.version</code></a> property.</li>
+    <li>More robust handling of nested modes in <a href="../demo/formatting.html">formatting</a> and <a href="../demo/closetag.html">closetag</a> plug-ins.</li>
+    <li>Un/redo now preserves <a href="manual.html#markText">marked text</a> and bookmarks.</li>
+    <li><a href="https://github.com/marijnh/CodeMirror/compare/v2.33...v2.34">Full list</a> of patches.</li>
+  </ul>
+
+  <p class="rel">19-09-2012: <a href="http://codemirror.net/codemirror-3.0beta1.zip">Version 3.0, beta 1</a>:</p>
+
+  <ul class="rel-note">
+    <li>Bi-directional text support.</li>
+    <li>More powerful gutter model.</li>
+    <li>Support for arbitrary text/widget height.</li>
+    <li>In-line widgets.</li>
+    <li>Generalized event handling.</li>
+  </ul>
+
+  <p class="rel">23-08-2012: <a href="http://codemirror.net/codemirror-2.33.zip">Version 2.33</a>:</p>
+
+  <ul class="rel-note">
+    <li>New mode: <a href="../mode/sieve/index.html">Sieve</a>.</li>
+    <li>New <a href="manual.html#getViewport"><code>getViewPort</code></a> and <a href="manual.html#option_onViewportChange"><code>onViewportChange</code></a> API.</li>
+    <li><a href="manual.html#option_cursorBlinkRate">Configurable</a> cursor blink rate.</li>
+    <li>Make binding a key to <code>false</code> disabling handling (again).</li>
+    <li>Show non-printing characters as red dots.</li>
+    <li>More tweaks to the scrolling model.</li>
+    <li>Expanded testsuite. Basic linter added.</li>
+    <li>Remove most uses of <code>innerHTML</code>. Remove <code>CodeMirror.htmlEscape</code>.</li>
+    <li><a href="https://github.com/marijnh/CodeMirror/compare/v2.32...v2.33">Full list</a> of patches.</li>
+  </ul>
+
+  <p class="rel">23-07-2012: <a href="http://codemirror.net/codemirror-2.32.zip">Version 2.32</a>:</p>
+
+  <p class="rel-note">Emergency fix for a bug where an editor with
+  line wrapping on IE will break when there is <em>no</em>
+  scrollbar.</p>
+
+  <p class="rel">20-07-2012: <a href="http://codemirror.net/codemirror-2.31.zip">Version 2.31</a>:</p>
+
+  <ul class="rel-note">
+    <li>New modes: <a href="../mode/ocaml/index.html">OCaml</a>, <a href="../mode/haxe/index.html">Haxe</a>, and <a href="../mode/vb/index.html">VB.NET</a>.</li>
+    <li>Several fixes to the new scrolling model.</li>
+    <li>Add a <a href="manual.html#setSize"><code>setSize</code></a> method for programmatic resizing.</li>
+    <li>Add <a href="manual.html#getHistory"><code>getHistory</code></a> and <a href="manual.html#setHistory"><code>setHistory</code></a> methods.</li>
+    <li>Allow custom line separator string in <a href="manual.html#getValue"><code>getValue</code></a> and <a href="manual.html#getRange"><code>getRange</code></a>.</li>
+    <li>Support double- and triple-click drag, double-clicking whitespace.</li>
+    <li>And more... <a href="https://github.com/marijnh/CodeMirror/compare/v2.3...v2.31">(all patches)</a></li>
+  </ul>
+
+  <p class="rel">22-06-2012: <a href="http://codemirror.net/codemirror-2.3.zip">Version 2.3</a>:</p>
+
+  <ul class="rel-note">
+    <li><strong>New scrollbar implementation</strong>. Should flicker less. Changes DOM structure of the editor.</li>
+    <li>New theme: <a href="../demo/theme.html?vibrant-ink">vibrant-ink</a>.</li>
+    <li>Many extensions to the VIM keymap (including text objects).</li>
+    <li>Add <a href="../demo/multiplex.html">mode-multiplexing</a> utility script.</li>
+    <li>Fix bug where right-click paste works in read-only mode.</li>
+    <li>Add a <a href="manual.html#getScrollInfo"><code>getScrollInfo</code></a> method.</li>
+    <li>Lots of other <a href="https://github.com/marijnh/CodeMirror/compare/v2.25...v2.3">fixes</a>.</li>
+  </ul>
+
+  <p class="rel">23-05-2012: <a href="http://codemirror.net/codemirror-2.25.zip">Version 2.25</a>:</p>
+
+  <ul class="rel-note">
+    <li>New mode: <a href="../mode/erlang/index.html">Erlang</a>.</li>
+    <li><strong>Remove xmlpure mode</strong> (use <a href="../mode/xml/index.html">xml.js</a>).</li>
+    <li>Fix line-wrapping in Opera.</li>
+    <li>Fix X Windows middle-click paste in Chrome.</li>
+    <li>Fix bug that broke pasting of huge documents.</li>
+    <li>Fix backspace and tab key repeat in Opera.</li>
+  </ul>
+
+  <p class="rel">23-04-2012: <a href="http://codemirror.net/codemirror-2.24.zip">Version 2.24</a>:</p>
+
+  <ul class="rel-note">
+    <li><strong>Drop support for Internet Explorer 6</strong>.</li>
+    <li>New
+    modes: <a href="../mode/shell/index.html">Shell</a>, <a href="../mode/tiki/index.html">Tiki
+    wiki</a>, <a href="../mode/pig/index.html">Pig Latin</a>.</li>
+    <li>New themes: <a href="../demo/theme.html?ambiance">Ambiance</a>, <a href="../demo/theme.html?blackboard">Blackboard</a>.</li>
+    <li>More control over drag/drop
+    with <a href="manual.html#option_dragDrop"><code>dragDrop</code></a>
+    and <a href="manual.html#option_onDragEvent"><code>onDragEvent</code></a>
+    options.</li>
+    <li>Make HTML mode a bit less pedantic.</li>
+    <li>Add <a href="manual.html#compoundChange"><code>compoundChange</code></a> API method.</li>
+    <li>Several fixes in undo history and line hiding.</li>
+    <li>Remove (broken) support for <code>catchall</code> in key maps,
+    add <code>nofallthrough</code> boolean field instead.</li>
+  </ul>
+
+  <p class="rel">26-03-2012: <a href="http://codemirror.net/codemirror-2.23.zip">Version 2.23</a>:</p>
+
+  <ul class="rel-note">
+    <li>Change <strong>default binding for tab</strong> <a href="javascript:void(document.getElementById('tabbinding').style.display='')">[more]</a>
+      <div style="display: none" id=tabbinding>
+        Starting in 2.23, these bindings are default:
+        <ul><li>Tab: Insert tab character</li>
+          <li>Shift-tab: Reset line indentation to default</li>
+          <li>Ctrl/Cmd-[: Reduce line indentation (old tab behaviour)</li>
+          <li>Ctrl/Cmd-]: Increase line indentation (old shift-tab behaviour)</li>
+        </ul>
+      </div>
+    </li>
+    <li>New modes: <a href="../mode/xquery/index.html">XQuery</a> and <a href="../mode/vbscript/index.html">VBScript</a>.</li>
+    <li>Two new themes: <a href="../mode/less/index.html">lesser-dark</a> and <a href="../mode/xquery/index.html">xq-dark</a>.</li>
+    <li>Differentiate between background and text styles in <a href="manual.html#setLineClass"><code>setLineClass</code></a>.</li>
+    <li>Fix drag-and-drop in IE9+.</li>
+    <li>Extend <a href="manual.html#charCoords"><code>charCoords</code></a>
+    and <a href="manual.html#cursorCoords"><code>cursorCoords</code></a> with a <code>mode</code> argument.</li>
+    <li>Add <a href="manual.html#option_autofocus"><code>autofocus</code></a> option.</li>
+    <li>Add <a href="manual.html#findMarksAt"><code>findMarksAt</code></a> method.</li>
+  </ul>
+
+  <p class="rel">27-02-2012: <a href="http://codemirror.net/codemirror-2.22.zip">Version 2.22</a>:</p>
+
+  <ul class="rel-note">
+    <li>Allow <a href="manual.html#keymaps">key handlers</a> to pass up events, allow binding characters.</li>
+    <li>Add <a href="manual.html#option_autoClearEmptyLines"><code>autoClearEmptyLines</code></a> option.</li>
+    <li>Properly use tab stops when rendering tabs.</li>
+    <li>Make PHP mode more robust.</li>
+    <li>Support indentation blocks in <a href="manual.html#addon_foldcode">code folder</a>.</li>
+    <li>Add a script for <a href="manual.html#addon_match-highlighter">highlighting instances of the selection</a>.</li>
+    <li>New <a href="../mode/properties/index.html">.properties</a> mode.</li>
+    <li>Fix many bugs.</li>
+  </ul>
+
+  <p class="rel">27-01-2012: <a href="http://codemirror.net/codemirror-2.21.zip">Version 2.21</a>:</p>
+
+  <ul class="rel-note">
+    <li>Added <a href="../mode/less/index.html">LESS</a>, <a href="../mode/mysql/index.html">MySQL</a>,
+    <a href="../mode/go/index.html">Go</a>, and <a href="../mode/verilog/index.html">Verilog</a> modes.</li>
+    <li>Add <a href="manual.html#option_smartIndent"><code>smartIndent</code></a>
+    option.</li>
+    <li>Support a cursor in <a href="manual.html#option_readOnly"><code>readOnly</code></a>-mode.</li>
+    <li>Support assigning multiple styles to a token.</li>
+    <li>Use a new approach to drawing the selection.</li>
+    <li>Add <a href="manual.html#scrollTo"><code>scrollTo</code></a> method.</li>
+    <li>Allow undo/redo events to span non-adjacent lines.</li>
+    <li>Lots and lots of bugfixes.</li>
+  </ul>
+
+  <p class="rel">20-12-2011: <a href="http://codemirror.net/codemirror-2.2.zip">Version 2.2</a>:</p>
+
+  <ul class="rel-note">
+    <li>Slightly incompatible API changes. Read <a href="upgrade_v2.2.html">this</a>.</li>
+    <li>New approach
+    to <a href="manual.html#option_extraKeys">binding</a> keys,
+    support for <a href="manual.html#option_keyMap">custom
+    bindings</a>.</li>
+    <li>Support for overwrite (insert).</li>
+    <li><a href="manual.html#option_tabSize">Custom-width</a>
+    and <a href="../demo/visibletabs.html">stylable</a> tabs.</li>
+    <li>Moved more code into <a href="manual.html#addons">add-on scripts</a>.</li>
+    <li>Support for sane vertical cursor movement in wrapped lines.</li>
+    <li>More reliable handling of
+    editing <a href="manual.html#markText">marked text</a>.</li>
+    <li>Add minimal <a href="../demo/emacs.html">emacs</a>
+    and <a href="../demo/vim.html">vim</a> bindings.</li>
+    <li>Rename <code>coordsFromIndex</code>
+    to <a href="manual.html#posFromIndex"><code>posFromIndex</code></a>,
+    add <a href="manual.html#indexFromPos"><code>indexFromPos</code></a>
+    method.</li>
+  </ul>
+
+  <p class="rel">21-11-2011: <a href="http://codemirror.net/codemirror-2.18.zip">Version 2.18</a>:</p>
+  <p class="rel-note">Fixes <code>TextMarker.clear</code>, which is broken in 2.17.</p>
+
+  <p class="rel">21-11-2011: <a href="http://codemirror.net/codemirror-2.17.zip">Version 2.17</a>:</p>
+  <ul class="rel-note">
+    <li>Add support for <a href="manual.html#option_lineWrapping">line
+    wrapping</a> and <a href="manual.html#hideLine">code
+    folding</a>.</li>
+    <li>Add <a href="../mode/gfm/index.html">Github-style Markdown</a> mode.</li>
+    <li>Add <a href="../theme/monokai.css">Monokai</a>
+    and <a href="../theme/rubyblue.css">Rubyblue</a> themes.</li>
+    <li>Add <a href="manual.html#setBookmark"><code>setBookmark</code></a> method.</li>
+    <li>Move some of the demo code into reusable components
+    under <a href="../addon/"><code>lib/util</code></a>.</li>
+    <li>Make screen-coord-finding code faster and more reliable.</li>
+    <li>Fix drag-and-drop in Firefox.</li>
+    <li>Improve support for IME.</li>
+    <li>Speed up content rendering.</li>
+    <li>Fix browser's built-in search in Webkit.</li>
+    <li>Make double- and triple-click work in IE.</li>
+    <li>Various fixes to modes.</li>
+  </ul>
+
+  <p class="rel">27-10-2011: <a href="http://codemirror.net/codemirror-2.16.zip">Version 2.16</a>:</p>
+  <ul class="rel-note">
+    <li>Add <a href="../mode/perl/index.html">Perl</a>, <a href="../mode/rust/index.html">Rust</a>, <a href="../mode/tiddlywiki/index.html">TiddlyWiki</a>, and <a href="../mode/groovy/index.html">Groovy</a> modes.</li>
+    <li>Dragging text inside the editor now moves, rather than copies.</li>
+    <li>Add a <a href="manual.html#coordsFromIndex"><code>coordsFromIndex</code></a> method.</li>
+    <li><strong>API change</strong>: <code>setValue</code> now no longer clears history. Use <a href="manual.html#clearHistory"><code>clearHistory</code></a> for that.</li>
+    <li><strong>API change</strong>: <a href="manual.html#markText"><code>markText</code></a> now
+    returns an object with <code>clear</code> and <code>find</code>
+    methods. Marked text is now more robust when edited.</li>
+    <li>Fix editing code with tabs in Internet Explorer.</li>
+  </ul>
+
+  <p class="rel">26-09-2011: <a href="http://codemirror.net/codemirror-2.15.zip">Version 2.15</a>:</p>
+  <p class="rel-note">Fix bug that snuck into 2.14: Clicking the
+  character that currently has the cursor didn't re-focus the
+  editor.</p>
+
+  <p class="rel">26-09-2011: <a href="http://codemirror.net/codemirror-2.14.zip">Version 2.14</a>:</p>
+  <ul class="rel-note">
+    <li>Add <a href="../mode/clojure/index.html">Clojure</a>, <a href="../mode/pascal/index.html">Pascal</a>, <a href="../mode/ntriples/index.html">NTriples</a>, <a href="../mode/jinja2/index.html">Jinja2</a>, and <a href="../mode/markdown/index.html">Markdown</a> modes.</li>
+    <li>Add <a href="../theme/cobalt.css">Cobalt</a> and <a href="../theme/eclipse.css">Eclipse</a> themes.</li>
+    <li>Add a <a href="manual.html#option_fixedGutter"><code>fixedGutter</code></a> option.</li>
+    <li>Fix bug with <code>setValue</code> breaking cursor movement.</li>
+    <li>Make gutter updates much more efficient.</li>
+    <li>Allow dragging of text out of the editor (on modern browsers).</li>
+  </ul>
+
+
+  <p class="rel">23-08-2011: <a href="http://codemirror.net/codemirror-2.13.zip">Version 2.13</a>:</p>
+  <ul class="rel-note">
+    <li>Add <a href="../mode/ruby/index.html">Ruby</a>, <a href="../mode/r/index.html">R</a>, <a href="../mode/coffeescript/index.html">CoffeeScript</a>, and <a href="../mode/velocity/index.html">Velocity</a> modes.</li>
+    <li>Add <a href="manual.html#getGutterElement"><code>getGutterElement</code></a> to API.</li>
+    <li>Several fixes to scrolling and positioning.</li>
+    <li>Add <a href="manual.html#option_smartHome"><code>smartHome</code></a> option.</li>
+    <li>Add an experimental <a href="../mode/xmlpure/index.html">pure XML</a> mode.</li>
+  </ul>
+
+  <p class="rel">25-07-2011: <a href="http://codemirror.net/codemirror-2.12.zip">Version 2.12</a>:</p>
+  <ul class="rel-note">
+    <li>Add a <a href="../mode/sparql/index.html">SPARQL</a> mode.</li>
+    <li>Fix bug with cursor jumping around in an unfocused editor in IE.</li>
+    <li>Allow key and mouse events to bubble out of the editor. Ignore widget clicks.</li>
+    <li>Solve cursor flakiness after undo/redo.</li>
+    <li>Fix block-reindent ignoring the last few lines.</li>
+    <li>Fix parsing of multi-line attrs in XML mode.</li>
+    <li>Use <code>innerHTML</code> for HTML-escaping.</li>
+    <li>Some fixes to indentation in C-like mode.</li>
+    <li>Shrink horiz scrollbars when long lines removed.</li>
+    <li>Fix width feedback loop bug that caused the width of an inner DIV to shrink.</li>
+  </ul>
+
+  <p class="rel">04-07-2011: <a href="http://codemirror.net/codemirror-2.11.zip">Version 2.11</a>:</p>
+  <ul class="rel-note">
+    <li>Add a <a href="../mode/scheme/index.html">Scheme mode</a>.</li>
+    <li>Add a <code>replace</code> method to search cursors, for cursor-preserving replacements.</li>
+    <li>Make the <a href="../mode/clike/index.html">C-like mode</a> mode more customizable.</li>
+    <li>Update XML mode to spot mismatched tags.</li>
+    <li>Add <code>getStateAfter</code> API and <code>compareState</code> mode API methods for finer-grained mode magic.</li>
+    <li>Add a <code>getScrollerElement</code> API method to manipulate the scrolling DIV.</li>
+    <li>Fix drag-and-drop for Firefox.</li>
+    <li>Add a C# configuration for the <a href="../mode/clike/index.html">C-like mode</a>.</li>
+    <li>Add <a href="../demo/fullscreen.html">full-screen editing</a> and <a href="../demo/changemode.html">mode-changing</a> demos.</li>
+  </ul>
+
+  <p class="rel">07-06-2011: <a href="http://codemirror.net/codemirror-2.1.zip">Version 2.1</a>:</p>
+  <p class="rel-note">Add
+  a <a href="manual.html#option_theme">theme</a> system
+  (<a href="../demo/theme.html">demo</a>). Note that this is not
+  backwards-compatible—you'll have to update your styles and
+  modes!</p>
+
+  <p class="rel">07-06-2011: <a href="http://codemirror.net/codemirror-2.02.zip">Version 2.02</a>:</p>
+  <ul class="rel-note">
+    <li>Add a <a href="../mode/lua/index.html">Lua mode</a>.</li>
+    <li>Fix reverse-searching for a regexp.</li>
+    <li>Empty lines can no longer break highlighting.</li>
+    <li>Rework scrolling model (the outer wrapper no longer does the scrolling).</li>
+    <li>Solve horizontal jittering on long lines.</li>
+    <li>Add <a href="../demo/runmode.html">runmode.js</a>.</li>
+    <li>Immediately re-highlight text when typing.</li>
+    <li>Fix problem with 'sticking' horizontal scrollbar.</li>
+  </ul>
+
+  <p class="rel">26-05-2011: <a href="http://codemirror.net/codemirror-2.01.zip">Version 2.01</a>:</p>
+  <ul class="rel-note">
+    <li>Add a <a href="../mode/smalltalk/index.html">Smalltalk mode</a>.</li>
+    <li>Add a <a href="../mode/rst/index.html">reStructuredText mode</a>.</li>
+    <li>Add a <a href="../mode/python/index.html">Python mode</a>.</li>
+    <li>Add a <a href="../mode/plsql/index.html">PL/SQL mode</a>.</li>
+    <li><code>coordsChar</code> now works</li>
+    <li>Fix a problem where <code>onCursorActivity</code> interfered with <code>onChange</code>.</li>
+    <li>Fix a number of scrolling and mouse-click-position glitches.</li>
+    <li>Pass information about the changed lines to <code>onChange</code>.</li>
+    <li>Support cmd-up/down on OS X.</li>
+    <li>Add triple-click line selection.</li>
+    <li>Don't handle shift when changing the selection through the API.</li>
+    <li>Support <code>"nocursor"</code> mode for <code>readOnly</code> option.</li>
+    <li>Add an <code>onHighlightComplete</code> option.</li>
+    <li>Fix the context menu for Firefox.</li>
+  </ul>
+
+  <p class="rel">28-03-2011: <a href="http://codemirror.net/codemirror-2.0.zip">Version 2.0</a>:</p>
+  <p class="rel-note">CodeMirror 2 is a complete rewrite that's
+  faster, smaller, simpler to use, and less dependent on browser
+  quirks. See <a href="internals.html">this</a>
+  and <a href="http://groups.google.com/group/codemirror/browse_thread/thread/5a8e894024a9f580">this</a>
+  for more information.</p>
+
+  <p class="rel">28-03-2011: <a href="http://codemirror.net/codemirror-1.0.zip">Version 1.0</a>:</p>
+  <ul class="rel-note">
+    <li>Fix error when debug history overflows.</li>
+    <li>Refine handling of C# verbatim strings.</li>
+    <li>Fix some issues with JavaScript indentation.</li>
+  </ul>
+
+  <p class="rel">22-02-2011: <a href="https://github.com/marijnh/codemirror/tree/beta2">Version 2.0 beta 2</a>:</p>
+  <p class="rel-note">Somewhat more mature API, lots of bugs shaken out.</p>
+
+  <p class="rel">17-02-2011: <a href="http://codemirror.net/codemirror-0.94.zip">Version 0.94</a>:</p>
+  <ul class="rel-note">
+    <li><code>tabMode: "spaces"</code> was modified slightly (now indents when something is selected).</li>
+    <li>Fixes a bug that would cause the selection code to break on some IE versions.</li>
+    <li>Disabling spell-check on WebKit browsers now works.</li>
+  </ul>
+
+  <p class="rel">08-02-2011: <a href="http://codemirror.net/">Version 2.0 beta 1</a>:</p>
+  <p class="rel-note">CodeMirror 2 is a complete rewrite of
+  CodeMirror, no longer depending on an editable frame.</p>
+
+  <p class="rel">19-01-2011: <a href="http://codemirror.net/codemirror-0.93.zip">Version 0.93</a>:</p>
+  <ul class="rel-note">
+    <li>Added a <a href="contrib/regex/index.html">Regular Expression</a> parser.</li>
+    <li>Fixes to the PHP parser.</li>
+    <li>Support for regular expression in search/replace.</li>
+    <li>Add <code>save</code> method to instances created with <code>fromTextArea</code>.</li>
+    <li>Add support for MS T-SQL in the SQL parser.</li>
+    <li>Support use of CSS classes for highlighting brackets.</li>
+    <li>Fix yet another hang with line-numbering in hidden editors.</li>
+  </ul>
+
+  <p class="rel">17-12-2010: <a href="http://codemirror.net/codemirror-0.92.zip">Version 0.92</a>:</p>
+  <ul class="rel-note">
+    <li>Make CodeMirror work in XHTML documents.</li>
+    <li>Fix bug in handling of backslashes in Python strings.</li>
+    <li>The <code>styleNumbers</code> option is now officially
+    supported and documented.</li>
+    <li><code>onLineNumberClick</code> option added.</li>
+    <li>More consistent names <code>onLoad</code> and
+    <code>onCursorActivity</code> callbacks. Old names still work, but
+    are deprecated.</li>
+    <li>Add a <a href="contrib/freemarker/index.html">Freemarker</a> mode.</li>
+  </ul>
+
+  <p class="rel">11-11-2010: <a
+  href="http://codemirror.net/codemirror-0.91.zip">Version 0.91</a>:</p>
+  <ul class="rel-note">
+    <li>Adds support for <a href="contrib/java">Java</a>.</li>
+    <li>Small additions to the <a href="contrib/php">PHP</a> and <a href="contrib/sql">SQL</a> parsers.</li>
+    <li>Work around various <a href="https://bugs.webkit.org/show_bug.cgi?id=47806">Webkit</a> <a href="https://bugs.webkit.org/show_bug.cgi?id=23474">issues</a>.</li>
+    <li>Fix <code>toTextArea</code> to update the code in the textarea.</li>
+    <li>Add a <code>noScriptCaching</code> option (hack to ease development).</li>
+    <li>Make sub-modes of <a href="mixedtest.html">HTML mixed</a> mode configurable.</li>
+  </ul>
+
+  <p class="rel">02-10-2010: <a
+  href="http://codemirror.net/codemirror-0.9.zip">Version 0.9</a>:</p>
+  <ul class="rel-note">
+    <li>Add support for searching backwards.</li>
+    <li>There are now parsers for <a href="contrib/scheme/index.html">Scheme</a>, <a href="contrib/xquery/index.html">XQuery</a>, and <a href="contrib/ometa/index.html">OmetaJS</a>.</li>
+    <li>Makes <code>height: "dynamic"</code> more robust.</li>
+    <li>Fixes bug where paste did not work on OS X.</li>
+    <li>Add a <code>enterMode</code> and <code>electricChars</code> options to make indentation even more customizable.</li>
+    <li>Add <code>firstLineNumber</code> option.</li>
+    <li>Fix bad handling of <code>@media</code> rules by the CSS parser.</li>
+    <li>Take a new, more robust approach to working around the invisible-last-line bug in WebKit.</li>
+  </ul>
+
+  <p class="rel">22-07-2010: <a
+  href="http://codemirror.net/codemirror-0.8.zip">Version 0.8</a>:</p>
+  <ul class="rel-note">
+    <li>Add a <code>cursorCoords</code> method to find the screen
+    coordinates of the cursor.</li>
+    <li>A number of fixes and support for more syntax in the PHP parser.</li>
+    <li>Fix indentation problem with JSON-mode JS parser in Webkit.</li>
+    <li>Add a <a href="compress.html">minification</a> UI.</li>
+    <li>Support a <code>height: dynamic</code> mode, where the editor's
+    height will adjust to the size of its content.</li>
+    <li>Better support for IME input mode.</li>
+    <li>Fix JavaScript parser getting confused when seeing a no-argument
+    function call.</li>
+    <li>Have CSS parser see the difference between selectors and other
+    identifiers.</li>
+    <li>Fix scrolling bug when pasting in a horizontally-scrolled
+    editor.</li>
+    <li>Support <code>toTextArea</code> method in instances created with
+    <code>fromTextArea</code>.</li>
+    <li>Work around new Opera cursor bug that causes the cursor to jump
+    when pressing backspace at the end of a line.</li>
+  </ul>
+
+  <p class="rel">27-04-2010: <a
+  href="http://codemirror.net/codemirror-0.67.zip">Version
+  0.67</a>:</p>
+  <p class="rel-note">More consistent page-up/page-down behaviour
+  across browsers. Fix some issues with hidden editors looping forever
+  when line-numbers were enabled. Make PHP parser parse
+  <code>"\\"</code> correctly. Have <code>jumpToLine</code> work on
+  line handles, and add <code>cursorLine</code> function to fetch the
+  line handle where the cursor currently is. Add new
+  <code>setStylesheet</code> function to switch style-sheets in a
+  running editor.</p>
+
+  <p class="rel">01-03-2010: <a
+  href="http://codemirror.net/codemirror-0.66.zip">Version
+  0.66</a>:</p>
+  <p class="rel-note">Adds <code>removeLine</code> method to API.
+  Introduces the <a href="contrib/plsql/index.html">PLSQL parser</a>.
+  Marks XML errors by adding (rather than replacing) a CSS class, so
+  that they can be disabled by modifying their style. Fixes several
+  selection bugs, and a number of small glitches.</p>
+
+  <p class="rel">12-11-2009: <a
+  href="http://codemirror.net/codemirror-0.65.zip">Version
+  0.65</a>:</p>
+  <p class="rel-note">Add support for having both line-wrapping and
+  line-numbers turned on, make paren-highlighting style customisable
+  (<code>markParen</code> and <code>unmarkParen</code> config
+  options), work around a selection bug that Opera
+  <em>re</em>introduced in version 10.</p>
+
+  <p class="rel">23-10-2009: <a
+  href="http://codemirror.net/codemirror-0.64.zip">Version
+  0.64</a>:</p>
+  <p class="rel-note">Solves some issues introduced by the
+  paste-handling changes from the previous release. Adds
+  <code>setSpellcheck</code>, <code>setTextWrapping</code>,
+  <code>setIndentUnit</code>, <code>setUndoDepth</code>,
+  <code>setTabMode</code>, and <code>setLineNumbers</code> to
+  customise a running editor. Introduces an <a
+  href="contrib/sql/index.html">SQL</a> parser. Fixes a few small
+  problems in the <a href="contrib/python/index.html">Python</a>
+  parser. And, as usual, add workarounds for various newly discovered
+  browser incompatibilities.</p>
+
+<p class="rel"><em>31-08-2009</em>: <a
+href="http://codemirror.net/codemirror-0.63.zip">Version
+0.63</a>:</p>
+<p class="rel-note"> Overhaul of paste-handling (less fragile), fixes for several
+serious IE8 issues (cursor jumping, end-of-document bugs) and a number
+of small problems.</p>
+
+<p class="rel"><em>30-05-2009</em>: <a
+href="http://codemirror.net/codemirror-0.62.zip">Version
+0.62</a>:</p>
+<p class="rel-note">Introduces <a href="contrib/python/index.html">Python</a>
+and <a href="contrib/lua/index.html">Lua</a> parsers. Add
+<code>setParser</code> (on-the-fly mode changing) and
+<code>clearHistory</code> methods. Make parsing passes time-based
+instead of lines-based (see the <code>passTime</code> option).</p>
+
+</body></html>
diff --git a/third-party/codemirror-3.15/doc/realworld.html b/third-party/codemirror-3.15/doc/realworld.html
new file mode 100644 (file)
index 0000000..d83554a
--- /dev/null
@@ -0,0 +1,119 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8"/>
+    <title>CodeMirror: Real-world uses</title>
+    <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Droid+Sans|Droid+Sans:bold"/>
+    <link rel="stylesheet" type="text/css" href="docs.css"/>
+  </head>
+  <body>
+
+<h1><span class="logo-braces">{ }</span> <a href="http://codemirror.net/">CodeMirror</a></h1>
+
+<div class="grey">
+<img src="baboon.png" class="logo" alt="logo"/>
+<pre>
+/* Real world uses,
+   full list */
+</pre>
+</div>
+
+    <p><a href="mailto:marijnh@gmail.com">Contact me</a> if you'd like
+    your project to be added to this list.</p>
+
+    <ul>
+      <li><a href="http://brackets.io">Adobe Brackets</a> (code editor)</li>
+      <li><a href="http://amber-lang.net/">Amber</a> (JavaScript-based Smalltalk system)</li>
+      <li><a href="http://apeye.org/">APEye</a> (tool for testing &amp; documenting APIs)</li>
+      <li><a href="http://blog.bitbucket.org/2013/05/14/edit-your-code-in-the-cloud-with-bitbucket/">Bitbucket</a> (code hosting)</li>
+      <li><a href="http://buzz.blogger.com/2013/04/improvements-to-blogger-template-html.html">Blogger's template editor</a></li>
+      <li><a href="http://bluegriffon.org/">BlueGriffon</a> (HTML editor)</li>
+      <li><a href="http://cargocollective.com/">Cargo Collective</a> (creative publishing platform)</li>
+      <li><a href="http://clickhelp.co/">ClickHelp</a> (technical writing tool)</li>
+      <li><a href="http://drupal.org/project/cpn">Code per Node</a> (Drupal module)</li>
+      <li><a href="http://www.codebugapp.com/">Codebug</a> (PHP Xdebug front-end)</li>
+      <li><a href="https://github.com/angelozerr/CodeMirror-Eclipse">CodeMirror Eclipse</a> (embed CM in Eclipse)</li>
+      <li><a href="http://emmet.io/blog/codemirror-movie/">CodeMirror movie</a> (scripted editing demos)</li>
+      <li><a href="http://code.google.com/p/codemirror2-gwt/">CodeMirror2-GWT</a> (Google Web Toolkit wrapper)</li>
+      <li><a href="http://www.crunchzilla.com/code-monster">Code Monster</a> & <a href="http://www.crunchzilla.com/code-maven">Code Maven</a> (learning environment)</li>
+      <li><a href="http://codepen.io">Codepen</a> (gallery of animations)</li>
+      <li><a href="http://sasstwo.codeschool.com/levels/1/challenges/1">Code School</a> (online tech learning environment)</li>
+      <li><a href="http://code-snippets.bungeshea.com/">Code Snippets</a> (WordPress snippet management plugin)</li>
+      <li><a href="http://antonmi.github.io/code_together/">Code together</a> (collaborative editing)</li>
+      <li><a href="http://codev.it/">Codev</a> (collaborative IDE)</li>
+      <li><a href="http://www.codezample.com">CodeZample</a> (code snippet sharing)</li>
+      <li><a href="http://ot.substance.io/demo/">Collaborative CodeMirror demo</a> (CodeMirror + operational transforms)</li>
+      <li><a href="http://www.communitycodecamp.com/">Community Code Camp</a> (code snippet sharing)</li>
+      <li><a href="http://www.ckwnc.com/">CKWNC</a> (UML editor)</li>
+      <li><a href="http://cssdeck.com/">CSSDeck</a> (CSS showcase)</li>
+      <li><a href="http://ireneros.com/deck/deck.js-codemirror/introduction/#textarea-code">Deck.js integration</a> (slides with editors)</li>
+      <li><a href="http://www.dbninja.com">DbNinja</a> (MySQL access interface)</li>
+      <li><a href="https://chat.echoplex.us/">Echoplexus</a> (chat and collaborative coding)</li>
+      <li><a href="http://elm-lang.org/Examples.elm">Elm language examples</a></li>
+      <li><a href="http://eloquentjavascript.net/chapter1.html">Eloquent JavaScript</a> (book)</li>
+      <li><a href="http://emmet.io">Emmet</a> (fast XML editing)</li>
+      <li><a href="http://www.fastfig.com/">Fastfig</a> (online computation/math tool)</li>
+      <li><a href="https://metacpan.org/module/Farabi">Farabi</a> (modern Perl IDE)</li>
+      <li><a href="http://blog.pamelafox.org/2012/02/interactive-html5-slides-with-fathomjs.html">FathomJS integration</a> (slides with editors, again)</li>
+      <li><a href="http://fiddlesalad.com/">Fiddle Salad</a> (web development environment)</li>
+      <li><a href="http://www.firepad.io">Firepad</a> (collaborative text editor)</li>
+      <li><a href="http://tour.golang.org">Go language tour</a></li>
+      <li><a href="https://github.com/github/android">GitHub's Android app</a></li>
+      <li><a href="https://script.google.com/">Google Apps Script</a></li>
+      <li><a href="http://web.uvic.ca/~siefkenj/graphit/graphit.html">Graphit</a> (function graphing)</li>
+      <li><a href="http://www.handcraft2.com/">Handcraft 2</a> (HTML prototyping)</li>
+      <li><a href="http://try.haxe.org">Haxe</a> (Haxe Playground) </li>
+      <li><a href="http://haxpad.com/">HaxPad</a> (editor for Win RT)</li>
+      <li><a href="http://megafonweblab.github.com/histone-javascript/">Histone template engine playground</a></li>
+      <li><a href="http://icecoder.net">ICEcoder</a> (web IDE)</li>
+      <li><a href="http://www.janvas.com/">Janvas</a> (vector graphics editor)</li>
+      <li><a href="http://extensions.joomla.org/extensions/edition/editors/8723">Joomla plugin</a></li>
+      <li><a href="http://jqfundamentals.com/">jQuery fundamentals</a> (interactive tutorial)</li>
+      <li><a href="http://jsbin.com">jsbin.com</a> (JS playground)</li>
+      <li><a href="http://jsfiddle.com">jsfiddle.com</a> (another JS playground)</li>
+      <li><a href="http://www.jshint.com/">JSHint</a> (JS linter)</li>
+      <li><a href="http://jumpseller.com/">Jumpseller</a> (online store builder)</li>
+      <li><a href="http://kl1p.com/cmtest/1">kl1p</a> (paste service)</li>
+      <li><a href="http://www.chris-granger.com/2012/04/12/light-table---a-new-ide-concept/">Light Table</a> (experimental IDE)</li>
+      <li><a href="http://marklighteditor.com/">Marklight editor</a> (lightweight markup editor)</li>
+      <li><a href="http://www.mergely.com/">Mergely</a> (interactive diffing)</li>
+      <li><a href="http://www.iunbug.com/mihtool">MIHTool</a> (iOS web-app debugging tool)</li>
+      <li><a href="http://mongo-mapreduce-webbrowser.opensagres.cloudbees.net/">Mongo MapReduce WebBrowser</a></li>
+      <li><a href="https://www.my2ndgeneration.com/">My2ndGeneration</a> (social coding)</li>
+      <li><a href="http://www.navigatecms.com">Navigate CMS</a></li>
+      <li><a href="https://notex.ch">NoTex</a> (rST authoring)</li>
+      <li><a href="http://oakoutliner.com">Oak</a> (online outliner)</li>
+      <li><a href="http://clrhome.org/asm/">ORG</a> (z80 assembly IDE)</li>
+      <li><a href="https://github.com/mamacdon/orion-codemirror">Orion-CodeMirror integration</a> (running CodeMirror modes in Orion)</li>
+      <li><a href="http://paperjs.org/">Paper.js</a> (graphics scripting)</li>
+      <li><a href="http://prose.io/">Prose.io</a> (github content editor)</li>
+      <li><a href="http://ql.io/">ql.io</a> (http API query helper)</li>
+      <li><a href="http://qyapp.com">QiYun web app platform</a></li>
+      <li><a href="http://ariya.ofilabs.com/2011/09/hybrid-webnative-desktop-codemirror.html">Qt+Webkit integration</a> (building a desktop CodeMirror app)</li>
+      <li><a href="http://www.quivive-file-manager.com">Quivive File Manager</a></li>
+      <li><a href="http://rascalmicro.com/docs/basic-tutorial-getting-started.html">Rascal</a> (tiny computer)</li>
+      <li><a href="https://www.realtime.io/">RealTime.io</a> (Internet-of-Things infrastructure)</li>
+      <li><a href="https://www.shadertoy.com/">Shadertoy</a> (shader sharing)</li>
+      <li><a href="http://www.sketchpatch.net/labs/livecodelabIntro.html">sketchPatch Livecodelab</a></li>
+      <li><a href="http://www.skulpt.org/">Skulpt</a> (in-browser Python environment)</li>
+      <li><a href="http://snippets.pro/">Snippets.pro</a> (code snippet sharing)</li>
+      <li><a href="http://www.solidshops.com/">SolidShops</a> (hosted e-commerce platform)</li>
+      <li><a href="http://sqlfiddle.com">SQLFiddle</a> (SQL playground)</li>
+      <li><a href="https://thefiletree.com">The File Tree</a> (collab editor)</li>
+      <li><a href="http://www.toolsverse.com/products/data-explorer/">Toolsverse Data Explorer</a> (database management)</li>
+      <li><a href="http://enjalot.com/tributary/2636296/sinwaves.js">Tributary</a> (augmented editing)</li>
+      <li><a href="http://blog.englard.net/post/39608000629/codeintumblr">Tumblr code highlighting shim</a></li>
+      <li><a href="http://turbopy.com/">TurboPY</a> (web publishing framework)</li>
+      <li><a href="http://cruise.eecs.uottawa.ca/umpleonline/">UmpleOnline</a> (model-oriented programming tool)</li>
+      <li><a href="https://upsource.jetbrains.com/#idea/view/923f30395f2603cd9f42a32bcafd13b6c28de0ff/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/style/ReplaceAbstractClassInstanceByMapIntention.java">Upsource</a> (code viewer)</li>
+      <li><a href="http://www.webglacademy.com/">WebGL academy</a> (learning WebGL)</li>
+      <li><a href="http://webglplayground.net/">WebGL playground</a></li>
+      <li><a href="https://www.webkit.org/blog/2518/state-of-web-inspector/#source-code">WebKit Web inspector</a></li>
+      <li><a href="http://www.wescheme.org/">WeScheme</a> (learning tool)</li>
+      <li><a href="http://wordpress.org/extend/plugins/codemirror-for-codeeditor/">WordPress plugin</a></li>
+      <li><a href="http://www.xosystem.org/home/applications_websites/xosystem_website/xoside_EN.php">XOSide</a> (online editor)</li>
+      <li><a href="http://videlibri.sourceforge.net/cgi-bin/xidelcgi">XQuery tester</a></li>
+    </ul>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/doc/reporting.html b/third-party/codemirror-3.15/doc/reporting.html
new file mode 100644 (file)
index 0000000..a616512
--- /dev/null
@@ -0,0 +1,60 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8"/>
+    <title>CodeMirror: Reporting Bugs</title>
+    <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Droid+Sans|Droid+Sans:bold"/>
+    <link rel="stylesheet" type="text/css" href="docs.css"/>
+    <style>li { margin-top: 1em; }</style>
+  </head>
+  <body>
+
+<h1><span class="logo-braces">{ }</span> <a href="http://codemirror.net/">CodeMirror</a></h1>
+
+<div class="grey">
+<img src="baboon.png" class="logo" alt="logo"/>
+<pre>
+/* Reporting bugs
+   effectively */
+</pre>
+</div>
+
+<div class="left">
+
+<p>So you found a problem in CodeMirror. By all means, report it! Bug
+reports from users are the main drive behind improvements to
+CodeMirror. But first, please read over these points:</p>
+
+<ol>
+  <li>CodeMirror is maintained by volunteers. They don't owe you
+  anything, so be polite. Reports with an indignant or belligerent
+  tone tend to be moved to the bottom of the pile.</li>
+
+  <li>Include information about <strong>the browser in which the
+  problem occurred</strong>. Even if you tested several browsers, and
+  the problem occurred in all of them, mention this fact in the bug
+  report. Also include browser version numbers and the operating
+  system that you're on.</li>
+
+  <li>Mention which release of CodeMirror you're using. Preferably,
+  try also with the current development snapshot, to ensure the
+  problem has not already been fixed.</li>
+
+  <li>Mention very precisely what went wrong. "X is broken" is not a
+  good bug report. What did you expect to happen? What happened
+  instead? Describe the exact steps a maintainer has to take to make
+  the problem occur. We can not fix something that we can not
+  observe.</li>
+
+  <li>If the problem can not be reproduced in any of the demos
+  included in the CodeMirror distribution, please provide an HTML
+  document that demonstrates the problem. The best way to do this is
+  to go to <a href="http://jsbin.com/ihunin/edit">jsbin.com</a>, enter
+  it there, press save, and include the resulting link in your bug
+  report.</li>
+</ol>
+
+</div>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/doc/upgrade_v2.2.html b/third-party/codemirror-3.15/doc/upgrade_v2.2.html
new file mode 100644 (file)
index 0000000..7e4d840
--- /dev/null
@@ -0,0 +1,98 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8"/>
+    <title>CodeMirror: Upgrading to v2.2</title>
+    <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Droid+Sans|Droid+Sans:bold"/>
+    <link rel="stylesheet" type="text/css" href="docs.css"/>
+  </head>
+  <body>
+
+<h1><span class="logo-braces">{ }</span> <a href="http://codemirror.net/">CodeMirror</a></h1>
+
+<div class="grey">
+<img src="baboon.png" class="logo" alt="logo"/>
+<pre>
+/* Upgrading to
+   v2.2 */
+</pre>
+</div>
+
+<div class="left">
+
+<p>There are a few things in the 2.2 release that require some care
+when upgrading.</p>
+
+<h2>No more default.css</h2>
+
+<p>The default theme is now included
+in <a href="../lib/codemirror.css"><code>codemirror.css</code></a>, so
+you do not have to included it separately anymore. (It was tiny, so
+even if you're not using it, the extra data overhead is negligible.)
+
+<h2>Different key customization</h2>
+
+<p>CodeMirror has moved to a system
+where <a href="manual.html#option_keyMap">keymaps</a> are used to
+bind behavior to keys. This means <a href="../demo/emacs.html">custom
+bindings</a> are now possible.</p>
+
+<p>Three options that influenced key
+behavior, <code>tabMode</code>, <code>enterMode</code>,
+and <code>smartHome</code>, are no longer supported. Instead, you can
+provide custom bindings to influence the way these keys act. This is
+done through the
+new <a href="manual.html#option_extraKeys"><code>extraKeys</code></a>
+option, which can hold an object mapping key names to functionality. A
+simple example would be:</p>
+
+<pre>  extraKeys: {
+    "Ctrl-S": function(instance) { saveText(instance.getValue()); },
+    "Ctrl-/": "undo"
+  }</pre>
+
+<p>Keys can be mapped either to functions, which will be given the
+editor instance as argument, or to strings, which are mapped through
+functions through the <code>CodeMirror.commands</code> table, which
+contains all the built-in editing commands, and can be inspected and
+extended by external code.</p>
+
+<p>By default, the <code>Home</code> key is bound to
+the <code>"goLineStartSmart"</code> command, which moves the cursor to
+the first non-whitespace character on the line. You can set do this to
+make it always go to the very start instead:</p>
+
+<pre>  extraKeys: {"Home": "goLineStart"}</pre>
+
+<p>Similarly, <code>Enter</code> is bound
+to <code>"newlineAndIndent"</code> by default. You can bind it to
+something else to get different behavior. To disable special handling
+completely and only get a newline character inserted, you can bind it
+to <code>false</code>:</p>
+
+<pre>  extraKeys: {"Enter": false}</pre>
+
+<p>The same works for <code>Tab</code>. If you don't want CodeMirror
+to handle it, bind it to <code>false</code>. The default behaviour is
+to indent the current line more (<code>"indentMore"</code> command),
+and indent it less when shift is held (<code>"indentLess"</code>).
+There are also <code>"indentAuto"</code> (smart indent)
+and <code>"insertTab"</code> commands provided for alternate
+behaviors. Or you can write your own handler function to do something
+different altogether.</p>
+
+<h2>Tabs</h2>
+
+<p>Handling of tabs changed completely. The display width of tabs can
+now be set with the <code>tabSize</code> option, and tabs can
+be <a href="../demo/visibletabs.html">styled</a> by setting CSS rules
+for the <code>cm-tab</code> class.</p>
+
+<p>The default width for tabs is now 4, as opposed to the 8 that is
+hard-wired into browsers. If you are relying on 8-space tabs, make
+sure you explicitly set <code>tabSize: 8</code> in your options.</p>
+
+</div>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/doc/upgrade_v3.html b/third-party/codemirror-3.15/doc/upgrade_v3.html
new file mode 100644 (file)
index 0000000..7e8a6b6
--- /dev/null
@@ -0,0 +1,227 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8"/>
+    <title>CodeMirror: Upgrading to v3</title>
+    <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Droid+Sans|Droid+Sans:bold"/>
+    <link rel="stylesheet" type="text/css" href="docs.css"/>
+    <script src="../lib/codemirror.js"></script>
+    <link rel="stylesheet" href="../lib/codemirror.css">
+    <script src="../addon/runmode/runmode.js"></script>
+    <script src="../addon/runmode/colorize.js"></script>
+    <script src="../mode/javascript/javascript.js"></script>
+    <script src="../mode/xml/xml.js"></script>
+    <script src="../mode/css/css.js"></script>
+    <script src="../mode/htmlmixed/htmlmixed.js"></script>
+  </head>
+  <body>
+
+<h1><span class="logo-braces">{ }</span> <a href="http://codemirror.net/">CodeMirror</a></h1>
+
+<div class="grey">
+<img src="baboon.png" class="logo" alt="logo"/>
+<pre>
+/* Upgrading to
+   version 3 */
+</pre>
+</div>
+
+<div class="clear"><div class="leftbig blk">
+
+<p>Version 3 does not depart too much from 2.x API, and sites that use
+CodeMirror in a very simple way might be able to upgrade without
+trouble. But it does introduce a number of incompatibilities. Please
+at least skim this text before upgrading.</p>
+
+<p>Note that <strong>version 3 drops full support for Internet
+Explorer 7</strong>. The editor will mostly work on that browser, but
+it'll be significantly glitchy.</p>
+
+<h2 id=dom>DOM structure</h2>
+
+<p>This one is the most likely to cause problems. The internal
+structure of the editor has changed quite a lot, mostly to implement a
+new scrolling model.</p>
+
+<p>Editor height is now set on the outer wrapper element (CSS
+class <code>CodeMirror</code>), not on the scroller element
+(<code>CodeMirror-scroll</code>).</p>
+
+<p>Other nodes were moved, dropped, and added. If you have any code
+that makes assumptions about the internal DOM structure of the editor,
+you'll have to re-test it and probably update it to work with v3.</p>
+
+<p>See the <a href="manual.html#styling">styling section</a> of the
+manual for more information.</p>
+
+<h2 id=gutters>Gutter model</h2>
+
+<p>In CodeMirror 2.x, there was a single gutter, and line markers
+created with <code>setMarker</code> would have to somehow coexist with
+the line numbers (if present). Version 3 allows you to specify an
+array of gutters, <a href="manual.html#option_gutters">by class
+name</a>,
+use <a href="manual.html#setGutterMarker"><code>setGutterMarker</code></a>
+to add or remove markers in individual gutters, and clear whole
+gutters
+with <a href="manual.html#clearGutter"><code>clearGutter</code></a>.
+Gutter markers are now specified as DOM nodes, rather than HTML
+snippets.</p>
+
+<p>The gutters no longer horizontally scrolls along with the content.
+The <code>fixedGutter</code> option was removed (since it is now the
+only behavior).</p>
+
+<pre data-lang="text/html">
+&lt;style>
+  /* Define a gutter style */
+  .note-gutter { width: 3em; background: cyan; }
+&lt;/style>
+&lt;script>
+  // Create an instance with two gutters -- line numbers and notes
+  var cm = new CodeMirror(document.body, {
+    gutters: ["note-gutter", "CodeMirror-linenumbers"],
+    lineNumbers: true
+  });
+  // Add a note to line 0
+  cm.setGutterMarker(0, "note-gutter", document.createTextNode("hi"));
+&lt;/script>
+</pre>
+
+<h2 id=events>Event handling</h2>
+
+<p>Most of the <code>onXYZ</code> options have been removed. The same
+effect is now obtained by calling
+the <a href="manual.html#on"><code>on</code></a> method with a string
+identifying the event type. Multiple handlers can now be registered
+(and individually unregistered) for an event, and objects such as line
+handlers now also expose events. See <a href="manual.html#events">the
+full list here</a>.</p>
+
+<p>(The <code>onKeyEvent</code> and <code>onDragEvent</code> options,
+which act more as hooks than as event handlers, are still there in
+their old form.)</p>
+
+<pre data-lang="javascript">
+cm.on("change", function(cm, change) {
+  console.log("something changed! (" + change.origin + ")");
+});
+</pre>
+
+<h2 id=marktext>markText method arguments</h2>
+
+<p>The <a href="manual.html#markText"><code>markText</code></a> method
+(which has gained some interesting new features, such as creating
+atomic and read-only spans, or replacing spans with widgets) no longer
+takes the CSS class name as a separate argument, but makes it an
+optional field in the options object instead.</p>
+
+<pre data-lang="javascript">
+// Style first ten lines, and forbid the cursor from entering them
+cm.markText({line: 0, ch: 0}, {line: 10, ch: 0}, {
+  className: "magic-text",
+  inclusiveLeft: true,
+  atomic: true
+});
+</pre>
+
+<h2 id=folding>Line folding</h2>
+
+<p>The interface for hiding lines has been
+removed. <a href="manual.html#markText"><code>markText</code></a> can
+now be used to do the same in a more flexible and powerful way.</p>
+
+<p>The <a href="../demo/folding.html">folding script</a> has been
+updated to use the new interface, and should now be more robust.</p>
+
+<pre data-lang="javascript">
+// Fold a range, replacing it with the text "??"
+var range = cm.markText({line: 4, ch: 2}, {line: 8, ch: 1}, {
+  replacedWith: document.createTextNode("??"),
+  // Auto-unfold when cursor moves into the range
+  clearOnEnter: true
+});
+// Get notified when auto-unfolding
+CodeMirror.on(range, "clear", function() {
+  console.log("boom");
+});
+</pre>
+
+<h2 id=lineclass>Line CSS classes</h2>
+
+<p>The <code>setLineClass</code> method has been replaced
+by <a href="manual.html#addLineClass"><code>addLineClass</code></a>
+and <a href="manual.html#removeLineClass"><code>removeLineClass</code></a>,
+which allow more modular control over the classes attached to a line.</p>
+
+<pre data-lang="javascript">
+var marked = cm.addLineClass(10, "background", "highlighted-line");
+setTimeout(function() {
+  cm.removeLineClass(marked, "background", "highlighted-line");
+});
+</pre>
+
+<h2 id=positions>Position properties</h2>
+
+<p>All methods that take or return objects that represent screen
+positions now use <code>{left, top, bottom, right}</code> properties
+(not always all of them) instead of the <code>{x, y, yBot}</code> used
+by some methods in v2.x.</p>
+
+<p>Affected methods
+are <a href="manual.html#cursorCoords"><code>cursorCoords</code></a>, <a href="manual.html#charCoords"><code>charCoords</code></a>, <a href="manual.html#coordsChar"><code>coordsChar</code></a>,
+and <a href="manual.html#getScrollInfo"><code>getScrollInfo</code></a>.</p>
+
+<h2 id=matchbrackets>Bracket matching no longer in core</h2>
+
+<p>The <a href="manual.html#addon_matchbrackets"><code>matchBrackets</code></a>
+option is no longer defined in the core editor.
+Load <code>addon/edit/matchbrackets.js</code> to enable it.</p>
+
+<h2 id=modes>Mode management</h2>
+
+<p>The <code>CodeMirror.listModes</code>
+and <code>CodeMirror.listMIMEs</code> functions, used for listing
+defined modes, are gone. You are now encouraged to simply
+inspect <code>CodeMirror.modes</code> (mapping mode names to mode
+constructors) and <code>CodeMirror.mimeModes</code> (mapping MIME
+strings to mode specs).</p>
+
+<h2 id=new>New features</h2>
+
+<p>Some more reasons to upgrade to version 3.</p>
+
+<ul>
+  <li>Bi-directional text support. CodeMirror will now mostly do the
+  right thing when editing Arabic or Hebrew text.</li>
+  <li>Arbitrary line heights. Using fonts with different heights
+  inside the editor (whether off by one pixel or fifty) is now
+  supported and handled gracefully.</li>
+  <li>In-line widgets. See <a href="../demo/widget.html">the demo</a>
+  and <a href="manual.html#addLineWidget">the docs</a>.</li>
+  <li>Defining custom options
+  with <a href="manual.html#defineOption"><code>CodeMirror.defineOption</code></a>.</li>
+</ul>
+
+</div><div class="rightsmall blk">
+
+<h2>Contents</h2>
+
+<ul>
+  <li><a href="#dom">DOM structure</a></li>
+  <li><a href="#gutters">Gutter model</a></li>
+  <li><a href="#events">Event handling</a></li>
+  <li><a href="#folding">Line folding</a></li>
+  <li><a href="#marktext">markText method arguments</a></li>
+  <li><a href="#lineclass">Line CSS classes</a></li>
+  <li><a href="#positions">Position properties</a></li>
+  <li><a href="#matchbrackets">Bracket matching</a></li>
+  <li><a href="#modes">Mode management</a></li>
+  <li><a href="#new">New features</a></li>
+</ul>
+
+</div></div>
+
+<script>setTimeout(function(){CodeMirror.colorize();}, 20);</script>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/index.html b/third-party/codemirror-3.15/index.html
new file mode 100644 (file)
index 0000000..2f2ba05
--- /dev/null
@@ -0,0 +1,480 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8"/>
+    <title>CodeMirror</title>
+    <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Droid+Sans|Droid+Sans:bold"/>
+    <link rel="stylesheet" type="text/css" href="doc/docs.css"/>
+    <link rel="alternate" href="https://groups.google.com/group/codemirror-announce/feed/atom_v1_0_topics.xml" type="application/atom+xml"/>
+  </head>
+  <body>
+
+<h1><span class="logo-braces">{ }</span> <a href="http://codemirror.net/">CodeMirror</a></h1>
+
+<div class="grey">
+<img src="doc/baboon.png" class="logo" alt="logo"/>
+<pre>
+/* In-browser code editing
+   made bearable */
+</pre>
+</div>
+
+<div class="clear"><div class="left blk">
+
+  <p style="margin-top: 0">CodeMirror is a JavaScript component that
+  provides a code editor in the browser. When a mode is available for
+  the language you are coding in, it will color your code, and
+  optionally help with indentation.</p>
+
+  <p>A <a href="doc/manual.html">rich programming API</a> and a CSS
+  theming system are available for customizing CodeMirror to fit your
+  application, and extending it with new functionality.</p>
+
+  <div class="clear"><div class="left1 blk">
+
+    <h2 style="margin-top: 0">Supported modes:</h2>
+
+    <ul>
+      <li><a href="mode/clike/index.html">C, C++, C#</a></li>
+      <li><a href="mode/clojure/index.html">Clojure</a></li>
+      <li><a href="mode/coffeescript/index.html">CoffeeScript</a></li>
+      <li><a href="mode/commonlisp/index.html">Common Lisp</a></li>
+      <li><a href="mode/css/index.html">CSS</a></li>
+      <li><a href="mode/python/index.html">Cython</a></li>
+      <li><a href="mode/d/index.html">D</a></li>
+      <li><a href="mode/diff/index.html">diff</a></li>
+      <li><a href="mode/ecl/index.html">ECL</a></li>
+      <li><a href="mode/erlang/index.html">Erlang</a></li>
+      <li><a href="mode/go/index.html">Go</a></li>
+      <li><a href="mode/groovy/index.html">Groovy</a></li>
+      <li><a href="mode/haskell/index.html">Haskell</a></li>
+      <li><a href="mode/haxe/index.html">Haxe</a></li>
+      <li><a href="mode/htmlmixed/index.html">HTML mixed-mode</a></li>
+      <li><a href="mode/http/index.html">HTTP</a></li>
+      <li><a href="mode/clike/index.html">Java</a></li>
+      <li><a href="mode/javascript/index.html">JavaScript</a></li>
+      <li><a href="mode/less/index.html">LESS</a></li>
+      <li><a href="mode/lua/index.html">Lua</a></li>
+      <li><a href="mode/markdown/index.html">Markdown</a> (<a href="mode/gfm/index.html">GitHub-flavour</a>)</li>
+      <li><a href="mode/ntriples/index.html">NTriples</a></li>
+      <li><a href="mode/ocaml/index.html">OCaml</a></li>
+      <li><a href="mode/pascal/index.html">Pascal</a></li>
+      <li><a href="mode/perl/index.html">Perl</a></li>
+      <li><a href="mode/php/index.html">PHP</a></li>
+      <li><a href="mode/properties/index.html">Properties files</a></li>
+      <li><a href="mode/python/index.html">Python</a></li>
+      <li><a href="mode/r/index.html">R</a></li>
+      <li><a href="mode/rst/index.html">reStructuredText</a></li>
+      <li><a href="mode/ruby/index.html">Ruby</a></li>
+      <li><a href="mode/rust/index.html">Rust</a></li>
+      <li><a href="mode/sass/index.html">Sass</a></li>
+      <li><a href="mode/clike/scala.html">Scala</a></li>
+      <li><a href="mode/scheme/index.html">Scheme</a></li>
+      <li><a href="mode/shell/index.html">Shell</a></li>
+      <li><a href="mode/smalltalk/index.html">Smalltalk</a></li>
+      <li><a href="mode/smarty/index.html">Smarty</a></li>
+      <li><a href="mode/sql/index.html">SQL</a> (several dialects)</li>
+      <li><a href="mode/sparql/index.html">SPARQL</a></li>
+      <li><a href="mode/stex/index.html">sTeX, LaTeX</a></li>
+      <li><a href="mode/tcl/index.html">Tcl</a></li>
+      <li><a href="mode/vb/index.html">VB.NET</a></li>
+      <li><a href="mode/vbscript/index.html">VBScript</a></li>
+      <li><a href="mode/velocity/index.html">Velocity</a></li>
+      <li><a href="mode/xml/index.html">XML/HTML</a></li>
+      <li><a href="mode/xquery/index.html">XQuery</a></li>
+      <li><a href="mode/yaml/index.html">YAML</a></li>
+      <li><a href="mode/z80/index.html">Z80</a></li>
+      <li><a href="doc/modes.html">Full list...</a></li>
+    </ul>
+
+  </div><div class="left2 blk">
+
+    <h2 style="margin-top: 0">Usage demos:</h2>
+
+    <ul>
+      <li><a href="demo/complete.html">Autocompletion</a> (<a href="demo/xmlcomplete.html">XML</a>)</li>
+      <li><a href="demo/search.html">Search/replace</a></li>
+      <li><a href="demo/folding.html">Code folding</a></li>
+      <li><a href="demo/bidi.html">Bi-directional text</a></li>
+      <li><a href="demo/widget.html">Line widgets</a> (via JSHint)</li>
+      <li><a href="demo/buffers.html">Split view</a></li>
+      <li><a href="demo/mustache.html">Mode overlays</a></li>
+      <li><a href="demo/multiplex.html">Mode multiplexer</a></li>
+      <li><a href="demo/preview.html">HTML editor with preview</a></li>
+      <li><a href="demo/resize.html">Auto-resizing editor</a></li>
+      <li><a href="demo/marker.html">Setting breakpoints</a></li>
+      <li><a href="demo/activeline.html">Highlighting the current line</a></li>
+      <li><a href="demo/matchhighlighter.html">Highlighting selection matches</a></li>
+      <li><a href="demo/theme.html">Theming</a></li>
+      <li><a href="demo/variableheight.html">Mixed font sizes</a></li>
+      <li><a href="demo/runmode.html">Stand-alone highlighting</a></li>
+      <li><a href="demo/fullscreen.html">Full-screen editing</a></li>
+      <li><a href="demo/changemode.html">Mode auto-changing</a></li>
+      <li><a href="demo/visibletabs.html">Visible tabs</a></li>
+      <li><a href="demo/emacs.html">Emacs keybindings</a></li>
+      <li><a href="demo/vim.html">Vim keybindings</a></li>
+      <li><a href="demo/closetag.html">Automatic xml tag closing</a></li>
+      <li><a href="demo/loadmode.html">Lazy mode loading</a></li>
+      <li><a href="demo/btree.html">Document tree visualization</a></li>
+    </ul>
+
+    <h2>Real-world uses:</h2>
+
+    <ul>
+      <li><a href="http://www.chris-granger.com/2012/04/12/light-table---a-new-ide-concept/">Light Table</a></li>
+      <li><a href="http://brackets.io">Adobe Brackets</a></li>
+      <li><a href="https://www.webkit.org/blog/2518/state-of-web-inspector/#source-code">WebKit Web inspector</a></li>
+      <li><a href="http://jsbin.com">jsbin.com</a></li>
+      <li><a href="http://jsfiddle.net">jsfiddle.net</a></li>
+      <li><a href="http://blog.bitbucket.org/2013/05/14/edit-your-code-in-the-cloud-with-bitbucket/">Bitbucket</a></li>
+      <li><a href="https://script.google.com/">Google Apps Script</a></li>
+      <li><a href="http://eloquentjavascript.net/chapter1.html">Eloquent JavaScript</a></li>
+      <li><a href="http://emmet.io">Emmet</a></li>
+      <li><a href="http://prose.io/">Prose.io</a></li>
+      <li><a href="https://upsource.jetbrains.com/#idea/view/923f30395f2603cd9f42a32bcafd13b6c28de0ff/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/style/ReplaceAbstractClassInstanceByMapIntention.java">Upsource</a></li>
+      <li><a href="http://paperjs.org/">Paper.js</a></li>
+      <li><a href="http://codev.it/">Codev</a></li>
+      <li><a href="http://enjalot.com/tributary/2636296/sinwaves.js">Tributary</a></li>
+      <li><a href="http://www.wescheme.org/">WeScheme</a></li>
+      <li><a href="http://www.mergely.com/">Mergely</a></li>
+      <li><a href="http://webglplayground.net/">WebGL playground</a></li>
+      <li><a href="https://thefiletree.com">The File Tree</a></li>
+      <li><a href="http://www.jshint.com/">JSHint</a></li>
+      <li><a href="http://sqlfiddle.com">SQLFiddle</a></li>
+      <li><a href="http://cssdeck.com/">CSSDeck</a></li>
+      <li><a href="http://www.sketchpatch.net/labs/livecodelabIntro.html">sketchPatch Livecodelab</a></li>
+      <li><a href="https://notex.ch">NoTex</a></li>
+      <li><a href="https://github.com/github/android">GitHub's Android app</a></li>
+      <li><a href="doc/realworld.html">More...</a></li>
+    </ul>
+
+  </div></div>
+
+  <h2 id="code">Getting the code</h2>
+
+  <p>All of CodeMirror is released under a <a
+  href="LICENSE">MIT-style</a> license. To get it, you can download
+  the <a href="http://codemirror.net/codemirror.zip">latest
+  release</a> or the current <a
+  href="http://codemirror.net/codemirror-latest.zip">development
+  snapshot</a> as zip files. To create a custom minified script file,
+  you can use the <a href="doc/compress.html">compression API</a>.</p>
+
+  <p>We use <a href="http://git-scm.com/">git</a> for version control.
+  The main repository can be fetched in this way:</p>
+
+  <pre class="code">git clone http://marijnhaverbeke.nl/git/codemirror</pre>
+
+  <p>CodeMirror can also be found on GitHub at <a
+  href="http://github.com/marijnh/CodeMirror">marijnh/CodeMirror</a>.
+  If you plan to hack on the code and contribute patches, the best way
+  to do it is to create a GitHub fork, and send pull requests.</p>
+
+  <h2 id="documention">Documentation</h2>
+
+  <p>The <a href="doc/manual.html">manual</a> is your first stop for
+  learning how to use this library. It starts with a quick explanation
+  of how to use the editor, and then describes the API in detail.</p>
+
+  <p>For those who want to learn more about the code, there is
+  a <a href="http://marijnhaverbeke.nl/blog/#cm-internals">series of
+  posts</a> on CodeMirror on my blog, and the
+  old <a href="doc/internals.html">overview of the editor
+  internals</a>.
+  The <a href="http://github.com/marijnh/CodeMirror">source code</a>
+  itself is, for the most part, also very readable.</p>
+
+  <h2 id="support">Support and bug reports</h2>
+
+  <p>Community discussion, questions, and informal bug reporting is
+  done on
+  the <a href="http://groups.google.com/group/codemirror">CodeMirror
+  Google group</a>. There is a separate
+  group, <a href="http://groups.google.com/group/codemirror-announce">CodeMirror-announce</a>,
+  which is lower-volume, and is only used for major announcements—new
+  versions and such. These will be cross-posted to both groups, so you
+  don't need to subscribe to both.</p>
+
+  <p>Though bug reports through e-mail are responded to, the preferred
+  way to report bugs is to use
+  the <a href="http://github.com/marijnh/CodeMirror/issues">GitHub
+  issue tracker</a>. Before reporting a
+  bug, <a href="doc/reporting.html">read these pointers</a>. Also,
+  the issue tracker is for <em>bugs</em>, not requests for help.</p>
+
+  <p>When none of these seem fitting, you can
+  simply <a href="mailto:marijnh@gmail.com">e-mail the maintainer</a>
+  directly.</p>
+
+  <h2 id="supported">Supported browsers</h2>
+
+  <p>The following <em>desktop</em> browsers are able to run CodeMirror:</p>
+
+  <ul>
+    <li>Firefox 3 or higher</li>
+    <li>Chrome, any version</li>
+    <li>Safari 5.2 or higher</li>
+    <li>Opera 9 or higher (with some key-handling problems on OS X)</li>
+    <li>Internet Explorer 8 or higher<br>
+    <li>Internet Explorer 7 (standards mode) is usable, but buggy. It
+    has a <a href="http://therealcrisp.xs4all.nl/meuk/IE-zindexbug.html">z-index
+    bug</a> that prevents CodeMirror from working properly.</li>
+  </ul>
+
+  <p>Note that CodeMirror is only supported in
+  <strong>standards</strong> mode. So not quirks mode,
+  but <em>also</em> not the quasi-standards mode that IE gives you
+  when you specify a transitional doctype. Simply using the
+  HTML5-style <code>&lt;!doctype html></code> is recommended.</li>
+
+  <p>Mobile browsers mostly kind of work, but, because of limitations
+  and their fundamentally different UI assumptions, show a lot of
+  quirks that are hard to work around.</p>
+
+  <h2 id="commercial">Commercial support</h2>
+
+  <p>CodeMirror is developed and maintained by me, Marijn Haverbeke,
+  in my own time. If your company is getting value out of CodeMirror,
+  please consider purchasing a support contract.</p>
+
+  <ul>
+    <li>You'll be funding further work on CodeMirror.</li>
+    <li>You ensure that you get a quick response when you have a
+    problem, even when I am otherwise busy.</li>
+  </ul>
+
+  <p>CodeMirror support contracts exist in two
+  forms—<strong>basic</strong> at €100 per month,
+  and <strong>premium</strong> at €500 per
+  month. <a href="mailto:marijnh@gmail.com">Contact me</a> for further
+  information.</p>
+
+</div>
+
+<div class="right blk">
+
+  <a href="http://codemirror.net/codemirror.zip" class="download">Download the latest release</a>
+
+  <h2>Support CodeMirror</h2>
+
+  <ul>
+    <li>Donate
+    (<span onclick="document.getElementById('paypal').submit();"
+    class="quasilink">Paypal</span>,
+    <span onclick="document.getElementById('bankinfo').style.display = 'block';"
+           class="quasilink">bank</span>,
+    <a href="https://www.gittip.com/marijnh">Gittip</a>, or
+    <a href="https://flattr.com/profile/marijnh">Flattr</a>)</li>
+    <li>Purchase <a href="#commercial">commercial support</a></li>
+  </ul>
+
+  <p id="bankinfo" style="display: none;">
+    Bank: <i>Rabobank</i><br/>
+    Country: <i>Netherlands</i><br/>
+    SWIFT: <i>RABONL2U</i><br/>
+    Account: <i>147850770</i><br/>
+    Name: <i>Marijn Haverbeke</i><br/>
+    IBAN: <i>NL26 RABO 0147 8507 70</i>
+  </p>
+
+  <h2>Reading material</h2>
+
+  <ul>
+    <li><a href="doc/manual.html">User manual</a></li>
+    <li><a href="http://github.com/marijnh/CodeMirror">Browse the code</a></li>
+  </ul>
+
+  <h2 id=releases>Releases</h2>
+
+  <p class="rel">29-07-2013: <a href="http://codemirror.net/codemirror-3.15.zip">Version 3.15</a>:</p>
+
+  <ul class="rel-note">
+    <li>New modes: <a href="mode/jade/index.html">Jade</a>, <a href="mode/nginx/index.html">Nginx</a>.</li>
+    <li>New addons: <a href="demo/tern.html">Tern</a>, <a href="doc/manual.html#addon_matchtags">matchtags</a>, and <a href="doc/manual.html#addon_foldgutter">foldgutter</a>.</li>
+    <li>Introduced <a href="doc/manual.html#getHelper"><em>helper</em></a> concept (<a href="https://groups.google.com/forum/#!msg/codemirror/cOc0xvUUEUU/nLrX1-qnidgJ">context</a>).</li>
+    <li>New method: <a href="doc/manual.html#getModeAt"><code>getModeAt</code></a>.</li>
+    <li>New themes: base16 <a href="demo/theme.html?base16-dark">dark</a>/<a href="demo/theme.html?base16-light">light</a>, 3024 <a href="demo/theme.html?3024-night">dark</a>/<a href="demo/theme.html?3024-day">light</a>, <a href="demo/theme.html?tomorrow-night-eighties">tomorrow-night</a>.</li>
+    <li>Full <a href="https://github.com/marijnh/CodeMirror/compare/3.14.0...3.15.0">list of patches</a>.</li>
+  </ul>
+
+  <p class="rel">20-06-2013: <a href="http://codemirror.net/codemirror-3.14.zip">Version 3.14</a>:</p>
+
+  <ul class="rel-note">
+    <li>New
+    addons: <a href="doc/manual.html#addon_trailingspace">trailing
+    space highlight</a>, <a href="doc/manual.html#addon_xml-hint">XML
+    completion</a> (rewritten),
+    and <a href="doc/manual.html#addon_merge">diff merging</a>.</li>
+    <li><a href="doc/manual.html#markText"><code>markText</code></a>
+    and <a href="doc/manual.html#addLineWidget"><code>addLineWidget</code></a>
+    now take a <code>handleMouseEvents</code> option.</li>
+    <li>New methods: <a href="doc/manual.html#lineAtHeight"><code>lineAtHeight</code></a>,
+    <a href="doc/manual.html#getTokenTypeAt"><code>getTokenTypeAt</code></a>.</li>
+    <li>More precise cleanness-tracking
+    using <a href="doc/manual.html#changeGeneration"><code>changeGeneration</code></a>
+    and <a href="doc/manual.html#isClean"><code>isClean</code></a>.</li>
+    <li>Many extensions to <a href="demo/emacs.html">Emacs</a> mode
+    (prefixes, more navigation units, and more).</li>
+    <li>New
+    events <a href="doc/manual.html#event_keyHandled"><code>"keyHandled"</code></a>
+    and <a href="doc/manual.html#event_inputRead"><code>"inputRead"</code></a>.</li>
+    <li>Various improvements to <a href="mode/ruby/index.html">Ruby</a>,
+    <a href="mode/smarty/index.html">Smarty</a>, <a href="mode/sql/index.html">SQL</a>,
+    and <a href="demo/vim.html">Vim</a> modes.</li>
+    <li>Full <a href="https://github.com/marijnh/CodeMirror/compare/3.13.0...3.14.0">list of patches</a>.</li>
+  </ul>
+
+  <p class="rel">20-05-2013: <a href="http://codemirror.net/codemirror-3.13.zip">Version 3.13</a>:</p>
+
+  <ul class="rel-note">
+    <li>New modes: <a href="mode/cobol/index.html">COBOL</a> and <a href="mode/haml/index.html">HAML</a>.</li>
+    <li>New options: <a href="doc/manual.html#option_cursorScrollMargin"><code>cursorScrollMargin</code></a> and <a href="doc/manual.html#option_coverGutterNextToScrollbar"><code>coverGutterNextToScrollbar</code></a>.</li>
+    <li>New addon: <a href="doc/manual.html#addon_comment">commenting</a>.</li>
+    <li>More features added to the <a href="demo/vim.html">Vim keymap</a>.</li>
+    <li>Full <a href="https://github.com/marijnh/CodeMirror/compare/v3.12...3.13.0">list of patches</a>.</li>
+  </ul>
+
+  <p class="rel">19-04-2013: <a href="http://codemirror.net/codemirror-3.12.zip">Version 3.12</a>:</p>
+
+  <ul class="rel-note">
+    <li>New mode: <a href="mode/gas/index.html">GNU assembler</a>.</li>
+    <li>New
+    options: <a href="doc/manual.html#option_maxHighlightLength"><code>maxHighlightLength</code></a>
+    and <a href="doc/manual.html#option_historyEventDelay"><code>historyEventDelay</code></a>.</li>
+    <li>Added <a href="doc/manual.html#mark_addToHistory"><code>addToHistory</code></a>
+    option for <code>markText</code>.</li>
+    <li>Various fixes to JavaScript tokenization and indentation corner cases.</li>
+    <li>Further improvements to the vim mode.</li>
+    <li>Full <a href="https://github.com/marijnh/CodeMirror/compare/v3.11...v3.12">list of patches</a>.</li>
+  </ul>
+
+  <p class="rel">20-03-2013: <a href="http://codemirror.net/codemirror-3.11.zip">Version 3.11</a>:</p>
+
+  <ul class="rel-note">
+    <li><strong>Removed code:</strong> <code>collapserange</code>,
+    <code>formatting</code>, and <code>simple-hint</code>
+    addons. <code>plsql</code> and <code>mysql</code> modes
+    (use <a href="mode/sql/index.html"><code>sql</code></a> mode).</li>
+    <li><strong>Moved code:</strong> the range-finding functions for folding now have <a href="addon/fold/">their own files</a>.</li>
+    <li><strong>Changed interface:</strong>
+    the <a href="doc/manual.html#addon_continuecomment"><code>continuecomment</code></a>
+    addon now exposes an option, rather than a command.</li>
+    <li>New
+    modes: <a href="mode/css/scss.html">SCSS</a>, <a href="mode/tcl/index.html">Tcl</a>, <a href="mode/livescript/index.html">LiveScript</a>,
+    and <a href="mode/mirc/index.html">mIRC</a>.</li>
+    <li>New addons: <a href="demo/placeholder.html"><code>placeholder</code></a>, <a href="demo/html5complete.html">HTML completion</a>.</li>
+    <li>New
+    methods: <a href="doc/manual.html#hasFocus"><code>hasFocus</code></a>, <a href="doc/manual.html#defaultCharWidth"><code>defaultCharWidth</code></a>.</li>
+    <li>New events: <a href="doc/manual.html#event_beforeCursorEnter"><code>beforeCursorEnter</code></a>, <a href="doc/manual.html#event_renderLine"><code>renderLine</code></a>.</li>
+    <li>Many improvements to the <a href="doc/manual.html#addon_show-hint"><code>show-hint</code></a> completion
+    dialog addon.</li>
+    <li>Tweak behavior of by-word cursor motion.</li>
+    <li>Further improvements to the <a href="demo/vim.html">vim mode</a>.</li>
+    <li>Full <a href="https://github.com/marijnh/CodeMirror/compare/v3.1...v3.11">list of patches</a>.</li>
+  </ul>
+
+  <p class="rel">21-02-2013: <a href="http://codemirror.net/codemirror-3.1.zip">Version 3.1</a>:</p>
+
+  <ul class="rel-note">
+    <li><strong>Incompatible:</strong> key handlers may
+    now <em>return</em>, rather
+    than <em>throw</em> <code>CodeMirror.Pass</code> to signal they
+    didn't handle the key.</li>
+    <li>Make documents a <a href="doc/manual.html#api_doc">first-class
+    construct</a>, support split views and subviews.</li>
+    <li>Add a <a href="doc/manual.html#addon_show-hint">new module</a>
+    for showing completion hints.
+    Deprecate <code>simple-hint.js</code>.</li>
+    <li>Extend <a href="mode/htmlmixed/index.html">htmlmixed mode</a>
+    to allow custom handling of script types.</li>
+    <li>Support an <code>insertLeft</code> option
+    to <a href="doc/manual.html#setBookmark"><code>setBookmark</code></a>.</li>
+    <li>Add an <a href="doc/manual.html#eachLine"><code>eachLine</code></a>
+    method to iterate over a document.</li>
+    <li>New addon modules: <a href="demo/markselection.html">selection
+    marking</a>, <a href="demo/lint.html">linting</a>,
+    and <a href="demo/closebrackets.html">automatic bracket
+    closing</a>.</li>
+    <li>Add <a href="doc/manual.html#event_beforeChange"><code>"beforeChange"</code></a>
+    and <a href="doc/manual.html#event_beforeSelectionChange"><code>"beforeSelectionChange"</code></a>
+    events.</li>
+    <li>Add <a href="doc/manual.html#event_hide"><code>"hide"</code></a>
+    and <a href="doc/manual.html#event_unhide"><code>"unhide"</code></a>
+    events to marked ranges.</li>
+    <li>Fix <a href="doc/manual.html#coordsChar"><code>coordsChar</code></a>'s
+    interpretation of its argument to match the documentation.</li>
+    <li>New modes: <a href="mode/turtle/index.html">Turtle</a>
+    and <a href="mode/q/index.html">Q</a>.</li>
+    <li>Further improvements to the <a href="demo/vim.html">vim mode</a>.</li>
+    <li>Full <a href="https://github.com/marijnh/CodeMirror/compare/v3.01...v3.1">list of patches</a>.</li>
+  </ul>
+  
+
+  <p class="rel">25-01-2013: <a href="http://codemirror.net/codemirror-3.02.zip">Version 3.02</a>:</p>
+
+  <p class="rel-note">Single-bugfix release. Fixes a problem that
+  prevents CodeMirror instances from being garbage-collected after
+  they become unused.</p>
+
+  <p class="rel">21-01-2013: <a href="http://codemirror.net/codemirror-3.01.zip">Version 3.01</a>:</p>
+
+  <ul class="rel-note">
+    <li>Move all add-ons into an organized directory structure
+    under <a href="addon/"><code>/addon</code></a>. <strong>You might have to adjust your
+    paths.</strong></li>
+    <li>New
+    modes: <a href="mode/d/index.html">D</a>, <a href="mode/sass/index.html">Sass</a>, <a href="mode/apl/index.html">APL</a>, <a href="mode/sql/index.html">SQL</a>
+    (configurable), and <a href="mode/asterisk/index.html">Asterisk</a>.</li>
+    <li>Several bugfixes in right-to-left text support.</li>
+    <li>Add <a href="doc/manual.html#option_rtlMoveVisually"><code>rtlMoveVisually</code></a> option.</li>
+    <li>Improvements to vim keymap.</li>
+    <li>Add built-in (lightweight) <a href="doc/manual.html#addOverlay">overlay mode</a> support.</li>
+    <li>Support <code>showIfHidden</code> option for <a href="doc/manual.html#addLineWidget">line widgets</a>.</li>
+    <li>Add simple <a href="doc/manual.html#addon_python-hint">Python hinter</a>.</li>
+    <li>Bring back the <a href="doc/manual.html#option_fixedGutter"><code>fixedGutter</code></a> option.</li>
+    <li>Full <a href="https://github.com/marijnh/CodeMirror/compare/v3.0...v3.01">list of patches</a>.</li>
+  </ul>
+
+  <p class="rel">21-01-2013: <a href="http://codemirror.net/codemirror-2.38.zip">Version 2.38</a>:</p>
+
+  <p class="rel-note">Integrate some bugfixes, enhancements to the vim keymap, and new
+  modes
+  (<a href="mode/d/index.html">D</a>, <a href="mode/sass/index.html">Sass</a>, <a href="mode/apl/index.html">APL</a>)
+  from the v3 branch.</p>
+
+  <p class="rel">20-12-2012: <a href="http://codemirror.net/codemirror-2.37.zip">Version 2.37</a>:</p>
+
+  <ul class="rel-note">
+    <li>New mode: <a href="mode/sql/index.html">SQL</a> (will replace <a href="mode/plsql/index.html">plsql</a> and <a href="mode/mysql/index.html">mysql</a> modes).</li>
+    <li>Further work on the new VIM mode.</li>
+    <li>Fix Cmd/Ctrl keys on recent Operas on OS X.</li>
+    <li>Full <a href="https://github.com/marijnh/CodeMirror/compare/v2.36...v2.37">list of patches</a>.</li>
+  </ul>
+
+  <p class="rel">10-12-2012: <a href="http://codemirror.net/codemirror-3.0.zip">Version 3.0</a>:</p>
+
+  <p class="rel-note"><strong>New major version</strong>. Only
+  partially backwards-compatible. See
+  the <a href="doc/upgrade_v3.html">upgrading guide</a> for more
+  information. Changes since release candidate 2:</p>
+
+  <ul class="rel-note">
+    <li>Rewritten VIM mode.</li>
+    <li>Fix a few minor scrolling and sizing issues.</li>
+    <li>Work around Safari segfault when dragging.</li>
+    <li>Full <a href="https://github.com/marijnh/CodeMirror/compare/v3.0rc2...v3.0">list of patches</a>.</li>
+  </ul>
+  
+  <p><a href="doc/oldrelease.html">Older releases...</a></p>
+
+</div></div>
+
+<div style="height: 2em">&nbsp;</div>
+
+  <form action="https://www.paypal.com/cgi-bin/webscr" method="post" id="paypal">
+    <input type="hidden" name="cmd" value="_s-xclick"/>
+    <input type="hidden" name="hosted_button_id" value="3FVHS5FGUY7CC"/>
+  </form>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/keymap/emacs.js b/third-party/codemirror-3.15/keymap/emacs.js
new file mode 100644 (file)
index 0000000..8727121
--- /dev/null
@@ -0,0 +1,387 @@
+(function() {
+  "use strict";
+
+  var Pos = CodeMirror.Pos;
+  function posEq(a, b) { return a.line == b.line && a.ch == b.ch; }
+
+  // Kill 'ring'
+
+  var killRing = [];
+  function addToRing(str) {
+    killRing.push(str);
+    if (killRing.length > 50) killRing.shift();
+  }
+  function growRingTop(str) {
+    if (!killRing.length) return addToRing(str);
+    killRing[killRing.length - 1] += str;
+  }
+  function getFromRing(n) { return killRing[killRing.length - (n ? Math.min(n, 1) : 1)] || ""; }
+  function popFromRing() { if (killRing.length > 1) killRing.pop(); return getFromRing(); }
+
+  var lastKill = null;
+
+  function kill(cm, from, to, mayGrow, text) {
+    if (text == null) text = cm.getRange(from, to);
+
+    if (mayGrow && lastKill && lastKill.cm == cm && posEq(from, lastKill.pos) && cm.isClean(lastKill.gen))
+      growRingTop(text);
+    else
+      addToRing(text);
+    cm.replaceRange("", from, to, "+delete");
+
+    if (mayGrow) lastKill = {cm: cm, pos: from, gen: cm.changeGeneration()};
+    else lastKill = null;
+  }
+
+  // Boundaries of various units
+
+  function byChar(cm, pos, dir) {
+    return cm.findPosH(pos, dir, "char", true);
+  }
+
+  function byWord(cm, pos, dir) {
+    return cm.findPosH(pos, dir, "word", true);
+  }
+
+  function byLine(cm, pos, dir) {
+    return cm.findPosV(pos, dir, "line", cm.doc.sel.goalColumn);
+  }
+
+  function byPage(cm, pos, dir) {
+    return cm.findPosV(pos, dir, "page", cm.doc.sel.goalColumn);
+  }
+
+  function byParagraph(cm, pos, dir) {
+    var no = pos.line, line = cm.getLine(no);
+    var sawText = /\S/.test(dir < 0 ? line.slice(0, pos.ch) : line.slice(pos.ch));
+    var fst = cm.firstLine(), lst = cm.lastLine();
+    for (;;) {
+      no += dir;
+      if (no < fst || no > lst)
+        return cm.clipPos(Pos(no - dir, dir < 0 ? 0 : null));
+      line = cm.getLine(no);
+      var hasText = /\S/.test(line);
+      if (hasText) sawText = true;
+      else if (sawText) return Pos(no, 0);
+    }
+  }
+
+  function bySentence(cm, pos, dir) {
+    var line = pos.line, ch = pos.ch;
+    var text = cm.getLine(pos.line), sawWord = false;
+    for (;;) {
+      var next = text.charAt(ch + (dir < 0 ? -1 : 0));
+      if (!next) { // End/beginning of line reached
+        if (line == (dir < 0 ? cm.firstLine() : cm.lastLine())) return Pos(line, ch);
+        text = cm.getLine(line + dir);
+        if (!/\S/.test(text)) return Pos(line, ch);
+        line += dir;
+        ch = dir < 0 ? text.length : 0;
+        continue;
+      }
+      if (sawWord && /[!?.]/.test(next)) return Pos(line, ch + (dir > 0 ? 1 : 0));
+      if (!sawWord) sawWord = /\w/.test(next);
+      ch += dir;
+    }
+  }
+
+  function byExpr(cm, pos, dir) {
+    var wrap;
+    if (cm.findMatchingBracket && (wrap = cm.findMatchingBracket(pos, true))
+        && wrap.match && (wrap.forward ? 1 : -1) == dir)
+      return dir > 0 ? Pos(wrap.to.line, wrap.to.ch + 1) : wrap.to;
+
+    for (var first = true;; first = false) {
+      var token = cm.getTokenAt(pos);
+      var after = Pos(pos.line, dir < 0 ? token.start : token.end);
+      if (first && dir > 0 && token.end == pos.ch || !/\w/.test(token.string)) {
+        var newPos = cm.findPosH(after, dir, "char");
+        if (posEq(after, newPos)) return pos;
+        else pos = newPos;
+      } else {
+        return after;
+      }
+    }
+  }
+
+  // Prefixes (only crudely supported)
+
+  function getPrefix(cm, precise) {
+    var digits = cm.state.emacsPrefix;
+    if (!digits) return precise ? null : 1;
+    clearPrefix(cm);
+    return digits == "-" ? -1 : Number(digits);
+  }
+
+  function repeated(cmd) {
+    var f = typeof cmd == "string" ? function(cm) { cm.execCommand(cmd); } : cmd;
+    return function(cm) {
+      var prefix = getPrefix(cm);
+      f(cm);
+      for (var i = 1; i < prefix; ++i) f(cm);
+    };
+  }
+
+  function findEnd(cm, by, dir) {
+    var pos = cm.getCursor(), prefix = getPrefix(cm);
+    if (prefix < 0) { dir = -dir; prefix = -prefix; }
+    for (var i = 0; i < prefix; ++i) {
+      var newPos = by(cm, pos, dir);
+      if (posEq(newPos, pos)) break;
+      pos = newPos;
+    }
+    return pos;
+  }
+
+  function move(by, dir) {
+    var f = function(cm) {
+      cm.extendSelection(findEnd(cm, by, dir));
+    };
+    f.motion = true;
+    return f;
+  }
+
+  function killTo(cm, by, dir) {
+    kill(cm, cm.getCursor(), findEnd(cm, by, dir), true);
+  }
+
+  function addPrefix(cm, digit) {
+    if (cm.state.emacsPrefix) {
+      if (digit != "-") cm.state.emacsPrefix += digit;
+      return;
+    }
+    // Not active yet
+    cm.state.emacsPrefix = digit;
+    cm.on("keyHandled", maybeClearPrefix);
+    cm.on("inputRead", maybeDuplicateInput);
+  }
+
+  var prefixPreservingKeys = {"Alt-G": true, "Ctrl-X": true, "Ctrl-Q": true, "Ctrl-U": true};
+
+  function maybeClearPrefix(cm, arg) {
+    if (!cm.state.emacsPrefixMap && !prefixPreservingKeys.hasOwnProperty(arg))
+      clearPrefix(cm);
+  }
+
+  function clearPrefix(cm) {
+    cm.state.emacsPrefix = null;
+    cm.off("keyHandled", maybeClearPrefix);
+    cm.off("inputRead", maybeDuplicateInput);
+  }
+
+  function maybeDuplicateInput(cm, event) {
+    var dup = getPrefix(cm);
+    if (dup > 1 && event.origin == "+input") {
+      var one = event.text.join("\n"), txt = "";
+      for (var i = 1; i < dup; ++i) txt += one;
+      cm.replaceSelection(txt, "end", "+input");
+    }
+  }
+
+  function addPrefixMap(cm) {
+    cm.state.emacsPrefixMap = true;
+    cm.addKeyMap(prefixMap);
+    cm.on("keyHandled", maybeRemovePrefixMap);
+    cm.on("inputRead", maybeRemovePrefixMap);
+  }
+
+  function maybeRemovePrefixMap(cm, arg) {
+    if (typeof arg == "string" && (/^\d$/.test(arg) || arg == "Ctrl-U")) return;
+    cm.removeKeyMap(prefixMap);
+    cm.state.emacsPrefixMap = false;
+    cm.off("keyHandled", maybeRemovePrefixMap);
+    cm.off("inputRead", maybeRemovePrefixMap);
+  }
+
+  // Utilities
+
+  function setMark(cm) {
+    cm.setCursor(cm.getCursor());
+    cm.setExtending(true);
+    cm.on("change", function() { cm.setExtending(false); });
+  }
+
+  function getInput(cm, msg, f) {
+    if (cm.openDialog)
+      cm.openDialog(msg + ": <input type=\"text\" style=\"width: 10em\"/>", f, {bottom: true});
+    else
+      f(prompt(msg, ""));
+  }
+
+  function operateOnWord(cm, op) {
+    var start = cm.getCursor(), end = cm.findPosH(start, 1, "word");
+    cm.replaceRange(op(cm.getRange(start, end)), start, end);
+    cm.setCursor(end);
+  }
+
+  function toEnclosingExpr(cm) {
+    var pos = cm.getCursor(), line = pos.line, ch = pos.ch;
+    var stack = [];
+    while (line >= cm.firstLine()) {
+      var text = cm.getLine(line);
+      for (var i = ch == null ? text.length : ch; i > 0;) {
+        var ch = text.charAt(--i);
+        if (ch == ")")
+          stack.push("(");
+        else if (ch == "]")
+          stack.push("[");
+        else if (ch == "}")
+          stack.push("{");
+        else if (/[\(\{\[]/.test(ch) && (!stack.length || stack.pop() != ch))
+          return cm.extendSelection(Pos(line, i));
+      }
+      --line; ch = null;
+    }
+  }
+
+  // Actual keymap
+
+  var keyMap = CodeMirror.keyMap.emacs = {
+    "Ctrl-W": function(cm) {kill(cm, cm.getCursor("start"), cm.getCursor("end"));},
+    "Ctrl-K": repeated(function(cm) {
+      var start = cm.getCursor(), end = cm.clipPos(Pos(start.line));
+      var text = cm.getRange(start, end);
+      if (!/\S/.test(text)) {
+        text += "\n";
+        end = Pos(start.line + 1, 0);
+      }
+      kill(cm, start, end, true, text);
+    }),
+    "Alt-W": function(cm) {
+      addToRing(cm.getSelection());
+    },
+    "Ctrl-Y": function(cm) {
+      var start = cm.getCursor();
+      cm.replaceRange(getFromRing(getPrefix(cm)), start, start, "paste");
+      cm.setSelection(start, cm.getCursor());
+    },
+    "Alt-Y": function(cm) {cm.replaceSelection(popFromRing());},
+
+    "Ctrl-Space": setMark, "Ctrl-Shift-2": setMark,
+
+    "Ctrl-F": move(byChar, 1), "Ctrl-B": move(byChar, -1),
+    "Right": move(byChar, 1), "Left": move(byChar, -1),
+    "Ctrl-D": function(cm) { killTo(cm, byChar, 1); },
+    "Delete": function(cm) { killTo(cm, byChar, 1); },
+    "Ctrl-H": function(cm) { killTo(cm, byChar, -1); },
+    "Backspace": function(cm) { killTo(cm, byChar, -1); },
+
+    "Alt-F": move(byWord, 1), "Alt-B": move(byWord, -1),
+    "Alt-D": function(cm) { killTo(cm, byWord, 1); },
+    "Alt-Backspace": function(cm) { killTo(cm, byWord, -1); },
+
+    "Ctrl-N": move(byLine, 1), "Ctrl-P": move(byLine, -1),
+    "Down": move(byLine, 1), "Up": move(byLine, -1),
+    "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
+    "End": "goLineEnd", "Home": "goLineStart",
+
+    "Alt-V": move(byPage, -1), "Ctrl-V": move(byPage, 1),
+    "PageUp": move(byPage, -1), "PageDown": move(byPage, 1),
+
+    "Ctrl-Up": move(byParagraph, -1), "Ctrl-Down": move(byParagraph, 1),
+
+    "Alt-A": move(bySentence, -1), "Alt-E": move(bySentence, 1),
+    "Alt-K": function(cm) { killTo(cm, bySentence, 1); },
+
+    "Ctrl-Alt-K": function(cm) { killTo(cm, byExpr, 1); },
+    "Ctrl-Alt-Backspace": function(cm) { killTo(cm, byExpr, -1); },
+    "Ctrl-Alt-F": move(byExpr, 1), "Ctrl-Alt-B": move(byExpr, -1),
+
+    "Shift-Ctrl-Alt-2": function(cm) {
+      cm.setSelection(findEnd(cm, byExpr, 1), cm.getCursor());
+    },
+    "Ctrl-Alt-T": function(cm) {
+      var leftStart = byExpr(cm, cm.getCursor(), -1), leftEnd = byExpr(cm, leftStart, 1);
+      var rightEnd = byExpr(cm, leftEnd, 1), rightStart = byExpr(cm, rightEnd, -1);
+      cm.replaceRange(cm.getRange(rightStart, rightEnd) + cm.getRange(leftEnd, rightStart) +
+                      cm.getRange(leftStart, leftEnd), leftStart, rightEnd);
+    },
+    "Ctrl-Alt-U": repeated(toEnclosingExpr),
+
+    "Alt-Space": function(cm) {
+      var pos = cm.getCursor(), from = pos.ch, to = pos.ch, text = cm.getLine(pos.line);
+      while (from && /\s/.test(text.charAt(from - 1))) --from;
+      while (to < text.length && /\s/.test(text.charAt(to))) ++to;
+      cm.replaceRange(" ", Pos(pos.line, from), Pos(pos.line, to));
+    },
+    "Ctrl-O": repeated(function(cm) { cm.replaceSelection("\n", "start"); }),
+    "Ctrl-T": repeated(function(cm) {
+      var pos = cm.getCursor();
+      if (pos.ch < cm.getLine(pos.line).length) pos = Pos(pos.line, pos.ch + 1);
+      var from = cm.findPosH(pos, -2, "char");
+      var range = cm.getRange(from, pos);
+      if (range.length != 2) return;
+      cm.setSelection(from, pos);
+      cm.replaceSelection(range.charAt(1) + range.charAt(0), "end");
+    }),
+
+    "Alt-C": repeated(function(cm) {
+      operateOnWord(cm, function(w) {
+        var letter = w.search(/\w/);
+        if (letter == -1) return w;
+        return w.slice(0, letter) + w.charAt(letter).toUpperCase() + w.slice(letter + 1).toLowerCase();
+      });
+    }),
+    "Alt-U": repeated(function(cm) {
+      operateOnWord(cm, function(w) { return w.toUpperCase(); });
+    }),
+    "Alt-L": repeated(function(cm) {
+      operateOnWord(cm, function(w) { return w.toLowerCase(); });
+    }),
+
+    "Alt-;": "toggleComment",
+
+    "Ctrl-/": repeated("undo"), "Shift-Ctrl--": repeated("undo"),
+    "Ctrl-Z": repeated("undo"), "Cmd-Z": repeated("undo"),
+    "Shift-Alt-,": "goDocStart", "Shift-Alt-.": "goDocEnd",
+    "Ctrl-S": "findNext", "Ctrl-R": "findPrev", "Ctrl-G": "clearSearch", "Shift-Alt-5": "replace",
+    "Alt-/": "autocomplete",
+    "Ctrl-J": "newlineAndIndent", "Enter": false, "Tab": "indentAuto",
+
+    "Alt-G": function(cm) {cm.setOption("keyMap", "emacs-Alt-G");},
+    "Ctrl-X": function(cm) {cm.setOption("keyMap", "emacs-Ctrl-X");},
+    "Ctrl-Q": function(cm) {cm.setOption("keyMap", "emacs-Ctrl-Q");},
+    "Ctrl-U": addPrefixMap
+  };
+
+  CodeMirror.keyMap["emacs-Ctrl-X"] = {
+    "Tab": function(cm) {
+      cm.indentSelection(getPrefix(cm, true) || cm.getOption("indentUnit"));
+    },
+    "Ctrl-X": function(cm) {
+      cm.setSelection(cm.getCursor("head"), cm.getCursor("anchor"));
+    },
+
+    "Ctrl-S": "save", "Ctrl-W": "save", "S": "saveAll", "F": "open", "U": repeated("undo"), "K": "close",
+    "Delete": function(cm) { kill(cm, cm.getCursor(), sentenceEnd(cm, 1), true); },
+    auto: "emacs", nofallthrough: true, disableInput: true
+  };
+
+  CodeMirror.keyMap["emacs-Alt-G"] = {
+    "G": function(cm) {
+      var prefix = getPrefix(cm, true);
+      if (prefix != null && prefix > 0) return cm.setCursor(prefix - 1);
+
+      getInput(cm, "Goto line", function(str) {
+        var num;
+        if (str && !isNaN(num = Number(str)) && num == num|0 && num > 0)
+          cm.setCursor(num - 1);
+      });
+    },
+    auto: "emacs", nofallthrough: true, disableInput: true
+  };
+
+  CodeMirror.keyMap["emacs-Ctrl-Q"] = {
+    "Tab": repeated("insertTab"),
+    auto: "emacs", nofallthrough: true
+  };
+
+  var prefixMap = {"Ctrl-G": clearPrefix};
+  function regPrefix(d) {
+    prefixMap[d] = function(cm) { addPrefix(cm, d); };
+    keyMap["Ctrl-" + d] = function(cm) { addPrefix(cm, d); };
+    prefixPreservingKeys["Ctrl-" + d] = true;
+  }
+  for (var i = 0; i < 10; ++i) regPrefix(String(i));
+  regPrefix("-");
+})();
diff --git a/third-party/codemirror-3.15/keymap/extra.js b/third-party/codemirror-3.15/keymap/extra.js
new file mode 100644 (file)
index 0000000..18dd5a9
--- /dev/null
@@ -0,0 +1,43 @@
+// A number of additional default bindings that are too obscure to
+// include in the core codemirror.js file.
+
+(function() {
+  "use strict";
+
+  var Pos = CodeMirror.Pos;
+
+  function moveLines(cm, start, end, dist) {
+    if (!dist || start > end) return 0;
+
+    var from = cm.clipPos(Pos(start, 0)), to = cm.clipPos(Pos(end));
+    var text = cm.getRange(from, to);
+
+    if (start <= cm.firstLine())
+      cm.replaceRange("", from, Pos(to.line + 1, 0));
+    else
+      cm.replaceRange("", Pos(from.line - 1), to);
+    var target = from.line + dist;
+    if (target <= cm.firstLine()) {
+      cm.replaceRange(text + "\n", Pos(target, 0));
+      return cm.firstLine() - from.line;
+    } else {
+      var targetPos = cm.clipPos(Pos(target - 1));
+      cm.replaceRange("\n" + text, targetPos);
+      return targetPos.line + 1 - from.line;
+    }
+  }
+
+  function moveSelectedLines(cm, dist) {
+    var head = cm.getCursor("head"), anchor = cm.getCursor("anchor");
+    cm.operation(function() {
+      var moved = moveLines(cm, Math.min(head.line, anchor.line), Math.max(head.line, anchor.line), dist);
+      cm.setSelection(Pos(anchor.line + moved, anchor.ch), Pos(head.line + moved, head.ch));
+    });
+  }
+
+  CodeMirror.commands.moveLinesUp = function(cm) { moveSelectedLines(cm, -1); };
+  CodeMirror.commands.moveLinesDown = function(cm) { moveSelectedLines(cm, 1); };
+
+  CodeMirror.keyMap["default"]["Alt-Up"] = "moveLinesUp";
+  CodeMirror.keyMap["default"]["Alt-Down"] = "moveLinesDown";
+})();
diff --git a/third-party/codemirror-3.15/keymap/vim.js b/third-party/codemirror-3.15/keymap/vim.js
new file mode 100644 (file)
index 0000000..8db2767
--- /dev/null
@@ -0,0 +1,3648 @@
+/**
+ * Supported keybindings:
+ *
+ *   Motion:
+ *   h, j, k, l
+ *   gj, gk
+ *   e, E, w, W, b, B, ge, gE
+ *   f<character>, F<character>, t<character>, T<character>
+ *   $, ^, 0, -, +, _
+ *   gg, G
+ *   %
+ *   '<character>, `<character>
+ *
+ *   Operator:
+ *   d, y, c
+ *   dd, yy, cc
+ *   g~, g~g~
+ *   >, <, >>, <<
+ *
+ *   Operator-Motion:
+ *   x, X, D, Y, C, ~
+ *
+ *   Action:
+ *   a, i, s, A, I, S, o, O
+ *   zz, z., z<CR>, zt, zb, z-
+ *   J
+ *   u, Ctrl-r
+ *   m<character>
+ *   r<character>
+ *
+ *   Modes:
+ *   ESC - leave insert mode, visual mode, and clear input state.
+ *   Ctrl-[, Ctrl-c - same as ESC.
+ *
+ * Registers: unamed, -, a-z, A-Z, 0-9
+ *   (Does not respect the special case for number registers when delete
+ *    operator is made with these commands: %, (, ),  , /, ?, n, N, {, } )
+ *   TODO: Implement the remaining registers.
+ * Marks: a-z, A-Z, and 0-9
+ *   TODO: Implement the remaining special marks. They have more complex
+ *       behavior.
+ *
+ * Code structure:
+ *  1. Default keymap
+ *  2. Variable declarations and short basic helpers
+ *  3. Instance (External API) implementation
+ *  4. Internal state tracking objects (input state, counter) implementation
+ *     and instanstiation
+ *  5. Key handler (the main command dispatcher) implementation
+ *  6. Motion, operator, and action implementations
+ *  7. Helper functions for the key handler, motions, operators, and actions
+ *  8. Set up Vim to work as a keymap for CodeMirror.
+ */
+
+(function() {
+  'use strict';
+
+  var defaultKeymap = [
+    // Key to key mapping. This goes first to make it possible to override
+    // existing mappings.
+    { keys: ['<Left>'], type: 'keyToKey', toKeys: ['h'] },
+    { keys: ['<Right>'], type: 'keyToKey', toKeys: ['l'] },
+    { keys: ['<Up>'], type: 'keyToKey', toKeys: ['k'] },
+    { keys: ['<Down>'], type: 'keyToKey', toKeys: ['j'] },
+    { keys: ['<Space>'], type: 'keyToKey', toKeys: ['l'] },
+    { keys: ['<BS>'], type: 'keyToKey', toKeys: ['h'] },
+    { keys: ['<C-Space>'], type: 'keyToKey', toKeys: ['W'] },
+    { keys: ['<C-BS>'], type: 'keyToKey', toKeys: ['B'] },
+    { keys: ['<S-Space>'], type: 'keyToKey', toKeys: ['w'] },
+    { keys: ['<S-BS>'], type: 'keyToKey', toKeys: ['b'] },
+    { keys: ['<C-n>'], type: 'keyToKey', toKeys: ['j'] },
+    { keys: ['<C-p>'], type: 'keyToKey', toKeys: ['k'] },
+    { keys: ['C-['], type: 'keyToKey', toKeys: ['<Esc>'] },
+    { keys: ['<C-c>'], type: 'keyToKey', toKeys: ['<Esc>'] },
+    { keys: ['s'], type: 'keyToKey', toKeys: ['c', 'l'] },
+    { keys: ['S'], type: 'keyToKey', toKeys: ['c', 'c'] },
+    { keys: ['<Home>'], type: 'keyToKey', toKeys: ['0'] },
+    { keys: ['<End>'], type: 'keyToKey', toKeys: ['$'] },
+    { keys: ['<PageUp>'], type: 'keyToKey', toKeys: ['<C-b>'] },
+    { keys: ['<PageDown>'], type: 'keyToKey', toKeys: ['<C-f>'] },
+    // Motions
+    { keys: ['H'], type: 'motion',
+        motion: 'moveToTopLine',
+        motionArgs: { linewise: true, toJumplist: true }},
+    { keys: ['M'], type: 'motion',
+        motion: 'moveToMiddleLine',
+        motionArgs: { linewise: true, toJumplist: true }},
+    { keys: ['L'], type: 'motion',
+        motion: 'moveToBottomLine',
+        motionArgs: { linewise: true, toJumplist: true }},
+    { keys: ['h'], type: 'motion',
+        motion: 'moveByCharacters',
+        motionArgs: { forward: false }},
+    { keys: ['l'], type: 'motion',
+        motion: 'moveByCharacters',
+        motionArgs: { forward: true }},
+    { keys: ['j'], type: 'motion',
+        motion: 'moveByLines',
+        motionArgs: { forward: true, linewise: true }},
+    { keys: ['k'], type: 'motion',
+        motion: 'moveByLines',
+        motionArgs: { forward: false, linewise: true }},
+    { keys: ['g','j'], type: 'motion',
+        motion: 'moveByDisplayLines',
+        motionArgs: { forward: true }},
+    { keys: ['g','k'], type: 'motion',
+        motion: 'moveByDisplayLines',
+        motionArgs: { forward: false }},
+    { keys: ['w'], type: 'motion',
+        motion: 'moveByWords',
+        motionArgs: { forward: true, wordEnd: false }},
+    { keys: ['W'], type: 'motion',
+        motion: 'moveByWords',
+        motionArgs: { forward: true, wordEnd: false, bigWord: true }},
+    { keys: ['e'], type: 'motion',
+        motion: 'moveByWords',
+        motionArgs: { forward: true, wordEnd: true, inclusive: true }},
+    { keys: ['E'], type: 'motion',
+        motion: 'moveByWords',
+        motionArgs: { forward: true, wordEnd: true, bigWord: true,
+            inclusive: true }},
+    { keys: ['b'], type: 'motion',
+        motion: 'moveByWords',
+        motionArgs: { forward: false, wordEnd: false }},
+    { keys: ['B'], type: 'motion',
+        motion: 'moveByWords',
+        motionArgs: { forward: false, wordEnd: false, bigWord: true }},
+    { keys: ['g', 'e'], type: 'motion',
+        motion: 'moveByWords',
+        motionArgs: { forward: false, wordEnd: true, inclusive: true }},
+    { keys: ['g', 'E'], type: 'motion',
+        motion: 'moveByWords',
+        motionArgs: { forward: false, wordEnd: true, bigWord: true,
+            inclusive: true }},
+    { keys: ['{'], type: 'motion', motion: 'moveByParagraph',
+        motionArgs: { forward: false, toJumplist: true }},
+    { keys: ['}'], type: 'motion', motion: 'moveByParagraph',
+        motionArgs: { forward: true, toJumplist: true }},
+    { keys: ['<C-f>'], type: 'motion',
+        motion: 'moveByPage', motionArgs: { forward: true }},
+    { keys: ['<C-b>'], type: 'motion',
+        motion: 'moveByPage', motionArgs: { forward: false }},
+    { keys: ['<C-d>'], type: 'motion',
+        motion: 'moveByScroll',
+        motionArgs: { forward: true, explicitRepeat: true }},
+    { keys: ['<C-u>'], type: 'motion',
+        motion: 'moveByScroll',
+        motionArgs: { forward: false, explicitRepeat: true }},
+    { keys: ['g', 'g'], type: 'motion',
+        motion: 'moveToLineOrEdgeOfDocument',
+        motionArgs: { forward: false, explicitRepeat: true, linewise: true, toJumplist: true }},
+    { keys: ['G'], type: 'motion',
+        motion: 'moveToLineOrEdgeOfDocument',
+        motionArgs: { forward: true, explicitRepeat: true, linewise: true, toJumplist: true }},
+    { keys: ['0'], type: 'motion', motion: 'moveToStartOfLine' },
+    { keys: ['^'], type: 'motion',
+        motion: 'moveToFirstNonWhiteSpaceCharacter' },
+    { keys: ['+'], type: 'motion',
+        motion: 'moveByLines',
+        motionArgs: { forward: true, toFirstChar:true }},
+    { keys: ['-'], type: 'motion',
+        motion: 'moveByLines',
+        motionArgs: { forward: false, toFirstChar:true }},
+    { keys: ['_'], type: 'motion',
+        motion: 'moveByLines',
+        motionArgs: { forward: true, toFirstChar:true, repeatOffset:-1 }},
+    { keys: ['$'], type: 'motion',
+        motion: 'moveToEol',
+        motionArgs: { inclusive: true }},
+    { keys: ['%'], type: 'motion',
+        motion: 'moveToMatchedSymbol',
+        motionArgs: { inclusive: true, toJumplist: true }},
+    { keys: ['f', 'character'], type: 'motion',
+        motion: 'moveToCharacter',
+        motionArgs: { forward: true , inclusive: true }},
+    { keys: ['F', 'character'], type: 'motion',
+        motion: 'moveToCharacter',
+        motionArgs: { forward: false }},
+    { keys: ['t', 'character'], type: 'motion',
+        motion: 'moveTillCharacter',
+        motionArgs: { forward: true, inclusive: true }},
+    { keys: ['T', 'character'], type: 'motion',
+        motion: 'moveTillCharacter',
+        motionArgs: { forward: false }},
+    { keys: [';'], type: 'motion', motion: 'repeatLastCharacterSearch',
+        motionArgs: { forward: true }},
+    { keys: [','], type: 'motion', motion: 'repeatLastCharacterSearch',
+        motionArgs: { forward: false }},
+    { keys: ['\'', 'character'], type: 'motion', motion: 'goToMark',
+        motionArgs: {toJumplist: true}},
+    { keys: ['`', 'character'], type: 'motion', motion: 'goToMark',
+        motionArgs: {toJumplist: true}},
+    { keys: [']', '`'], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true } },
+    { keys: ['[', '`'], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false } },
+    { keys: [']', '\''], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true, linewise: true } },
+    { keys: ['[', '\''], type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false, linewise: true } },
+    { keys: [']', 'character'], type: 'motion',
+        motion: 'moveToSymbol',
+        motionArgs: { forward: true, toJumplist: true}},
+    { keys: ['[', 'character'], type: 'motion',
+        motion: 'moveToSymbol',
+        motionArgs: { forward: false, toJumplist: true}},
+    { keys: ['|'], type: 'motion',
+        motion: 'moveToColumn',
+        motionArgs: { }},
+    // Operators
+    { keys: ['d'], type: 'operator', operator: 'delete' },
+    { keys: ['y'], type: 'operator', operator: 'yank' },
+    { keys: ['c'], type: 'operator', operator: 'change' },
+    { keys: ['>'], type: 'operator', operator: 'indent',
+        operatorArgs: { indentRight: true }},
+    { keys: ['<'], type: 'operator', operator: 'indent',
+        operatorArgs: { indentRight: false }},
+    { keys: ['g', '~'], type: 'operator', operator: 'swapcase' },
+    { keys: ['n'], type: 'motion', motion: 'findNext',
+        motionArgs: { forward: true, toJumplist: true }},
+    { keys: ['N'], type: 'motion', motion: 'findNext',
+        motionArgs: { forward: false, toJumplist: true }},
+    // Operator-Motion dual commands
+    { keys: ['x'], type: 'operatorMotion', operator: 'delete',
+        motion: 'moveByCharacters', motionArgs: { forward: true },
+        operatorMotionArgs: { visualLine: false }},
+    { keys: ['X'], type: 'operatorMotion', operator: 'delete',
+        motion: 'moveByCharacters', motionArgs: { forward: false },
+        operatorMotionArgs: { visualLine: true }},
+    { keys: ['D'], type: 'operatorMotion', operator: 'delete',
+      motion: 'moveToEol', motionArgs: { inclusive: true },
+        operatorMotionArgs: { visualLine: true }},
+    { keys: ['Y'], type: 'operatorMotion', operator: 'yank',
+        motion: 'moveToEol', motionArgs: { inclusive: true },
+        operatorMotionArgs: { visualLine: true }},
+    { keys: ['C'], type: 'operatorMotion',
+        operator: 'change',
+        motion: 'moveToEol', motionArgs: { inclusive: true },
+        operatorMotionArgs: { visualLine: true }},
+    { keys: ['~'], type: 'operatorMotion',
+        operator: 'swapcase', operatorArgs: { shouldMoveCursor: true },
+        motion: 'moveByCharacters', motionArgs: { forward: true }},
+    // Actions
+    { keys: ['<C-i>'], type: 'action', action: 'jumpListWalk',
+        actionArgs: { forward: true }},
+    { keys: ['<C-o>'], type: 'action', action: 'jumpListWalk',
+        actionArgs: { forward: false }},
+    { keys: ['a'], type: 'action', action: 'enterInsertMode', isEdit: true,
+        actionArgs: { insertAt: 'charAfter' }},
+    { keys: ['A'], type: 'action', action: 'enterInsertMode', isEdit: true,
+        actionArgs: { insertAt: 'eol' }},
+    { keys: ['i'], type: 'action', action: 'enterInsertMode', isEdit: true,
+        actionArgs: { insertAt: 'inplace' }},
+    { keys: ['I'], type: 'action', action: 'enterInsertMode', isEdit: true,
+        actionArgs: { insertAt: 'firstNonBlank' }},
+    { keys: ['o'], type: 'action', action: 'newLineAndEnterInsertMode',
+        isEdit: true, interlaceInsertRepeat: true,
+        actionArgs: { after: true }},
+    { keys: ['O'], type: 'action', action: 'newLineAndEnterInsertMode',
+        isEdit: true, interlaceInsertRepeat: true,
+        actionArgs: { after: false }},
+    { keys: ['v'], type: 'action', action: 'toggleVisualMode' },
+    { keys: ['V'], type: 'action', action: 'toggleVisualMode',
+        actionArgs: { linewise: true }},
+    { keys: ['J'], type: 'action', action: 'joinLines', isEdit: true },
+    { keys: ['p'], type: 'action', action: 'paste', isEdit: true,
+        actionArgs: { after: true, isEdit: true }},
+    { keys: ['P'], type: 'action', action: 'paste', isEdit: true,
+        actionArgs: { after: false, isEdit: true }},
+    { keys: ['r', 'character'], type: 'action', action: 'replace', isEdit: true },
+    { keys: ['@', 'character'], type: 'action', action: 'replayMacro' },
+    { keys: ['q', 'character'], type: 'action', action: 'enterMacroRecordMode' },
+    // Handle Replace-mode as a special case of insert mode.
+    { keys: ['R'], type: 'action', action: 'enterInsertMode', isEdit: true,
+        actionArgs: { replace: true }},
+    { keys: ['u'], type: 'action', action: 'undo' },
+    { keys: ['<C-r>'], type: 'action', action: 'redo' },
+    { keys: ['m', 'character'], type: 'action', action: 'setMark' },
+    { keys: ['"', 'character'], type: 'action', action: 'setRegister' },
+    { keys: ['z', 'z'], type: 'action', action: 'scrollToCursor',
+        actionArgs: { position: 'center' }},
+    { keys: ['z', '.'], type: 'action', action: 'scrollToCursor',
+        actionArgs: { position: 'center' },
+        motion: 'moveToFirstNonWhiteSpaceCharacter' },
+    { keys: ['z', 't'], type: 'action', action: 'scrollToCursor',
+        actionArgs: { position: 'top' }},
+    { keys: ['z', '<CR>'], type: 'action', action: 'scrollToCursor',
+        actionArgs: { position: 'top' },
+        motion: 'moveToFirstNonWhiteSpaceCharacter' },
+    { keys: ['z', '-'], type: 'action', action: 'scrollToCursor',
+        actionArgs: { position: 'bottom' }},
+    { keys: ['z', 'b'], type: 'action', action: 'scrollToCursor',
+        actionArgs: { position: 'bottom' },
+        motion: 'moveToFirstNonWhiteSpaceCharacter' },
+    { keys: ['.'], type: 'action', action: 'repeatLastEdit' },
+    { keys: ['<C-a>'], type: 'action', action: 'incrementNumberToken',
+        isEdit: true,
+        actionArgs: {increase: true, backtrack: false}},
+    { keys: ['<C-x>'], type: 'action', action: 'incrementNumberToken',
+        isEdit: true,
+        actionArgs: {increase: false, backtrack: false}},
+    // Text object motions
+    { keys: ['a', 'character'], type: 'motion',
+        motion: 'textObjectManipulation' },
+    { keys: ['i', 'character'], type: 'motion',
+        motion: 'textObjectManipulation',
+        motionArgs: { textObjectInner: true }},
+    // Search
+    { keys: ['/'], type: 'search',
+        searchArgs: { forward: true, querySrc: 'prompt', toJumplist: true }},
+    { keys: ['?'], type: 'search',
+        searchArgs: { forward: false, querySrc: 'prompt', toJumplist: true }},
+    { keys: ['*'], type: 'search',
+        searchArgs: { forward: true, querySrc: 'wordUnderCursor', toJumplist: true }},
+    { keys: ['#'], type: 'search',
+        searchArgs: { forward: false, querySrc: 'wordUnderCursor', toJumplist: true }},
+    // Ex command
+    { keys: [':'], type: 'ex' }
+  ];
+
+  var Vim = function() {
+    CodeMirror.defineOption('vimMode', false, function(cm, val) {
+      if (val) {
+        cm.setOption('keyMap', 'vim');
+        cm.on('beforeSelectionChange', beforeSelectionChange);
+        maybeInitVimState(cm);
+      } else if (cm.state.vim) {
+        cm.setOption('keyMap', 'default');
+        cm.off('beforeSelectionChange', beforeSelectionChange);
+        cm.state.vim = null;
+      }
+    });
+    function beforeSelectionChange(cm, cur) {
+      var vim = cm.state.vim;
+      if (vim.insertMode || vim.exMode) return;
+
+      var head = cur.head;
+      if (head.ch && head.ch == cm.doc.getLine(head.line).length) {
+        head.ch--;
+      }
+    }
+
+    var numberRegex = /[\d]/;
+    var wordRegexp = [(/\w/), (/[^\w\s]/)], bigWordRegexp = [(/\S/)];
+    function makeKeyRange(start, size) {
+      var keys = [];
+      for (var i = start; i < start + size; i++) {
+        keys.push(String.fromCharCode(i));
+      }
+      return keys;
+    }
+    var upperCaseAlphabet = makeKeyRange(65, 26);
+    var lowerCaseAlphabet = makeKeyRange(97, 26);
+    var numbers = makeKeyRange(48, 10);
+    var specialSymbols = '~`!@#$%^&*()_-+=[{}]\\|/?.,<>:;"\''.split('');
+    var specialKeys = ['Left', 'Right', 'Up', 'Down', 'Space', 'Backspace',
+        'Esc', 'Home', 'End', 'PageUp', 'PageDown', 'Enter'];
+    var validMarks = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['<', '>']);
+    var validRegisters = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['-', '"']);
+
+    function isLine(cm, line) {
+      return line >= cm.firstLine() && line <= cm.lastLine();
+    }
+    function isLowerCase(k) {
+      return (/^[a-z]$/).test(k);
+    }
+    function isMatchableSymbol(k) {
+      return '()[]{}'.indexOf(k) != -1;
+    }
+    function isNumber(k) {
+      return numberRegex.test(k);
+    }
+    function isUpperCase(k) {
+      return (/^[A-Z]$/).test(k);
+    }
+    function isWhiteSpaceString(k) {
+      return (/^\s*$/).test(k);
+    }
+    function inArray(val, arr) {
+      for (var i = 0; i < arr.length; i++) {
+        if (arr[i] == val) {
+          return true;
+        }
+      }
+      return false;
+    }
+
+    var createCircularJumpList = function() {
+      var size = 100;
+      var pointer = -1;
+      var head = 0;
+      var tail = 0;
+      var buffer = new Array(size);
+      function add(cm, oldCur, newCur) {
+        var current = pointer % size;
+        var curMark = buffer[current];
+        function useNextSlot(cursor) {
+          var next = ++pointer % size;
+          var trashMark = buffer[next];
+          if (trashMark) {
+            trashMark.clear();
+          }
+          buffer[next] = cm.setBookmark(cursor);
+        }
+        if (curMark) {
+          var markPos = curMark.find();
+          // avoid recording redundant cursor position
+          if (markPos && !cursorEqual(markPos, oldCur)) {
+            useNextSlot(oldCur);
+          }
+        } else {
+          useNextSlot(oldCur);
+        }
+        useNextSlot(newCur);
+        head = pointer;
+        tail = pointer - size + 1;
+        if (tail < 0) {
+          tail = 0;
+        }
+      }
+      function move(cm, offset) {
+        pointer += offset;
+        if (pointer > head) {
+          pointer = head;
+        } else if (pointer < tail) {
+          pointer = tail;
+        }
+        var mark = buffer[(size + pointer) % size];
+        // skip marks that are temporarily removed from text buffer
+        if (mark && !mark.find()) {
+          var inc = offset > 0 ? 1 : -1;
+          var newCur;
+          var oldCur = cm.getCursor();
+          do {
+            pointer += inc;
+            mark = buffer[(size + pointer) % size];
+            // skip marks that are the same as current position
+            if (mark &&
+                (newCur = mark.find()) &&
+                !cursorEqual(oldCur, newCur)) {
+              break;
+            }
+          } while (pointer < head && pointer > tail);
+        }
+        return mark;
+      }
+      return {
+        cachedCursor: undefined, //used for # and * jumps
+        add: add,
+        move: move
+      };
+    };
+
+    var createMacroState = function() {
+      return {
+        macroKeyBuffer: [],
+        latestRegister: undefined,
+        inReplay: false,
+        lastInsertModeChanges: {
+          changes: [], // Change list
+          expectCursorActivityForChange: false // Set to true on change, false on cursorActivity.
+        },
+        enteredMacroMode: undefined,
+        isMacroPlaying: false,
+        toggle: function(cm, registerName) {
+          if (this.enteredMacroMode) { //onExit
+            this.enteredMacroMode(); // close dialog
+            this.enteredMacroMode = undefined;
+          } else { //onEnter
+            this.latestRegister = registerName;
+            this.enteredMacroMode = cm.openDialog(
+              '(recording)['+registerName+']', null, {bottom:true});
+          }
+        }
+      };
+    };
+
+
+    function maybeInitVimState(cm) {
+      if (!cm.state.vim) {
+        // Store instance state in the CodeMirror object.
+        cm.state.vim = {
+          inputState: new InputState(),
+          // Vim's input state that triggered the last edit, used to repeat
+          // motions and operators with '.'.
+          lastEditInputState: undefined,
+          // Vim's action command before the last edit, used to repeat actions
+          // with '.' and insert mode repeat.
+          lastEditActionCommand: undefined,
+          // When using jk for navigation, if you move from a longer line to a
+          // shorter line, the cursor may clip to the end of the shorter line.
+          // If j is pressed again and cursor goes to the next line, the
+          // cursor should go back to its horizontal position on the longer
+          // line if it can. This is to keep track of the horizontal position.
+          lastHPos: -1,
+          // Doing the same with screen-position for gj/gk
+          lastHSPos: -1,
+          // The last motion command run. Cleared if a non-motion command gets
+          // executed in between.
+          lastMotion: null,
+          marks: {},
+          insertMode: false,
+          // Repeat count for changes made in insert mode, triggered by key
+          // sequences like 3,i. Only exists when insertMode is true.
+          insertModeRepeat: undefined,
+          visualMode: false,
+          // If we are in visual line mode. No effect if visualMode is false.
+          visualLine: false
+        };
+      }
+      return cm.state.vim;
+    }
+    var vimGlobalState;
+    function resetVimGlobalState() {
+      vimGlobalState = {
+        // The current search query.
+        searchQuery: null,
+        // Whether we are searching backwards.
+        searchIsReversed: false,
+        jumpList: createCircularJumpList(),
+        macroModeState: createMacroState(),
+        // Recording latest f, t, F or T motion command.
+        lastChararacterSearch: {increment:0, forward:true, selectedCharacter:''},
+        registerController: new RegisterController({})
+      };
+    }
+
+    var vimApi= {
+      buildKeyMap: function() {
+        // TODO: Convert keymap into dictionary format for fast lookup.
+      },
+      // Testing hook, though it might be useful to expose the register
+      // controller anyways.
+      getRegisterController: function() {
+        return vimGlobalState.registerController;
+      },
+      // Testing hook.
+      resetVimGlobalState_: resetVimGlobalState,
+
+      // Testing hook.
+      getVimGlobalState_: function() {
+        return vimGlobalState;
+      },
+
+      // Testing hook.
+      maybeInitVimState_: maybeInitVimState,
+
+      InsertModeKey: InsertModeKey,
+      map: function(lhs, rhs) {
+        // Add user defined key bindings.
+        exCommandDispatcher.map(lhs, rhs);
+      },
+      defineEx: function(name, prefix, func){
+        if (name.indexOf(prefix) !== 0) {
+          throw new Error('(Vim.defineEx) "'+prefix+'" is not a prefix of "'+name+'", command not registered');
+        }
+        exCommands[name]=func;
+        exCommandDispatcher.commandMap_[prefix]={name:name, shortName:prefix, type:'api'};
+      },
+      // This is the outermost function called by CodeMirror, after keys have
+      // been mapped to their Vim equivalents.
+      handleKey: function(cm, key) {
+        var command;
+        var vim = maybeInitVimState(cm);
+        var macroModeState = vimGlobalState.macroModeState;
+        if (macroModeState.enteredMacroMode) {
+          if (key == 'q') {
+            actions.exitMacroRecordMode();
+            vim.inputState = new InputState();
+            return;
+          }
+        }
+        if (key == '<Esc>') {
+          // Clear input state and get back to normal mode.
+          vim.inputState = new InputState();
+          if (vim.visualMode) {
+            exitVisualMode(cm);
+          }
+          return;
+        }
+        // Enter visual mode when the mouse selects text.
+        if (!vim.visualMode &&
+            !cursorEqual(cm.getCursor('head'), cm.getCursor('anchor'))) {
+          vim.visualMode = true;
+          vim.visualLine = false;
+          cm.on('mousedown', exitVisualMode);
+        }
+        if (key != '0' || (key == '0' && vim.inputState.getRepeat() === 0)) {
+          // Have to special case 0 since it's both a motion and a number.
+          command = commandDispatcher.matchCommand(key, defaultKeymap, vim);
+        }
+        if (!command) {
+          if (isNumber(key)) {
+            // Increment count unless count is 0 and key is 0.
+            vim.inputState.pushRepeatDigit(key);
+          }
+          return;
+        }
+        if (command.type == 'keyToKey') {
+          // TODO: prevent infinite recursion.
+          for (var i = 0; i < command.toKeys.length; i++) {
+            this.handleKey(cm, command.toKeys[i]);
+          }
+        } else {
+          if (macroModeState.enteredMacroMode) {
+            logKey(macroModeState, key);
+          }
+          commandDispatcher.processCommand(cm, vim, command);
+        }
+      }
+    };
+
+    // Represents the current input state.
+    function InputState() {
+      this.prefixRepeat = [];
+      this.motionRepeat = [];
+
+      this.operator = null;
+      this.operatorArgs = null;
+      this.motion = null;
+      this.motionArgs = null;
+      this.keyBuffer = []; // For matching multi-key commands.
+      this.registerName = null; // Defaults to the unamed register.
+    }
+    InputState.prototype.pushRepeatDigit = function(n) {
+      if (!this.operator) {
+        this.prefixRepeat = this.prefixRepeat.concat(n);
+      } else {
+        this.motionRepeat = this.motionRepeat.concat(n);
+      }
+    };
+    InputState.prototype.getRepeat = function() {
+      var repeat = 0;
+      if (this.prefixRepeat.length > 0 || this.motionRepeat.length > 0) {
+        repeat = 1;
+        if (this.prefixRepeat.length > 0) {
+          repeat *= parseInt(this.prefixRepeat.join(''), 10);
+        }
+        if (this.motionRepeat.length > 0) {
+          repeat *= parseInt(this.motionRepeat.join(''), 10);
+        }
+      }
+      return repeat;
+    };
+
+    /*
+     * Register stores information about copy and paste registers.  Besides
+     * text, a register must store whether it is linewise (i.e., when it is
+     * pasted, should it insert itself into a new line, or should the text be
+     * inserted at the cursor position.)
+     */
+    function Register(text, linewise) {
+      this.clear();
+      if (text) {
+        this.set(text, linewise);
+      }
+    }
+    Register.prototype = {
+      set: function(text, linewise) {
+        this.text = text;
+        this.linewise = !!linewise;
+      },
+      append: function(text, linewise) {
+        // if this register has ever been set to linewise, use linewise.
+        if (linewise || this.linewise) {
+          this.text += '\n' + text;
+          this.linewise = true;
+        } else {
+          this.text += text;
+        }
+      },
+      clear: function() {
+        this.text = '';
+        this.linewise = false;
+      },
+      toString: function() { return this.text; }
+    };
+
+    /*
+     * vim registers allow you to keep many independent copy and paste buffers.
+     * See http://usevim.com/2012/04/13/registers/ for an introduction.
+     *
+     * RegisterController keeps the state of all the registers.  An initial
+     * state may be passed in.  The unnamed register '"' will always be
+     * overridden.
+     */
+    function RegisterController(registers) {
+      this.registers = registers;
+      this.unamedRegister = registers['"'] = new Register();
+    }
+    RegisterController.prototype = {
+      pushText: function(registerName, operator, text, linewise) {
+        if (linewise && text.charAt(0) == '\n') {
+          text = text.slice(1) + '\n';
+        }
+        // Lowercase and uppercase registers refer to the same register.
+        // Uppercase just means append.
+        var register = this.isValidRegister(registerName) ?
+            this.getRegister(registerName) : null;
+        // if no register/an invalid register was specified, things go to the
+        // default registers
+        if (!register) {
+          switch (operator) {
+            case 'yank':
+              // The 0 register contains the text from the most recent yank.
+              this.registers['0'] = new Register(text, linewise);
+              break;
+            case 'delete':
+            case 'change':
+              if (text.indexOf('\n') == -1) {
+                // Delete less than 1 line. Update the small delete register.
+                this.registers['-'] = new Register(text, linewise);
+              } else {
+                // Shift down the contents of the numbered registers and put the
+                // deleted text into register 1.
+                this.shiftNumericRegisters_();
+                this.registers['1'] = new Register(text, linewise);
+              }
+              break;
+          }
+          // Make sure the unnamed register is set to what just happened
+          this.unamedRegister.set(text, linewise);
+          return;
+        }
+
+        // If we've gotten to this point, we've actually specified a register
+        var append = isUpperCase(registerName);
+        if (append) {
+          register.append(text, linewise);
+          // The unamed register always has the same value as the last used
+          // register.
+          this.unamedRegister.append(text, linewise);
+        } else {
+          register.set(text, linewise);
+          this.unamedRegister.set(text, linewise);
+        }
+      },
+      setRegisterText: function(name, text, linewise) {
+        this.getRegister(name).set(text, linewise);
+      },
+      // Gets the register named @name.  If one of @name doesn't already exist,
+      // create it.  If @name is invalid, return the unamedRegister.
+      getRegister: function(name) {
+        if (!this.isValidRegister(name)) {
+          return this.unamedRegister;
+        }
+        name = name.toLowerCase();
+        if (!this.registers[name]) {
+          this.registers[name] = new Register();
+        }
+        return this.registers[name];
+      },
+      isValidRegister: function(name) {
+        return name && inArray(name, validRegisters);
+      },
+      shiftNumericRegisters_: function() {
+        for (var i = 9; i >= 2; i--) {
+          this.registers[i] = this.getRegister('' + (i - 1));
+        }
+      }
+    };
+
+    var commandDispatcher = {
+      matchCommand: function(key, keyMap, vim) {
+        var inputState = vim.inputState;
+        var keys = inputState.keyBuffer.concat(key);
+        for (var i = 0; i < keyMap.length; i++) {
+          var command = keyMap[i];
+          if (matchKeysPartial(keys, command.keys)) {
+            if (keys.length < command.keys.length) {
+              // Matches part of a multi-key command. Buffer and wait for next
+              // stroke.
+              inputState.keyBuffer.push(key);
+              return null;
+            }
+            if (inputState.operator && command.type == 'action') {
+              // Ignore matched action commands after an operator. Operators
+              // only operate on motions. This check is really for text
+              // objects since aW, a[ etcs conflicts with a.
+              continue;
+            }
+            // Matches whole comand. Return the command.
+            if (command.keys[keys.length - 1] == 'character') {
+              inputState.selectedCharacter = keys[keys.length - 1];
+              if(inputState.selectedCharacter.length>1){
+                switch(inputState.selectedCharacter){
+                  case '<CR>':
+                    inputState.selectedCharacter='\n';
+                    break;
+                  case '<Space>':
+                    inputState.selectedCharacter=' ';
+                    break;
+                  default:
+                    continue;
+                }
+              }
+            }
+            inputState.keyBuffer = [];
+            return command;
+          }
+        }
+        // Clear the buffer since there are no partial matches.
+        inputState.keyBuffer = [];
+        return null;
+      },
+      processCommand: function(cm, vim, command) {
+        vim.inputState.repeatOverride = command.repeatOverride;
+        switch (command.type) {
+          case 'motion':
+            this.processMotion(cm, vim, command);
+            break;
+          case 'operator':
+            this.processOperator(cm, vim, command);
+            break;
+          case 'operatorMotion':
+            this.processOperatorMotion(cm, vim, command);
+            break;
+          case 'action':
+            this.processAction(cm, vim, command);
+            break;
+          case 'search':
+            this.processSearch(cm, vim, command);
+            break;
+          case 'ex':
+          case 'keyToEx':
+            this.processEx(cm, vim, command);
+            break;
+          default:
+            break;
+        }
+      },
+      processMotion: function(cm, vim, command) {
+        vim.inputState.motion = command.motion;
+        vim.inputState.motionArgs = copyArgs(command.motionArgs);
+        this.evalInput(cm, vim);
+      },
+      processOperator: function(cm, vim, command) {
+        var inputState = vim.inputState;
+        if (inputState.operator) {
+          if (inputState.operator == command.operator) {
+            // Typing an operator twice like 'dd' makes the operator operate
+            // linewise
+            inputState.motion = 'expandToLine';
+            inputState.motionArgs = { linewise: true };
+            this.evalInput(cm, vim);
+            return;
+          } else {
+            // 2 different operators in a row doesn't make sense.
+            vim.inputState = new InputState();
+          }
+        }
+        inputState.operator = command.operator;
+        inputState.operatorArgs = copyArgs(command.operatorArgs);
+        if (vim.visualMode) {
+          // Operating on a selection in visual mode. We don't need a motion.
+          this.evalInput(cm, vim);
+        }
+      },
+      processOperatorMotion: function(cm, vim, command) {
+        var visualMode = vim.visualMode;
+        var operatorMotionArgs = copyArgs(command.operatorMotionArgs);
+        if (operatorMotionArgs) {
+          // Operator motions may have special behavior in visual mode.
+          if (visualMode && operatorMotionArgs.visualLine) {
+            vim.visualLine = true;
+          }
+        }
+        this.processOperator(cm, vim, command);
+        if (!visualMode) {
+          this.processMotion(cm, vim, command);
+        }
+      },
+      processAction: function(cm, vim, command) {
+        var inputState = vim.inputState;
+        var repeat = inputState.getRepeat();
+        var repeatIsExplicit = !!repeat;
+        var actionArgs = copyArgs(command.actionArgs) || {};
+        if (inputState.selectedCharacter) {
+          actionArgs.selectedCharacter = inputState.selectedCharacter;
+        }
+        // Actions may or may not have motions and operators. Do these first.
+        if (command.operator) {
+          this.processOperator(cm, vim, command);
+        }
+        if (command.motion) {
+          this.processMotion(cm, vim, command);
+        }
+        if (command.motion || command.operator) {
+          this.evalInput(cm, vim);
+        }
+        actionArgs.repeat = repeat || 1;
+        actionArgs.repeatIsExplicit = repeatIsExplicit;
+        actionArgs.registerName = inputState.registerName;
+        vim.inputState = new InputState();
+        vim.lastMotion = null;
+        if (command.isEdit) {
+          this.recordLastEdit(vim, inputState, command);
+        }
+        actions[command.action](cm, actionArgs, vim);
+      },
+      processSearch: function(cm, vim, command) {
+        if (!cm.getSearchCursor) {
+          // Search depends on SearchCursor.
+          return;
+        }
+        var forward = command.searchArgs.forward;
+        getSearchState(cm).setReversed(!forward);
+        var promptPrefix = (forward) ? '/' : '?';
+        var originalQuery = getSearchState(cm).getQuery();
+        var originalScrollPos = cm.getScrollInfo();
+        function handleQuery(query, ignoreCase, smartCase) {
+          try {
+            updateSearchQuery(cm, query, ignoreCase, smartCase);
+          } catch (e) {
+            showConfirm(cm, 'Invalid regex: ' + query);
+            return;
+          }
+          commandDispatcher.processMotion(cm, vim, {
+            type: 'motion',
+            motion: 'findNext',
+            motionArgs: { forward: true, toJumplist: command.searchArgs.toJumplist }
+          });
+        }
+        function onPromptClose(query) {
+          cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
+          handleQuery(query, true /** ignoreCase */, true /** smartCase */);
+        }
+        function onPromptKeyUp(_e, query) {
+          var parsedQuery;
+          try {
+            parsedQuery = updateSearchQuery(cm, query,
+                true /** ignoreCase */, true /** smartCase */);
+          } catch (e) {
+            // Swallow bad regexes for incremental search.
+          }
+          if (parsedQuery) {
+            cm.scrollIntoView(findNext(cm, !forward, parsedQuery), 30);
+          } else {
+            clearSearchHighlight(cm);
+            cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
+          }
+        }
+        function onPromptKeyDown(e, _query, close) {
+          var keyName = CodeMirror.keyName(e);
+          if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[') {
+            updateSearchQuery(cm, originalQuery);
+            clearSearchHighlight(cm);
+            cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
+
+            CodeMirror.e_stop(e);
+            close();
+            cm.focus();
+          }
+        }
+        switch (command.searchArgs.querySrc) {
+          case 'prompt':
+            showPrompt(cm, {
+                onClose: onPromptClose,
+                prefix: promptPrefix,
+                desc: searchPromptDesc,
+                onKeyUp: onPromptKeyUp,
+                onKeyDown: onPromptKeyDown
+            });
+            break;
+          case 'wordUnderCursor':
+            var word = expandWordUnderCursor(cm, false /** inclusive */,
+                true /** forward */, false /** bigWord */,
+                true /** noSymbol */);
+            var isKeyword = true;
+            if (!word) {
+              word = expandWordUnderCursor(cm, false /** inclusive */,
+                  true /** forward */, false /** bigWord */,
+                  false /** noSymbol */);
+              isKeyword = false;
+            }
+            if (!word) {
+              return;
+            }
+            var query = cm.getLine(word.start.line).substring(word.start.ch,
+                word.end.ch);
+            if (isKeyword) {
+              query = '\\b' + query + '\\b';
+            } else {
+              query = escapeRegex(query);
+            }
+
+            // cachedCursor is used to save the old position of the cursor
+            // when * or # causes vim to seek for the nearest word and shift
+            // the cursor before entering the motion.
+            vimGlobalState.jumpList.cachedCursor = cm.getCursor();
+            cm.setCursor(word.start);
+
+            handleQuery(query, true /** ignoreCase */, false /** smartCase */);
+            break;
+        }
+      },
+      processEx: function(cm, vim, command) {
+        function onPromptClose(input) {
+          // Give the prompt some time to close so that if processCommand shows
+          // an error, the elements don't overlap.
+          exCommandDispatcher.processCommand(cm, input);
+        }
+        function onPromptKeyDown(e, _input, close) {
+          var keyName = CodeMirror.keyName(e);
+          if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[') {
+            CodeMirror.e_stop(e);
+            close();
+            cm.focus();
+          }
+        }
+        if (command.type == 'keyToEx') {
+          // Handle user defined Ex to Ex mappings
+          exCommandDispatcher.processCommand(cm, command.exArgs.input);
+        } else {
+          if (vim.visualMode) {
+            showPrompt(cm, { onClose: onPromptClose, prefix: ':', value: '\'<,\'>',
+                onKeyDown: onPromptKeyDown});
+          } else {
+            showPrompt(cm, { onClose: onPromptClose, prefix: ':',
+                onKeyDown: onPromptKeyDown});
+          }
+        }
+      },
+      evalInput: function(cm, vim) {
+        // If the motion comand is set, execute both the operator and motion.
+        // Otherwise return.
+        var inputState = vim.inputState;
+        var motion = inputState.motion;
+        var motionArgs = inputState.motionArgs || {};
+        var operator = inputState.operator;
+        var operatorArgs = inputState.operatorArgs || {};
+        var registerName = inputState.registerName;
+        var selectionEnd = cm.getCursor('head');
+        var selectionStart = cm.getCursor('anchor');
+        // The difference between cur and selection cursors are that cur is
+        // being operated on and ignores that there is a selection.
+        var curStart = copyCursor(selectionEnd);
+        var curOriginal = copyCursor(curStart);
+        var curEnd;
+        var repeat;
+        if (operator) {
+          this.recordLastEdit(vim, inputState);
+        }
+        if (inputState.repeatOverride !== undefined) {
+          // If repeatOverride is specified, that takes precedence over the
+          // input state's repeat. Used by Ex mode and can be user defined.
+          repeat = inputState.repeatOverride;
+        } else {
+          repeat = inputState.getRepeat();
+        }
+        if (repeat > 0 && motionArgs.explicitRepeat) {
+          motionArgs.repeatIsExplicit = true;
+        } else if (motionArgs.noRepeat ||
+            (!motionArgs.explicitRepeat && repeat === 0)) {
+          repeat = 1;
+          motionArgs.repeatIsExplicit = false;
+        }
+        if (inputState.selectedCharacter) {
+          // If there is a character input, stick it in all of the arg arrays.
+          motionArgs.selectedCharacter = operatorArgs.selectedCharacter =
+              inputState.selectedCharacter;
+        }
+        motionArgs.repeat = repeat;
+        vim.inputState = new InputState();
+        if (motion) {
+          var motionResult = motions[motion](cm, motionArgs, vim);
+          vim.lastMotion = motions[motion];
+          if (!motionResult) {
+            return;
+          }
+          if (motionArgs.toJumplist) {
+            var jumpList = vimGlobalState.jumpList;
+            // if the current motion is # or *, use cachedCursor
+            var cachedCursor = jumpList.cachedCursor;
+            if (cachedCursor) {
+              recordJumpPosition(cm, cachedCursor, motionResult);
+              delete jumpList.cachedCursor;
+            } else {
+              recordJumpPosition(cm, curOriginal, motionResult);
+            }
+          }
+          if (motionResult instanceof Array) {
+            curStart = motionResult[0];
+            curEnd = motionResult[1];
+          } else {
+            curEnd = motionResult;
+          }
+          // TODO: Handle null returns from motion commands better.
+          if (!curEnd) {
+            curEnd = { ch: curStart.ch, line: curStart.line };
+          }
+          if (vim.visualMode) {
+            // Check if the selection crossed over itself. Will need to shift
+            // the start point if that happened.
+            if (cursorIsBefore(selectionStart, selectionEnd) &&
+                (cursorEqual(selectionStart, curEnd) ||
+                    cursorIsBefore(curEnd, selectionStart))) {
+              // The end of the selection has moved from after the start to
+              // before the start. We will shift the start right by 1.
+              selectionStart.ch += 1;
+            } else if (cursorIsBefore(selectionEnd, selectionStart) &&
+                (cursorEqual(selectionStart, curEnd) ||
+                    cursorIsBefore(selectionStart, curEnd))) {
+              // The opposite happened. We will shift the start left by 1.
+              selectionStart.ch -= 1;
+            }
+            selectionEnd = curEnd;
+            if (vim.visualLine) {
+              if (cursorIsBefore(selectionStart, selectionEnd)) {
+                selectionStart.ch = 0;
+                selectionEnd.ch = lineLength(cm, selectionEnd.line);
+              } else {
+                selectionEnd.ch = 0;
+                selectionStart.ch = lineLength(cm, selectionStart.line);
+              }
+            }
+            cm.setSelection(selectionStart, selectionEnd);
+            updateMark(cm, vim, '<',
+                cursorIsBefore(selectionStart, selectionEnd) ? selectionStart
+                    : selectionEnd);
+            updateMark(cm, vim, '>',
+                cursorIsBefore(selectionStart, selectionEnd) ? selectionEnd
+                    : selectionStart);
+          } else if (!operator) {
+            curEnd = clipCursorToContent(cm, curEnd);
+            cm.setCursor(curEnd.line, curEnd.ch);
+          }
+        }
+
+        if (operator) {
+          var inverted = false;
+          vim.lastMotion = null;
+          operatorArgs.repeat = repeat; // Indent in visual mode needs this.
+          if (vim.visualMode) {
+            curStart = selectionStart;
+            curEnd = selectionEnd;
+            motionArgs.inclusive = true;
+          }
+          // Swap start and end if motion was backward.
+          if (cursorIsBefore(curEnd, curStart)) {
+            var tmp = curStart;
+            curStart = curEnd;
+            curEnd = tmp;
+            inverted = true;
+          }
+          if (motionArgs.inclusive && !(vim.visualMode && inverted)) {
+            // Move the selection end one to the right to include the last
+            // character.
+            curEnd.ch++;
+          }
+          var linewise = motionArgs.linewise ||
+              (vim.visualMode && vim.visualLine);
+          if (linewise) {
+            // Expand selection to entire line.
+            expandSelectionToLine(cm, curStart, curEnd);
+          } else if (motionArgs.forward) {
+            // Clip to trailing newlines only if the motion goes forward.
+            clipToLine(cm, curStart, curEnd);
+          }
+          operatorArgs.registerName = registerName;
+          // Keep track of linewise as it affects how paste and change behave.
+          operatorArgs.linewise = linewise;
+          operators[operator](cm, operatorArgs, vim, curStart,
+              curEnd, curOriginal);
+          if (vim.visualMode) {
+            exitVisualMode(cm);
+          }
+        }
+      },
+      recordLastEdit: function(vim, inputState, actionCommand) {
+        var macroModeState = vimGlobalState.macroModeState;
+        if (macroModeState.inReplay) { return; }
+        vim.lastEditInputState = inputState;
+        vim.lastEditActionCommand = actionCommand;
+        macroModeState.lastInsertModeChanges.changes = [];
+        macroModeState.lastInsertModeChanges.expectCursorActivityForChange = false;
+      }
+    };
+
+    /**
+     * typedef {Object{line:number,ch:number}} Cursor An object containing the
+     *     position of the cursor.
+     */
+    // All of the functions below return Cursor objects.
+    var motions = {
+      moveToTopLine: function(cm, motionArgs) {
+        var line = getUserVisibleLines(cm).top + motionArgs.repeat -1;
+        return { line: line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(line)) };
+      },
+      moveToMiddleLine: function(cm) {
+        var range = getUserVisibleLines(cm);
+        var line = Math.floor((range.top + range.bottom) * 0.5);
+        return { line: line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(line)) };
+      },
+      moveToBottomLine: function(cm, motionArgs) {
+        var line = getUserVisibleLines(cm).bottom - motionArgs.repeat +1;
+        return { line: line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(line)) };
+      },
+      expandToLine: function(cm, motionArgs) {
+        // Expands forward to end of line, and then to next line if repeat is
+        // >1. Does not handle backward motion!
+        var cur = cm.getCursor();
+        return { line: cur.line + motionArgs.repeat - 1, ch: Infinity };
+      },
+      findNext: function(cm, motionArgs) {
+        var state = getSearchState(cm);
+        var query = state.getQuery();
+        if (!query) {
+          return;
+        }
+        var prev = !motionArgs.forward;
+        // If search is initiated with ? instead of /, negate direction.
+        prev = (state.isReversed()) ? !prev : prev;
+        highlightSearchMatches(cm, query);
+        return findNext(cm, prev/** prev */, query, motionArgs.repeat);
+      },
+      goToMark: function(_cm, motionArgs, vim) {
+        var mark = vim.marks[motionArgs.selectedCharacter];
+        if (mark) {
+          return mark.find();
+        }
+        return null;
+      },
+      jumpToMark: function(cm, motionArgs, vim) {
+        var best = cm.getCursor();
+        for (var i = 0; i < motionArgs.repeat; i++) {
+          var cursor = best;
+          for (var key in vim.marks) {
+            if (!isLowerCase(key)) {
+              continue;
+            }
+            var mark = vim.marks[key].find();
+            var isWrongDirection = (motionArgs.forward) ?
+              cursorIsBefore(mark, cursor) : cursorIsBefore(cursor, mark);
+
+            if (isWrongDirection) {
+              continue;
+            }
+            if (motionArgs.linewise && (mark.line == cursor.line)) {
+              continue;
+            }
+
+            var equal = cursorEqual(cursor, best);
+            var between = (motionArgs.forward) ?
+              cusrorIsBetween(cursor, mark, best) :
+              cusrorIsBetween(best, mark, cursor);
+
+            if (equal || between) {
+              best = mark;
+            }
+          }
+        }
+
+        if (motionArgs.linewise) {
+          // Vim places the cursor on the first non-whitespace character of
+          // the line if there is one, else it places the cursor at the end
+          // of the line, regardless of whether a mark was found.
+          best.ch = findFirstNonWhiteSpaceCharacter(cm.getLine(best.line));
+        }
+        return best;
+      },
+      moveByCharacters: function(cm, motionArgs) {
+        var cur = cm.getCursor();
+        var repeat = motionArgs.repeat;
+        var ch = motionArgs.forward ? cur.ch + repeat : cur.ch - repeat;
+        return { line: cur.line, ch: ch };
+      },
+      moveByLines: function(cm, motionArgs, vim) {
+        var cur = cm.getCursor();
+        var endCh = cur.ch;
+        // Depending what our last motion was, we may want to do different
+        // things. If our last motion was moving vertically, we want to
+        // preserve the HPos from our last horizontal move.  If our last motion
+        // was going to the end of a line, moving vertically we should go to
+        // the end of the line, etc.
+        switch (vim.lastMotion) {
+          case this.moveByLines:
+          case this.moveByDisplayLines:
+          case this.moveByScroll:
+          case this.moveToColumn:
+          case this.moveToEol:
+            endCh = vim.lastHPos;
+            break;
+          default:
+            vim.lastHPos = endCh;
+        }
+        var repeat = motionArgs.repeat+(motionArgs.repeatOffset||0);
+        var line = motionArgs.forward ? cur.line + repeat : cur.line - repeat;
+        var first = cm.firstLine();
+        var last = cm.lastLine();
+        // Vim cancels linewise motions that start on an edge and move beyond
+        // that edge. It does not cancel motions that do not start on an edge.
+        if ((line < first && cur.line == first) ||
+            (line > last && cur.line == last)) {
+          return;
+        }
+        if(motionArgs.toFirstChar){
+          endCh=findFirstNonWhiteSpaceCharacter(cm.getLine(line));
+          vim.lastHPos = endCh;
+        }
+        vim.lastHSPos = cm.charCoords({line:line, ch:endCh},'div').left;
+        return { line: line, ch: endCh };
+      },
+      moveByDisplayLines: function(cm, motionArgs, vim) {
+        var cur = cm.getCursor();
+        switch (vim.lastMotion) {
+          case this.moveByDisplayLines:
+          case this.moveByScroll:
+          case this.moveByLines:
+          case this.moveToColumn:
+          case this.moveToEol:
+            break;
+          default:
+            vim.lastHSPos = cm.charCoords(cur,'div').left;
+        }
+        var repeat = motionArgs.repeat;
+        var res=cm.findPosV(cur,(motionArgs.forward ? repeat : -repeat),'line',vim.lastHSPos);
+        if (res.hitSide) {
+          if (motionArgs.forward) {
+            var lastCharCoords = cm.charCoords(res, 'div');
+            var goalCoords = { top: lastCharCoords.top + 8, left: vim.lastHSPos };
+            var res = cm.coordsChar(goalCoords, 'div');
+          } else {
+            var resCoords = cm.charCoords({ line: cm.firstLine(), ch: 0}, 'div');
+            resCoords.left = vim.lastHSPos;
+            res = cm.coordsChar(resCoords, 'div');
+          }
+        }
+        vim.lastHPos = res.ch;
+        return res;
+      },
+      moveByPage: function(cm, motionArgs) {
+        // CodeMirror only exposes functions that move the cursor page down, so
+        // doing this bad hack to move the cursor and move it back. evalInput
+        // will move the cursor to where it should be in the end.
+        var curStart = cm.getCursor();
+        var repeat = motionArgs.repeat;
+        cm.moveV((motionArgs.forward ? repeat : -repeat), 'page');
+        var curEnd = cm.getCursor();
+        cm.setCursor(curStart);
+        return curEnd;
+      },
+      moveByParagraph: function(cm, motionArgs) {
+        var line = cm.getCursor().line;
+        var repeat = motionArgs.repeat;
+        var inc = motionArgs.forward ? 1 : -1;
+        for (var i = 0; i < repeat; i++) {
+          if ((!motionArgs.forward && line === cm.firstLine() ) ||
+              (motionArgs.forward && line == cm.lastLine())) {
+            break;
+          }
+          line += inc;
+          while (line !== cm.firstLine() && line != cm.lastLine() && cm.getLine(line)) {
+            line += inc;
+          }
+        }
+        return { line: line, ch: 0 };
+      },
+      moveByScroll: function(cm, motionArgs, vim) {
+        var scrollbox = cm.getScrollInfo();
+        var curEnd = null;
+        var repeat = motionArgs.repeat;
+        if (!repeat) {
+          repeat = scrollbox.clientHeight / (2 * cm.defaultTextHeight());
+        }
+        var orig = cm.charCoords(cm.getCursor(), 'local');
+        motionArgs.repeat = repeat;
+        var curEnd = motions.moveByDisplayLines(cm, motionArgs, vim);
+        if (!curEnd) {
+          return null;
+        }
+        var dest = cm.charCoords(curEnd, 'local');
+        cm.scrollTo(null, scrollbox.top + dest.top - orig.top);
+        return curEnd;
+      },
+      moveByWords: function(cm, motionArgs) {
+        return moveToWord(cm, motionArgs.repeat, !!motionArgs.forward,
+            !!motionArgs.wordEnd, !!motionArgs.bigWord);
+      },
+      moveTillCharacter: function(cm, motionArgs) {
+        var repeat = motionArgs.repeat;
+        var curEnd = moveToCharacter(cm, repeat, motionArgs.forward,
+            motionArgs.selectedCharacter);
+        var increment = motionArgs.forward ? -1 : 1;
+        recordLastCharacterSearch(increment, motionArgs);
+        if(!curEnd)return cm.getCursor();
+        curEnd.ch += increment;
+        return curEnd;
+      },
+      moveToCharacter: function(cm, motionArgs) {
+        var repeat = motionArgs.repeat;
+        recordLastCharacterSearch(0, motionArgs);
+        return moveToCharacter(cm, repeat, motionArgs.forward,
+            motionArgs.selectedCharacter) || cm.getCursor();
+      },
+      moveToSymbol: function(cm, motionArgs) {
+        var repeat = motionArgs.repeat;
+        return findSymbol(cm, repeat, motionArgs.forward,
+            motionArgs.selectedCharacter) || cm.getCursor();
+      },
+      moveToColumn: function(cm, motionArgs, vim) {
+        var repeat = motionArgs.repeat;
+        // repeat is equivalent to which column we want to move to!
+        vim.lastHPos = repeat - 1;
+        vim.lastHSPos = cm.charCoords(cm.getCursor(),'div').left;
+        return moveToColumn(cm, repeat);
+      },
+      moveToEol: function(cm, motionArgs, vim) {
+        var cur = cm.getCursor();
+        vim.lastHPos = Infinity;
+        var retval={ line: cur.line + motionArgs.repeat - 1, ch: Infinity };
+        var end=cm.clipPos(retval);
+        end.ch--;
+        vim.lastHSPos = cm.charCoords(end,'div').left;
+        return retval;
+      },
+      moveToFirstNonWhiteSpaceCharacter: function(cm) {
+        // Go to the start of the line where the text begins, or the end for
+        // whitespace-only lines
+        var cursor = cm.getCursor();
+        return { line: cursor.line,
+            ch: findFirstNonWhiteSpaceCharacter(cm.getLine(cursor.line)) };
+      },
+      moveToMatchedSymbol: function(cm) {
+        var cursor = cm.getCursor();
+        var line = cursor.line;
+        var ch = cursor.ch;
+        var lineText = cm.getLine(line);
+        var symbol;
+        var startContext = cm.getTokenAt(cursor).type;
+        var startCtxLevel = getContextLevel(startContext);
+        do {
+          symbol = lineText.charAt(ch++);
+          if (symbol && isMatchableSymbol(symbol)) {
+            var endContext = cm.getTokenAt({line:line, ch:ch}).type;
+            var endCtxLevel = getContextLevel(endContext);
+            if (startCtxLevel >= endCtxLevel) {
+              break;
+            }
+          }
+        } while (symbol);
+        if (symbol) {
+          return findMatchedSymbol(cm, {line:line, ch:ch-1}, symbol);
+        } else {
+          return cursor;
+        }
+      },
+      moveToStartOfLine: function(cm) {
+        var cursor = cm.getCursor();
+        return { line: cursor.line, ch: 0 };
+      },
+      moveToLineOrEdgeOfDocument: function(cm, motionArgs) {
+        var lineNum = motionArgs.forward ? cm.lastLine() : cm.firstLine();
+        if (motionArgs.repeatIsExplicit) {
+          lineNum = motionArgs.repeat - cm.getOption('firstLineNumber');
+        }
+        return { line: lineNum,
+            ch: findFirstNonWhiteSpaceCharacter(cm.getLine(lineNum)) };
+      },
+      textObjectManipulation: function(cm, motionArgs) {
+        var character = motionArgs.selectedCharacter;
+        // Inclusive is the difference between a and i
+        // TODO: Instead of using the additional text object map to perform text
+        //     object operations, merge the map into the defaultKeyMap and use
+        //     motionArgs to define behavior. Define separate entries for 'aw',
+        //     'iw', 'a[', 'i[', etc.
+        var inclusive = !motionArgs.textObjectInner;
+        if (!textObjects[character]) {
+          // No text object defined for this, don't move.
+          return null;
+        }
+        var tmp = textObjects[character](cm, inclusive);
+        var start = tmp.start;
+        var end = tmp.end;
+        return [start, end];
+      },
+      repeatLastCharacterSearch: function(cm, motionArgs) {
+        var lastSearch = vimGlobalState.lastChararacterSearch;
+        var repeat = motionArgs.repeat;
+        var forward = motionArgs.forward === lastSearch.forward;
+        var increment = (lastSearch.increment ? 1 : 0) * (forward ? -1 : 1);
+        cm.moveH(-increment, 'char');
+        motionArgs.inclusive = forward ? true : false;
+        var curEnd = moveToCharacter(cm, repeat, forward, lastSearch.selectedCharacter);
+        if (!curEnd) {
+          cm.moveH(increment, 'char');
+          return cm.getCursor();
+        }
+        curEnd.ch += increment;
+        return curEnd;
+      }
+    };
+
+    var operators = {
+      change: function(cm, operatorArgs, _vim, curStart, curEnd) {
+        vimGlobalState.registerController.pushText(
+            operatorArgs.registerName, 'change', cm.getRange(curStart, curEnd),
+            operatorArgs.linewise);
+        if (operatorArgs.linewise) {
+          // Push the next line back down, if there is a next line.
+          var replacement = curEnd.line > cm.lastLine() ? '' : '\n';
+          cm.replaceRange(replacement, curStart, curEnd);
+          cm.indentLine(curStart.line, 'smart');
+          // null ch so setCursor moves to end of line.
+          curStart.ch = null;
+        } else {
+          // Exclude trailing whitespace if the range is not all whitespace.
+          var text = cm.getRange(curStart, curEnd);
+          if (!isWhiteSpaceString(text)) {
+            var match = (/\s+$/).exec(text);
+            if (match) {
+              curEnd = offsetCursor(curEnd, 0, - match[0].length);
+            }
+          }
+          cm.replaceRange('', curStart, curEnd);
+        }
+        actions.enterInsertMode(cm, {}, cm.state.vim);
+        cm.setCursor(curStart);
+      },
+      // delete is a javascript keyword.
+      'delete': function(cm, operatorArgs, _vim, curStart, curEnd) {
+        // If the ending line is past the last line, inclusive, instead of
+        // including the trailing \n, include the \n before the starting line
+        if (operatorArgs.linewise &&
+            curEnd.line > cm.lastLine() && curStart.line > cm.firstLine()) {
+          curStart.line--;
+          curStart.ch = lineLength(cm, curStart.line);
+        }
+        vimGlobalState.registerController.pushText(
+            operatorArgs.registerName, 'delete', cm.getRange(curStart, curEnd),
+            operatorArgs.linewise);
+        cm.replaceRange('', curStart, curEnd);
+        if (operatorArgs.linewise) {
+          cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm));
+        } else {
+          cm.setCursor(curStart);
+        }
+      },
+      indent: function(cm, operatorArgs, vim, curStart, curEnd) {
+        var startLine = curStart.line;
+        var endLine = curEnd.line;
+        // In visual mode, n> shifts the selection right n times, instead of
+        // shifting n lines right once.
+        var repeat = (vim.visualMode) ? operatorArgs.repeat : 1;
+        if (operatorArgs.linewise) {
+          // The only way to delete a newline is to delete until the start of
+          // the next line, so in linewise mode evalInput will include the next
+          // line. We don't want this in indent, so we go back a line.
+          endLine--;
+        }
+        for (var i = startLine; i <= endLine; i++) {
+          for (var j = 0; j < repeat; j++) {
+            cm.indentLine(i, operatorArgs.indentRight);
+          }
+        }
+        cm.setCursor(curStart);
+        cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm));
+      },
+      swapcase: function(cm, operatorArgs, _vim, curStart, curEnd, curOriginal) {
+        var toSwap = cm.getRange(curStart, curEnd);
+        var swapped = '';
+        for (var i = 0; i < toSwap.length; i++) {
+          var character = toSwap.charAt(i);
+          swapped += isUpperCase(character) ? character.toLowerCase() :
+              character.toUpperCase();
+        }
+        cm.replaceRange(swapped, curStart, curEnd);
+        if (!operatorArgs.shouldMoveCursor) {
+          cm.setCursor(curOriginal);
+        }
+      },
+      yank: function(cm, operatorArgs, _vim, curStart, curEnd, curOriginal) {
+        vimGlobalState.registerController.pushText(
+            operatorArgs.registerName, 'yank',
+            cm.getRange(curStart, curEnd), operatorArgs.linewise);
+        cm.setCursor(curOriginal);
+      }
+    };
+
+    var actions = {
+      jumpListWalk: function(cm, actionArgs, vim) {
+        if (vim.visualMode) {
+          return;
+        }
+        var repeat = actionArgs.repeat;
+        var forward = actionArgs.forward;
+        var jumpList = vimGlobalState.jumpList;
+
+        var mark = jumpList.move(cm, forward ? repeat : -repeat);
+        var markPos = mark ? mark.find() : undefined;
+        markPos = markPos ? markPos : cm.getCursor();
+        cm.setCursor(markPos);
+      },
+      scrollToCursor: function(cm, actionArgs) {
+        var lineNum = cm.getCursor().line;
+        var charCoords = cm.charCoords({line: lineNum, ch: 0}, 'local');
+        var height = cm.getScrollInfo().clientHeight;
+        var y = charCoords.top;
+        var lineHeight = charCoords.bottom - y;
+        switch (actionArgs.position) {
+          case 'center': y = y - (height / 2) + lineHeight;
+            break;
+          case 'bottom': y = y - height + lineHeight*1.4;
+            break;
+          case 'top': y = y + lineHeight*0.4;
+            break;
+        }
+        cm.scrollTo(null, y);
+      },
+      replayMacro: function(cm, actionArgs) {
+        var registerName = actionArgs.selectedCharacter;
+        var repeat = actionArgs.repeat;
+        var macroModeState = vimGlobalState.macroModeState;
+        if (registerName == '@') {
+          registerName = macroModeState.latestRegister;
+        }
+        var keyBuffer = parseRegisterToKeyBuffer(macroModeState, registerName);
+        while(repeat--){
+          executeMacroKeyBuffer(cm, macroModeState, keyBuffer);
+        }
+      },
+      exitMacroRecordMode: function() {
+        var macroModeState = vimGlobalState.macroModeState;
+        macroModeState.toggle();
+        parseKeyBufferToRegister(macroModeState.latestRegister,
+                                 macroModeState.macroKeyBuffer);
+      },
+      enterMacroRecordMode: function(cm, actionArgs) {
+        var macroModeState = vimGlobalState.macroModeState;
+        var registerName = actionArgs.selectedCharacter;
+        macroModeState.toggle(cm, registerName);
+        emptyMacroKeyBuffer(macroModeState);
+      },
+      enterInsertMode: function(cm, actionArgs, vim) {
+        if (cm.getOption('readOnly')) { return; }
+        vim.insertMode = true;
+        vim.insertModeRepeat = actionArgs && actionArgs.repeat || 1;
+        var insertAt = (actionArgs) ? actionArgs.insertAt : null;
+        if (insertAt == 'eol') {
+          var cursor = cm.getCursor();
+          cursor = { line: cursor.line, ch: lineLength(cm, cursor.line) };
+          cm.setCursor(cursor);
+        } else if (insertAt == 'charAfter') {
+          cm.setCursor(offsetCursor(cm.getCursor(), 0, 1));
+        } else if (insertAt == 'firstNonBlank') {
+          cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm));
+        }
+        cm.setOption('keyMap', 'vim-insert');
+        if (actionArgs && actionArgs.replace) {
+          // Handle Replace-mode as a special case of insert mode.
+          cm.toggleOverwrite(true);
+          cm.setOption('keyMap', 'vim-replace');
+        } else {
+          cm.setOption('keyMap', 'vim-insert');
+        }
+        if (!vimGlobalState.macroModeState.inReplay) {
+          // Only record if not replaying.
+          cm.on('change', onChange);
+          cm.on('cursorActivity', onCursorActivity);
+          CodeMirror.on(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);
+        }
+      },
+      toggleVisualMode: function(cm, actionArgs, vim) {
+        var repeat = actionArgs.repeat;
+        var curStart = cm.getCursor();
+        var curEnd;
+        // TODO: The repeat should actually select number of characters/lines
+        //     equal to the repeat times the size of the previous visual
+        //     operation.
+        if (!vim.visualMode) {
+          cm.on('mousedown', exitVisualMode);
+          vim.visualMode = true;
+          vim.visualLine = !!actionArgs.linewise;
+          if (vim.visualLine) {
+            curStart.ch = 0;
+            curEnd = clipCursorToContent(cm, {
+              line: curStart.line + repeat - 1,
+              ch: lineLength(cm, curStart.line)
+            }, true /** includeLineBreak */);
+          } else {
+            curEnd = clipCursorToContent(cm, {
+              line: curStart.line,
+              ch: curStart.ch + repeat
+            }, true /** includeLineBreak */);
+          }
+          // Make the initial selection.
+          if (!actionArgs.repeatIsExplicit && !vim.visualLine) {
+            // This is a strange case. Here the implicit repeat is 1. The
+            // following commands lets the cursor hover over the 1 character
+            // selection.
+            cm.setCursor(curEnd);
+            cm.setSelection(curEnd, curStart);
+          } else {
+            cm.setSelection(curStart, curEnd);
+          }
+        } else {
+          curStart = cm.getCursor('anchor');
+          curEnd = cm.getCursor('head');
+          if (!vim.visualLine && actionArgs.linewise) {
+            // Shift-V pressed in characterwise visual mode. Switch to linewise
+            // visual mode instead of exiting visual mode.
+            vim.visualLine = true;
+            curStart.ch = cursorIsBefore(curStart, curEnd) ? 0 :
+                lineLength(cm, curStart.line);
+            curEnd.ch = cursorIsBefore(curStart, curEnd) ?
+                lineLength(cm, curEnd.line) : 0;
+            cm.setSelection(curStart, curEnd);
+          } else if (vim.visualLine && !actionArgs.linewise) {
+            // v pressed in linewise visual mode. Switch to characterwise visual
+            // mode instead of exiting visual mode.
+            vim.visualLine = false;
+          } else {
+            exitVisualMode(cm);
+          }
+        }
+        updateMark(cm, vim, '<', cursorIsBefore(curStart, curEnd) ? curStart
+            : curEnd);
+        updateMark(cm, vim, '>', cursorIsBefore(curStart, curEnd) ? curEnd
+            : curStart);
+      },
+      joinLines: function(cm, actionArgs, vim) {
+        var curStart, curEnd;
+        if (vim.visualMode) {
+          curStart = cm.getCursor('anchor');
+          curEnd = cm.getCursor('head');
+          curEnd.ch = lineLength(cm, curEnd.line) - 1;
+        } else {
+          // Repeat is the number of lines to join. Minimum 2 lines.
+          var repeat = Math.max(actionArgs.repeat, 2);
+          curStart = cm.getCursor();
+          curEnd = clipCursorToContent(cm, { line: curStart.line + repeat - 1,
+              ch: Infinity });
+        }
+        var finalCh = 0;
+        cm.operation(function() {
+          for (var i = curStart.line; i < curEnd.line; i++) {
+            finalCh = lineLength(cm, curStart.line);
+            var tmp = { line: curStart.line + 1,
+                ch: lineLength(cm, curStart.line + 1) };
+            var text = cm.getRange(curStart, tmp);
+            text = text.replace(/\n\s*/g, ' ');
+            cm.replaceRange(text, curStart, tmp);
+          }
+          var curFinalPos = { line: curStart.line, ch: finalCh };
+          cm.setCursor(curFinalPos);
+        });
+      },
+      newLineAndEnterInsertMode: function(cm, actionArgs, vim) {
+        vim.insertMode = true;
+        var insertAt = cm.getCursor();
+        if (insertAt.line === cm.firstLine() && !actionArgs.after) {
+          // Special case for inserting newline before start of document.
+          cm.replaceRange('\n', { line: cm.firstLine(), ch: 0 });
+          cm.setCursor(cm.firstLine(), 0);
+        } else {
+          insertAt.line = (actionArgs.after) ? insertAt.line :
+              insertAt.line - 1;
+          insertAt.ch = lineLength(cm, insertAt.line);
+          cm.setCursor(insertAt);
+          var newlineFn = CodeMirror.commands.newlineAndIndentContinueComment ||
+              CodeMirror.commands.newlineAndIndent;
+          newlineFn(cm);
+        }
+        this.enterInsertMode(cm, { repeat: actionArgs.repeat }, vim);
+      },
+      paste: function(cm, actionArgs) {
+        var cur = cm.getCursor();
+        var register = vimGlobalState.registerController.getRegister(
+            actionArgs.registerName);
+        if (!register.text) {
+          return;
+        }
+        for (var text = '', i = 0; i < actionArgs.repeat; i++) {
+          text += register.text;
+        }
+        var linewise = register.linewise;
+        if (linewise) {
+          if (actionArgs.after) {
+            // Move the newline at the end to the start instead, and paste just
+            // before the newline character of the line we are on right now.
+            text = '\n' + text.slice(0, text.length - 1);
+            cur.ch = lineLength(cm, cur.line);
+          } else {
+            cur.ch = 0;
+          }
+        } else {
+          cur.ch += actionArgs.after ? 1 : 0;
+        }
+        cm.replaceRange(text, cur);
+        // Now fine tune the cursor to where we want it.
+        var curPosFinal;
+        var idx;
+        if (linewise && actionArgs.after) {
+          curPosFinal = { line: cur.line + 1,
+              ch: findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line + 1)) };
+        } else if (linewise && !actionArgs.after) {
+          curPosFinal = { line: cur.line,
+              ch: findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line)) };
+        } else if (!linewise && actionArgs.after) {
+          idx = cm.indexFromPos(cur);
+          curPosFinal = cm.posFromIndex(idx + text.length - 1);
+        } else {
+          idx = cm.indexFromPos(cur);
+          curPosFinal = cm.posFromIndex(idx + text.length);
+        }
+        cm.setCursor(curPosFinal);
+      },
+      undo: function(cm, actionArgs) {
+        cm.operation(function() {
+          repeatFn(cm, CodeMirror.commands.undo, actionArgs.repeat)();
+          cm.setCursor(cm.getCursor('anchor'));
+        });
+      },
+      redo: function(cm, actionArgs) {
+        repeatFn(cm, CodeMirror.commands.redo, actionArgs.repeat)();
+      },
+      setRegister: function(_cm, actionArgs, vim) {
+        vim.inputState.registerName = actionArgs.selectedCharacter;
+      },
+      setMark: function(cm, actionArgs, vim) {
+        var markName = actionArgs.selectedCharacter;
+        updateMark(cm, vim, markName, cm.getCursor());
+      },
+      replace: function(cm, actionArgs, vim) {
+        var replaceWith = actionArgs.selectedCharacter;
+        var curStart = cm.getCursor();
+        var replaceTo;
+        var curEnd;
+        if(vim.visualMode){
+          curStart=cm.getCursor('start');
+          curEnd=cm.getCursor('end');
+          // workaround to catch the character under the cursor
+          //  existing workaround doesn't cover actions
+          curEnd=cm.clipPos({line: curEnd.line, ch: curEnd.ch+1});
+        }else{
+          var line = cm.getLine(curStart.line);
+          replaceTo = curStart.ch + actionArgs.repeat;
+          if (replaceTo > line.length) {
+            replaceTo=line.length;
+          }
+          curEnd = { line: curStart.line, ch: replaceTo };
+        }
+        if(replaceWith=='\n'){
+          if(!vim.visualMode) cm.replaceRange('', curStart, curEnd);
+          // special case, where vim help says to replace by just one line-break
+          (CodeMirror.commands.newlineAndIndentContinueComment || CodeMirror.commands.newlineAndIndent)(cm);
+        }else {
+          var replaceWithStr=cm.getRange(curStart, curEnd);
+          //replace all characters in range by selected, but keep linebreaks
+          replaceWithStr=replaceWithStr.replace(/[^\n]/g,replaceWith);
+          cm.replaceRange(replaceWithStr, curStart, curEnd);
+          if(vim.visualMode){
+            cm.setCursor(curStart);
+            exitVisualMode(cm);
+          }else{
+            cm.setCursor(offsetCursor(curEnd, 0, -1));
+          }
+        }
+      },
+      incrementNumberToken: function(cm, actionArgs) {
+        var cur = cm.getCursor();
+        var lineStr = cm.getLine(cur.line);
+        var re = /-?\d+/g;
+        var match;
+        var start;
+        var end;
+        var numberStr;
+        var token;
+        while ((match = re.exec(lineStr)) !== null) {
+          token = match[0];
+          start = match.index;
+          end = start + token.length;
+          if(cur.ch < end)break;
+        }
+        if(!actionArgs.backtrack && (end <= cur.ch))return;
+        if (token) {
+          var increment = actionArgs.increase ? 1 : -1;
+          var number = parseInt(token) + (increment * actionArgs.repeat);
+          var from = {ch:start, line:cur.line};
+          var to = {ch:end, line:cur.line};
+          numberStr = number.toString();
+          cm.replaceRange(numberStr, from, to);
+        } else {
+          return;
+        }
+        cm.setCursor({line: cur.line, ch: start + numberStr.length - 1});
+      },
+      repeatLastEdit: function(cm, actionArgs, vim) {
+        var lastEditInputState = vim.lastEditInputState;
+        if (!lastEditInputState) { return; }
+        var repeat = actionArgs.repeat;
+        if (repeat && actionArgs.repeatIsExplicit) {
+          vim.lastEditInputState.repeatOverride = repeat;
+        } else {
+          repeat = vim.lastEditInputState.repeatOverride || repeat;
+        }
+        repeatLastEdit(cm, vim, repeat, false /** repeatForInsert */);
+      }
+    };
+
+    var textObjects = {
+      // TODO: lots of possible exceptions that can be thrown here. Try da(
+      //     outside of a () block.
+      // TODO: implement text objects for the reverse like }. Should just be
+      //     an additional mapping after moving to the defaultKeyMap.
+      'w': function(cm, inclusive) {
+        return expandWordUnderCursor(cm, inclusive, true /** forward */,
+            false /** bigWord */);
+      },
+      'W': function(cm, inclusive) {
+        return expandWordUnderCursor(cm, inclusive,
+            true /** forward */, true /** bigWord */);
+      },
+      '{': function(cm, inclusive) {
+        return selectCompanionObject(cm, '}', inclusive);
+      },
+      '(': function(cm, inclusive) {
+        return selectCompanionObject(cm, ')', inclusive);
+      },
+      '[': function(cm, inclusive) {
+        return selectCompanionObject(cm, ']', inclusive);
+      },
+      '\'': function(cm, inclusive) {
+        return findBeginningAndEnd(cm, "'", inclusive);
+      },
+      '"': function(cm, inclusive) {
+        return findBeginningAndEnd(cm, '"', inclusive);
+      }
+    };
+
+    /*
+     * Below are miscellaneous utility functions used by vim.js
+     */
+
+    /**
+     * Clips cursor to ensure that line is within the buffer's range
+     * If includeLineBreak is true, then allow cur.ch == lineLength.
+     */
+    function clipCursorToContent(cm, cur, includeLineBreak) {
+      var line = Math.min(Math.max(cm.firstLine(), cur.line), cm.lastLine() );
+      var maxCh = lineLength(cm, line) - 1;
+      maxCh = (includeLineBreak) ? maxCh + 1 : maxCh;
+      var ch = Math.min(Math.max(0, cur.ch), maxCh);
+      return { line: line, ch: ch };
+    }
+    function copyArgs(args) {
+      var ret = {};
+      for (var prop in args) {
+        if (args.hasOwnProperty(prop)) {
+          ret[prop] = args[prop];
+        }
+      }
+      return ret;
+    }
+    function offsetCursor(cur, offsetLine, offsetCh) {
+      return { line: cur.line + offsetLine, ch: cur.ch + offsetCh };
+    }
+    function matchKeysPartial(pressed, mapped) {
+      for (var i = 0; i < pressed.length; i++) {
+        // 'character' means any character. For mark, register commads, etc.
+        if (pressed[i] != mapped[i] && mapped[i] != 'character') {
+          return false;
+        }
+      }
+      return true;
+    }
+    function repeatFn(cm, fn, repeat) {
+      return function() {
+        for (var i = 0; i < repeat; i++) {
+          fn(cm);
+        }
+      };
+    }
+    function copyCursor(cur) {
+      return { line: cur.line, ch: cur.ch };
+    }
+    function cursorEqual(cur1, cur2) {
+      return cur1.ch == cur2.ch && cur1.line == cur2.line;
+    }
+    function cursorIsBefore(cur1, cur2) {
+      if (cur1.line < cur2.line) {
+        return true;
+      }
+      if (cur1.line == cur2.line && cur1.ch < cur2.ch) {
+        return true;
+      }
+      return false;
+    }
+    function cusrorIsBetween(cur1, cur2, cur3) {
+      // returns true if cur2 is between cur1 and cur3.
+      var cur1before2 = cursorIsBefore(cur1, cur2);
+      var cur2before3 = cursorIsBefore(cur2, cur3);
+      return cur1before2 && cur2before3;
+    }
+    function lineLength(cm, lineNum) {
+      return cm.getLine(lineNum).length;
+    }
+    function reverse(s){
+      return s.split('').reverse().join('');
+    }
+    function trim(s) {
+      if (s.trim) {
+        return s.trim();
+      }
+      return s.replace(/^\s+|\s+$/g, '');
+    }
+    function escapeRegex(s) {
+      return s.replace(/([.?*+$\[\]\/\\(){}|\-])/g, '\\$1');
+    }
+
+    function exitVisualMode(cm) {
+      cm.off('mousedown', exitVisualMode);
+      var vim = cm.state.vim;
+      vim.visualMode = false;
+      vim.visualLine = false;
+      var selectionStart = cm.getCursor('anchor');
+      var selectionEnd = cm.getCursor('head');
+      if (!cursorEqual(selectionStart, selectionEnd)) {
+        // Clear the selection and set the cursor only if the selection has not
+        // already been cleared. Otherwise we risk moving the cursor somewhere
+        // it's not supposed to be.
+        cm.setCursor(clipCursorToContent(cm, selectionEnd));
+      }
+    }
+
+    // Remove any trailing newlines from the selection. For
+    // example, with the caret at the start of the last word on the line,
+    // 'dw' should word, but not the newline, while 'w' should advance the
+    // caret to the first character of the next line.
+    function clipToLine(cm, curStart, curEnd) {
+      var selection = cm.getRange(curStart, curEnd);
+      // Only clip if the selection ends with trailing newline + whitespace
+      if (/\n\s*$/.test(selection)) {
+        var lines = selection.split('\n');
+        // We know this is all whitepsace.
+        lines.pop();
+
+        // Cases:
+        // 1. Last word is an empty line - do not clip the trailing '\n'
+        // 2. Last word is not an empty line - clip the trailing '\n'
+        var line;
+        // Find the line containing the last word, and clip all whitespace up
+        // to it.
+        for (var line = lines.pop(); lines.length > 0 && line && isWhiteSpaceString(line); line = lines.pop()) {
+          curEnd.line--;
+          curEnd.ch = 0;
+        }
+        // If the last word is not an empty line, clip an additional newline
+        if (line) {
+          curEnd.line--;
+          curEnd.ch = lineLength(cm, curEnd.line);
+        } else {
+          curEnd.ch = 0;
+        }
+      }
+    }
+
+    // Expand the selection to line ends.
+    function expandSelectionToLine(_cm, curStart, curEnd) {
+      curStart.ch = 0;
+      curEnd.ch = 0;
+      curEnd.line++;
+    }
+
+    function findFirstNonWhiteSpaceCharacter(text) {
+      if (!text) {
+        return 0;
+      }
+      var firstNonWS = text.search(/\S/);
+      return firstNonWS == -1 ? text.length : firstNonWS;
+    }
+
+    function expandWordUnderCursor(cm, inclusive, _forward, bigWord, noSymbol) {
+      var cur = cm.getCursor();
+      var line = cm.getLine(cur.line);
+      var idx = cur.ch;
+
+      // Seek to first word or non-whitespace character, depending on if
+      // noSymbol is true.
+      var textAfterIdx = line.substring(idx);
+      var firstMatchedChar;
+      if (noSymbol) {
+        firstMatchedChar = textAfterIdx.search(/\w/);
+      } else {
+        firstMatchedChar = textAfterIdx.search(/\S/);
+      }
+      if (firstMatchedChar == -1) {
+        return null;
+      }
+      idx += firstMatchedChar;
+      textAfterIdx = line.substring(idx);
+      var textBeforeIdx = line.substring(0, idx);
+
+      var matchRegex;
+      // Greedy matchers for the "word" we are trying to expand.
+      if (bigWord) {
+        matchRegex = /^\S+/;
+      } else {
+        if ((/\w/).test(line.charAt(idx))) {
+          matchRegex = /^\w+/;
+        } else {
+          matchRegex = /^[^\w\s]+/;
+        }
+      }
+
+      var wordAfterRegex = matchRegex.exec(textAfterIdx);
+      var wordStart = idx;
+      var wordEnd = idx + wordAfterRegex[0].length;
+      // TODO: Find a better way to do this. It will be slow on very long lines.
+      var revTextBeforeIdx = reverse(textBeforeIdx);
+      var wordBeforeRegex = matchRegex.exec(revTextBeforeIdx);
+      if (wordBeforeRegex) {
+        wordStart -= wordBeforeRegex[0].length;
+      }
+
+      if (inclusive) {
+        // If present, trim all whitespace after word.
+        // Otherwise, trim all whitespace before word.
+        var textAfterWordEnd = line.substring(wordEnd);
+        var whitespacesAfterWord = textAfterWordEnd.match(/^\s*/)[0].length;
+        if (whitespacesAfterWord > 0) {
+          wordEnd += whitespacesAfterWord;
+        } else {
+          var revTrim = revTextBeforeIdx.length - wordStart;
+          var textBeforeWordStart = revTextBeforeIdx.substring(revTrim);
+          var whitespacesBeforeWord = textBeforeWordStart.match(/^\s*/)[0].length;
+          wordStart -= whitespacesBeforeWord;
+        }
+      }
+
+      return { start: { line: cur.line, ch: wordStart },
+        end: { line: cur.line, ch: wordEnd }};
+    }
+
+    function recordJumpPosition(cm, oldCur, newCur) {
+      if(!cursorEqual(oldCur, newCur)) {
+        vimGlobalState.jumpList.add(cm, oldCur, newCur);
+      }
+    }
+
+    function recordLastCharacterSearch(increment, args) {
+        vimGlobalState.lastChararacterSearch.increment = increment;
+        vimGlobalState.lastChararacterSearch.forward = args.forward;
+        vimGlobalState.lastChararacterSearch.selectedCharacter = args.selectedCharacter;
+    }
+
+    var symbolToMode = {
+        '(': 'bracket', ')': 'bracket', '{': 'bracket', '}': 'bracket',
+        '[': 'section', ']': 'section',
+        '*': 'comment', '/': 'comment',
+        'm': 'method', 'M': 'method',
+        '#': 'preprocess'
+    };
+    var findSymbolModes = {
+      bracket: {
+        isComplete: function(state) {
+          if (state.nextCh === state.symb) {
+            state.depth++;
+            if(state.depth >= 1)return true;
+          } else if (state.nextCh === state.reverseSymb) {
+            state.depth--;
+          }
+          return false;
+        }
+      },
+      section: {
+        init: function(state) {
+          state.curMoveThrough = true;
+          state.symb = (state.forward ? ']' : '[') === state.symb ? '{' : '}';
+        },
+        isComplete: function(state) {
+          return state.index === 0 && state.nextCh === state.symb;
+        }
+      },
+      comment: {
+        isComplete: function(state) {
+          var found = state.lastCh === '*' && state.nextCh === '/';
+          state.lastCh = state.nextCh;
+          return found;
+        }
+      },
+      // TODO: The original Vim implementation only operates on level 1 and 2.
+      // The current implementation doesn't check for code block level and
+      // therefore it operates on any levels.
+      method: {
+        init: function(state) {
+          state.symb = (state.symb === 'm' ? '{' : '}');
+          state.reverseSymb = state.symb === '{' ? '}' : '{';
+        },
+        isComplete: function(state) {
+          if(state.nextCh === state.symb)return true;
+          return false;
+        }
+      },
+      preprocess: {
+        init: function(state) {
+          state.index = 0;
+        },
+        isComplete: function(state) {
+          if (state.nextCh === '#') {
+            var token = state.lineText.match(/#(\w+)/)[1];
+            if (token === 'endif') {
+              if (state.forward && state.depth === 0) {
+                return true;
+              }
+              state.depth++;
+            } else if (token === 'if') {
+              if (!state.forward && state.depth === 0) {
+                return true;
+              }
+              state.depth--;
+            }
+            if(token === 'else' && state.depth === 0)return true;
+          }
+          return false;
+        }
+      }
+    };
+    function findSymbol(cm, repeat, forward, symb) {
+      var cur = cm.getCursor();
+      var increment = forward ? 1 : -1;
+      var endLine = forward ? cm.lineCount() : -1;
+      var curCh = cur.ch;
+      var line = cur.line;
+      var lineText = cm.getLine(line);
+      var state = {
+        lineText: lineText,
+        nextCh: lineText.charAt(curCh),
+        lastCh: null,
+        index: curCh,
+        symb: symb,
+        reverseSymb: (forward ?  { ')': '(', '}': '{' } : { '(': ')', '{': '}' })[symb],
+        forward: forward,
+        depth: 0,
+        curMoveThrough: false
+      };
+      var mode = symbolToMode[symb];
+      if(!mode)return cur;
+      var init = findSymbolModes[mode].init;
+      var isComplete = findSymbolModes[mode].isComplete;
+      if(init)init(state);
+      while (line !== endLine && repeat) {
+        state.index += increment;
+        state.nextCh = state.lineText.charAt(state.index);
+        if (!state.nextCh) {
+          line += increment;
+          state.lineText = cm.getLine(line) || '';
+          if (increment > 0) {
+            state.index = 0;
+          } else {
+            var lineLen = state.lineText.length;
+            state.index = (lineLen > 0) ? (lineLen-1) : 0;
+          }
+          state.nextCh = state.lineText.charAt(state.index);
+        }
+        if (isComplete(state)) {
+          cur.line = line;
+          cur.ch = state.index;
+          repeat--;
+        }
+      }
+      if (state.nextCh || state.curMoveThrough) {
+        return { line: line, ch: state.index };
+      }
+      return cur;
+    }
+
+    /*
+     * Returns the boundaries of the next word. If the cursor in the middle of
+     * the word, then returns the boundaries of the current word, starting at
+     * the cursor. If the cursor is at the start/end of a word, and we are going
+     * forward/backward, respectively, find the boundaries of the next word.
+     *
+     * @param {CodeMirror} cm CodeMirror object.
+     * @param {Cursor} cur The cursor position.
+     * @param {boolean} forward True to search forward. False to search
+     *     backward.
+     * @param {boolean} bigWord True if punctuation count as part of the word.
+     *     False if only [a-zA-Z0-9] characters count as part of the word.
+     * @param {boolean} emptyLineIsWord True if empty lines should be treated
+     *     as words.
+     * @return {Object{from:number, to:number, line: number}} The boundaries of
+     *     the word, or null if there are no more words.
+     */
+    function findWord(cm, cur, forward, bigWord, emptyLineIsWord) {
+      var lineNum = cur.line;
+      var pos = cur.ch;
+      var line = cm.getLine(lineNum);
+      var dir = forward ? 1 : -1;
+      var regexps = bigWord ? bigWordRegexp : wordRegexp;
+
+      if (emptyLineIsWord && line == '') {
+        lineNum += dir;
+        line = cm.getLine(lineNum);
+        if (!isLine(cm, lineNum)) {
+          return null;
+        }
+        pos = (forward) ? 0 : line.length;
+      }
+
+      while (true) {
+        if (emptyLineIsWord && line == '') {
+          return { from: 0, to: 0, line: lineNum };
+        }
+        var stop = (dir > 0) ? line.length : -1;
+        var wordStart = stop, wordEnd = stop;
+        // Find bounds of next word.
+        while (pos != stop) {
+          var foundWord = false;
+          for (var i = 0; i < regexps.length && !foundWord; ++i) {
+            if (regexps[i].test(line.charAt(pos))) {
+              wordStart = pos;
+              // Advance to end of word.
+              while (pos != stop && regexps[i].test(line.charAt(pos))) {
+                pos += dir;
+              }
+              wordEnd = pos;
+              foundWord = wordStart != wordEnd;
+              if (wordStart == cur.ch && lineNum == cur.line &&
+                  wordEnd == wordStart + dir) {
+                // We started at the end of a word. Find the next one.
+                continue;
+              } else {
+                return {
+                  from: Math.min(wordStart, wordEnd + 1),
+                  to: Math.max(wordStart, wordEnd),
+                  line: lineNum };
+              }
+            }
+          }
+          if (!foundWord) {
+            pos += dir;
+          }
+        }
+        // Advance to next/prev line.
+        lineNum += dir;
+        if (!isLine(cm, lineNum)) {
+          return null;
+        }
+        line = cm.getLine(lineNum);
+        pos = (dir > 0) ? 0 : line.length;
+      }
+      // Should never get here.
+      throw new Error('The impossible happened.');
+    }
+
+    /**
+     * @param {CodeMirror} cm CodeMirror object.
+     * @param {int} repeat Number of words to move past.
+     * @param {boolean} forward True to search forward. False to search
+     *     backward.
+     * @param {boolean} wordEnd True to move to end of word. False to move to
+     *     beginning of word.
+     * @param {boolean} bigWord True if punctuation count as part of the word.
+     *     False if only alphabet characters count as part of the word.
+     * @return {Cursor} The position the cursor should move to.
+     */
+    function moveToWord(cm, repeat, forward, wordEnd, bigWord) {
+      var cur = cm.getCursor();
+      var curStart = copyCursor(cur);
+      var words = [];
+      if (forward && !wordEnd || !forward && wordEnd) {
+        repeat++;
+      }
+      // For 'e', empty lines are not considered words, go figure.
+      var emptyLineIsWord = !(forward && wordEnd);
+      for (var i = 0; i < repeat; i++) {
+        var word = findWord(cm, cur, forward, bigWord, emptyLineIsWord);
+        if (!word) {
+          var eodCh = lineLength(cm, cm.lastLine());
+          words.push(forward
+              ? {line: cm.lastLine(), from: eodCh, to: eodCh}
+              : {line: 0, from: 0, to: 0});
+          break;
+        }
+        words.push(word);
+        cur = {line: word.line, ch: forward ? (word.to - 1) : word.from};
+      }
+      var shortCircuit = words.length != repeat;
+      var firstWord = words[0];
+      var lastWord = words.pop();
+      if (forward && !wordEnd) {
+        // w
+        if (!shortCircuit && (firstWord.from != curStart.ch || firstWord.line != curStart.line)) {
+          // We did not start in the middle of a word. Discard the extra word at the end.
+          lastWord = words.pop();
+        }
+        return {line: lastWord.line, ch: lastWord.from};
+      } else if (forward && wordEnd) {
+        return {line: lastWord.line, ch: lastWord.to - 1};
+      } else if (!forward && wordEnd) {
+        // ge
+        if (!shortCircuit && (firstWord.to != curStart.ch || firstWord.line != curStart.line)) {
+          // We did not start in the middle of a word. Discard the extra word at the end.
+          lastWord = words.pop();
+        }
+        return {line: lastWord.line, ch: lastWord.to};
+      } else {
+        // b
+        return {line: lastWord.line, ch: lastWord.from};
+      }
+    }
+
+    function moveToCharacter(cm, repeat, forward, character) {
+      var cur = cm.getCursor();
+      var start = cur.ch;
+      var idx;
+      for (var i = 0; i < repeat; i ++) {
+        var line = cm.getLine(cur.line);
+        idx = charIdxInLine(start, line, character, forward, true);
+        if (idx == -1) {
+          return null;
+        }
+        start = idx;
+      }
+      return { line: cm.getCursor().line, ch: idx };
+    }
+
+    function moveToColumn(cm, repeat) {
+      // repeat is always >= 1, so repeat - 1 always corresponds
+      // to the column we want to go to.
+      var line = cm.getCursor().line;
+      return clipCursorToContent(cm, { line: line, ch: repeat - 1 });
+    }
+
+    function updateMark(cm, vim, markName, pos) {
+      if (!inArray(markName, validMarks)) {
+        return;
+      }
+      if (vim.marks[markName]) {
+        vim.marks[markName].clear();
+      }
+      vim.marks[markName] = cm.setBookmark(pos);
+    }
+
+    function charIdxInLine(start, line, character, forward, includeChar) {
+      // Search for char in line.
+      // motion_options: {forward, includeChar}
+      // If includeChar = true, include it too.
+      // If forward = true, search forward, else search backwards.
+      // If char is not found on this line, do nothing
+      var idx;
+      if (forward) {
+        idx = line.indexOf(character, start + 1);
+        if (idx != -1 && !includeChar) {
+          idx -= 1;
+        }
+      } else {
+        idx = line.lastIndexOf(character, start - 1);
+        if (idx != -1 && !includeChar) {
+          idx += 1;
+        }
+      }
+      return idx;
+    }
+
+    function getContextLevel(ctx) {
+      return (ctx === 'string' || ctx === 'comment') ? 1 : 0;
+    }
+
+    function findMatchedSymbol(cm, cur, symb) {
+      var line = cur.line;
+      var ch = cur.ch;
+      symb = symb ? symb : cm.getLine(line).charAt(ch);
+
+      var symbContext = cm.getTokenAt({line:line, ch:ch+1}).type;
+      var symbCtxLevel = getContextLevel(symbContext);
+
+      var reverseSymb = ({
+        '(': ')', ')': '(',
+        '[': ']', ']': '[',
+        '{': '}', '}': '{'})[symb];
+
+      // Couldn't find a matching symbol, abort
+      if (!reverseSymb) {
+        return cur;
+      }
+
+      // set our increment to move forward (+1) or backwards (-1)
+      // depending on which bracket we're matching
+      var increment = ({'(': 1, '{': 1, '[': 1})[symb] || -1;
+      var endLine = increment === 1 ? cm.lineCount() : -1;
+      var depth = 1, nextCh = symb, index = ch, lineText = cm.getLine(line);
+      // Simple search for closing paren--just count openings and closings till
+      // we find our match
+      // TODO: use info from CodeMirror to ignore closing brackets in comments
+      // and quotes, etc.
+      while (line !== endLine && depth > 0) {
+        index += increment;
+        nextCh = lineText.charAt(index);
+        if (!nextCh) {
+          line += increment;
+          lineText = cm.getLine(line) || '';
+          if (increment > 0) {
+            index = 0;
+          } else {
+            var lineLen = lineText.length;
+            index = (lineLen > 0) ? (lineLen-1) : 0;
+          }
+          nextCh = lineText.charAt(index);
+        }
+        var revSymbContext = cm.getTokenAt({line:line, ch:index+1}).type;
+        var revSymbCtxLevel = getContextLevel(revSymbContext);
+        if (symbCtxLevel >= revSymbCtxLevel) {
+          if (nextCh === symb) {
+            depth++;
+          } else if (nextCh === reverseSymb) {
+            depth--;
+          }
+        }
+      }
+
+      if (nextCh) {
+        return { line: line, ch: index };
+      }
+      return cur;
+    }
+
+    function selectCompanionObject(cm, revSymb, inclusive) {
+      var cur = cm.getCursor();
+
+      var end = findMatchedSymbol(cm, cur, revSymb);
+      var start = findMatchedSymbol(cm, end);
+      start.ch += inclusive ? 1 : 0;
+      end.ch += inclusive ? 0 : 1;
+
+      return { start: start, end: end };
+    }
+
+    // Takes in a symbol and a cursor and tries to simulate text objects that
+    // have identical opening and closing symbols
+    // TODO support across multiple lines
+    function findBeginningAndEnd(cm, symb, inclusive) {
+      var cur = cm.getCursor();
+      var line = cm.getLine(cur.line);
+      var chars = line.split('');
+      var start, end, i, len;
+      var firstIndex = chars.indexOf(symb);
+
+      // the decision tree is to always look backwards for the beginning first,
+      // but if the cursor is in front of the first instance of the symb,
+      // then move the cursor forward
+      if (cur.ch < firstIndex) {
+        cur.ch = firstIndex;
+        // Why is this line even here???
+        // cm.setCursor(cur.line, firstIndex+1);
+      }
+      // otherwise if the cursor is currently on the closing symbol
+      else if (firstIndex < cur.ch && chars[cur.ch] == symb) {
+        end = cur.ch; // assign end to the current cursor
+        --cur.ch; // make sure to look backwards
+      }
+
+      // if we're currently on the symbol, we've got a start
+      if (chars[cur.ch] == symb && !end) {
+        start = cur.ch + 1; // assign start to ahead of the cursor
+      } else {
+        // go backwards to find the start
+        for (i = cur.ch; i > -1 && !start; i--) {
+          if (chars[i] == symb) {
+            start = i + 1;
+          }
+        }
+      }
+
+      // look forwards for the end symbol
+      if (start && !end) {
+        for (i = start, len = chars.length; i < len && !end; i++) {
+          if (chars[i] == symb) {
+            end = i;
+          }
+        }
+      }
+
+      // nothing found
+      if (!start || !end) {
+        return { start: cur, end: cur };
+      }
+
+      // include the symbols
+      if (inclusive) {
+        --start; ++end;
+      }
+
+      return {
+        start: { line: cur.line, ch: start },
+        end: { line: cur.line, ch: end }
+      };
+    }
+
+    // Search functions
+    function SearchState() {}
+    SearchState.prototype = {
+      getQuery: function() {
+        return vimGlobalState.query;
+      },
+      setQuery: function(query) {
+        vimGlobalState.query = query;
+      },
+      getOverlay: function() {
+        return this.searchOverlay;
+      },
+      setOverlay: function(overlay) {
+        this.searchOverlay = overlay;
+      },
+      isReversed: function() {
+        return vimGlobalState.isReversed;
+      },
+      setReversed: function(reversed) {
+        vimGlobalState.isReversed = reversed;
+      }
+    };
+    function getSearchState(cm) {
+      var vim = cm.state.vim;
+      return vim.searchState_ || (vim.searchState_ = new SearchState());
+    }
+    function dialog(cm, template, shortText, onClose, options) {
+      if (cm.openDialog) {
+        cm.openDialog(template, onClose, { bottom: true, value: options.value,
+            onKeyDown: options.onKeyDown, onKeyUp: options.onKeyUp });
+      }
+      else {
+        onClose(prompt(shortText, ''));
+      }
+    }
+
+    function findUnescapedSlashes(str) {
+      var escapeNextChar = false;
+      var slashes = [];
+      for (var i = 0; i < str.length; i++) {
+        var c = str.charAt(i);
+        if (!escapeNextChar && c == '/') {
+          slashes.push(i);
+        }
+        escapeNextChar = (c == '\\');
+      }
+      return slashes;
+    }
+    /**
+     * Extract the regular expression from the query and return a Regexp object.
+     * Returns null if the query is blank.
+     * If ignoreCase is passed in, the Regexp object will have the 'i' flag set.
+     * If smartCase is passed in, and the query contains upper case letters,
+     *   then ignoreCase is overridden, and the 'i' flag will not be set.
+     * If the query contains the /i in the flag part of the regular expression,
+     *   then both ignoreCase and smartCase are ignored, and 'i' will be passed
+     *   through to the Regex object.
+     */
+    function parseQuery(query, ignoreCase, smartCase) {
+      // Check if the query is already a regex.
+      if (query instanceof RegExp) { return query; }
+      // First try to extract regex + flags from the input. If no flags found,
+      // extract just the regex. IE does not accept flags directly defined in
+      // the regex string in the form /regex/flags
+      var slashes = findUnescapedSlashes(query);
+      var regexPart;
+      var forceIgnoreCase;
+      if (!slashes.length) {
+        // Query looks like 'regexp'
+        regexPart = query;
+      } else {
+        // Query looks like 'regexp/...'
+        regexPart = query.substring(0, slashes[0]);
+        var flagsPart = query.substring(slashes[0]);
+        forceIgnoreCase = (flagsPart.indexOf('i') != -1);
+      }
+      if (!regexPart) {
+        return null;
+      }
+      if (smartCase) {
+        ignoreCase = (/^[^A-Z]*$/).test(regexPart);
+      }
+      var regexp = new RegExp(regexPart,
+          (ignoreCase || forceIgnoreCase) ? 'i' : undefined);
+      return regexp;
+    }
+    function showConfirm(cm, text) {
+      if (cm.openConfirm) {
+        cm.openConfirm('<span style="color: red">' + text +
+            '</span> <button type="button">OK</button>', function() {},
+            {bottom: true});
+      } else {
+        alert(text);
+      }
+    }
+    function makePrompt(prefix, desc) {
+      var raw = '';
+      if (prefix) {
+        raw += '<span style="font-family: monospace">' + prefix + '</span>';
+      }
+      raw += '<input type="text"/> ' +
+          '<span style="color: #888">';
+      if (desc) {
+        raw += '<span style="color: #888">';
+        raw += desc;
+        raw += '</span>';
+      }
+      return raw;
+    }
+    var searchPromptDesc = '(Javascript regexp)';
+    function showPrompt(cm, options) {
+      var shortText = (options.prefix || '') + ' ' + (options.desc || '');
+      var prompt = makePrompt(options.prefix, options.desc);
+      dialog(cm, prompt, shortText, options.onClose, options);
+    }
+    function regexEqual(r1, r2) {
+      if (r1 instanceof RegExp && r2 instanceof RegExp) {
+          var props = ['global', 'multiline', 'ignoreCase', 'source'];
+          for (var i = 0; i < props.length; i++) {
+              var prop = props[i];
+              if (r1[prop] !== r2[prop]) {
+                  return false;
+              }
+          }
+          return true;
+      }
+      return false;
+    }
+    // Returns true if the query is valid.
+    function updateSearchQuery(cm, rawQuery, ignoreCase, smartCase) {
+      if (!rawQuery) {
+        return;
+      }
+      var state = getSearchState(cm);
+      var query = parseQuery(rawQuery, !!ignoreCase, !!smartCase);
+      if (!query) {
+        return;
+      }
+      highlightSearchMatches(cm, query);
+      if (regexEqual(query, state.getQuery())) {
+        return query;
+      }
+      state.setQuery(query);
+      return query;
+    }
+    function searchOverlay(query) {
+      if (query.source.charAt(0) == '^') {
+        var matchSol = true;
+      }
+      return {
+        token: function(stream) {
+          if (matchSol && !stream.sol()) {
+            stream.skipToEnd();
+            return;
+          }
+          var match = stream.match(query, false);
+          if (match) {
+            if (match[0].length == 0) {
+              // Matched empty string, skip to next.
+              stream.next();
+              return 'searching';
+            }
+            if (!stream.sol()) {
+              // Backtrack 1 to match \b
+              stream.backUp(1);
+              if (!query.exec(stream.next() + match[0])) {
+                stream.next();
+                return null;
+              }
+            }
+            stream.match(query);
+            return 'searching';
+          }
+          while (!stream.eol()) {
+            stream.next();
+            if (stream.match(query, false)) break;
+          }
+        },
+        query: query
+      };
+    }
+    function highlightSearchMatches(cm, query) {
+      var overlay = getSearchState(cm).getOverlay();
+      if (!overlay || query != overlay.query) {
+        if (overlay) {
+          cm.removeOverlay(overlay);
+        }
+        overlay = searchOverlay(query);
+        cm.addOverlay(overlay);
+        getSearchState(cm).setOverlay(overlay);
+      }
+    }
+    function findNext(cm, prev, query, repeat) {
+      if (repeat === undefined) { repeat = 1; }
+      return cm.operation(function() {
+        var pos = cm.getCursor();
+        var cursor = cm.getSearchCursor(query, pos);
+        for (var i = 0; i < repeat; i++) {
+          var found = cursor.find(prev);
+          if (i == 0 && found && cursorEqual(cursor.from(), pos)) { found = cursor.find(prev); }
+          if (!found) {
+            // SearchCursor may have returned null because it hit EOF, wrap
+            // around and try again.
+            cursor = cm.getSearchCursor(query,
+                (prev) ? { line: cm.lastLine() } : {line: cm.firstLine(), ch: 0} );
+            if (!cursor.find(prev)) {
+              return;
+            }
+          }
+        }
+        return cursor.from();
+      });
+    }
+    function clearSearchHighlight(cm) {
+      cm.removeOverlay(getSearchState(cm).getOverlay());
+      getSearchState(cm).setOverlay(null);
+    }
+    /**
+     * Check if pos is in the specified range, INCLUSIVE.
+     * Range can be specified with 1 or 2 arguments.
+     * If the first range argument is an array, treat it as an array of line
+     * numbers. Match pos against any of the lines.
+     * If the first range argument is a number,
+     *   if there is only 1 range argument, check if pos has the same line
+     *       number
+     *   if there are 2 range arguments, then check if pos is in between the two
+     *       range arguments.
+     */
+    function isInRange(pos, start, end) {
+      if (typeof pos != 'number') {
+        // Assume it is a cursor position. Get the line number.
+        pos = pos.line;
+      }
+      if (start instanceof Array) {
+        return inArray(pos, start);
+      } else {
+        if (end) {
+          return (pos >= start && pos <= end);
+        } else {
+          return pos == start;
+        }
+      }
+    }
+    function getUserVisibleLines(cm) {
+      var scrollInfo = cm.getScrollInfo();
+      var occludeToleranceTop = 6;
+      var occludeToleranceBottom = 10;
+      var from = cm.coordsChar({left:0, top: occludeToleranceTop + scrollInfo.top}, 'local');
+      var bottomY = scrollInfo.clientHeight - occludeToleranceBottom + scrollInfo.top;
+      var to = cm.coordsChar({left:0, top: bottomY}, 'local');
+      return {top: from.line, bottom: to.line};
+    }
+
+    // Ex command handling
+    // Care must be taken when adding to the default Ex command map. For any
+    // pair of commands that have a shared prefix, at least one of their
+    // shortNames must not match the prefix of the other command.
+    var defaultExCommandMap = [
+      { name: 'map', type: 'builtIn' },
+      { name: 'write', shortName: 'w', type: 'builtIn' },
+      { name: 'undo', shortName: 'u', type: 'builtIn' },
+      { name: 'redo', shortName: 'red', type: 'builtIn' },
+      { name: 'sort', shortName: 'sor', type: 'builtIn'},
+      { name: 'substitute', shortName: 's', type: 'builtIn'},
+      { name: 'nohlsearch', shortName: 'noh', type: 'builtIn'},
+      { name: 'delmarks', shortName: 'delm', type: 'builtin'}
+    ];
+    Vim.ExCommandDispatcher = function() {
+      this.buildCommandMap_();
+    };
+    Vim.ExCommandDispatcher.prototype = {
+      processCommand: function(cm, input) {
+        var vim = cm.state.vim;
+        if (vim.visualMode) {
+          exitVisualMode(cm);
+        }
+        var inputStream = new CodeMirror.StringStream(input);
+        var params = {};
+        params.input = input;
+        try {
+          this.parseInput_(cm, inputStream, params);
+        } catch(e) {
+          showConfirm(cm, e);
+          return;
+        }
+        var commandName;
+        if (!params.commandName) {
+          // If only a line range is defined, move to the line.
+          if (params.line !== undefined) {
+            commandName = 'move';
+          }
+        } else {
+          var command = this.matchCommand_(params.commandName);
+          if (command) {
+            commandName = command.name;
+            this.parseCommandArgs_(inputStream, params, command);
+            if (command.type == 'exToKey') {
+              // Handle Ex to Key mapping.
+              for (var i = 0; i < command.toKeys.length; i++) {
+                CodeMirror.Vim.handleKey(cm, command.toKeys[i]);
+              }
+              return;
+            } else if (command.type == 'exToEx') {
+              // Handle Ex to Ex mapping.
+              this.processCommand(cm, command.toInput);
+              return;
+            }
+          }
+        }
+        if (!commandName) {
+          showConfirm(cm, 'Not an editor command ":' + input + '"');
+          return;
+        }
+        try {
+          exCommands[commandName](cm, params);
+        } catch(e) {
+          showConfirm(cm, e);
+        }
+      },
+      parseInput_: function(cm, inputStream, result) {
+        inputStream.eatWhile(':');
+        // Parse range.
+        if (inputStream.eat('%')) {
+          result.line = cm.firstLine();
+          result.lineEnd = cm.lastLine();
+        } else {
+          result.line = this.parseLineSpec_(cm, inputStream);
+          if (result.line !== undefined && inputStream.eat(',')) {
+            result.lineEnd = this.parseLineSpec_(cm, inputStream);
+          }
+        }
+
+        // Parse command name.
+        var commandMatch = inputStream.match(/^(\w+)/);
+        if (commandMatch) {
+          result.commandName = commandMatch[1];
+        } else {
+          result.commandName = inputStream.match(/.*/)[0];
+        }
+
+        return result;
+      },
+      parseLineSpec_: function(cm, inputStream) {
+        var numberMatch = inputStream.match(/^(\d+)/);
+        if (numberMatch) {
+          return parseInt(numberMatch[1], 10) - 1;
+        }
+        switch (inputStream.next()) {
+          case '.':
+            return cm.getCursor().line;
+          case '$':
+            return cm.lastLine();
+          case '\'':
+            var mark = cm.state.vim.marks[inputStream.next()];
+            if (mark && mark.find()) {
+              return mark.find().line;
+            }
+            throw new Error('Mark not set');
+          default:
+            inputStream.backUp(1);
+            return undefined;
+        }
+      },
+      parseCommandArgs_: function(inputStream, params, command) {
+        if (inputStream.eol()) {
+          return;
+        }
+        params.argString = inputStream.match(/.*/)[0];
+        // Parse command-line arguments
+        var delim = command.argDelimiter || /\s+/;
+        var args = trim(params.argString).split(delim);
+        if (args.length && args[0]) {
+          params.args = args;
+        }
+      },
+      matchCommand_: function(commandName) {
+        // Return the command in the command map that matches the shortest
+        // prefix of the passed in command name. The match is guaranteed to be
+        // unambiguous if the defaultExCommandMap's shortNames are set up
+        // correctly. (see @code{defaultExCommandMap}).
+        for (var i = commandName.length; i > 0; i--) {
+          var prefix = commandName.substring(0, i);
+          if (this.commandMap_[prefix]) {
+            var command = this.commandMap_[prefix];
+            if (command.name.indexOf(commandName) === 0) {
+              return command;
+            }
+          }
+        }
+        return null;
+      },
+      buildCommandMap_: function() {
+        this.commandMap_ = {};
+        for (var i = 0; i < defaultExCommandMap.length; i++) {
+          var command = defaultExCommandMap[i];
+          var key = command.shortName || command.name;
+          this.commandMap_[key] = command;
+        }
+      },
+      map: function(lhs, rhs) {
+        if (lhs != ':' && lhs.charAt(0) == ':') {
+          var commandName = lhs.substring(1);
+          if (rhs != ':' && rhs.charAt(0) == ':') {
+            // Ex to Ex mapping
+            this.commandMap_[commandName] = {
+              name: commandName,
+              type: 'exToEx',
+              toInput: rhs.substring(1)
+            };
+          } else {
+            // Ex to key mapping
+            this.commandMap_[commandName] = {
+              name: commandName,
+              type: 'exToKey',
+              toKeys: parseKeyString(rhs)
+            };
+          }
+        } else {
+          if (rhs != ':' && rhs.charAt(0) == ':') {
+            // Key to Ex mapping.
+            defaultKeymap.unshift({
+              keys: parseKeyString(lhs),
+              type: 'keyToEx',
+              exArgs: { input: rhs.substring(1) }});
+          } else {
+            // Key to key mapping
+            defaultKeymap.unshift({
+              keys: parseKeyString(lhs),
+              type: 'keyToKey',
+              toKeys: parseKeyString(rhs)
+            });
+          }
+        }
+      }
+    };
+
+    // Converts a key string sequence of the form a<C-w>bd<Left> into Vim's
+    // keymap representation.
+    function parseKeyString(str) {
+      var key, match;
+      var keys = [];
+      while (str) {
+        match = (/<\w+-.+?>|<\w+>|./).exec(str);
+        if(match === null)break;
+        key = match[0];
+        str = str.substring(match.index + key.length);
+        keys.push(key);
+      }
+      return keys;
+    }
+
+    var exCommands = {
+      map: function(cm, params) {
+        var mapArgs = params.args;
+        if (!mapArgs || mapArgs.length < 2) {
+          if (cm) {
+            showConfirm(cm, 'Invalid mapping: ' + params.input);
+          }
+          return;
+        }
+        exCommandDispatcher.map(mapArgs[0], mapArgs[1], cm);
+      },
+      move: function(cm, params) {
+        commandDispatcher.processCommand(cm, cm.state.vim, {
+            type: 'motion',
+            motion: 'moveToLineOrEdgeOfDocument',
+            motionArgs: { forward: false, explicitRepeat: true,
+              linewise: true },
+            repeatOverride: params.line+1});
+      },
+      sort: function(cm, params) {
+        var reverse, ignoreCase, unique, number;
+        function parseArgs() {
+          if (params.argString) {
+            var args = new CodeMirror.StringStream(params.argString);
+            if (args.eat('!')) { reverse = true; }
+            if (args.eol()) { return; }
+            if (!args.eatSpace()) { throw new Error('invalid arguments ' + args.match(/.*/)[0]); }
+            var opts = args.match(/[a-z]+/);
+            if (opts) {
+              opts = opts[0];
+              ignoreCase = opts.indexOf('i') != -1;
+              unique = opts.indexOf('u') != -1;
+              var decimal = opts.indexOf('d') != -1 && 1;
+              var hex = opts.indexOf('x') != -1 && 1;
+              var octal = opts.indexOf('o') != -1 && 1;
+              if (decimal + hex + octal > 1) { throw new Error('invalid arguments'); }
+              number = decimal && 'decimal' || hex && 'hex' || octal && 'octal';
+            }
+            if (args.eatSpace() && args.match(/\/.*\//)) { throw new Error('patterns not supported'); }
+          }
+        }
+        parseArgs();
+        var lineStart = params.line || cm.firstLine();
+        var lineEnd = params.lineEnd || params.line || cm.lastLine();
+        if (lineStart == lineEnd) { return; }
+        var curStart = { line: lineStart, ch: 0 };
+        var curEnd = { line: lineEnd, ch: lineLength(cm, lineEnd) };
+        var text = cm.getRange(curStart, curEnd).split('\n');
+        var numberRegex = (number == 'decimal') ? /(-?)([\d]+)/ :
+           (number == 'hex') ? /(-?)(?:0x)?([0-9a-f]+)/i :
+           (number == 'octal') ? /([0-7]+)/ : null;
+        var radix = (number == 'decimal') ? 10 : (number == 'hex') ? 16 : (number == 'octal') ? 8 : null;
+        var numPart = [], textPart = [];
+        if (number) {
+          for (var i = 0; i < text.length; i++) {
+            if (numberRegex.exec(text[i])) {
+              numPart.push(text[i]);
+            } else {
+              textPart.push(text[i]);
+            }
+          }
+        } else {
+          textPart = text;
+        }
+        function compareFn(a, b) {
+          if (reverse) { var tmp; tmp = a; a = b; b = tmp; }
+          if (ignoreCase) { a = a.toLowerCase(); b = b.toLowerCase(); }
+          var anum = number && numberRegex.exec(a);
+          var bnum = number && numberRegex.exec(b);
+          if (!anum) { return a < b ? -1 : 1; }
+          anum = parseInt((anum[1] + anum[2]).toLowerCase(), radix);
+          bnum = parseInt((bnum[1] + bnum[2]).toLowerCase(), radix);
+          return anum - bnum;
+        }
+        numPart.sort(compareFn);
+        textPart.sort(compareFn);
+        text = (!reverse) ? textPart.concat(numPart) : numPart.concat(textPart);
+        if (unique) { // Remove duplicate lines
+          var textOld = text;
+          var lastLine;
+          text = [];
+          for (var i = 0; i < textOld.length; i++) {
+            if (textOld[i] != lastLine) {
+              text.push(textOld[i]);
+            }
+            lastLine = textOld[i];
+          }
+        }
+        cm.replaceRange(text.join('\n'), curStart, curEnd);
+      },
+      substitute: function(cm, params) {
+        if (!cm.getSearchCursor) {
+          throw new Error('Search feature not available. Requires searchcursor.js or ' +
+              'any other getSearchCursor implementation.');
+        }
+        var argString = params.argString;
+        var slashes = findUnescapedSlashes(argString);
+        if (slashes[0] !== 0) {
+          showConfirm(cm, 'Substitutions should be of the form ' +
+              ':s/pattern/replace/');
+          return;
+        }
+        var regexPart = argString.substring(slashes[0] + 1, slashes[1]);
+        var replacePart = '';
+        var flagsPart;
+        var count;
+        var confirm = false; // Whether to confirm each replace.
+        if (slashes[1]) {
+          replacePart = argString.substring(slashes[1] + 1, slashes[2]);
+        }
+        if (slashes[2]) {
+          // After the 3rd slash, we can have flags followed by a space followed
+          // by count.
+          var trailing = argString.substring(slashes[2] + 1).split(' ');
+          flagsPart = trailing[0];
+          count = parseInt(trailing[1]);
+        }
+        if (flagsPart) {
+          if (flagsPart.indexOf('c') != -1) {
+            confirm = true;
+            flagsPart.replace('c', '');
+          }
+          regexPart = regexPart + '/' + flagsPart;
+        }
+        if (regexPart) {
+          // If regex part is empty, then use the previous query. Otherwise use
+          // the regex part as the new query.
+          try {
+            updateSearchQuery(cm, regexPart, true /** ignoreCase */,
+              true /** smartCase */);
+          } catch (e) {
+            showConfirm(cm, 'Invalid regex: ' + regexPart);
+            return;
+          }
+        }
+        var state = getSearchState(cm);
+        var query = state.getQuery();
+        var lineStart = (params.line !== undefined) ? params.line : cm.getCursor().line;
+        var lineEnd = params.lineEnd || lineStart;
+        if (count) {
+          lineStart = lineEnd;
+          lineEnd = lineStart + count - 1;
+        }
+        var startPos = clipCursorToContent(cm, { line: lineStart, ch: 0 });
+        var cursor = cm.getSearchCursor(query, startPos);
+        doReplace(cm, confirm, lineStart, lineEnd, cursor, query, replacePart);
+      },
+      redo: CodeMirror.commands.redo,
+      undo: CodeMirror.commands.undo,
+      write: function(cm) {
+        if (CodeMirror.commands.save) {
+          // If a save command is defined, call it.
+          CodeMirror.commands.save(cm);
+        } else {
+          // Saves to text area if no save command is defined.
+          cm.save();
+        }
+      },
+      nohlsearch: function(cm) {
+        clearSearchHighlight(cm);
+      },
+      delmarks: function(cm, params) {
+        if (!params.argString || !params.argString.trim()) {
+          showConfirm(cm, 'Argument required');
+          return;
+        }
+
+        var state = cm.state.vim;
+        var stream = new CodeMirror.StringStream(params.argString.trim());
+        while (!stream.eol()) {
+          stream.eatSpace();
+
+          // Record the streams position at the beginning of the loop for use
+          // in error messages.
+          var count = stream.pos;
+
+          if (!stream.match(/[a-zA-Z]/, false)) {
+            showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
+            return;
+          }
+
+          var sym = stream.next();
+          // Check if this symbol is part of a range
+          if (stream.match('-', true)) {
+            // This symbol is part of a range.
+
+            // The range must terminate at an alphabetic character.
+            if (!stream.match(/[a-zA-Z]/, false)) {
+              showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
+              return;
+            }
+
+            var startMark = sym;
+            var finishMark = stream.next();
+            // The range must terminate at an alphabetic character which
+            // shares the same case as the start of the range.
+            if (isLowerCase(startMark) && isLowerCase(finishMark) ||
+                isUpperCase(startMark) && isUpperCase(finishMark)) {
+              var start = startMark.charCodeAt(0);
+              var finish = finishMark.charCodeAt(0);
+              if (start >= finish) {
+                showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
+                return;
+              }
+
+              // Because marks are always ASCII values, and we have
+              // determined that they are the same case, we can use
+              // their char codes to iterate through the defined range.
+              for (var j = 0; j <= finish - start; j++) {
+                var mark = String.fromCharCode(start + j);
+                delete state.marks[mark];
+              }
+            } else {
+              showConfirm(cm, 'Invalid argument: ' + startMark + '-');
+              return;
+            }
+          } else {
+            // This symbol is a valid mark, and is not part of a range.
+            delete state.marks[sym];
+          }
+        }
+      }
+    };
+
+    var exCommandDispatcher = new Vim.ExCommandDispatcher();
+
+    /**
+    * @param {CodeMirror} cm CodeMirror instance we are in.
+    * @param {boolean} confirm Whether to confirm each replace.
+    * @param {Cursor} lineStart Line to start replacing from.
+    * @param {Cursor} lineEnd Line to stop replacing at.
+    * @param {RegExp} query Query for performing matches with.
+    * @param {string} replaceWith Text to replace matches with. May contain $1,
+    *     $2, etc for replacing captured groups using Javascript replace.
+    */
+    function doReplace(cm, confirm, lineStart, lineEnd, searchCursor, query,
+        replaceWith) {
+      // Set up all the functions.
+      cm.state.vim.exMode = true;
+      var done = false;
+      var lastPos = searchCursor.from();
+      function replaceAll() {
+        cm.operation(function() {
+          while (!done) {
+            replace();
+            next();
+          }
+          stop();
+        });
+      }
+      function replace() {
+        var text = cm.getRange(searchCursor.from(), searchCursor.to());
+        var newText = text.replace(query, replaceWith);
+        searchCursor.replace(newText);
+      }
+      function next() {
+        var found = searchCursor.findNext();
+        if (!found) {
+          done = true;
+        } else if (isInRange(searchCursor.from(), lineStart, lineEnd)) {
+          cm.scrollIntoView(searchCursor.from(), 30);
+          cm.setSelection(searchCursor.from(), searchCursor.to());
+          lastPos = searchCursor.from();
+          done = false;
+        } else {
+          done = true;
+        }
+      }
+      function stop(close) {
+        if (close) { close(); }
+        cm.focus();
+        if (lastPos) {
+          cm.setCursor(lastPos);
+          var vim = cm.state.vim;
+          vim.exMode = false;
+          vim.lastHPos = vim.lastHSPos = lastPos.ch;
+        }
+      }
+      function onPromptKeyDown(e, _value, close) {
+        // Swallow all keys.
+        CodeMirror.e_stop(e);
+        var keyName = CodeMirror.keyName(e);
+        switch (keyName) {
+          case 'Y':
+            replace(); next(); break;
+          case 'N':
+            next(); break;
+          case 'A':
+            cm.operation(replaceAll); break;
+          case 'L':
+            replace();
+            // fall through and exit.
+          case 'Q':
+          case 'Esc':
+          case 'Ctrl-C':
+          case 'Ctrl-[':
+            stop(close);
+            break;
+        }
+        if (done) { stop(close); }
+      }
+
+      // Actually do replace.
+      next();
+      if (done) {
+        throw new Error('No matches for ' + query.source);
+      }
+      if (!confirm) {
+        replaceAll();
+        return;
+      }
+      showPrompt(cm, {
+        prefix: 'replace with <strong>' + replaceWith + '</strong> (y/n/a/q/l)',
+        onKeyDown: onPromptKeyDown
+      });
+    }
+
+    // Register Vim with CodeMirror
+    function buildVimKeyMap() {
+      /**
+       * Handle the raw key event from CodeMirror. Translate the
+       * Shift + key modifier to the resulting letter, while preserving other
+       * modifers.
+       */
+      // TODO: Figure out a way to catch capslock.
+      function cmKeyToVimKey(key, modifier) {
+        var vimKey = key;
+        if (isUpperCase(vimKey)) {
+          // Convert to lower case if shift is not the modifier since the key
+          // we get from CodeMirror is always upper case.
+          if (modifier == 'Shift') {
+            modifier = null;
+          }
+          else {
+            vimKey = vimKey.toLowerCase();
+          }
+        }
+        if (modifier) {
+          // Vim will parse modifier+key combination as a single key.
+          vimKey = modifier.charAt(0) + '-' + vimKey;
+        }
+        var specialKey = ({Enter:'CR',Backspace:'BS',Delete:'Del'})[vimKey];
+        vimKey = specialKey ? specialKey : vimKey;
+        vimKey = vimKey.length > 1 ? '<'+ vimKey + '>' : vimKey;
+        return vimKey;
+      }
+
+      // Closure to bind CodeMirror, key, modifier.
+      function keyMapper(vimKey) {
+        return function(cm) {
+          CodeMirror.Vim.handleKey(cm, vimKey);
+        };
+      }
+
+      var cmToVimKeymap = {
+        'nofallthrough': true,
+        'disableInput': true,
+        'style': 'fat-cursor'
+      };
+      function bindKeys(keys, modifier) {
+        for (var i = 0; i < keys.length; i++) {
+          var key = keys[i];
+          if (!modifier && inArray(key, specialSymbols)) {
+            // Wrap special symbols with '' because that's how CodeMirror binds
+            // them.
+            key = "'" + key + "'";
+          }
+          var vimKey = cmKeyToVimKey(keys[i], modifier);
+          var cmKey = modifier ? modifier + '-' + key : key;
+          cmToVimKeymap[cmKey] = keyMapper(vimKey);
+        }
+      }
+      bindKeys(upperCaseAlphabet);
+      bindKeys(upperCaseAlphabet, 'Shift');
+      bindKeys(upperCaseAlphabet, 'Ctrl');
+      bindKeys(specialSymbols);
+      bindKeys(specialSymbols, 'Ctrl');
+      bindKeys(numbers);
+      bindKeys(numbers, 'Ctrl');
+      bindKeys(specialKeys);
+      bindKeys(specialKeys, 'Ctrl');
+      return cmToVimKeymap;
+    }
+    CodeMirror.keyMap.vim = buildVimKeyMap();
+
+    function exitInsertMode(cm) {
+      var vim = cm.state.vim;
+      var inReplay = vimGlobalState.macroModeState.inReplay;
+      if (!inReplay) {
+        cm.off('change', onChange);
+        cm.off('cursorActivity', onCursorActivity);
+        CodeMirror.off(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);
+      }
+      if (!inReplay && vim.insertModeRepeat > 1) {
+        // Perform insert mode repeat for commands like 3,a and 3,o.
+        repeatLastEdit(cm, vim, vim.insertModeRepeat - 1,
+            true /** repeatForInsert */);
+        vim.lastEditInputState.repeatOverride = vim.insertModeRepeat;
+      }
+      delete vim.insertModeRepeat;
+      cm.setCursor(cm.getCursor().line, cm.getCursor().ch-1, true);
+      vim.insertMode = false;
+      cm.setOption('keyMap', 'vim');
+      cm.toggleOverwrite(false); // exit replace mode if we were in it.
+    }
+
+    CodeMirror.keyMap['vim-insert'] = {
+      // TODO: override navigation keys so that Esc will cancel automatic
+      // indentation from o, O, i_<CR>
+      'Esc': exitInsertMode,
+      'Ctrl-[': exitInsertMode,
+      'Ctrl-C': exitInsertMode,
+      'Ctrl-N': 'autocomplete',
+      'Ctrl-P': 'autocomplete',
+      'Enter': function(cm) {
+        var fn = CodeMirror.commands.newlineAndIndentContinueComment ||
+            CodeMirror.commands.newlineAndIndent;
+        fn(cm);
+      },
+      fallthrough: ['default']
+    };
+
+    CodeMirror.keyMap['vim-replace'] = {
+      'Backspace': 'goCharLeft',
+      fallthrough: ['vim-insert']
+    };
+
+    function parseRegisterToKeyBuffer(macroModeState, registerName) {
+      var match, key;
+      var register = vimGlobalState.registerController.getRegister(registerName);
+      var text = register.toString();
+      var macroKeyBuffer = macroModeState.macroKeyBuffer;
+      emptyMacroKeyBuffer(macroModeState);
+      do {
+        match = (/<\w+-.+?>|<\w+>|./).exec(text);
+        if(match === null)break;
+        key = match[0];
+        text = text.substring(match.index + key.length);
+        macroKeyBuffer.push(key);
+      } while (text);
+      return macroKeyBuffer;
+    }
+
+    function parseKeyBufferToRegister(registerName, keyBuffer) {
+      var text = keyBuffer.join('');
+      vimGlobalState.registerController.setRegisterText(registerName, text);
+    }
+
+    function emptyMacroKeyBuffer(macroModeState) {
+      if(macroModeState.isMacroPlaying)return;
+      var macroKeyBuffer = macroModeState.macroKeyBuffer;
+      macroKeyBuffer.length = 0;
+    }
+
+    function executeMacroKeyBuffer(cm, macroModeState, keyBuffer) {
+      macroModeState.isMacroPlaying = true;
+      for (var i = 0, len = keyBuffer.length; i < len; i++) {
+        CodeMirror.Vim.handleKey(cm, keyBuffer[i]);
+      };
+      macroModeState.isMacroPlaying = false;
+    }
+
+    function logKey(macroModeState, key) {
+      if(macroModeState.isMacroPlaying)return;
+      var macroKeyBuffer = macroModeState.macroKeyBuffer;
+      macroKeyBuffer.push(key);
+    }
+
+    /**
+     * Listens for changes made in insert mode.
+     * Should only be active in insert mode.
+     */
+    function onChange(_cm, changeObj) {
+      var macroModeState = vimGlobalState.macroModeState;
+      var lastChange = macroModeState.lastInsertModeChanges;
+      while (changeObj) {
+        lastChange.expectCursorActivityForChange = true;
+        if (changeObj.origin == '+input' || changeObj.origin == 'paste'
+            || changeObj.origin === undefined /* only in testing */) {
+          var text = changeObj.text.join('\n');
+          lastChange.changes.push(text);
+        }
+        // Change objects may be chained with next.
+        changeObj = changeObj.next;
+      }
+    }
+
+    /**
+    * Listens for any kind of cursor activity on CodeMirror.
+    * - For tracking cursor activity in insert mode.
+    * - Should only be active in insert mode.
+    */
+    function onCursorActivity() {
+      var macroModeState = vimGlobalState.macroModeState;
+      var lastChange = macroModeState.lastInsertModeChanges;
+      if (lastChange.expectCursorActivityForChange) {
+        lastChange.expectCursorActivityForChange = false;
+      } else {
+        // Cursor moved outside the context of an edit. Reset the change.
+        lastChange.changes = [];
+      }
+    }
+
+    /** Wrapper for special keys pressed in insert mode */
+    function InsertModeKey(keyName) {
+      this.keyName = keyName;
+    }
+
+    /**
+    * Handles raw key down events from the text area.
+    * - Should only be active in insert mode.
+    * - For recording deletes in insert mode.
+    */
+    function onKeyEventTargetKeyDown(e) {
+      var macroModeState = vimGlobalState.macroModeState;
+      var lastChange = macroModeState.lastInsertModeChanges;
+      var keyName = CodeMirror.keyName(e);
+      function onKeyFound() {
+        lastChange.changes.push(new InsertModeKey(keyName));
+        return true;
+      }
+      if (keyName.indexOf('Delete') != -1 || keyName.indexOf('Backspace') != -1) {
+        CodeMirror.lookupKey(keyName, ['vim-insert'], onKeyFound);
+      }
+    }
+
+    /**
+     * Repeats the last edit, which includes exactly 1 command and at most 1
+     * insert. Operator and motion commands are read from lastEditInputState,
+     * while action commands are read from lastEditActionCommand.
+     *
+     * If repeatForInsert is true, then the function was called by
+     * exitInsertMode to repeat the insert mode changes the user just made. The
+     * corresponding enterInsertMode call was made with a count.
+     */
+    function repeatLastEdit(cm, vim, repeat, repeatForInsert) {
+      var macroModeState = vimGlobalState.macroModeState;
+      macroModeState.inReplay = true;
+      var isAction = !!vim.lastEditActionCommand;
+      var cachedInputState = vim.inputState;
+      function repeatCommand() {
+        if (isAction) {
+          commandDispatcher.processAction(cm, vim, vim.lastEditActionCommand);
+        } else {
+          commandDispatcher.evalInput(cm, vim);
+        }
+      }
+      function repeatInsert(repeat) {
+        if (macroModeState.lastInsertModeChanges.changes.length > 0) {
+          // For some reason, repeat cw in desktop VIM will does not repeat
+          // insert mode changes. Will conform to that behavior.
+          repeat = !vim.lastEditActionCommand ? 1 : repeat;
+          repeatLastInsertModeChanges(cm, repeat, macroModeState);
+        }
+      }
+      vim.inputState = vim.lastEditInputState;
+      if (isAction && vim.lastEditActionCommand.interlaceInsertRepeat) {
+        // o and O repeat have to be interlaced with insert repeats so that the
+        // insertions appear on separate lines instead of the last line.
+        for (var i = 0; i < repeat; i++) {
+          repeatCommand();
+          repeatInsert(1);
+        }
+      } else {
+        if (!repeatForInsert) {
+          // Hack to get the cursor to end up at the right place. If I is
+          // repeated in insert mode repeat, cursor will be 1 insert
+          // change set left of where it should be.
+          repeatCommand();
+        }
+        repeatInsert(repeat);
+      }
+      vim.inputState = cachedInputState;
+      if (vim.insertMode && !repeatForInsert) {
+        // Don't exit insert mode twice. If repeatForInsert is set, then we
+        // were called by an exitInsertMode call lower on the stack.
+        exitInsertMode(cm);
+      }
+      macroModeState.inReplay = false;
+    };
+
+    function repeatLastInsertModeChanges(cm, repeat, macroModeState) {
+      var lastChange = macroModeState.lastInsertModeChanges;
+      function keyHandler(binding) {
+        if (typeof binding == 'string') {
+          CodeMirror.commands[binding](cm);
+        } else {
+          binding(cm);
+        }
+        return true;
+      }
+      for (var i = 0; i < repeat; i++) {
+        for (var j = 0; j < lastChange.changes.length; j++) {
+          var change = lastChange.changes[j];
+          if (change instanceof InsertModeKey) {
+            CodeMirror.lookupKey(change.keyName, ['vim-insert'], keyHandler);
+          } else {
+            var cur = cm.getCursor();
+            cm.replaceRange(change, cur, cur);
+          }
+        }
+      }
+    }
+
+    resetVimGlobalState();
+    return vimApi;
+  };
+  // Initialize Vim and make it available as an API.
+  CodeMirror.Vim = Vim();
+}
+)();
diff --git a/third-party/codemirror-3.15/lib/codemirror.css b/third-party/codemirror-3.15/lib/codemirror.css
new file mode 100644 (file)
index 0000000..7eb2215
--- /dev/null
@@ -0,0 +1,258 @@
+/* BASICS */
+
+.CodeMirror {
+  /* Set height, width, borders, and global font properties here */
+  font-family: monospace;
+/*  height: 300px; //jordan */
+}
+.CodeMirror-scroll {
+  /* Set scrolling behaviour here */
+  overflow: auto;
+}
+
+/* PADDING */
+
+.CodeMirror-lines {
+  padding: 4px 0; /* Vertical padding around content */
+}
+.CodeMirror pre {
+  padding: 0 4px; /* Horizontal padding of content */
+}
+
+.CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
+  background-color: white; /* The little square between H and V scrollbars */
+}
+
+/* GUTTER */
+
+.CodeMirror-gutters {
+  border-right: 1px solid #ddd;
+  background-color: #f7f7f7;
+  white-space: nowrap;
+}
+.CodeMirror-linenumbers {}
+.CodeMirror-linenumber {
+  padding: 0 3px 0 5px;
+  min-width: 20px;
+  text-align: right;
+  color: #999;
+}
+
+/* CURSOR */
+
+.CodeMirror div.CodeMirror-cursor {
+  border-left: 1px solid black;
+  z-index: 3;
+}
+/* Shown when moving in bi-directional text */
+.CodeMirror div.CodeMirror-secondarycursor {
+  border-left: 1px solid silver;
+}
+.CodeMirror.cm-keymap-fat-cursor div.CodeMirror-cursor {
+  width: auto;
+  border: 0;
+  background: #7e7;
+  z-index: 1;
+}
+/* Can style cursor different in overwrite (non-insert) mode */
+.CodeMirror div.CodeMirror-cursor.CodeMirror-overwrite {}
+
+.cm-tab { display: inline-block; }
+
+/* DEFAULT THEME */
+
+.cm-s-default .cm-keyword {color: #708;}
+.cm-s-default .cm-atom {color: #219;}
+.cm-s-default .cm-number {color: #164;}
+.cm-s-default .cm-def {color: #00f;}
+.cm-s-default .cm-variable {color: black;}
+.cm-s-default .cm-variable-2 {color: #05a;}
+.cm-s-default .cm-variable-3 {color: #085;}
+.cm-s-default .cm-property {color: black;}
+.cm-s-default .cm-operator {color: black;}
+.cm-s-default .cm-comment {color: #a50;}
+.cm-s-default .cm-string {color: #a11;}
+.cm-s-default .cm-string-2 {color: #f50;}
+.cm-s-default .cm-meta {color: #555;}
+.cm-s-default .cm-error {color: #f00;}
+.cm-s-default .cm-qualifier {color: #555;}
+.cm-s-default .cm-builtin {color: #30a;}
+.cm-s-default .cm-bracket {color: #997;}
+.cm-s-default .cm-tag {color: #170;}
+.cm-s-default .cm-attribute {color: #00c;}
+.cm-s-default .cm-header {color: blue;}
+.cm-s-default .cm-quote {color: #090;}
+.cm-s-default .cm-hr {color: #999;}
+.cm-s-default .cm-link {color: #00c;}
+
+.cm-negative {color: #d44;}
+.cm-positive {color: #292;}
+.cm-header, .cm-strong {font-weight: bold;}
+.cm-em {font-style: italic;}
+.cm-link {text-decoration: underline;}
+
+.cm-invalidchar {color: #f00;}
+
+div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;}
+div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;}
+
+/* STOP */
+
+/* The rest of this file contains styles related to the mechanics of
+   the editor. You probably shouldn't touch them. */
+
+.CodeMirror {
+  line-height: 1;
+  position: relative;
+  overflow: hidden;
+  background: white;
+  color: black;
+}
+
+.CodeMirror-scroll {
+  /* 30px is the magic margin used to hide the element's real scrollbars */
+  /* See overflow: hidden in .CodeMirror */
+  margin-bottom: -30px; margin-right: -30px;
+  padding-bottom: 30px; padding-right: 30px;
+  height: 100%;
+  outline: none; /* Prevent dragging from highlighting the element */
+  position: relative;
+}
+.CodeMirror-sizer {
+  position: relative;
+}
+
+/* The fake, visible scrollbars. Used to force redraw during scrolling
+   before actuall scrolling happens, thus preventing shaking and
+   flickering artifacts. */
+.CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
+  position: absolute;
+  z-index: 6;
+  display: none;
+}
+.CodeMirror-vscrollbar {
+  right: 0; top: 0;
+  overflow-x: hidden;
+  overflow-y: scroll;
+}
+.CodeMirror-hscrollbar {
+  bottom: 0; left: 0;
+  overflow-y: hidden;
+  overflow-x: scroll;
+}
+.CodeMirror-scrollbar-filler {
+  right: 0; bottom: 0;
+}
+.CodeMirror-gutter-filler {
+  left: 0; bottom: 0;
+}
+
+.CodeMirror-gutters {
+  position: absolute; left: 0; top: 0;
+  padding-bottom: 30px;
+  z-index: 3;
+}
+.CodeMirror-gutter {
+  white-space: normal;
+  height: 100%;
+  padding-bottom: 30px;
+  margin-bottom: -32px;
+  display: inline-block;
+  /* Hack to make IE7 behave */
+  *zoom:1;
+  *display:inline;
+}
+.CodeMirror-gutter-elt {
+  position: absolute;
+  cursor: default;
+  z-index: 4;
+}
+
+.CodeMirror-lines {
+  cursor: text;
+}
+.CodeMirror pre {
+  /* Reset some styles that the rest of the page might have set */
+  -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0;
+  border-width: 0;
+  background: transparent;
+  font-family: inherit;
+  font-size: inherit;
+  margin: 0;
+  white-space: pre;
+  word-wrap: normal;
+  line-height: inherit;
+  color: inherit;
+  z-index: 2;
+  position: relative;
+  overflow: visible;
+}
+.CodeMirror-wrap pre {
+  word-wrap: break-word;
+  white-space: pre-wrap;
+  word-break: normal;
+}
+.CodeMirror-code pre {
+  border-right: 30px solid transparent;
+  width: -webkit-fit-content;
+  width: -moz-fit-content;
+  width: fit-content;
+}
+.CodeMirror-wrap .CodeMirror-code pre {
+  border-right: none;
+  width: auto;
+}
+.CodeMirror-linebackground {
+  position: absolute;
+  left: 0; right: 0; top: 0; bottom: 0;
+  z-index: 0;
+}
+
+.CodeMirror-linewidget {
+  position: relative;
+  z-index: 2;
+  overflow: auto;
+}
+
+.CodeMirror-widget {
+}
+
+.CodeMirror-wrap .CodeMirror-scroll {
+  overflow-x: hidden;
+}
+
+.CodeMirror-measure {
+  position: absolute;
+  width: 100%; height: 0px;
+  overflow: hidden;
+  visibility: hidden;
+}
+.CodeMirror-measure pre { position: static; }
+
+.CodeMirror div.CodeMirror-cursor {
+  position: absolute;
+  visibility: hidden;
+  border-right: none;
+  width: 0;
+}
+.CodeMirror-focused div.CodeMirror-cursor {
+  visibility: visible;
+}
+
+.CodeMirror-selected { background: #d9d9d9; }
+.CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; }
+
+.cm-searching {
+  background: #ffa;
+  background: rgba(255, 255, 0, .4);
+}
+
+/* IE7 hack to prevent it from returning funny offsetTops on the spans */
+.CodeMirror span { *vertical-align: text-bottom; }
+
+@media print {
+  /* Hide the cursor when printing */
+  .CodeMirror div.CodeMirror-cursor {
+    visibility: hidden;
+  }
+}
diff --git a/third-party/codemirror-3.15/lib/codemirror.js b/third-party/codemirror-3.15/lib/codemirror.js
new file mode 100644 (file)
index 0000000..1d0d996
--- /dev/null
@@ -0,0 +1,5799 @@
+// CodeMirror version 3.15
+//
+// CodeMirror is the only global var we claim
+window.CodeMirror = (function() {
+  "use strict";
+
+  // BROWSER SNIFFING
+
+  // Crude, but necessary to handle a number of hard-to-feature-detect
+  // bugs and behavior differences.
+  var gecko = /gecko\/\d/i.test(navigator.userAgent);
+  var ie = /MSIE \d/.test(navigator.userAgent);
+  var ie_lt8 = ie && (document.documentMode == null || document.documentMode < 8);
+  var ie_lt9 = ie && (document.documentMode == null || document.documentMode < 9);
+  var webkit = /WebKit\//.test(navigator.userAgent);
+  var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent);
+  var chrome = /Chrome\//.test(navigator.userAgent);
+  var opera = /Opera\//.test(navigator.userAgent);
+  var safari = /Apple Computer/.test(navigator.vendor);
+  var khtml = /KHTML\//.test(navigator.userAgent);
+  var mac_geLion = /Mac OS X 1\d\D([7-9]|\d\d)\D/.test(navigator.userAgent);
+  var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent);
+  var phantom = /PhantomJS/.test(navigator.userAgent);
+
+  var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent);
+  // This is woefully incomplete. Suggestions for alternative methods welcome.
+  var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent);
+  var mac = ios || /Mac/.test(navigator.platform);
+  var windows = /windows/i.test(navigator.platform);
+
+  var opera_version = opera && navigator.userAgent.match(/Version\/(\d*\.\d*)/);
+  if (opera_version) opera_version = Number(opera_version[1]);
+  if (opera_version && opera_version >= 15) { opera = false; webkit = true; }
+  // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
+  var flipCtrlCmd = mac && (qtwebkit || opera && (opera_version == null || opera_version < 12.11));
+  var captureMiddleClick = gecko || (ie && !ie_lt9);
+
+  // Optimize some code when these features are not used
+  var sawReadOnlySpans = false, sawCollapsedSpans = false;
+
+  // CONSTRUCTOR
+
+  function CodeMirror(place, options) {
+    if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
+
+    this.options = options = options || {};
+    // Determine effective options based on given values and defaults.
+    for (var opt in defaults) if (!options.hasOwnProperty(opt) && defaults.hasOwnProperty(opt))
+      options[opt] = defaults[opt];
+    setGuttersForLineNumbers(options);
+
+    var docStart = typeof options.value == "string" ? 0 : options.value.first;
+    var display = this.display = makeDisplay(place, docStart);
+    display.wrapper.CodeMirror = this;
+    updateGutters(this);
+    if (options.autofocus && !mobile) focusInput(this);
+
+    this.state = {keyMaps: [],
+                  overlays: [],
+                  modeGen: 0,
+                  overwrite: false, focused: false,
+                  suppressEdits: false, pasteIncoming: false,
+                  draggingText: false,
+                  highlight: new Delayed()};
+
+    themeChanged(this);
+    if (options.lineWrapping)
+      this.display.wrapper.className += " CodeMirror-wrap";
+
+    var doc = options.value;
+    if (typeof doc == "string") doc = new Doc(options.value, options.mode);
+    operation(this, attachDoc)(this, doc);
+
+    // Override magic textarea content restore that IE sometimes does
+    // on our hidden textarea on reload
+    if (ie) setTimeout(bind(resetInput, this, true), 20);
+
+    registerEventHandlers(this);
+    // IE throws unspecified error in certain cases, when
+    // trying to access activeElement before onload
+    var hasFocus; try { hasFocus = (document.activeElement == display.input); } catch(e) { }
+    if (hasFocus || (options.autofocus && !mobile)) setTimeout(bind(onFocus, this), 20);
+    else onBlur(this);
+
+    operation(this, function() {
+      for (var opt in optionHandlers)
+        if (optionHandlers.propertyIsEnumerable(opt))
+          optionHandlers[opt](this, options[opt], Init);
+      for (var i = 0; i < initHooks.length; ++i) initHooks[i](this);
+    })();
+  }
+
+  // DISPLAY CONSTRUCTOR
+
+  function makeDisplay(place, docStart) {
+    var d = {};
+
+    var input = d.input = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none; font-size: 4px;");
+    if (webkit) input.style.width = "1000px";
+    else input.setAttribute("wrap", "off");
+    // if border: 0; -- iOS fails to open keyboard (issue #1287)
+    if (ios) input.style.border = "1px solid black";
+    input.setAttribute("autocorrect", "off"); input.setAttribute("autocapitalize", "off"); input.setAttribute("spellcheck", "false");
+
+    // Wraps and hides input textarea
+    d.inputDiv = elt("div", [input], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
+    // The actual fake scrollbars.
+    d.scrollbarH = elt("div", [elt("div", null, null, "height: 1px")], "CodeMirror-hscrollbar");
+    d.scrollbarV = elt("div", [elt("div", null, null, "width: 1px")], "CodeMirror-vscrollbar");
+    d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
+    d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
+    // DIVs containing the selection and the actual code
+    d.lineDiv = elt("div", null, "CodeMirror-code");
+    d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
+    // Blinky cursor, and element used to ensure cursor fits at the end of a line
+    d.cursor = elt("div", "\u00a0", "CodeMirror-cursor");
+    // Secondary cursor, shown when on a 'jump' in bi-directional text
+    d.otherCursor = elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor");
+    // Used to measure text size
+    d.measure = elt("div", null, "CodeMirror-measure");
+    // Wraps everything that needs to exist inside the vertically-padded coordinate system
+    d.lineSpace = elt("div", [d.measure, d.selectionDiv, d.lineDiv, d.cursor, d.otherCursor],
+                         null, "position: relative; outline: none");
+    // Moved around its parent to cover visible view
+    d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
+    // Set to the height of the text, causes scrolling
+    d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
+    // D is needed because behavior of elts with overflow: auto and padding is inconsistent across browsers
+    d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerCutOff + "px; width: 1px;");
+    // Will contain the gutters, if any
+    d.gutters = elt("div", null, "CodeMirror-gutters");
+    d.lineGutter = null;
+    // Provides scrolling
+    d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
+    d.scroller.setAttribute("tabIndex", "-1");
+    // The element in which the editor lives.
+    d.wrapper = elt("div", [d.inputDiv, d.scrollbarH, d.scrollbarV,
+                            d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
+    // Work around IE7 z-index bug
+    if (ie_lt8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
+    if (place.appendChild) place.appendChild(d.wrapper); else place(d.wrapper);
+
+    // Needed to hide big blue blinking cursor on Mobile Safari
+    if (ios) input.style.width = "0px";
+    if (!webkit) d.scroller.draggable = true;
+    // Needed to handle Tab key in KHTML
+    if (khtml) { d.inputDiv.style.height = "1px"; d.inputDiv.style.position = "absolute"; }
+    // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
+    else if (ie_lt8) d.scrollbarH.style.minWidth = d.scrollbarV.style.minWidth = "18px";
+
+    // Current visible range (may be bigger than the view window).
+    d.viewOffset = d.lastSizeC = 0;
+    d.showingFrom = d.showingTo = docStart;
+
+    // Used to only resize the line number gutter when necessary (when
+    // the amount of lines crosses a boundary that makes its width change)
+    d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
+    // See readInput and resetInput
+    d.prevInput = "";
+    // Set to true when a non-horizontal-scrolling widget is added. As
+    // an optimization, widget aligning is skipped when d is false.
+    d.alignWidgets = false;
+    // Flag that indicates whether we currently expect input to appear
+    // (after some event like 'keypress' or 'input') and are polling
+    // intensively.
+    d.pollingFast = false;
+    // Self-resetting timeout for the poller
+    d.poll = new Delayed();
+
+    d.cachedCharWidth = d.cachedTextHeight = null;
+    d.measureLineCache = [];
+    d.measureLineCachePos = 0;
+
+    // Tracks when resetInput has punted to just putting a short
+    // string instead of the (large) selection.
+    d.inaccurateSelection = false;
+
+    // Tracks the maximum line length so that the horizontal scrollbar
+    // can be kept static when scrolling.
+    d.maxLine = null;
+    d.maxLineLength = 0;
+    d.maxLineChanged = false;
+
+    // Used for measuring wheel scrolling granularity
+    d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
+
+    return d;
+  }
+
+  // STATE UPDATES
+
+  // Used to get the editor into a consistent state again when options change.
+
+  function loadMode(cm) {
+    cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption);
+    cm.doc.iter(function(line) {
+      if (line.stateAfter) line.stateAfter = null;
+      if (line.styles) line.styles = null;
+    });
+    cm.doc.frontier = cm.doc.first;
+    startWorker(cm, 100);
+    cm.state.modeGen++;
+    if (cm.curOp) regChange(cm);
+  }
+
+  function wrappingChanged(cm) {
+    if (cm.options.lineWrapping) {
+      cm.display.wrapper.className += " CodeMirror-wrap";
+      cm.display.sizer.style.minWidth = "";
+    } else {
+      cm.display.wrapper.className = cm.display.wrapper.className.replace(" CodeMirror-wrap", "");
+      computeMaxLength(cm);
+    }
+    estimateLineHeights(cm);
+    regChange(cm);
+    clearCaches(cm);
+    setTimeout(function(){updateScrollbars(cm);}, 100);
+  }
+
+  function estimateHeight(cm) {
+    var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
+    var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
+    return function(line) {
+      if (lineIsHidden(cm.doc, line))
+        return 0;
+      else if (wrapping)
+        return (Math.ceil(line.text.length / perLine) || 1) * th;
+      else
+        return th;
+    };
+  }
+
+  function estimateLineHeights(cm) {
+    var doc = cm.doc, est = estimateHeight(cm);
+    doc.iter(function(line) {
+      var estHeight = est(line);
+      if (estHeight != line.height) updateLineHeight(line, estHeight);
+    });
+  }
+
+  function keyMapChanged(cm) {
+    var map = keyMap[cm.options.keyMap], style = map.style;
+    cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-keymap-\S+/g, "") +
+      (style ? " cm-keymap-" + style : "");
+    cm.state.disableInput = map.disableInput;
+  }
+
+  function themeChanged(cm) {
+    cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
+      cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
+    clearCaches(cm);
+  }
+
+  function guttersChanged(cm) {
+    updateGutters(cm);
+    regChange(cm);
+    setTimeout(function(){alignHorizontally(cm);}, 20);
+  }
+
+  function updateGutters(cm) {
+    var gutters = cm.display.gutters, specs = cm.options.gutters;
+    removeChildren(gutters);
+    for (var i = 0; i < specs.length; ++i) {
+      var gutterClass = specs[i];
+      var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
+      if (gutterClass == "CodeMirror-linenumbers") {
+        cm.display.lineGutter = gElt;
+        gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
+      }
+    }
+    gutters.style.display = i ? "" : "none";
+  }
+
+  function lineLength(doc, line) {
+    if (line.height == 0) return 0;
+    var len = line.text.length, merged, cur = line;
+    while (merged = collapsedSpanAtStart(cur)) {
+      var found = merged.find();
+      cur = getLine(doc, found.from.line);
+      len += found.from.ch - found.to.ch;
+    }
+    cur = line;
+    while (merged = collapsedSpanAtEnd(cur)) {
+      var found = merged.find();
+      len -= cur.text.length - found.from.ch;
+      cur = getLine(doc, found.to.line);
+      len += cur.text.length - found.to.ch;
+    }
+    return len;
+  }
+
+  function computeMaxLength(cm) {
+    var d = cm.display, doc = cm.doc;
+    d.maxLine = getLine(doc, doc.first);
+    d.maxLineLength = lineLength(doc, d.maxLine);
+    d.maxLineChanged = true;
+    doc.iter(function(line) {
+      var len = lineLength(doc, line);
+      if (len > d.maxLineLength) {
+        d.maxLineLength = len;
+        d.maxLine = line;
+      }
+    });
+  }
+
+  // Make sure the gutters options contains the element
+  // "CodeMirror-linenumbers" when the lineNumbers option is true.
+  function setGuttersForLineNumbers(options) {
+    var found = false;
+    for (var i = 0; i < options.gutters.length; ++i) {
+      if (options.gutters[i] == "CodeMirror-linenumbers") {
+        if (options.lineNumbers) found = true;
+        else options.gutters.splice(i--, 1);
+      }
+    }
+    if (!found && options.lineNumbers)
+      options.gutters.push("CodeMirror-linenumbers");
+  }
+
+  // SCROLLBARS
+
+  // Re-synchronize the fake scrollbars with the actual size of the
+  // content. Optionally force a scrollTop.
+  function updateScrollbars(cm) {
+    var d = cm.display, docHeight = cm.doc.height;
+    var totalHeight = docHeight + paddingVert(d);
+    d.sizer.style.minHeight = d.heightForcer.style.top = totalHeight + "px";
+    d.gutters.style.height = Math.max(totalHeight, d.scroller.clientHeight - scrollerCutOff) + "px";
+    var scrollHeight = Math.max(totalHeight, d.scroller.scrollHeight);
+    var needsH = d.scroller.scrollWidth > (d.scroller.clientWidth + 1);
+    var needsV = scrollHeight > (d.scroller.clientHeight + 1);
+    if (needsV) {
+      d.scrollbarV.style.display = "block";
+      d.scrollbarV.style.bottom = needsH ? scrollbarWidth(d.measure) + "px" : "0";
+      d.scrollbarV.firstChild.style.height =
+        (scrollHeight - d.scroller.clientHeight + d.scrollbarV.clientHeight) + "px";
+    } else d.scrollbarV.style.display = "";
+    if (needsH) {
+      d.scrollbarH.style.display = "block";
+      d.scrollbarH.style.right = needsV ? scrollbarWidth(d.measure) + "px" : "0";
+      d.scrollbarH.firstChild.style.width =
+        (d.scroller.scrollWidth - d.scroller.clientWidth + d.scrollbarH.clientWidth) + "px";
+    } else d.scrollbarH.style.display = "";
+    if (needsH && needsV) {
+      d.scrollbarFiller.style.display = "block";
+      d.scrollbarFiller.style.height = d.scrollbarFiller.style.width = scrollbarWidth(d.measure) + "px";
+    } else d.scrollbarFiller.style.display = "";
+    if (needsH && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
+      d.gutterFiller.style.display = "block";
+      d.gutterFiller.style.height = scrollbarWidth(d.measure) + "px";
+      d.gutterFiller.style.width = d.gutters.offsetWidth + "px";
+    } else d.gutterFiller.style.display = "";
+
+    if (mac_geLion && scrollbarWidth(d.measure) === 0)
+      d.scrollbarV.style.minWidth = d.scrollbarH.style.minHeight = mac_geMountainLion ? "18px" : "12px";
+  }
+
+  function visibleLines(display, doc, viewPort) {
+    var top = display.scroller.scrollTop, height = display.wrapper.clientHeight;
+    if (typeof viewPort == "number") top = viewPort;
+    else if (viewPort) {top = viewPort.top; height = viewPort.bottom - viewPort.top;}
+    top = Math.floor(top - paddingTop(display));
+    var bottom = Math.ceil(top + height);
+    return {from: lineAtHeight(doc, top), to: lineAtHeight(doc, bottom)};
+  }
+
+  // LINE NUMBERS
+
+  function alignHorizontally(cm) {
+    var display = cm.display;
+    if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return;
+    var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
+    var gutterW = display.gutters.offsetWidth, l = comp + "px";
+    for (var n = display.lineDiv.firstChild; n; n = n.nextSibling) if (n.alignable) {
+      for (var i = 0, a = n.alignable; i < a.length; ++i) a[i].style.left = l;
+    }
+    if (cm.options.fixedGutter)
+      display.gutters.style.left = (comp + gutterW) + "px";
+  }
+
+  function maybeUpdateLineNumberWidth(cm) {
+    if (!cm.options.lineNumbers) return false;
+    var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
+    if (last.length != display.lineNumChars) {
+      var test = display.measure.appendChild(elt("div", [elt("div", last)],
+                                                 "CodeMirror-linenumber CodeMirror-gutter-elt"));
+      var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
+      display.lineGutter.style.width = "";
+      display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding);
+      display.lineNumWidth = display.lineNumInnerWidth + padding;
+      display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
+      display.lineGutter.style.width = display.lineNumWidth + "px";
+      return true;
+    }
+    return false;
+  }
+
+  function lineNumberFor(options, i) {
+    return String(options.lineNumberFormatter(i + options.firstLineNumber));
+  }
+  function compensateForHScroll(display) {
+    return getRect(display.scroller).left - getRect(display.sizer).left;
+  }
+
+  // DISPLAY DRAWING
+
+  function updateDisplay(cm, changes, viewPort, forced) {
+    var oldFrom = cm.display.showingFrom, oldTo = cm.display.showingTo, updated;
+    var visible = visibleLines(cm.display, cm.doc, viewPort);
+    for (;;) {
+      if (!updateDisplayInner(cm, changes, visible, forced)) break;
+      forced = false;
+      updated = true;
+      updateSelection(cm);
+      updateScrollbars(cm);
+
+      // Clip forced viewport to actual scrollable area
+      if (viewPort)
+        viewPort = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight,
+                            typeof viewPort == "number" ? viewPort : viewPort.top);
+      visible = visibleLines(cm.display, cm.doc, viewPort);
+      if (visible.from >= cm.display.showingFrom && visible.to <= cm.display.showingTo)
+        break;
+      changes = [];
+    }
+
+    if (updated) {
+      signalLater(cm, "update", cm);
+      if (cm.display.showingFrom != oldFrom || cm.display.showingTo != oldTo)
+        signalLater(cm, "viewportChange", cm, cm.display.showingFrom, cm.display.showingTo);
+    }
+    return updated;
+  }
+
+  // Uses a set of changes plus the current scroll position to
+  // determine which DOM updates have to be made, and makes the
+  // updates.
+  function updateDisplayInner(cm, changes, visible, forced) {
+    var display = cm.display, doc = cm.doc;
+    if (!display.wrapper.clientWidth) {
+      display.showingFrom = display.showingTo = doc.first;
+      display.viewOffset = 0;
+      return;
+    }
+
+    // Bail out if the visible area is already rendered and nothing changed.
+    if (!forced && changes.length == 0 &&
+        visible.from > display.showingFrom && visible.to < display.showingTo)
+      return;
+
+    if (maybeUpdateLineNumberWidth(cm))
+      changes = [{from: doc.first, to: doc.first + doc.size}];
+    var gutterW = display.sizer.style.marginLeft = display.gutters.offsetWidth + "px";
+    display.scrollbarH.style.left = cm.options.fixedGutter ? gutterW : "0";
+
+    // Used to determine which lines need their line numbers updated
+    var positionsChangedFrom = Infinity;
+    if (cm.options.lineNumbers)
+      for (var i = 0; i < changes.length; ++i)
+        if (changes[i].diff) { positionsChangedFrom = changes[i].from; break; }
+
+    var end = doc.first + doc.size;
+    var from = Math.max(visible.from - cm.options.viewportMargin, doc.first);
+    var to = Math.min(end, visible.to + cm.options.viewportMargin);
+    if (display.showingFrom < from && from - display.showingFrom < 20) from = Math.max(doc.first, display.showingFrom);
+    if (display.showingTo > to && display.showingTo - to < 20) to = Math.min(end, display.showingTo);
+    if (sawCollapsedSpans) {
+      from = lineNo(visualLine(doc, getLine(doc, from)));
+      while (to < end && lineIsHidden(doc, getLine(doc, to))) ++to;
+    }
+
+    // Create a range of theoretically intact lines, and punch holes
+    // in that using the change info.
+    var intact = [{from: Math.max(display.showingFrom, doc.first),
+                   to: Math.min(display.showingTo, end)}];
+    if (intact[0].from >= intact[0].to) intact = [];
+    else intact = computeIntact(intact, changes);
+    // When merged lines are present, we might have to reduce the
+    // intact ranges because changes in continued fragments of the
+    // intact lines do require the lines to be redrawn.
+    if (sawCollapsedSpans)
+      for (var i = 0; i < intact.length; ++i) {
+        var range = intact[i], merged;
+        while (merged = collapsedSpanAtEnd(getLine(doc, range.to - 1))) {
+          var newTo = merged.find().from.line;
+          if (newTo > range.from) range.to = newTo;
+          else { intact.splice(i--, 1); break; }
+        }
+      }
+
+    // Clip off the parts that won't be visible
+    var intactLines = 0;
+    for (var i = 0; i < intact.length; ++i) {
+      var range = intact[i];
+      if (range.from < from) range.from = from;
+      if (range.to > to) range.to = to;
+      if (range.from >= range.to) intact.splice(i--, 1);
+      else intactLines += range.to - range.from;
+    }
+    if (!forced && intactLines == to - from && from == display.showingFrom && to == display.showingTo) {
+      updateViewOffset(cm);
+      return;
+    }
+    intact.sort(function(a, b) {return a.from - b.from;});
+
+    // Avoid crashing on IE's "unspecified error" when in iframes
+    try {
+      var focused = document.activeElement;
+    } catch(e) {}
+    if (intactLines < (to - from) * .7) display.lineDiv.style.display = "none";
+    patchDisplay(cm, from, to, intact, positionsChangedFrom);
+    display.lineDiv.style.display = "";
+    if (focused && document.activeElement != focused && focused.offsetHeight) focused.focus();
+
+    var different = from != display.showingFrom || to != display.showingTo ||
+      display.lastSizeC != display.wrapper.clientHeight;
+    // This is just a bogus formula that detects when the editor is
+    // resized or the font size changes.
+    if (different) {
+      display.lastSizeC = display.wrapper.clientHeight;
+      startWorker(cm, 400);
+    }
+    display.showingFrom = from; display.showingTo = to;
+
+    updateHeightsInViewport(cm);
+    updateViewOffset(cm);
+
+    return true;
+  }
+
+  function updateHeightsInViewport(cm) {
+    var display = cm.display;
+    var prevBottom = display.lineDiv.offsetTop;
+    for (var node = display.lineDiv.firstChild, height; node; node = node.nextSibling) if (node.lineObj) {
+      if (ie_lt8) {
+        var bot = node.offsetTop + node.offsetHeight;
+        height = bot - prevBottom;
+        prevBottom = bot;
+      } else {
+        var box = getRect(node);
+        height = box.bottom - box.top;
+      }
+      var diff = node.lineObj.height - height;
+      if (height < 2) height = textHeight(display);
+      if (diff > .001 || diff < -.001) {
+        updateLineHeight(node.lineObj, height);
+        var widgets = node.lineObj.widgets;
+        if (widgets) for (var i = 0; i < widgets.length; ++i)
+          widgets[i].height = widgets[i].node.offsetHeight;
+      }
+    }
+  }
+
+  function updateViewOffset(cm) {
+    var off = cm.display.viewOffset = heightAtLine(cm, getLine(cm.doc, cm.display.showingFrom));
+    // Position the mover div to align with the current virtual scroll position
+    cm.display.mover.style.top = off + "px";
+  }
+
+  function computeIntact(intact, changes) {
+    for (var i = 0, l = changes.length || 0; i < l; ++i) {
+      var change = changes[i], intact2 = [], diff = change.diff || 0;
+      for (var j = 0, l2 = intact.length; j < l2; ++j) {
+        var range = intact[j];
+        if (change.to <= range.from && change.diff) {
+          intact2.push({from: range.from + diff, to: range.to + diff});
+        } else if (change.to <= range.from || change.from >= range.to) {
+          intact2.push(range);
+        } else {
+          if (change.from > range.from)
+            intact2.push({from: range.from, to: change.from});
+          if (change.to < range.to)
+            intact2.push({from: change.to + diff, to: range.to + diff});
+        }
+      }
+      intact = intact2;
+    }
+    return intact;
+  }
+
+  function getDimensions(cm) {
+    var d = cm.display, left = {}, width = {};
+    for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
+      left[cm.options.gutters[i]] = n.offsetLeft;
+      width[cm.options.gutters[i]] = n.offsetWidth;
+    }
+    return {fixedPos: compensateForHScroll(d),
+            gutterTotalWidth: d.gutters.offsetWidth,
+            gutterLeft: left,
+            gutterWidth: width,
+            wrapperWidth: d.wrapper.clientWidth};
+  }
+
+  function patchDisplay(cm, from, to, intact, updateNumbersFrom) {
+    var dims = getDimensions(cm);
+    var display = cm.display, lineNumbers = cm.options.lineNumbers;
+    if (!intact.length && (!webkit || !cm.display.currentWheelTarget))
+      removeChildren(display.lineDiv);
+    var container = display.lineDiv, cur = container.firstChild;
+
+    function rm(node) {
+      var next = node.nextSibling;
+      if (webkit && mac && cm.display.currentWheelTarget == node) {
+        node.style.display = "none";
+        node.lineObj = null;
+      } else {
+        node.parentNode.removeChild(node);
+      }
+      return next;
+    }
+
+    var nextIntact = intact.shift(), lineN = from;
+    cm.doc.iter(from, to, function(line) {
+      if (nextIntact && nextIntact.to == lineN) nextIntact = intact.shift();
+      if (lineIsHidden(cm.doc, line)) {
+        if (line.height != 0) updateLineHeight(line, 0);
+        if (line.widgets && cur.previousSibling) for (var i = 0; i < line.widgets.length; ++i) {
+          var w = line.widgets[i];
+          if (w.showIfHidden) {
+            var prev = cur.previousSibling;
+            if (/pre/i.test(prev.nodeName)) {
+              var wrap = elt("div", null, null, "position: relative");
+              prev.parentNode.replaceChild(wrap, prev);
+              wrap.appendChild(prev);
+              prev = wrap;
+            }
+            var wnode = prev.appendChild(elt("div", [w.node], "CodeMirror-linewidget"));
+            if (!w.handleMouseEvents) wnode.ignoreEvents = true;
+            positionLineWidget(w, wnode, prev, dims);
+          }
+        }
+      } else if (nextIntact && nextIntact.from <= lineN && nextIntact.to > lineN) {
+        // This line is intact. Skip to the actual node. Update its
+        // line number if needed.
+        while (cur.lineObj != line) cur = rm(cur);
+        if (lineNumbers && updateNumbersFrom <= lineN && cur.lineNumber)
+          setTextContent(cur.lineNumber, lineNumberFor(cm.options, lineN));
+        cur = cur.nextSibling;
+      } else {
+        // For lines with widgets, make an attempt to find and reuse
+        // the existing element, so that widgets aren't needlessly
+        // removed and re-inserted into the dom
+        if (line.widgets) for (var j = 0, search = cur, reuse; search && j < 20; ++j, search = search.nextSibling)
+          if (search.lineObj == line && /div/i.test(search.nodeName)) { reuse = search; break; }
+        // This line needs to be generated.
+        var lineNode = buildLineElement(cm, line, lineN, dims, reuse);
+        if (lineNode != reuse) {
+          container.insertBefore(lineNode, cur);
+        } else {
+          while (cur != reuse) cur = rm(cur);
+          cur = cur.nextSibling;
+        }
+
+        lineNode.lineObj = line;
+      }
+      ++lineN;
+    });
+    while (cur) cur = rm(cur);
+  }
+
+  function buildLineElement(cm, line, lineNo, dims, reuse) {
+    var lineElement = lineContent(cm, line);
+    var markers = line.gutterMarkers, display = cm.display, wrap;
+
+    if (!cm.options.lineNumbers && !markers && !line.bgClass && !line.wrapClass && !line.widgets)
+      return lineElement;
+
+    // Lines with gutter elements, widgets or a background class need
+    // to be wrapped again, and have the extra elements added to the
+    // wrapper div
+
+    if (reuse) {
+      reuse.alignable = null;
+      var isOk = true, widgetsSeen = 0, insertBefore = null;
+      for (var n = reuse.firstChild, next; n; n = next) {
+        next = n.nextSibling;
+        if (!/\bCodeMirror-linewidget\b/.test(n.className)) {
+          reuse.removeChild(n);
+        } else {
+          for (var i = 0; i < line.widgets.length; ++i) {
+            var widget = line.widgets[i];
+            if (widget.node == n.firstChild) {
+              if (!widget.above && !insertBefore) insertBefore = n;
+              positionLineWidget(widget, n, reuse, dims);
+              ++widgetsSeen;
+              break;
+            }
+          }
+          if (i == line.widgets.length) { isOk = false; break; }
+        }
+      }
+      reuse.insertBefore(lineElement, insertBefore);
+      if (isOk && widgetsSeen == line.widgets.length) {
+        wrap = reuse;
+        reuse.className = line.wrapClass || "";
+      }
+    }
+    if (!wrap) {
+      wrap = elt("div", null, line.wrapClass, "position: relative");
+      wrap.appendChild(lineElement);
+    }
+    // Kludge to make sure the styled element lies behind the selection (by z-index)
+    if (line.bgClass)
+      wrap.insertBefore(elt("div", null, line.bgClass + " CodeMirror-linebackground"), wrap.firstChild);
+    if (cm.options.lineNumbers || markers) {
+      var gutterWrap = wrap.insertBefore(elt("div", null, null, "position: absolute; left: " +
+                                             (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"),
+                                         wrap.firstChild);
+      if (cm.options.fixedGutter) (wrap.alignable || (wrap.alignable = [])).push(gutterWrap);
+      if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
+        wrap.lineNumber = gutterWrap.appendChild(
+          elt("div", lineNumberFor(cm.options, lineNo),
+              "CodeMirror-linenumber CodeMirror-gutter-elt",
+              "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "
+              + display.lineNumInnerWidth + "px"));
+      if (markers)
+        for (var k = 0; k < cm.options.gutters.length; ++k) {
+          var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
+          if (found)
+            gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +
+                                       dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
+        }
+    }
+    if (ie_lt8) wrap.style.zIndex = 2;
+    if (line.widgets && wrap != reuse) for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
+      var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
+      if (!widget.handleMouseEvents) node.ignoreEvents = true;
+      positionLineWidget(widget, node, wrap, dims);
+      if (widget.above)
+        wrap.insertBefore(node, cm.options.lineNumbers && line.height != 0 ? gutterWrap : lineElement);
+      else
+        wrap.appendChild(node);
+      signalLater(widget, "redraw");
+    }
+    return wrap;
+  }
+
+  function positionLineWidget(widget, node, wrap, dims) {
+    if (widget.noHScroll) {
+      (wrap.alignable || (wrap.alignable = [])).push(node);
+      var width = dims.wrapperWidth;
+      node.style.left = dims.fixedPos + "px";
+      if (!widget.coverGutter) {
+        width -= dims.gutterTotalWidth;
+        node.style.paddingLeft = dims.gutterTotalWidth + "px";
+      }
+      node.style.width = width + "px";
+    }
+    if (widget.coverGutter) {
+      node.style.zIndex = 5;
+      node.style.position = "relative";
+      if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";
+    }
+  }
+
+  // SELECTION / CURSOR
+
+  function updateSelection(cm) {
+    var display = cm.display;
+    var collapsed = posEq(cm.doc.sel.from, cm.doc.sel.to);
+    if (collapsed || cm.options.showCursorWhenSelecting)
+      updateSelectionCursor(cm);
+    else
+      display.cursor.style.display = display.otherCursor.style.display = "none";
+    if (!collapsed)
+      updateSelectionRange(cm);
+    else
+      display.selectionDiv.style.display = "none";
+
+    // Move the hidden textarea near the cursor to prevent scrolling artifacts
+    if (cm.options.moveInputWithCursor) {
+      var headPos = cursorCoords(cm, cm.doc.sel.head, "div");
+      var wrapOff = getRect(display.wrapper), lineOff = getRect(display.lineDiv);
+      display.inputDiv.style.top = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
+                                                        headPos.top + lineOff.top - wrapOff.top)) + "px";
+      display.inputDiv.style.left = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
+                                                         headPos.left + lineOff.left - wrapOff.left)) + "px";
+    }
+  }
+
+  // No selection, plain cursor
+  function updateSelectionCursor(cm) {
+    var display = cm.display, pos = cursorCoords(cm, cm.doc.sel.head, "div");
+    display.cursor.style.left = pos.left + "px";
+    display.cursor.style.top = pos.top + "px";
+    display.cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
+    display.cursor.style.display = "";
+
+    if (pos.other) {
+      display.otherCursor.style.display = "";
+      display.otherCursor.style.left = pos.other.left + "px";
+      display.otherCursor.style.top = pos.other.top + "px";
+      display.otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
+    } else { display.otherCursor.style.display = "none"; }
+  }
+
+  // Highlight selection
+  function updateSelectionRange(cm) {
+    var display = cm.display, doc = cm.doc, sel = cm.doc.sel;
+    var fragment = document.createDocumentFragment();
+    var clientWidth = display.lineSpace.offsetWidth, pl = paddingLeft(cm.display);
+
+    function add(left, top, width, bottom) {
+      if (top < 0) top = 0;
+      fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
+                               "px; top: " + top + "px; width: " + (width == null ? clientWidth - left : width) +
+                               "px; height: " + (bottom - top) + "px"));
+    }
+
+    function drawForLine(line, fromArg, toArg) {
+      var lineObj = getLine(doc, line);
+      var lineLen = lineObj.text.length;
+      var start, end;
+      function coords(ch, bias) {
+        return charCoords(cm, Pos(line, ch), "div", lineObj, bias);
+      }
+
+      iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
+        var leftPos = coords(from, "left"), rightPos, left, right;
+        if (from == to) {
+          rightPos = leftPos;
+          left = right = leftPos.left;
+        } else {
+          rightPos = coords(to - 1, "right");
+          if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }
+          left = leftPos.left;
+          right = rightPos.right;
+        }
+        if (fromArg == null && from == 0) left = pl;
+        if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
+          add(left, leftPos.top, null, leftPos.bottom);
+          left = pl;
+          if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
+        }
+        if (toArg == null && to == lineLen) right = clientWidth;
+        if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
+          start = leftPos;
+        if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
+          end = rightPos;
+        if (left < pl + 1) left = pl;
+        add(left, rightPos.top, right - left, rightPos.bottom);
+      });
+      return {start: start, end: end};
+    }
+
+    if (sel.from.line == sel.to.line) {
+      drawForLine(sel.from.line, sel.from.ch, sel.to.ch);
+    } else {
+      var fromLine = getLine(doc, sel.from.line), toLine = getLine(doc, sel.to.line);
+      var singleVLine = visualLine(doc, fromLine) == visualLine(doc, toLine);
+      var leftEnd = drawForLine(sel.from.line, sel.from.ch, singleVLine ? fromLine.text.length : null).end;
+      var rightStart = drawForLine(sel.to.line, singleVLine ? 0 : null, sel.to.ch).start;
+      if (singleVLine) {
+        if (leftEnd.top < rightStart.top - 2) {
+          add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
+          add(pl, rightStart.top, rightStart.left, rightStart.bottom);
+        } else {
+          add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
+        }
+      }
+      if (leftEnd.bottom < rightStart.top)
+        add(pl, leftEnd.bottom, null, rightStart.top);
+    }
+
+    removeChildrenAndAdd(display.selectionDiv, fragment);
+    display.selectionDiv.style.display = "";
+  }
+
+  // Cursor-blinking
+  function restartBlink(cm) {
+    if (!cm.state.focused) return;
+    var display = cm.display;
+    clearInterval(display.blinker);
+    var on = true;
+    display.cursor.style.visibility = display.otherCursor.style.visibility = "";
+    display.blinker = setInterval(function() {
+      display.cursor.style.visibility = display.otherCursor.style.visibility = (on = !on) ? "" : "hidden";
+    }, cm.options.cursorBlinkRate);
+  }
+
+  // HIGHLIGHT WORKER
+
+  function startWorker(cm, time) {
+    if (cm.doc.mode.startState && cm.doc.frontier < cm.display.showingTo)
+      cm.state.highlight.set(time, bind(highlightWorker, cm));
+  }
+
+  function highlightWorker(cm) {
+    var doc = cm.doc;
+    if (doc.frontier < doc.first) doc.frontier = doc.first;
+    if (doc.frontier >= cm.display.showingTo) return;
+    var end = +new Date + cm.options.workTime;
+    var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));
+    var changed = [], prevChange;
+    doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.showingTo + 500), function(line) {
+      if (doc.frontier >= cm.display.showingFrom) { // Visible
+        var oldStyles = line.styles;
+        line.styles = highlightLine(cm, line, state);
+        var ischange = !oldStyles || oldStyles.length != line.styles.length;
+        for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];
+        if (ischange) {
+          if (prevChange && prevChange.end == doc.frontier) prevChange.end++;
+          else changed.push(prevChange = {start: doc.frontier, end: doc.frontier + 1});
+        }
+        line.stateAfter = copyState(doc.mode, state);
+      } else {
+        processLine(cm, line, state);
+        line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
+      }
+      ++doc.frontier;
+      if (+new Date > end) {
+        startWorker(cm, cm.options.workDelay);
+        return true;
+      }
+    });
+    if (changed.length)
+      operation(cm, function() {
+        for (var i = 0; i < changed.length; ++i)
+          regChange(this, changed[i].start, changed[i].end);
+      })();
+  }
+
+  // Finds the line to start with when starting a parse. Tries to
+  // find a line with a stateAfter, so that it can start with a
+  // valid state. If that fails, it returns the line with the
+  // smallest indentation, which tends to need the least context to
+  // parse correctly.
+  function findStartLine(cm, n, precise) {
+    var minindent, minline, doc = cm.doc;
+    for (var search = n, lim = n - 100; search > lim; --search) {
+      if (search <= doc.first) return doc.first;
+      var line = getLine(doc, search - 1);
+      if (line.stateAfter && (!precise || search <= doc.frontier)) return search;
+      var indented = countColumn(line.text, null, cm.options.tabSize);
+      if (minline == null || minindent > indented) {
+        minline = search - 1;
+        minindent = indented;
+      }
+    }
+    return minline;
+  }
+
+  function getStateBefore(cm, n, precise) {
+    var doc = cm.doc, display = cm.display;
+      if (!doc.mode.startState) return true;
+    var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter;
+    if (!state) state = startState(doc.mode);
+    else state = copyState(doc.mode, state);
+    doc.iter(pos, n, function(line) {
+      processLine(cm, line, state);
+      var save = pos == n - 1 || pos % 5 == 0 || pos >= display.showingFrom && pos < display.showingTo;
+      line.stateAfter = save ? copyState(doc.mode, state) : null;
+      ++pos;
+    });
+    return state;
+  }
+
+  // POSITION MEASUREMENT
+
+  function paddingTop(display) {return display.lineSpace.offsetTop;}
+  function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;}
+  function paddingLeft(display) {
+    var e = removeChildrenAndAdd(display.measure, elt("pre", null, null, "text-align: left")).appendChild(elt("span", "x"));
+    return e.offsetLeft;
+  }
+
+  function measureChar(cm, line, ch, data, bias) {
+    var dir = -1;
+    data = data || measureLine(cm, line);
+
+    for (var pos = ch;; pos += dir) {
+      var r = data[pos];
+      if (r) break;
+      if (dir < 0 && pos == 0) dir = 1;
+    }
+    bias = pos > ch ? "left" : pos < ch ? "right" : bias;
+    if (bias == "left" && r.leftSide) r = r.leftSide;
+    else if (bias == "right" && r.rightSide) r = r.rightSide;
+    return {left: pos < ch ? r.right : r.left,
+            right: pos > ch ? r.left : r.right,
+            top: r.top,
+            bottom: r.bottom};
+  }
+
+  function findCachedMeasurement(cm, line) {
+    var cache = cm.display.measureLineCache;
+    for (var i = 0; i < cache.length; ++i) {
+      var memo = cache[i];
+      if (memo.text == line.text && memo.markedSpans == line.markedSpans &&
+          cm.display.scroller.clientWidth == memo.width &&
+          memo.classes == line.textClass + "|" + line.bgClass + "|" + line.wrapClass)
+        return memo;
+    }
+  }
+
+  function clearCachedMeasurement(cm, line) {
+    var exists = findCachedMeasurement(cm, line);
+    if (exists) exists.text = exists.measure = exists.markedSpans = null;
+  }
+
+  function measureLine(cm, line) {
+    // First look in the cache
+    var cached = findCachedMeasurement(cm, line);
+    if (cached) return cached.measure;
+
+    // Failing that, recompute and store result in cache
+    var measure = measureLineInner(cm, line);
+    var cache = cm.display.measureLineCache;
+    var memo = {text: line.text, width: cm.display.scroller.clientWidth,
+                markedSpans: line.markedSpans, measure: measure,
+                classes: line.textClass + "|" + line.bgClass + "|" + line.wrapClass};
+    if (cache.length == 16) cache[++cm.display.measureLineCachePos % 16] = memo;
+    else cache.push(memo);
+    return measure;
+  }
+
+  function measureLineInner(cm, line) {
+    var display = cm.display, measure = emptyArray(line.text.length);
+    var pre = lineContent(cm, line, measure, true);
+
+    // IE does not cache element positions of inline elements between
+    // calls to getBoundingClientRect. This makes the loop below,
+    // which gathers the positions of all the characters on the line,
+    // do an amount of layout work quadratic to the number of
+    // characters. When line wrapping is off, we try to improve things
+    // by first subdividing the line into a bunch of inline blocks, so
+    // that IE can reuse most of the layout information from caches
+    // for those blocks. This does interfere with line wrapping, so it
+    // doesn't work when wrapping is on, but in that case the
+    // situation is slightly better, since IE does cache line-wrapping
+    // information and only recomputes per-line.
+    if (ie && !ie_lt8 && !cm.options.lineWrapping && pre.childNodes.length > 100) {
+      var fragment = document.createDocumentFragment();
+      var chunk = 10, n = pre.childNodes.length;
+      for (var i = 0, chunks = Math.ceil(n / chunk); i < chunks; ++i) {
+        var wrap = elt("div", null, null, "display: inline-block");
+        for (var j = 0; j < chunk && n; ++j) {
+          wrap.appendChild(pre.firstChild);
+          --n;
+        }
+        fragment.appendChild(wrap);
+      }
+      pre.appendChild(fragment);
+    }
+
+    removeChildrenAndAdd(display.measure, pre);
+
+    var outer = getRect(display.lineDiv);
+    var vranges = [], data = emptyArray(line.text.length), maxBot = pre.offsetHeight;
+    // Work around an IE7/8 bug where it will sometimes have randomly
+    // replaced our pre with a clone at this point.
+    if (ie_lt9 && display.measure.first != pre)
+      removeChildrenAndAdd(display.measure, pre);
+
+    function measureRect(rect) {
+      var top = rect.top - outer.top, bot = rect.bottom - outer.top;
+      if (bot > maxBot) bot = maxBot;
+      if (top < 0) top = 0;
+      for (var i = vranges.length - 2; i >= 0; i -= 2) {
+        var rtop = vranges[i], rbot = vranges[i+1];
+        if (rtop > bot || rbot < top) continue;
+        if (rtop <= top && rbot >= bot ||
+            top <= rtop && bot >= rbot ||
+            Math.min(bot, rbot) - Math.max(top, rtop) >= (bot - top) >> 1) {
+          vranges[i] = Math.min(top, rtop);
+          vranges[i+1] = Math.max(bot, rbot);
+          break;
+        }
+      }
+      if (i < 0) { i = vranges.length; vranges.push(top, bot); }
+      return {left: rect.left - outer.left,
+              right: rect.right - outer.left,
+              top: i, bottom: null};
+    }
+    function finishRect(rect) {
+      rect.bottom = vranges[rect.top+1];
+      rect.top = vranges[rect.top];
+    }
+
+    for (var i = 0, cur; i < measure.length; ++i) if (cur = measure[i]) {
+      var node = cur, rect = null;
+      // A widget might wrap, needs special care
+      if (/\bCodeMirror-widget\b/.test(cur.className) && cur.getClientRects) {
+        if (cur.firstChild.nodeType == 1) node = cur.firstChild;
+        var rects = node.getClientRects();
+        if (rects.length > 1) {
+          rect = data[i] = measureRect(rects[0]);
+          rect.rightSide = measureRect(rects[rects.length - 1]);
+        }
+      }
+      if (!rect) rect = data[i] = measureRect(getRect(node));
+      if (cur.measureRight) rect.right = getRect(cur.measureRight).left;
+      if (cur.leftSide) rect.leftSide = measureRect(getRect(cur.leftSide));
+    }
+    for (var i = 0, cur; i < data.length; ++i) if (cur = data[i]) {
+      finishRect(cur);
+      if (cur.leftSide) finishRect(cur.leftSide);
+      if (cur.rightSide) finishRect(cur.rightSide);
+    }
+    return data;
+  }
+
+  function measureLineWidth(cm, line) {
+    var hasBadSpan = false;
+    if (line.markedSpans) for (var i = 0; i < line.markedSpans; ++i) {
+      var sp = line.markedSpans[i];
+      if (sp.collapsed && (sp.to == null || sp.to == line.text.length)) hasBadSpan = true;
+    }
+    var cached = !hasBadSpan && findCachedMeasurement(cm, line);
+    if (cached) return measureChar(cm, line, line.text.length, cached.measure, "right").right;
+
+    var pre = lineContent(cm, line, null, true);
+    var end = pre.appendChild(zeroWidthElement(cm.display.measure));
+    removeChildrenAndAdd(cm.display.measure, pre);
+    return getRect(end).right - getRect(cm.display.lineDiv).left;
+  }
+
+  function clearCaches(cm) {
+    cm.display.measureLineCache.length = cm.display.measureLineCachePos = 0;
+    cm.display.cachedCharWidth = cm.display.cachedTextHeight = null;
+    if (!cm.options.lineWrapping) cm.display.maxLineChanged = true;
+    cm.display.lineNumChars = null;
+  }
+
+  function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; }
+  function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; }
+
+  // Context is one of "line", "div" (display.lineDiv), "local"/null (editor), or "page"
+  function intoCoordSystem(cm, lineObj, rect, context) {
+    if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
+      var size = widgetHeight(lineObj.widgets[i]);
+      rect.top += size; rect.bottom += size;
+    }
+    if (context == "line") return rect;
+    if (!context) context = "local";
+    var yOff = heightAtLine(cm, lineObj);
+    if (context == "local") yOff += paddingTop(cm.display);
+    else yOff -= cm.display.viewOffset;
+    if (context == "page" || context == "window") {
+      var lOff = getRect(cm.display.lineSpace);
+      yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
+      var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
+      rect.left += xOff; rect.right += xOff;
+    }
+    rect.top += yOff; rect.bottom += yOff;
+    return rect;
+  }
+
+  // Context may be "window", "page", "div", or "local"/null
+  // Result is in "div" coords
+  function fromCoordSystem(cm, coords, context) {
+    if (context == "div") return coords;
+    var left = coords.left, top = coords.top;
+    // First move into "page" coordinate system
+    if (context == "page") {
+      left -= pageScrollX();
+      top -= pageScrollY();
+    } else if (context == "local" || !context) {
+      var localBox = getRect(cm.display.sizer);
+      left += localBox.left;
+      top += localBox.top;
+    }
+
+    var lineSpaceBox = getRect(cm.display.lineSpace);
+    return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top};
+  }
+
+  function charCoords(cm, pos, context, lineObj, bias) {
+    if (!lineObj) lineObj = getLine(cm.doc, pos.line);
+    return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, null, bias), context);
+  }
+
+  function cursorCoords(cm, pos, context, lineObj, measurement) {
+    lineObj = lineObj || getLine(cm.doc, pos.line);
+    if (!measurement) measurement = measureLine(cm, lineObj);
+    function get(ch, right) {
+      var m = measureChar(cm, lineObj, ch, measurement, right ? "right" : "left");
+      if (right) m.left = m.right; else m.right = m.left;
+      return intoCoordSystem(cm, lineObj, m, context);
+    }
+    function getBidi(ch, partPos) {
+      var part = order[partPos], right = part.level % 2;
+      if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) {
+        part = order[--partPos];
+        ch = bidiRight(part) - (part.level % 2 ? 0 : 1);
+        right = true;
+      } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) {
+        part = order[++partPos];
+        ch = bidiLeft(part) - part.level % 2;
+        right = false;
+      }
+      if (right && ch == part.to && ch > part.from) return get(ch - 1);
+      return get(ch, right);
+    }
+    var order = getOrder(lineObj), ch = pos.ch;
+    if (!order) return get(ch);
+    var partPos = getBidiPartAt(order, ch);
+    var val = getBidi(ch, partPos);
+    if (bidiOther != null) val.other = getBidi(ch, bidiOther);
+    return val;
+  }
+
+  function PosWithInfo(line, ch, outside, xRel) {
+    var pos = new Pos(line, ch);
+    pos.xRel = xRel;
+    if (outside) pos.outside = true;
+    return pos;
+  }
+
+  // Coords must be lineSpace-local
+  function coordsChar(cm, x, y) {
+    var doc = cm.doc;
+    y += cm.display.viewOffset;
+    if (y < 0) return PosWithInfo(doc.first, 0, true, -1);
+    var lineNo = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
+    if (lineNo > last)
+      return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);
+    if (x < 0) x = 0;
+
+    for (;;) {
+      var lineObj = getLine(doc, lineNo);
+      var found = coordsCharInner(cm, lineObj, lineNo, x, y);
+      var merged = collapsedSpanAtEnd(lineObj);
+      var mergedPos = merged && merged.find();
+      if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
+        lineNo = mergedPos.to.line;
+      else
+        return found;
+    }
+  }
+
+  function coordsCharInner(cm, lineObj, lineNo, x, y) {
+    var innerOff = y - heightAtLine(cm, lineObj);
+    var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth;
+    var measurement = measureLine(cm, lineObj);
+
+    function getX(ch) {
+      var sp = cursorCoords(cm, Pos(lineNo, ch), "line",
+                            lineObj, measurement);
+      wrongLine = true;
+      if (innerOff > sp.bottom) return sp.left - adjust;
+      else if (innerOff < sp.top) return sp.left + adjust;
+      else wrongLine = false;
+      return sp.left;
+    }
+
+    var bidi = getOrder(lineObj), dist = lineObj.text.length;
+    var from = lineLeft(lineObj), to = lineRight(lineObj);
+    var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine;
+
+    if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1);
+    // Do a binary search between these bounds.
+    for (;;) {
+      if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
+        var ch = x < fromX || x - fromX <= toX - x ? from : to;
+        var xDiff = x - (ch == from ? fromX : toX);
+        while (isExtendingChar.test(lineObj.text.charAt(ch))) ++ch;
+        var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside,
+                              xDiff < 0 ? -1 : xDiff ? 1 : 0);
+        return pos;
+      }
+      var step = Math.ceil(dist / 2), middle = from + step;
+      if (bidi) {
+        middle = from;
+        for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);
+      }
+      var middleX = getX(middle);
+      if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;}
+      else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;}
+    }
+  }
+
+  var measureText;
+  function textHeight(display) {
+    if (display.cachedTextHeight != null) return display.cachedTextHeight;
+    if (measureText == null) {
+      measureText = elt("pre");
+      // Measure a bunch of lines, for browsers that compute
+      // fractional heights.
+      for (var i = 0; i < 49; ++i) {
+        measureText.appendChild(document.createTextNode("x"));
+        measureText.appendChild(elt("br"));
+      }
+      measureText.appendChild(document.createTextNode("x"));
+    }
+    removeChildrenAndAdd(display.measure, measureText);
+    var height = measureText.offsetHeight / 50;
+    if (height > 3) display.cachedTextHeight = height;
+    removeChildren(display.measure);
+    return height || 1;
+  }
+
+  function charWidth(display) {
+    if (display.cachedCharWidth != null) return display.cachedCharWidth;
+    var anchor = elt("span", "x");
+    var pre = elt("pre", [anchor]);
+    removeChildrenAndAdd(display.measure, pre);
+    var width = anchor.offsetWidth;
+    if (width > 2) display.cachedCharWidth = width;
+    return width || 10;
+  }
+
+  // OPERATIONS
+
+  // Operations are used to wrap changes in such a way that each
+  // change won't have to update the cursor and display (which would
+  // be awkward, slow, and error-prone), but instead updates are
+  // batched and then all combined and executed at once.
+
+  var nextOpId = 0;
+  function startOperation(cm) {
+    cm.curOp = {
+      // An array of ranges of lines that have to be updated. See
+      // updateDisplay.
+      changes: [],
+      forceUpdate: false,
+      updateInput: null,
+      userSelChange: null,
+      textChanged: null,
+      selectionChanged: false,
+      cursorActivity: false,
+      updateMaxLine: false,
+      updateScrollPos: false,
+      id: ++nextOpId
+    };
+    if (!delayedCallbackDepth++) delayedCallbacks = [];
+  }
+
+  function endOperation(cm) {
+    var op = cm.curOp, doc = cm.doc, display = cm.display;
+    cm.curOp = null;
+
+    if (op.updateMaxLine) computeMaxLength(cm);
+    if (display.maxLineChanged && !cm.options.lineWrapping && display.maxLine) {
+      var width = measureLineWidth(cm, display.maxLine);
+      display.sizer.style.minWidth = Math.max(0, width + 3 + scrollerCutOff) + "px";
+      display.maxLineChanged = false;
+      var maxScrollLeft = Math.max(0, display.sizer.offsetLeft + display.sizer.offsetWidth - display.scroller.clientWidth);
+      if (maxScrollLeft < doc.scrollLeft && !op.updateScrollPos)
+        setScrollLeft(cm, Math.min(display.scroller.scrollLeft, maxScrollLeft), true);
+    }
+    var newScrollPos, updated;
+    if (op.updateScrollPos) {
+      newScrollPos = op.updateScrollPos;
+    } else if (op.selectionChanged && display.scroller.clientHeight) { // don't rescroll if not visible
+      var coords = cursorCoords(cm, doc.sel.head);
+      newScrollPos = calculateScrollPos(cm, coords.left, coords.top, coords.left, coords.bottom);
+    }
+    if (op.changes.length || op.forceUpdate || newScrollPos && newScrollPos.scrollTop != null) {
+      updated = updateDisplay(cm, op.changes, newScrollPos && newScrollPos.scrollTop, op.forceUpdate);
+      if (cm.display.scroller.offsetHeight) cm.doc.scrollTop = cm.display.scroller.scrollTop;
+    }
+    if (!updated && op.selectionChanged) updateSelection(cm);
+    if (op.updateScrollPos) {
+      display.scroller.scrollTop = display.scrollbarV.scrollTop = doc.scrollTop = newScrollPos.scrollTop;
+      display.scroller.scrollLeft = display.scrollbarH.scrollLeft = doc.scrollLeft = newScrollPos.scrollLeft;
+      alignHorizontally(cm);
+      if (op.scrollToPos)
+        scrollPosIntoView(cm, clipPos(cm.doc, op.scrollToPos), op.scrollToPosMargin);
+    } else if (newScrollPos) {
+      scrollCursorIntoView(cm);
+    }
+    if (op.selectionChanged) restartBlink(cm);
+
+    if (cm.state.focused && op.updateInput)
+      resetInput(cm, op.userSelChange);
+
+    var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
+    if (hidden) for (var i = 0; i < hidden.length; ++i)
+      if (!hidden[i].lines.length) signal(hidden[i], "hide");
+    if (unhidden) for (var i = 0; i < unhidden.length; ++i)
+      if (unhidden[i].lines.length) signal(unhidden[i], "unhide");
+
+    var delayed;
+    if (!--delayedCallbackDepth) {
+      delayed = delayedCallbacks;
+      delayedCallbacks = null;
+    }
+    if (op.textChanged)
+      signal(cm, "change", cm, op.textChanged);
+    if (op.cursorActivity) signal(cm, "cursorActivity", cm);
+    if (delayed) for (var i = 0; i < delayed.length; ++i) delayed[i]();
+  }
+
+  // Wraps a function in an operation. Returns the wrapped function.
+  function operation(cm1, f) {
+    return function() {
+      var cm = cm1 || this, withOp = !cm.curOp;
+      if (withOp) startOperation(cm);
+      try { var result = f.apply(cm, arguments); }
+      finally { if (withOp) endOperation(cm); }
+      return result;
+    };
+  }
+  function docOperation(f) {
+    return function() {
+      var withOp = this.cm && !this.cm.curOp, result;
+      if (withOp) startOperation(this.cm);
+      try { result = f.apply(this, arguments); }
+      finally { if (withOp) endOperation(this.cm); }
+      return result;
+    };
+  }
+  function runInOp(cm, f) {
+    var withOp = !cm.curOp, result;
+    if (withOp) startOperation(cm);
+    try { result = f(); }
+    finally { if (withOp) endOperation(cm); }
+    return result;
+  }
+
+  function regChange(cm, from, to, lendiff) {
+    if (from == null) from = cm.doc.first;
+    if (to == null) to = cm.doc.first + cm.doc.size;
+    cm.curOp.changes.push({from: from, to: to, diff: lendiff});
+  }
+
+  // INPUT HANDLING
+
+  function slowPoll(cm) {
+    if (cm.display.pollingFast) return;
+    cm.display.poll.set(cm.options.pollInterval, function() {
+      readInput(cm);
+      if (cm.state.focused) slowPoll(cm);
+    });
+  }
+
+  function fastPoll(cm) {
+    var missed = false;
+    cm.display.pollingFast = true;
+    function p() {
+      var changed = readInput(cm);
+      if (!changed && !missed) {missed = true; cm.display.poll.set(60, p);}
+      else {cm.display.pollingFast = false; slowPoll(cm);}
+    }
+    cm.display.poll.set(20, p);
+  }
+
+  // prevInput is a hack to work with IME. If we reset the textarea
+  // on every change, that breaks IME. So we look for changes
+  // compared to the previous content instead. (Modern browsers have
+  // events that indicate IME taking place, but these are not widely
+  // supported or compatible enough yet to rely on.)
+  function readInput(cm) {
+    var input = cm.display.input, prevInput = cm.display.prevInput, doc = cm.doc, sel = doc.sel;
+    if (!cm.state.focused || hasSelection(input) || isReadOnly(cm) || cm.state.disableInput) return false;
+    var text = input.value;
+    if (text == prevInput && posEq(sel.from, sel.to)) return false;
+    if (ie && !ie_lt9 && cm.display.inputHasSelection === text) {
+      resetInput(cm, true);
+      return false;
+    }
+
+    var withOp = !cm.curOp;
+    if (withOp) startOperation(cm);
+    sel.shift = false;
+    var same = 0, l = Math.min(prevInput.length, text.length);
+    while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same;
+    var from = sel.from, to = sel.to;
+    if (same < prevInput.length)
+      from = Pos(from.line, from.ch - (prevInput.length - same));
+    else if (cm.state.overwrite && posEq(from, to) && !cm.state.pasteIncoming)
+      to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + (text.length - same)));
+
+    var updateInput = cm.curOp.updateInput;
+    var changeEvent = {from: from, to: to, text: splitLines(text.slice(same)),
+                       origin: cm.state.pasteIncoming ? "paste" : "+input"};
+    makeChange(cm.doc, changeEvent, "end");
+    cm.curOp.updateInput = updateInput;
+    signalLater(cm, "inputRead", cm, changeEvent);
+
+    if (text.length > 1000 || text.indexOf("\n") > -1) input.value = cm.display.prevInput = "";
+    else cm.display.prevInput = text;
+    if (withOp) endOperation(cm);
+    cm.state.pasteIncoming = false;
+    return true;
+  }
+
+  function resetInput(cm, user) {
+    var minimal, selected, doc = cm.doc;
+    if (!posEq(doc.sel.from, doc.sel.to)) {
+      cm.display.prevInput = "";
+      minimal = hasCopyEvent &&
+        (doc.sel.to.line - doc.sel.from.line > 100 || (selected = cm.getSelection()).length > 1000);
+      var content = minimal ? "-" : selected || cm.getSelection();
+      cm.display.input.value = content;
+      if (cm.state.focused) selectInput(cm.display.input);
+      if (ie && !ie_lt9) cm.display.inputHasSelection = content;
+    } else if (user) {
+      cm.display.prevInput = cm.display.input.value = "";
+      if (ie && !ie_lt9) cm.display.inputHasSelection = null;
+    }
+    cm.display.inaccurateSelection = minimal;
+  }
+
+  function focusInput(cm) {
+    if (cm.options.readOnly != "nocursor" && (!mobile || document.activeElement != cm.display.input))
+      cm.display.input.focus();
+  }
+
+  function isReadOnly(cm) {
+    return cm.options.readOnly || cm.doc.cantEdit;
+  }
+
+  // EVENT HANDLERS
+
+  function registerEventHandlers(cm) {
+    var d = cm.display;
+    on(d.scroller, "mousedown", operation(cm, onMouseDown));
+    if (ie)
+      on(d.scroller, "dblclick", operation(cm, function(e) {
+        if (signalDOMEvent(cm, e)) return;
+        var pos = posFromMouse(cm, e);
+        if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return;
+        e_preventDefault(e);
+        var word = findWordAt(getLine(cm.doc, pos.line).text, pos);
+        extendSelection(cm.doc, word.from, word.to);
+      }));
+    else
+      on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); });
+    on(d.lineSpace, "selectstart", function(e) {
+      if (!eventInWidget(d, e)) e_preventDefault(e);
+    });
+    // Gecko browsers fire contextmenu *after* opening the menu, at
+    // which point we can't mess with it anymore. Context menu is
+    // handled in onMouseDown for Gecko.
+    if (!captureMiddleClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);});
+
+    on(d.scroller, "scroll", function() {
+      if (d.scroller.clientHeight) {
+        setScrollTop(cm, d.scroller.scrollTop);
+        setScrollLeft(cm, d.scroller.scrollLeft, true);
+        signal(cm, "scroll", cm);
+      }
+    });
+    on(d.scrollbarV, "scroll", function() {
+      if (d.scroller.clientHeight) setScrollTop(cm, d.scrollbarV.scrollTop);
+    });
+    on(d.scrollbarH, "scroll", function() {
+      if (d.scroller.clientHeight) setScrollLeft(cm, d.scrollbarH.scrollLeft);
+    });
+
+    on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);});
+    on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);});
+
+    function reFocus() { if (cm.state.focused) setTimeout(bind(focusInput, cm), 0); }
+    on(d.scrollbarH, "mousedown", reFocus);
+    on(d.scrollbarV, "mousedown", reFocus);
+    // Prevent wrapper from ever scrolling
+    on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
+
+    var resizeTimer;
+    function onResize() {
+      if (resizeTimer == null) resizeTimer = setTimeout(function() {
+        resizeTimer = null;
+        // Might be a text scaling operation, clear size caches.
+        d.cachedCharWidth = d.cachedTextHeight = knownScrollbarWidth = null;
+        clearCaches(cm);
+        runInOp(cm, bind(regChange, cm));
+      }, 100);
+    }
+    on(window, "resize", onResize);
+    // Above handler holds on to the editor and its data structures.
+    // Here we poll to unregister it when the editor is no longer in
+    // the document, so that it can be garbage-collected.
+    function unregister() {
+      for (var p = d.wrapper.parentNode; p && p != document.body; p = p.parentNode) {}
+      if (p) setTimeout(unregister, 5000);
+      else off(window, "resize", onResize);
+    }
+    setTimeout(unregister, 5000);
+
+    on(d.input, "keyup", operation(cm, function(e) {
+      if (signalDOMEvent(cm, e) || cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return;
+      if (e.keyCode == 16) cm.doc.sel.shift = false;
+    }));
+    on(d.input, "input", bind(fastPoll, cm));
+    on(d.input, "keydown", operation(cm, onKeyDown));
+    on(d.input, "keypress", operation(cm, onKeyPress));
+    on(d.input, "focus", bind(onFocus, cm));
+    on(d.input, "blur", bind(onBlur, cm));
+
+    function drag_(e) {
+      if (signalDOMEvent(cm, e) || cm.options.onDragEvent && cm.options.onDragEvent(cm, addStop(e))) return;
+      e_stop(e);
+    }
+    if (cm.options.dragDrop) {
+      on(d.scroller, "dragstart", function(e){onDragStart(cm, e);});
+      on(d.scroller, "dragenter", drag_);
+      on(d.scroller, "dragover", drag_);
+      on(d.scroller, "drop", operation(cm, onDrop));
+    }
+    on(d.scroller, "paste", function(e){
+      if (eventInWidget(d, e)) return;
+      focusInput(cm);
+      fastPoll(cm);
+    });
+    on(d.input, "paste", function() {
+      cm.state.pasteIncoming = true;
+      fastPoll(cm);
+    });
+
+    function prepareCopy() {
+      if (d.inaccurateSelection) {
+        d.prevInput = "";
+        d.inaccurateSelection = false;
+        d.input.value = cm.getSelection();
+        selectInput(d.input);
+      }
+    }
+    on(d.input, "cut", prepareCopy);
+    on(d.input, "copy", prepareCopy);
+
+    // Needed to handle Tab key in KHTML
+    if (khtml) on(d.sizer, "mouseup", function() {
+        if (document.activeElement == d.input) d.input.blur();
+        focusInput(cm);
+    });
+  }
+
+  function eventInWidget(display, e) {
+    for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
+      if (!n || n.ignoreEvents || n.parentNode == display.sizer && n != display.mover) return true;
+    }
+  }
+
+  function posFromMouse(cm, e, liberal) {
+    var display = cm.display;
+    if (!liberal) {
+      var target = e_target(e);
+      if (target == display.scrollbarH || target == display.scrollbarH.firstChild ||
+          target == display.scrollbarV || target == display.scrollbarV.firstChild ||
+          target == display.scrollbarFiller || target == display.gutterFiller) return null;
+    }
+    var x, y, space = getRect(display.lineSpace);
+    // Fails unpredictably on IE[67] when mouse is dragged around quickly.
+    try { x = e.clientX; y = e.clientY; } catch (e) { return null; }
+    return coordsChar(cm, x - space.left, y - space.top);
+  }
+
+  var lastClick, lastDoubleClick;
+  function onMouseDown(e) {
+    if (signalDOMEvent(this, e)) return;
+    var cm = this, display = cm.display, doc = cm.doc, sel = doc.sel;
+    sel.shift = e.shiftKey;
+
+    if (eventInWidget(display, e)) {
+      if (!webkit) {
+        display.scroller.draggable = false;
+        setTimeout(function(){display.scroller.draggable = true;}, 100);
+      }
+      return;
+    }
+    if (clickInGutter(cm, e)) return;
+    var start = posFromMouse(cm, e);
+
+    switch (e_button(e)) {
+    case 3:
+      if (captureMiddleClick) onContextMenu.call(cm, cm, e);
+      return;
+    case 2:
+      if (start) extendSelection(cm.doc, start);
+      setTimeout(bind(focusInput, cm), 20);
+      e_preventDefault(e);
+      return;
+    }
+    // For button 1, if it was clicked inside the editor
+    // (posFromMouse returning non-null), we have to adjust the
+    // selection.
+    if (!start) {if (e_target(e) == display.scroller) e_preventDefault(e); return;}
+
+    if (!cm.state.focused) onFocus(cm);
+
+    var now = +new Date, type = "single";
+    if (lastDoubleClick && lastDoubleClick.time > now - 400 && posEq(lastDoubleClick.pos, start)) {
+      type = "triple";
+      e_preventDefault(e);
+      setTimeout(bind(focusInput, cm), 20);
+      selectLine(cm, start.line);
+    } else if (lastClick && lastClick.time > now - 400 && posEq(lastClick.pos, start)) {
+      type = "double";
+      lastDoubleClick = {time: now, pos: start};
+      e_preventDefault(e);
+      var word = findWordAt(getLine(doc, start.line).text, start);
+      extendSelection(cm.doc, word.from, word.to);
+    } else { lastClick = {time: now, pos: start}; }
+
+    var last = start;
+    if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) && !posEq(sel.from, sel.to) &&
+        !posLess(start, sel.from) && !posLess(sel.to, start) && type == "single") {
+      var dragEnd = operation(cm, function(e2) {
+        if (webkit) display.scroller.draggable = false;
+        cm.state.draggingText = false;
+        off(document, "mouseup", dragEnd);
+        off(display.scroller, "drop", dragEnd);
+        if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
+          e_preventDefault(e2);
+          extendSelection(cm.doc, start);
+          focusInput(cm);
+        }
+      });
+      // Let the drag handler handle this.
+      if (webkit) display.scroller.draggable = true;
+      cm.state.draggingText = dragEnd;
+      // IE's approach to draggable
+      if (display.scroller.dragDrop) display.scroller.dragDrop();
+      on(document, "mouseup", dragEnd);
+      on(display.scroller, "drop", dragEnd);
+      return;
+    }
+    e_preventDefault(e);
+    if (type == "single") extendSelection(cm.doc, clipPos(doc, start));
+
+    var startstart = sel.from, startend = sel.to, lastPos = start;
+
+    function doSelect(cur) {
+      if (posEq(lastPos, cur)) return;
+      lastPos = cur;
+
+      if (type == "single") {
+        extendSelection(cm.doc, clipPos(doc, start), cur);
+        return;
+      }
+
+      startstart = clipPos(doc, startstart);
+      startend = clipPos(doc, startend);
+      if (type == "double") {
+        var word = findWordAt(getLine(doc, cur.line).text, cur);
+        if (posLess(cur, startstart)) extendSelection(cm.doc, word.from, startend);
+        else extendSelection(cm.doc, startstart, word.to);
+      } else if (type == "triple") {
+        if (posLess(cur, startstart)) extendSelection(cm.doc, startend, clipPos(doc, Pos(cur.line, 0)));
+        else extendSelection(cm.doc, startstart, clipPos(doc, Pos(cur.line + 1, 0)));
+      }
+    }
+
+    var editorSize = getRect(display.wrapper);
+    // Used to ensure timeout re-tries don't fire when another extend
+    // happened in the meantime (clearTimeout isn't reliable -- at
+    // least on Chrome, the timeouts still happen even when cleared,
+    // if the clear happens after their scheduled firing time).
+    var counter = 0;
+
+    function extend(e) {
+      var curCount = ++counter;
+      var cur = posFromMouse(cm, e, true);
+      if (!cur) return;
+      if (!posEq(cur, last)) {
+        if (!cm.state.focused) onFocus(cm);
+        last = cur;
+        doSelect(cur);
+        var visible = visibleLines(display, doc);
+        if (cur.line >= visible.to || cur.line < visible.from)
+          setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);
+      } else {
+        var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
+        if (outside) setTimeout(operation(cm, function() {
+          if (counter != curCount) return;
+          display.scroller.scrollTop += outside;
+          extend(e);
+        }), 50);
+      }
+    }
+
+    function done(e) {
+      counter = Infinity;
+      e_preventDefault(e);
+      focusInput(cm);
+      off(document, "mousemove", move);
+      off(document, "mouseup", up);
+    }
+
+    var move = operation(cm, function(e) {
+      if (!ie && !e_button(e)) done(e);
+      else extend(e);
+    });
+    var up = operation(cm, done);
+    on(document, "mousemove", move);
+    on(document, "mouseup", up);
+  }
+
+  function clickInGutter(cm, e) {
+    var display = cm.display;
+    try { var mX = e.clientX, mY = e.clientY; }
+    catch(e) { return false; }
+
+    if (mX >= Math.floor(getRect(display.gutters).right)) return false;
+    e_preventDefault(e);
+    if (!hasHandler(cm, "gutterClick")) return true;
+
+    var lineBox = getRect(display.lineDiv);
+    if (mY > lineBox.bottom) return true;
+    mY -= lineBox.top - display.viewOffset;
+
+    for (var i = 0; i < cm.options.gutters.length; ++i) {
+      var g = display.gutters.childNodes[i];
+      if (g && getRect(g).right >= mX) {
+        var line = lineAtHeight(cm.doc, mY);
+        var gutter = cm.options.gutters[i];
+        signalLater(cm, "gutterClick", cm, line, gutter, e);
+        break;
+      }
+    }
+    return true;
+  }
+
+  // Kludge to work around strange IE behavior where it'll sometimes
+  // re-fire a series of drag-related events right after the drop (#1551)
+  var lastDrop = 0;
+
+  function onDrop(e) {
+    var cm = this;
+    if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e) || (cm.options.onDragEvent && cm.options.onDragEvent(cm, addStop(e))))
+      return;
+    e_preventDefault(e);
+    if (ie) lastDrop = +new Date;
+    var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
+    if (!pos || isReadOnly(cm)) return;
+    if (files && files.length && window.FileReader && window.File) {
+      var n = files.length, text = Array(n), read = 0;
+      var loadFile = function(file, i) {
+        var reader = new FileReader;
+        reader.onload = function() {
+          text[i] = reader.result;
+          if (++read == n) {
+            pos = clipPos(cm.doc, pos);
+            makeChange(cm.doc, {from: pos, to: pos, text: splitLines(text.join("\n")), origin: "paste"}, "around");
+          }
+        };
+        reader.readAsText(file);
+      };
+      for (var i = 0; i < n; ++i) loadFile(files[i], i);
+    } else {
+      // Don't do a replace if the drop happened inside of the selected text.
+      if (cm.state.draggingText && !(posLess(pos, cm.doc.sel.from) || posLess(cm.doc.sel.to, pos))) {
+        cm.state.draggingText(e);
+        // Ensure the editor is re-focused
+        setTimeout(bind(focusInput, cm), 20);
+        return;
+      }
+      try {
+        var text = e.dataTransfer.getData("Text");
+        if (text) {
+          var curFrom = cm.doc.sel.from, curTo = cm.doc.sel.to;
+          setSelection(cm.doc, pos, pos);
+          if (cm.state.draggingText) replaceRange(cm.doc, "", curFrom, curTo, "paste");
+          cm.replaceSelection(text, null, "paste");
+          focusInput(cm);
+          onFocus(cm);
+        }
+      }
+      catch(e){}
+    }
+  }
+
+  function onDragStart(cm, e) {
+    if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; }
+    if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return;
+
+    var txt = cm.getSelection();
+    e.dataTransfer.setData("Text", txt);
+
+    // Use dummy image instead of default browsers image.
+    // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
+    if (e.dataTransfer.setDragImage && !safari) {
+      var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
+      if (opera) {
+        img.width = img.height = 1;
+        cm.display.wrapper.appendChild(img);
+        // Force a relayout, or Opera won't use our image for some obscure reason
+        img._top = img.offsetTop;
+      }
+      e.dataTransfer.setDragImage(img, 0, 0);
+      if (opera) img.parentNode.removeChild(img);
+    }
+  }
+
+  function setScrollTop(cm, val) {
+    if (Math.abs(cm.doc.scrollTop - val) < 2) return;
+    cm.doc.scrollTop = val;
+    if (!gecko) updateDisplay(cm, [], val);
+    if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
+    if (cm.display.scrollbarV.scrollTop != val) cm.display.scrollbarV.scrollTop = val;
+    if (gecko) updateDisplay(cm, []);
+    startWorker(cm, 100);
+  }
+  function setScrollLeft(cm, val, isScroller) {
+    if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return;
+    val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
+    cm.doc.scrollLeft = val;
+    alignHorizontally(cm);
+    if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
+    if (cm.display.scrollbarH.scrollLeft != val) cm.display.scrollbarH.scrollLeft = val;
+  }
+
+  // Since the delta values reported on mouse wheel events are
+  // unstandardized between browsers and even browser versions, and
+  // generally horribly unpredictable, this code starts by measuring
+  // the scroll effect that the first few mouse wheel events have,
+  // and, from that, detects the way it can convert deltas to pixel
+  // offsets afterwards.
+  //
+  // The reason we want to know the amount a wheel event will scroll
+  // is that it gives us a chance to update the display before the
+  // actual scrolling happens, reducing flickering.
+
+  var wheelSamples = 0, wheelPixelsPerUnit = null;
+  // Fill in a browser-detected starting value on browsers where we
+  // know one. These don't have to be accurate -- the result of them
+  // being wrong would just be a slight flicker on the first wheel
+  // scroll (if it is large enough).
+  if (ie) wheelPixelsPerUnit = -.53;
+  else if (gecko) wheelPixelsPerUnit = 15;
+  else if (chrome) wheelPixelsPerUnit = -.7;
+  else if (safari) wheelPixelsPerUnit = -1/3;
+
+  function onScrollWheel(cm, e) {
+    var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
+    if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
+    if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;
+    else if (dy == null) dy = e.wheelDelta;
+
+    var display = cm.display, scroll = display.scroller;
+    // Quit if there's nothing to scroll here
+    if (!(dx && scroll.scrollWidth > scroll.clientWidth ||
+          dy && scroll.scrollHeight > scroll.clientHeight)) return;
+
+    // Webkit browsers on OS X abort momentum scrolls when the target
+    // of the scroll event is removed from the scrollable element.
+    // This hack (see related code in patchDisplay) makes sure the
+    // element is kept around.
+    if (dy && mac && webkit) {
+      for (var cur = e.target; cur != scroll; cur = cur.parentNode) {
+        if (cur.lineObj) {
+          cm.display.currentWheelTarget = cur;
+          break;
+        }
+      }
+    }
+
+    // On some browsers, horizontal scrolling will cause redraws to
+    // happen before the gutter has been realigned, causing it to
+    // wriggle around in a most unseemly way. When we have an
+    // estimated pixels/delta value, we just handle horizontal
+    // scrolling entirely here. It'll be slightly off from native, but
+    // better than glitching out.
+    if (dx && !gecko && !opera && wheelPixelsPerUnit != null) {
+      if (dy)
+        setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));
+      setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
+      e_preventDefault(e);
+      display.wheelStartX = null; // Abort measurement, if in progress
+      return;
+    }
+
+    if (dy && wheelPixelsPerUnit != null) {
+      var pixels = dy * wheelPixelsPerUnit;
+      var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
+      if (pixels < 0) top = Math.max(0, top + pixels - 50);
+      else bot = Math.min(cm.doc.height, bot + pixels + 50);
+      updateDisplay(cm, [], {top: top, bottom: bot});
+    }
+
+    if (wheelSamples < 20) {
+      if (display.wheelStartX == null) {
+        display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
+        display.wheelDX = dx; display.wheelDY = dy;
+        setTimeout(function() {
+          if (display.wheelStartX == null) return;
+          var movedX = scroll.scrollLeft - display.wheelStartX;
+          var movedY = scroll.scrollTop - display.wheelStartY;
+          var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
+            (movedX && display.wheelDX && movedX / display.wheelDX);
+          display.wheelStartX = display.wheelStartY = null;
+          if (!sample) return;
+          wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
+          ++wheelSamples;
+        }, 200);
+      } else {
+        display.wheelDX += dx; display.wheelDY += dy;
+      }
+    }
+  }
+
+  function doHandleBinding(cm, bound, dropShift) {
+    if (typeof bound == "string") {
+      bound = commands[bound];
+      if (!bound) return false;
+    }
+    // Ensure previous input has been read, so that the handler sees a
+    // consistent view of the document
+    if (cm.display.pollingFast && readInput(cm)) cm.display.pollingFast = false;
+    var doc = cm.doc, prevShift = doc.sel.shift, done = false;
+    try {
+      if (isReadOnly(cm)) cm.state.suppressEdits = true;
+      if (dropShift) doc.sel.shift = false;
+      done = bound(cm) != Pass;
+    } finally {
+      doc.sel.shift = prevShift;
+      cm.state.suppressEdits = false;
+    }
+    return done;
+  }
+
+  function allKeyMaps(cm) {
+    var maps = cm.state.keyMaps.slice(0);
+    if (cm.options.extraKeys) maps.push(cm.options.extraKeys);
+    maps.push(cm.options.keyMap);
+    return maps;
+  }
+
+  var maybeTransition;
+  function handleKeyBinding(cm, e) {
+    // Handle auto keymap transitions
+    var startMap = getKeyMap(cm.options.keyMap), next = startMap.auto;
+    clearTimeout(maybeTransition);
+    if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() {
+      if (getKeyMap(cm.options.keyMap) == startMap) {
+        cm.options.keyMap = (next.call ? next.call(null, cm) : next);
+        keyMapChanged(cm);
+      }
+    }, 50);
+
+    var name = keyName(e, true), handled = false;
+    if (!name) return false;
+    var keymaps = allKeyMaps(cm);
+
+    if (e.shiftKey) {
+      // First try to resolve full name (including 'Shift-'). Failing
+      // that, see if there is a cursor-motion command (starting with
+      // 'go') bound to the keyname without 'Shift-'.
+      handled = lookupKey("Shift-" + name, keymaps, function(b) {return doHandleBinding(cm, b, true);})
+             || lookupKey(name, keymaps, function(b) {
+                  if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
+                    return doHandleBinding(cm, b);
+                });
+    } else {
+      handled = lookupKey(name, keymaps, function(b) { return doHandleBinding(cm, b); });
+    }
+
+    if (handled) {
+      e_preventDefault(e);
+      restartBlink(cm);
+      if (ie_lt9) { e.oldKeyCode = e.keyCode; e.keyCode = 0; }
+      signalLater(cm, "keyHandled", cm, name, e);
+    }
+    return handled;
+  }
+
+  function handleCharBinding(cm, e, ch) {
+    var handled = lookupKey("'" + ch + "'", allKeyMaps(cm),
+                            function(b) { return doHandleBinding(cm, b, true); });
+    if (handled) {
+      e_preventDefault(e);
+      restartBlink(cm);
+      signalLater(cm, "keyHandled", cm, "'" + ch + "'", e);
+    }
+    return handled;
+  }
+
+  var lastStoppedKey = null;
+  function onKeyDown(e) {
+    var cm = this;
+    if (!cm.state.focused) onFocus(cm);
+    if (ie && e.keyCode == 27) { e.returnValue = false; }
+    if (signalDOMEvent(cm, e) || cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return;
+    var code = e.keyCode;
+    // IE does strange things with escape.
+    cm.doc.sel.shift = code == 16 || e.shiftKey;
+    // First give onKeyEvent option a chance to handle this.
+    var handled = handleKeyBinding(cm, e);
+    if (opera) {
+      lastStoppedKey = handled ? code : null;
+      // Opera has no cut event... we try to at least catch the key combo
+      if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
+        cm.replaceSelection("");
+    }
+  }
+
+  function onKeyPress(e) {
+    var cm = this;
+    if (signalDOMEvent(cm, e) || cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return;
+    var keyCode = e.keyCode, charCode = e.charCode;
+    if (opera && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
+    if (((opera && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(cm, e)) return;
+    var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
+    if (this.options.electricChars && this.doc.mode.electricChars &&
+        this.options.smartIndent && !isReadOnly(this) &&
+        this.doc.mode.electricChars.indexOf(ch) > -1)
+      setTimeout(operation(cm, function() {indentLine(cm, cm.doc.sel.to.line, "smart");}), 75);
+    if (handleCharBinding(cm, e, ch)) return;
+    if (ie && !ie_lt9) cm.display.inputHasSelection = null;
+    fastPoll(cm);
+  }
+
+  function onFocus(cm) {
+    if (cm.options.readOnly == "nocursor") return;
+    if (!cm.state.focused) {
+      signal(cm, "focus", cm);
+      cm.state.focused = true;
+      if (cm.display.wrapper.className.search(/\bCodeMirror-focused\b/) == -1)
+        cm.display.wrapper.className += " CodeMirror-focused";
+      resetInput(cm, true);
+    }
+    slowPoll(cm);
+    restartBlink(cm);
+  }
+  function onBlur(cm) {
+    if (cm.state.focused) {
+      signal(cm, "blur", cm);
+      cm.state.focused = false;
+      cm.display.wrapper.className = cm.display.wrapper.className.replace(" CodeMirror-focused", "");
+    }
+    clearInterval(cm.display.blinker);
+    setTimeout(function() {if (!cm.state.focused) cm.doc.sel.shift = false;}, 150);
+  }
+
+  var detectingSelectAll;
+  function onContextMenu(cm, e) {
+    if (signalDOMEvent(cm, e, "contextmenu")) return;
+    var display = cm.display, sel = cm.doc.sel;
+    if (eventInWidget(display, e)) return;
+
+    var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
+    if (!pos || opera) return; // Opera is difficult.
+    if (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to))
+      operation(cm, setSelection)(cm.doc, pos, pos);
+
+    var oldCSS = display.input.style.cssText;
+    display.inputDiv.style.position = "absolute";
+    display.input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
+      "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: white; outline: none;" +
+      "border-width: 0; outline: none; overflow: hidden; opacity: .05; -ms-opacity: .05; filter: alpha(opacity=5);";
+    focusInput(cm);
+    resetInput(cm, true);
+    // Adds "Select all" to context menu in FF
+    if (posEq(sel.from, sel.to)) display.input.value = display.prevInput = " ";
+
+    function prepareSelectAllHack() {
+      if (display.input.selectionStart != null) {
+        var extval = display.input.value = " " + (posEq(sel.from, sel.to) ? "" : display.input.value);
+        display.prevInput = " ";
+        display.input.selectionStart = 1; display.input.selectionEnd = extval.length;
+      }
+    }
+    function rehide() {
+      display.inputDiv.style.position = "relative";
+      display.input.style.cssText = oldCSS;
+      if (ie_lt9) display.scrollbarV.scrollTop = display.scroller.scrollTop = scrollPos;
+      slowPoll(cm);
+
+      // Try to detect the user choosing select-all
+      if (display.input.selectionStart != null) {
+        if (!ie || ie_lt9) prepareSelectAllHack();
+        clearTimeout(detectingSelectAll);
+        var i = 0, poll = function(){
+          if (display.prevInput == " " && display.input.selectionStart == 0)
+            operation(cm, commands.selectAll)(cm);
+          else if (i++ < 10) detectingSelectAll = setTimeout(poll, 500);
+          else resetInput(cm);
+        };
+        detectingSelectAll = setTimeout(poll, 200);
+      }
+    }
+
+    if (ie && !ie_lt9) prepareSelectAllHack();
+    if (captureMiddleClick) {
+      e_stop(e);
+      var mouseup = function() {
+        off(window, "mouseup", mouseup);
+        setTimeout(rehide, 20);
+      };
+      on(window, "mouseup", mouseup);
+    } else {
+      setTimeout(rehide, 50);
+    }
+  }
+
+  // UPDATING
+
+  var changeEnd = CodeMirror.changeEnd = function(change) {
+    if (!change.text) return change.to;
+    return Pos(change.from.line + change.text.length - 1,
+               lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));
+  };
+
+  // Make sure a position will be valid after the given change.
+  function clipPostChange(doc, change, pos) {
+    if (!posLess(change.from, pos)) return clipPos(doc, pos);
+    var diff = (change.text.length - 1) - (change.to.line - change.from.line);
+    if (pos.line > change.to.line + diff) {
+      var preLine = pos.line - diff, lastLine = doc.first + doc.size - 1;
+      if (preLine > lastLine) return Pos(lastLine, getLine(doc, lastLine).text.length);
+      return clipToLen(pos, getLine(doc, preLine).text.length);
+    }
+    if (pos.line == change.to.line + diff)
+      return clipToLen(pos, lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0) +
+                       getLine(doc, change.to.line).text.length - change.to.ch);
+    var inside = pos.line - change.from.line;
+    return clipToLen(pos, change.text[inside].length + (inside ? 0 : change.from.ch));
+  }
+
+  // Hint can be null|"end"|"start"|"around"|{anchor,head}
+  function computeSelAfterChange(doc, change, hint) {
+    if (hint && typeof hint == "object") // Assumed to be {anchor, head} object
+      return {anchor: clipPostChange(doc, change, hint.anchor),
+              head: clipPostChange(doc, change, hint.head)};
+
+    if (hint == "start") return {anchor: change.from, head: change.from};
+
+    var end = changeEnd(change);
+    if (hint == "around") return {anchor: change.from, head: end};
+    if (hint == "end") return {anchor: end, head: end};
+
+    // hint is null, leave the selection alone as much as possible
+    var adjustPos = function(pos) {
+      if (posLess(pos, change.from)) return pos;
+      if (!posLess(change.to, pos)) return end;
+
+      var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
+      if (pos.line == change.to.line) ch += end.ch - change.to.ch;
+      return Pos(line, ch);
+    };
+    return {anchor: adjustPos(doc.sel.anchor), head: adjustPos(doc.sel.head)};
+  }
+
+  function filterChange(doc, change, update) {
+    var obj = {
+      canceled: false,
+      from: change.from,
+      to: change.to,
+      text: change.text,
+      origin: change.origin,
+      cancel: function() { this.canceled = true; }
+    };
+    if (update) obj.update = function(from, to, text, origin) {
+      if (from) this.from = clipPos(doc, from);
+      if (to) this.to = clipPos(doc, to);
+      if (text) this.text = text;
+      if (origin !== undefined) this.origin = origin;
+    };
+    signal(doc, "beforeChange", doc, obj);
+    if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj);
+
+    if (obj.canceled) return null;
+    return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin};
+  }
+
+  // Replace the range from from to to by the strings in replacement.
+  // change is a {from, to, text [, origin]} object
+  function makeChange(doc, change, selUpdate, ignoreReadOnly) {
+    if (doc.cm) {
+      if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, selUpdate, ignoreReadOnly);
+      if (doc.cm.state.suppressEdits) return;
+    }
+
+    if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
+      change = filterChange(doc, change, true);
+      if (!change) return;
+    }
+
+    // Possibly split or suppress the update based on the presence
+    // of read-only spans in its range.
+    var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
+    if (split) {
+      for (var i = split.length - 1; i >= 1; --i)
+        makeChangeNoReadonly(doc, {from: split[i].from, to: split[i].to, text: [""]});
+      if (split.length)
+        makeChangeNoReadonly(doc, {from: split[0].from, to: split[0].to, text: change.text}, selUpdate);
+    } else {
+      makeChangeNoReadonly(doc, change, selUpdate);
+    }
+  }
+
+  function makeChangeNoReadonly(doc, change, selUpdate) {
+    var selAfter = computeSelAfterChange(doc, change, selUpdate);
+    addToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
+
+    makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
+    var rebased = [];
+
+    linkedDocs(doc, function(doc, sharedHist) {
+      if (!sharedHist && indexOf(rebased, doc.history) == -1) {
+        rebaseHist(doc.history, change);
+        rebased.push(doc.history);
+      }
+      makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
+    });
+  }
+
+  function makeChangeFromHistory(doc, type) {
+    if (doc.cm && doc.cm.state.suppressEdits) return;
+
+    var hist = doc.history;
+    var event = (type == "undo" ? hist.done : hist.undone).pop();
+    if (!event) return;
+
+    var anti = {changes: [], anchorBefore: event.anchorAfter, headBefore: event.headAfter,
+                anchorAfter: event.anchorBefore, headAfter: event.headBefore,
+                generation: hist.generation};
+    (type == "undo" ? hist.undone : hist.done).push(anti);
+    hist.generation = event.generation || ++hist.maxGeneration;
+
+    var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
+
+    for (var i = event.changes.length - 1; i >= 0; --i) {
+      var change = event.changes[i];
+      change.origin = type;
+      if (filter && !filterChange(doc, change, false)) {
+        (type == "undo" ? hist.done : hist.undone).length = 0;
+        return;
+      }
+
+      anti.changes.push(historyChangeFromChange(doc, change));
+
+      var after = i ? computeSelAfterChange(doc, change, null)
+                    : {anchor: event.anchorBefore, head: event.headBefore};
+      makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
+      var rebased = [];
+
+      linkedDocs(doc, function(doc, sharedHist) {
+        if (!sharedHist && indexOf(rebased, doc.history) == -1) {
+          rebaseHist(doc.history, change);
+          rebased.push(doc.history);
+        }
+        makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
+      });
+    }
+  }
+
+  function shiftDoc(doc, distance) {
+    function shiftPos(pos) {return Pos(pos.line + distance, pos.ch);}
+    doc.first += distance;
+    if (doc.cm) regChange(doc.cm, doc.first, doc.first, distance);
+    doc.sel.head = shiftPos(doc.sel.head); doc.sel.anchor = shiftPos(doc.sel.anchor);
+    doc.sel.from = shiftPos(doc.sel.from); doc.sel.to = shiftPos(doc.sel.to);
+  }
+
+  function makeChangeSingleDoc(doc, change, selAfter, spans) {
+    if (doc.cm && !doc.cm.curOp)
+      return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);
+
+    if (change.to.line < doc.first) {
+      shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
+      return;
+    }
+    if (change.from.line > doc.lastLine()) return;
+
+    // Clip the change to the size of this doc
+    if (change.from.line < doc.first) {
+      var shift = change.text.length - 1 - (doc.first - change.from.line);
+      shiftDoc(doc, shift);
+      change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
+                text: [lst(change.text)], origin: change.origin};
+    }
+    var last = doc.lastLine();
+    if (change.to.line > last) {
+      change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
+                text: [change.text[0]], origin: change.origin};
+    }
+
+    change.removed = getBetween(doc, change.from, change.to);
+
+    if (!selAfter) selAfter = computeSelAfterChange(doc, change, null);
+    if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans, selAfter);
+    else updateDoc(doc, change, spans, selAfter);
+  }
+
+  function makeChangeSingleDocInEditor(cm, change, spans, selAfter) {
+    var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
+
+    var recomputeMaxLength = false, checkWidthStart = from.line;
+    if (!cm.options.lineWrapping) {
+      checkWidthStart = lineNo(visualLine(doc, getLine(doc, from.line)));
+      doc.iter(checkWidthStart, to.line + 1, function(line) {
+        if (line == display.maxLine) {
+          recomputeMaxLength = true;
+          return true;
+        }
+      });
+    }
+
+    if (!posLess(doc.sel.head, change.from) && !posLess(change.to, doc.sel.head))
+      cm.curOp.cursorActivity = true;
+
+    updateDoc(doc, change, spans, selAfter, estimateHeight(cm));
+
+    if (!cm.options.lineWrapping) {
+      doc.iter(checkWidthStart, from.line + change.text.length, function(line) {
+        var len = lineLength(doc, line);
+        if (len > display.maxLineLength) {
+          display.maxLine = line;
+          display.maxLineLength = len;
+          display.maxLineChanged = true;
+          recomputeMaxLength = false;
+        }
+      });
+      if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
+    }
+
+    // Adjust frontier, schedule worker
+    doc.frontier = Math.min(doc.frontier, from.line);
+    startWorker(cm, 400);
+
+    var lendiff = change.text.length - (to.line - from.line) - 1;
+    // Remember that these lines changed, for updating the display
+    regChange(cm, from.line, to.line + 1, lendiff);
+
+    if (hasHandler(cm, "change")) {
+      var changeObj = {from: from, to: to,
+                       text: change.text,
+                       removed: change.removed,
+                       origin: change.origin};
+      if (cm.curOp.textChanged) {
+        for (var cur = cm.curOp.textChanged; cur.next; cur = cur.next) {}
+        cur.next = changeObj;
+      } else cm.curOp.textChanged = changeObj;
+    }
+  }
+
+  function replaceRange(doc, code, from, to, origin) {
+    if (!to) to = from;
+    if (posLess(to, from)) { var tmp = to; to = from; from = tmp; }
+    if (typeof code == "string") code = splitLines(code);
+    makeChange(doc, {from: from, to: to, text: code, origin: origin}, null);
+  }
+
+  // POSITION OBJECT
+
+  function Pos(line, ch) {
+    if (!(this instanceof Pos)) return new Pos(line, ch);
+    this.line = line; this.ch = ch;
+  }
+  CodeMirror.Pos = Pos;
+
+  function posEq(a, b) {return a.line == b.line && a.ch == b.ch;}
+  function posLess(a, b) {return a.line < b.line || (a.line == b.line && a.ch < b.ch);}
+  function copyPos(x) {return Pos(x.line, x.ch);}
+
+  // SELECTION
+
+  function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));}
+  function clipPos(doc, pos) {
+    if (pos.line < doc.first) return Pos(doc.first, 0);
+    var last = doc.first + doc.size - 1;
+    if (pos.line > last) return Pos(last, getLine(doc, last).text.length);
+    return clipToLen(pos, getLine(doc, pos.line).text.length);
+  }
+  function clipToLen(pos, linelen) {
+    var ch = pos.ch;
+    if (ch == null || ch > linelen) return Pos(pos.line, linelen);
+    else if (ch < 0) return Pos(pos.line, 0);
+    else return pos;
+  }
+  function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;}
+
+  // If shift is held, this will move the selection anchor. Otherwise,
+  // it'll set the whole selection.
+  function extendSelection(doc, pos, other, bias) {
+    if (doc.sel.shift || doc.sel.extend) {
+      var anchor = doc.sel.anchor;
+      if (other) {
+        var posBefore = posLess(pos, anchor);
+        if (posBefore != posLess(other, anchor)) {
+          anchor = pos;
+          pos = other;
+        } else if (posBefore != posLess(pos, other)) {
+          pos = other;
+        }
+      }
+      setSelection(doc, anchor, pos, bias);
+    } else {
+      setSelection(doc, pos, other || pos, bias);
+    }
+    if (doc.cm) doc.cm.curOp.userSelChange = true;
+  }
+
+  function filterSelectionChange(doc, anchor, head) {
+    var obj = {anchor: anchor, head: head};
+    signal(doc, "beforeSelectionChange", doc, obj);
+    if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj);
+    obj.anchor = clipPos(doc, obj.anchor); obj.head = clipPos(doc, obj.head);
+    return obj;
+  }
+
+  // Update the selection. Last two args are only used by
+  // updateDoc, since they have to be expressed in the line
+  // numbers before the update.
+  function setSelection(doc, anchor, head, bias, checkAtomic) {
+    if (!checkAtomic && hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) {
+      var filtered = filterSelectionChange(doc, anchor, head);
+      head = filtered.head;
+      anchor = filtered.anchor;
+    }
+
+    var sel = doc.sel;
+    sel.goalColumn = null;
+    // Skip over atomic spans.
+    if (checkAtomic || !posEq(anchor, sel.anchor))
+      anchor = skipAtomic(doc, anchor, bias, checkAtomic != "push");
+    if (checkAtomic || !posEq(head, sel.head))
+      head = skipAtomic(doc, head, bias, checkAtomic != "push");
+
+    if (posEq(sel.anchor, anchor) && posEq(sel.head, head)) return;
+
+    sel.anchor = anchor; sel.head = head;
+    var inv = posLess(head, anchor);
+    sel.from = inv ? head : anchor;
+    sel.to = inv ? anchor : head;
+
+    if (doc.cm)
+      doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged =
+        doc.cm.curOp.cursorActivity = true;
+
+    signalLater(doc, "cursorActivity", doc);
+  }
+
+  function reCheckSelection(cm) {
+    setSelection(cm.doc, cm.doc.sel.from, cm.doc.sel.to, null, "push");
+  }
+
+  function skipAtomic(doc, pos, bias, mayClear) {
+    var flipped = false, curPos = pos;
+    var dir = bias || 1;
+    doc.cantEdit = false;
+    search: for (;;) {
+      var line = getLine(doc, curPos.line);
+      if (line.markedSpans) {
+        for (var i = 0; i < line.markedSpans.length; ++i) {
+          var sp = line.markedSpans[i], m = sp.marker;
+          if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) &&
+              (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) {
+            if (mayClear) {
+              signal(m, "beforeCursorEnter");
+              if (m.explicitlyCleared) {
+                if (!line.markedSpans) break;
+                else {--i; continue;}
+              }
+            }
+            if (!m.atomic) continue;
+            var newPos = m.find()[dir < 0 ? "from" : "to"];
+            if (posEq(newPos, curPos)) {
+              newPos.ch += dir;
+              if (newPos.ch < 0) {
+                if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1));
+                else newPos = null;
+              } else if (newPos.ch > line.text.length) {
+                if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0);
+                else newPos = null;
+              }
+              if (!newPos) {
+                if (flipped) {
+                  // Driven in a corner -- no valid cursor position found at all
+                  // -- try again *with* clearing, if we didn't already
+                  if (!mayClear) return skipAtomic(doc, pos, bias, true);
+                  // Otherwise, turn off editing until further notice, and return the start of the doc
+                  doc.cantEdit = true;
+                  return Pos(doc.first, 0);
+                }
+                flipped = true; newPos = pos; dir = -dir;
+              }
+            }
+            curPos = newPos;
+            continue search;
+          }
+        }
+      }
+      return curPos;
+    }
+  }
+
+  // SCROLLING
+
+  function scrollCursorIntoView(cm) {
+    var coords = scrollPosIntoView(cm, cm.doc.sel.head, cm.options.cursorScrollMargin);
+    if (!cm.state.focused) return;
+    var display = cm.display, box = getRect(display.sizer), doScroll = null;
+    if (coords.top + box.top < 0) doScroll = true;
+    else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
+    if (doScroll != null && !phantom) {
+      var hidden = display.cursor.style.display == "none";
+      if (hidden) {
+        display.cursor.style.display = "";
+        display.cursor.style.left = coords.left + "px";
+        display.cursor.style.top = (coords.top - display.viewOffset) + "px";
+      }
+      display.cursor.scrollIntoView(doScroll);
+      if (hidden) display.cursor.style.display = "none";
+    }
+  }
+
+  function scrollPosIntoView(cm, pos, margin) {
+    if (margin == null) margin = 0;
+    for (;;) {
+      var changed = false, coords = cursorCoords(cm, pos);
+      var scrollPos = calculateScrollPos(cm, coords.left, coords.top - margin, coords.left, coords.bottom + margin);
+      var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
+      if (scrollPos.scrollTop != null) {
+        setScrollTop(cm, scrollPos.scrollTop);
+        if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true;
+      }
+      if (scrollPos.scrollLeft != null) {
+        setScrollLeft(cm, scrollPos.scrollLeft);
+        if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true;
+      }
+      if (!changed) return coords;
+    }
+  }
+
+  function scrollIntoView(cm, x1, y1, x2, y2) {
+    var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
+    if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);
+    if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);
+  }
+
+  function calculateScrollPos(cm, x1, y1, x2, y2) {
+    var display = cm.display, snapMargin = textHeight(cm.display);
+    if (y1 < 0) y1 = 0;
+    var screen = display.scroller.clientHeight - scrollerCutOff, screentop = display.scroller.scrollTop, result = {};
+    var docBottom = cm.doc.height + paddingVert(display);
+    var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin;
+    if (y1 < screentop) {
+      result.scrollTop = atTop ? 0 : y1;
+    } else if (y2 > screentop + screen) {
+      var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen);
+      if (newTop != screentop) result.scrollTop = newTop;
+    }
+
+    var screenw = display.scroller.clientWidth - scrollerCutOff, screenleft = display.scroller.scrollLeft;
+    x1 += display.gutters.offsetWidth; x2 += display.gutters.offsetWidth;
+    var gutterw = display.gutters.offsetWidth;
+    var atLeft = x1 < gutterw + 10;
+    if (x1 < screenleft + gutterw || atLeft) {
+      if (atLeft) x1 = 0;
+      result.scrollLeft = Math.max(0, x1 - 10 - gutterw);
+    } else if (x2 > screenw + screenleft - 3) {
+      result.scrollLeft = x2 + 10 - screenw;
+    }
+    return result;
+  }
+
+  function updateScrollPos(cm, left, top) {
+    cm.curOp.updateScrollPos = {scrollLeft: left == null ? cm.doc.scrollLeft : left,
+                                scrollTop: top == null ? cm.doc.scrollTop : top};
+  }
+
+  function addToScrollPos(cm, left, top) {
+    var pos = cm.curOp.updateScrollPos || (cm.curOp.updateScrollPos = {scrollLeft: cm.doc.scrollLeft, scrollTop: cm.doc.scrollTop});
+    var scroll = cm.display.scroller;
+    pos.scrollTop = Math.max(0, Math.min(scroll.scrollHeight - scroll.clientHeight, pos.scrollTop + top));
+    pos.scrollLeft = Math.max(0, Math.min(scroll.scrollWidth - scroll.clientWidth, pos.scrollLeft + left));
+  }
+
+  // API UTILITIES
+
+  function indentLine(cm, n, how, aggressive) {
+    var doc = cm.doc;
+    if (how == null) how = "add";
+    if (how == "smart") {
+      if (!cm.doc.mode.indent) how = "prev";
+      else var state = getStateBefore(cm, n);
+    }
+
+    var tabSize = cm.options.tabSize;
+    var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
+    var curSpaceString = line.text.match(/^\s*/)[0], indentation;
+    if (how == "smart") {
+      indentation = cm.doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
+      if (indentation == Pass) {
+        if (!aggressive) return;
+        how = "prev";
+      }
+    }
+    if (how == "prev") {
+      if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
+      else indentation = 0;
+    } else if (how == "add") {
+      indentation = curSpace + cm.options.indentUnit;
+    } else if (how == "subtract") {
+      indentation = curSpace - cm.options.indentUnit;
+    } else if (typeof how == "number") {
+      indentation = curSpace + how;
+    }
+    indentation = Math.max(0, indentation);
+
+    var indentString = "", pos = 0;
+    if (cm.options.indentWithTabs)
+      for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
+    if (pos < indentation) indentString += spaceStr(indentation - pos);
+
+    if (indentString != curSpaceString)
+      replaceRange(cm.doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
+    line.stateAfter = null;
+  }
+
+  function changeLine(cm, handle, op) {
+    var no = handle, line = handle, doc = cm.doc;
+    if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
+    else no = lineNo(handle);
+    if (no == null) return null;
+    if (op(line, no)) regChange(cm, no, no + 1);
+    else return null;
+    return line;
+  }
+
+  function findPosH(doc, pos, dir, unit, visually) {
+    var line = pos.line, ch = pos.ch, origDir = dir;
+    var lineObj = getLine(doc, line);
+    var possible = true;
+    function findNextLine() {
+      var l = line + dir;
+      if (l < doc.first || l >= doc.first + doc.size) return (possible = false);
+      line = l;
+      return lineObj = getLine(doc, l);
+    }
+    function moveOnce(boundToLine) {
+      var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
+      if (next == null) {
+        if (!boundToLine && findNextLine()) {
+          if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);
+          else ch = dir < 0 ? lineObj.text.length : 0;
+        } else return (possible = false);
+      } else ch = next;
+      return true;
+    }
+
+    if (unit == "char") moveOnce();
+    else if (unit == "column") moveOnce(true);
+    else if (unit == "word" || unit == "group") {
+      var sawType = null, group = unit == "group";
+      for (var first = true;; first = false) {
+        if (dir < 0 && !moveOnce(!first)) break;
+        var cur = lineObj.text.charAt(ch) || "\n";
+        var type = isWordChar(cur) ? "w"
+          : !group ? null
+          : /\s/.test(cur) ? null
+          : "p";
+        if (sawType && sawType != type) {
+          if (dir < 0) {dir = 1; moveOnce();}
+          break;
+        }
+        if (type) sawType = type;
+        if (dir > 0 && !moveOnce(!first)) break;
+      }
+    }
+    var result = skipAtomic(doc, Pos(line, ch), origDir, true);
+    if (!possible) result.hitSide = true;
+    return result;
+  }
+
+  function findPosV(cm, pos, dir, unit) {
+    var doc = cm.doc, x = pos.left, y;
+    if (unit == "page") {
+      var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
+      y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display));
+    } else if (unit == "line") {
+      y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
+    }
+    for (;;) {
+      var target = coordsChar(cm, x, y);
+      if (!target.outside) break;
+      if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; }
+      y += dir * 5;
+    }
+    return target;
+  }
+
+  function findWordAt(line, pos) {
+    var start = pos.ch, end = pos.ch;
+    if (line) {
+      if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end;
+      var startChar = line.charAt(start);
+      var check = isWordChar(startChar) ? isWordChar
+        : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);}
+        : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
+      while (start > 0 && check(line.charAt(start - 1))) --start;
+      while (end < line.length && check(line.charAt(end))) ++end;
+    }
+    return {from: Pos(pos.line, start), to: Pos(pos.line, end)};
+  }
+
+  function selectLine(cm, line) {
+    extendSelection(cm.doc, Pos(line, 0), clipPos(cm.doc, Pos(line + 1, 0)));
+  }
+
+  // PROTOTYPE
+
+  // The publicly visible API. Note that operation(null, f) means
+  // 'wrap f in an operation, performed on its `this` parameter'
+
+  CodeMirror.prototype = {
+    constructor: CodeMirror,
+    focus: function(){window.focus(); focusInput(this); onFocus(this); fastPoll(this);},
+
+    setOption: function(option, value) {
+      var options = this.options, old = options[option];
+      if (options[option] == value && option != "mode") return;
+      options[option] = value;
+      if (optionHandlers.hasOwnProperty(option))
+        operation(this, optionHandlers[option])(this, value, old);
+    },
+
+    getOption: function(option) {return this.options[option];},
+    getDoc: function() {return this.doc;},
+
+    addKeyMap: function(map, bottom) {
+      this.state.keyMaps[bottom ? "push" : "unshift"](map);
+    },
+    removeKeyMap: function(map) {
+      var maps = this.state.keyMaps;
+      for (var i = 0; i < maps.length; ++i)
+        if (maps[i] == map || (typeof maps[i] != "string" && maps[i].name == map)) {
+          maps.splice(i, 1);
+          return true;
+        }
+    },
+
+    addOverlay: operation(null, function(spec, options) {
+      var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
+      if (mode.startState) throw new Error("Overlays may not be stateful.");
+      this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque});
+      this.state.modeGen++;
+      regChange(this);
+    }),
+    removeOverlay: operation(null, function(spec) {
+      var overlays = this.state.overlays;
+      for (var i = 0; i < overlays.length; ++i) {
+        var cur = overlays[i].modeSpec;
+        if (cur == spec || typeof spec == "string" && cur.name == spec) {
+          overlays.splice(i, 1);
+          this.state.modeGen++;
+          regChange(this);
+          return;
+        }
+      }
+    }),
+
+    indentLine: operation(null, function(n, dir, aggressive) {
+      if (typeof dir != "string" && typeof dir != "number") {
+        if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
+        else dir = dir ? "add" : "subtract";
+      }
+      if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive);
+    }),
+    indentSelection: operation(null, function(how) {
+      var sel = this.doc.sel;
+      if (posEq(sel.from, sel.to)) return indentLine(this, sel.from.line, how);
+      var e = sel.to.line - (sel.to.ch ? 0 : 1);
+      for (var i = sel.from.line; i <= e; ++i) indentLine(this, i, how);
+    }),
+
+    // Fetch the parser token for a given character. Useful for hacks
+    // that want to inspect the mode state (say, for completion).
+    getTokenAt: function(pos, precise) {
+      var doc = this.doc;
+      pos = clipPos(doc, pos);
+      var state = getStateBefore(this, pos.line, precise), mode = this.doc.mode;
+      var line = getLine(doc, pos.line);
+      var stream = new StringStream(line.text, this.options.tabSize);
+      while (stream.pos < pos.ch && !stream.eol()) {
+        stream.start = stream.pos;
+        var style = mode.token(stream, state);
+      }
+      return {start: stream.start,
+              end: stream.pos,
+              string: stream.current(),
+              className: style || null, // Deprecated, use 'type' instead
+              type: style || null,
+              state: state};
+    },
+
+    getTokenTypeAt: function(pos) {
+      pos = clipPos(this.doc, pos);
+      var styles = getLineStyles(this, getLine(this.doc, pos.line));
+      var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
+      if (ch == 0) return styles[2];
+      for (;;) {
+        var mid = (before + after) >> 1;
+        if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid;
+        else if (styles[mid * 2 + 1] < ch) before = mid + 1;
+        else return styles[mid * 2 + 2];
+      }
+    },
+
+    getModeAt: function(pos) {
+      var mode = this.doc.mode;
+      if (!mode.innerMode) return mode;
+      return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode;
+    },
+
+    getHelper: function(pos, type) {
+      if (!helpers.hasOwnProperty(type)) return;
+      var help = helpers[type], mode = this.getModeAt(pos);
+      return mode[type] && help[mode[type]] ||
+        mode.helperType && help[mode.helperType] ||
+        help[mode.name];
+    },
+
+    getStateAfter: function(line, precise) {
+      var doc = this.doc;
+      line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
+      return getStateBefore(this, line + 1, precise);
+    },
+
+    cursorCoords: function(start, mode) {
+      var pos, sel = this.doc.sel;
+      if (start == null) pos = sel.head;
+      else if (typeof start == "object") pos = clipPos(this.doc, start);
+      else pos = start ? sel.from : sel.to;
+      return cursorCoords(this, pos, mode || "page");
+    },
+
+    charCoords: function(pos, mode) {
+      return charCoords(this, clipPos(this.doc, pos), mode || "page");
+    },
+
+    coordsChar: function(coords, mode) {
+      coords = fromCoordSystem(this, coords, mode || "page");
+      return coordsChar(this, coords.left, coords.top);
+    },
+
+    lineAtHeight: function(height, mode) {
+      height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
+      return lineAtHeight(this.doc, height + this.display.viewOffset);
+    },
+    heightAtLine: function(line, mode) {
+      var end = false, last = this.doc.first + this.doc.size - 1;
+      if (line < this.doc.first) line = this.doc.first;
+      else if (line > last) { line = last; end = true; }
+      var lineObj = getLine(this.doc, line);
+      return intoCoordSystem(this, getLine(this.doc, line), {top: 0, left: 0}, mode || "page").top +
+        (end ? lineObj.height : 0);
+    },
+
+    defaultTextHeight: function() { return textHeight(this.display); },
+    defaultCharWidth: function() { return charWidth(this.display); },
+
+    setGutterMarker: operation(null, function(line, gutterID, value) {
+      return changeLine(this, line, function(line) {
+        var markers = line.gutterMarkers || (line.gutterMarkers = {});
+        markers[gutterID] = value;
+        if (!value && isEmpty(markers)) line.gutterMarkers = null;
+        return true;
+      });
+    }),
+
+    clearGutter: operation(null, function(gutterID) {
+      var cm = this, doc = cm.doc, i = doc.first;
+      doc.iter(function(line) {
+        if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
+          line.gutterMarkers[gutterID] = null;
+          regChange(cm, i, i + 1);
+          if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
+        }
+        ++i;
+      });
+    }),
+
+    addLineClass: operation(null, function(handle, where, cls) {
+      return changeLine(this, handle, function(line) {
+        var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass";
+        if (!line[prop]) line[prop] = cls;
+        else if (new RegExp("(?:^|\\s)" + cls + "(?:$|\\s)").test(line[prop])) return false;
+        else line[prop] += " " + cls;
+        return true;
+      });
+    }),
+
+    removeLineClass: operation(null, function(handle, where, cls) {
+      return changeLine(this, handle, function(line) {
+        var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass";
+        var cur = line[prop];
+        if (!cur) return false;
+        else if (cls == null) line[prop] = null;
+        else {
+          var found = cur.match(new RegExp("(?:^|\\s+)" + cls + "(?:$|\\s+)"));
+          if (!found) return false;
+          var end = found.index + found[0].length;
+          line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
+        }
+        return true;
+      });
+    }),
+
+    addLineWidget: operation(null, function(handle, node, options) {
+      return addLineWidget(this, handle, node, options);
+    }),
+
+    removeLineWidget: function(widget) { widget.clear(); },
+
+    lineInfo: function(line) {
+      if (typeof line == "number") {
+        if (!isLine(this.doc, line)) return null;
+        var n = line;
+        line = getLine(this.doc, line);
+        if (!line) return null;
+      } else {
+        var n = lineNo(line);
+        if (n == null) return null;
+      }
+      return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
+              textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
+              widgets: line.widgets};
+    },
+
+    getViewport: function() { return {from: this.display.showingFrom, to: this.display.showingTo};},
+
+    addWidget: function(pos, node, scroll, vert, horiz) {
+      var display = this.display;
+      pos = cursorCoords(this, clipPos(this.doc, pos));
+      var top = pos.bottom, left = pos.left;
+      node.style.position = "absolute";
+      display.sizer.appendChild(node);
+      if (vert == "over") {
+        top = pos.top;
+      } else if (vert == "above" || vert == "near") {
+        var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
+        hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
+        // Default to positioning above (if specified and possible); otherwise default to positioning below
+        if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
+          top = pos.top - node.offsetHeight;
+        else if (pos.bottom + node.offsetHeight <= vspace)
+          top = pos.bottom;
+        if (left + node.offsetWidth > hspace)
+          left = hspace - node.offsetWidth;
+      }
+      node.style.top = top + "px";
+      node.style.left = node.style.right = "";
+      if (horiz == "right") {
+        left = display.sizer.clientWidth - node.offsetWidth;
+        node.style.right = "0px";
+      } else {
+        if (horiz == "left") left = 0;
+        else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
+        node.style.left = left + "px";
+      }
+      if (scroll)
+        scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
+    },
+
+    triggerOnKeyDown: operation(null, onKeyDown),
+
+    execCommand: function(cmd) {return commands[cmd](this);},
+
+    findPosH: function(from, amount, unit, visually) {
+      var dir = 1;
+      if (amount < 0) { dir = -1; amount = -amount; }
+      for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
+        cur = findPosH(this.doc, cur, dir, unit, visually);
+        if (cur.hitSide) break;
+      }
+      return cur;
+    },
+
+    moveH: operation(null, function(dir, unit) {
+      var sel = this.doc.sel, pos;
+      if (sel.shift || sel.extend || posEq(sel.from, sel.to))
+        pos = findPosH(this.doc, sel.head, dir, unit, this.options.rtlMoveVisually);
+      else
+        pos = dir < 0 ? sel.from : sel.to;
+      extendSelection(this.doc, pos, pos, dir);
+    }),
+
+    deleteH: operation(null, function(dir, unit) {
+      var sel = this.doc.sel;
+      if (!posEq(sel.from, sel.to)) replaceRange(this.doc, "", sel.from, sel.to, "+delete");
+      else replaceRange(this.doc, "", sel.from, findPosH(this.doc, sel.head, dir, unit, false), "+delete");
+      this.curOp.userSelChange = true;
+    }),
+
+    findPosV: function(from, amount, unit, goalColumn) {
+      var dir = 1, x = goalColumn;
+      if (amount < 0) { dir = -1; amount = -amount; }
+      for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
+        var coords = cursorCoords(this, cur, "div");
+        if (x == null) x = coords.left;
+        else coords.left = x;
+        cur = findPosV(this, coords, dir, unit);
+        if (cur.hitSide) break;
+      }
+      return cur;
+    },
+
+    moveV: operation(null, function(dir, unit) {
+      var sel = this.doc.sel;
+      var pos = cursorCoords(this, sel.head, "div");
+      if (sel.goalColumn != null) pos.left = sel.goalColumn;
+      var target = findPosV(this, pos, dir, unit);
+
+      if (unit == "page") addToScrollPos(this, 0, charCoords(this, target, "div").top - pos.top);
+      extendSelection(this.doc, target, target, dir);
+      sel.goalColumn = pos.left;
+    }),
+
+    toggleOverwrite: function(value) {
+      if (value != null && value == this.state.overwrite) return;
+      if (this.state.overwrite = !this.state.overwrite)
+        this.display.cursor.className += " CodeMirror-overwrite";
+      else
+        this.display.cursor.className = this.display.cursor.className.replace(" CodeMirror-overwrite", "");
+    },
+    hasFocus: function() { return this.state.focused; },
+
+    scrollTo: operation(null, function(x, y) {
+      updateScrollPos(this, x, y);
+    }),
+    getScrollInfo: function() {
+      var scroller = this.display.scroller, co = scrollerCutOff;
+      return {left: scroller.scrollLeft, top: scroller.scrollTop,
+              height: scroller.scrollHeight - co, width: scroller.scrollWidth - co,
+              clientHeight: scroller.clientHeight - co, clientWidth: scroller.clientWidth - co};
+    },
+
+    scrollIntoView: operation(null, function(pos, margin) {
+      if (typeof pos == "number") pos = Pos(pos, 0);
+      if (!margin) margin = 0;
+      var coords = pos;
+
+      if (!pos || pos.line != null) {
+        this.curOp.scrollToPos = pos ? clipPos(this.doc, pos) : this.doc.sel.head;
+        this.curOp.scrollToPosMargin = margin;
+        coords = cursorCoords(this, this.curOp.scrollToPos);
+      }
+      var sPos = calculateScrollPos(this, coords.left, coords.top - margin, coords.right, coords.bottom + margin);
+      updateScrollPos(this, sPos.scrollLeft, sPos.scrollTop);
+    }),
+
+    setSize: operation(null, function(width, height) {
+      function interpret(val) {
+        return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
+      }
+      if (width != null) this.display.wrapper.style.width = interpret(width);
+      if (height != null) this.display.wrapper.style.height = interpret(height);
+      if (this.options.lineWrapping)
+        this.display.measureLineCache.length = this.display.measureLineCachePos = 0;
+      this.curOp.forceUpdate = true;
+    }),
+
+    operation: function(f){return runInOp(this, f);},
+
+    refresh: operation(null, function() {
+      clearCaches(this);
+      updateScrollPos(this, this.doc.scrollLeft, this.doc.scrollTop);
+      regChange(this);
+    }),
+
+    swapDoc: operation(null, function(doc) {
+      var old = this.doc;
+      old.cm = null;
+      attachDoc(this, doc);
+      clearCaches(this);
+      resetInput(this, true);
+      updateScrollPos(this, doc.scrollLeft, doc.scrollTop);
+      return old;
+    }),
+
+    getInputField: function(){return this.display.input;},
+    getWrapperElement: function(){return this.display.wrapper;},
+    getScrollerElement: function(){return this.display.scroller;},
+    getGutterElement: function(){return this.display.gutters;}
+  };
+  eventMixin(CodeMirror);
+
+  // OPTION DEFAULTS
+
+  var optionHandlers = CodeMirror.optionHandlers = {};
+
+  // The default configuration options.
+  var defaults = CodeMirror.defaults = {};
+
+  function option(name, deflt, handle, notOnInit) {
+    CodeMirror.defaults[name] = deflt;
+    if (handle) optionHandlers[name] =
+      notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;
+  }
+
+  var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}};
+
+  // These two are, on init, called from the constructor because they
+  // have to be initialized before the editor can start at all.
+  option("value", "", function(cm, val) {
+    cm.setValue(val);
+  }, true);
+  option("mode", null, function(cm, val) {
+    cm.doc.modeOption = val;
+    loadMode(cm);
+  }, true);
+
+  option("indentUnit", 2, loadMode, true);
+  option("indentWithTabs", false);
+  option("smartIndent", true);
+  option("tabSize", 4, function(cm) {
+    loadMode(cm);
+    clearCaches(cm);
+    regChange(cm);
+  }, true);
+  option("electricChars", true);
+  option("rtlMoveVisually", !windows);
+
+  option("theme", "default", function(cm) {
+    themeChanged(cm);
+    guttersChanged(cm);
+  }, true);
+  option("keyMap", "default", keyMapChanged);
+  option("extraKeys", null);
+
+  option("onKeyEvent", null);
+  option("onDragEvent", null);
+
+  option("lineWrapping", false, wrappingChanged, true);
+  option("gutters", [], function(cm) {
+    setGuttersForLineNumbers(cm.options);
+    guttersChanged(cm);
+  }, true);
+  option("fixedGutter", true, function(cm, val) {
+    cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
+    cm.refresh();
+  }, true);
+  option("coverGutterNextToScrollbar", false, updateScrollbars, true);
+  option("lineNumbers", false, function(cm) {
+    setGuttersForLineNumbers(cm.options);
+    guttersChanged(cm);
+  }, true);
+  option("firstLineNumber", 1, guttersChanged, true);
+  option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true);
+  option("showCursorWhenSelecting", false, updateSelection, true);
+
+  option("readOnly", false, function(cm, val) {
+    if (val == "nocursor") {onBlur(cm); cm.display.input.blur();}
+    else if (!val) resetInput(cm, true);
+  });
+  option("dragDrop", true);
+
+  option("cursorBlinkRate", 530);
+  option("cursorScrollMargin", 0);
+  option("cursorHeight", 1);
+  option("workTime", 100);
+  option("workDelay", 100);
+  option("flattenSpans", true);
+  option("pollInterval", 100);
+  option("undoDepth", 40, function(cm, val){cm.doc.history.undoDepth = val;});
+  option("historyEventDelay", 500);
+  option("viewportMargin", 10, function(cm){cm.refresh();}, true);
+  option("maxHighlightLength", 10000, function(cm){loadMode(cm); cm.refresh();}, true);
+  option("moveInputWithCursor", true, function(cm, val) {
+    if (!val) cm.display.inputDiv.style.top = cm.display.inputDiv.style.left = 0;
+  });
+
+  option("tabindex", null, function(cm, val) {
+    cm.display.input.tabIndex = val || "";
+  });
+  option("autofocus", null);
+
+  // MODE DEFINITION AND QUERYING
+
+  // Known modes, by name and by MIME
+  var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
+
+  CodeMirror.defineMode = function(name, mode) {
+    if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
+    if (arguments.length > 2) {
+      mode.dependencies = [];
+      for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]);
+    }
+    modes[name] = mode;
+  };
+
+  CodeMirror.defineMIME = function(mime, spec) {
+    mimeModes[mime] = spec;
+  };
+
+  CodeMirror.resolveMode = function(spec) {
+    if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
+      spec = mimeModes[spec];
+    } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
+      var found = mimeModes[spec.name];
+      spec = createObj(found, spec);
+      spec.name = found.name;
+    } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
+      return CodeMirror.resolveMode("application/xml");
+    }
+    if (typeof spec == "string") return {name: spec};
+    else return spec || {name: "null"};
+  };
+
+  CodeMirror.getMode = function(options, spec) {
+    var spec = CodeMirror.resolveMode(spec);
+    var mfactory = modes[spec.name];
+    if (!mfactory) return CodeMirror.getMode(options, "text/plain");
+    var modeObj = mfactory(options, spec);
+    if (modeExtensions.hasOwnProperty(spec.name)) {
+      var exts = modeExtensions[spec.name];
+      for (var prop in exts) {
+        if (!exts.hasOwnProperty(prop)) continue;
+        if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop];
+        modeObj[prop] = exts[prop];
+      }
+    }
+    modeObj.name = spec.name;
+
+    return modeObj;
+  };
+
+  CodeMirror.defineMode("null", function() {
+    return {token: function(stream) {stream.skipToEnd();}};
+  });
+  CodeMirror.defineMIME("text/plain", "null");
+
+  var modeExtensions = CodeMirror.modeExtensions = {};
+  CodeMirror.extendMode = function(mode, properties) {
+    var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
+    copyObj(properties, exts);
+  };
+
+  // EXTENSIONS
+
+  CodeMirror.defineExtension = function(name, func) {
+    CodeMirror.prototype[name] = func;
+  };
+  CodeMirror.defineDocExtension = function(name, func) {
+    Doc.prototype[name] = func;
+  };
+  CodeMirror.defineOption = option;
+
+  var initHooks = [];
+  CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
+
+  var helpers = CodeMirror.helpers = {};
+  CodeMirror.registerHelper = function(type, name, value) {
+    if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {};
+    helpers[type][name] = value;
+  };
+
+  // UTILITIES
+
+  CodeMirror.isWordChar = isWordChar;
+
+  // MODE STATE HANDLING
+
+  // Utility functions for working with state. Exported because modes
+  // sometimes need to do this.
+  function copyState(mode, state) {
+    if (state === true) return state;
+    if (mode.copyState) return mode.copyState(state);
+    var nstate = {};
+    for (var n in state) {
+      var val = state[n];
+      if (val instanceof Array) val = val.concat([]);
+      nstate[n] = val;
+    }
+    return nstate;
+  }
+  CodeMirror.copyState = copyState;
+
+  function startState(mode, a1, a2) {
+    return mode.startState ? mode.startState(a1, a2) : true;
+  }
+  CodeMirror.startState = startState;
+
+  CodeMirror.innerMode = function(mode, state) {
+    while (mode.innerMode) {
+      var info = mode.innerMode(state);
+      if (!info || info.mode == mode) break;
+      state = info.state;
+      mode = info.mode;
+    }
+    return info || {mode: mode, state: state};
+  };
+
+  // STANDARD COMMANDS
+
+  var commands = CodeMirror.commands = {
+    selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()));},
+    killLine: function(cm) {
+      var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from, to);
+      if (!sel && cm.getLine(from.line).length == from.ch)
+        cm.replaceRange("", from, Pos(from.line + 1, 0), "+delete");
+      else cm.replaceRange("", from, sel ? to : Pos(from.line), "+delete");
+    },
+    deleteLine: function(cm) {
+      var l = cm.getCursor().line;
+      cm.replaceRange("", Pos(l, 0), Pos(l), "+delete");
+    },
+    delLineLeft: function(cm) {
+      var cur = cm.getCursor();
+      cm.replaceRange("", Pos(cur.line, 0), cur, "+delete");
+    },
+    undo: function(cm) {cm.undo();},
+    redo: function(cm) {cm.redo();},
+    goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));},
+    goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));},
+    goLineStart: function(cm) {
+      cm.extendSelection(lineStart(cm, cm.getCursor().line));
+    },
+    goLineStartSmart: function(cm) {
+      var cur = cm.getCursor(), start = lineStart(cm, cur.line);
+      var line = cm.getLineHandle(start.line);
+      var order = getOrder(line);
+      if (!order || order[0].level == 0) {
+        var firstNonWS = Math.max(0, line.text.search(/\S/));
+        var inWS = cur.line == start.line && cur.ch <= firstNonWS && cur.ch;
+        cm.extendSelection(Pos(start.line, inWS ? 0 : firstNonWS));
+      } else cm.extendSelection(start);
+    },
+    goLineEnd: function(cm) {
+      cm.extendSelection(lineEnd(cm, cm.getCursor().line));
+    },
+    goLineRight: function(cm) {
+      var top = cm.charCoords(cm.getCursor(), "div").top + 5;
+      cm.extendSelection(cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"));
+    },
+    goLineLeft: function(cm) {
+      var top = cm.charCoords(cm.getCursor(), "div").top + 5;
+      cm.extendSelection(cm.coordsChar({left: 0, top: top}, "div"));
+    },
+    goLineUp: function(cm) {cm.moveV(-1, "line");},
+    goLineDown: function(cm) {cm.moveV(1, "line");},
+    goPageUp: function(cm) {cm.moveV(-1, "page");},
+    goPageDown: function(cm) {cm.moveV(1, "page");},
+    goCharLeft: function(cm) {cm.moveH(-1, "char");},
+    goCharRight: function(cm) {cm.moveH(1, "char");},
+    goColumnLeft: function(cm) {cm.moveH(-1, "column");},
+    goColumnRight: function(cm) {cm.moveH(1, "column");},
+    goWordLeft: function(cm) {cm.moveH(-1, "word");},
+    goGroupRight: function(cm) {cm.moveH(1, "group");},
+    goGroupLeft: function(cm) {cm.moveH(-1, "group");},
+    goWordRight: function(cm) {cm.moveH(1, "word");},
+    delCharBefore: function(cm) {cm.deleteH(-1, "char");},
+    delCharAfter: function(cm) {cm.deleteH(1, "char");},
+    delWordBefore: function(cm) {cm.deleteH(-1, "word");},
+    delWordAfter: function(cm) {cm.deleteH(1, "word");},
+    delGroupBefore: function(cm) {cm.deleteH(-1, "group");},
+    delGroupAfter: function(cm) {cm.deleteH(1, "group");},
+    indentAuto: function(cm) {cm.indentSelection("smart");},
+    indentMore: function(cm) {cm.indentSelection("add");},
+    indentLess: function(cm) {cm.indentSelection("subtract");},
+    insertTab: function(cm) {cm.replaceSelection("\t", "end", "+input");},
+    defaultTab: function(cm) {
+      if (cm.somethingSelected()) cm.indentSelection("add");
+      else cm.replaceSelection("\t", "end", "+input");
+    },
+    transposeChars: function(cm) {
+      var cur = cm.getCursor(), line = cm.getLine(cur.line);
+      if (cur.ch > 0 && cur.ch < line.length - 1)
+        cm.replaceRange(line.charAt(cur.ch) + line.charAt(cur.ch - 1),
+                        Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1));
+    },
+    newlineAndIndent: function(cm) {
+      operation(cm, function() {
+        cm.replaceSelection("\n", "end", "+input");
+        cm.indentLine(cm.getCursor().line, null, true);
+      })();
+    },
+    toggleOverwrite: function(cm) {cm.toggleOverwrite();}
+  };
+
+  // STANDARD KEYMAPS
+
+  var keyMap = CodeMirror.keyMap = {};
+  keyMap.basic = {
+    "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
+    "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
+    "Delete": "delCharAfter", "Backspace": "delCharBefore", "Tab": "defaultTab", "Shift-Tab": "indentAuto",
+    "Enter": "newlineAndIndent", "Insert": "toggleOverwrite"
+  };
+  // Note that the save and find-related commands aren't defined by
+  // default. Unknown commands are simply ignored.
+  keyMap.pcDefault = {
+    "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
+    "Ctrl-Home": "goDocStart", "Alt-Up": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Down": "goDocEnd",
+    "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
+    "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
+    "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
+    "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
+    fallthrough: "basic"
+  };
+  keyMap.macDefault = {
+    "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
+    "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
+    "Alt-Right": "goGroupRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLineEnd", "Alt-Backspace": "delGroupBefore",
+    "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
+    "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
+    "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delLineLeft",
+    fallthrough: ["basic", "emacsy"]
+  };
+  keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
+  keyMap.emacsy = {
+    "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
+    "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
+    "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
+    "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
+  };
+
+  // KEYMAP DISPATCH
+
+  function getKeyMap(val) {
+    if (typeof val == "string") return keyMap[val];
+    else return val;
+  }
+
+  function lookupKey(name, maps, handle) {
+    function lookup(map) {
+      map = getKeyMap(map);
+      var found = map[name];
+      if (found === false) return "stop";
+      if (found != null && handle(found)) return true;
+      if (map.nofallthrough) return "stop";
+
+      var fallthrough = map.fallthrough;
+      if (fallthrough == null) return false;
+      if (Object.prototype.toString.call(fallthrough) != "[object Array]")
+        return lookup(fallthrough);
+      for (var i = 0, e = fallthrough.length; i < e; ++i) {
+        var done = lookup(fallthrough[i]);
+        if (done) return done;
+      }
+      return false;
+    }
+
+    for (var i = 0; i < maps.length; ++i) {
+      var done = lookup(maps[i]);
+      if (done) return done != "stop";
+    }
+  }
+  function isModifierKey(event) {
+    var name = keyNames[event.keyCode];
+    return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
+  }
+  function keyName(event, noShift) {
+    if (opera && event.keyCode == 34 && event["char"]) return false;
+    var name = keyNames[event.keyCode];
+    if (name == null || event.altGraphKey) return false;
+    if (event.altKey) name = "Alt-" + name;
+    if (flipCtrlCmd ? event.metaKey : event.ctrlKey) name = "Ctrl-" + name;
+    if (flipCtrlCmd ? event.ctrlKey : event.metaKey) name = "Cmd-" + name;
+    if (!noShift && event.shiftKey) name = "Shift-" + name;
+    return name;
+  }
+  CodeMirror.lookupKey = lookupKey;
+  CodeMirror.isModifierKey = isModifierKey;
+  CodeMirror.keyName = keyName;
+
+  // FROMTEXTAREA
+
+  CodeMirror.fromTextArea = function(textarea, options) {
+    if (!options) options = {};
+    options.value = textarea.value;
+    if (!options.tabindex && textarea.tabindex)
+      options.tabindex = textarea.tabindex;
+    if (!options.placeholder && textarea.placeholder)
+      options.placeholder = textarea.placeholder;
+    // Set autofocus to true if this textarea is focused, or if it has
+    // autofocus and no other element is focused.
+    if (options.autofocus == null) {
+      var hasFocus = document.body;
+      // doc.activeElement occasionally throws on IE
+      try { hasFocus = document.activeElement; } catch(e) {}
+      options.autofocus = hasFocus == textarea ||
+        textarea.getAttribute("autofocus") != null && hasFocus == document.body;
+    }
+
+    function save() {textarea.value = cm.getValue();}
+    if (textarea.form) {
+      on(textarea.form, "submit", save);
+      // Deplorable hack to make the submit method do the right thing.
+      if (!options.leaveSubmitMethodAlone) {
+        var form = textarea.form, realSubmit = form.submit;
+        try {
+          var wrappedSubmit = form.submit = function() {
+            save();
+            form.submit = realSubmit;
+            form.submit();
+            form.submit = wrappedSubmit;
+          };
+        } catch(e) {}
+      }
+    }
+
+    textarea.style.display = "none";
+    var cm = CodeMirror(function(node) {
+      textarea.parentNode.insertBefore(node, textarea.nextSibling);
+    }, options);
+    cm.save = save;
+    cm.getTextArea = function() { return textarea; };
+    cm.toTextArea = function() {
+      save();
+      textarea.parentNode.removeChild(cm.getWrapperElement());
+      textarea.style.display = "";
+      if (textarea.form) {
+        off(textarea.form, "submit", save);
+        if (typeof textarea.form.submit == "function")
+          textarea.form.submit = realSubmit;
+      }
+    };
+    return cm;
+  };
+
+  // STRING STREAM
+
+  // Fed to the mode parsers, provides helper functions to make
+  // parsers more succinct.
+
+  // The character stream used by a mode's parser.
+  function StringStream(string, tabSize) {
+    this.pos = this.start = 0;
+    this.string = string;
+    this.tabSize = tabSize || 8;
+    this.lastColumnPos = this.lastColumnValue = 0;
+  }
+
+  StringStream.prototype = {
+    eol: function() {return this.pos >= this.string.length;},
+    sol: function() {return this.pos == 0;},
+    peek: function() {return this.string.charAt(this.pos) || undefined;},
+    next: function() {
+      if (this.pos < this.string.length)
+        return this.string.charAt(this.pos++);
+    },
+    eat: function(match) {
+      var ch = this.string.charAt(this.pos);
+      if (typeof match == "string") var ok = ch == match;
+      else var ok = ch && (match.test ? match.test(ch) : match(ch));
+      if (ok) {++this.pos; return ch;}
+    },
+    eatWhile: function(match) {
+      var start = this.pos;
+      while (this.eat(match)){}
+      return this.pos > start;
+    },
+    eatSpace: function() {
+      var start = this.pos;
+      while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
+      return this.pos > start;
+    },
+    skipToEnd: function() {this.pos = this.string.length;},
+    skipTo: function(ch) {
+      var found = this.string.indexOf(ch, this.pos);
+      if (found > -1) {this.pos = found; return true;}
+    },
+    backUp: function(n) {this.pos -= n;},
+    column: function() {
+      if (this.lastColumnPos < this.start) {
+        this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
+        this.lastColumnPos = this.start;
+      }
+      return this.lastColumnValue;
+    },
+    indentation: function() {return countColumn(this.string, null, this.tabSize);},
+    match: function(pattern, consume, caseInsensitive) {
+      if (typeof pattern == "string") {
+        var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
+        var substr = this.string.substr(this.pos, pattern.length);
+        if (cased(substr) == cased(pattern)) {
+          if (consume !== false) this.pos += pattern.length;
+          return true;
+        }
+      } else {
+        var match = this.string.slice(this.pos).match(pattern);
+        if (match && match.index > 0) return null;
+        if (match && consume !== false) this.pos += match[0].length;
+        return match;
+      }
+    },
+    current: function(){return this.string.slice(this.start, this.pos);}
+  };
+  CodeMirror.StringStream = StringStream;
+
+  // TEXTMARKERS
+
+  function TextMarker(doc, type) {
+    this.lines = [];
+    this.type = type;
+    this.doc = doc;
+  }
+  CodeMirror.TextMarker = TextMarker;
+  eventMixin(TextMarker);
+
+  TextMarker.prototype.clear = function() {
+    if (this.explicitlyCleared) return;
+    var cm = this.doc.cm, withOp = cm && !cm.curOp;
+    if (withOp) startOperation(cm);
+    if (hasHandler(this, "clear")) {
+      var found = this.find();
+      if (found) signalLater(this, "clear", found.from, found.to);
+    }
+    var min = null, max = null;
+    for (var i = 0; i < this.lines.length; ++i) {
+      var line = this.lines[i];
+      var span = getMarkedSpanFor(line.markedSpans, this);
+      if (span.to != null) max = lineNo(line);
+      line.markedSpans = removeMarkedSpan(line.markedSpans, span);
+      if (span.from != null)
+        min = lineNo(line);
+      else if (this.collapsed && !lineIsHidden(this.doc, line) && cm)
+        updateLineHeight(line, textHeight(cm.display));
+    }
+    if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) {
+      var visual = visualLine(cm.doc, this.lines[i]), len = lineLength(cm.doc, visual);
+      if (len > cm.display.maxLineLength) {
+        cm.display.maxLine = visual;
+        cm.display.maxLineLength = len;
+        cm.display.maxLineChanged = true;
+      }
+    }
+
+    if (min != null && cm) regChange(cm, min, max + 1);
+    this.lines.length = 0;
+    this.explicitlyCleared = true;
+    if (this.atomic && this.doc.cantEdit) {
+      this.doc.cantEdit = false;
+      if (cm) reCheckSelection(cm);
+    }
+    if (withOp) endOperation(cm);
+  };
+
+  TextMarker.prototype.find = function() {
+    var from, to;
+    for (var i = 0; i < this.lines.length; ++i) {
+      var line = this.lines[i];
+      var span = getMarkedSpanFor(line.markedSpans, this);
+      if (span.from != null || span.to != null) {
+        var found = lineNo(line);
+        if (span.from != null) from = Pos(found, span.from);
+        if (span.to != null) to = Pos(found, span.to);
+      }
+    }
+    if (this.type == "bookmark") return from;
+    return from && {from: from, to: to};
+  };
+
+  TextMarker.prototype.changed = function() {
+    var pos = this.find(), cm = this.doc.cm;
+    if (!pos || !cm) return;
+    var line = getLine(this.doc, pos.from.line);
+    clearCachedMeasurement(cm, line);
+    if (pos.from.line >= cm.display.showingFrom && pos.from.line < cm.display.showingTo) {
+      for (var node = cm.display.lineDiv.firstChild; node; node = node.nextSibling) if (node.lineObj == line) {
+        if (node.offsetHeight != line.height) updateLineHeight(line, node.offsetHeight);
+        break;
+      }
+      runInOp(cm, function() {
+        cm.curOp.selectionChanged = cm.curOp.forceUpdate = cm.curOp.updateMaxLine = true;
+      });
+    }
+  };
+
+  TextMarker.prototype.attachLine = function(line) {
+    if (!this.lines.length && this.doc.cm) {
+      var op = this.doc.cm.curOp;
+      if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
+        (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
+    }
+    this.lines.push(line);
+  };
+  TextMarker.prototype.detachLine = function(line) {
+    this.lines.splice(indexOf(this.lines, line), 1);
+    if (!this.lines.length && this.doc.cm) {
+      var op = this.doc.cm.curOp;
+      (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
+    }
+  };
+
+  function markText(doc, from, to, options, type) {
+    if (options && options.shared) return markTextShared(doc, from, to, options, type);
+    if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type);
+
+    var marker = new TextMarker(doc, type);
+    if (type == "range" && !posLess(from, to)) return marker;
+    if (options) copyObj(options, marker);
+    if (marker.replacedWith) {
+      marker.collapsed = true;
+      marker.replacedWith = elt("span", [marker.replacedWith], "CodeMirror-widget");
+      if (!options.handleMouseEvents) marker.replacedWith.ignoreEvents = true;
+    }
+    if (marker.collapsed) sawCollapsedSpans = true;
+
+    if (marker.addToHistory)
+      addToHistory(doc, {from: from, to: to, origin: "markText"},
+                   {head: doc.sel.head, anchor: doc.sel.anchor}, NaN);
+
+    var curLine = from.line, size = 0, collapsedAtStart, collapsedAtEnd, cm = doc.cm, updateMaxLine;
+    doc.iter(curLine, to.line + 1, function(line) {
+      if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(doc, line) == cm.display.maxLine)
+        updateMaxLine = true;
+      var span = {from: null, to: null, marker: marker};
+      size += line.text.length;
+      if (curLine == from.line) {span.from = from.ch; size -= from.ch;}
+      if (curLine == to.line) {span.to = to.ch; size -= line.text.length - to.ch;}
+      if (marker.collapsed) {
+        if (curLine == to.line) collapsedAtEnd = collapsedSpanAt(line, to.ch);
+        if (curLine == from.line) collapsedAtStart = collapsedSpanAt(line, from.ch);
+        else updateLineHeight(line, 0);
+      }
+      addMarkedSpan(line, span);
+      ++curLine;
+    });
+    if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) {
+      if (lineIsHidden(doc, line)) updateLineHeight(line, 0);
+    });
+
+    if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); });
+
+    if (marker.readOnly) {
+      sawReadOnlySpans = true;
+      if (doc.history.done.length || doc.history.undone.length)
+        doc.clearHistory();
+    }
+    if (marker.collapsed) {
+      if (collapsedAtStart != collapsedAtEnd)
+        throw new Error("Inserting collapsed marker overlapping an existing one");
+      marker.size = size;
+      marker.atomic = true;
+    }
+    if (cm) {
+      if (updateMaxLine) cm.curOp.updateMaxLine = true;
+      if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.collapsed)
+        regChange(cm, from.line, to.line + 1);
+      if (marker.atomic) reCheckSelection(cm);
+    }
+    return marker;
+  }
+
+  // SHARED TEXTMARKERS
+
+  function SharedTextMarker(markers, primary) {
+    this.markers = markers;
+    this.primary = primary;
+    for (var i = 0, me = this; i < markers.length; ++i) {
+      markers[i].parent = this;
+      on(markers[i], "clear", function(){me.clear();});
+    }
+  }
+  CodeMirror.SharedTextMarker = SharedTextMarker;
+  eventMixin(SharedTextMarker);
+
+  SharedTextMarker.prototype.clear = function() {
+    if (this.explicitlyCleared) return;
+    this.explicitlyCleared = true;
+    for (var i = 0; i < this.markers.length; ++i)
+      this.markers[i].clear();
+    signalLater(this, "clear");
+  };
+  SharedTextMarker.prototype.find = function() {
+    return this.primary.find();
+  };
+
+  function markTextShared(doc, from, to, options, type) {
+    options = copyObj(options);
+    options.shared = false;
+    var markers = [markText(doc, from, to, options, type)], primary = markers[0];
+    var widget = options.replacedWith;
+    linkedDocs(doc, function(doc) {
+      if (widget) options.replacedWith = widget.cloneNode(true);
+      markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
+      for (var i = 0; i < doc.linked.length; ++i)
+        if (doc.linked[i].isParent) return;
+      primary = lst(markers);
+    });
+    return new SharedTextMarker(markers, primary);
+  }
+
+  // TEXTMARKER SPANS
+
+  function getMarkedSpanFor(spans, marker) {
+    if (spans) for (var i = 0; i < spans.length; ++i) {
+      var span = spans[i];
+      if (span.marker == marker) return span;
+    }
+  }
+  function removeMarkedSpan(spans, span) {
+    for (var r, i = 0; i < spans.length; ++i)
+      if (spans[i] != span) (r || (r = [])).push(spans[i]);
+    return r;
+  }
+  function addMarkedSpan(line, span) {
+    line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
+    span.marker.attachLine(line);
+  }
+
+  function markedSpansBefore(old, startCh, isInsert) {
+    if (old) for (var i = 0, nw; i < old.length; ++i) {
+      var span = old[i], marker = span.marker;
+      var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
+      if (startsBefore || marker.type == "bookmark" && span.from == startCh && (!isInsert || !span.marker.insertLeft)) {
+        var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
+        (nw || (nw = [])).push({from: span.from,
+                                to: endsAfter ? null : span.to,
+                                marker: marker});
+      }
+    }
+    return nw;
+  }
+
+  function markedSpansAfter(old, endCh, isInsert) {
+    if (old) for (var i = 0, nw; i < old.length; ++i) {
+      var span = old[i], marker = span.marker;
+      var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
+      if (endsAfter || marker.type == "bookmark" && span.from == endCh && (!isInsert || span.marker.insertLeft)) {
+        var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
+        (nw || (nw = [])).push({from: startsBefore ? null : span.from - endCh,
+                                to: span.to == null ? null : span.to - endCh,
+                                marker: marker});
+      }
+    }
+    return nw;
+  }
+
+  function stretchSpansOverChange(doc, change) {
+    var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
+    var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
+    if (!oldFirst && !oldLast) return null;
+
+    var startCh = change.from.ch, endCh = change.to.ch, isInsert = posEq(change.from, change.to);
+    // Get the spans that 'stick out' on both sides
+    var first = markedSpansBefore(oldFirst, startCh, isInsert);
+    var last = markedSpansAfter(oldLast, endCh, isInsert);
+
+    // Next, merge those two ends
+    var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
+    if (first) {
+      // Fix up .to properties of first
+      for (var i = 0; i < first.length; ++i) {
+        var span = first[i];
+        if (span.to == null) {
+          var found = getMarkedSpanFor(last, span.marker);
+          if (!found) span.to = startCh;
+          else if (sameLine) span.to = found.to == null ? null : found.to + offset;
+        }
+      }
+    }
+    if (last) {
+      // Fix up .from in last (or move them into first in case of sameLine)
+      for (var i = 0; i < last.length; ++i) {
+        var span = last[i];
+        if (span.to != null) span.to += offset;
+        if (span.from == null) {
+          var found = getMarkedSpanFor(first, span.marker);
+          if (!found) {
+            span.from = offset;
+            if (sameLine) (first || (first = [])).push(span);
+          }
+        } else {
+          span.from += offset;
+          if (sameLine) (first || (first = [])).push(span);
+        }
+      }
+    }
+    if (sameLine && first) {
+      // Make sure we didn't create any zero-length spans
+      for (var i = 0; i < first.length; ++i)
+        if (first[i].from != null && first[i].from == first[i].to && first[i].marker.type != "bookmark")
+          first.splice(i--, 1);
+      if (!first.length) first = null;
+    }
+
+    var newMarkers = [first];
+    if (!sameLine) {
+      // Fill gap with whole-line-spans
+      var gap = change.text.length - 2, gapMarkers;
+      if (gap > 0 && first)
+        for (var i = 0; i < first.length; ++i)
+          if (first[i].to == null)
+            (gapMarkers || (gapMarkers = [])).push({from: null, to: null, marker: first[i].marker});
+      for (var i = 0; i < gap; ++i)
+        newMarkers.push(gapMarkers);
+      newMarkers.push(last);
+    }
+    return newMarkers;
+  }
+
+  function mergeOldSpans(doc, change) {
+    var old = getOldSpans(doc, change);
+    var stretched = stretchSpansOverChange(doc, change);
+    if (!old) return stretched;
+    if (!stretched) return old;
+
+    for (var i = 0; i < old.length; ++i) {
+      var oldCur = old[i], stretchCur = stretched[i];
+      if (oldCur && stretchCur) {
+        spans: for (var j = 0; j < stretchCur.length; ++j) {
+          var span = stretchCur[j];
+          for (var k = 0; k < oldCur.length; ++k)
+            if (oldCur[k].marker == span.marker) continue spans;
+          oldCur.push(span);
+        }
+      } else if (stretchCur) {
+        old[i] = stretchCur;
+      }
+    }
+    return old;
+  }
+
+  function removeReadOnlyRanges(doc, from, to) {
+    var markers = null;
+    doc.iter(from.line, to.line + 1, function(line) {
+      if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
+        var mark = line.markedSpans[i].marker;
+        if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
+          (markers || (markers = [])).push(mark);
+      }
+    });
+    if (!markers) return null;
+    var parts = [{from: from, to: to}];
+    for (var i = 0; i < markers.length; ++i) {
+      var mk = markers[i], m = mk.find();
+      for (var j = 0; j < parts.length; ++j) {
+        var p = parts[j];
+        if (posLess(p.to, m.from) || posLess(m.to, p.from)) continue;
+        var newParts = [j, 1];
+        if (posLess(p.from, m.from) || !mk.inclusiveLeft && posEq(p.from, m.from))
+          newParts.push({from: p.from, to: m.from});
+        if (posLess(m.to, p.to) || !mk.inclusiveRight && posEq(p.to, m.to))
+          newParts.push({from: m.to, to: p.to});
+        parts.splice.apply(parts, newParts);
+        j += newParts.length - 1;
+      }
+    }
+    return parts;
+  }
+
+  function collapsedSpanAt(line, ch) {
+    var sps = sawCollapsedSpans && line.markedSpans, found;
+    if (sps) for (var sp, i = 0; i < sps.length; ++i) {
+      sp = sps[i];
+      if (!sp.marker.collapsed) continue;
+      if ((sp.from == null || sp.from < ch) &&
+          (sp.to == null || sp.to > ch) &&
+          (!found || found.width < sp.marker.width))
+        found = sp.marker;
+    }
+    return found;
+  }
+  function collapsedSpanAtStart(line) { return collapsedSpanAt(line, -1); }
+  function collapsedSpanAtEnd(line) { return collapsedSpanAt(line, line.text.length + 1); }
+
+  function visualLine(doc, line) {
+    var merged;
+    while (merged = collapsedSpanAtStart(line))
+      line = getLine(doc, merged.find().from.line);
+    return line;
+  }
+
+  function lineIsHidden(doc, line) {
+    var sps = sawCollapsedSpans && line.markedSpans;
+    if (sps) for (var sp, i = 0; i < sps.length; ++i) {
+      sp = sps[i];
+      if (!sp.marker.collapsed) continue;
+      if (sp.from == null) return true;
+      if (sp.marker.replacedWith) continue;
+      if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
+        return true;
+    }
+  }
+  function lineIsHiddenInner(doc, line, span) {
+    if (span.to == null) {
+      var end = span.marker.find().to, endLine = getLine(doc, end.line);
+      return lineIsHiddenInner(doc, endLine, getMarkedSpanFor(endLine.markedSpans, span.marker));
+    }
+    if (span.marker.inclusiveRight && span.to == line.text.length)
+      return true;
+    for (var sp, i = 0; i < line.markedSpans.length; ++i) {
+      sp = line.markedSpans[i];
+      if (sp.marker.collapsed && !sp.marker.replacedWith && sp.from == span.to &&
+          (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
+          lineIsHiddenInner(doc, line, sp)) return true;
+    }
+  }
+
+  function detachMarkedSpans(line) {
+    var spans = line.markedSpans;
+    if (!spans) return;
+    for (var i = 0; i < spans.length; ++i)
+      spans[i].marker.detachLine(line);
+    line.markedSpans = null;
+  }
+
+  function attachMarkedSpans(line, spans) {
+    if (!spans) return;
+    for (var i = 0; i < spans.length; ++i)
+      spans[i].marker.attachLine(line);
+    line.markedSpans = spans;
+  }
+
+  // LINE WIDGETS
+
+  var LineWidget = CodeMirror.LineWidget = function(cm, node, options) {
+    if (options) for (var opt in options) if (options.hasOwnProperty(opt))
+      this[opt] = options[opt];
+    this.cm = cm;
+    this.node = node;
+  };
+  eventMixin(LineWidget);
+  function widgetOperation(f) {
+    return function() {
+      var withOp = !this.cm.curOp;
+      if (withOp) startOperation(this.cm);
+      try {var result = f.apply(this, arguments);}
+      finally {if (withOp) endOperation(this.cm);}
+      return result;
+    };
+  }
+  LineWidget.prototype.clear = widgetOperation(function() {
+    var ws = this.line.widgets, no = lineNo(this.line);
+    if (no == null || !ws) return;
+    for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1);
+    if (!ws.length) this.line.widgets = null;
+    var aboveVisible = heightAtLine(this.cm, this.line) < this.cm.doc.scrollTop;
+    updateLineHeight(this.line, Math.max(0, this.line.height - widgetHeight(this)));
+    if (aboveVisible) addToScrollPos(this.cm, 0, -this.height);
+    regChange(this.cm, no, no + 1);
+  });
+  LineWidget.prototype.changed = widgetOperation(function() {
+    var oldH = this.height;
+    this.height = null;
+    var diff = widgetHeight(this) - oldH;
+    if (!diff) return;
+    updateLineHeight(this.line, this.line.height + diff);
+    var no = lineNo(this.line);
+    regChange(this.cm, no, no + 1);
+  });
+
+  function widgetHeight(widget) {
+    if (widget.height != null) return widget.height;
+    if (!widget.node.parentNode || widget.node.parentNode.nodeType != 1)
+      removeChildrenAndAdd(widget.cm.display.measure, elt("div", [widget.node], null, "position: relative"));
+    return widget.height = widget.node.offsetHeight;
+  }
+
+  function addLineWidget(cm, handle, node, options) {
+    var widget = new LineWidget(cm, node, options);
+    if (widget.noHScroll) cm.display.alignWidgets = true;
+    changeLine(cm, handle, function(line) {
+      var widgets = line.widgets || (line.widgets = []);
+      if (widget.insertAt == null) widgets.push(widget);
+      else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget);
+      widget.line = line;
+      if (!lineIsHidden(cm.doc, line) || widget.showIfHidden) {
+        var aboveVisible = heightAtLine(cm, line) < cm.doc.scrollTop;
+        updateLineHeight(line, line.height + widgetHeight(widget));
+        if (aboveVisible) addToScrollPos(cm, 0, widget.height);
+      }
+      return true;
+    });
+    return widget;
+  }
+
+  // LINE DATA STRUCTURE
+
+  // Line objects. These hold state related to a line, including
+  // highlighting info (the styles array).
+  var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) {
+    this.text = text;
+    attachMarkedSpans(this, markedSpans);
+    this.height = estimateHeight ? estimateHeight(this) : 1;
+  };
+  eventMixin(Line);
+
+  function updateLine(line, text, markedSpans, estimateHeight) {
+    line.text = text;
+    if (line.stateAfter) line.stateAfter = null;
+    if (line.styles) line.styles = null;
+    if (line.order != null) line.order = null;
+    detachMarkedSpans(line);
+    attachMarkedSpans(line, markedSpans);
+    var estHeight = estimateHeight ? estimateHeight(line) : 1;
+    if (estHeight != line.height) updateLineHeight(line, estHeight);
+  }
+
+  function cleanUpLine(line) {
+    line.parent = null;
+    detachMarkedSpans(line);
+  }
+
+  // Run the given mode's parser over a line, update the styles
+  // array, which contains alternating fragments of text and CSS
+  // classes.
+  function runMode(cm, text, mode, state, f) {
+    var flattenSpans = mode.flattenSpans;
+    if (flattenSpans == null) flattenSpans = cm.options.flattenSpans;
+    var curStart = 0, curStyle = null;
+    var stream = new StringStream(text, cm.options.tabSize), style;
+    if (text == "" && mode.blankLine) mode.blankLine(state);
+    while (!stream.eol()) {
+      if (stream.pos > cm.options.maxHighlightLength) {
+        flattenSpans = false;
+        // Webkit seems to refuse to render text nodes longer than 57444 characters
+        stream.pos = Math.min(text.length, stream.start + 50000);
+        style = null;
+      } else {
+        style = mode.token(stream, state);
+      }
+      if (!flattenSpans || curStyle != style) {
+        if (curStart < stream.start) f(stream.start, curStyle);
+        curStart = stream.start; curStyle = style;
+      }
+      stream.start = stream.pos;
+    }
+    if (curStart < stream.pos) f(stream.pos, curStyle);
+  }
+
+  function highlightLine(cm, line, state) {
+    // A styles array always starts with a number identifying the
+    // mode/overlays that it is based on (for easy invalidation).
+    var st = [cm.state.modeGen];
+    // Compute the base array of styles
+    runMode(cm, line.text, cm.doc.mode, state, function(end, style) {st.push(end, style);});
+
+    // Run overlays, adjust style array.
+    for (var o = 0; o < cm.state.overlays.length; ++o) {
+      var overlay = cm.state.overlays[o], i = 1, at = 0;
+      runMode(cm, line.text, overlay.mode, true, function(end, style) {
+        var start = i;
+        // Ensure there's a token end at the current position, and that i points at it
+        while (at < end) {
+          var i_end = st[i];
+          if (i_end > end)
+            st.splice(i, 1, end, st[i+1], i_end);
+          i += 2;
+          at = Math.min(end, i_end);
+        }
+        if (!style) return;
+        if (overlay.opaque) {
+          st.splice(start, i - start, end, style);
+          i = start + 2;
+        } else {
+          for (; start < i; start += 2) {
+            var cur = st[start+1];
+            st[start+1] = cur ? cur + " " + style : style;
+          }
+        }
+      });
+    }
+
+    return st;
+  }
+
+  function getLineStyles(cm, line) {
+    if (!line.styles || line.styles[0] != cm.state.modeGen)
+      line.styles = highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line)));
+    return line.styles;
+  }
+
+  // Lightweight form of highlight -- proceed over this line and
+  // update state, but don't save a style array.
+  function processLine(cm, line, state) {
+    var mode = cm.doc.mode;
+    var stream = new StringStream(line.text, cm.options.tabSize);
+    if (line.text == "" && mode.blankLine) mode.blankLine(state);
+    while (!stream.eol() && stream.pos <= cm.options.maxHighlightLength) {
+      mode.token(stream, state);
+      stream.start = stream.pos;
+    }
+  }
+
+  var styleToClassCache = {};
+  function styleToClass(style) {
+    if (!style) return null;
+    return styleToClassCache[style] ||
+      (styleToClassCache[style] = "cm-" + style.replace(/ +/g, " cm-"));
+  }
+
+  function lineContent(cm, realLine, measure, copyWidgets) {
+    var merged, line = realLine, empty = true;
+    while (merged = collapsedSpanAtStart(line))
+      line = getLine(cm.doc, merged.find().from.line);
+
+    var builder = {pre: elt("pre"), col: 0, pos: 0,
+                   measure: null, measuredSomething: false, cm: cm,
+                   copyWidgets: copyWidgets};
+    if (line.textClass) builder.pre.className = line.textClass;
+
+    do {
+      if (line.text) empty = false;
+      builder.measure = line == realLine && measure;
+      builder.pos = 0;
+      builder.addToken = builder.measure ? buildTokenMeasure : buildToken;
+      if ((ie || webkit) && cm.getOption("lineWrapping"))
+        builder.addToken = buildTokenSplitSpaces(builder.addToken);
+      var next = insertLineContent(line, builder, getLineStyles(cm, line));
+      if (measure && line == realLine && !builder.measuredSomething) {
+        measure[0] = builder.pre.appendChild(zeroWidthElement(cm.display.measure));
+        builder.measuredSomething = true;
+      }
+      if (next) line = getLine(cm.doc, next.to.line);
+    } while (next);
+
+    if (measure && !builder.measuredSomething && !measure[0])
+      measure[0] = builder.pre.appendChild(empty ? elt("span", "\u00a0") : zeroWidthElement(cm.display.measure));
+    if (!builder.pre.firstChild && !lineIsHidden(cm.doc, realLine))
+      builder.pre.appendChild(document.createTextNode("\u00a0"));
+
+    var order;
+    // Work around problem with the reported dimensions of single-char
+    // direction spans on IE (issue #1129). See also the comment in
+    // cursorCoords.
+    if (measure && ie && (order = getOrder(line))) {
+      var l = order.length - 1;
+      if (order[l].from == order[l].to) --l;
+      var last = order[l], prev = order[l - 1];
+      if (last.from + 1 == last.to && prev && last.level < prev.level) {
+        var span = measure[builder.pos - 1];
+        if (span) span.parentNode.insertBefore(span.measureRight = zeroWidthElement(cm.display.measure),
+                                               span.nextSibling);
+      }
+    }
+
+    signal(cm, "renderLine", cm, realLine, builder.pre);
+    return builder.pre;
+  }
+
+  var tokenSpecialChars = /[\t\u0000-\u0019\u00ad\u200b\u2028\u2029\uFEFF]/g;
+  function buildToken(builder, text, style, startStyle, endStyle, title) {
+    if (!text) return;
+    if (!tokenSpecialChars.test(text)) {
+      builder.col += text.length;
+      var content = document.createTextNode(text);
+    } else {
+      var content = document.createDocumentFragment(), pos = 0;
+      while (true) {
+        tokenSpecialChars.lastIndex = pos;
+        var m = tokenSpecialChars.exec(text);
+        var skipped = m ? m.index - pos : text.length - pos;
+        if (skipped) {
+          content.appendChild(document.createTextNode(text.slice(pos, pos + skipped)));
+          builder.col += skipped;
+        }
+        if (!m) break;
+        pos += skipped + 1;
+        if (m[0] == "\t") {
+          var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
+          content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
+          builder.col += tabWidth;
+        } else {
+          var token = elt("span", "\u2022", "cm-invalidchar");
+          token.title = "\\u" + m[0].charCodeAt(0).toString(16);
+          content.appendChild(token);
+          builder.col += 1;
+        }
+      }
+    }
+    if (style || startStyle || endStyle || builder.measure) {
+      var fullStyle = style || "";
+      if (startStyle) fullStyle += startStyle;
+      if (endStyle) fullStyle += endStyle;
+      var token = elt("span", [content], fullStyle);
+      if (title) token.title = title;
+      return builder.pre.appendChild(token);
+    }
+    builder.pre.appendChild(content);
+  }
+
+  function buildTokenMeasure(builder, text, style, startStyle, endStyle) {
+    var wrapping = builder.cm.options.lineWrapping;
+    for (var i = 0; i < text.length; ++i) {
+      var ch = text.charAt(i), start = i == 0;
+      if (ch >= "\ud800" && ch < "\udbff" && i < text.length - 1) {
+        ch = text.slice(i, i + 2);
+        ++i;
+      } else if (i && wrapping && spanAffectsWrapping(text, i)) {
+        builder.pre.appendChild(elt("wbr"));
+      }
+      var old = builder.measure[builder.pos];
+      var span = builder.measure[builder.pos] =
+        buildToken(builder, ch, style,
+                   start && startStyle, i == text.length - 1 && endStyle);
+      if (old) span.leftSide = old.leftSide || old;
+      // In IE single-space nodes wrap differently than spaces
+      // embedded in larger text nodes, except when set to
+      // white-space: normal (issue #1268).
+      if (ie && wrapping && ch == " " && i && !/\s/.test(text.charAt(i - 1)) &&
+          i < text.length - 1 && !/\s/.test(text.charAt(i + 1)))
+        span.style.whiteSpace = "normal";
+      builder.pos += ch.length;
+    }
+    if (text.length) builder.measuredSomething = true;
+  }
+
+  function buildTokenSplitSpaces(inner) {
+    function split(old) {
+      var out = " ";
+      for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0";
+      out += " ";
+      return out;
+    }
+    return function(builder, text, style, startStyle, endStyle, title) {
+      return inner(builder, text.replace(/ {3,}/, split), style, startStyle, endStyle, title);
+    };
+  }
+
+  function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
+    var widget = !ignoreWidget && marker.replacedWith;
+    if (widget) {
+      if (builder.copyWidgets) widget = widget.cloneNode(true);
+      builder.pre.appendChild(widget);
+      if (builder.measure) {
+        if (size) {
+          builder.measure[builder.pos] = widget;
+        } else {
+          var elt = builder.measure[builder.pos] = zeroWidthElement(builder.cm.display.measure);
+          if (marker.type != "bookmark" || marker.insertLeft)
+            builder.pre.insertBefore(elt, widget);
+          else
+            builder.pre.appendChild(elt);
+        }
+        builder.measuredSomething = true;
+      }
+    }
+    builder.pos += size;
+  }
+
+  // Outputs a number of spans to make up a line, taking highlighting
+  // and marked text into account.
+  function insertLineContent(line, builder, styles) {
+    var spans = line.markedSpans, allText = line.text, at = 0;
+    if (!spans) {
+      for (var i = 1; i < styles.length; i+=2)
+        builder.addToken(builder, allText.slice(at, at = styles[i]), styleToClass(styles[i+1]));
+      return;
+    }
+
+    var len = allText.length, pos = 0, i = 1, text = "", style;
+    var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
+    for (;;) {
+      if (nextChange == pos) { // Update current marker set
+        spanStyle = spanEndStyle = spanStartStyle = title = "";
+        collapsed = null; nextChange = Infinity;
+        var foundBookmark = null;
+        for (var j = 0; j < spans.length; ++j) {
+          var sp = spans[j], m = sp.marker;
+          if (sp.from <= pos && (sp.to == null || sp.to > pos)) {
+            if (sp.to != null && nextChange > sp.to) { nextChange = sp.to; spanEndStyle = ""; }
+            if (m.className) spanStyle += " " + m.className;
+            if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
+            if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle;
+            if (m.title && !title) title = m.title;
+            if (m.collapsed && (!collapsed || collapsed.marker.size < m.size))
+              collapsed = sp;
+          } else if (sp.from > pos && nextChange > sp.from) {
+            nextChange = sp.from;
+          }
+          if (m.type == "bookmark" && sp.from == pos && m.replacedWith) foundBookmark = m;
+        }
+        if (collapsed && (collapsed.from || 0) == pos) {
+          buildCollapsedSpan(builder, (collapsed.to == null ? len : collapsed.to) - pos,
+                             collapsed.marker, collapsed.from == null);
+          if (collapsed.to == null) return collapsed.marker.find();
+        }
+        if (foundBookmark && !collapsed) buildCollapsedSpan(builder, 0, foundBookmark);
+      }
+      if (pos >= len) break;
+
+      var upto = Math.min(len, nextChange);
+      while (true) {
+        if (text) {
+          var end = pos + text.length;
+          if (!collapsed) {
+            var tokenText = end > upto ? text.slice(0, upto - pos) : text;
+            builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
+                             spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title);
+          }
+          if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
+          pos = end;
+          spanStartStyle = "";
+        }
+        text = allText.slice(at, at = styles[i++]);
+        style = styleToClass(styles[i++]);
+      }
+    }
+  }
+
+  // DOCUMENT DATA STRUCTURE
+
+  function updateDoc(doc, change, markedSpans, selAfter, estimateHeight) {
+    function spansFor(n) {return markedSpans ? markedSpans[n] : null;}
+    function update(line, text, spans) {
+      updateLine(line, text, spans, estimateHeight);
+      signalLater(line, "change", line, change);
+    }
+
+    var from = change.from, to = change.to, text = change.text;
+    var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
+    var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
+
+    // First adjust the line structure
+    if (from.ch == 0 && to.ch == 0 && lastText == "") {
+      // This is a whole-line replace. Treated specially to make
+      // sure line objects move the way they are supposed to.
+      for (var i = 0, e = text.length - 1, added = []; i < e; ++i)
+        added.push(new Line(text[i], spansFor(i), estimateHeight));
+      update(lastLine, lastLine.text, lastSpans);
+      if (nlines) doc.remove(from.line, nlines);
+      if (added.length) doc.insert(from.line, added);
+    } else if (firstLine == lastLine) {
+      if (text.length == 1) {
+        update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
+      } else {
+        for (var added = [], i = 1, e = text.length - 1; i < e; ++i)
+          added.push(new Line(text[i], spansFor(i), estimateHeight));
+        added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
+        update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
+        doc.insert(from.line + 1, added);
+      }
+    } else if (text.length == 1) {
+      update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
+      doc.remove(from.line + 1, nlines);
+    } else {
+      update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
+      update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
+      for (var i = 1, e = text.length - 1, added = []; i < e; ++i)
+        added.push(new Line(text[i], spansFor(i), estimateHeight));
+      if (nlines > 1) doc.remove(from.line + 1, nlines - 1);
+      doc.insert(from.line + 1, added);
+    }
+
+    signalLater(doc, "change", doc, change);
+    setSelection(doc, selAfter.anchor, selAfter.head, null, true);
+  }
+
+  function LeafChunk(lines) {
+    this.lines = lines;
+    this.parent = null;
+    for (var i = 0, e = lines.length, height = 0; i < e; ++i) {
+      lines[i].parent = this;
+      height += lines[i].height;
+    }
+    this.height = height;
+  }
+
+  LeafChunk.prototype = {
+    chunkSize: function() { return this.lines.length; },
+    removeInner: function(at, n) {
+      for (var i = at, e = at + n; i < e; ++i) {
+        var line = this.lines[i];
+        this.height -= line.height;
+        cleanUpLine(line);
+        signalLater(line, "delete");
+      }
+      this.lines.splice(at, n);
+    },
+    collapse: function(lines) {
+      lines.splice.apply(lines, [lines.length, 0].concat(this.lines));
+    },
+    insertInner: function(at, lines, height) {
+      this.height += height;
+      this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
+      for (var i = 0, e = lines.length; i < e; ++i) lines[i].parent = this;
+    },
+    iterN: function(at, n, op) {
+      for (var e = at + n; at < e; ++at)
+        if (op(this.lines[at])) return true;
+    }
+  };
+
+  function BranchChunk(children) {
+    this.children = children;
+    var size = 0, height = 0;
+    for (var i = 0, e = children.length; i < e; ++i) {
+      var ch = children[i];
+      size += ch.chunkSize(); height += ch.height;
+      ch.parent = this;
+    }
+    this.size = size;
+    this.height = height;
+    this.parent = null;
+  }
+
+  BranchChunk.prototype = {
+    chunkSize: function() { return this.size; },
+    removeInner: function(at, n) {
+      this.size -= n;
+      for (var i = 0; i < this.children.length; ++i) {
+        var child = this.children[i], sz = child.chunkSize();
+        if (at < sz) {
+          var rm = Math.min(n, sz - at), oldHeight = child.height;
+          child.removeInner(at, rm);
+          this.height -= oldHeight - child.height;
+          if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
+          if ((n -= rm) == 0) break;
+          at = 0;
+        } else at -= sz;
+      }
+      if (this.size - n < 25) {
+        var lines = [];
+        this.collapse(lines);
+        this.children = [new LeafChunk(lines)];
+        this.children[0].parent = this;
+      }
+    },
+    collapse: function(lines) {
+      for (var i = 0, e = this.children.length; i < e; ++i) this.children[i].collapse(lines);
+    },
+    insertInner: function(at, lines, height) {
+      this.size += lines.length;
+      this.height += height;
+      for (var i = 0, e = this.children.length; i < e; ++i) {
+        var child = this.children[i], sz = child.chunkSize();
+        if (at <= sz) {
+          child.insertInner(at, lines, height);
+          if (child.lines && child.lines.length > 50) {
+            while (child.lines.length > 50) {
+              var spilled = child.lines.splice(child.lines.length - 25, 25);
+              var newleaf = new LeafChunk(spilled);
+              child.height -= newleaf.height;
+              this.children.splice(i + 1, 0, newleaf);
+              newleaf.parent = this;
+            }
+            this.maybeSpill();
+          }
+          break;
+        }
+        at -= sz;
+      }
+    },
+    maybeSpill: function() {
+      if (this.children.length <= 10) return;
+      var me = this;
+      do {
+        var spilled = me.children.splice(me.children.length - 5, 5);
+        var sibling = new BranchChunk(spilled);
+        if (!me.parent) { // Become the parent node
+          var copy = new BranchChunk(me.children);
+          copy.parent = me;
+          me.children = [copy, sibling];
+          me = copy;
+        } else {
+          me.size -= sibling.size;
+          me.height -= sibling.height;
+          var myIndex = indexOf(me.parent.children, me);
+          me.parent.children.splice(myIndex + 1, 0, sibling);
+        }
+        sibling.parent = me.parent;
+      } while (me.children.length > 10);
+      me.parent.maybeSpill();
+    },
+    iterN: function(at, n, op) {
+      for (var i = 0, e = this.children.length; i < e; ++i) {
+        var child = this.children[i], sz = child.chunkSize();
+        if (at < sz) {
+          var used = Math.min(n, sz - at);
+          if (child.iterN(at, used, op)) return true;
+          if ((n -= used) == 0) break;
+          at = 0;
+        } else at -= sz;
+      }
+    }
+  };
+
+  var nextDocId = 0;
+  var Doc = CodeMirror.Doc = function(text, mode, firstLine) {
+    if (!(this instanceof Doc)) return new Doc(text, mode, firstLine);
+    if (firstLine == null) firstLine = 0;
+
+    BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
+    this.first = firstLine;
+    this.scrollTop = this.scrollLeft = 0;
+    this.cantEdit = false;
+    this.history = makeHistory();
+    this.cleanGeneration = 1;
+    this.frontier = firstLine;
+    var start = Pos(firstLine, 0);
+    this.sel = {from: start, to: start, head: start, anchor: start, shift: false, extend: false, goalColumn: null};
+    this.id = ++nextDocId;
+    this.modeOption = mode;
+
+    if (typeof text == "string") text = splitLines(text);
+    updateDoc(this, {from: start, to: start, text: text}, null, {head: start, anchor: start});
+  };
+
+  Doc.prototype = createObj(BranchChunk.prototype, {
+    constructor: Doc,
+    iter: function(from, to, op) {
+      if (op) this.iterN(from - this.first, to - from, op);
+      else this.iterN(this.first, this.first + this.size, from);
+    },
+
+    insert: function(at, lines) {
+      var height = 0;
+      for (var i = 0, e = lines.length; i < e; ++i) height += lines[i].height;
+      this.insertInner(at - this.first, lines, height);
+    },
+    remove: function(at, n) { this.removeInner(at - this.first, n); },
+
+    getValue: function(lineSep) {
+      var lines = getLines(this, this.first, this.first + this.size);
+      if (lineSep === false) return lines;
+      return lines.join(lineSep || "\n");
+    },
+    setValue: function(code) {
+      var top = Pos(this.first, 0), last = this.first + this.size - 1;
+      makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
+                        text: splitLines(code), origin: "setValue"},
+                 {head: top, anchor: top}, true);
+    },
+    replaceRange: function(code, from, to, origin) {
+      from = clipPos(this, from);
+      to = to ? clipPos(this, to) : from;
+      replaceRange(this, code, from, to, origin);
+    },
+    getRange: function(from, to, lineSep) {
+      var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
+      if (lineSep === false) return lines;
+      return lines.join(lineSep || "\n");
+    },
+
+    getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;},
+    setLine: function(line, text) {
+      if (isLine(this, line))
+        replaceRange(this, text, Pos(line, 0), clipPos(this, Pos(line)));
+    },
+    removeLine: function(line) {
+      if (line) replaceRange(this, "", clipPos(this, Pos(line - 1)), clipPos(this, Pos(line)));
+      else replaceRange(this, "", Pos(0, 0), clipPos(this, Pos(1, 0)));
+    },
+
+    getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);},
+    getLineNumber: function(line) {return lineNo(line);},
+
+    getLineHandleVisualStart: function(line) {
+      if (typeof line == "number") line = getLine(this, line);
+      return visualLine(this, line);
+    },
+
+    lineCount: function() {return this.size;},
+    firstLine: function() {return this.first;},
+    lastLine: function() {return this.first + this.size - 1;},
+
+    clipPos: function(pos) {return clipPos(this, pos);},
+
+    getCursor: function(start) {
+      var sel = this.sel, pos;
+      if (start == null || start == "head") pos = sel.head;
+      else if (start == "anchor") pos = sel.anchor;
+      else if (start == "end" || start === false) pos = sel.to;
+      else pos = sel.from;
+      return copyPos(pos);
+    },
+    somethingSelected: function() {return !posEq(this.sel.head, this.sel.anchor);},
+
+    setCursor: docOperation(function(line, ch, extend) {
+      var pos = clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line);
+      if (extend) extendSelection(this, pos);
+      else setSelection(this, pos, pos);
+    }),
+    setSelection: docOperation(function(anchor, head) {
+      setSelection(this, clipPos(this, anchor), clipPos(this, head || anchor));
+    }),
+    extendSelection: docOperation(function(from, to) {
+      extendSelection(this, clipPos(this, from), to && clipPos(this, to));
+    }),
+
+    getSelection: function(lineSep) {return this.getRange(this.sel.from, this.sel.to, lineSep);},
+    replaceSelection: function(code, collapse, origin) {
+      makeChange(this, {from: this.sel.from, to: this.sel.to, text: splitLines(code), origin: origin}, collapse || "around");
+    },
+    undo: docOperation(function() {makeChangeFromHistory(this, "undo");}),
+    redo: docOperation(function() {makeChangeFromHistory(this, "redo");}),
+
+    setExtending: function(val) {this.sel.extend = val;},
+
+    historySize: function() {
+      var hist = this.history;
+      return {undo: hist.done.length, redo: hist.undone.length};
+    },
+    clearHistory: function() {this.history = makeHistory(this.history.maxGeneration);},
+
+    markClean: function() {
+      this.cleanGeneration = this.changeGeneration();
+    },
+    changeGeneration: function() {
+      this.history.lastOp = this.history.lastOrigin = null;
+      return this.history.generation;
+    },
+    isClean: function (gen) {
+      return this.history.generation == (gen || this.cleanGeneration);
+    },
+
+    getHistory: function() {
+      return {done: copyHistoryArray(this.history.done),
+              undone: copyHistoryArray(this.history.undone)};
+    },
+    setHistory: function(histData) {
+      var hist = this.history = makeHistory(this.history.maxGeneration);
+      hist.done = histData.done.slice(0);
+      hist.undone = histData.undone.slice(0);
+    },
+
+    markText: function(from, to, options) {
+      return markText(this, clipPos(this, from), clipPos(this, to), options, "range");
+    },
+    setBookmark: function(pos, options) {
+      var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
+                      insertLeft: options && options.insertLeft};
+      pos = clipPos(this, pos);
+      return markText(this, pos, pos, realOpts, "bookmark");
+    },
+    findMarksAt: function(pos) {
+      pos = clipPos(this, pos);
+      var markers = [], spans = getLine(this, pos.line).markedSpans;
+      if (spans) for (var i = 0; i < spans.length; ++i) {
+        var span = spans[i];
+        if ((span.from == null || span.from <= pos.ch) &&
+            (span.to == null || span.to >= pos.ch))
+          markers.push(span.marker.parent || span.marker);
+      }
+      return markers;
+    },
+    getAllMarks: function() {
+      var markers = [];
+      this.iter(function(line) {
+        var sps = line.markedSpans;
+        if (sps) for (var i = 0; i < sps.length; ++i)
+          if (sps[i].from != null) markers.push(sps[i].marker);
+      });
+      return markers;
+    },
+
+    posFromIndex: function(off) {
+      var ch, lineNo = this.first;
+      this.iter(function(line) {
+        var sz = line.text.length + 1;
+        if (sz > off) { ch = off; return true; }
+        off -= sz;
+        ++lineNo;
+      });
+      return clipPos(this, Pos(lineNo, ch));
+    },
+    indexFromPos: function (coords) {
+      coords = clipPos(this, coords);
+      var index = coords.ch;
+      if (coords.line < this.first || coords.ch < 0) return 0;
+      this.iter(this.first, coords.line, function (line) {
+        index += line.text.length + 1;
+      });
+      return index;
+    },
+
+    copy: function(copyHistory) {
+      var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first);
+      doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
+      doc.sel = {from: this.sel.from, to: this.sel.to, head: this.sel.head, anchor: this.sel.anchor,
+                 shift: this.sel.shift, extend: false, goalColumn: this.sel.goalColumn};
+      if (copyHistory) {
+        doc.history.undoDepth = this.history.undoDepth;
+        doc.setHistory(this.getHistory());
+      }
+      return doc;
+    },
+
+    linkedDoc: function(options) {
+      if (!options) options = {};
+      var from = this.first, to = this.first + this.size;
+      if (options.from != null && options.from > from) from = options.from;
+      if (options.to != null && options.to < to) to = options.to;
+      var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from);
+      if (options.sharedHist) copy.history = this.history;
+      (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
+      copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
+      return copy;
+    },
+    unlinkDoc: function(other) {
+      if (other instanceof CodeMirror) other = other.doc;
+      if (this.linked) for (var i = 0; i < this.linked.length; ++i) {
+        var link = this.linked[i];
+        if (link.doc != other) continue;
+        this.linked.splice(i, 1);
+        other.unlinkDoc(this);
+        break;
+      }
+      // If the histories were shared, split them again
+      if (other.history == this.history) {
+        var splitIds = [other.id];
+        linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true);
+        other.history = makeHistory();
+        other.history.done = copyHistoryArray(this.history.done, splitIds);
+        other.history.undone = copyHistoryArray(this.history.undone, splitIds);
+      }
+    },
+    iterLinkedDocs: function(f) {linkedDocs(this, f);},
+
+    getMode: function() {return this.mode;},
+    getEditor: function() {return this.cm;}
+  });
+
+  Doc.prototype.eachLine = Doc.prototype.iter;
+
+  // The Doc methods that should be available on CodeMirror instances
+  var dontDelegate = "iter insert remove copy getEditor".split(" ");
+  for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
+    CodeMirror.prototype[prop] = (function(method) {
+      return function() {return method.apply(this.doc, arguments);};
+    })(Doc.prototype[prop]);
+
+  eventMixin(Doc);
+
+  function linkedDocs(doc, f, sharedHistOnly) {
+    function propagate(doc, skip, sharedHist) {
+      if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) {
+        var rel = doc.linked[i];
+        if (rel.doc == skip) continue;
+        var shared = sharedHist && rel.sharedHist;
+        if (sharedHistOnly && !shared) continue;
+        f(rel.doc, shared);
+        propagate(rel.doc, doc, shared);
+      }
+    }
+    propagate(doc, null, true);
+  }
+
+  function attachDoc(cm, doc) {
+    if (doc.cm) throw new Error("This document is already in use.");
+    cm.doc = doc;
+    doc.cm = cm;
+    estimateLineHeights(cm);
+    loadMode(cm);
+    if (!cm.options.lineWrapping) computeMaxLength(cm);
+    cm.options.mode = doc.modeOption;
+    regChange(cm);
+  }
+
+  // LINE UTILITIES
+
+  function getLine(chunk, n) {
+    n -= chunk.first;
+    while (!chunk.lines) {
+      for (var i = 0;; ++i) {
+        var child = chunk.children[i], sz = child.chunkSize();
+        if (n < sz) { chunk = child; break; }
+        n -= sz;
+      }
+    }
+    return chunk.lines[n];
+  }
+
+  function getBetween(doc, start, end) {
+    var out = [], n = start.line;
+    doc.iter(start.line, end.line + 1, function(line) {
+      var text = line.text;
+      if (n == end.line) text = text.slice(0, end.ch);
+      if (n == start.line) text = text.slice(start.ch);
+      out.push(text);
+      ++n;
+    });
+    return out;
+  }
+  function getLines(doc, from, to) {
+    var out = [];
+    doc.iter(from, to, function(line) { out.push(line.text); });
+    return out;
+  }
+
+  function updateLineHeight(line, height) {
+    var diff = height - line.height;
+    for (var n = line; n; n = n.parent) n.height += diff;
+  }
+
+  function lineNo(line) {
+    if (line.parent == null) return null;
+    var cur = line.parent, no = indexOf(cur.lines, line);
+    for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
+      for (var i = 0;; ++i) {
+        if (chunk.children[i] == cur) break;
+        no += chunk.children[i].chunkSize();
+      }
+    }
+    return no + cur.first;
+  }
+
+  function lineAtHeight(chunk, h) {
+    var n = chunk.first;
+    outer: do {
+      for (var i = 0, e = chunk.children.length; i < e; ++i) {
+        var child = chunk.children[i], ch = child.height;
+        if (h < ch) { chunk = child; continue outer; }
+        h -= ch;
+        n += child.chunkSize();
+      }
+      return n;
+    } while (!chunk.lines);
+    for (var i = 0, e = chunk.lines.length; i < e; ++i) {
+      var line = chunk.lines[i], lh = line.height;
+      if (h < lh) break;
+      h -= lh;
+    }
+    return n + i;
+  }
+
+  function heightAtLine(cm, lineObj) {
+    lineObj = visualLine(cm.doc, lineObj);
+
+    var h = 0, chunk = lineObj.parent;
+    for (var i = 0; i < chunk.lines.length; ++i) {
+      var line = chunk.lines[i];
+      if (line == lineObj) break;
+      else h += line.height;
+    }
+    for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
+      for (var i = 0; i < p.children.length; ++i) {
+        var cur = p.children[i];
+        if (cur == chunk) break;
+        else h += cur.height;
+      }
+    }
+    return h;
+  }
+
+  function getOrder(line) {
+    var order = line.order;
+    if (order == null) order = line.order = bidiOrdering(line.text);
+    return order;
+  }
+
+  // HISTORY
+
+  function makeHistory(startGen) {
+    return {
+      // Arrays of history events. Doing something adds an event to
+      // done and clears undo. Undoing moves events from done to
+      // undone, redoing moves them in the other direction.
+      done: [], undone: [], undoDepth: Infinity,
+      // Used to track when changes can be merged into a single undo
+      // event
+      lastTime: 0, lastOp: null, lastOrigin: null,
+      // Used by the isClean() method
+      generation: startGen || 1, maxGeneration: startGen || 1
+    };
+  }
+
+  function attachLocalSpans(doc, change, from, to) {
+    var existing = change["spans_" + doc.id], n = 0;
+    doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {
+      if (line.markedSpans)
+        (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;
+      ++n;
+    });
+  }
+
+  function historyChangeFromChange(doc, change) {
+    var from = { line: change.from.line, ch: change.from.ch };
+    var histChange = {from: from, to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
+    attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
+    linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true);
+    return histChange;
+  }
+
+  function addToHistory(doc, change, selAfter, opId) {
+    var hist = doc.history;
+    hist.undone.length = 0;
+    var time = +new Date, cur = lst(hist.done);
+
+    if (cur &&
+        (hist.lastOp == opId ||
+         hist.lastOrigin == change.origin && change.origin &&
+         ((change.origin.charAt(0) == "+" && doc.cm && hist.lastTime > time - doc.cm.options.historyEventDelay) ||
+          change.origin.charAt(0) == "*"))) {
+      // Merge this change into the last event
+      var last = lst(cur.changes);
+      if (posEq(change.from, change.to) && posEq(change.from, last.to)) {
+        // Optimized case for simple insertion -- don't want to add
+        // new changesets for every character typed
+        last.to = changeEnd(change);
+      } else {
+        // Add new sub-event
+        cur.changes.push(historyChangeFromChange(doc, change));
+      }
+      cur.anchorAfter = selAfter.anchor; cur.headAfter = selAfter.head;
+    } else {
+      // Can not be merged, start a new event.
+      cur = {changes: [historyChangeFromChange(doc, change)],
+             generation: hist.generation,
+             anchorBefore: doc.sel.anchor, headBefore: doc.sel.head,
+             anchorAfter: selAfter.anchor, headAfter: selAfter.head};
+      hist.done.push(cur);
+      hist.generation = ++hist.maxGeneration;
+      while (hist.done.length > hist.undoDepth)
+        hist.done.shift();
+    }
+    hist.lastTime = time;
+    hist.lastOp = opId;
+    hist.lastOrigin = change.origin;
+  }
+
+  function removeClearedSpans(spans) {
+    if (!spans) return null;
+    for (var i = 0, out; i < spans.length; ++i) {
+      if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
+      else if (out) out.push(spans[i]);
+    }
+    return !out ? spans : out.length ? out : null;
+  }
+
+  function getOldSpans(doc, change) {
+    var found = change["spans_" + doc.id];
+    if (!found) return null;
+    for (var i = 0, nw = []; i < change.text.length; ++i)
+      nw.push(removeClearedSpans(found[i]));
+    return nw;
+  }
+
+  // Used both to provide a JSON-safe object in .getHistory, and, when
+  // detaching a document, to split the history in two
+  function copyHistoryArray(events, newGroup) {
+    for (var i = 0, copy = []; i < events.length; ++i) {
+      var event = events[i], changes = event.changes, newChanges = [];
+      copy.push({changes: newChanges, anchorBefore: event.anchorBefore, headBefore: event.headBefore,
+                 anchorAfter: event.anchorAfter, headAfter: event.headAfter});
+      for (var j = 0; j < changes.length; ++j) {
+        var change = changes[j], m;
+        newChanges.push({from: change.from, to: change.to, text: change.text});
+        if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) {
+          if (indexOf(newGroup, Number(m[1])) > -1) {
+            lst(newChanges)[prop] = change[prop];
+            delete change[prop];
+          }
+        }
+      }
+    }
+    return copy;
+  }
+
+  // Rebasing/resetting history to deal with externally-sourced changes
+
+  function rebaseHistSel(pos, from, to, diff) {
+    if (to < pos.line) {
+      pos.line += diff;
+    } else if (from < pos.line) {
+      pos.line = from;
+      pos.ch = 0;
+    }
+  }
+
+  // Tries to rebase an array of history events given a change in the
+  // document. If the change touches the same lines as the event, the
+  // event, and everything 'behind' it, is discarded. If the change is
+  // before the event, the event's positions are updated. Uses a
+  // copy-on-write scheme for the positions, to avoid having to
+  // reallocate them all on every rebase, but also avoid problems with
+  // shared position objects being unsafely updated.
+  function rebaseHistArray(array, from, to, diff) {
+    for (var i = 0; i < array.length; ++i) {
+      var sub = array[i], ok = true;
+      for (var j = 0; j < sub.changes.length; ++j) {
+        var cur = sub.changes[j];
+        if (!sub.copied) { cur.from = copyPos(cur.from); cur.to = copyPos(cur.to); }
+        if (to < cur.from.line) {
+          cur.from.line += diff;
+          cur.to.line += diff;
+        } else if (from <= cur.to.line) {
+          ok = false;
+          break;
+        }
+      }
+      if (!sub.copied) {
+        sub.anchorBefore = copyPos(sub.anchorBefore); sub.headBefore = copyPos(sub.headBefore);
+        sub.anchorAfter = copyPos(sub.anchorAfter); sub.readAfter = copyPos(sub.headAfter);
+        sub.copied = true;
+      }
+      if (!ok) {
+        array.splice(0, i + 1);
+        i = 0;
+      } else {
+        rebaseHistSel(sub.anchorBefore); rebaseHistSel(sub.headBefore);
+        rebaseHistSel(sub.anchorAfter); rebaseHistSel(sub.headAfter);
+      }
+    }
+  }
+
+  function rebaseHist(hist, change) {
+    var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
+    rebaseHistArray(hist.done, from, to, diff);
+    rebaseHistArray(hist.undone, from, to, diff);
+  }
+
+  // EVENT OPERATORS
+
+  function stopMethod() {e_stop(this);}
+  // Ensure an event has a stop method.
+  function addStop(event) {
+    if (!event.stop) event.stop = stopMethod;
+    return event;
+  }
+
+  function e_preventDefault(e) {
+    if (e.preventDefault) e.preventDefault();
+    else e.returnValue = false;
+  }
+  function e_stopPropagation(e) {
+    if (e.stopPropagation) e.stopPropagation();
+    else e.cancelBubble = true;
+  }
+  function e_defaultPrevented(e) {
+    return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;
+  }
+  function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
+  CodeMirror.e_stop = e_stop;
+  CodeMirror.e_preventDefault = e_preventDefault;
+  CodeMirror.e_stopPropagation = e_stopPropagation;
+
+  function e_target(e) {return e.target || e.srcElement;}
+  function e_button(e) {
+    var b = e.which;
+    if (b == null) {
+      if (e.button & 1) b = 1;
+      else if (e.button & 2) b = 3;
+      else if (e.button & 4) b = 2;
+    }
+    if (mac && e.ctrlKey && b == 1) b = 3;
+    return b;
+  }
+
+  // EVENT HANDLING
+
+  function on(emitter, type, f) {
+    if (emitter.addEventListener)
+      emitter.addEventListener(type, f, false);
+    else if (emitter.attachEvent)
+      emitter.attachEvent("on" + type, f);
+    else {
+      var map = emitter._handlers || (emitter._handlers = {});
+      var arr = map[type] || (map[type] = []);
+      arr.push(f);
+    }
+  }
+
+  function off(emitter, type, f) {
+    if (emitter.removeEventListener)
+      emitter.removeEventListener(type, f, false);
+    else if (emitter.detachEvent)
+      emitter.detachEvent("on" + type, f);
+    else {
+      var arr = emitter._handlers && emitter._handlers[type];
+      if (!arr) return;
+      for (var i = 0; i < arr.length; ++i)
+        if (arr[i] == f) { arr.splice(i, 1); break; }
+    }
+  }
+
+  function signal(emitter, type /*, values...*/) {
+    var arr = emitter._handlers && emitter._handlers[type];
+    if (!arr) return;
+    var args = Array.prototype.slice.call(arguments, 2);
+    for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args);
+  }
+
+  var delayedCallbacks, delayedCallbackDepth = 0;
+  function signalLater(emitter, type /*, values...*/) {
+    var arr = emitter._handlers && emitter._handlers[type];
+    if (!arr) return;
+    var args = Array.prototype.slice.call(arguments, 2);
+    if (!delayedCallbacks) {
+      ++delayedCallbackDepth;
+      delayedCallbacks = [];
+      setTimeout(fireDelayed, 0);
+    }
+    function bnd(f) {return function(){f.apply(null, args);};};
+    for (var i = 0; i < arr.length; ++i)
+      delayedCallbacks.push(bnd(arr[i]));
+  }
+
+  function signalDOMEvent(cm, e, override) {
+    signal(cm, override || e.type, cm, e);
+    return e_defaultPrevented(e) || e.codemirrorIgnore;
+  }
+
+  function fireDelayed() {
+    --delayedCallbackDepth;
+    var delayed = delayedCallbacks;
+    delayedCallbacks = null;
+    for (var i = 0; i < delayed.length; ++i) delayed[i]();
+  }
+
+  function hasHandler(emitter, type) {
+    var arr = emitter._handlers && emitter._handlers[type];
+    return arr && arr.length > 0;
+  }
+
+  CodeMirror.on = on; CodeMirror.off = off; CodeMirror.signal = signal;
+
+  function eventMixin(ctor) {
+    ctor.prototype.on = function(type, f) {on(this, type, f);};
+    ctor.prototype.off = function(type, f) {off(this, type, f);};
+  }
+
+  // MISC UTILITIES
+
+  // Number of pixels added to scroller and sizer to hide scrollbar
+  var scrollerCutOff = 30;
+
+  // Returned or thrown by various protocols to signal 'I'm not
+  // handling this'.
+  var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
+
+  function Delayed() {this.id = null;}
+  Delayed.prototype = {set: function(ms, f) {clearTimeout(this.id); this.id = setTimeout(f, ms);}};
+
+  // Counts the column offset in a string, taking tabs into account.
+  // Used mostly to find indentation.
+  function countColumn(string, end, tabSize, startIndex, startValue) {
+    if (end == null) {
+      end = string.search(/[^\s\u00a0]/);
+      if (end == -1) end = string.length;
+    }
+    for (var i = startIndex || 0, n = startValue || 0; i < end; ++i) {
+      if (string.charAt(i) == "\t") n += tabSize - (n % tabSize);
+      else ++n;
+    }
+    return n;
+  }
+  CodeMirror.countColumn = countColumn;
+
+  var spaceStrs = [""];
+  function spaceStr(n) {
+    while (spaceStrs.length <= n)
+      spaceStrs.push(lst(spaceStrs) + " ");
+    return spaceStrs[n];
+  }
+
+  function lst(arr) { return arr[arr.length-1]; }
+
+  function selectInput(node) {
+    if (ios) { // Mobile Safari apparently has a bug where select() is broken.
+      node.selectionStart = 0;
+      node.selectionEnd = node.value.length;
+    } else {
+      // Suppress mysterious IE10 errors
+      try { node.select(); }
+      catch(_e) {}
+    }
+  }
+
+  function indexOf(collection, elt) {
+    if (collection.indexOf) return collection.indexOf(elt);
+    for (var i = 0, e = collection.length; i < e; ++i)
+      if (collection[i] == elt) return i;
+    return -1;
+  }
+
+  function createObj(base, props) {
+    function Obj() {}
+    Obj.prototype = base;
+    var inst = new Obj();
+    if (props) copyObj(props, inst);
+    return inst;
+  }
+
+  function copyObj(obj, target) {
+    if (!target) target = {};
+    for (var prop in obj) if (obj.hasOwnProperty(prop)) target[prop] = obj[prop];
+    return target;
+  }
+
+  function emptyArray(size) {
+    for (var a = [], i = 0; i < size; ++i) a.push(undefined);
+    return a;
+  }
+
+  function bind(f) {
+    var args = Array.prototype.slice.call(arguments, 1);
+    return function(){return f.apply(null, args);};
+  }
+
+  var nonASCIISingleCaseWordChar = /[\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
+  function isWordChar(ch) {
+    return /\w/.test(ch) || ch > "\x80" &&
+      (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
+  }
+
+  function isEmpty(obj) {
+    for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false;
+    return true;
+  }
+
+  var isExtendingChar = /[\u0300-\u036F\u0483-\u0487\u0488-\u0489\u0591-\u05BD\u05BF\u05C1-\u05C2\u05C4-\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7-\u06E8\u06EA-\u06ED\uA66F\uA670-\uA672\uA674-\uA67D\uA69F\udc00-\udfff]/;
+
+  // DOM UTILITIES
+
+  function elt(tag, content, className, style) {
+    var e = document.createElement(tag);
+    if (className) e.className = className;
+    if (style) e.style.cssText = style;
+    if (typeof content == "string") setTextContent(e, content);
+    else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
+    return e;
+  }
+
+  function removeChildren(e) {
+    for (var count = e.childNodes.length; count > 0; --count)
+      e.removeChild(e.firstChild);
+    return e;
+  }
+
+  function removeChildrenAndAdd(parent, e) {
+    return removeChildren(parent).appendChild(e);
+  }
+
+  function setTextContent(e, str) {
+    if (ie_lt9) {
+      e.innerHTML = "";
+      e.appendChild(document.createTextNode(str));
+    } else e.textContent = str;
+  }
+
+  function getRect(node) {
+    return node.getBoundingClientRect();
+  }
+  CodeMirror.replaceGetRect = function(f) { getRect = f; };
+
+  // FEATURE DETECTION
+
+  // Detect drag-and-drop
+  var dragAndDrop = function() {
+    // There is *some* kind of drag-and-drop support in IE6-8, but I
+    // couldn't get it to work yet.
+    if (ie_lt9) return false;
+    var div = elt('div');
+    return "draggable" in div || "dragDrop" in div;
+  }();
+
+  // For a reason I have yet to figure out, some browsers disallow
+  // word wrapping between certain characters *only* if a new inline
+  // element is started between them. This makes it hard to reliably
+  // measure the position of things, since that requires inserting an
+  // extra span. This terribly fragile set of tests matches the
+  // character combinations that suffer from this phenomenon on the
+  // various browsers.
+  function spanAffectsWrapping() { return false; }
+  if (gecko) // Only for "$'"
+    spanAffectsWrapping = function(str, i) {
+      return str.charCodeAt(i - 1) == 36 && str.charCodeAt(i) == 39;
+    };
+  else if (safari && !/Version\/([6-9]|\d\d)\b/.test(navigator.userAgent))
+    spanAffectsWrapping = function(str, i) {
+      return /\-[^ \-?]|\?[^ !\'\"\),.\-\/:;\?\]\}]/.test(str.slice(i - 1, i + 1));
+    };
+  else if (webkit && !/Chrome\/(?:29|[3-9]\d|\d\d\d)\./.test(navigator.userAgent))
+    spanAffectsWrapping = function(str, i) {
+      if (i > 1 && str.charCodeAt(i - 1) == 45) {
+        if (/\w/.test(str.charAt(i - 2)) && /[^\-?\.]/.test(str.charAt(i))) return true;
+        if (i > 2 && /[\d\.,]/.test(str.charAt(i - 2)) && /[\d\.,]/.test(str.charAt(i))) return false;
+      }
+      return /[~!#%&*)=+}\]|\"\.>,:;][({[<]|-[^\-?\.\u2010-\u201f\u2026]|\?[\w~`@#$%\^&*(_=+{[|><]|…[\w~`@#$%\^&*(_=+{[><]/.test(str.slice(i - 1, i + 1));
+    };
+
+  var knownScrollbarWidth;
+  function scrollbarWidth(measure) {
+    if (knownScrollbarWidth != null) return knownScrollbarWidth;
+    var test = elt("div", null, null, "width: 50px; height: 50px; overflow-x: scroll");
+    removeChildrenAndAdd(measure, test);
+    if (test.offsetWidth)
+      knownScrollbarWidth = test.offsetHeight - test.clientHeight;
+    return knownScrollbarWidth || 0;
+  }
+
+  var zwspSupported;
+  function zeroWidthElement(measure) {
+    if (zwspSupported == null) {
+      var test = elt("span", "\u200b");
+      removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
+      if (measure.firstChild.offsetHeight != 0)
+        zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !ie_lt8;
+    }
+    if (zwspSupported) return elt("span", "\u200b");
+    else return elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
+  }
+
+  // See if "".split is the broken IE version, if so, provide an
+  // alternative way to split lines.
+  var splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
+    var pos = 0, result = [], l = string.length;
+    while (pos <= l) {
+      var nl = string.indexOf("\n", pos);
+      if (nl == -1) nl = string.length;
+      var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
+      var rt = line.indexOf("\r");
+      if (rt != -1) {
+        result.push(line.slice(0, rt));
+        pos += rt + 1;
+      } else {
+        result.push(line);
+        pos = nl + 1;
+      }
+    }
+    return result;
+  } : function(string){return string.split(/\r\n?|\n/);};
+  CodeMirror.splitLines = splitLines;
+
+  var hasSelection = window.getSelection ? function(te) {
+    try { return te.selectionStart != te.selectionEnd; }
+    catch(e) { return false; }
+  } : function(te) {
+    try {var range = te.ownerDocument.selection.createRange();}
+    catch(e) {}
+    if (!range || range.parentElement() != te) return false;
+    return range.compareEndPoints("StartToEnd", range) != 0;
+  };
+
+  var hasCopyEvent = (function() {
+    var e = elt("div");
+    if ("oncopy" in e) return true;
+    e.setAttribute("oncopy", "return;");
+    return typeof e.oncopy == 'function';
+  })();
+
+  // KEY NAMING
+
+  var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
+                  19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
+                  36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
+                  46: "Delete", 59: ";", 91: "Mod", 92: "Mod", 93: "Mod", 109: "-", 107: "=", 127: "Delete",
+                  186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
+                  221: "]", 222: "'", 63276: "PageUp", 63277: "PageDown", 63275: "End", 63273: "Home",
+                  63234: "Left", 63232: "Up", 63235: "Right", 63233: "Down", 63302: "Insert", 63272: "Delete"};
+  CodeMirror.keyNames = keyNames;
+  (function() {
+    // Number keys
+    for (var i = 0; i < 10; i++) keyNames[i + 48] = String(i);
+    // Alphabetic keys
+    for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
+    // Function keys
+    for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
+  })();
+
+  // BIDI HELPERS
+
+  function iterateBidiSections(order, from, to, f) {
+    if (!order) return f(from, to, "ltr");
+    var found = false;
+    for (var i = 0; i < order.length; ++i) {
+      var part = order[i];
+      if (part.from < to && part.to > from || from == to && part.to == from) {
+        f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
+        found = true;
+      }
+    }
+    if (!found) f(from, to, "ltr");
+  }
+
+  function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
+  function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
+
+  function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
+  function lineRight(line) {
+    var order = getOrder(line);
+    if (!order) return line.text.length;
+    return bidiRight(lst(order));
+  }
+
+  function lineStart(cm, lineN) {
+    var line = getLine(cm.doc, lineN);
+    var visual = visualLine(cm.doc, line);
+    if (visual != line) lineN = lineNo(visual);
+    var order = getOrder(visual);
+    var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);
+    return Pos(lineN, ch);
+  }
+  function lineEnd(cm, lineN) {
+    var merged, line;
+    while (merged = collapsedSpanAtEnd(line = getLine(cm.doc, lineN)))
+      lineN = merged.find().to.line;
+    var order = getOrder(line);
+    var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
+    return Pos(lineN, ch);
+  }
+
+  function compareBidiLevel(order, a, b) {
+    var linedir = order[0].level;
+    if (a == linedir) return true;
+    if (b == linedir) return false;
+    return a < b;
+  }
+  var bidiOther;
+  function getBidiPartAt(order, pos) {
+    for (var i = 0, found; i < order.length; ++i) {
+      var cur = order[i];
+      if (cur.from < pos && cur.to > pos) { bidiOther = null; return i; }
+      if (cur.from == pos || cur.to == pos) {
+        if (found == null) {
+          found = i;
+        } else if (compareBidiLevel(order, cur.level, order[found].level)) {
+          bidiOther = found;
+          return i;
+        } else {
+          bidiOther = i;
+          return found;
+        }
+      }
+    }
+    bidiOther = null;
+    return found;
+  }
+
+  function moveInLine(line, pos, dir, byUnit) {
+    if (!byUnit) return pos + dir;
+    do pos += dir;
+    while (pos > 0 && isExtendingChar.test(line.text.charAt(pos)));
+    return pos;
+  }
+
+  // This is somewhat involved. It is needed in order to move
+  // 'visually' through bi-directional text -- i.e., pressing left
+  // should make the cursor go left, even when in RTL text. The
+  // tricky part is the 'jumps', where RTL and LTR text touch each
+  // other. This often requires the cursor offset to move more than
+  // one unit, in order to visually move one unit.
+  function moveVisually(line, start, dir, byUnit) {
+    var bidi = getOrder(line);
+    if (!bidi) return moveLogically(line, start, dir, byUnit);
+    var pos = getBidiPartAt(bidi, start), part = bidi[pos];
+    var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit);
+
+    for (;;) {
+      if (target > part.from && target < part.to) return target;
+      if (target == part.from || target == part.to) {
+        if (getBidiPartAt(bidi, target) == pos) return target;
+        part = bidi[pos += dir];
+        return (dir > 0) == part.level % 2 ? part.to : part.from;
+      } else {
+        part = bidi[pos += dir];
+        if (!part) return null;
+        if ((dir > 0) == part.level % 2)
+          target = moveInLine(line, part.to, -1, byUnit);
+        else
+          target = moveInLine(line, part.from, 1, byUnit);
+      }
+    }
+  }
+
+  function moveLogically(line, start, dir, byUnit) {
+    var target = start + dir;
+    if (byUnit) while (target > 0 && isExtendingChar.test(line.text.charAt(target))) target += dir;
+    return target < 0 || target > line.text.length ? null : target;
+  }
+
+  // Bidirectional ordering algorithm
+  // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
+  // that this (partially) implements.
+
+  // One-char codes used for character types:
+  // L (L):   Left-to-Right
+  // R (R):   Right-to-Left
+  // r (AL):  Right-to-Left Arabic
+  // 1 (EN):  European Number
+  // + (ES):  European Number Separator
+  // % (ET):  European Number Terminator
+  // n (AN):  Arabic Number
+  // , (CS):  Common Number Separator
+  // m (NSM): Non-Spacing Mark
+  // b (BN):  Boundary Neutral
+  // s (B):   Paragraph Separator
+  // t (S):   Segment Separator
+  // w (WS):  Whitespace
+  // N (ON):  Other Neutrals
+
+  // Returns null if characters are ordered as they appear
+  // (left-to-right), or an array of sections ({from, to, level}
+  // objects) in the order in which they occur visually.
+  var bidiOrdering = (function() {
+    // Character types for codepoints 0 to 0xff
+    var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLL";
+    // Character types for codepoints 0x600 to 0x6ff
+    var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmmrrrrrrrrrrrrrrrrrr";
+    function charType(code) {
+      if (code <= 0xff) return lowTypes.charAt(code);
+      else if (0x590 <= code && code <= 0x5f4) return "R";
+      else if (0x600 <= code && code <= 0x6ff) return arabicTypes.charAt(code - 0x600);
+      else if (0x700 <= code && code <= 0x8ac) return "r";
+      else return "L";
+    }
+
+    var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
+    var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
+    // Browsers seem to always treat the boundaries of block elements as being L.
+    var outerType = "L";
+
+    return function(str) {
+      if (!bidiRE.test(str)) return false;
+      var len = str.length, types = [];
+      for (var i = 0, type; i < len; ++i)
+        types.push(type = charType(str.charCodeAt(i)));
+
+      // W1. Examine each non-spacing mark (NSM) in the level run, and
+      // change the type of the NSM to the type of the previous
+      // character. If the NSM is at the start of the level run, it will
+      // get the type of sor.
+      for (var i = 0, prev = outerType; i < len; ++i) {
+        var type = types[i];
+        if (type == "m") types[i] = prev;
+        else prev = type;
+      }
+
+      // W2. Search backwards from each instance of a European number
+      // until the first strong type (R, L, AL, or sor) is found. If an
+      // AL is found, change the type of the European number to Arabic
+      // number.
+      // W3. Change all ALs to R.
+      for (var i = 0, cur = outerType; i < len; ++i) {
+        var type = types[i];
+        if (type == "1" && cur == "r") types[i] = "n";
+        else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }
+      }
+
+      // W4. A single European separator between two European numbers
+      // changes to a European number. A single common separator between
+      // two numbers of the same type changes to that type.
+      for (var i = 1, prev = types[0]; i < len - 1; ++i) {
+        var type = types[i];
+        if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1";
+        else if (type == "," && prev == types[i+1] &&
+                 (prev == "1" || prev == "n")) types[i] = prev;
+        prev = type;
+      }
+
+      // W5. A sequence of European terminators adjacent to European
+      // numbers changes to all European numbers.
+      // W6. Otherwise, separators and terminators change to Other
+      // Neutral.
+      for (var i = 0; i < len; ++i) {
+        var type = types[i];
+        if (type == ",") types[i] = "N";
+        else if (type == "%") {
+          for (var end = i + 1; end < len && types[end] == "%"; ++end) {}
+          var replace = (i && types[i-1] == "!") || (end < len - 1 && types[end] == "1") ? "1" : "N";
+          for (var j = i; j < end; ++j) types[j] = replace;
+          i = end - 1;
+        }
+      }
+
+      // W7. Search backwards from each instance of a European number
+      // until the first strong type (R, L, or sor) is found. If an L is
+      // found, then change the type of the European number to L.
+      for (var i = 0, cur = outerType; i < len; ++i) {
+        var type = types[i];
+        if (cur == "L" && type == "1") types[i] = "L";
+        else if (isStrong.test(type)) cur = type;
+      }
+
+      // N1. A sequence of neutrals takes the direction of the
+      // surrounding strong text if the text on both sides has the same
+      // direction. European and Arabic numbers act as if they were R in
+      // terms of their influence on neutrals. Start-of-level-run (sor)
+      // and end-of-level-run (eor) are used at level run boundaries.
+      // N2. Any remaining neutrals take the embedding direction.
+      for (var i = 0; i < len; ++i) {
+        if (isNeutral.test(types[i])) {
+          for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}
+          var before = (i ? types[i-1] : outerType) == "L";
+          var after = (end < len - 1 ? types[end] : outerType) == "L";
+          var replace = before || after ? "L" : "R";
+          for (var j = i; j < end; ++j) types[j] = replace;
+          i = end - 1;
+        }
+      }
+
+      // Here we depart from the documented algorithm, in order to avoid
+      // building up an actual levels array. Since there are only three
+      // levels (0, 1, 2) in an implementation that doesn't take
+      // explicit embedding into account, we can build up the order on
+      // the fly, without following the level-based algorithm.
+      var order = [], m;
+      for (var i = 0; i < len;) {
+        if (countsAsLeft.test(types[i])) {
+          var start = i;
+          for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}
+          order.push({from: start, to: i, level: 0});
+        } else {
+          var pos = i, at = order.length;
+          for (++i; i < len && types[i] != "L"; ++i) {}
+          for (var j = pos; j < i;) {
+            if (countsAsNum.test(types[j])) {
+              if (pos < j) order.splice(at, 0, {from: pos, to: j, level: 1});
+              var nstart = j;
+              for (++j; j < i && countsAsNum.test(types[j]); ++j) {}
+              order.splice(at, 0, {from: nstart, to: j, level: 2});
+              pos = j;
+            } else ++j;
+          }
+          if (pos < i) order.splice(at, 0, {from: pos, to: i, level: 1});
+        }
+      }
+      if (order[0].level == 1 && (m = str.match(/^\s+/))) {
+        order[0].from = m[0].length;
+        order.unshift({from: 0, to: m[0].length, level: 0});
+      }
+      if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
+        lst(order).to -= m[0].length;
+        order.push({from: len - m[0].length, to: len, level: 0});
+      }
+      if (order[0].level != lst(order).level)
+        order.push({from: len, to: len, level: order[0].level});
+
+      return order;
+    };
+  })();
+
+  // THE END
+
+  CodeMirror.version = "3.15.0";
+
+  return CodeMirror;
+})();
diff --git a/third-party/codemirror-3.15/mode/apl/apl.js b/third-party/codemirror-3.15/mode/apl/apl.js
new file mode 100644 (file)
index 0000000..5c23af8
--- /dev/null
@@ -0,0 +1,160 @@
+CodeMirror.defineMode("apl", function() {
+  var builtInOps = {
+    ".": "innerProduct",
+    "\\": "scan",
+    "/": "reduce",
+    "⌿": "reduce1Axis",
+    "⍀": "scan1Axis",
+    "¨": "each",
+    "⍣": "power"
+  };
+  var builtInFuncs = {
+    "+": ["conjugate", "add"],
+    "−": ["negate", "subtract"],
+    "×": ["signOf", "multiply"],
+    "÷": ["reciprocal", "divide"],
+    "⌈": ["ceiling", "greaterOf"],
+    "⌊": ["floor", "lesserOf"],
+    "∣": ["absolute", "residue"],
+    "⍳": ["indexGenerate", "indexOf"],
+    "?": ["roll", "deal"],
+    "⋆": ["exponentiate", "toThePowerOf"],
+    "⍟": ["naturalLog", "logToTheBase"],
+    "○": ["piTimes", "circularFuncs"],
+    "!": ["factorial", "binomial"],
+    "⌹": ["matrixInverse", "matrixDivide"],
+    "<": [null, "lessThan"],
+    "≤": [null, "lessThanOrEqual"],
+    "=": [null, "equals"],
+    ">": [null, "greaterThan"],
+    "≥": [null, "greaterThanOrEqual"],
+    "≠": [null, "notEqual"],
+    "≡": ["depth", "match"],
+    "≢": [null, "notMatch"],
+    "∈": ["enlist", "membership"],
+    "⍷": [null, "find"],
+    "∪": ["unique", "union"],
+    "∩": [null, "intersection"],
+    "∼": ["not", "without"],
+    "∨": [null, "or"],
+    "∧": [null, "and"],
+    "⍱": [null, "nor"],
+    "⍲": [null, "nand"],
+    "⍴": ["shapeOf", "reshape"],
+    ",": ["ravel", "catenate"],
+    "⍪": [null, "firstAxisCatenate"],
+    "⌽": ["reverse", "rotate"],
+    "⊖": ["axis1Reverse", "axis1Rotate"],
+    "⍉": ["transpose", null],
+    "↑": ["first", "take"],
+    "↓": [null, "drop"],
+    "⊂": ["enclose", "partitionWithAxis"],
+    "⊃": ["diclose", "pick"],
+    "⌷": [null, "index"],
+    "⍋": ["gradeUp", null],
+    "⍒": ["gradeDown", null],
+    "⊤": ["encode", null],
+    "⊥": ["decode", null],
+    "⍕": ["format", "formatByExample"],
+    "⍎": ["execute", null],
+    "⊣": ["stop", "left"],
+    "⊢": ["pass", "right"]
+  };
+
+  var isOperator = /[\.\/⌿⍀¨⍣]/;
+  var isNiladic = /⍬/;
+  var isFunction = /[\+−×÷⌈⌊∣⍳\?⋆⍟○!⌹<≤=>≥≠≡≢∈⍷∪∩∼∨∧⍱⍲⍴,⍪⌽⊖⍉↑↓⊂⊃⌷⍋⍒⊤⊥⍕⍎⊣⊢]/;
+  var isArrow = /←/;
+  var isComment = /[⍝#].*$/;
+
+  var stringEater = function(type) {
+    var prev;
+    prev = false;
+    return function(c) {
+      prev = c;
+      if (c === type) {
+        return prev === "\\";
+      }
+      return true;
+    };
+  };
+  return {
+    startState: function() {
+      return {
+        prev: false,
+        func: false,
+        op: false,
+        string: false,
+        escape: false
+      };
+    },
+    token: function(stream, state) {
+      var ch, funcName, word;
+      if (stream.eatSpace()) {
+        return null;
+      }
+      ch = stream.next();
+      if (ch === '"' || ch === "'") {
+        stream.eatWhile(stringEater(ch));
+        stream.next();
+        state.prev = true;
+        return "string";
+      }
+      if (/[\[{\(]/.test(ch)) {
+        state.prev = false;
+        return null;
+      }
+      if (/[\]}\)]/.test(ch)) {
+        state.prev = true;
+        return null;
+      }
+      if (isNiladic.test(ch)) {
+        state.prev = false;
+        return "niladic";
+      }
+      if (/[¯\d]/.test(ch)) {
+        if (state.func) {
+          state.func = false;
+          state.prev = false;
+        } else {
+          state.prev = true;
+        }
+        stream.eatWhile(/[\w\.]/);
+        return "number";
+      }
+      if (isOperator.test(ch)) {
+        return "operator apl-" + builtInOps[ch];
+      }
+      if (isArrow.test(ch)) {
+        return "apl-arrow";
+      }
+      if (isFunction.test(ch)) {
+        funcName = "apl-";
+        if (builtInFuncs[ch] != null) {
+          if (state.prev) {
+            funcName += builtInFuncs[ch][1];
+          } else {
+            funcName += builtInFuncs[ch][0];
+          }
+        }
+        state.func = true;
+        state.prev = false;
+        return "function " + funcName;
+      }
+      if (isComment.test(ch)) {
+        stream.skipToEnd();
+        return "comment";
+      }
+      if (ch === "∘" && stream.peek() === ".") {
+        stream.next();
+        return "function jot-dot";
+      }
+      stream.eatWhile(/[\w\$_]/);
+      word = stream.current();
+      state.prev = true;
+      return "keyword";
+    }
+  };
+});
+
+CodeMirror.defineMIME("text/apl", "apl");
diff --git a/third-party/codemirror-3.15/mode/apl/index.html b/third-party/codemirror-3.15/mode/apl/index.html
new file mode 100644 (file)
index 0000000..119ff17
--- /dev/null
@@ -0,0 +1,61 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: APL mode</title>
+    <link rel="stylesheet" href="../../doc/docs.css"> 
+    <link rel="stylesheet" href="../../lib/codemirror.css"> 
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../../addon/edit/matchbrackets.js"></script>
+    <script src="./apl.js"></script>
+    <style>
+       .CodeMirror { border: 2px inset #dee; }
+    </style>
+  </head>
+  <body>
+    <h1>CodeMirror: APL mode</h1>
+
+<form><textarea id="code" name="code">
+⍝ Conway's game of life
+
+⍝ This example was inspired by the impressive demo at
+⍝ http://www.youtube.com/watch?v=a9xAKttWgP4
+
+⍝ Create a matrix:
+⍝     0 1 1
+⍝     1 1 0
+⍝     0 1 0
+creature ← (3 3 ⍴ ⍳ 9) ∈ 1 2 3 4 7   ⍝ Original creature from demo
+creature ← (3 3 ⍴ ⍳ 9) ∈ 1 3 6 7 8   ⍝ Glider
+
+⍝ Place the creature on a larger board, near the centre
+board ← ¯1 ⊖ ¯2 ⌽ 5 7 ↑ creature
+
+⍝ A function to move from one generation to the next
+life ← {∨/ 1 ⍵ ∧ 3 4 = ⊂+/ +⌿ 1 0 ¯1 ∘.⊖ 1 0 ¯1 ⌽¨ ⊂⍵}
+
+⍝ Compute n-th generation and format it as a
+⍝ character matrix
+gen ← {' #'[(life ⍣ ⍵) board]}
+
+⍝ Show first three generations
+(gen 1) (gen 2) (gen 3)
+</textarea></form>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        matchBrackets: true,
+        mode: "text/apl"
+      });
+    </script>
+
+    <p>Simple mode that tries to handle APL as well as it can.</p>
+    <p>It attempts to label functions/operators based upon
+    monadic/dyadic usage (but this is far from fully fleshed out).
+    This means there are meaningful classnames so hover states can
+    have popups etc.</p>
+
+    <p><strong>MIME types defined:</strong> <code>text/apl</code> (APL code)</p>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/asterisk/asterisk.js b/third-party/codemirror-3.15/mode/asterisk/asterisk.js
new file mode 100644 (file)
index 0000000..60b689d
--- /dev/null
@@ -0,0 +1,183 @@
+/*
+ * =====================================================================================
+ *
+ *       Filename:  mode/asterisk/asterisk.js
+ *
+ *    Description:  CodeMirror mode for Asterisk dialplan
+ *
+ *        Created:  05/17/2012 09:20:25 PM
+ *       Revision:  none
+ *
+ *         Author:  Stas Kobzar (stas@modulis.ca),
+ *        Company:  Modulis.ca Inc.
+ *
+ * =====================================================================================
+ */
+
+CodeMirror.defineMode("asterisk", function() {
+  var atoms    = ["exten", "same", "include","ignorepat","switch"],
+      dpcmd    = ["#include","#exec"],
+      apps     = [
+                  "addqueuemember","adsiprog","aelsub","agentlogin","agentmonitoroutgoing","agi",
+                  "alarmreceiver","amd","answer","authenticate","background","backgrounddetect",
+                  "bridge","busy","callcompletioncancel","callcompletionrequest","celgenuserevent",
+                  "changemonitor","chanisavail","channelredirect","chanspy","clearhash","confbridge",
+                  "congestion","continuewhile","controlplayback","dahdiacceptr2call","dahdibarge",
+                  "dahdiras","dahdiscan","dahdisendcallreroutingfacility","dahdisendkeypadfacility",
+                  "datetime","dbdel","dbdeltree","deadagi","dial","dictate","directory","disa",
+                  "dumpchan","eagi","echo","endwhile","exec","execif","execiftime","exitwhile","extenspy",
+                  "externalivr","festival","flash","followme","forkcdr","getcpeid","gosub","gosubif",
+                  "goto","gotoif","gotoiftime","hangup","iax2provision","ices","importvar","incomplete",
+                  "ivrdemo","jabberjoin","jabberleave","jabbersend","jabbersendgroup","jabberstatus",
+                  "jack","log","macro","macroexclusive","macroexit","macroif","mailboxexists","meetme",
+                  "meetmeadmin","meetmechanneladmin","meetmecount","milliwatt","minivmaccmess","minivmdelete",
+                  "minivmgreet","minivmmwi","minivmnotify","minivmrecord","mixmonitor","monitor","morsecode",
+                  "mp3player","mset","musiconhold","nbscat","nocdr","noop","odbc","odbc","odbcfinish",
+                  "originate","ospauth","ospfinish","osplookup","ospnext","page","park","parkandannounce",
+                  "parkedcall","pausemonitor","pausequeuemember","pickup","pickupchan","playback","playtones",
+                  "privacymanager","proceeding","progress","queue","queuelog","raiseexception","read","readexten",
+                  "readfile","receivefax","receivefax","receivefax","record","removequeuemember",
+                  "resetcdr","retrydial","return","ringing","sayalpha","saycountedadj","saycountednoun",
+                  "saycountpl","saydigits","saynumber","sayphonetic","sayunixtime","senddtmf","sendfax",
+                  "sendfax","sendfax","sendimage","sendtext","sendurl","set","setamaflags",
+                  "setcallerpres","setmusiconhold","sipaddheader","sipdtmfmode","sipremoveheader","skel",
+                  "slastation","slatrunk","sms","softhangup","speechactivategrammar","speechbackground",
+                  "speechcreate","speechdeactivategrammar","speechdestroy","speechloadgrammar","speechprocessingsound",
+                  "speechstart","speechunloadgrammar","stackpop","startmusiconhold","stopmixmonitor","stopmonitor",
+                  "stopmusiconhold","stopplaytones","system","testclient","testserver","transfer","tryexec",
+                  "trysystem","unpausemonitor","unpausequeuemember","userevent","verbose","vmauthenticate",
+                  "vmsayname","voicemail","voicemailmain","wait","waitexten","waitfornoise","waitforring",
+                  "waitforsilence","waitmusiconhold","waituntil","while","zapateller"
+                 ];
+
+  function basicToken(stream,state){
+    var cur = '';
+    var ch  = '';
+    ch = stream.next();
+    // comment
+    if(ch == ";") {
+      stream.skipToEnd();
+      return "comment";
+    }
+    // context
+    if(ch == '[') {
+      stream.skipTo(']');
+      stream.eat(']');
+      return "header";
+    }
+    // string
+    if(ch == '"') {
+      stream.skipTo('"');
+      return "string";
+    }
+    if(ch == "'") {
+      stream.skipTo("'");
+      return "string-2";
+    }
+    // dialplan commands
+    if(ch == '#') {
+      stream.eatWhile(/\w/);
+      cur = stream.current();
+      if(dpcmd.indexOf(cur) !== -1) {
+        stream.skipToEnd();
+        return "strong";
+      }
+    }
+    // application args
+    if(ch == '$'){
+      var ch1 = stream.peek();
+      if(ch1 == '{'){
+        stream.skipTo('}');
+        stream.eat('}');
+        return "variable-3";
+      }
+    }
+    // extension
+    stream.eatWhile(/\w/);
+    cur = stream.current();
+    if(atoms.indexOf(cur) !== -1) {
+      state.extenStart = true;
+      switch(cur) {
+        case 'same': state.extenSame = true; break;
+        case 'include':
+        case 'switch':
+        case 'ignorepat':
+          state.extenInclude = true;break;
+        default:break;
+      }
+      return "atom";
+    }
+  }
+
+  return {
+    startState: function() {
+      return {
+        extenStart: false,
+        extenSame:  false,
+        extenInclude: false,
+        extenExten: false,
+        extenPriority: false,
+        extenApplication: false
+      };
+    },
+    token: function(stream, state) {
+
+      var cur = '';
+      var ch  = '';
+      if(stream.eatSpace()) return null;
+      // extension started
+      if(state.extenStart){
+        stream.eatWhile(/[^\s]/);
+        cur = stream.current();
+        if(/^=>?$/.test(cur)){
+          state.extenExten = true;
+          state.extenStart = false;
+          return "strong";
+        } else {
+          state.extenStart = false;
+          stream.skipToEnd();
+          return "error";
+        }
+      } else if(state.extenExten) {
+        // set exten and priority
+        state.extenExten = false;
+        state.extenPriority = true;
+        stream.eatWhile(/[^,]/);
+        if(state.extenInclude) {
+          stream.skipToEnd();
+          state.extenPriority = false;
+          state.extenInclude = false;
+        }
+        if(state.extenSame) {
+          state.extenPriority = false;
+          state.extenSame = false;
+          state.extenApplication = true;
+        }
+        return "tag";
+      } else if(state.extenPriority) {
+        state.extenPriority = false;
+        state.extenApplication = true;
+        ch = stream.next(); // get comma
+        if(state.extenSame) return null;
+        stream.eatWhile(/[^,]/);
+        return "number";
+      } else if(state.extenApplication) {
+        stream.eatWhile(/,/);
+        cur = stream.current();
+        if(cur === ',') return null;
+        stream.eatWhile(/\w/);
+        cur = stream.current().toLowerCase();
+        state.extenApplication = false;
+        if(apps.indexOf(cur) !== -1){
+          return "def strong";
+        }
+      } else{
+        return basicToken(stream,state);
+      }
+
+      return null;
+    }
+  };
+});
+
+CodeMirror.defineMIME("text/x-asterisk", "asterisk");
diff --git a/third-party/codemirror-3.15/mode/asterisk/index.html b/third-party/codemirror-3.15/mode/asterisk/index.html
new file mode 100644 (file)
index 0000000..0a796a0
--- /dev/null
@@ -0,0 +1,142 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Asterisk dialplan mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="asterisk.js"></script>
+    <style>
+      .CodeMirror {border: 1px solid #999;}
+      .cm-s-default span.cm-arrow { color: red; }
+    </style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Asterisk dialplan mode</h1>
+    <form><textarea id="code" name="code">
+; extensions.conf - the Asterisk dial plan
+;
+
+[general]
+;
+; If static is set to no, or omitted, then the pbx_config will rewrite
+; this file when extensions are modified.  Remember that all comments
+; made in the file will be lost when that happens.
+static=yes
+
+#include "/etc/asterisk/additional_general.conf
+
+[iaxprovider]
+switch => IAX2/user:[key]@myserver/mycontext
+
+[dynamic]
+#exec /usr/bin/dynamic-peers.pl
+
+[trunkint]
+;
+; International long distance through trunk
+;
+exten => _9011.,1,Macro(dundi-e164,${EXTEN:4})
+exten => _9011.,n,Dial(${GLOBAL(TRUNK)}/${FILTER(0-9,${EXTEN:${GLOBAL(TRUNKMSD)}})})
+
+[local]
+;
+; Master context for local, toll-free, and iaxtel calls only
+;
+ignorepat => 9
+include => default
+
+[demo]
+include => stdexten
+;
+; We start with what to do when a call first comes in.
+;
+exten => s,1,Wait(1)                   ; Wait a second, just for fun
+same  => n,Answer                      ; Answer the line
+same  => n,Set(TIMEOUT(digit)=5)       ; Set Digit Timeout to 5 seconds
+same  => n,Set(TIMEOUT(response)=10)   ; Set Response Timeout to 10 seconds
+same  => n(restart),BackGround(demo-congrats)  ; Play a congratulatory message
+same  => n(instruct),BackGround(demo-instruct) ; Play some instructions
+same  => n,WaitExten                   ; Wait for an extension to be dialed.
+
+exten => 2,1,BackGround(demo-moreinfo) ; Give some more information.
+exten => 2,n,Goto(s,instruct)
+
+exten => 3,1,Set(LANGUAGE()=fr)                ; Set language to french
+exten => 3,n,Goto(s,restart)           ; Start with the congratulations
+
+exten => 1000,1,Goto(default,s,1)
+;
+; We also create an example user, 1234, who is on the console and has
+; voicemail, etc.
+;
+exten => 1234,1,Playback(transfer,skip)                ; "Please hold while..."
+                                       ; (but skip if channel is not up)
+exten => 1234,n,Gosub(${EXTEN},stdexten(${GLOBAL(CONSOLE)}))
+exten => 1234,n,Goto(default,s,1)              ; exited Voicemail
+
+exten => 1235,1,Voicemail(1234,u)              ; Right to voicemail
+
+exten => 1236,1,Dial(Console/dsp)              ; Ring forever
+exten => 1236,n,Voicemail(1234,b)              ; Unless busy
+
+;
+; # for when they're done with the demo
+;
+exten => #,1,Playback(demo-thanks)     ; "Thanks for trying the demo"
+exten => #,n,Hangup                    ; Hang them up.
+
+;
+; A timeout and "invalid extension rule"
+;
+exten => t,1,Goto(#,1)                 ; If they take too long, give up
+exten => i,1,Playback(invalid)         ; "That's not valid, try again"
+
+;
+; Create an extension, 500, for dialing the
+; Asterisk demo.
+;
+exten => 500,1,Playback(demo-abouttotry); Let them know what's going on
+exten => 500,n,Dial(IAX2/guest@pbx.digium.com/s@default)       ; Call the Asterisk demo
+exten => 500,n,Playback(demo-nogo)     ; Couldn't connect to the demo site
+exten => 500,n,Goto(s,6)               ; Return to the start over message.
+
+;
+; Create an extension, 600, for evaluating echo latency.
+;
+exten => 600,1,Playback(demo-echotest) ; Let them know what's going on
+exten => 600,n,Echo                    ; Do the echo test
+exten => 600,n,Playback(demo-echodone) ; Let them know it's over
+exten => 600,n,Goto(s,6)               ; Start over
+
+;
+;      You can use the Macro Page to intercom a individual user
+exten => 76245,1,Macro(page,SIP/Grandstream1)
+; or if your peernames are the same as extensions
+exten => _7XXX,1,Macro(page,SIP/${EXTEN})
+;
+;
+; System Wide Page at extension 7999
+;
+exten => 7999,1,Set(TIMEOUT(absolute)=60)
+exten => 7999,2,Page(Local/Grandstream1@page&Local/Xlite1@page&Local/1234@page/n,d)
+
+; Give voicemail at extension 8500
+;
+exten => 8500,1,VoicemailMain
+exten => 8500,n,Goto(s,6)
+
+    </textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        mode: "text/x-asterisk",
+        matchBrackets: true,
+        lineNumber: true
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-asterisk</code>.</p>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/clike/clike.js b/third-party/codemirror-3.15/mode/clike/clike.js
new file mode 100644 (file)
index 0000000..f6626cd
--- /dev/null
@@ -0,0 +1,362 @@
+CodeMirror.defineMode("clike", function(config, parserConfig) {
+  var indentUnit = config.indentUnit,
+      statementIndentUnit = parserConfig.statementIndentUnit || indentUnit,
+      dontAlignCalls = parserConfig.dontAlignCalls,
+      keywords = parserConfig.keywords || {},
+      builtin = parserConfig.builtin || {},
+      blockKeywords = parserConfig.blockKeywords || {},
+      atoms = parserConfig.atoms || {},
+      hooks = parserConfig.hooks || {},
+      multiLineStrings = parserConfig.multiLineStrings;
+  var isOperatorChar = /[+\-*&%=<>!?|\/]/;
+
+  var curPunc;
+
+  function tokenBase(stream, state) {
+    var ch = stream.next();
+    if (hooks[ch]) {
+      var result = hooks[ch](stream, state);
+      if (result !== false) return result;
+    }
+    if (ch == '"' || ch == "'") {
+      state.tokenize = tokenString(ch);
+      return state.tokenize(stream, state);
+    }
+    if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
+      curPunc = ch;
+      return null;
+    }
+    if (/\d/.test(ch)) {
+      stream.eatWhile(/[\w\.]/);
+      return "number";
+    }
+    if (ch == "/") {
+      if (stream.eat("*")) {
+        state.tokenize = tokenComment;
+        return tokenComment(stream, state);
+      }
+      if (stream.eat("/")) {
+        stream.skipToEnd();
+        return "comment";
+      }
+    }
+    if (isOperatorChar.test(ch)) {
+      stream.eatWhile(isOperatorChar);
+      return "operator";
+    }
+    stream.eatWhile(/[\w\$_]/);
+    var cur = stream.current();
+    if (keywords.propertyIsEnumerable(cur)) {
+      if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
+      return "keyword";
+    }
+    if (builtin.propertyIsEnumerable(cur)) {
+      if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
+      return "builtin";
+    }
+    if (atoms.propertyIsEnumerable(cur)) return "atom";
+    return "variable";
+  }
+
+  function tokenString(quote) {
+    return function(stream, state) {
+      var escaped = false, next, end = false;
+      while ((next = stream.next()) != null) {
+        if (next == quote && !escaped) {end = true; break;}
+        escaped = !escaped && next == "\\";
+      }
+      if (end || !(escaped || multiLineStrings))
+        state.tokenize = null;
+      return "string";
+    };
+  }
+
+  function tokenComment(stream, state) {
+    var maybeEnd = false, ch;
+    while (ch = stream.next()) {
+      if (ch == "/" && maybeEnd) {
+        state.tokenize = null;
+        break;
+      }
+      maybeEnd = (ch == "*");
+    }
+    return "comment";
+  }
+
+  function Context(indented, column, type, align, prev) {
+    this.indented = indented;
+    this.column = column;
+    this.type = type;
+    this.align = align;
+    this.prev = prev;
+  }
+  function pushContext(state, col, type) {
+    var indent = state.indented;
+    if (state.context && state.context.type == "statement")
+      indent = state.context.indented;
+    return state.context = new Context(indent, col, type, null, state.context);
+  }
+  function popContext(state) {
+    var t = state.context.type;
+    if (t == ")" || t == "]" || t == "}")
+      state.indented = state.context.indented;
+    return state.context = state.context.prev;
+  }
+
+  // Interface
+
+  return {
+    startState: function(basecolumn) {
+      return {
+        tokenize: null,
+        context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
+        indented: 0,
+        startOfLine: true
+      };
+    },
+
+    token: function(stream, state) {
+      var ctx = state.context;
+      if (stream.sol()) {
+        if (ctx.align == null) ctx.align = false;
+        state.indented = stream.indentation();
+        state.startOfLine = true;
+      }
+      if (stream.eatSpace()) return null;
+      curPunc = null;
+      var style = (state.tokenize || tokenBase)(stream, state);
+      if (style == "comment" || style == "meta") return style;
+      if (ctx.align == null) ctx.align = true;
+
+      if ((curPunc == ";" || curPunc == ":" || curPunc == ",") && ctx.type == "statement") popContext(state);
+      else if (curPunc == "{") pushContext(state, stream.column(), "}");
+      else if (curPunc == "[") pushContext(state, stream.column(), "]");
+      else if (curPunc == "(") pushContext(state, stream.column(), ")");
+      else if (curPunc == "}") {
+        while (ctx.type == "statement") ctx = popContext(state);
+        if (ctx.type == "}") ctx = popContext(state);
+        while (ctx.type == "statement") ctx = popContext(state);
+      }
+      else if (curPunc == ctx.type) popContext(state);
+      else if (((ctx.type == "}" || ctx.type == "top") && curPunc != ';') || (ctx.type == "statement" && curPunc == "newstatement"))
+        pushContext(state, stream.column(), "statement");
+      state.startOfLine = false;
+      return style;
+    },
+
+    indent: function(state, textAfter) {
+      if (state.tokenize != tokenBase && state.tokenize != null) return CodeMirror.Pass;
+      var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
+      if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev;
+      var closing = firstChar == ctx.type;
+      if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit);
+      else if (ctx.align && (!dontAlignCalls || ctx.type != ")")) return ctx.column + (closing ? 0 : 1);
+      else if (ctx.type == ")" && !closing) return ctx.indented + statementIndentUnit;
+      else return ctx.indented + (closing ? 0 : indentUnit);
+    },
+
+    electricChars: "{}",
+    blockCommentStart: "/*",
+    blockCommentEnd: "*/",
+    lineComment: "//",
+    fold: "brace"
+  };
+});
+
+(function() {
+  function words(str) {
+    var obj = {}, words = str.split(" ");
+    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
+    return obj;
+  }
+  var cKeywords = "auto if break int case long char register continue return default short do sizeof " +
+    "double static else struct entry switch extern typedef float union for unsigned " +
+    "goto while enum void const signed volatile";
+
+  function cppHook(stream, state) {
+    if (!state.startOfLine) return false;
+    for (;;) {
+      if (stream.skipTo("\\")) {
+        stream.next();
+        if (stream.eol()) {
+          state.tokenize = cppHook;
+          break;
+        }
+      } else {
+        stream.skipToEnd();
+        state.tokenize = null;
+        break;
+      }
+    }
+    return "meta";
+  }
+
+  // C#-style strings where "" escapes a quote.
+  function tokenAtString(stream, state) {
+    var next;
+    while ((next = stream.next()) != null) {
+      if (next == '"' && !stream.eat('"')) {
+        state.tokenize = null;
+        break;
+      }
+    }
+    return "string";
+  }
+
+  function mimes(ms, mode) {
+    for (var i = 0; i < ms.length; ++i) CodeMirror.defineMIME(ms[i], mode);
+  }
+
+  mimes(["text/x-csrc", "text/x-c", "text/x-chdr"], {
+    name: "clike",
+    keywords: words(cKeywords),
+    blockKeywords: words("case do else for if switch while struct"),
+    atoms: words("null"),
+    hooks: {"#": cppHook}
+  });
+  mimes(["text/x-c++src", "text/x-c++hdr"], {
+    name: "clike",
+    keywords: words(cKeywords + " asm dynamic_cast namespace reinterpret_cast try bool explicit new " +
+                    "static_cast typeid catch operator template typename class friend private " +
+                    "this using const_cast inline public throw virtual delete mutable protected " +
+                    "wchar_t"),
+    blockKeywords: words("catch class do else finally for if struct switch try while"),
+    atoms: words("true false null"),
+    hooks: {"#": cppHook}
+  });
+  CodeMirror.defineMIME("text/x-java", {
+    name: "clike",
+    keywords: words("abstract assert boolean break byte case catch char class const continue default " +
+                    "do double else enum extends final finally float for goto if implements import " +
+                    "instanceof int interface long native new package private protected public " +
+                    "return short static strictfp super switch synchronized this throw throws transient " +
+                    "try void volatile while"),
+    blockKeywords: words("catch class do else finally for if switch try while"),
+    atoms: words("true false null"),
+    hooks: {
+      "@": function(stream) {
+        stream.eatWhile(/[\w\$_]/);
+        return "meta";
+      }
+    }
+  });
+  CodeMirror.defineMIME("text/x-csharp", {
+    name: "clike",
+    keywords: words("abstract as base break case catch checked class const continue" +
+                    " default delegate do else enum event explicit extern finally fixed for" +
+                    " foreach goto if implicit in interface internal is lock namespace new" +
+                    " operator out override params private protected public readonly ref return sealed" +
+                    " sizeof stackalloc static struct switch this throw try typeof unchecked" +
+                    " unsafe using virtual void volatile while add alias ascending descending dynamic from get" +
+                    " global group into join let orderby partial remove select set value var yield"),
+    blockKeywords: words("catch class do else finally for foreach if struct switch try while"),
+    builtin: words("Boolean Byte Char DateTime DateTimeOffset Decimal Double" +
+                    " Guid Int16 Int32 Int64 Object SByte Single String TimeSpan UInt16 UInt32" +
+                    " UInt64 bool byte char decimal double short int long object"  +
+                    " sbyte float string ushort uint ulong"),
+    atoms: words("true false null"),
+    hooks: {
+      "@": function(stream, state) {
+        if (stream.eat('"')) {
+          state.tokenize = tokenAtString;
+          return tokenAtString(stream, state);
+        }
+        stream.eatWhile(/[\w\$_]/);
+        return "meta";
+      }
+    }
+  });
+  CodeMirror.defineMIME("text/x-scala", {
+    name: "clike",
+    keywords: words(
+
+      /* scala */
+      "abstract case catch class def do else extends false final finally for forSome if " +
+      "implicit import lazy match new null object override package private protected return " +
+      "sealed super this throw trait try trye type val var while with yield _ : = => <- <: " +
+      "<% >: # @ " +
+
+      /* package scala */
+      "assert assume require print println printf readLine readBoolean readByte readShort " +
+      "readChar readInt readLong readFloat readDouble " +
+
+      "AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either " +
+      "Enumeration Equiv Error Exception Fractional Function IndexedSeq Integral Iterable " +
+      "Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering " +
+      "Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder " +
+      "StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector :: #:: " +
+
+      /* package java.lang */
+      "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " +
+      "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " +
+      "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " +
+      "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void"
+
+
+    ),
+    blockKeywords: words("catch class do else finally for forSome if match switch try while"),
+    atoms: words("true false null"),
+    hooks: {
+      "@": function(stream) {
+        stream.eatWhile(/[\w\$_]/);
+        return "meta";
+      }
+    }
+  });
+  mimes(["x-shader/x-vertex", "x-shader/x-fragment"], {
+    name: "clike",
+    keywords: words("float int bool void " +
+                    "vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 " +
+                    "mat2 mat3 mat4 " +
+                    "sampler1D sampler2D sampler3D samplerCube " +
+                    "sampler1DShadow sampler2DShadow" +
+                    "const attribute uniform varying " +
+                    "break continue discard return " +
+                    "for while do if else struct " +
+                    "in out inout"),
+    blockKeywords: words("for while do if else struct"),
+    builtin: words("radians degrees sin cos tan asin acos atan " +
+                    "pow exp log exp2 sqrt inversesqrt " +
+                    "abs sign floor ceil fract mod min max clamp mix step smootstep " +
+                    "length distance dot cross normalize ftransform faceforward " +
+                    "reflect refract matrixCompMult " +
+                    "lessThan lessThanEqual greaterThan greaterThanEqual " +
+                    "equal notEqual any all not " +
+                    "texture1D texture1DProj texture1DLod texture1DProjLod " +
+                    "texture2D texture2DProj texture2DLod texture2DProjLod " +
+                    "texture3D texture3DProj texture3DLod texture3DProjLod " +
+                    "textureCube textureCubeLod " +
+                    "shadow1D shadow2D shadow1DProj shadow2DProj " +
+                    "shadow1DLod shadow2DLod shadow1DProjLod shadow2DProjLod " +
+                    "dFdx dFdy fwidth " +
+                    "noise1 noise2 noise3 noise4"),
+    atoms: words("true false " +
+                "gl_FragColor gl_SecondaryColor gl_Normal gl_Vertex " +
+                "gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 gl_MultiTexCoord3 " +
+                "gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 " +
+                "gl_FogCoord " +
+                "gl_Position gl_PointSize gl_ClipVertex " +
+                "gl_FrontColor gl_BackColor gl_FrontSecondaryColor gl_BackSecondaryColor " +
+                "gl_TexCoord gl_FogFragCoord " +
+                "gl_FragCoord gl_FrontFacing " +
+                "gl_FragColor gl_FragData gl_FragDepth " +
+                "gl_ModelViewMatrix gl_ProjectionMatrix gl_ModelViewProjectionMatrix " +
+                "gl_TextureMatrix gl_NormalMatrix gl_ModelViewMatrixInverse " +
+                "gl_ProjectionMatrixInverse gl_ModelViewProjectionMatrixInverse " +
+                "gl_TexureMatrixTranspose gl_ModelViewMatrixInverseTranspose " +
+                "gl_ProjectionMatrixInverseTranspose " +
+                "gl_ModelViewProjectionMatrixInverseTranspose " +
+                "gl_TextureMatrixInverseTranspose " +
+                "gl_NormalScale gl_DepthRange gl_ClipPlane " +
+                "gl_Point gl_FrontMaterial gl_BackMaterial gl_LightSource gl_LightModel " +
+                "gl_FrontLightModelProduct gl_BackLightModelProduct " +
+                "gl_TextureColor gl_EyePlaneS gl_EyePlaneT gl_EyePlaneR gl_EyePlaneQ " +
+                "gl_FogParameters " +
+                "gl_MaxLights gl_MaxClipPlanes gl_MaxTextureUnits gl_MaxTextureCoords " +
+                "gl_MaxVertexAttribs gl_MaxVertexUniformComponents gl_MaxVaryingFloats " +
+                "gl_MaxVertexTextureImageUnits gl_MaxTextureImageUnits " +
+                "gl_MaxFragmentUniformComponents gl_MaxCombineTextureImageUnits " +
+                "gl_MaxDrawBuffers"),
+    hooks: {"#": cppHook}
+  });
+}());
diff --git a/third-party/codemirror-3.15/mode/clike/index.html b/third-party/codemirror-3.15/mode/clike/index.html
new file mode 100644 (file)
index 0000000..5f90394
--- /dev/null
@@ -0,0 +1,103 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: C-like mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../../addon/edit/matchbrackets.js"></script>
+    <script src="clike.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style>.CodeMirror {border: 2px inset #dee;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: C-like mode</h1>
+
+<form><textarea id="code" name="code">
+/* C demo code */
+
+#include <zmq.h>
+#include <pthread.h>
+#include <semaphore.h>
+#include <time.h>
+#include <stdio.h>
+#include <fcntl.h>
+#include <malloc.h>
+
+typedef struct {
+  void* arg_socket;
+  zmq_msg_t* arg_msg;
+  char* arg_string;
+  unsigned long arg_len;
+  int arg_int, arg_command;
+
+  int signal_fd;
+  int pad;
+  void* context;
+  sem_t sem;
+} acl_zmq_context;
+
+#define p(X) (context->arg_##X)
+
+void* zmq_thread(void* context_pointer) {
+  acl_zmq_context* context = (acl_zmq_context*)context_pointer;
+  char ok = 'K', err = 'X';
+  int res;
+
+  while (1) {
+    while ((res = sem_wait(&amp;context->sem)) == EINTR);
+    if (res) {write(context->signal_fd, &amp;err, 1); goto cleanup;}
+    switch(p(command)) {
+    case 0: goto cleanup;
+    case 1: p(socket) = zmq_socket(context->context, p(int)); break;
+    case 2: p(int) = zmq_close(p(socket)); break;
+    case 3: p(int) = zmq_bind(p(socket), p(string)); break;
+    case 4: p(int) = zmq_connect(p(socket), p(string)); break;
+    case 5: p(int) = zmq_getsockopt(p(socket), p(int), (void*)p(string), &amp;p(len)); break;
+    case 6: p(int) = zmq_setsockopt(p(socket), p(int), (void*)p(string), p(len)); break;
+    case 7: p(int) = zmq_send(p(socket), p(msg), p(int)); break;
+    case 8: p(int) = zmq_recv(p(socket), p(msg), p(int)); break;
+    case 9: p(int) = zmq_poll(p(socket), p(int), p(len)); break;
+    }
+    p(command) = errno;
+    write(context->signal_fd, &amp;ok, 1);
+  }
+ cleanup:
+  close(context->signal_fd);
+  free(context_pointer);
+  return 0;
+}
+
+void* zmq_thread_init(void* zmq_context, int signal_fd) {
+  acl_zmq_context* context = malloc(sizeof(acl_zmq_context));
+  pthread_t thread;
+
+  context->context = zmq_context;
+  context->signal_fd = signal_fd;
+  sem_init(&amp;context->sem, 1, 0);
+  pthread_create(&amp;thread, 0, &amp;zmq_thread, context);
+  pthread_detach(thread);
+  return context;
+}
+</textarea></form>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        matchBrackets: true,
+        mode: "text/x-csrc"
+      });
+    </script>
+
+    <p>Simple mode that tries to handle C-like languages as well as it
+    can. Takes two configuration parameters: <code>keywords</code>, an
+    object whose property names are the keywords in the language,
+    and <code>useCPP</code>, which determines whether C preprocessor
+    directives are recognized.</p>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-csrc</code>
+    (C code), <code>text/x-c++src</code> (C++
+    code), <code>text/x-java</code> (Java
+    code), <code>text/x-csharp</code> (C#).</p>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/clike/scala.html b/third-party/codemirror-3.15/mode/clike/scala.html
new file mode 100644 (file)
index 0000000..f3c7eea
--- /dev/null
@@ -0,0 +1,767 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: C-like mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <link rel="stylesheet" href="../../theme/ambiance.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../../addon/edit/matchbrackets.js"></script>
+    <script src="clike.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style>
+      body
+      {
+        margin: 0;
+        padding: 0;
+        max-width:inherit;
+        height: 100%;
+      }
+      html, form, .CodeMirror, .CodeMirror-scroll
+      {
+        height: 100%;        
+      }
+    </style>
+  </head>
+  <body>
+<form>
+<textarea id="code" name="code">
+
+  /*                     __                                               *\
+  **     ________ ___   / /  ___     Scala API                            **
+  **    / __/ __// _ | / /  / _ |    (c) 2003-2011, LAMP/EPFL             **
+  **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+  ** /____/\___/_/ |_/____/_/ | |                                         **
+  **                          |/                                          **
+  \*                                                                      */
+
+  package scala.collection
+
+  import generic._
+  import mutable.{ Builder, ListBuffer }
+  import annotation.{tailrec, migration, bridge}
+  import annotation.unchecked.{ uncheckedVariance => uV }
+  import parallel.ParIterable
+
+  /** A template trait for traversable collections of type `Traversable[A]`.
+   *  
+   *  $traversableInfo
+   *  @define mutability
+   *  @define traversableInfo
+   *  This is a base trait of all kinds of $mutability Scala collections. It
+   *  implements the behavior common to all collections, in terms of a method
+   *  `foreach` with signature:
+   * {{{
+   *     def foreach[U](f: Elem => U): Unit
+   * }}}
+   *  Collection classes mixing in this trait provide a concrete 
+   *  `foreach` method which traverses all the
+   *  elements contained in the collection, applying a given function to each.
+   *  They also need to provide a method `newBuilder`
+   *  which creates a builder for collections of the same kind.
+   *  
+   *  A traversable class might or might not have two properties: strictness
+   *  and orderedness. Neither is represented as a type.
+   *  
+   *  The instances of a strict collection class have all their elements
+   *  computed before they can be used as values. By contrast, instances of
+   *  a non-strict collection class may defer computation of some of their
+   *  elements until after the instance is available as a value.
+   *  A typical example of a non-strict collection class is a
+   *  <a href="../immutable/Stream.html" target="ContentFrame">
+   *  `scala.collection.immutable.Stream`</a>.
+   *  A more general class of examples are `TraversableViews`.
+   *  
+   *  If a collection is an instance of an ordered collection class, traversing
+   *  its elements with `foreach` will always visit elements in the
+   *  same order, even for different runs of the program. If the class is not
+   *  ordered, `foreach` can visit elements in different orders for
+   *  different runs (but it will keep the same order in the same run).'
+   * 
+   *  A typical example of a collection class which is not ordered is a
+   *  `HashMap` of objects. The traversal order for hash maps will
+   *  depend on the hash codes of its elements, and these hash codes might
+   *  differ from one run to the next. By contrast, a `LinkedHashMap`
+   *  is ordered because it's `foreach` method visits elements in the
+   *  order they were inserted into the `HashMap`.
+   *
+   *  @author Martin Odersky
+   *  @version 2.8
+   *  @since   2.8
+   *  @tparam A    the element type of the collection
+   *  @tparam Repr the type of the actual collection containing the elements.
+   *
+   *  @define Coll Traversable
+   *  @define coll traversable collection
+   */
+  trait TraversableLike[+A, +Repr] extends HasNewBuilder[A, Repr] 
+                                      with FilterMonadic[A, Repr]
+                                      with TraversableOnce[A]
+                                      with GenTraversableLike[A, Repr]
+                                      with Parallelizable[A, ParIterable[A]]
+  {
+    self =>
+
+    import Traversable.breaks._
+
+    /** The type implementing this traversable */
+    protected type Self = Repr
+
+    /** The collection of type $coll underlying this `TraversableLike` object.
+     *  By default this is implemented as the `TraversableLike` object itself,
+     *  but this can be overridden.
+     */
+    def repr: Repr = this.asInstanceOf[Repr]
+
+    /** The underlying collection seen as an instance of `$Coll`.
+     *  By default this is implemented as the current collection object itself,
+     *  but this can be overridden.
+     */
+    protected[this] def thisCollection: Traversable[A] = this.asInstanceOf[Traversable[A]]
+
+    /** A conversion from collections of type `Repr` to `$Coll` objects.
+     *  By default this is implemented as just a cast, but this can be overridden.
+     */
+    protected[this] def toCollection(repr: Repr): Traversable[A] = repr.asInstanceOf[Traversable[A]]
+
+    /** Creates a new builder for this collection type.
+     */
+    protected[this] def newBuilder: Builder[A, Repr]
+
+    protected[this] def parCombiner = ParIterable.newCombiner[A]
+
+    /** Applies a function `f` to all elements of this $coll.
+     *  
+     *    Note: this method underlies the implementation of most other bulk operations.
+     *    It's important to implement this method in an efficient way.
+     *  
+     *
+     *  @param  f   the function that is applied for its side-effect to every element.
+     *              The result of function `f` is discarded.
+     *              
+     *  @tparam  U  the type parameter describing the result of function `f`. 
+     *              This result will always be ignored. Typically `U` is `Unit`,
+     *              but this is not necessary.
+     *
+     *  @usecase def foreach(f: A => Unit): Unit
+     */
+    def foreach[U](f: A => U): Unit
+
+    /** Tests whether this $coll is empty.
+     *
+     *  @return    `true` if the $coll contain no elements, `false` otherwise.
+     */
+    def isEmpty: Boolean = {
+      var result = true
+      breakable {
+        for (x <- this) {
+          result = false
+          break
+        }
+      }
+      result
+    }
+
+    /** Tests whether this $coll is known to have a finite size.
+     *  All strict collections are known to have finite size. For a non-strict collection
+     *  such as `Stream`, the predicate returns `true` if all elements have been computed.
+     *  It returns `false` if the stream is not yet evaluated to the end.
+     *
+     *  Note: many collection methods will not work on collections of infinite sizes. 
+     *
+     *  @return  `true` if this collection is known to have finite size, `false` otherwise.
+     */
+    def hasDefiniteSize = true
+
+    def ++[B >: A, That](that: GenTraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+      val b = bf(repr)
+      if (that.isInstanceOf[IndexedSeqLike[_, _]]) b.sizeHint(this, that.seq.size)
+      b ++= thisCollection
+      b ++= that.seq
+      b.result
+    }
+
+    @bridge
+    def ++[B >: A, That](that: TraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That =
+      ++(that: GenTraversableOnce[B])(bf)
+
+    /** Concatenates this $coll with the elements of a traversable collection.
+     *  It differs from ++ in that the right operand determines the type of the
+     *  resulting collection rather than the left one.
+     * 
+     *  @param that   the traversable to append.
+     *  @tparam B     the element type of the returned collection. 
+     *  @tparam That  $thatinfo
+     *  @param bf     $bfinfo
+     *  @return       a new collection of type `That` which contains all elements
+     *                of this $coll followed by all elements of `that`.
+     * 
+     *  @usecase def ++:[B](that: TraversableOnce[B]): $Coll[B]
+     *  
+     *  @return       a new $coll which contains all elements of this $coll
+     *                followed by all elements of `that`.
+     */
+    def ++:[B >: A, That](that: TraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+      val b = bf(repr)
+      if (that.isInstanceOf[IndexedSeqLike[_, _]]) b.sizeHint(this, that.size)
+      b ++= that
+      b ++= thisCollection
+      b.result
+    }
+
+    /** This overload exists because: for the implementation of ++: we should reuse
+     *  that of ++ because many collections override it with more efficient versions.
+     *  Since TraversableOnce has no '++' method, we have to implement that directly,
+     *  but Traversable and down can use the overload.
+     */
+    def ++:[B >: A, That](that: Traversable[B])(implicit bf: CanBuildFrom[Repr, B, That]): That =
+      (that ++ seq)(breakOut)
+
+    def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+      val b = bf(repr)
+      b.sizeHint(this) 
+      for (x <- this) b += f(x)
+      b.result
+    }
+
+    def flatMap[B, That](f: A => GenTraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+      val b = bf(repr)
+      for (x <- this) b ++= f(x).seq
+      b.result
+    }
+
+    /** Selects all elements of this $coll which satisfy a predicate.
+     *
+     *  @param p     the predicate used to test elements.
+     *  @return      a new $coll consisting of all elements of this $coll that satisfy the given
+     *               predicate `p`. The order of the elements is preserved.
+     */
+    def filter(p: A => Boolean): Repr = {
+      val b = newBuilder
+      for (x <- this) 
+        if (p(x)) b += x
+      b.result
+    }
+
+    /** Selects all elements of this $coll which do not satisfy a predicate.
+     *
+     *  @param p     the predicate used to test elements.
+     *  @return      a new $coll consisting of all elements of this $coll that do not satisfy the given
+     *               predicate `p`. The order of the elements is preserved.
+     */
+    def filterNot(p: A => Boolean): Repr = filter(!p(_))
+
+    def collect[B, That](pf: PartialFunction[A, B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+      val b = bf(repr)
+      for (x <- this) if (pf.isDefinedAt(x)) b += pf(x)
+      b.result
+    }
+
+    /** Builds a new collection by applying an option-valued function to all
+     *  elements of this $coll on which the function is defined.
+     *
+     *  @param f      the option-valued function which filters and maps the $coll.
+     *  @tparam B     the element type of the returned collection.
+     *  @tparam That  $thatinfo
+     *  @param bf     $bfinfo
+     *  @return       a new collection of type `That` resulting from applying the option-valued function
+     *                `f` to each element and collecting all defined results.
+     *                The order of the elements is preserved.
+     *
+     *  @usecase def filterMap[B](f: A => Option[B]): $Coll[B]
+     *  
+     *  @param pf     the partial function which filters and maps the $coll.
+     *  @return       a new $coll resulting from applying the given option-valued function
+     *                `f` to each element and collecting all defined results.
+     *                The order of the elements is preserved.
+    def filterMap[B, That](f: A => Option[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+      val b = bf(repr)
+      for (x <- this) 
+        f(x) match {
+          case Some(y) => b += y
+          case _ =>
+        }
+      b.result
+    }
+     */
+
+    /** Partitions this $coll in two ${coll}s according to a predicate.
+     *
+     *  @param p the predicate on which to partition.
+     *  @return  a pair of ${coll}s: the first $coll consists of all elements that 
+     *           satisfy the predicate `p` and the second $coll consists of all elements
+     *           that don't. The relative order of the elements in the resulting ${coll}s
+     *           is the same as in the original $coll.
+     */
+    def partition(p: A => Boolean): (Repr, Repr) = {
+      val l, r = newBuilder
+      for (x <- this) (if (p(x)) l else r) += x
+      (l.result, r.result)
+    }
+
+    def groupBy[K](f: A => K): immutable.Map[K, Repr] = {
+      val m = mutable.Map.empty[K, Builder[A, Repr]]
+      for (elem <- this) {
+        val key = f(elem)
+        val bldr = m.getOrElseUpdate(key, newBuilder)
+        bldr += elem
+      }
+      val b = immutable.Map.newBuilder[K, Repr]
+      for ((k, v) <- m)
+        b += ((k, v.result))
+
+      b.result
+    }
+
+    /** Tests whether a predicate holds for all elements of this $coll.
+     *
+     *  $mayNotTerminateInf
+     *
+     *  @param   p     the predicate used to test elements.
+     *  @return        `true` if the given predicate `p` holds for all elements
+     *                 of this $coll, otherwise `false`.
+     */
+    def forall(p: A => Boolean): Boolean = {
+      var result = true
+      breakable {
+        for (x <- this)
+          if (!p(x)) { result = false; break }
+      }
+      result
+    }
+
+    /** Tests whether a predicate holds for some of the elements of this $coll.
+     *
+     *  $mayNotTerminateInf
+     *
+     *  @param   p     the predicate used to test elements.
+     *  @return        `true` if the given predicate `p` holds for some of the
+     *                 elements of this $coll, otherwise `false`.
+     */
+    def exists(p: A => Boolean): Boolean = {
+      var result = false
+      breakable {
+        for (x <- this)
+          if (p(x)) { result = true; break }
+      }
+      result
+    }
+
+    /** Finds the first element of the $coll satisfying a predicate, if any.
+     * 
+     *  $mayNotTerminateInf
+     *  $orderDependent
+     *
+     *  @param p    the predicate used to test elements.
+     *  @return     an option value containing the first element in the $coll
+     *              that satisfies `p`, or `None` if none exists.
+     */
+    def find(p: A => Boolean): Option[A] = {
+      var result: Option[A] = None
+      breakable {
+        for (x <- this)
+          if (p(x)) { result = Some(x); break }
+      }
+      result
+    }
+
+    def scan[B >: A, That](z: B)(op: (B, B) => B)(implicit cbf: CanBuildFrom[Repr, B, That]): That = scanLeft(z)(op)
+
+    def scanLeft[B, That](z: B)(op: (B, A) => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+      val b = bf(repr)
+      b.sizeHint(this, 1)
+      var acc = z
+      b += acc
+      for (x <- this) { acc = op(acc, x); b += acc }
+      b.result
+    }
+
+    @migration(2, 9,
+      "This scanRight definition has changed in 2.9.\n" +
+      "The previous behavior can be reproduced with scanRight.reverse."
+    )
+    def scanRight[B, That](z: B)(op: (A, B) => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+      var scanned = List(z)
+      var acc = z
+      for (x <- reversed) {
+        acc = op(x, acc)
+        scanned ::= acc
+      }
+      val b = bf(repr)
+      for (elem <- scanned) b += elem
+      b.result
+    }
+
+    /** Selects the first element of this $coll.
+     *  $orderDependent
+     *  @return  the first element of this $coll.
+     *  @throws `NoSuchElementException` if the $coll is empty.
+     */
+    def head: A = {
+      var result: () => A = () => throw new NoSuchElementException
+      breakable {
+        for (x <- this) {
+          result = () => x
+          break
+        }
+      }
+      result()
+    }
+
+    /** Optionally selects the first element.
+     *  $orderDependent
+     *  @return  the first element of this $coll if it is nonempty, `None` if it is empty.
+     */
+    def headOption: Option[A] = if (isEmpty) None else Some(head)
+
+    /** Selects all elements except the first.
+     *  $orderDependent
+     *  @return  a $coll consisting of all elements of this $coll
+     *           except the first one.
+     *  @throws `UnsupportedOperationException` if the $coll is empty.
+     */ 
+    override def tail: Repr = {
+      if (isEmpty) throw new UnsupportedOperationException("empty.tail")
+      drop(1)
+    }
+
+    /** Selects the last element.
+      * $orderDependent
+      * @return The last element of this $coll.
+      * @throws NoSuchElementException If the $coll is empty.
+      */
+    def last: A = {
+      var lst = head
+      for (x <- this)
+        lst = x
+      lst
+    }
+
+    /** Optionally selects the last element.
+     *  $orderDependent
+     *  @return  the last element of this $coll$ if it is nonempty, `None` if it is empty.
+     */
+    def lastOption: Option[A] = if (isEmpty) None else Some(last)
+
+    /** Selects all elements except the last.
+     *  $orderDependent
+     *  @return  a $coll consisting of all elements of this $coll
+     *           except the last one.
+     *  @throws `UnsupportedOperationException` if the $coll is empty.
+     */
+    def init: Repr = {
+      if (isEmpty) throw new UnsupportedOperationException("empty.init")
+      var lst = head
+      var follow = false
+      val b = newBuilder
+      b.sizeHint(this, -1)
+      for (x <- this.seq) {
+        if (follow) b += lst
+        else follow = true
+        lst = x
+      }
+      b.result
+    }
+
+    def take(n: Int): Repr = slice(0, n)
+
+    def drop(n: Int): Repr = 
+      if (n <= 0) {
+        val b = newBuilder
+        b.sizeHint(this)
+        b ++= thisCollection result
+      }
+      else sliceWithKnownDelta(n, Int.MaxValue, -n)
+
+    def slice(from: Int, until: Int): Repr = sliceWithKnownBound(math.max(from, 0), until)
+
+    // Precondition: from >= 0, until > 0, builder already configured for building.
+    private[this] def sliceInternal(from: Int, until: Int, b: Builder[A, Repr]): Repr = {
+      var i = 0
+      breakable {
+        for (x <- this.seq) {
+          if (i >= from) b += x
+          i += 1
+          if (i >= until) break
+        }
+      }
+      b.result
+    }
+    // Precondition: from >= 0
+    private[scala] def sliceWithKnownDelta(from: Int, until: Int, delta: Int): Repr = {
+      val b = newBuilder
+      if (until <= from) b.result
+      else {
+        b.sizeHint(this, delta)
+        sliceInternal(from, until, b)
+      }
+    }
+    // Precondition: from >= 0
+    private[scala] def sliceWithKnownBound(from: Int, until: Int): Repr = {
+      val b = newBuilder
+      if (until <= from) b.result
+      else {
+        b.sizeHintBounded(until - from, this)      
+        sliceInternal(from, until, b)
+      }
+    }
+
+    def takeWhile(p: A => Boolean): Repr = {
+      val b = newBuilder
+      breakable {
+        for (x <- this) {
+          if (!p(x)) break
+          b += x
+        }
+      }
+      b.result
+    }
+
+    def dropWhile(p: A => Boolean): Repr = {
+      val b = newBuilder
+      var go = false
+      for (x <- this) {
+        if (!p(x)) go = true
+        if (go) b += x
+      }
+      b.result
+    }
+
+    def span(p: A => Boolean): (Repr, Repr) = {
+      val l, r = newBuilder
+      var toLeft = true
+      for (x <- this) {
+        toLeft = toLeft && p(x)
+        (if (toLeft) l else r) += x
+      }
+      (l.result, r.result)
+    }
+
+    def splitAt(n: Int): (Repr, Repr) = {
+      val l, r = newBuilder
+      l.sizeHintBounded(n, this)
+      if (n >= 0) r.sizeHint(this, -n)
+      var i = 0
+      for (x <- this) {
+        (if (i < n) l else r) += x
+        i += 1
+      }
+      (l.result, r.result)
+    }
+
+    /** Iterates over the tails of this $coll. The first value will be this
+     *  $coll and the final one will be an empty $coll, with the intervening
+     *  values the results of successive applications of `tail`.
+     *
+     *  @return   an iterator over all the tails of this $coll
+     *  @example  `List(1,2,3).tails = Iterator(List(1,2,3), List(2,3), List(3), Nil)`
+     */  
+    def tails: Iterator[Repr] = iterateUntilEmpty(_.tail)
+
+    /** Iterates over the inits of this $coll. The first value will be this
+     *  $coll and the final one will be an empty $coll, with the intervening
+     *  values the results of successive applications of `init`.
+     *
+     *  @return  an iterator over all the inits of this $coll
+     *  @example  `List(1,2,3).inits = Iterator(List(1,2,3), List(1,2), List(1), Nil)`
+     */
+    def inits: Iterator[Repr] = iterateUntilEmpty(_.init)
+
+    /** Copies elements of this $coll to an array.
+     *  Fills the given array `xs` with at most `len` elements of
+     *  this $coll, starting at position `start`.
+     *  Copying will stop once either the end of the current $coll is reached,
+     *  or the end of the array is reached, or `len` elements have been copied.
+     *
+     *  $willNotTerminateInf
+     * 
+     *  @param  xs     the array to fill.
+     *  @param  start  the starting index.
+     *  @param  len    the maximal number of elements to copy.
+     *  @tparam B      the type of the elements of the array. 
+     * 
+     *
+     *  @usecase def copyToArray(xs: Array[A], start: Int, len: Int): Unit
+     */
+    def copyToArray[B >: A](xs: Array[B], start: Int, len: Int) {
+      var i = start
+      val end = (start + len) min xs.length
+      breakable {
+        for (x <- this) {
+          if (i >= end) break
+          xs(i) = x
+          i += 1
+        }
+      }
+    }
+
+    def toTraversable: Traversable[A] = thisCollection
+    def toIterator: Iterator[A] = toStream.iterator
+    def toStream: Stream[A] = toBuffer.toStream
+
+    /** Converts this $coll to a string.
+     *
+     *  @return   a string representation of this collection. By default this
+     *            string consists of the `stringPrefix` of this $coll,
+     *            followed by all elements separated by commas and enclosed in parentheses.
+     */
+    override def toString = mkString(stringPrefix + "(", ", ", ")")
+
+    /** Defines the prefix of this object's `toString` representation.
+     *
+     *  @return  a string representation which starts the result of `toString`
+     *           applied to this $coll. By default the string prefix is the
+     *           simple name of the collection class $coll.
+     */
+    def stringPrefix : String = {
+      var string = repr.asInstanceOf[AnyRef].getClass.getName
+      val idx1 = string.lastIndexOf('.' : Int)
+      if (idx1 != -1) string = string.substring(idx1 + 1)
+      val idx2 = string.indexOf('$')
+      if (idx2 != -1) string = string.substring(0, idx2)
+      string
+    }
+
+    /** Creates a non-strict view of this $coll.
+     * 
+     *  @return a non-strict view of this $coll.
+     */
+    def view = new TraversableView[A, Repr] {
+      protected lazy val underlying = self.repr
+      override def foreach[U](f: A => U) = self foreach f
+    }
+
+    /** Creates a non-strict view of a slice of this $coll.
+     *
+     *  Note: the difference between `view` and `slice` is that `view` produces
+     *        a view of the current $coll, whereas `slice` produces a new $coll.
+     * 
+     *  Note: `view(from, to)` is equivalent to `view.slice(from, to)`
+     *  $orderDependent
+     * 
+     *  @param from   the index of the first element of the view
+     *  @param until  the index of the element following the view
+     *  @return a non-strict view of a slice of this $coll, starting at index `from`
+     *  and extending up to (but not including) index `until`.
+     */
+    def view(from: Int, until: Int): TraversableView[A, Repr] = view.slice(from, until)
+
+    /** Creates a non-strict filter of this $coll.
+     *
+     *  Note: the difference between `c filter p` and `c withFilter p` is that
+     *        the former creates a new collection, whereas the latter only
+     *        restricts the domain of subsequent `map`, `flatMap`, `foreach`,
+     *        and `withFilter` operations.
+     *  $orderDependent
+     * 
+     *  @param p   the predicate used to test elements.
+     *  @return    an object of class `WithFilter`, which supports
+     *             `map`, `flatMap`, `foreach`, and `withFilter` operations.
+     *             All these operations apply to those elements of this $coll which
+     *             satisfy the predicate `p`.
+     */
+    def withFilter(p: A => Boolean): FilterMonadic[A, Repr] = new WithFilter(p)
+
+    /** A class supporting filtered operations. Instances of this class are
+     *  returned by method `withFilter`.
+     */
+    class WithFilter(p: A => Boolean) extends FilterMonadic[A, Repr] {
+
+      /** Builds a new collection by applying a function to all elements of the
+       *  outer $coll containing this `WithFilter` instance that satisfy predicate `p`.
+       *
+       *  @param f      the function to apply to each element.
+       *  @tparam B     the element type of the returned collection.
+       *  @tparam That  $thatinfo
+       *  @param bf     $bfinfo
+       *  @return       a new collection of type `That` resulting from applying
+       *                the given function `f` to each element of the outer $coll
+       *                that satisfies predicate `p` and collecting the results.
+       *
+       *  @usecase def map[B](f: A => B): $Coll[B] 
+       *  
+       *  @return       a new $coll resulting from applying the given function
+       *                `f` to each element of the outer $coll that satisfies
+       *                predicate `p` and collecting the results.
+       */
+      def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+        val b = bf(repr)
+        for (x <- self) 
+          if (p(x)) b += f(x)
+        b.result
+      }
+
+      /** Builds a new collection by applying a function to all elements of the
+       *  outer $coll containing this `WithFilter` instance that satisfy
+       *  predicate `p` and concatenating the results. 
+       *
+       *  @param f      the function to apply to each element.
+       *  @tparam B     the element type of the returned collection.
+       *  @tparam That  $thatinfo
+       *  @param bf     $bfinfo
+       *  @return       a new collection of type `That` resulting from applying
+       *                the given collection-valued function `f` to each element
+       *                of the outer $coll that satisfies predicate `p` and
+       *                concatenating the results.
+       *
+       *  @usecase def flatMap[B](f: A => TraversableOnce[B]): $Coll[B]
+       * 
+       *  @return       a new $coll resulting from applying the given collection-valued function
+       *                `f` to each element of the outer $coll that satisfies predicate `p` and concatenating the results.
+       */
+      def flatMap[B, That](f: A => GenTraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+        val b = bf(repr)
+        for (x <- self) 
+          if (p(x)) b ++= f(x).seq
+        b.result
+      }
+
+      /** Applies a function `f` to all elements of the outer $coll containing
+       *  this `WithFilter` instance that satisfy predicate `p`.
+       *
+       *  @param  f   the function that is applied for its side-effect to every element.
+       *              The result of function `f` is discarded.
+       *              
+       *  @tparam  U  the type parameter describing the result of function `f`. 
+       *              This result will always be ignored. Typically `U` is `Unit`,
+       *              but this is not necessary.
+       *
+       *  @usecase def foreach(f: A => Unit): Unit
+       */   
+      def foreach[U](f: A => U): Unit = 
+        for (x <- self) 
+          if (p(x)) f(x)
+
+      /** Further refines the filter for this $coll.
+       *
+       *  @param q   the predicate used to test elements.
+       *  @return    an object of class `WithFilter`, which supports
+       *             `map`, `flatMap`, `foreach`, and `withFilter` operations.
+       *             All these operations apply to those elements of this $coll which
+       *             satisfy the predicate `q` in addition to the predicate `p`.
+       */
+      def withFilter(q: A => Boolean): WithFilter = 
+        new WithFilter(x => p(x) && q(x))
+    }
+
+    // A helper for tails and inits.
+    private def iterateUntilEmpty(f: Traversable[A @uV] => Traversable[A @uV]): Iterator[Repr] = {
+      val it = Iterator.iterate(thisCollection)(f) takeWhile (x => !x.isEmpty)
+      it ++ Iterator(Nil) map (newBuilder ++= _ result)
+    }
+  }
+
+
+</textarea>
+</form>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        matchBrackets: true,
+        theme: "ambiance",
+        mode: "text/x-scala"
+      });
+    </script>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/clojure/clojure.js b/third-party/codemirror-3.15/mode/clojure/clojure.js
new file mode 100644 (file)
index 0000000..ee22a12
--- /dev/null
@@ -0,0 +1,224 @@
+/**
+ * Author: Hans Engel
+ * Branched from CodeMirror's Scheme mode (by Koh Zi Han, based on implementation by Koh Zi Chun)
+ */
+CodeMirror.defineMode("clojure", function () {
+    var BUILTIN = "builtin", COMMENT = "comment", STRING = "string", CHARACTER = "string-2",
+        ATOM = "atom", NUMBER = "number", BRACKET = "bracket", KEYWORD = "keyword";
+    var INDENT_WORD_SKIP = 2;
+
+    function makeKeywords(str) {
+        var obj = {}, words = str.split(" ");
+        for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
+        return obj;
+    }
+
+    var atoms = makeKeywords("true false nil");
+
+    var keywords = makeKeywords(
+      "defn defn- def def- defonce defmulti defmethod defmacro defstruct deftype defprotocol defrecord defproject deftest slice defalias defhinted defmacro- defn-memo defnk defnk defonce- defunbound defunbound- defvar defvar- let letfn do case cond condp for loop recur when when-not when-let when-first if if-let if-not . .. -> ->> doto and or dosync doseq dotimes dorun doall load import unimport ns in-ns refer try catch finally throw with-open with-local-vars binding gen-class gen-and-load-class gen-and-save-class handler-case handle");
+
+    var builtins = makeKeywords(
+        "* *' *1 *2 *3 *agent* *allow-unresolved-vars* *assert* *clojure-version* *command-line-args* *compile-files* *compile-path* *compiler-options* *data-readers* *e *err* *file* *flush-on-newline* *fn-loader* *in* *math-context* *ns* *out* *print-dup* *print-length* *print-level* *print-meta* *print-readably* *read-eval* *source-path* *unchecked-math* *use-context-classloader* *verbose-defrecords* *warn-on-reflection* + +' - -' -> ->> ->ArrayChunk ->Vec ->VecNode ->VecSeq -cache-protocol-fn -reset-methods .. / < <= = == > >= EMPTY-NODE accessor aclone add-classpath add-watch agent agent-error agent-errors aget alength alias all-ns alter alter-meta! alter-var-root amap ancestors and apply areduce array-map aset aset-boolean aset-byte aset-char aset-double aset-float aset-int aset-long aset-short assert assoc assoc! assoc-in associative? atom await await-for await1 bases bean bigdec bigint biginteger binding bit-and bit-and-not bit-clear bit-flip bit-not bit-or bit-set bit-shift-left bit-shift-right bit-test bit-xor boolean boolean-array booleans bound-fn bound-fn* bound? butlast byte byte-array bytes case cast char char-array char-escape-string char-name-string char? chars chunk chunk-append chunk-buffer chunk-cons chunk-first chunk-next chunk-rest chunked-seq? class class? clear-agent-errors clojure-version coll? comment commute comp comparator compare compare-and-set! compile complement concat cond condp conj conj! cons constantly construct-proxy contains? count counted? create-ns create-struct cycle dec dec' decimal? declare default-data-readers definline definterface defmacro defmethod defmulti defn defn- defonce defprotocol defrecord defstruct deftype delay delay? deliver denominator deref derive descendants destructure disj disj! dissoc dissoc! distinct distinct? doall dorun doseq dosync dotimes doto double double-array doubles drop drop-last drop-while empty empty? ensure enumeration-seq error-handler error-mode eval even? every-pred every? ex-data ex-info extend extend-protocol extend-type extenders extends? false? ffirst file-seq filter filterv find find-keyword find-ns find-protocol-impl find-protocol-method find-var first flatten float float-array float? floats flush fn fn? fnext fnil for force format frequencies future future-call future-cancel future-cancelled? future-done? future? gen-class gen-interface gensym get get-in get-method get-proxy-class get-thread-bindings get-validator group-by hash hash-combine hash-map hash-set identical? identity if-let if-not ifn? import in-ns inc inc' init-proxy instance? int int-array integer? interleave intern interpose into into-array ints io! isa? iterate iterator-seq juxt keep keep-indexed key keys keyword keyword? last lazy-cat lazy-seq let letfn line-seq list list* list? load load-file load-reader load-string loaded-libs locking long long-array longs loop macroexpand macroexpand-1 make-array make-hierarchy map map-indexed map? mapcat mapv max max-key memfn memoize merge merge-with meta method-sig methods min min-key mod munge name namespace namespace-munge neg? newline next nfirst nil? nnext not not-any? not-empty not-every? not= ns ns-aliases ns-imports ns-interns ns-map ns-name ns-publics ns-refers ns-resolve ns-unalias ns-unmap nth nthnext nthrest num number? numerator object-array odd? or parents partial partition partition-all partition-by pcalls peek persistent! pmap pop pop! pop-thread-bindings pos? pr pr-str prefer-method prefers primitives-classnames print print-ctor print-dup print-method print-simple print-str printf println println-str prn prn-str promise proxy proxy-call-with-super proxy-mappings proxy-name proxy-super push-thread-bindings pvalues quot rand rand-int rand-nth range ratio? rational? rationalize re-find re-groups re-matcher re-matches re-pattern re-seq read read-line read-string realized? reduce reduce-kv reductions ref ref-history-count ref-max-history ref-min-history ref-set refer refer-clojure reify release-pending-sends rem remove remove-all-methods remove-method remove-ns remove-watch repeat repeatedly replace replicate require reset! reset-meta! resolve rest restart-agent resultset-seq reverse reversible? rseq rsubseq satisfies? second select-keys send send-off seq seq? seque sequence sequential? set set-error-handler! set-error-mode! set-validator! set? short short-array shorts shuffle shutdown-agents slurp some some-fn sort sort-by sorted-map sorted-map-by sorted-set sorted-set-by sorted? special-symbol? spit split-at split-with str string? struct struct-map subs subseq subvec supers swap! symbol symbol? sync take take-last take-nth take-while test the-ns thread-bound? time to-array to-array-2d trampoline transient tree-seq true? type unchecked-add unchecked-add-int unchecked-byte unchecked-char unchecked-dec unchecked-dec-int unchecked-divide-int unchecked-double unchecked-float unchecked-inc unchecked-inc-int unchecked-int unchecked-long unchecked-multiply unchecked-multiply-int unchecked-negate unchecked-negate-int unchecked-remainder-int unchecked-short unchecked-subtract unchecked-subtract-int underive unquote unquote-splicing update-in update-proxy use val vals var-get var-set var? vary-meta vec vector vector-of vector? when when-first when-let when-not while with-bindings with-bindings* with-in-str with-loading-context with-local-vars with-meta with-open with-out-str with-precision with-redefs with-redefs-fn xml-seq zero? zipmap *default-data-reader-fn* as-> cond-> cond->> reduced reduced? send-via set-agent-send-executor! set-agent-send-off-executor! some-> some->>");
+
+    var indentKeys = makeKeywords(
+        // Built-ins
+        "ns fn def defn defmethod bound-fn if if-not case condp when while when-not when-first do future comment doto locking proxy with-open with-precision reify deftype defrecord defprotocol extend extend-protocol extend-type try catch " +
+
+        // Binding forms
+        "let letfn binding loop for doseq dotimes when-let if-let " +
+
+        // Data structures
+        "defstruct struct-map assoc " +
+
+        // clojure.test
+        "testing deftest " +
+
+        // contrib
+        "handler-case handle dotrace deftrace");
+
+    var tests = {
+        digit: /\d/,
+        digit_or_colon: /[\d:]/,
+        hex: /[0-9a-f]/i,
+        sign: /[+-]/,
+        exponent: /e/i,
+        keyword_char: /[^\s\(\[\;\)\]]/,
+        symbol: /[\w*+!\-\._?:\/]/
+    };
+
+    function stateStack(indent, type, prev) { // represents a state stack object
+        this.indent = indent;
+        this.type = type;
+        this.prev = prev;
+    }
+
+    function pushStack(state, indent, type) {
+        state.indentStack = new stateStack(indent, type, state.indentStack);
+    }
+
+    function popStack(state) {
+        state.indentStack = state.indentStack.prev;
+    }
+
+    function isNumber(ch, stream){
+        // hex
+        if ( ch === '0' && stream.eat(/x/i) ) {
+            stream.eatWhile(tests.hex);
+            return true;
+        }
+
+        // leading sign
+        if ( ( ch == '+' || ch == '-' ) && ( tests.digit.test(stream.peek()) ) ) {
+          stream.eat(tests.sign);
+          ch = stream.next();
+        }
+
+        if ( tests.digit.test(ch) ) {
+            stream.eat(ch);
+            stream.eatWhile(tests.digit);
+
+            if ( '.' == stream.peek() ) {
+                stream.eat('.');
+                stream.eatWhile(tests.digit);
+            }
+
+            if ( stream.eat(tests.exponent) ) {
+                stream.eat(tests.sign);
+                stream.eatWhile(tests.digit);
+            }
+
+            return true;
+        }
+
+        return false;
+    }
+
+    // Eat character that starts after backslash \
+    function eatCharacter(stream) {
+        var first = stream.next();
+        // Read special literals: backspace, newline, space, return.
+        // Just read all lowercase letters.
+        if (first.match(/[a-z]/) && stream.match(/[a-z]+/, true)) {
+            return;
+        }
+        // Read unicode character: \u1000 \uA0a1
+        if (first === "u") {
+            stream.match(/[0-9a-z]{4}/i, true);
+        }
+    }
+
+    return {
+        startState: function () {
+            return {
+                indentStack: null,
+                indentation: 0,
+                mode: false
+            };
+        },
+
+        token: function (stream, state) {
+            if (state.indentStack == null && stream.sol()) {
+                // update indentation, but only if indentStack is empty
+                state.indentation = stream.indentation();
+            }
+
+            // skip spaces
+            if (stream.eatSpace()) {
+                return null;
+            }
+            var returnType = null;
+
+            switch(state.mode){
+                case "string": // multi-line string parsing mode
+                    var next, escaped = false;
+                    while ((next = stream.next()) != null) {
+                        if (next == "\"" && !escaped) {
+
+                            state.mode = false;
+                            break;
+                        }
+                        escaped = !escaped && next == "\\";
+                    }
+                    returnType = STRING; // continue on in string mode
+                    break;
+                default: // default parsing mode
+                    var ch = stream.next();
+
+                    if (ch == "\"") {
+                        state.mode = "string";
+                        returnType = STRING;
+                    } else if (ch == "\\") {
+                        eatCharacter(stream);
+                        returnType = CHARACTER;
+                    } else if (ch == "'" && !( tests.digit_or_colon.test(stream.peek()) )) {
+                        returnType = ATOM;
+                    } else if (ch == ";") { // comment
+                        stream.skipToEnd(); // rest of the line is a comment
+                        returnType = COMMENT;
+                    } else if (isNumber(ch,stream)){
+                        returnType = NUMBER;
+                    } else if (ch == "(" || ch == "[" || ch == "{" ) {
+                        var keyWord = '', indentTemp = stream.column(), letter;
+                        /**
+                        Either
+                        (indent-word ..
+                        (non-indent-word ..
+                        (;something else, bracket, etc.
+                        */
+
+                        if (ch == "(") while ((letter = stream.eat(tests.keyword_char)) != null) {
+                            keyWord += letter;
+                        }
+
+                        if (keyWord.length > 0 && (indentKeys.propertyIsEnumerable(keyWord) ||
+                                                   /^(?:def|with)/.test(keyWord))) { // indent-word
+                            pushStack(state, indentTemp + INDENT_WORD_SKIP, ch);
+                        } else { // non-indent word
+                            // we continue eating the spaces
+                            stream.eatSpace();
+                            if (stream.eol() || stream.peek() == ";") {
+                                // nothing significant after
+                                // we restart indentation 1 space after
+                                pushStack(state, indentTemp + 1, ch);
+                            } else {
+                                pushStack(state, indentTemp + stream.current().length, ch); // else we match
+                            }
+                        }
+                        stream.backUp(stream.current().length - 1); // undo all the eating
+
+                        returnType = BRACKET;
+                    } else if (ch == ")" || ch == "]" || ch == "}") {
+                        returnType = BRACKET;
+                        if (state.indentStack != null && state.indentStack.type == (ch == ")" ? "(" : (ch == "]" ? "[" :"{"))) {
+                            popStack(state);
+                        }
+                    } else if ( ch == ":" ) {
+                        stream.eatWhile(tests.symbol);
+                        return ATOM;
+                    } else {
+                        stream.eatWhile(tests.symbol);
+
+                        if (keywords && keywords.propertyIsEnumerable(stream.current())) {
+                            returnType = KEYWORD;
+                        } else if (builtins && builtins.propertyIsEnumerable(stream.current())) {
+                            returnType = BUILTIN;
+                        } else if (atoms && atoms.propertyIsEnumerable(stream.current())) {
+                            returnType = ATOM;
+                        } else returnType = null;
+                    }
+            }
+
+            return returnType;
+        },
+
+        indent: function (state) {
+            if (state.indentStack == null) return state.indentation;
+            return state.indentStack.indent;
+        },
+
+        lineComment: ";;"
+    };
+});
+
+CodeMirror.defineMIME("text/x-clojure", "clojure");
diff --git a/third-party/codemirror-3.15/mode/clojure/index.html b/third-party/codemirror-3.15/mode/clojure/index.html
new file mode 100644 (file)
index 0000000..bfe6fc9
--- /dev/null
@@ -0,0 +1,76 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Clojure mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="clojure.js"></script>
+    <style>.CodeMirror {background: #f8f8f8;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Clojure mode</h1>
+    <form><textarea id="code" name="code">
+; Conway's Game of Life, based on the work of:
+;; Laurent Petit https://gist.github.com/1200343
+;; Christophe Grand http://clj-me.cgrand.net/2011/08/19/conways-game-of-life
+
+(ns ^{:doc "Conway's Game of Life."}
+ game-of-life)
+
+;; Core game of life's algorithm functions
+
+(defn neighbours
+  "Given a cell's coordinates, returns the coordinates of its neighbours."
+  [[x y]]
+  (for [dx [-1 0 1] dy (if (zero? dx) [-1 1] [-1 0 1])]
+    [(+ dx x) (+ dy y)]))
+
+(defn step
+  "Given a set of living cells, computes the new set of living cells."
+  [cells]
+  (set (for [[cell n] (frequencies (mapcat neighbours cells))
+             :when (or (= n 3) (and (= n 2) (cells cell)))]
+         cell)))
+
+;; Utility methods for displaying game on a text terminal
+
+(defn print-board
+  "Prints a board on *out*, representing a step in the game."
+  [board w h]
+  (doseq [x (range (inc w)) y (range (inc h))]
+    (if (= y 0) (print "\n"))
+    (print (if (board [x y]) "[X]" " . "))))
+
+(defn display-grids
+  "Prints a squence of boards on *out*, representing several steps."
+  [grids w h]
+  (doseq [board grids]
+    (print-board board w h)
+    (print "\n")))
+
+;; Launches an example board
+
+(def
+  ^{:doc "board represents the initial set of living cells"}
+   board #{[2 1] [2 2] [2 3]})
+
+(display-grids (take 3 (iterate step board)) 5 5)
+
+;; Let's play with characters
+(println \1 \a \# \\
+         \" \( \newline
+         \} \" \space
+         \tab \return \backspace
+         \u1000 \uAaAa \u9F9F)
+
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-clojure</code>.</p>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/cobol/cobol.js b/third-party/codemirror-3.15/mode/cobol/cobol.js
new file mode 100644 (file)
index 0000000..d92491d
--- /dev/null
@@ -0,0 +1,240 @@
+/**
+ * Author: Gautam Mehta
+ * Branched from CodeMirror's Scheme mode
+ */
+CodeMirror.defineMode("cobol", function () {
+  var BUILTIN = "builtin", COMMENT = "comment", STRING = "string",
+      ATOM = "atom", NUMBER = "number", KEYWORD = "keyword", MODTAG = "header",
+      COBOLLINENUM = "def", PERIOD = "link";
+  function makeKeywords(str) {
+    var obj = {}, words = str.split(" ");
+    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
+    return obj;
+  }
+  var atoms = makeKeywords("TRUE FALSE ZEROES ZEROS ZERO SPACES SPACE LOW-VALUE LOW-VALUES ");
+  var keywords = makeKeywords(
+      "ACCEPT ACCESS ACQUIRE ADD ADDRESS " +
+      "ADVANCING AFTER ALIAS ALL ALPHABET " +
+      "ALPHABETIC ALPHABETIC-LOWER ALPHABETIC-UPPER ALPHANUMERIC ALPHANUMERIC-EDITED " +
+      "ALSO ALTER ALTERNATE AND ANY " +
+      "ARE AREA AREAS ARITHMETIC ASCENDING " +
+      "ASSIGN AT ATTRIBUTE AUTHOR AUTO " +
+      "AUTO-SKIP AUTOMATIC B-AND B-EXOR B-LESS " +
+      "B-NOT B-OR BACKGROUND-COLOR BACKGROUND-COLOUR BEEP " +
+      "BEFORE BELL BINARY BIT BITS " +
+      "BLANK BLINK BLOCK BOOLEAN BOTTOM " +
+      "BY CALL CANCEL CD CF " +
+      "CH CHARACTER CHARACTERS CLASS CLOCK-UNITS " +
+      "CLOSE COBOL CODE CODE-SET COL " +
+      "COLLATING COLUMN COMMA COMMIT COMMITMENT " +
+      "COMMON COMMUNICATION COMP COMP-0 COMP-1 " +
+      "COMP-2 COMP-3 COMP-4 COMP-5 COMP-6 " +
+      "COMP-7 COMP-8 COMP-9 COMPUTATIONAL COMPUTATIONAL-0 " +
+      "COMPUTATIONAL-1 COMPUTATIONAL-2 COMPUTATIONAL-3 COMPUTATIONAL-4 COMPUTATIONAL-5 " +
+      "COMPUTATIONAL-6 COMPUTATIONAL-7 COMPUTATIONAL-8 COMPUTATIONAL-9 COMPUTE " +
+      "CONFIGURATION CONNECT CONSOLE CONTAINED CONTAINS " +
+      "CONTENT CONTINUE CONTROL CONTROL-AREA CONTROLS " +
+      "CONVERTING COPY CORR CORRESPONDING COUNT " +
+      "CRT CRT-UNDER CURRENCY CURRENT CURSOR " +
+      "DATA DATE DATE-COMPILED DATE-WRITTEN DAY " +
+      "DAY-OF-WEEK DB DB-ACCESS-CONTROL-KEY DB-DATA-NAME DB-EXCEPTION " +
+      "DB-FORMAT-NAME DB-RECORD-NAME DB-SET-NAME DB-STATUS DBCS " +
+      "DBCS-EDITED DE DEBUG-CONTENTS DEBUG-ITEM DEBUG-LINE " +
+      "DEBUG-NAME DEBUG-SUB-1 DEBUG-SUB-2 DEBUG-SUB-3 DEBUGGING " +
+      "DECIMAL-POINT DECLARATIVES DEFAULT DELETE DELIMITED " +
+      "DELIMITER DEPENDING DESCENDING DESCRIBED DESTINATION " +
+      "DETAIL DISABLE DISCONNECT DISPLAY DISPLAY-1 " +
+      "DISPLAY-2 DISPLAY-3 DISPLAY-4 DISPLAY-5 DISPLAY-6 " +
+      "DISPLAY-7 DISPLAY-8 DISPLAY-9 DIVIDE DIVISION " +
+      "DOWN DROP DUPLICATE DUPLICATES DYNAMIC " +
+      "EBCDIC EGI EJECT ELSE EMI " +
+      "EMPTY EMPTY-CHECK ENABLE END END. END-ACCEPT END-ACCEPT. " +
+      "END-ADD END-CALL END-COMPUTE END-DELETE END-DISPLAY " +
+      "END-DIVIDE END-EVALUATE END-IF END-INVOKE END-MULTIPLY " +
+      "END-OF-PAGE END-PERFORM END-READ END-RECEIVE END-RETURN " +
+      "END-REWRITE END-SEARCH END-START END-STRING END-SUBTRACT " +
+      "END-UNSTRING END-WRITE END-XML ENTER ENTRY " +
+      "ENVIRONMENT EOP EQUAL EQUALS ERASE " +
+      "ERROR ESI EVALUATE EVERY EXCEEDS " +
+      "EXCEPTION EXCLUSIVE EXIT EXTEND EXTERNAL " +
+      "EXTERNALLY-DESCRIBED-KEY FD FETCH FILE FILE-CONTROL " +
+      "FILE-STREAM FILES FILLER FINAL FIND " +
+      "FINISH FIRST FOOTING FOR FOREGROUND-COLOR " +
+      "FOREGROUND-COLOUR FORMAT FREE FROM FULL " +
+      "FUNCTION GENERATE GET GIVING GLOBAL " +
+      "GO GOBACK GREATER GROUP HEADING " +
+      "HIGH-VALUE HIGH-VALUES HIGHLIGHT I-O I-O-CONTROL " +
+      "ID IDENTIFICATION IF IN INDEX " +
+      "INDEX-1 INDEX-2 INDEX-3 INDEX-4 INDEX-5 " +
+      "INDEX-6 INDEX-7 INDEX-8 INDEX-9 INDEXED " +
+      "INDIC INDICATE INDICATOR INDICATORS INITIAL " +
+      "INITIALIZE INITIATE INPUT INPUT-OUTPUT INSPECT " +
+      "INSTALLATION INTO INVALID INVOKE IS " +
+      "JUST JUSTIFIED KANJI KEEP KEY " +
+      "LABEL LAST LD LEADING LEFT " +
+      "LEFT-JUSTIFY LENGTH LENGTH-CHECK LESS LIBRARY " +
+      "LIKE LIMIT LIMITS LINAGE LINAGE-COUNTER " +
+      "LINE LINE-COUNTER LINES LINKAGE LOCAL-STORAGE " +
+      "LOCALE LOCALLY LOCK " +
+      "MEMBER MEMORY MERGE MESSAGE METACLASS " +
+      "MODE MODIFIED MODIFY MODULES MOVE " +
+      "MULTIPLE MULTIPLY NATIONAL NATIVE NEGATIVE " +
+      "NEXT NO NO-ECHO NONE NOT " +
+      "NULL NULL-KEY-MAP NULL-MAP NULLS NUMBER " +
+      "NUMERIC NUMERIC-EDITED OBJECT OBJECT-COMPUTER OCCURS " +
+      "OF OFF OMITTED ON ONLY " +
+      "OPEN OPTIONAL OR ORDER ORGANIZATION " +
+      "OTHER OUTPUT OVERFLOW OWNER PACKED-DECIMAL " +
+      "PADDING PAGE PAGE-COUNTER PARSE PERFORM " +
+      "PF PH PIC PICTURE PLUS " +
+      "POINTER POSITION POSITIVE PREFIX PRESENT " +
+      "PRINTING PRIOR PROCEDURE PROCEDURE-POINTER PROCEDURES " +
+      "PROCEED PROCESS PROCESSING PROGRAM PROGRAM-ID " +
+      "PROMPT PROTECTED PURGE QUEUE QUOTE " +
+      "QUOTES RANDOM RD READ READY " +
+      "REALM RECEIVE RECONNECT RECORD RECORD-NAME " +
+      "RECORDS RECURSIVE REDEFINES REEL REFERENCE " +
+      "REFERENCE-MONITOR REFERENCES RELATION RELATIVE RELEASE " +
+      "REMAINDER REMOVAL RENAMES REPEATED REPLACE " +
+      "REPLACING REPORT REPORTING REPORTS REPOSITORY " +
+      "REQUIRED RERUN RESERVE RESET RETAINING " +
+      "RETRIEVAL RETURN RETURN-CODE RETURNING REVERSE-VIDEO " +
+      "REVERSED REWIND REWRITE RF RH " +
+      "RIGHT RIGHT-JUSTIFY ROLLBACK ROLLING ROUNDED " +
+      "RUN SAME SCREEN SD SEARCH " +
+      "SECTION SECURE SECURITY SEGMENT SEGMENT-LIMIT " +
+      "SELECT SEND SENTENCE SEPARATE SEQUENCE " +
+      "SEQUENTIAL SET SHARED SIGN SIZE " +
+      "SKIP1 SKIP2 SKIP3 SORT SORT-MERGE " +
+      "SORT-RETURN SOURCE SOURCE-COMPUTER SPACE-FILL " +
+      "SPECIAL-NAMES STANDARD STANDARD-1 STANDARD-2 " +
+      "START STARTING STATUS STOP STORE " +
+      "STRING SUB-QUEUE-1 SUB-QUEUE-2 SUB-QUEUE-3 SUB-SCHEMA " +
+      "SUBFILE SUBSTITUTE SUBTRACT SUM SUPPRESS " +
+      "SYMBOLIC SYNC SYNCHRONIZED SYSIN SYSOUT " +
+      "TABLE TALLYING TAPE TENANT TERMINAL " +
+      "TERMINATE TEST TEXT THAN THEN " +
+      "THROUGH THRU TIME TIMES TITLE " +
+      "TO TOP TRAILING TRAILING-SIGN TRANSACTION " +
+      "TYPE TYPEDEF UNDERLINE UNEQUAL UNIT " +
+      "UNSTRING UNTIL UP UPDATE UPON " +
+      "USAGE USAGE-MODE USE USING VALID " +
+      "VALIDATE VALUE VALUES VARYING VLR " +
+      "WAIT WHEN WHEN-COMPILED WITH WITHIN " +
+      "WORDS WORKING-STORAGE WRITE XML XML-CODE " +
+      "XML-EVENT XML-NTEXT XML-TEXT ZERO ZERO-FILL " );
+
+  var builtins = makeKeywords("- * ** / + < <= = > >= ");
+  var tests = {
+    digit: /\d/,
+    digit_or_colon: /[\d:]/,
+    hex: /[0-9a-f]/i,
+    sign: /[+-]/,
+    exponent: /e/i,
+    keyword_char: /[^\s\(\[\;\)\]]/,
+    symbol: /[\w*+\-]/
+  };
+  function isNumber(ch, stream){
+    // hex
+    if ( ch === '0' && stream.eat(/x/i) ) {
+      stream.eatWhile(tests.hex);
+      return true;
+    }
+    // leading sign
+    if ( ( ch == '+' || ch == '-' ) && ( tests.digit.test(stream.peek()) ) ) {
+      stream.eat(tests.sign);
+      ch = stream.next();
+    }
+    if ( tests.digit.test(ch) ) {
+      stream.eat(ch);
+      stream.eatWhile(tests.digit);
+      if ( '.' == stream.peek()) {
+        stream.eat('.');
+        stream.eatWhile(tests.digit);
+      }
+      if ( stream.eat(tests.exponent) ) {
+        stream.eat(tests.sign);
+        stream.eatWhile(tests.digit);
+      }
+      return true;
+    }
+    return false;
+  }
+  return {
+    startState: function () {
+      return {
+        indentStack: null,
+        indentation: 0,
+        mode: false
+      };
+    },
+    token: function (stream, state) {
+      if (state.indentStack == null && stream.sol()) {
+        // update indentation, but only if indentStack is empty
+        state.indentation = 6 ; //stream.indentation();
+      }
+      // skip spaces
+      if (stream.eatSpace()) {
+        return null;
+      }
+      var returnType = null;
+      switch(state.mode){
+      case "string": // multi-line string parsing mode
+        var next = false;
+        while ((next = stream.next()) != null) {
+          if (next == "\"" || next == "\'") {
+            state.mode = false;
+            break;
+          }
+        }
+        returnType = STRING; // continue on in string mode
+        break;
+      default: // default parsing mode
+        var ch = stream.next();
+        var col = stream.column();
+        if (col >= 0 && col <= 5) {
+          returnType = COBOLLINENUM;
+        } else if (col >= 72 && col <= 79) {
+          stream.skipToEnd();
+          returnType = MODTAG;
+        } else if (ch == "*" && col == 6) { // comment
+          stream.skipToEnd(); // rest of the line is a comment
+          returnType = COMMENT;
+        } else if (ch == "\"" || ch == "\'") {
+          state.mode = "string";
+          returnType = STRING;
+        } else if (ch == "'" && !( tests.digit_or_colon.test(stream.peek()) )) {
+          returnType = ATOM;
+        } else if (ch == ".") {
+          returnType = PERIOD;
+        } else if (isNumber(ch,stream)){
+          returnType = NUMBER;
+        } else {
+          if (stream.current().match(tests.symbol)) {
+            while (col < 71) {
+              if (stream.eat(tests.symbol) === undefined) {
+                break;
+              } else {
+                col++;
+              }
+            }
+          }
+          if (keywords && keywords.propertyIsEnumerable(stream.current().toUpperCase())) {
+            returnType = KEYWORD;
+          } else if (builtins && builtins.propertyIsEnumerable(stream.current().toUpperCase())) {
+            returnType = BUILTIN;
+          } else if (atoms && atoms.propertyIsEnumerable(stream.current().toUpperCase())) {
+            returnType = ATOM;
+          } else returnType = null;
+        }
+      }
+      return returnType;
+    },
+    indent: function (state) {
+      if (state.indentStack == null) return state.indentation;
+      return state.indentStack.indent;
+    }
+  };
+});
+
+CodeMirror.defineMIME("text/x-cobol", "cobol");
diff --git a/third-party/codemirror-3.15/mode/cobol/index.html b/third-party/codemirror-3.15/mode/cobol/index.html
new file mode 100644 (file)
index 0000000..71cc2fa
--- /dev/null
@@ -0,0 +1,195 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: COBOL mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../../addon/edit/matchbrackets.js"></script>
+    <script src="cobol.js"></script>
+    <link rel="stylesheet" href="../../theme/neat.css">
+    <link rel="stylesheet" href="../../theme/elegant.css">
+    <link rel="stylesheet" href="../../theme/erlang-dark.css">
+    <link rel="stylesheet" href="../../theme/night.css">
+    <link rel="stylesheet" href="../../theme/monokai.css">
+    <link rel="stylesheet" href="../../theme/cobalt.css">
+    <link rel="stylesheet" href="../../theme/eclipse.css">
+    <link rel="stylesheet" href="../../theme/rubyblue.css">
+    <link rel="stylesheet" href="../../theme/lesser-dark.css">
+    <link rel="stylesheet" href="../../theme/xq-dark.css">
+    <link rel="stylesheet" href="../../theme/xq-light.css">
+    <link rel="stylesheet" href="../../theme/ambiance.css">
+    <link rel="stylesheet" href="../../theme/blackboard.css">
+    <link rel="stylesheet" href="../../theme/vibrant-ink.css">
+    <link rel="stylesheet" href="../../theme/solarized.css">
+    <link rel="stylesheet" href="../../theme/twilight.css">
+    <link rel="stylesheet" href="../../theme/midnight.css">
+    <link rel="stylesheet" href="../../addon/dialog/dialog.css">
+    <script src="../../addon/selection/active-line.js"></script>
+    <script src="../../addon/search/search.js"></script>
+    <script src="../../addon/dialog/dialog.js"></script>
+    <script src="../../addon/search/searchcursor.js"></script>
+    <style>
+        .CodeMirror {
+          border: 1px solid #eee;
+          font-size : 20px;
+          height : auto !important;
+        }
+        .CodeMirror-activeline-background {background: #555555 !important;}
+    </style>
+  </head>
+  <body>
+    <p> Select Theme <select onchange="selectTheme()" id="selectTheme">
+        <option>default</option>
+        <option>ambiance</option>
+        <option>blackboard</option>
+        <option>cobalt</option>
+        <option>eclipse</option>
+        <option>elegant</option>
+        <option>erlang-dark</option>
+        <option>lesser-dark</option>
+        <option>midnight</option>
+        <option>monokai</option>
+        <option>neat</option>
+        <option>night</option>
+        <option>rubyblue</option>
+        <option>solarized dark</option>
+        <option>solarized light</option>
+        <option selected>twilight</option>
+        <option>vibrant-ink</option>
+        <option>xq-dark</option>
+        <option>xq-light</option>
+    </select>    Select Font Size <select onchange="selectFontsize()" id="selectFontSize">
+          <option value="13px">13px</option>
+          <option value="14px">14px</option>
+          <option value="16px">16px</option>
+          <option value="18px">18px</option>
+          <option value="20px" selected="selected">20px</option>
+          <option value="24px">24px</option>
+          <option value="26px">26px</option>
+          <option value="28px">28px</option>
+          <option value="30px">30px</option>
+          <option value="32px">32px</option>
+          <option value="34px">34px</option>
+          <option value="36px">36px</option>
+        </select>
+<label for="checkBoxReadOnly">Read-only</label>
+<input type="checkbox" id="checkBoxReadOnly" onchange="selectReadOnly()">
+<label for="id_tabToIndentSpace">Insert Spaces on Tab</label>
+<input type="checkbox" id="id_tabToIndentSpace" onchange="tabToIndentSpace()">
+</p>
+<textarea id="code" name="code">
+---------1---------2---------3---------4---------5---------6---------7---------8
+12345678911234567892123456789312345678941234567895123456789612345678971234567898
+000010 IDENTIFICATION DIVISION.                                        MODTGHERE
+000020 PROGRAM-ID.       SAMPLE.
+000030 AUTHOR.           TEST SAM. 
+000040 DATE-WRITTEN.     5 February 2013
+000041
+000042* A sample program just to show the form.
+000043* The program copies its input to the output,
+000044* and counts the number of records.
+000045* At the end this number is printed.
+000046
+000050 ENVIRONMENT DIVISION.
+000060 INPUT-OUTPUT SECTION.
+000070 FILE-CONTROL.
+000080     SELECT STUDENT-FILE     ASSIGN TO SYSIN
+000090         ORGANIZATION IS LINE SEQUENTIAL.
+000100     SELECT PRINT-FILE       ASSIGN TO SYSOUT
+000110         ORGANIZATION IS LINE SEQUENTIAL.
+000120
+000130 DATA DIVISION.
+000140 FILE SECTION.
+000150 FD  STUDENT-FILE
+000160     RECORD CONTAINS 43 CHARACTERS
+000170     DATA RECORD IS STUDENT-IN.
+000180 01  STUDENT-IN              PIC X(43).
+000190
+000200 FD  PRINT-FILE
+000210     RECORD CONTAINS 80 CHARACTERS
+000220     DATA RECORD IS PRINT-LINE.
+000230 01  PRINT-LINE              PIC X(80).
+000240
+000250 WORKING-STORAGE SECTION.
+000260 01  DATA-REMAINS-SWITCH     PIC X(2)      VALUE SPACES.
+000261 01  RECORDS-WRITTEN         PIC 99.
+000270
+000280 01  DETAIL-LINE.
+000290     05  FILLER              PIC X(7)      VALUE SPACES.
+000300     05  RECORD-IMAGE        PIC X(43).
+000310     05  FILLER              PIC X(30)     VALUE SPACES.
+000311 
+000312 01  SUMMARY-LINE.
+000313     05  FILLER              PIC X(7)      VALUE SPACES.
+000314     05  TOTAL-READ          PIC 99.
+000315     05  FILLER              PIC X         VALUE SPACE.
+000316     05  FILLER              PIC X(17)     
+000317                 VALUE  'Records were read'.
+000318     05  FILLER              PIC X(53)     VALUE SPACES.
+000319
+000320 PROCEDURE DIVISION.
+000321
+000330 PREPARE-SENIOR-REPORT.
+000340     OPEN INPUT  STUDENT-FILE
+000350          OUTPUT PRINT-FILE.
+000351     MOVE ZERO TO RECORDS-WRITTEN.
+000360     READ STUDENT-FILE
+000370         AT END MOVE 'NO' TO DATA-REMAINS-SWITCH
+000380     END-READ.
+000390     PERFORM PROCESS-RECORDS
+000410         UNTIL DATA-REMAINS-SWITCH = 'NO'.
+000411     PERFORM PRINT-SUMMARY.
+000420     CLOSE STUDENT-FILE
+000430           PRINT-FILE.
+000440     STOP RUN.
+000450
+000460 PROCESS-RECORDS.
+000470     MOVE STUDENT-IN TO RECORD-IMAGE.
+000480     MOVE DETAIL-LINE TO PRINT-LINE.
+000490     WRITE PRINT-LINE.
+000500     ADD 1 TO RECORDS-WRITTEN.
+000510     READ STUDENT-FILE
+000520         AT END MOVE 'NO' TO DATA-REMAINS-SWITCH
+000530     END-READ. 
+000540
+000550 PRINT-SUMMARY.
+000560     MOVE RECORDS-WRITTEN TO TOTAL-READ.
+000570     MOVE SUMMARY-LINE TO PRINT-LINE.
+000571     WRITE PRINT-LINE. 
+000572
+000580
+</textarea>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        matchBrackets: true,
+        mode: "text/x-cobol",
+        theme : "twilight",
+        styleActiveLine: true,
+        showCursorWhenSelecting : true,  
+      });
+      function selectTheme() {
+        var themeInput = document.getElementById("selectTheme");
+        var theme = themeInput.options[themeInput.selectedIndex].innerHTML;
+        editor.setOption("theme", theme);
+      }
+      function selectFontsize() {
+        var fontSizeInput = document.getElementById("selectFontSize");
+        var fontSize = fontSizeInput.options[fontSizeInput.selectedIndex].innerHTML;
+        editor.getWrapperElement().style["font-size"] = fontSize;
+        editor.refresh();
+      }
+      function selectReadOnly() {
+        editor.setOption("readOnly", document.getElementById("checkBoxReadOnly").checked);
+      }
+      function tabToIndentSpace() {
+        if (document.getElementById("id_tabToIndentSpace").checked) {
+            editor.setOption("extraKeys", {Tab: function(cm) { cm.replaceSelection("    ", "end"); }});
+        } else {
+            editor.setOption("extraKeys", {Tab: function(cm) { cm.replaceSelection("    ", "end"); }});
+        }
+      }
+    </script>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/coffeescript/LICENSE b/third-party/codemirror-3.15/mode/coffeescript/LICENSE
new file mode 100644 (file)
index 0000000..977e284
--- /dev/null
@@ -0,0 +1,22 @@
+The MIT License
+
+Copyright (c) 2011 Jeff Pickhardt
+Modified from the Python CodeMirror mode, Copyright (c) 2010 Timothy Farrell
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
\ No newline at end of file
diff --git a/third-party/codemirror-3.15/mode/coffeescript/coffeescript.js b/third-party/codemirror-3.15/mode/coffeescript/coffeescript.js
new file mode 100644 (file)
index 0000000..4f54b0c
--- /dev/null
@@ -0,0 +1,348 @@
+/**
+ * Link to the project's GitHub page:
+ * https://github.com/pickhardt/coffeescript-codemirror-mode
+ */
+CodeMirror.defineMode('coffeescript', function(conf) {
+    var ERRORCLASS = 'error';
+
+    function wordRegexp(words) {
+        return new RegExp("^((" + words.join(")|(") + "))\\b");
+    }
+
+    var singleOperators = new RegExp("^[\\+\\-\\*/%&|\\^~<>!\?]");
+    var singleDelimiters = new RegExp('^[\\(\\)\\[\\]\\{\\},:`=;\\.]');
+    var doubleOperators = new RegExp("^((\->)|(\=>)|(\\+\\+)|(\\+\\=)|(\\-\\-)|(\\-\\=)|(\\*\\*)|(\\*\\=)|(\\/\\/)|(\\/\\=)|(==)|(!=)|(<=)|(>=)|(<>)|(<<)|(>>)|(//))");
+    var doubleDelimiters = new RegExp("^((\\.\\.)|(\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))");
+    var tripleDelimiters = new RegExp("^((\\.\\.\\.)|(//=)|(>>=)|(<<=)|(\\*\\*=))");
+    var identifiers = new RegExp("^[_A-Za-z$][_A-Za-z$0-9]*");
+    var properties = new RegExp("^(@|this\.)[_A-Za-z$][_A-Za-z$0-9]*");
+
+    var wordOperators = wordRegexp(['and', 'or', 'not',
+                                    'is', 'isnt', 'in',
+                                    'instanceof', 'typeof']);
+    var indentKeywords = ['for', 'while', 'loop', 'if', 'unless', 'else',
+                          'switch', 'try', 'catch', 'finally', 'class'];
+    var commonKeywords = ['break', 'by', 'continue', 'debugger', 'delete',
+                          'do', 'in', 'of', 'new', 'return', 'then',
+                          'this', 'throw', 'when', 'until'];
+
+    var keywords = wordRegexp(indentKeywords.concat(commonKeywords));
+
+    indentKeywords = wordRegexp(indentKeywords);
+
+
+    var stringPrefixes = new RegExp("^('{3}|\"{3}|['\"])");
+    var regexPrefixes = new RegExp("^(/{3}|/)");
+    var commonConstants = ['Infinity', 'NaN', 'undefined', 'null', 'true', 'false', 'on', 'off', 'yes', 'no'];
+    var constants = wordRegexp(commonConstants);
+
+    // Tokenizers
+    function tokenBase(stream, state) {
+        // Handle scope changes
+        if (stream.sol()) {
+            var scopeOffset = state.scopes[0].offset;
+            if (stream.eatSpace()) {
+                var lineOffset = stream.indentation();
+                if (lineOffset > scopeOffset) {
+                    return 'indent';
+                } else if (lineOffset < scopeOffset) {
+                    return 'dedent';
+                }
+                return null;
+            } else {
+                if (scopeOffset > 0) {
+                    dedent(stream, state);
+                }
+            }
+        }
+        if (stream.eatSpace()) {
+            return null;
+        }
+
+        var ch = stream.peek();
+
+        // Handle docco title comment (single line)
+        if (stream.match("####")) {
+            stream.skipToEnd();
+            return 'comment';
+        }
+
+        // Handle multi line comments
+        if (stream.match("###")) {
+            state.tokenize = longComment;
+            return state.tokenize(stream, state);
+        }
+
+        // Single line comment
+        if (ch === '#') {
+            stream.skipToEnd();
+            return 'comment';
+        }
+
+        // Handle number literals
+        if (stream.match(/^-?[0-9\.]/, false)) {
+            var floatLiteral = false;
+            // Floats
+            if (stream.match(/^-?\d*\.\d+(e[\+\-]?\d+)?/i)) {
+              floatLiteral = true;
+            }
+            if (stream.match(/^-?\d+\.\d*/)) {
+              floatLiteral = true;
+            }
+            if (stream.match(/^-?\.\d+/)) {
+              floatLiteral = true;
+            }
+
+            if (floatLiteral) {
+                // prevent from getting extra . on 1..
+                if (stream.peek() == "."){
+                    stream.backUp(1);
+                }
+                return 'number';
+            }
+            // Integers
+            var intLiteral = false;
+            // Hex
+            if (stream.match(/^-?0x[0-9a-f]+/i)) {
+              intLiteral = true;
+            }
+            // Decimal
+            if (stream.match(/^-?[1-9]\d*(e[\+\-]?\d+)?/)) {
+                intLiteral = true;
+            }
+            // Zero by itself with no other piece of number.
+            if (stream.match(/^-?0(?![\dx])/i)) {
+              intLiteral = true;
+            }
+            if (intLiteral) {
+                return 'number';
+            }
+        }
+
+        // Handle strings
+        if (stream.match(stringPrefixes)) {
+            state.tokenize = tokenFactory(stream.current(), 'string');
+            return state.tokenize(stream, state);
+        }
+        // Handle regex literals
+        if (stream.match(regexPrefixes)) {
+            if (stream.current() != '/' || stream.match(/^.*\//, false)) { // prevent highlight of division
+                state.tokenize = tokenFactory(stream.current(), 'string-2');
+                return state.tokenize(stream, state);
+            } else {
+                stream.backUp(1);
+            }
+        }
+
+        // Handle operators and delimiters
+        if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters)) {
+            return 'punctuation';
+        }
+        if (stream.match(doubleOperators)
+            || stream.match(singleOperators)
+            || stream.match(wordOperators)) {
+            return 'operator';
+        }
+        if (stream.match(singleDelimiters)) {
+            return 'punctuation';
+        }
+
+        if (stream.match(constants)) {
+            return 'atom';
+        }
+
+        if (stream.match(keywords)) {
+            return 'keyword';
+        }
+
+        if (stream.match(identifiers)) {
+            return 'variable';
+        }
+
+        if (stream.match(properties)) {
+            return 'property';
+        }
+
+        // Handle non-detected items
+        stream.next();
+        return ERRORCLASS;
+    }
+
+    function tokenFactory(delimiter, outclass) {
+        var singleline = delimiter.length == 1;
+        return function(stream, state) {
+            while (!stream.eol()) {
+                stream.eatWhile(/[^'"\/\\]/);
+                if (stream.eat('\\')) {
+                    stream.next();
+                    if (singleline && stream.eol()) {
+                        return outclass;
+                    }
+                } else if (stream.match(delimiter)) {
+                    state.tokenize = tokenBase;
+                    return outclass;
+                } else {
+                    stream.eat(/['"\/]/);
+                }
+            }
+            if (singleline) {
+                if (conf.mode.singleLineStringErrors) {
+                    outclass = ERRORCLASS;
+                } else {
+                    state.tokenize = tokenBase;
+                }
+            }
+            return outclass;
+        };
+    }
+
+    function longComment(stream, state) {
+        while (!stream.eol()) {
+            stream.eatWhile(/[^#]/);
+            if (stream.match("###")) {
+                state.tokenize = tokenBase;
+                break;
+            }
+            stream.eatWhile("#");
+        }
+        return "comment";
+    }
+
+    function indent(stream, state, type) {
+        type = type || 'coffee';
+        var indentUnit = 0;
+        if (type === 'coffee') {
+            for (var i = 0; i < state.scopes.length; i++) {
+                if (state.scopes[i].type === 'coffee') {
+                    indentUnit = state.scopes[i].offset + conf.indentUnit;
+                    break;
+                }
+            }
+        } else {
+            indentUnit = stream.column() + stream.current().length;
+        }
+        state.scopes.unshift({
+            offset: indentUnit,
+            type: type
+        });
+    }
+
+    function dedent(stream, state) {
+        if (state.scopes.length == 1) return;
+        if (state.scopes[0].type === 'coffee') {
+            var _indent = stream.indentation();
+            var _indent_index = -1;
+            for (var i = 0; i < state.scopes.length; ++i) {
+                if (_indent === state.scopes[i].offset) {
+                    _indent_index = i;
+                    break;
+                }
+            }
+            if (_indent_index === -1) {
+                return true;
+            }
+            while (state.scopes[0].offset !== _indent) {
+                state.scopes.shift();
+            }
+            return false;
+        } else {
+            state.scopes.shift();
+            return false;
+        }
+    }
+
+    function tokenLexer(stream, state) {
+        var style = state.tokenize(stream, state);
+        var current = stream.current();
+
+        // Handle '.' connected identifiers
+        if (current === '.') {
+            style = state.tokenize(stream, state);
+            current = stream.current();
+            if (style === 'variable') {
+                return 'variable';
+            } else {
+                return ERRORCLASS;
+            }
+        }
+
+        // Handle scope changes.
+        if (current === 'return') {
+            state.dedent += 1;
+        }
+        if (((current === '->' || current === '=>') &&
+                  !state.lambda &&
+                  state.scopes[0].type == 'coffee' &&
+                  stream.peek() === '')
+               || style === 'indent') {
+            indent(stream, state);
+        }
+        var delimiter_index = '[({'.indexOf(current);
+        if (delimiter_index !== -1) {
+            indent(stream, state, '])}'.slice(delimiter_index, delimiter_index+1));
+        }
+        if (indentKeywords.exec(current)){
+            indent(stream, state);
+        }
+        if (current == 'then'){
+            dedent(stream, state);
+        }
+
+
+        if (style === 'dedent') {
+            if (dedent(stream, state)) {
+                return ERRORCLASS;
+            }
+        }
+        delimiter_index = '])}'.indexOf(current);
+        if (delimiter_index !== -1) {
+            if (dedent(stream, state)) {
+                return ERRORCLASS;
+            }
+        }
+        if (state.dedent > 0 && stream.eol() && state.scopes[0].type == 'coffee') {
+            if (state.scopes.length > 1) state.scopes.shift();
+            state.dedent -= 1;
+        }
+
+        return style;
+    }
+
+    var external = {
+        startState: function(basecolumn) {
+            return {
+              tokenize: tokenBase,
+              scopes: [{offset:basecolumn || 0, type:'coffee'}],
+              lastToken: null,
+              lambda: false,
+              dedent: 0
+          };
+        },
+
+        token: function(stream, state) {
+            var style = tokenLexer(stream, state);
+
+            state.lastToken = {style:style, content: stream.current()};
+
+            if (stream.eol() && stream.lambda) {
+                state.lambda = false;
+            }
+
+            return style;
+        },
+
+        indent: function(state) {
+            if (state.tokenize != tokenBase) {
+                return 0;
+            }
+
+            return state.scopes[0].offset;
+        },
+
+        lineComment: "#",
+        fold: "indent"
+    };
+    return external;
+});
+
+CodeMirror.defineMIME('text/x-coffeescript', 'coffeescript');
diff --git a/third-party/codemirror-3.15/mode/coffeescript/index.html b/third-party/codemirror-3.15/mode/coffeescript/index.html
new file mode 100644 (file)
index 0000000..ee72b8d
--- /dev/null
@@ -0,0 +1,728 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: CoffeeScript mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="coffeescript.js"></script>
+    <style>.CodeMirror {border-top: 1px solid silver; border-bottom: 1px solid silver;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: CoffeeScript mode</h1>
+    <form><textarea id="code" name="code">
+# CoffeeScript mode for CodeMirror
+# Copyright (c) 2011 Jeff Pickhardt, released under
+# the MIT License.
+#
+# Modified from the Python CodeMirror mode, which also is 
+# under the MIT License Copyright (c) 2010 Timothy Farrell.
+#
+# The following script, Underscore.coffee, is used to 
+# demonstrate CoffeeScript mode for CodeMirror.
+#
+# To download CoffeeScript mode for CodeMirror, go to:
+# https://github.com/pickhardt/coffeescript-codemirror-mode
+
+# **Underscore.coffee
+# (c) 2011 Jeremy Ashkenas, DocumentCloud Inc.**
+# Underscore is freely distributable under the terms of the
+# [MIT license](http://en.wikipedia.org/wiki/MIT_License).
+# Portions of Underscore are inspired by or borrowed from
+# [Prototype.js](http://prototypejs.org/api), Oliver Steele's
+# [Functional](http://osteele.com), and John Resig's
+# [Micro-Templating](http://ejohn.org).
+# For all details and documentation:
+# http://documentcloud.github.com/underscore/
+
+
+# Baseline setup
+# --------------
+
+# Establish the root object, `window` in the browser, or `global` on the server.
+root = this
+
+
+# Save the previous value of the `_` variable.
+previousUnderscore = root._
+
+### Multiline
+    comment
+###
+
+# Establish the object that gets thrown to break out of a loop iteration.
+# `StopIteration` is SOP on Mozilla.
+breaker = if typeof(StopIteration) is 'undefined' then '__break__' else StopIteration
+
+
+#### Docco style single line comment (title)
+
+
+# Helper function to escape **RegExp** contents, because JS doesn't have one.
+escapeRegExp = (string) -> string.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1')
+
+
+# Save bytes in the minified (but not gzipped) version:
+ArrayProto = Array.prototype
+ObjProto = Object.prototype
+
+
+# Create quick reference variables for speed access to core prototypes.
+slice = ArrayProto.slice
+unshift = ArrayProto.unshift
+toString = ObjProto.toString
+hasOwnProperty = ObjProto.hasOwnProperty
+propertyIsEnumerable = ObjProto.propertyIsEnumerable
+
+
+# All **ECMA5** native implementations we hope to use are declared here.
+nativeForEach = ArrayProto.forEach
+nativeMap = ArrayProto.map
+nativeReduce = ArrayProto.reduce
+nativeReduceRight = ArrayProto.reduceRight
+nativeFilter = ArrayProto.filter
+nativeEvery = ArrayProto.every
+nativeSome = ArrayProto.some
+nativeIndexOf = ArrayProto.indexOf
+nativeLastIndexOf = ArrayProto.lastIndexOf
+nativeIsArray = Array.isArray
+nativeKeys = Object.keys
+
+
+# Create a safe reference to the Underscore object for use below.
+_ = (obj) -> new wrapper(obj)
+
+
+# Export the Underscore object for **CommonJS**.
+if typeof(exports) != 'undefined' then exports._ = _
+
+
+# Export Underscore to global scope.
+root._ = _
+
+
+# Current version.
+_.VERSION = '1.1.0'
+
+
+# Collection Functions
+# --------------------
+
+# The cornerstone, an **each** implementation.
+# Handles objects implementing **forEach**, arrays, and raw objects.
+_.each = (obj, iterator, context) ->
+  try
+    if nativeForEach and obj.forEach is nativeForEach
+      obj.forEach iterator, context
+    else if _.isNumber obj.length
+      iterator.call context, obj[i], i, obj for i in [0...obj.length]
+    else
+      iterator.call context, val, key, obj for own key, val of obj
+  catch e
+    throw e if e isnt breaker
+  obj
+
+
+# Return the results of applying the iterator to each element. Use JavaScript
+# 1.6's version of **map**, if possible.
+_.map = (obj, iterator, context) ->
+  return obj.map(iterator, context) if nativeMap and obj.map is nativeMap
+  results = []
+  _.each obj, (value, index, list) ->
+    results.push iterator.call context, value, index, list
+  results
+
+
+# **Reduce** builds up a single result from a list of values. Also known as
+# **inject**, or **foldl**. Uses JavaScript 1.8's version of **reduce**, if possible.
+_.reduce = (obj, iterator, memo, context) ->
+  if nativeReduce and obj.reduce is nativeReduce
+    iterator = _.bind iterator, context if context
+    return obj.reduce iterator, memo
+  _.each obj, (value, index, list) ->
+    memo = iterator.call context, memo, value, index, list
+  memo
+
+
+# The right-associative version of **reduce**, also known as **foldr**. Uses
+# JavaScript 1.8's version of **reduceRight**, if available.
+_.reduceRight = (obj, iterator, memo, context) ->
+  if nativeReduceRight and obj.reduceRight is nativeReduceRight
+    iterator = _.bind iterator, context if context
+    return obj.reduceRight iterator, memo
+  reversed = _.clone(_.toArray(obj)).reverse()
+  _.reduce reversed, iterator, memo, context
+
+
+# Return the first value which passes a truth test.
+_.detect = (obj, iterator, context) ->
+  result = null
+  _.each obj, (value, index, list) ->
+    if iterator.call context, value, index, list
+      result = value
+      _.breakLoop()
+  result
+
+
+# Return all the elements that pass a truth test. Use JavaScript 1.6's
+# **filter**, if it exists.
+_.filter = (obj, iterator, context) ->
+  return obj.filter iterator, context if nativeFilter and obj.filter is nativeFilter
+  results = []
+  _.each obj, (value, index, list) ->
+    results.push value if iterator.call context, value, index, list
+  results
+
+
+# Return all the elements for which a truth test fails.
+_.reject = (obj, iterator, context) ->
+  results = []
+  _.each obj, (value, index, list) ->
+    results.push value if not iterator.call context, value, index, list
+  results
+
+
+# Determine whether all of the elements match a truth test. Delegate to
+# JavaScript 1.6's **every**, if it is present.
+_.every = (obj, iterator, context) ->
+  iterator ||= _.identity
+  return obj.every iterator, context if nativeEvery and obj.every is nativeEvery
+  result = true
+  _.each obj, (value, index, list) ->
+    _.breakLoop() unless (result = result and iterator.call(context, value, index, list))
+  result
+
+
+# Determine if at least one element in the object matches a truth test. Use
+# JavaScript 1.6's **some**, if it exists.
+_.some = (obj, iterator, context) ->
+  iterator ||= _.identity
+  return obj.some iterator, context if nativeSome and obj.some is nativeSome
+  result = false
+  _.each obj, (value, index, list) ->
+    _.breakLoop() if (result = iterator.call(context, value, index, list))
+  result
+
+
+# Determine if a given value is included in the array or object,
+# based on `===`.
+_.include = (obj, target) ->
+  return _.indexOf(obj, target) isnt -1 if nativeIndexOf and obj.indexOf is nativeIndexOf
+  return true for own key, val of obj when val is target
+  false
+
+
+# Invoke a method with arguments on every item in a collection.
+_.invoke = (obj, method) ->
+  args = _.rest arguments, 2
+  (if method then val[method] else val).apply(val, args) for val in obj
+
+
+# Convenience version of a common use case of **map**: fetching a property.
+_.pluck = (obj, key) ->
+  _.map(obj, (val) -> val[key])
+
+
+# Return the maximum item or (item-based computation).
+_.max = (obj, iterator, context) ->
+  return Math.max.apply(Math, obj) if not iterator and _.isArray(obj)
+  result = computed: -Infinity
+  _.each obj, (value, index, list) ->
+    computed = if iterator then iterator.call(context, value, index, list) else value
+    computed >= result.computed and (result = {value: value, computed: computed})
+  result.value
+
+
+# Return the minimum element (or element-based computation).
+_.min = (obj, iterator, context) ->
+  return Math.min.apply(Math, obj) if not iterator and _.isArray(obj)
+  result = computed: Infinity
+  _.each obj, (value, index, list) ->
+    computed = if iterator then iterator.call(context, value, index, list) else value
+    computed < result.computed and (result = {value: value, computed: computed})
+  result.value
+
+
+# Sort the object's values by a criterion produced by an iterator.
+_.sortBy = (obj, iterator, context) ->
+  _.pluck(((_.map obj, (value, index, list) ->
+    {value: value, criteria: iterator.call(context, value, index, list)}
+  ).sort((left, right) ->
+    a = left.criteria; b = right.criteria
+    if a < b then -1 else if a > b then 1 else 0
+  )), 'value')
+
+
+# Use a comparator function to figure out at what index an object should
+# be inserted so as to maintain order. Uses binary search.
+_.sortedIndex = (array, obj, iterator) ->
+  iterator ||= _.identity
+  low = 0
+  high = array.length
+  while low < high
+    mid = (low + high) >> 1
+    if iterator(array[mid]) < iterator(obj) then low = mid + 1 else high = mid
+  low
+
+
+# Convert anything iterable into a real, live array.
+_.toArray = (iterable) ->
+  return [] if (!iterable)
+  return iterable.toArray() if (iterable.toArray)
+  return iterable if (_.isArray(iterable))
+  return slice.call(iterable) if (_.isArguments(iterable))
+  _.values(iterable)
+
+
+# Return the number of elements in an object.
+_.size = (obj) -> _.toArray(obj).length
+
+
+# Array Functions
+# ---------------
+
+# Get the first element of an array. Passing `n` will return the first N
+# values in the array. Aliased as **head**. The `guard` check allows it to work
+# with **map**.
+_.first = (array, n, guard) ->
+  if n and not guard then slice.call(array, 0, n) else array[0]
+
+
+# Returns everything but the first entry of the array. Aliased as **tail**.
+# Especially useful on the arguments object. Passing an `index` will return
+# the rest of the values in the array from that index onward. The `guard`
+# check allows it to work with **map**.
+_.rest = (array, index, guard) ->
+  slice.call(array, if _.isUndefined(index) or guard then 1 else index)
+
+
+# Get the last element of an array.
+_.last = (array) -> array[array.length - 1]
+
+
+# Trim out all falsy values from an array.
+_.compact = (array) -> item for item in array when item
+
+
+# Return a completely flattened version of an array.
+_.flatten = (array) ->
+  _.reduce array, (memo, value) ->
+    return memo.concat(_.flatten(value)) if _.isArray value
+    memo.push value
+    memo
+  , []
+
+
+# Return a version of the array that does not contain the specified value(s).
+_.without = (array) ->
+  values = _.rest arguments
+  val for val in _.toArray(array) when not _.include values, val
+
+
+# Produce a duplicate-free version of the array. If the array has already
+# been sorted, you have the option of using a faster algorithm.
+_.uniq = (array, isSorted) ->
+  memo = []
+  for el, i in _.toArray array
+    memo.push el if i is 0 || (if isSorted is true then _.last(memo) isnt el else not _.include(memo, el))
+  memo
+
+
+# Produce an array that contains every item shared between all the
+# passed-in arrays.
+_.intersect = (array) ->
+  rest = _.rest arguments
+  _.select _.uniq(array), (item) ->
+    _.all rest, (other) ->
+      _.indexOf(other, item) >= 0
+
+
+# Zip together multiple lists into a single array -- elements that share
+# an index go together.
+_.zip = ->
+  length = _.max _.pluck arguments, 'length'
+  results = new Array length
+  for i in [0...length]
+    results[i] = _.pluck arguments, String i
+  results
+
+
+# If the browser doesn't supply us with **indexOf** (I'm looking at you, MSIE),
+# we need this function. Return the position of the first occurrence of an
+# item in an array, or -1 if the item is not included in the array.
+_.indexOf = (array, item) ->
+  return array.indexOf item if nativeIndexOf and array.indexOf is nativeIndexOf
+  i = 0; l = array.length
+  while l - i
+    if array[i] is item then return i else i++
+  -1
+
+
+# Provide JavaScript 1.6's **lastIndexOf**, delegating to the native function,
+# if possible.
+_.lastIndexOf = (array, item) ->
+  return array.lastIndexOf(item) if nativeLastIndexOf and array.lastIndexOf is nativeLastIndexOf
+  i = array.length
+  while i
+    if array[i] is item then return i else i--
+  -1
+
+
+# Generate an integer Array containing an arithmetic progression. A port of
+# [the native Python **range** function](http://docs.python.org/library/functions.html#range).
+_.range = (start, stop, step) ->
+  a = arguments
+  solo = a.length <= 1
+  i = start = if solo then 0 else a[0]
+  stop = if solo then a[0] else a[1]
+  step = a[2] or 1
+  len = Math.ceil((stop - start) / step)
+  return [] if len <= 0
+  range = new Array len
+  idx = 0
+  loop
+    return range if (if step > 0 then i - stop else stop - i) >= 0
+    range[idx] = i
+    idx++
+    i+= step
+
+
+# Function Functions
+# ------------------
+
+# Create a function bound to a given object (assigning `this`, and arguments,
+# optionally). Binding with arguments is also known as **curry**.
+_.bind = (func, obj) ->
+  args = _.rest arguments, 2
+  -> func.apply obj or root, args.concat arguments
+
+
+# Bind all of an object's methods to that object. Useful for ensuring that
+# all callbacks defined on an object belong to it.
+_.bindAll = (obj) ->
+  funcs = if arguments.length > 1 then _.rest(arguments) else _.functions(obj)
+  _.each funcs, (f) -> obj[f] = _.bind obj[f], obj
+  obj
+
+
+# Delays a function for the given number of milliseconds, and then calls
+# it with the arguments supplied.
+_.delay = (func, wait) ->
+  args = _.rest arguments, 2
+  setTimeout((-> func.apply(func, args)), wait)
+
+
+# Memoize an expensive function by storing its results.
+_.memoize = (func, hasher) ->
+  memo = {}
+  hasher or= _.identity
+  ->
+    key = hasher.apply this, arguments
+    return memo[key] if key of memo
+    memo[key] = func.apply this, arguments
+
+
+# Defers a function, scheduling it to run after the current call stack has
+# cleared.
+_.defer = (func) ->
+  _.delay.apply _, [func, 1].concat _.rest arguments
+
+
+# Returns the first function passed as an argument to the second,
+# allowing you to adjust arguments, run code before and after, and
+# conditionally execute the original function.
+_.wrap = (func, wrapper) ->
+  -> wrapper.apply wrapper, [func].concat arguments
+
+
+# Returns a function that is the composition of a list of functions, each
+# consuming the return value of the function that follows.
+_.compose = ->
+  funcs = arguments
+  ->
+    args = arguments
+    for i in [funcs.length - 1..0] by -1
+      args = [funcs[i].apply(this, args)]
+    args[0]
+
+
+# Object Functions
+# ----------------
+
+# Retrieve the names of an object's properties.
+_.keys = nativeKeys or (obj) ->
+  return _.range 0, obj.length if _.isArray(obj)
+  key for key, val of obj
+
+
+# Retrieve the values of an object's properties.
+_.values = (obj) ->
+  _.map obj, _.identity
+
+
+# Return a sorted list of the function names available in Underscore.
+_.functions = (obj) ->
+  _.filter(_.keys(obj), (key) -> _.isFunction(obj[key])).sort()
+
+
+# Extend a given object with all of the properties in a source object.
+_.extend = (obj) ->
+  for source in _.rest(arguments)
+    obj[key] = val for key, val of source
+  obj
+
+
+# Create a (shallow-cloned) duplicate of an object.
+_.clone = (obj) ->
+  return obj.slice 0 if _.isArray obj
+  _.extend {}, obj
+
+
+# Invokes interceptor with the obj, and then returns obj.
+# The primary purpose of this method is to "tap into" a method chain,
+# in order to perform operations on intermediate results within
+ the chain.
+_.tap = (obj, interceptor) ->
+  interceptor obj
+  obj
+
+
+# Perform a deep comparison to check if two objects are equal.
+_.isEqual = (a, b) ->
+  # Check object identity.
+  return true if a is b
+  # Different types?
+  atype = typeof(a); btype = typeof(b)
+  return false if atype isnt btype
+  # Basic equality test (watch out for coercions).
+  return true if `a == b`
+  # One is falsy and the other truthy.
+  return false if (!a and b) or (a and !b)
+  # One of them implements an `isEqual()`?
+  return a.isEqual(b) if a.isEqual
+  # Check dates' integer values.
+  return a.getTime() is b.getTime() if _.isDate(a) and _.isDate(b)
+  # Both are NaN?
+  return false if _.isNaN(a) and _.isNaN(b)
+  # Compare regular expressions.
+  if _.isRegExp(a) and _.isRegExp(b)
+    return a.source is b.source and
+           a.global is b.global and
+           a.ignoreCase is b.ignoreCase and
+           a.multiline is b.multiline
+  # If a is not an object by this point, we can't handle it.
+  return false if atype isnt 'object'
+  # Check for different array lengths before comparing contents.
+  return false if a.length and (a.length isnt b.length)
+  # Nothing else worked, deep compare the contents.
+  aKeys = _.keys(a); bKeys = _.keys(b)
+  # Different object sizes?
+  return false if aKeys.length isnt bKeys.length
+  # Recursive comparison of contents.
+  return false for key, val of a when !(key of b) or !_.isEqual(val, b[key])
+  true
+
+
+# Is a given array or object empty?
+_.isEmpty = (obj) ->
+  return obj.length is 0 if _.isArray(obj) or _.isString(obj)
+  return false for own key of obj
+  true
+
+
+# Is a given value a DOM element?
+_.isElement = (obj) -> obj and obj.nodeType is 1
+
+
+# Is a given value an array?
+_.isArray = nativeIsArray or (obj) -> !!(obj and obj.concat and obj.unshift and not obj.callee)
+
+
+# Is a given variable an arguments object?
+_.isArguments = (obj) -> obj and obj.callee
+
+
+# Is the given value a function?
+_.isFunction = (obj) -> !!(obj and obj.constructor and obj.call and obj.apply)
+
+
+# Is the given value a string?
+_.isString = (obj) -> !!(obj is '' or (obj and obj.charCodeAt and obj.substr))
+
+
+# Is a given value a number?
+_.isNumber = (obj) -> (obj is +obj) or toString.call(obj) is '[object Number]'
+
+
+# Is a given value a boolean?
+_.isBoolean = (obj) -> obj is true or obj is false
+
+
+# Is a given value a Date?
+_.isDate = (obj) -> !!(obj and obj.getTimezoneOffset and obj.setUTCFullYear)
+
+
+# Is the given value a regular expression?
+_.isRegExp = (obj) -> !!(obj and obj.exec and (obj.ignoreCase or obj.ignoreCase is false))
+
+
+# Is the given value NaN -- this one is interesting. `NaN != NaN`, and
+# `isNaN(undefined) == true`, so we make sure it's a number first.
+_.isNaN = (obj) -> _.isNumber(obj) and window.isNaN(obj)
+
+
+# Is a given value equal to null?
+_.isNull = (obj) -> obj is null
+
+
+# Is a given variable undefined?
+_.isUndefined = (obj) -> typeof obj is 'undefined'
+
+
+# Utility Functions
+# -----------------
+
+# Run Underscore.js in noConflict mode, returning the `_` variable to its
+# previous owner. Returns a reference to the Underscore object.
+_.noConflict = ->
+  root._ = previousUnderscore
+  this
+
+
+# Keep the identity function around for default iterators.
+_.identity = (value) -> value
+
+
+# Run a function `n` times.
+_.times = (n, iterator, context) ->
+  iterator.call context, i for i in [0...n]
+
+
+# Break out of the middle of an iteration.
+_.breakLoop = -> throw breaker
+
+
+# Add your own custom functions to the Underscore object, ensuring that
+# they're correctly added to the OOP wrapper as well.
+_.mixin = (obj) ->
+  for name in _.functions(obj)
+    addToWrapper name, _[name] = obj[name]
+
+
+# Generate a unique integer id (unique within the entire client session).
+# Useful for temporary DOM ids.
+idCounter = 0
+_.uniqueId = (prefix) ->
+  (prefix or '') + idCounter++
+
+
+# By default, Underscore uses **ERB**-style template delimiters, change the
+# following template settings to use alternative delimiters.
+_.templateSettings = {
+  start: '<%'
+  end: '%>'
+  interpolate: /<%=(.+?)%>/g
+}
+
+
+# JavaScript templating a-la **ERB**, pilfered from John Resig's
+# *Secrets of the JavaScript Ninja*, page 83.
+# Single-quote fix from Rick Strahl.
+# With alterations for arbitrary delimiters, and to preserve whitespace.
+_.template = (str, data) ->
+  c = _.templateSettings
+  endMatch = new RegExp("'(?=[^"+c.end.substr(0, 1)+"]*"+escapeRegExp(c.end)+")","g")
+  fn = new Function 'obj',
+    'var p=[],print=function(){p.push.apply(p,arguments);};' +
+    'with(obj||{}){p.push(\'' +
+    str.replace(/\r/g, '\\r')
+       .replace(/\n/g, '\\n')
+       .replace(/\t/g, '\\t')
+       .replace(endMatch,"���")
+       .split("'").join("\\'")
+       .split("���").join("'")
+       .replace(c.interpolate, "',$1,'")
+       .split(c.start).join("');")
+       .split(c.end).join("p.push('") +
+       "');}return p.join('');"
+  if data then fn(data) else fn
+
+
+# Aliases
+# -------
+
+_.forEach = _.each
+_.foldl = _.inject = _.reduce
+_.foldr = _.reduceRight
+_.select = _.filter
+_.all = _.every
+_.any = _.some
+_.contains = _.include
+_.head = _.first
+_.tail = _.rest
+_.methods = _.functions
+
+
+# Setup the OOP Wrapper
+# ---------------------
+
+# If Underscore is called as a function, it returns a wrapped object that
+# can be used OO-style. This wrapper holds altered versions of all the
+# underscore functions. Wrapped objects may be chained.
+wrapper = (obj) ->
+  this._wrapped = obj
+  this
+
+
+# Helper function to continue chaining intermediate results.
+result = (obj, chain) ->
+  if chain then _(obj).chain() else obj
+
+
+# A method to easily add functions to the OOP wrapper.
+addToWrapper = (name, func) ->
+  wrapper.prototype[name] = ->
+    args = _.toArray arguments
+    unshift.call args, this._wrapped
+    result func.apply(_, args), this._chain
+
+
+# Add all ofthe Underscore functions to the wrapper object.
+_.mixin _
+
+
+# Add all mutator Array functions to the wrapper.
+_.each ['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], (name) ->
+  method = Array.prototype[name]
+  wrapper.prototype[name] = ->
+    method.apply(this._wrapped, arguments)
+    result(this._wrapped, this._chain)
+
+
+# Add all accessor Array functions to the wrapper.
+_.each ['concat', 'join', 'slice'], (name) ->
+  method = Array.prototype[name]
+  wrapper.prototype[name] = ->
+    result(method.apply(this._wrapped, arguments), this._chain)
+
+
+# Start chaining a wrapped Underscore object.
+wrapper::chain = ->
+  this._chain = true
+  this
+
+
+# Extracts the result from a wrapped and chained object.
+wrapper::value = -> this._wrapped
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-coffeescript</code>.</p>
+
+    <p>The CoffeeScript mode was written by Jeff Pickhardt (<a href="LICENSE">license</a>).</p>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/commonlisp/commonlisp.js b/third-party/codemirror-3.15/mode/commonlisp/commonlisp.js
new file mode 100644 (file)
index 0000000..8fa08c8
--- /dev/null
@@ -0,0 +1,105 @@
+CodeMirror.defineMode("commonlisp", function (config) {
+  var assumeBody = /^with|^def|^do|^prog|case$|^cond$|bind$|when$|unless$/;
+  var numLiteral = /^(?:[+\-]?(?:\d+|\d*\.\d+)(?:[efd][+\-]?\d+)?|[+\-]?\d+(?:\/[+\-]?\d+)?|#b[+\-]?[01]+|#o[+\-]?[0-7]+|#x[+\-]?[\da-f]+)/;
+  var symbol = /[^\s'`,@()\[\]";]/;
+  var type;
+
+  function readSym(stream) {
+    var ch;
+    while (ch = stream.next()) {
+      if (ch == "\\") stream.next();
+      else if (!symbol.test(ch)) { stream.backUp(1); break; }
+    }
+    return stream.current();
+  }
+
+  function base(stream, state) {
+    if (stream.eatSpace()) {type = "ws"; return null;}
+    if (stream.match(numLiteral)) return "number";
+    var ch = stream.next();
+    if (ch == "\\") ch = stream.next();
+
+    if (ch == '"') return (state.tokenize = inString)(stream, state);
+    else if (ch == "(") { type = "open"; return "bracket"; }
+    else if (ch == ")" || ch == "]") { type = "close"; return "bracket"; }
+    else if (ch == ";") { stream.skipToEnd(); type = "ws"; return "comment"; }
+    else if (/['`,@]/.test(ch)) return null;
+    else if (ch == "|") {
+      if (stream.skipTo("|")) { stream.next(); return "symbol"; }
+      else { stream.skipToEnd(); return "error"; }
+    } else if (ch == "#") {
+      var ch = stream.next();
+      if (ch == "[") { type = "open"; return "bracket"; }
+      else if (/[+\-=\.']/.test(ch)) return null;
+      else if (/\d/.test(ch) && stream.match(/^\d*#/)) return null;
+      else if (ch == "|") return (state.tokenize = inComment)(stream, state);
+      else if (ch == ":") { readSym(stream); return "meta"; }
+      else return "error";
+    } else {
+      var name = readSym(stream);
+      if (name == ".") return null;
+      type = "symbol";
+      if (name == "nil" || name == "t") return "atom";
+      if (name.charAt(0) == ":") return "keyword";
+      if (name.charAt(0) == "&") return "variable-2";
+      return "variable";
+    }
+  }
+
+  function inString(stream, state) {
+    var escaped = false, next;
+    while (next = stream.next()) {
+      if (next == '"' && !escaped) { state.tokenize = base; break; }
+      escaped = !escaped && next == "\\";
+    }
+    return "string";
+  }
+
+  function inComment(stream, state) {
+    var next, last;
+    while (next = stream.next()) {
+      if (next == "#" && last == "|") { state.tokenize = base; break; }
+      last = next;
+    }
+    type = "ws";
+    return "comment";
+  }
+
+  return {
+    startState: function () {
+      return {ctx: {prev: null, start: 0, indentTo: 0}, tokenize: base};
+    },
+
+    token: function (stream, state) {
+      if (stream.sol() && typeof state.ctx.indentTo != "number")
+        state.ctx.indentTo = state.ctx.start + 1;
+
+      type = null;
+      var style = state.tokenize(stream, state);
+      if (type != "ws") {
+        if (state.ctx.indentTo == null) {
+          if (type == "symbol" && assumeBody.test(stream.current()))
+            state.ctx.indentTo = state.ctx.start + config.indentUnit;
+          else
+            state.ctx.indentTo = "next";
+        } else if (state.ctx.indentTo == "next") {
+          state.ctx.indentTo = stream.column();
+        }
+      }
+      if (type == "open") state.ctx = {prev: state.ctx, start: stream.column(), indentTo: null};
+      else if (type == "close") state.ctx = state.ctx.prev || state.ctx;
+      return style;
+    },
+
+    indent: function (state, _textAfter) {
+      var i = state.ctx.indentTo;
+      return typeof i == "number" ? i : state.ctx.start + 1;
+    },
+
+    lineComment: ";;",
+    blockCommentStart: "#|",
+    blockCommentEnd: "|#"
+  };
+});
+
+CodeMirror.defineMIME("text/x-common-lisp", "commonlisp");
diff --git a/third-party/codemirror-3.15/mode/commonlisp/index.html b/third-party/codemirror-3.15/mode/commonlisp/index.html
new file mode 100644 (file)
index 0000000..f9766a8
--- /dev/null
@@ -0,0 +1,165 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Common Lisp mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="commonlisp.js"></script>
+    <style>.CodeMirror {background: #f8f8f8;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Common Lisp mode</h1>
+    <form><textarea id="code" name="code">(in-package :cl-postgres)
+
+;; These are used to synthesize reader and writer names for integer
+;; reading/writing functions when the amount of bytes and the
+;; signedness is known. Both the macro that creates the functions and
+;; some macros that use them create names this way.
+(eval-when (:compile-toplevel :load-toplevel :execute)
+  (defun integer-reader-name (bytes signed)
+    (intern (with-standard-io-syntax
+              (format nil "~a~a~a~a" '#:read- (if signed "" '#:u) '#:int bytes))))
+  (defun integer-writer-name (bytes signed)
+    (intern (with-standard-io-syntax
+              (format nil "~a~a~a~a" '#:write- (if signed "" '#:u) '#:int bytes)))))
+
+(defmacro integer-reader (bytes)
+  "Create a function to read integers from a binary stream."
+  (let ((bits (* bytes 8)))
+    (labels ((return-form (signed)
+               (if signed
+                   `(if (logbitp ,(1- bits) result)
+                        (dpb result (byte ,(1- bits) 0) -1)
+                        result)
+                   `result))
+             (generate-reader (signed)
+               `(defun ,(integer-reader-name bytes signed) (socket)
+                  (declare (type stream socket)
+                           #.*optimize*)
+                  ,(if (= bytes 1)
+                       `(let ((result (the (unsigned-byte 8) (read-byte socket))))
+                          (declare (type (unsigned-byte 8) result))
+                          ,(return-form signed))
+                       `(let ((result 0))
+                          (declare (type (unsigned-byte ,bits) result))
+                          ,@(loop :for byte :from (1- bytes) :downto 0
+                                   :collect `(setf (ldb (byte 8 ,(* 8 byte)) result)
+                                                   (the (unsigned-byte 8) (read-byte socket))))
+                          ,(return-form signed))))))
+      `(progn
+;; This causes weird errors on SBCL in some circumstances. Disabled for now.
+;;         (declaim (inline ,(integer-reader-name bytes t)
+;;                          ,(integer-reader-name bytes nil)))
+         (declaim (ftype (function (t) (signed-byte ,bits))
+                         ,(integer-reader-name bytes t)))
+         ,(generate-reader t)
+         (declaim (ftype (function (t) (unsigned-byte ,bits))
+                         ,(integer-reader-name bytes nil)))
+         ,(generate-reader nil)))))
+
+(defmacro integer-writer (bytes)
+  "Create a function to write integers to a binary stream."
+  (let ((bits (* 8 bytes)))
+    `(progn
+      (declaim (inline ,(integer-writer-name bytes t)
+                       ,(integer-writer-name bytes nil)))
+      (defun ,(integer-writer-name bytes nil) (socket value)
+        (declare (type stream socket)
+                 (type (unsigned-byte ,bits) value)
+                 #.*optimize*)
+        ,@(if (= bytes 1)
+              `((write-byte value socket))
+              (loop :for byte :from (1- bytes) :downto 0
+                    :collect `(write-byte (ldb (byte 8 ,(* byte 8)) value)
+                               socket)))
+        (values))
+      (defun ,(integer-writer-name bytes t) (socket value)
+        (declare (type stream socket)
+                 (type (signed-byte ,bits) value)
+                 #.*optimize*)
+        ,@(if (= bytes 1)
+              `((write-byte (ldb (byte 8 0) value) socket))
+              (loop :for byte :from (1- bytes) :downto 0
+                    :collect `(write-byte (ldb (byte 8 ,(* byte 8)) value)
+                               socket)))
+        (values)))))
+
+;; All the instances of the above that we need.
+
+(integer-reader 1)
+(integer-reader 2)
+(integer-reader 4)
+(integer-reader 8)
+
+(integer-writer 1)
+(integer-writer 2)
+(integer-writer 4)
+
+(defun write-bytes (socket bytes)
+  "Write a byte-array to a stream."
+  (declare (type stream socket)
+           (type (simple-array (unsigned-byte 8)) bytes)
+           #.*optimize*)
+  (write-sequence bytes socket))
+
+(defun write-str (socket string)
+  "Write a null-terminated string to a stream \(encoding it when UTF-8
+support is enabled.)."
+  (declare (type stream socket)
+           (type string string)
+           #.*optimize*)
+  (enc-write-string string socket)
+  (write-uint1 socket 0))
+
+(declaim (ftype (function (t unsigned-byte)
+                          (simple-array (unsigned-byte 8) (*)))
+                read-bytes))
+(defun read-bytes (socket length)
+  "Read a byte array of the given length from a stream."
+  (declare (type stream socket)
+           (type fixnum length)
+           #.*optimize*)
+  (let ((result (make-array length :element-type '(unsigned-byte 8))))
+    (read-sequence result socket)
+    result))
+
+(declaim (ftype (function (t) string) read-str))
+(defun read-str (socket)
+  "Read a null-terminated string from a stream. Takes care of encoding
+when UTF-8 support is enabled."
+  (declare (type stream socket)
+           #.*optimize*)
+  (enc-read-string socket :null-terminated t))
+
+(defun skip-bytes (socket length)
+  "Skip a given number of bytes in a binary stream."
+  (declare (type stream socket)
+           (type (unsigned-byte 32) length)
+           #.*optimize*)
+  (dotimes (i length)
+    (read-byte socket)))
+
+(defun skip-str (socket)
+  "Skip a null-terminated string."
+  (declare (type stream socket)
+           #.*optimize*)
+  (loop :for char :of-type fixnum = (read-byte socket)
+        :until (zerop char)))
+
+(defun ensure-socket-is-closed (socket &amp;key abort)
+  (when (open-stream-p socket)
+    (handler-case
+        (close socket :abort abort)
+      (error (error)
+        (warn "Ignoring the error which happened while trying to close PostgreSQL socket: ~A" error)))))
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {lineNumbers: true});
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-common-lisp</code>.</p>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/css/css.js b/third-party/codemirror-3.15/mode/css/css.js
new file mode 100644 (file)
index 0000000..bdcd500
--- /dev/null
@@ -0,0 +1,623 @@
+CodeMirror.defineMode("css", function(config) {
+  return CodeMirror.getMode(config, "text/css");
+});
+
+CodeMirror.defineMode("css-base", function(config, parserConfig) {
+  "use strict";
+
+  var indentUnit = config.indentUnit,
+      hooks = parserConfig.hooks || {},
+      atMediaTypes = parserConfig.atMediaTypes || {},
+      atMediaFeatures = parserConfig.atMediaFeatures || {},
+      propertyKeywords = parserConfig.propertyKeywords || {},
+      colorKeywords = parserConfig.colorKeywords || {},
+      valueKeywords = parserConfig.valueKeywords || {},
+      allowNested = !!parserConfig.allowNested,
+      type = null;
+
+  function ret(style, tp) { type = tp; return style; }
+
+  function tokenBase(stream, state) {
+    var ch = stream.next();
+    if (hooks[ch]) {
+      // result[0] is style and result[1] is type
+      var result = hooks[ch](stream, state);
+      if (result !== false) return result;
+    }
+    if (ch == "@") {stream.eatWhile(/[\w\\\-]/); return ret("def", stream.current());}
+    else if (ch == "=") ret(null, "compare");
+    else if ((ch == "~" || ch == "|") && stream.eat("=")) return ret(null, "compare");
+    else if (ch == "\"" || ch == "'") {
+      state.tokenize = tokenString(ch);
+      return state.tokenize(stream, state);
+    }
+    else if (ch == "#") {
+      stream.eatWhile(/[\w\\\-]/);
+      return ret("atom", "hash");
+    }
+    else if (ch == "!") {
+      stream.match(/^\s*\w*/);
+      return ret("keyword", "important");
+    }
+    else if (/\d/.test(ch)) {
+      stream.eatWhile(/[\w.%]/);
+      return ret("number", "unit");
+    }
+    else if (ch === "-") {
+      if (/\d/.test(stream.peek())) {
+        stream.eatWhile(/[\w.%]/);
+        return ret("number", "unit");
+      } else if (stream.match(/^[^-]+-/)) {
+        return ret("meta", "meta");
+      }
+    }
+    else if (/[,+>*\/]/.test(ch)) {
+      return ret(null, "select-op");
+    }
+    else if (ch == "." && stream.match(/^-?[_a-z][_a-z0-9-]*/i)) {
+      return ret("qualifier", "qualifier");
+    }
+    else if (ch == ":") {
+      return ret("operator", ch);
+    }
+    else if (/[;{}\[\]\(\)]/.test(ch)) {
+      return ret(null, ch);
+    }
+    else if (ch == "u" && stream.match("rl(")) {
+      stream.backUp(1);
+      state.tokenize = tokenParenthesized;
+      return ret("property", "variable");
+    }
+    else {
+      stream.eatWhile(/[\w\\\-]/);
+      return ret("property", "variable");
+    }
+  }
+
+  function tokenString(quote, nonInclusive) {
+    return function(stream, state) {
+      var escaped = false, ch;
+      while ((ch = stream.next()) != null) {
+        if (ch == quote && !escaped)
+          break;
+        escaped = !escaped && ch == "\\";
+      }
+      if (!escaped) {
+        if (nonInclusive) stream.backUp(1);
+        state.tokenize = tokenBase;
+      }
+      return ret("string", "string");
+    };
+  }
+
+  function tokenParenthesized(stream, state) {
+    stream.next(); // Must be '('
+    if (!stream.match(/\s*[\"\']/, false))
+      state.tokenize = tokenString(")", true);
+    else
+      state.tokenize = tokenBase;
+    return ret(null, "(");
+  }
+
+  return {
+    startState: function(base) {
+      return {tokenize: tokenBase,
+              baseIndent: base || 0,
+              stack: [],
+              lastToken: null};
+    },
+
+    token: function(stream, state) {
+
+      // Use these terms when applicable (see http://www.xanthir.com/blog/b4E50)
+      //
+      // rule** or **ruleset:
+      // A selector + braces combo, or an at-rule.
+      //
+      // declaration block:
+      // A sequence of declarations.
+      //
+      // declaration:
+      // A property + colon + value combo.
+      //
+      // property value:
+      // The entire value of a property.
+      //
+      // component value:
+      // A single piece of a property value. Like the 5px in
+      // text-shadow: 0 0 5px blue;. Can also refer to things that are
+      // multiple terms, like the 1-4 terms that make up the background-size
+      // portion of the background shorthand.
+      //
+      // term:
+      // The basic unit of author-facing CSS, like a single number (5),
+      // dimension (5px), string ("foo"), or function. Officially defined
+      //  by the CSS 2.1 grammar (look for the 'term' production)
+      //
+      //
+      // simple selector:
+      // A single atomic selector, like a type selector, an attr selector, a
+      // class selector, etc.
+      //
+      // compound selector:
+      // One or more simple selectors without a combinator. div.example is
+      // compound, div > .example is not.
+      //
+      // complex selector:
+      // One or more compound selectors chained with combinators.
+      //
+      // combinator:
+      // The parts of selectors that express relationships. There are four
+      // currently - the space (descendant combinator), the greater-than
+      // bracket (child combinator), the plus sign (next sibling combinator),
+      // and the tilda (following sibling combinator).
+      //
+      // sequence of selectors:
+      // One or more of the named type of selector chained with commas.
+
+      state.tokenize = state.tokenize || tokenBase;
+      if (state.tokenize == tokenBase && stream.eatSpace()) return null;
+      var style = state.tokenize(stream, state);
+      if (style && typeof style != "string") style = ret(style[0], style[1]);
+
+      // Changing style returned based on context
+      var context = state.stack[state.stack.length-1];
+      if (style == "variable") {
+        if (type == "variable-definition") state.stack.push("propertyValue");
+        return state.lastToken = "variable-2";
+      } else if (style == "property") {
+        var word = stream.current().toLowerCase();
+        if (context == "propertyValue") {
+          if (valueKeywords.hasOwnProperty(word)) {
+            style = "string-2";
+          } else if (colorKeywords.hasOwnProperty(word)) {
+            style = "keyword";
+          } else {
+            style = "variable-2";
+          }
+        } else if (context == "rule") {
+          if (!propertyKeywords.hasOwnProperty(word)) {
+            style += " error";
+          }
+        } else if (context == "block") {
+          // if a value is present in both property, value, or color, the order
+          // of preference is property -> color -> value
+          if (propertyKeywords.hasOwnProperty(word)) {
+            style = "property";
+          } else if (colorKeywords.hasOwnProperty(word)) {
+            style = "keyword";
+          } else if (valueKeywords.hasOwnProperty(word)) {
+            style = "string-2";
+          } else {
+            style = "tag";
+          }
+        } else if (!context || context == "@media{") {
+          style = "tag";
+        } else if (context == "@media") {
+          if (atMediaTypes[stream.current()]) {
+            style = "attribute"; // Known attribute
+          } else if (/^(only|not)$/.test(word)) {
+            style = "keyword";
+          } else if (word == "and") {
+            style = "error"; // "and" is only allowed in @mediaType
+          } else if (atMediaFeatures.hasOwnProperty(word)) {
+            style = "error"; // Known property, should be in @mediaType(
+          } else {
+            // Unknown, expecting keyword or attribute, assuming attribute
+            style = "attribute error";
+          }
+        } else if (context == "@mediaType") {
+          if (atMediaTypes.hasOwnProperty(word)) {
+            style = "attribute";
+          } else if (word == "and") {
+            style = "operator";
+          } else if (/^(only|not)$/.test(word)) {
+            style = "error"; // Only allowed in @media
+          } else {
+            // Unknown attribute or property, but expecting property (preceded
+            // by "and"). Should be in parentheses
+            style = "error";
+          }
+        } else if (context == "@mediaType(") {
+          if (propertyKeywords.hasOwnProperty(word)) {
+            // do nothing, remains "property"
+          } else if (atMediaTypes.hasOwnProperty(word)) {
+            style = "error"; // Known property, should be in parentheses
+          } else if (word == "and") {
+            style = "operator";
+          } else if (/^(only|not)$/.test(word)) {
+            style = "error"; // Only allowed in @media
+          } else {
+            style += " error";
+          }
+        } else if (context == "@import") {
+          style = "tag";
+        } else {
+          style = "error";
+        }
+      } else if (style == "atom") {
+        if(!context || context == "@media{" || context == "block") {
+          style = "builtin";
+        } else if (context == "propertyValue") {
+          if (!/^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/.test(stream.current())) {
+            style += " error";
+          }
+        } else {
+          style = "error";
+        }
+      } else if (context == "@media" && type == "{") {
+        style = "error";
+      }
+
+      // Push/pop context stack
+      if (type == "{") {
+        if (context == "@media" || context == "@mediaType") {
+          state.stack[state.stack.length-1] = "@media{";
+        }
+        else {
+          var newContext = allowNested ? "block" : "rule";
+          state.stack.push(newContext);
+        }
+      }
+      else if (type == "}") {
+        if (context == "interpolation") style = "operator";
+        state.stack.pop();
+        if (context == "propertyValue") state.stack.pop();
+      }
+      else if (type == "interpolation") state.stack.push("interpolation");
+      else if (type == "@media") state.stack.push("@media");
+      else if (type == "@import") state.stack.push("@import");
+      else if (context == "@media" && /\b(keyword|attribute)\b/.test(style))
+        state.stack[state.stack.length-1] = "@mediaType";
+      else if (context == "@mediaType" && stream.current() == ",")
+        state.stack[state.stack.length-1] = "@media";
+      else if (type == "(") {
+        if (context == "@media" || context == "@mediaType") {
+          // Make sure @mediaType is used to avoid error on {
+          state.stack[state.stack.length-1] = "@mediaType";
+          state.stack.push("@mediaType(");
+        }
+      }
+      else if (type == ")") {
+        if (context == "propertyValue" && state.stack[state.stack.length-2] == "@mediaType(") {
+          // In @mediaType( without closing ; after propertyValue
+          state.stack.pop();
+          state.stack.pop();
+        }
+        else if (context == "@mediaType(") {
+          state.stack.pop();
+        }
+      }
+      else if (type == ":" && state.lastToken == "property") state.stack.push("propertyValue");
+      else if (context == "propertyValue" && type == ";") state.stack.pop();
+      else if (context == "@import" && type == ";") state.stack.pop();
+
+      return state.lastToken = style;
+    },
+
+    indent: function(state, textAfter) {
+      var n = state.stack.length;
+      if (/^\}/.test(textAfter))
+        n -= state.stack[n-1] == "propertyValue" ? 2 : 1;
+      return state.baseIndent + n * indentUnit;
+    },
+
+    electricChars: "}",
+    blockCommentStart: "/*",
+    blockCommentEnd: "*/",
+    fold: "brace"
+  };
+});
+
+(function() {
+  function keySet(array) {
+    var keys = {};
+    for (var i = 0; i < array.length; ++i) {
+      keys[array[i]] = true;
+    }
+    return keys;
+  }
+
+  var atMediaTypes = keySet([
+    "all", "aural", "braille", "handheld", "print", "projection", "screen",
+    "tty", "tv", "embossed"
+  ]);
+
+  var atMediaFeatures = keySet([
+    "width", "min-width", "max-width", "height", "min-height", "max-height",
+    "device-width", "min-device-width", "max-device-width", "device-height",
+    "min-device-height", "max-device-height", "aspect-ratio",
+    "min-aspect-ratio", "max-aspect-ratio", "device-aspect-ratio",
+    "min-device-aspect-ratio", "max-device-aspect-ratio", "color", "min-color",
+    "max-color", "color-index", "min-color-index", "max-color-index",
+    "monochrome", "min-monochrome", "max-monochrome", "resolution",
+    "min-resolution", "max-resolution", "scan", "grid"
+  ]);
+
+  var propertyKeywords = keySet([
+    "align-content", "align-items", "align-self", "alignment-adjust",
+    "alignment-baseline", "anchor-point", "animation", "animation-delay",
+    "animation-direction", "animation-duration", "animation-iteration-count",
+    "animation-name", "animation-play-state", "animation-timing-function",
+    "appearance", "azimuth", "backface-visibility", "background",
+    "background-attachment", "background-clip", "background-color",
+    "background-image", "background-origin", "background-position",
+    "background-repeat", "background-size", "baseline-shift", "binding",
+    "bleed", "bookmark-label", "bookmark-level", "bookmark-state",
+    "bookmark-target", "border", "border-bottom", "border-bottom-color",
+    "border-bottom-left-radius", "border-bottom-right-radius",
+    "border-bottom-style", "border-bottom-width", "border-collapse",
+    "border-color", "border-image", "border-image-outset",
+    "border-image-repeat", "border-image-slice", "border-image-source",
+    "border-image-width", "border-left", "border-left-color",
+    "border-left-style", "border-left-width", "border-radius", "border-right",
+    "border-right-color", "border-right-style", "border-right-width",
+    "border-spacing", "border-style", "border-top", "border-top-color",
+    "border-top-left-radius", "border-top-right-radius", "border-top-style",
+    "border-top-width", "border-width", "bottom", "box-decoration-break",
+    "box-shadow", "box-sizing", "break-after", "break-before", "break-inside",
+    "caption-side", "clear", "clip", "color", "color-profile", "column-count",
+    "column-fill", "column-gap", "column-rule", "column-rule-color",
+    "column-rule-style", "column-rule-width", "column-span", "column-width",
+    "columns", "content", "counter-increment", "counter-reset", "crop", "cue",
+    "cue-after", "cue-before", "cursor", "direction", "display",
+    "dominant-baseline", "drop-initial-after-adjust",
+    "drop-initial-after-align", "drop-initial-before-adjust",
+    "drop-initial-before-align", "drop-initial-size", "drop-initial-value",
+    "elevation", "empty-cells", "fit", "fit-position", "flex", "flex-basis",
+    "flex-direction", "flex-flow", "flex-grow", "flex-shrink", "flex-wrap",
+    "float", "float-offset", "font", "font-feature-settings", "font-family",
+    "font-kerning", "font-language-override", "font-size", "font-size-adjust",
+    "font-stretch", "font-style", "font-synthesis", "font-variant",
+    "font-variant-alternates", "font-variant-caps", "font-variant-east-asian",
+    "font-variant-ligatures", "font-variant-numeric", "font-variant-position",
+    "font-weight", "grid-cell", "grid-column", "grid-column-align",
+    "grid-column-sizing", "grid-column-span", "grid-columns", "grid-flow",
+    "grid-row", "grid-row-align", "grid-row-sizing", "grid-row-span",
+    "grid-rows", "grid-template", "hanging-punctuation", "height", "hyphens",
+    "icon", "image-orientation", "image-rendering", "image-resolution",
+    "inline-box-align", "justify-content", "left", "letter-spacing",
+    "line-break", "line-height", "line-stacking", "line-stacking-ruby",
+    "line-stacking-shift", "line-stacking-strategy", "list-style",
+    "list-style-image", "list-style-position", "list-style-type", "margin",
+    "margin-bottom", "margin-left", "margin-right", "margin-top",
+    "marker-offset", "marks", "marquee-direction", "marquee-loop",
+    "marquee-play-count", "marquee-speed", "marquee-style", "max-height",
+    "max-width", "min-height", "min-width", "move-to", "nav-down", "nav-index",
+    "nav-left", "nav-right", "nav-up", "opacity", "order", "orphans", "outline",
+    "outline-color", "outline-offset", "outline-style", "outline-width",
+    "overflow", "overflow-style", "overflow-wrap", "overflow-x", "overflow-y",
+    "padding", "padding-bottom", "padding-left", "padding-right", "padding-top",
+    "page", "page-break-after", "page-break-before", "page-break-inside",
+    "page-policy", "pause", "pause-after", "pause-before", "perspective",
+    "perspective-origin", "pitch", "pitch-range", "play-during", "position",
+    "presentation-level", "punctuation-trim", "quotes", "rendering-intent",
+    "resize", "rest", "rest-after", "rest-before", "richness", "right",
+    "rotation", "rotation-point", "ruby-align", "ruby-overhang",
+    "ruby-position", "ruby-span", "size", "speak", "speak-as", "speak-header",
+    "speak-numeral", "speak-punctuation", "speech-rate", "stress", "string-set",
+    "tab-size", "table-layout", "target", "target-name", "target-new",
+    "target-position", "text-align", "text-align-last", "text-decoration",
+    "text-decoration-color", "text-decoration-line", "text-decoration-skip",
+    "text-decoration-style", "text-emphasis", "text-emphasis-color",
+    "text-emphasis-position", "text-emphasis-style", "text-height",
+    "text-indent", "text-justify", "text-outline", "text-overflow", "text-shadow",
+    "text-size-adjust", "text-space-collapse", "text-transform", "text-underline-position",
+    "text-wrap", "top", "transform", "transform-origin", "transform-style",
+    "transition", "transition-delay", "transition-duration",
+    "transition-property", "transition-timing-function", "unicode-bidi",
+    "vertical-align", "visibility", "voice-balance", "voice-duration",
+    "voice-family", "voice-pitch", "voice-range", "voice-rate", "voice-stress",
+    "voice-volume", "volume", "white-space", "widows", "width", "word-break",
+    "word-spacing", "word-wrap", "z-index", "zoom",
+    // SVG-specific
+    "clip-path", "clip-rule", "mask", "enable-background", "filter", "flood-color",
+    "flood-opacity", "lighting-color", "stop-color", "stop-opacity", "pointer-events",
+    "color-interpolation", "color-interpolation-filters", "color-profile",
+    "color-rendering", "fill", "fill-opacity", "fill-rule", "image-rendering",
+    "marker", "marker-end", "marker-mid", "marker-start", "shape-rendering", "stroke",
+    "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin",
+    "stroke-miterlimit", "stroke-opacity", "stroke-width", "text-rendering",
+    "baseline-shift", "dominant-baseline", "glyph-orientation-horizontal",
+    "glyph-orientation-vertical", "kerning", "text-anchor", "writing-mode"
+  ]);
+
+  var colorKeywords = keySet([
+    "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige",
+    "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown",
+    "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue",
+    "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod",
+    "darkgray", "darkgreen", "darkkhaki", "darkmagenta", "darkolivegreen",
+    "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen",
+    "darkslateblue", "darkslategray", "darkturquoise", "darkviolet",
+    "deeppink", "deepskyblue", "dimgray", "dodgerblue", "firebrick",
+    "floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite",
+    "gold", "goldenrod", "gray", "green", "greenyellow", "honeydew",
+    "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender",
+    "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral",
+    "lightcyan", "lightgoldenrodyellow", "lightgray", "lightgreen", "lightpink",
+    "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray",
+    "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta",
+    "maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple",
+    "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise",
+    "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin",
+    "navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered",
+    "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred",
+    "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue",
+    "purple", "red", "rosybrown", "royalblue", "saddlebrown", "salmon",
+    "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue",
+    "slateblue", "slategray", "snow", "springgreen", "steelblue", "tan",
+    "teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white",
+    "whitesmoke", "yellow", "yellowgreen"
+  ]);
+
+  var valueKeywords = keySet([
+    "above", "absolute", "activeborder", "activecaption", "afar",
+    "after-white-space", "ahead", "alias", "all", "all-scroll", "alternate",
+    "always", "amharic", "amharic-abegede", "antialiased", "appworkspace",
+    "arabic-indic", "armenian", "asterisks", "auto", "avoid", "background",
+    "backwards", "baseline", "below", "bidi-override", "binary", "bengali",
+    "blink", "block", "block-axis", "bold", "bolder", "border", "border-box",
+    "both", "bottom", "break-all", "break-word", "button", "button-bevel",
+    "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "cambodian",
+    "capitalize", "caps-lock-indicator", "caption", "captiontext", "caret",
+    "cell", "center", "checkbox", "circle", "cjk-earthly-branch",
+    "cjk-heavenly-stem", "cjk-ideographic", "clear", "clip", "close-quote",
+    "col-resize", "collapse", "compact", "condensed", "contain", "content",
+    "content-box", "context-menu", "continuous", "copy", "cover", "crop",
+    "cross", "crosshair", "currentcolor", "cursive", "dashed", "decimal",
+    "decimal-leading-zero", "default", "default-button", "destination-atop",
+    "destination-in", "destination-out", "destination-over", "devanagari",
+    "disc", "discard", "document", "dot-dash", "dot-dot-dash", "dotted",
+    "double", "down", "e-resize", "ease", "ease-in", "ease-in-out", "ease-out",
+    "element", "ellipsis", "embed", "end", "ethiopic", "ethiopic-abegede",
+    "ethiopic-abegede-am-et", "ethiopic-abegede-gez", "ethiopic-abegede-ti-er",
+    "ethiopic-abegede-ti-et", "ethiopic-halehame-aa-er",
+    "ethiopic-halehame-aa-et", "ethiopic-halehame-am-et",
+    "ethiopic-halehame-gez", "ethiopic-halehame-om-et",
+    "ethiopic-halehame-sid-et", "ethiopic-halehame-so-et",
+    "ethiopic-halehame-ti-er", "ethiopic-halehame-ti-et",
+    "ethiopic-halehame-tig", "ew-resize", "expanded", "extra-condensed",
+    "extra-expanded", "fantasy", "fast", "fill", "fixed", "flat", "footnotes",
+    "forwards", "from", "geometricPrecision", "georgian", "graytext", "groove",
+    "gujarati", "gurmukhi", "hand", "hangul", "hangul-consonant", "hebrew",
+    "help", "hidden", "hide", "higher", "highlight", "highlighttext",
+    "hiragana", "hiragana-iroha", "horizontal", "hsl", "hsla", "icon", "ignore",
+    "inactiveborder", "inactivecaption", "inactivecaptiontext", "infinite",
+    "infobackground", "infotext", "inherit", "initial", "inline", "inline-axis",
+    "inline-block", "inline-table", "inset", "inside", "intrinsic", "invert",
+    "italic", "justify", "kannada", "katakana", "katakana-iroha", "khmer",
+    "landscape", "lao", "large", "larger", "left", "level", "lighter",
+    "line-through", "linear", "lines", "list-item", "listbox", "listitem",
+    "local", "logical", "loud", "lower", "lower-alpha", "lower-armenian",
+    "lower-greek", "lower-hexadecimal", "lower-latin", "lower-norwegian",
+    "lower-roman", "lowercase", "ltr", "malayalam", "match",
+    "media-controls-background", "media-current-time-display",
+    "media-fullscreen-button", "media-mute-button", "media-play-button",
+    "media-return-to-realtime-button", "media-rewind-button",
+    "media-seek-back-button", "media-seek-forward-button", "media-slider",
+    "media-sliderthumb", "media-time-remaining-display", "media-volume-slider",
+    "media-volume-slider-container", "media-volume-sliderthumb", "medium",
+    "menu", "menulist", "menulist-button", "menulist-text",
+    "menulist-textfield", "menutext", "message-box", "middle", "min-intrinsic",
+    "mix", "mongolian", "monospace", "move", "multiple", "myanmar", "n-resize",
+    "narrower", "ne-resize", "nesw-resize", "no-close-quote", "no-drop",
+    "no-open-quote", "no-repeat", "none", "normal", "not-allowed", "nowrap",
+    "ns-resize", "nw-resize", "nwse-resize", "oblique", "octal", "open-quote",
+    "optimizeLegibility", "optimizeSpeed", "oriya", "oromo", "outset",
+    "outside", "overlay", "overline", "padding", "padding-box", "painted",
+    "paused", "persian", "plus-darker", "plus-lighter", "pointer", "portrait",
+    "pre", "pre-line", "pre-wrap", "preserve-3d", "progress", "push-button",
+    "radio", "read-only", "read-write", "read-write-plaintext-only", "relative",
+    "repeat", "repeat-x", "repeat-y", "reset", "reverse", "rgb", "rgba",
+    "ridge", "right", "round", "row-resize", "rtl", "run-in", "running",
+    "s-resize", "sans-serif", "scroll", "scrollbar", "se-resize", "searchfield",
+    "searchfield-cancel-button", "searchfield-decoration",
+    "searchfield-results-button", "searchfield-results-decoration",
+    "semi-condensed", "semi-expanded", "separate", "serif", "show", "sidama",
+    "single", "skip-white-space", "slide", "slider-horizontal",
+    "slider-vertical", "sliderthumb-horizontal", "sliderthumb-vertical", "slow",
+    "small", "small-caps", "small-caption", "smaller", "solid", "somali",
+    "source-atop", "source-in", "source-out", "source-over", "space", "square",
+    "square-button", "start", "static", "status-bar", "stretch", "stroke",
+    "sub", "subpixel-antialiased", "super", "sw-resize", "table",
+    "table-caption", "table-cell", "table-column", "table-column-group",
+    "table-footer-group", "table-header-group", "table-row", "table-row-group",
+    "telugu", "text", "text-bottom", "text-top", "textarea", "textfield", "thai",
+    "thick", "thin", "threeddarkshadow", "threedface", "threedhighlight",
+    "threedlightshadow", "threedshadow", "tibetan", "tigre", "tigrinya-er",
+    "tigrinya-er-abegede", "tigrinya-et", "tigrinya-et-abegede", "to", "top",
+    "transparent", "ultra-condensed", "ultra-expanded", "underline", "up",
+    "upper-alpha", "upper-armenian", "upper-greek", "upper-hexadecimal",
+    "upper-latin", "upper-norwegian", "upper-roman", "uppercase", "urdu", "url",
+    "vertical", "vertical-text", "visible", "visibleFill", "visiblePainted",
+    "visibleStroke", "visual", "w-resize", "wait", "wave", "wider",
+    "window", "windowframe", "windowtext", "x-large", "x-small", "xor",
+    "xx-large", "xx-small"
+  ]);
+
+  function tokenCComment(stream, state) {
+    var maybeEnd = false, ch;
+    while ((ch = stream.next()) != null) {
+      if (maybeEnd && ch == "/") {
+        state.tokenize = null;
+        break;
+      }
+      maybeEnd = (ch == "*");
+    }
+    return ["comment", "comment"];
+  }
+
+  CodeMirror.defineMIME("text/css", {
+    atMediaTypes: atMediaTypes,
+    atMediaFeatures: atMediaFeatures,
+    propertyKeywords: propertyKeywords,
+    colorKeywords: colorKeywords,
+    valueKeywords: valueKeywords,
+    hooks: {
+      "<": function(stream, state) {
+        function tokenSGMLComment(stream, state) {
+          var dashes = 0, ch;
+          while ((ch = stream.next()) != null) {
+            if (dashes >= 2 && ch == ">") {
+              state.tokenize = null;
+              break;
+            }
+            dashes = (ch == "-") ? dashes + 1 : 0;
+          }
+          return ["comment", "comment"];
+        }
+        if (stream.eat("!")) {
+          state.tokenize = tokenSGMLComment;
+          return tokenSGMLComment(stream, state);
+        }
+      },
+      "/": function(stream, state) {
+        if (stream.eat("*")) {
+          state.tokenize = tokenCComment;
+          return tokenCComment(stream, state);
+        }
+        return false;
+      }
+    },
+    name: "css-base"
+  });
+
+  CodeMirror.defineMIME("text/x-scss", {
+    atMediaTypes: atMediaTypes,
+    atMediaFeatures: atMediaFeatures,
+    propertyKeywords: propertyKeywords,
+    colorKeywords: colorKeywords,
+    valueKeywords: valueKeywords,
+    allowNested: true,
+    hooks: {
+      "$": function(stream) {
+        stream.match(/^[\w-]+/);
+        if (stream.peek() == ":") {
+          return ["variable", "variable-definition"];
+        }
+        return ["variable", "variable"];
+      },
+      "/": function(stream, state) {
+        if (stream.eat("/")) {
+          stream.skipToEnd();
+          return ["comment", "comment"];
+        } else if (stream.eat("*")) {
+          state.tokenize = tokenCComment;
+          return tokenCComment(stream, state);
+        } else {
+          return ["operator", "operator"];
+        }
+      },
+      "#": function(stream) {
+        if (stream.eat("{")) {
+          return ["operator", "interpolation"];
+        } else {
+          stream.eatWhile(/[\w\\\-]/);
+          return ["atom", "hash"];
+        }
+      }
+    },
+    name: "css-base"
+  });
+})();
diff --git a/third-party/codemirror-3.15/mode/css/index.html b/third-party/codemirror-3.15/mode/css/index.html
new file mode 100644 (file)
index 0000000..ae2c3bf
--- /dev/null
@@ -0,0 +1,58 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: CSS mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="css.js"></script>
+    <style>.CodeMirror {background: #f8f8f8;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: CSS mode</h1>
+    <form><textarea id="code" name="code">
+/* Some example CSS */
+
+@import url("something.css");
+
+body {
+  margin: 0;
+  padding: 3em 6em;
+  font-family: tahoma, arial, sans-serif;
+  color: #000;
+}
+
+#navigation a {
+  font-weight: bold;
+  text-decoration: none !important;
+}
+
+h1 {
+  font-size: 2.5em;
+}
+
+h2 {
+  font-size: 1.7em;
+}
+
+h1:before, h2:before {
+  content: "::";
+}
+
+code {
+  font-family: courier, monospace;
+  font-size: 80%;
+  color: #418A8A;
+}
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/css</code>.</p>
+
+    <p><strong>Parsing/Highlighting Tests:</strong> <a href="../../test/index.html#css_*">normal</a>,  <a href="../../test/index.html#verbose,css_*">verbose</a>.</p>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/css/scss.html b/third-party/codemirror-3.15/mode/css/scss.html
new file mode 100644 (file)
index 0000000..b90cbe8
--- /dev/null
@@ -0,0 +1,145 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: SCSS mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="css.js"></script>
+    <style>.CodeMirror {background: #f8f8f8;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: SCSS mode</h1>
+    <form><textarea id="code" name="code">
+/* Some example SCSS */
+
+@import "compass/css3";
+$variable: #333;
+
+$blue: #3bbfce;
+$margin: 16px;
+
+.content-navigation {
+  #nested {
+    background-color: black;
+  }
+  border-color: $blue;
+  color:
+    darken($blue, 9%);
+}
+
+.border {
+  padding: $margin / 2;
+  margin: $margin / 2;
+  border-color: $blue;
+}
+
+@mixin table-base {
+  th {
+    text-align: center;
+    font-weight: bold;
+  }
+  td, th {padding: 2px}
+}
+
+table.hl {
+  margin: 2em 0;
+  td.ln {
+    text-align: right;
+  }
+}
+
+li {
+  font: {
+    family: serif;
+    weight: bold;
+    size: 1.2em;
+  }
+}
+
+@mixin left($dist) {
+  float: left;
+  margin-left: $dist;
+}
+
+#data {
+  @include left(10px);
+  @include table-base;
+}
+
+.source {
+  @include flow-into(target);
+  border: 10px solid green;
+  margin: 20px;
+  width: 200px; }
+
+.new-container {
+  @include flow-from(target);
+  border: 10px solid red;
+  margin: 20px;
+  width: 200px; }
+
+body {
+  margin: 0;
+  padding: 3em 6em;
+  font-family: tahoma, arial, sans-serif;
+  color: #000;
+}
+
+@mixin yellow() {
+  background: yellow;
+}
+
+.big {
+  font-size: 14px;
+}
+
+.nested {
+  @include border-radius(3px);
+  @extend .big;
+  p {
+    background: whitesmoke;
+    a {
+      color: red;
+    }
+  }
+}
+
+#navigation a {
+  font-weight: bold;
+  text-decoration: none !important;
+}
+
+h1 {
+  font-size: 2.5em;
+}
+
+h2 {
+  font-size: 1.7em;
+}
+
+h1:before, h2:before {
+  content: "::";
+}
+
+code {
+  font-family: courier, monospace;
+  font-size: 80%;
+  color: #418A8A;
+}
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        matchBrackets: true,
+        mode: "text/x-scss"
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/scss</code>.</p>
+
+    <p><strong>Parsing/Highlighting Tests:</strong> <a href="../../test/index.html#scss_*">normal</a>,  <a href="../../test/index.html#verbose,scss_*">verbose</a>.</p>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/css/scss_test.js b/third-party/codemirror-3.15/mode/css/scss_test.js
new file mode 100644 (file)
index 0000000..3644f63
--- /dev/null
@@ -0,0 +1,80 @@
+(function() {
+  var mode = CodeMirror.getMode({tabSize: 4}, "text/x-scss");
+  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1), "scss"); }
+
+  MT('url_with_quotation',
+    "[tag foo] { [property background][operator :][string-2 url]([string test.jpg]) }");
+
+  MT('url_with_double_quotes',
+    "[tag foo] { [property background][operator :][string-2 url]([string \"test.jpg\"]) }");
+
+  MT('url_with_single_quotes',
+    "[tag foo] { [property background][operator :][string-2 url]([string \'test.jpg\']) }");
+
+  MT('string',
+    "[def @import] [string \"compass/css3\"]");
+
+  MT('important_keyword',
+    "[tag foo] { [property background][operator :][string-2 url]([string \'test.jpg\']) [keyword !important] }");
+
+  MT('variable',
+    "[variable-2 $blue][operator :][atom #333]");
+
+  MT('variable_as_attribute',
+    "[tag foo] { [property color][operator :][variable-2 $blue] }");
+
+  MT('numbers',
+    "[tag foo] { [property padding][operator :][number 10px] [number 10] [number 10em] [number 8in] }");
+
+  MT('number_percentage',
+    "[tag foo] { [property width][operator :][number 80%] }");
+
+  MT('selector',
+    "[builtin #hello][qualifier .world]{}");
+
+  MT('singleline_comment',
+    "[comment // this is a comment]");
+
+  MT('multiline_comment',
+    "[comment /*foobar*/]");
+
+  MT('attribute_with_hyphen',
+    "[tag foo] { [property font-size][operator :][number 10px] }");
+
+  MT('string_after_attribute',
+    "[tag foo] { [property content][operator :][string \"::\"] }");
+
+  MT('directives',
+    "[def @include] [qualifier .mixin]");
+
+  MT('basic_structure',
+    "[tag p] { [property background][operator :][keyword red]; }");
+
+  MT('nested_structure',
+    "[tag p] { [tag a] { [property color][operator :][keyword red]; } }");
+
+  MT('mixin',
+    "[def @mixin] [tag table-base] {}");
+
+  MT('number_without_semicolon',
+    "[tag p] {[property width][operator :][number 12]}",
+    "[tag a] {[property color][operator :][keyword red];}");
+
+  MT('atom_in_nested_block',
+    "[tag p] { [tag a] { [property color][operator :][atom #000]; } }");
+
+  MT('interpolation_in_property',
+    "[tag foo] { [operator #{][variable-2 $hello][operator }:][number 2]; }");
+
+  MT('interpolation_in_selector',
+    "[tag foo][operator #{][variable-2 $hello][operator }] { [property color][operator :][atom #000]; }");
+
+  MT('interpolation_error',
+    "[tag foo][operator #{][error foo][operator }] { [property color][operator :][atom #000]; }");
+
+  MT("divide_operator",
+    "[tag foo] { [property width][operator :][number 4] [operator /] [number 2] }");
+
+  MT('nested_structure_with_id_selector',
+    "[tag p] { [builtin #hello] { [property color][operator :][keyword red]; } }");
+})();
diff --git a/third-party/codemirror-3.15/mode/css/test.js b/third-party/codemirror-3.15/mode/css/test.js
new file mode 100644 (file)
index 0000000..13fc04c
--- /dev/null
@@ -0,0 +1,126 @@
+(function() {
+  var mode = CodeMirror.getMode({tabSize: 4}, "css");
+  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }
+
+  // Requires at least one media query
+  MT("atMediaEmpty",
+     "[def @media] [error {] }");
+
+  MT("atMediaMultiple",
+     "[def @media] [keyword not] [attribute screen] [operator and] ([property color]), [keyword not] [attribute print] [operator and] ([property color]) { }");
+
+  MT("atMediaCheckStack",
+     "[def @media] [attribute screen] { } [tag foo] { }");
+
+  MT("atMediaCheckStack",
+     "[def @media] [attribute screen] ([property color]) { } [tag foo] { }");
+
+  MT("atMediaPropertyOnly",
+     "[def @media] ([property color]) { } [tag foo] { }");
+
+  MT("atMediaCheckStackInvalidAttribute",
+     "[def @media] [attribute&error foobarhello] { [tag foo] { } }");
+
+  MT("atMediaCheckStackInvalidAttribute",
+     "[def @media] [attribute&error foobarhello] { } [tag foo] { }");
+
+  // Error, because "and" is only allowed immediately preceding a media expression
+  MT("atMediaInvalidAttribute",
+     "[def @media] [attribute&error foobarhello] { }");
+
+  // Error, because "and" is only allowed immediately preceding a media expression
+  MT("atMediaInvalidAnd",
+     "[def @media] [error and] [attribute screen] { }");
+
+  // Error, because "not" is only allowed as the first item in each media query
+  MT("atMediaInvalidNot",
+     "[def @media] [attribute screen] [error not] ([error not]) { }");
+
+  // Error, because "only" is only allowed as the first item in each media query
+  MT("atMediaInvalidOnly",
+     "[def @media] [attribute screen] [error only] ([error only]) { }");
+
+  // Error, because "foobarhello" is neither a known type or property, but
+  // property was expected (after "and"), and it should be in parenthese.
+  MT("atMediaUnknownType",
+     "[def @media] [attribute screen] [operator and] [error foobarhello] { }");
+
+  // Error, because "color" is not a known type, but is a known property, and
+  // should be in parentheses.
+  MT("atMediaInvalidType",
+     "[def @media] [attribute screen] [operator and] [error color] { }");
+
+  // Error, because "print" is not a known property, but is a known type,
+  // and should not be in parenthese.
+  MT("atMediaInvalidProperty",
+     "[def @media] [attribute screen] [operator and] ([error print]) { }");
+
+  // Soft error, because "foobarhello" is not a known property or type.
+  MT("atMediaUnknownProperty",
+     "[def @media] [attribute screen] [operator and] ([property&error foobarhello]) { }");
+
+  // Make sure nesting works with media queries
+  MT("atMediaMaxWidthNested",
+     "[def @media] [attribute screen] [operator and] ([property max-width][operator :] [number 25px]) { [tag foo] { } }");
+
+  MT("tagSelector",
+     "[tag foo] { }");
+
+  MT("classSelector",
+     "[qualifier .foo-bar_hello] { }");
+
+  MT("idSelector",
+     "[builtin #foo] { [error #foo] }");
+
+  MT("tagSelectorUnclosed",
+     "[tag foo] { [property margin][operator :] [number 0] } [tag bar] { }");
+
+  MT("tagStringNoQuotes",
+     "[tag foo] { [property font-family][operator :] [variable-2 hello] [variable-2 world]; }");
+
+  MT("tagStringDouble",
+     "[tag foo] { [property font-family][operator :] [string \"hello world\"]; }");
+
+  MT("tagStringSingle",
+     "[tag foo] { [property font-family][operator :] [string 'hello world']; }");
+
+  MT("tagColorKeyword",
+     "[tag foo] {" +
+       "[property color][operator :] [keyword black];" +
+       "[property color][operator :] [keyword navy];" +
+       "[property color][operator :] [keyword yellow];" +
+       "}");
+
+  MT("tagColorHex3",
+     "[tag foo] { [property background][operator :] [atom #fff]; }");
+
+  MT("tagColorHex6",
+     "[tag foo] { [property background][operator :] [atom #ffffff]; }");
+
+  MT("tagColorHex4",
+     "[tag foo] { [property background][operator :] [atom&error #ffff]; }");
+
+  MT("tagColorHexInvalid",
+     "[tag foo] { [property background][operator :] [atom&error #ffg]; }");
+
+  MT("tagNegativeNumber",
+     "[tag foo] { [property margin][operator :] [number -5px]; }");
+
+  MT("tagPositiveNumber",
+     "[tag foo] { [property padding][operator :] [number 5px]; }");
+
+  MT("tagVendor",
+     "[tag foo] { [meta -foo-][property box-sizing][operator :] [meta -foo-][string-2 border-box]; }");
+
+  MT("tagBogusProperty",
+     "[tag foo] { [property&error barhelloworld][operator :] [number 0]; }");
+
+  MT("tagTwoProperties",
+     "[tag foo] { [property margin][operator :] [number 0]; [property padding][operator :] [number 0]; }");
+
+  MT("tagTwoPropertiesURL",
+     "[tag foo] { [property background][operator :] [string-2 url]([string //example.com/foo.png]); [property padding][operator :] [number 0]; }");
+
+  MT("commentSGML",
+     "[comment <!--comment-->]");
+})();
diff --git a/third-party/codemirror-3.15/mode/d/d.js b/third-party/codemirror-3.15/mode/d/d.js
new file mode 100755 (executable)
index 0000000..ab345f1
--- /dev/null
@@ -0,0 +1,205 @@
+CodeMirror.defineMode("d", function(config, parserConfig) {
+  var indentUnit = config.indentUnit,
+      statementIndentUnit = parserConfig.statementIndentUnit || indentUnit,
+      keywords = parserConfig.keywords || {},
+      builtin = parserConfig.builtin || {},
+      blockKeywords = parserConfig.blockKeywords || {},
+      atoms = parserConfig.atoms || {},
+      hooks = parserConfig.hooks || {},
+      multiLineStrings = parserConfig.multiLineStrings;
+  var isOperatorChar = /[+\-*&%=<>!?|\/]/;
+
+  var curPunc;
+
+  function tokenBase(stream, state) {
+    var ch = stream.next();
+    if (hooks[ch]) {
+      var result = hooks[ch](stream, state);
+      if (result !== false) return result;
+    }
+    if (ch == '"' || ch == "'" || ch == "`") {
+      state.tokenize = tokenString(ch);
+      return state.tokenize(stream, state);
+    }
+    if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
+      curPunc = ch;
+      return null;
+    }
+    if (/\d/.test(ch)) {
+      stream.eatWhile(/[\w\.]/);
+      return "number";
+    }
+    if (ch == "/") {
+      if (stream.eat("+")) {
+        state.tokenize = tokenComment;
+        return tokenNestedComment(stream, state);
+      }
+      if (stream.eat("*")) {
+        state.tokenize = tokenComment;
+        return tokenComment(stream, state);
+      }
+      if (stream.eat("/")) {
+        stream.skipToEnd();
+        return "comment";
+      }
+    }
+    if (isOperatorChar.test(ch)) {
+      stream.eatWhile(isOperatorChar);
+      return "operator";
+    }
+    stream.eatWhile(/[\w\$_]/);
+    var cur = stream.current();
+    if (keywords.propertyIsEnumerable(cur)) {
+      if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
+      return "keyword";
+    }
+    if (builtin.propertyIsEnumerable(cur)) {
+      if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
+      return "builtin";
+    }
+    if (atoms.propertyIsEnumerable(cur)) return "atom";
+    return "variable";
+  }
+
+  function tokenString(quote) {
+    return function(stream, state) {
+      var escaped = false, next, end = false;
+      while ((next = stream.next()) != null) {
+        if (next == quote && !escaped) {end = true; break;}
+        escaped = !escaped && next == "\\";
+      }
+      if (end || !(escaped || multiLineStrings))
+        state.tokenize = null;
+      return "string";
+    };
+  }
+
+  function tokenComment(stream, state) {
+    var maybeEnd = false, ch;
+    while (ch = stream.next()) {
+      if (ch == "/" && maybeEnd) {
+        state.tokenize = null;
+        break;
+      }
+      maybeEnd = (ch == "*");
+    }
+    return "comment";
+  }
+
+  function tokenNestedComment(stream, state) {
+    var maybeEnd = false, ch;
+    while (ch = stream.next()) {
+      if (ch == "/" && maybeEnd) {
+        state.tokenize = null;
+        break;
+      }
+      maybeEnd = (ch == "+");
+    }
+    return "comment";
+  }
+
+  function Context(indented, column, type, align, prev) {
+    this.indented = indented;
+    this.column = column;
+    this.type = type;
+    this.align = align;
+    this.prev = prev;
+  }
+  function pushContext(state, col, type) {
+    var indent = state.indented;
+    if (state.context && state.context.type == "statement")
+      indent = state.context.indented;
+    return state.context = new Context(indent, col, type, null, state.context);
+  }
+  function popContext(state) {
+    var t = state.context.type;
+    if (t == ")" || t == "]" || t == "}")
+      state.indented = state.context.indented;
+    return state.context = state.context.prev;
+  }
+
+  // Interface
+
+  return {
+    startState: function(basecolumn) {
+      return {
+        tokenize: null,
+        context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
+        indented: 0,
+        startOfLine: true
+      };
+    },
+
+    token: function(stream, state) {
+      var ctx = state.context;
+      if (stream.sol()) {
+        if (ctx.align == null) ctx.align = false;
+        state.indented = stream.indentation();
+        state.startOfLine = true;
+      }
+      if (stream.eatSpace()) return null;
+      curPunc = null;
+      var style = (state.tokenize || tokenBase)(stream, state);
+      if (style == "comment" || style == "meta") return style;
+      if (ctx.align == null) ctx.align = true;
+
+      if ((curPunc == ";" || curPunc == ":" || curPunc == ",") && ctx.type == "statement") popContext(state);
+      else if (curPunc == "{") pushContext(state, stream.column(), "}");
+      else if (curPunc == "[") pushContext(state, stream.column(), "]");
+      else if (curPunc == "(") pushContext(state, stream.column(), ")");
+      else if (curPunc == "}") {
+        while (ctx.type == "statement") ctx = popContext(state);
+        if (ctx.type == "}") ctx = popContext(state);
+        while (ctx.type == "statement") ctx = popContext(state);
+      }
+      else if (curPunc == ctx.type) popContext(state);
+      else if (((ctx.type == "}" || ctx.type == "top") && curPunc != ';') || (ctx.type == "statement" && curPunc == "newstatement"))
+        pushContext(state, stream.column(), "statement");
+      state.startOfLine = false;
+      return style;
+    },
+
+    indent: function(state, textAfter) {
+      if (state.tokenize != tokenBase && state.tokenize != null) return CodeMirror.Pass;
+      var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
+      if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev;
+      var closing = firstChar == ctx.type;
+      if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit);
+      else if (ctx.align) return ctx.column + (closing ? 0 : 1);
+      else return ctx.indented + (closing ? 0 : indentUnit);
+    },
+
+    electricChars: "{}"
+  };
+});
+
+(function() {
+  function words(str) {
+    var obj = {}, words = str.split(" ");
+    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
+    return obj;
+  }
+
+  var blockKeywords = "body catch class do else enum for foreach foreach_reverse if in interface mixin " +
+                      "out scope struct switch try union unittest version while with";
+
+  CodeMirror.defineMIME("text/x-d", {
+    name: "d",
+    keywords: words("abstract alias align asm assert auto break case cast cdouble cent cfloat const continue " +
+                    "debug default delegate delete deprecated export extern final finally function goto immutable " +
+                    "import inout invariant is lazy macro module new nothrow override package pragma private " +
+                    "protected public pure ref return shared short static super synchronized template this " +
+                    "throw typedef typeid typeof volatile __FILE__ __LINE__ __gshared __traits __vector __parameters " +
+                    blockKeywords),
+    blockKeywords: words(blockKeywords),
+    builtin: words("bool byte char creal dchar double float idouble ifloat int ireal long real short ubyte " +
+                   "ucent uint ulong ushort wchar wstring void size_t sizediff_t"),
+    atoms: words("exit failure success true false null"),
+    hooks: {
+      "@": function(stream, _state) {
+        stream.eatWhile(/[\w\$_]/);
+        return "meta";
+      }
+    }
+  });
+}());
diff --git a/third-party/codemirror-3.15/mode/d/index.html b/third-party/codemirror-3.15/mode/d/index.html
new file mode 100755 (executable)
index 0000000..1333272
--- /dev/null
@@ -0,0 +1,262 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: D mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../../addon/edit/matchbrackets.js"></script>
+    <script src="d.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style>.CodeMirror {border: 2px inset #dee;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: D mode</h1>
+
+<form><textarea id="code" name="code">
+/* D demo code // copied from phobos/sd/metastrings.d */
+// Written in the D programming language.
+
+/**
+Templates with which to do compile-time manipulation of strings.
+
+Macros:
+ WIKI = Phobos/StdMetastrings
+
+Copyright: Copyright Digital Mars 2007 - 2009.
+License:   <a href="http://www.boost.org/LICENSE_1_0.txt">Boost License 1.0</a>.
+Authors:   $(WEB digitalmars.com, Walter Bright),
+           Don Clugston
+Source:    $(PHOBOSSRC std/_metastrings.d)
+*/
+/*
+         Copyright Digital Mars 2007 - 2009.
+Distributed under the Boost Software License, Version 1.0.
+   (See accompanying file LICENSE_1_0.txt or copy at
+         http://www.boost.org/LICENSE_1_0.txt)
+ */
+module std.metastrings;
+
+/**
+Formats constants into a string at compile time.  Analogous to $(XREF
+string,format).
+
+Parameters:
+
+A = tuple of constants, which can be strings, characters, or integral
+    values.
+
+Formats:
+ *    The formats supported are %s for strings, and %%
+ *    for the % character.
+Example:
+---
+import std.metastrings;
+import std.stdio;
+
+void main()
+{
+  string s = Format!("Arg %s = %s", "foo", 27);
+  writefln(s); // "Arg foo = 27"
+}
+ * ---
+ */
+
+template Format(A...)
+{
+    static if (A.length == 0)
+        enum Format = "";
+    else static if (is(typeof(A[0]) : const(char)[]))
+        enum Format = FormatString!(A[0], A[1..$]);
+    else
+        enum Format = toStringNow!(A[0]) ~ Format!(A[1..$]);
+}
+
+template FormatString(const(char)[] F, A...)
+{
+    static if (F.length == 0)
+        enum FormatString = Format!(A);
+    else static if (F.length == 1)
+        enum FormatString = F[0] ~ Format!(A);
+    else static if (F[0..2] == "%s")
+        enum FormatString
+            = toStringNow!(A[0]) ~ FormatString!(F[2..$],A[1..$]);
+    else static if (F[0..2] == "%%")
+        enum FormatString = "%" ~ FormatString!(F[2..$],A);
+    else
+    {
+        static assert(F[0] != '%', "unrecognized format %" ~ F[1]);
+        enum FormatString = F[0] ~ FormatString!(F[1..$],A);
+    }
+}
+
+unittest
+{
+    auto s = Format!("hel%slo", "world", -138, 'c', true);
+    assert(s == "helworldlo-138ctrue", "[" ~ s ~ "]");
+}
+
+/**
+ * Convert constant argument to a string.
+ */
+
+template toStringNow(ulong v)
+{
+    static if (v < 10)
+        enum toStringNow = "" ~ cast(char)(v + '0');
+    else
+        enum toStringNow = toStringNow!(v / 10) ~ toStringNow!(v % 10);
+}
+
+unittest
+{
+    static assert(toStringNow!(1uL << 62) == "4611686018427387904");
+}
+
+/// ditto
+template toStringNow(long v)
+{
+    static if (v < 0)
+        enum toStringNow = "-" ~ toStringNow!(cast(ulong) -v);
+    else
+        enum toStringNow = toStringNow!(cast(ulong) v);
+}
+
+unittest
+{
+    static assert(toStringNow!(0x100000000) == "4294967296");
+    static assert(toStringNow!(-138L) == "-138");
+}
+
+/// ditto
+template toStringNow(uint U)
+{
+    enum toStringNow = toStringNow!(cast(ulong)U);
+}
+
+/// ditto
+template toStringNow(int I)
+{
+    enum toStringNow = toStringNow!(cast(long)I);
+}
+
+/// ditto
+template toStringNow(bool B)
+{
+    enum toStringNow = B ? "true" : "false";
+}
+
+/// ditto
+template toStringNow(string S)
+{
+    enum toStringNow = S;
+}
+
+/// ditto
+template toStringNow(char C)
+{
+    enum toStringNow = "" ~ C;
+}
+
+
+/********
+ * Parse unsigned integer literal from the start of string s.
+ * returns:
+ *    .value = the integer literal as a string,
+ *    .rest = the string following the integer literal
+ * Otherwise:
+ *    .value = null,
+ *    .rest = s
+ */
+
+template parseUinteger(const(char)[] s)
+{
+    static if (s.length == 0)
+    {
+        enum value = "";
+        enum rest = "";
+    }
+    else static if (s[0] >= '0' && s[0] <= '9')
+    {
+        enum value = s[0] ~ parseUinteger!(s[1..$]).value;
+        enum rest = parseUinteger!(s[1..$]).rest;
+    }
+    else
+    {
+        enum value = "";
+        enum rest = s;
+    }
+}
+
+/********
+Parse integer literal optionally preceded by $(D '-') from the start
+of string $(D s).
+
+Returns:
+   .value = the integer literal as a string,
+   .rest = the string following the integer literal
+
+Otherwise:
+   .value = null,
+   .rest = s
+*/
+
+template parseInteger(const(char)[] s)
+{
+    static if (s.length == 0)
+    {
+        enum value = "";
+        enum rest = "";
+    }
+    else static if (s[0] >= '0' && s[0] <= '9')
+    {
+        enum value = s[0] ~ parseUinteger!(s[1..$]).value;
+        enum rest = parseUinteger!(s[1..$]).rest;
+    }
+    else static if (s.length >= 2 &&
+            s[0] == '-' && s[1] >= '0' && s[1] <= '9')
+    {
+        enum value = s[0..2] ~ parseUinteger!(s[2..$]).value;
+        enum rest = parseUinteger!(s[2..$]).rest;
+    }
+    else
+    {
+        enum value = "";
+        enum rest = s;
+    }
+}
+
+unittest
+{
+    assert(parseUinteger!("1234abc").value == "1234");
+    assert(parseUinteger!("1234abc").rest == "abc");
+    assert(parseInteger!("-1234abc").value == "-1234");
+    assert(parseInteger!("-1234abc").rest == "abc");
+}
+
+/**
+Deprecated aliases held for backward compatibility.
+*/
+deprecated alias toStringNow ToString;
+/// Ditto
+deprecated alias parseUinteger ParseUinteger;
+/// Ditto
+deprecated alias parseUinteger ParseInteger;
+
+</textarea></form>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        matchBrackets: true,
+        indentUnit: 4,
+        mode: "text/x-d"
+      });
+    </script>
+
+    <p>Simple mode that handle D-Syntax (<a href="http://www.dlang.org">DLang Homepage</a>).</p>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-d</code>
+    .</p>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/diff/diff.js b/third-party/codemirror-3.15/mode/diff/diff.js
new file mode 100644 (file)
index 0000000..9a0d90e
--- /dev/null
@@ -0,0 +1,32 @@
+CodeMirror.defineMode("diff", function() {
+
+  var TOKEN_NAMES = {
+    '+': 'positive',
+    '-': 'negative',
+    '@': 'meta'
+  };
+
+  return {
+    token: function(stream) {
+      var tw_pos = stream.string.search(/[\t ]+?$/);
+
+      if (!stream.sol() || tw_pos === 0) {
+        stream.skipToEnd();
+        return ("error " + (
+          TOKEN_NAMES[stream.string.charAt(0)] || '')).replace(/ $/, '');
+      }
+
+      var token_name = TOKEN_NAMES[stream.peek()] || stream.skipToEnd();
+
+      if (tw_pos === -1) {
+        stream.skipToEnd();
+      } else {
+        stream.pos = tw_pos;
+      }
+
+      return token_name;
+    }
+  };
+});
+
+CodeMirror.defineMIME("text/x-diff", "diff");
diff --git a/third-party/codemirror-3.15/mode/diff/index.html b/third-party/codemirror-3.15/mode/diff/index.html
new file mode 100644 (file)
index 0000000..5560252
--- /dev/null
@@ -0,0 +1,105 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Diff mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="diff.js"></script>
+    <style>
+      .CodeMirror {border-top: 1px solid #ddd; border-bottom: 1px solid #ddd;}
+      span.cm-meta {color: #a0b !important;}
+      span.cm-error { background-color: black; opacity: 0.4;}
+      span.cm-error.cm-string { background-color: red; }
+      span.cm-error.cm-tag { background-color: #2b2; }
+    </style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Diff mode</h1>
+    <form><textarea id="code" name="code">
+diff --git a/index.html b/index.html
+index c1d9156..7764744 100644
+--- a/index.html
++++ b/index.html
+@@ -95,7 +95,8 @@ StringStream.prototype = {
+     <script>
+       var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+         lineNumbers: true,
+-        autoMatchBrackets: true
++        autoMatchBrackets: true,
++      onGutterClick: function(x){console.log(x);}
+       });
+     </script>
+   </body>
+diff --git a/lib/codemirror.js b/lib/codemirror.js
+index 04646a9..9a39cc7 100644
+--- a/lib/codemirror.js
++++ b/lib/codemirror.js
+@@ -399,10 +399,16 @@ var CodeMirror = (function() {
+     }
+     function onMouseDown(e) {
+-      var start = posFromMouse(e), last = start;    
++      var start = posFromMouse(e), last = start, target = e.target();
+       if (!start) return;
+       setCursor(start.line, start.ch, false);
+       if (e.button() != 1) return;
++      if (target.parentNode == gutter) {    
++        if (options.onGutterClick)
++          options.onGutterClick(indexOf(gutter.childNodes, target) + showingFrom);
++        return;
++      }
++
+       if (!focused) onFocus();
+       e.stop();
+@@ -808,7 +814,7 @@ var CodeMirror = (function() {
+       for (var i = showingFrom; i < showingTo; ++i) {
+         var marker = lines[i].gutterMarker;
+         if (marker) html.push('<div class="' + marker.style + '">' + htmlEscape(marker.text) + '</div>');
+-        else html.push("<div>" + (options.lineNumbers ? i + 1 : "\u00a0") + "</div>");
++        else html.push("<div>" + (options.lineNumbers ? i + options.firstLineNumber : "\u00a0") + "</div>");
+       }
+       gutter.style.display = "none"; // TODO test whether this actually helps
+       gutter.innerHTML = html.join("");
+@@ -1371,10 +1377,8 @@ var CodeMirror = (function() {
+         if (option == "parser") setParser(value);
+         else if (option === "lineNumbers") setLineNumbers(value);
+         else if (option === "gutter") setGutter(value);
+-        else if (option === "readOnly") options.readOnly = value;
+-        else if (option === "indentUnit") {options.indentUnit = indentUnit = value; setParser(options.parser);}
+-        else if (/^(?:enterMode|tabMode|indentWithTabs|readOnly|autoMatchBrackets|undoDepth)$/.test(option)) options[option] = value;
+-        else throw new Error("Can't set option " + option);
++        else if (option === "indentUnit") {options.indentUnit = value; setParser(options.parser);}
++        else options[option] = value;
+       },
+       cursorCoords: cursorCoords,
+       undo: operation(undo),
+@@ -1402,7 +1406,8 @@ var CodeMirror = (function() {
+       replaceRange: operation(replaceRange),
+       operation: function(f){return operation(f)();},
+-      refresh: function(){updateDisplay([{from: 0, to: lines.length}]);}
++      refresh: function(){updateDisplay([{from: 0, to: lines.length}]);},
++      getInputField: function(){return input;}
+     };
+     return instance;
+   }
+@@ -1420,6 +1425,7 @@ var CodeMirror = (function() {
+     readOnly: false,
+     onChange: null,
+     onCursorActivity: null,
++    onGutterClick: null,
+     autoMatchBrackets: false,
+     workTime: 200,
+     workDelay: 300,
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-diff</code>.</p>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/ecl/ecl.js b/third-party/codemirror-3.15/mode/ecl/ecl.js
new file mode 100644 (file)
index 0000000..7601b18
--- /dev/null
@@ -0,0 +1,192 @@
+CodeMirror.defineMode("ecl", function(config) {
+
+  function words(str) {
+    var obj = {}, words = str.split(" ");
+    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
+    return obj;
+  }
+
+  function metaHook(stream, state) {
+    if (!state.startOfLine) return false;
+    stream.skipToEnd();
+    return "meta";
+  }
+
+  var indentUnit = config.indentUnit;
+  var keyword = words("abs acos allnodes ascii asin asstring atan atan2 ave case choose choosen choosesets clustersize combine correlation cos cosh count covariance cron dataset dedup define denormalize distribute distributed distribution ebcdic enth error evaluate event eventextra eventname exists exp failcode failmessage fetch fromunicode getisvalid global graph group hash hash32 hash64 hashcrc hashmd5 having if index intformat isvalid iterate join keyunicode length library limit ln local log loop map matched matchlength matchposition matchtext matchunicode max merge mergejoin min nolocal nonempty normalize parse pipe power preload process project pull random range rank ranked realformat recordof regexfind regexreplace regroup rejected rollup round roundup row rowdiff sample set sin sinh sizeof soapcall sort sorted sqrt stepped stored sum table tan tanh thisnode topn tounicode transfer trim truncate typeof ungroup unicodeorder variance which workunit xmldecode xmlencode xmltext xmlunicode");
+  var variable = words("apply assert build buildindex evaluate fail keydiff keypatch loadxml nothor notify output parallel sequential soapcall wait");
+  var variable_2 = words("__compressed__ all and any as atmost before beginc++ best between case const counter csv descend encrypt end endc++ endmacro except exclusive expire export extend false few first flat from full function group header heading hole ifblock import in interface joined keep keyed last left limit load local locale lookup macro many maxcount maxlength min skew module named nocase noroot noscan nosort not of only opt or outer overwrite packed partition penalty physicallength pipe quote record relationship repeat return right scan self separator service shared skew skip sql store terminator thor threshold token transform trim true type unicodeorder unsorted validate virtual whole wild within xml xpath");
+  var variable_3 = words("ascii big_endian boolean data decimal ebcdic integer pattern qstring real record rule set of string token udecimal unicode unsigned varstring varunicode");
+  var builtin = words("checkpoint deprecated failcode failmessage failure global independent onwarning persist priority recovery stored success wait when");
+  var blockKeywords = words("catch class do else finally for if switch try while");
+  var atoms = words("true false null");
+  var hooks = {"#": metaHook};
+  var multiLineStrings;
+  var isOperatorChar = /[+\-*&%=<>!?|\/]/;
+
+  var curPunc;
+
+  function tokenBase(stream, state) {
+    var ch = stream.next();
+    if (hooks[ch]) {
+      var result = hooks[ch](stream, state);
+      if (result !== false) return result;
+    }
+    if (ch == '"' || ch == "'") {
+      state.tokenize = tokenString(ch);
+      return state.tokenize(stream, state);
+    }
+    if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
+      curPunc = ch;
+      return null;
+    }
+    if (/\d/.test(ch)) {
+      stream.eatWhile(/[\w\.]/);
+      return "number";
+    }
+    if (ch == "/") {
+      if (stream.eat("*")) {
+        state.tokenize = tokenComment;
+        return tokenComment(stream, state);
+      }
+      if (stream.eat("/")) {
+        stream.skipToEnd();
+        return "comment";
+      }
+    }
+    if (isOperatorChar.test(ch)) {
+      stream.eatWhile(isOperatorChar);
+      return "operator";
+    }
+    stream.eatWhile(/[\w\$_]/);
+    var cur = stream.current().toLowerCase();
+    if (keyword.propertyIsEnumerable(cur)) {
+      if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
+      return "keyword";
+    } else if (variable.propertyIsEnumerable(cur)) {
+      if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
+      return "variable";
+    } else if (variable_2.propertyIsEnumerable(cur)) {
+      if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
+      return "variable-2";
+    } else if (variable_3.propertyIsEnumerable(cur)) {
+      if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
+      return "variable-3";
+    } else if (builtin.propertyIsEnumerable(cur)) {
+      if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
+      return "builtin";
+    } else { //Data types are of from KEYWORD##
+                var i = cur.length - 1;
+                while(i >= 0 && (!isNaN(cur[i]) || cur[i] == '_'))
+                        --i;
+
+                if (i > 0) {
+                        var cur2 = cur.substr(0, i + 1);
+                if (variable_3.propertyIsEnumerable(cur2)) {
+                        if (blockKeywords.propertyIsEnumerable(cur2)) curPunc = "newstatement";
+                        return "variable-3";
+                }
+            }
+    }
+    if (atoms.propertyIsEnumerable(cur)) return "atom";
+    return null;
+  }
+
+  function tokenString(quote) {
+    return function(stream, state) {
+      var escaped = false, next, end = false;
+      while ((next = stream.next()) != null) {
+        if (next == quote && !escaped) {end = true; break;}
+        escaped = !escaped && next == "\\";
+      }
+      if (end || !(escaped || multiLineStrings))
+        state.tokenize = tokenBase;
+      return "string";
+    };
+  }
+
+  function tokenComment(stream, state) {
+    var maybeEnd = false, ch;
+    while (ch = stream.next()) {
+      if (ch == "/" && maybeEnd) {
+        state.tokenize = tokenBase;
+        break;
+      }
+      maybeEnd = (ch == "*");
+    }
+    return "comment";
+  }
+
+  function Context(indented, column, type, align, prev) {
+    this.indented = indented;
+    this.column = column;
+    this.type = type;
+    this.align = align;
+    this.prev = prev;
+  }
+  function pushContext(state, col, type) {
+    return state.context = new Context(state.indented, col, type, null, state.context);
+  }
+  function popContext(state) {
+    var t = state.context.type;
+    if (t == ")" || t == "]" || t == "}")
+      state.indented = state.context.indented;
+    return state.context = state.context.prev;
+  }
+
+  // Interface
+
+  return {
+    startState: function(basecolumn) {
+      return {
+        tokenize: null,
+        context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
+        indented: 0,
+        startOfLine: true
+      };
+    },
+
+    token: function(stream, state) {
+      var ctx = state.context;
+      if (stream.sol()) {
+        if (ctx.align == null) ctx.align = false;
+        state.indented = stream.indentation();
+        state.startOfLine = true;
+      }
+      if (stream.eatSpace()) return null;
+      curPunc = null;
+      var style = (state.tokenize || tokenBase)(stream, state);
+      if (style == "comment" || style == "meta") return style;
+      if (ctx.align == null) ctx.align = true;
+
+      if ((curPunc == ";" || curPunc == ":") && ctx.type == "statement") popContext(state);
+      else if (curPunc == "{") pushContext(state, stream.column(), "}");
+      else if (curPunc == "[") pushContext(state, stream.column(), "]");
+      else if (curPunc == "(") pushContext(state, stream.column(), ")");
+      else if (curPunc == "}") {
+        while (ctx.type == "statement") ctx = popContext(state);
+        if (ctx.type == "}") ctx = popContext(state);
+        while (ctx.type == "statement") ctx = popContext(state);
+      }
+      else if (curPunc == ctx.type) popContext(state);
+      else if (ctx.type == "}" || ctx.type == "top" || (ctx.type == "statement" && curPunc == "newstatement"))
+        pushContext(state, stream.column(), "statement");
+      state.startOfLine = false;
+      return style;
+    },
+
+    indent: function(state, textAfter) {
+      if (state.tokenize != tokenBase && state.tokenize != null) return 0;
+      var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
+      if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev;
+      var closing = firstChar == ctx.type;
+      if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : indentUnit);
+      else if (ctx.align) return ctx.column + (closing ? 0 : 1);
+      else return ctx.indented + (closing ? 0 : indentUnit);
+    },
+
+    electricChars: "{}"
+  };
+});
+
+CodeMirror.defineMIME("text/x-ecl", "ecl");
diff --git a/third-party/codemirror-3.15/mode/ecl/index.html b/third-party/codemirror-3.15/mode/ecl/index.html
new file mode 100644 (file)
index 0000000..0ba88c3
--- /dev/null
@@ -0,0 +1,39 @@
+<!doctype html>
+<html>
+  <head>
+    <title>CodeMirror: ECL mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="ecl.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style>.CodeMirror {border: 1px solid black;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: ECL mode</h1>
+    <form><textarea id="code" name="code">
+/*
+sample useless code to demonstrate ecl syntax highlighting
+this is a multiline comment!
+*/
+
+//  this is a singleline comment!
+
+import ut;
+r := 
+  record
+   string22 s1 := '123';
+   integer4 i1 := 123;
+  end;
+#option('tmp', true);
+d := dataset('tmp::qb', r, thor);
+output(d);
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
+    </script>
+
+    <p>Based on CodeMirror's clike mode.  For more information see <a href="http://hpccsystems.com">HPCC Systems</a> web site.</p>
+    <p><strong>MIME types defined:</strong> <code>text/x-ecl</code>.</p>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/erlang/erlang.js b/third-party/codemirror-3.15/mode/erlang/erlang.js
new file mode 100644 (file)
index 0000000..79e0434
--- /dev/null
@@ -0,0 +1,464 @@
+// block; "begin", "case", "fun", "if", "receive", "try": closed by "end"
+// block internal; "after", "catch", "of"
+// guard; "when", closed by "->"
+// "->" opens a clause, closed by ";" or "."
+// "<<" opens a binary, closed by ">>"
+// "," appears in arglists, lists, tuples and terminates lines of code
+// "." resets indentation to 0
+// obsolete; "cond", "let", "query"
+
+CodeMirror.defineMIME("text/x-erlang", "erlang");
+
+CodeMirror.defineMode("erlang", function(cmCfg) {
+
+  function rval(state,stream,type) {
+    // distinguish between "." as terminator and record field operator
+    if (type == "record") {
+      state.context = "record";
+    }else{
+      state.context = false;
+    }
+
+    // remember last significant bit on last line for indenting
+    if (type != "whitespace" && type != "comment") {
+      state.lastToken = stream.current();
+    }
+    //     erlang             -> CodeMirror tag
+    switch (type) {
+      case "atom":        return "atom";
+      case "attribute":   return "attribute";
+      case "builtin":     return "builtin";
+      case "comment":     return "comment";
+      case "fun":         return "meta";
+      case "function":    return "tag";
+      case "guard":       return "property";
+      case "keyword":     return "keyword";
+      case "macro":       return "variable-2";
+      case "number":      return "number";
+      case "operator":    return "operator";
+      case "record":      return "bracket";
+      case "string":      return "string";
+      case "type":        return "def";
+      case "variable":    return "variable";
+      case "error":       return "error";
+      case "separator":   return null;
+      case "open_paren":  return null;
+      case "close_paren": return null;
+      default:            return null;
+    }
+  }
+
+  var typeWords = [
+    "-type", "-spec", "-export_type", "-opaque"];
+
+  var keywordWords = [
+    "after","begin","catch","case","cond","end","fun","if",
+    "let","of","query","receive","try","when"];
+
+  var separatorWords = [
+    "->",";",":",".",","];
+
+  var operatorWords = [
+    "and","andalso","band","bnot","bor","bsl","bsr","bxor",
+    "div","not","or","orelse","rem","xor"];
+
+  var symbolWords = [
+    "+","-","*","/",">",">=","<","=<","=:=","==","=/=","/=","||","<-"];
+
+  var openParenWords = [
+    "<<","(","[","{"];
+
+  var closeParenWords = [
+    "}","]",")",">>"];
+
+  var guardWords = [
+    "is_atom","is_binary","is_bitstring","is_boolean","is_float",
+    "is_function","is_integer","is_list","is_number","is_pid",
+    "is_port","is_record","is_reference","is_tuple",
+    "atom","binary","bitstring","boolean","function","integer","list",
+    "number","pid","port","record","reference","tuple"];
+
+  var bifWords = [
+    "abs","adler32","adler32_combine","alive","apply","atom_to_binary",
+    "atom_to_list","binary_to_atom","binary_to_existing_atom",
+    "binary_to_list","binary_to_term","bit_size","bitstring_to_list",
+    "byte_size","check_process_code","contact_binary","crc32",
+    "crc32_combine","date","decode_packet","delete_module",
+    "disconnect_node","element","erase","exit","float","float_to_list",
+    "garbage_collect","get","get_keys","group_leader","halt","hd",
+    "integer_to_list","internal_bif","iolist_size","iolist_to_binary",
+    "is_alive","is_atom","is_binary","is_bitstring","is_boolean",
+    "is_float","is_function","is_integer","is_list","is_number","is_pid",
+    "is_port","is_process_alive","is_record","is_reference","is_tuple",
+    "length","link","list_to_atom","list_to_binary","list_to_bitstring",
+    "list_to_existing_atom","list_to_float","list_to_integer",
+    "list_to_pid","list_to_tuple","load_module","make_ref","module_loaded",
+    "monitor_node","node","node_link","node_unlink","nodes","notalive",
+    "now","open_port","pid_to_list","port_close","port_command",
+    "port_connect","port_control","pre_loaded","process_flag",
+    "process_info","processes","purge_module","put","register",
+    "registered","round","self","setelement","size","spawn","spawn_link",
+    "spawn_monitor","spawn_opt","split_binary","statistics",
+    "term_to_binary","time","throw","tl","trunc","tuple_size",
+    "tuple_to_list","unlink","unregister","whereis"];
+
+  // ignored for indenting purposes
+  var ignoreWords = [
+    ",", ":", "catch", "after", "of", "cond", "let", "query"];
+
+
+  var smallRE      = /[a-z_]/;
+  var largeRE      = /[A-Z_]/;
+  var digitRE      = /[0-9]/;
+  var octitRE      = /[0-7]/;
+  var anumRE       = /[a-z_A-Z0-9]/;
+  var symbolRE     = /[\+\-\*\/<>=\|:]/;
+  var openParenRE  = /[<\(\[\{]/;
+  var closeParenRE = /[>\)\]\}]/;
+  var sepRE        = /[\->\.,:;]/;
+
+  function isMember(element,list) {
+    return (-1 < list.indexOf(element));
+  }
+
+  function isPrev(stream,string) {
+    var start = stream.start;
+    var len = string.length;
+    if (len <= start) {
+      var word = stream.string.slice(start-len,start);
+      return word == string;
+    }else{
+      return false;
+    }
+  }
+
+  function tokenize(stream, state) {
+    if (stream.eatSpace()) {
+      return rval(state,stream,"whitespace");
+    }
+
+    // attributes and type specs
+    if ((peekToken(state).token == "" || peekToken(state).token == ".") &&
+        stream.peek() == '-') {
+      stream.next();
+      if (stream.eat(smallRE) && stream.eatWhile(anumRE)) {
+        if (isMember(stream.current(),typeWords)) {
+          return rval(state,stream,"type");
+        }else{
+          return rval(state,stream,"attribute");
+        }
+      }
+      stream.backUp(1);
+    }
+
+    var ch = stream.next();
+
+    // comment
+    if (ch == '%') {
+      stream.skipToEnd();
+      return rval(state,stream,"comment");
+    }
+
+    // macro
+    if (ch == '?') {
+      stream.eatWhile(anumRE);
+      return rval(state,stream,"macro");
+    }
+
+    // record
+    if ( ch == "#") {
+      stream.eatWhile(anumRE);
+      return rval(state,stream,"record");
+    }
+
+    // char
+    if ( ch == "$") {
+      if (stream.next() == "\\") {
+        if (!stream.eatWhile(octitRE)) {
+          stream.next();
+        }
+      }
+      return rval(state,stream,"string");
+    }
+
+    // quoted atom
+    if (ch == '\'') {
+      if (singleQuote(stream)) {
+        return rval(state,stream,"atom");
+      }else{
+        return rval(state,stream,"error");
+      }
+    }
+
+    // string
+    if (ch == '"') {
+      if (doubleQuote(stream)) {
+        return rval(state,stream,"string");
+      }else{
+        return rval(state,stream,"error");
+      }
+    }
+
+    // variable
+    if (largeRE.test(ch)) {
+      stream.eatWhile(anumRE);
+      return rval(state,stream,"variable");
+    }
+
+    // atom/keyword/BIF/function
+    if (smallRE.test(ch)) {
+      stream.eatWhile(anumRE);
+
+      if (stream.peek() == "/") {
+        stream.next();
+        if (stream.eatWhile(digitRE)) {
+          return rval(state,stream,"fun");      // f/0 style fun
+        }else{
+          stream.backUp(1);
+          return rval(state,stream,"atom");
+        }
+      }
+
+      var w = stream.current();
+
+      if (isMember(w,keywordWords)) {
+        pushToken(state,stream);
+        return rval(state,stream,"keyword");
+      }
+      if (stream.peek() == "(") {
+        // 'put' and 'erlang:put' are bifs, 'foo:put' is not
+        if (isMember(w,bifWords) &&
+            (!isPrev(stream,":") || isPrev(stream,"erlang:"))) {
+          return rval(state,stream,"builtin");
+        }else{
+          return rval(state,stream,"function");
+        }
+      }
+      if (isMember(w,guardWords)) {
+        return rval(state,stream,"guard");
+      }
+      if (isMember(w,operatorWords)) {
+        return rval(state,stream,"operator");
+      }
+      if (stream.peek() == ":") {
+        if (w == "erlang") {
+          return rval(state,stream,"builtin");
+        } else {
+          return rval(state,stream,"function");
+        }
+      }
+      return rval(state,stream,"atom");
+    }
+
+    // number
+    if (digitRE.test(ch)) {
+      stream.eatWhile(digitRE);
+      if (stream.eat('#')) {
+        stream.eatWhile(digitRE);    // 16#10  style integer
+      } else {
+        if (stream.eat('.')) {       // float
+          stream.eatWhile(digitRE);
+        }
+        if (stream.eat(/[eE]/)) {
+          stream.eat(/[-+]/);        // float with exponent
+          stream.eatWhile(digitRE);
+        }
+      }
+      return rval(state,stream,"number");   // normal integer
+    }
+
+    // open parens
+    if (nongreedy(stream,openParenRE,openParenWords)) {
+      pushToken(state,stream);
+      return rval(state,stream,"open_paren");
+    }
+
+    // close parens
+    if (nongreedy(stream,closeParenRE,closeParenWords)) {
+      pushToken(state,stream);
+      return rval(state,stream,"close_paren");
+    }
+
+    // separators
+    if (greedy(stream,sepRE,separatorWords)) {
+      // distinguish between "." as terminator and record field operator
+      if (state.context == false) {
+        pushToken(state,stream);
+      }
+      return rval(state,stream,"separator");
+    }
+
+    // operators
+    if (greedy(stream,symbolRE,symbolWords)) {
+      return rval(state,stream,"operator");
+    }
+
+    return rval(state,stream,null);
+  }
+
+  function nongreedy(stream,re,words) {
+    if (stream.current().length == 1 && re.test(stream.current())) {
+      stream.backUp(1);
+      while (re.test(stream.peek())) {
+        stream.next();
+        if (isMember(stream.current(),words)) {
+          return true;
+        }
+      }
+      stream.backUp(stream.current().length-1);
+    }
+    return false;
+  }
+
+  function greedy(stream,re,words) {
+    if (stream.current().length == 1 && re.test(stream.current())) {
+      while (re.test(stream.peek())) {
+        stream.next();
+      }
+      while (0 < stream.current().length) {
+        if (isMember(stream.current(),words)) {
+          return true;
+        }else{
+          stream.backUp(1);
+        }
+      }
+      stream.next();
+    }
+    return false;
+  }
+
+  function doubleQuote(stream) {
+    return quote(stream, '"', '\\');
+  }
+
+  function singleQuote(stream) {
+    return quote(stream,'\'','\\');
+  }
+
+  function quote(stream,quoteChar,escapeChar) {
+    while (!stream.eol()) {
+      var ch = stream.next();
+      if (ch == quoteChar) {
+        return true;
+      }else if (ch == escapeChar) {
+        stream.next();
+      }
+    }
+    return false;
+  }
+
+  function Token(stream) {
+    this.token  = stream ? stream.current() : "";
+    this.column = stream ? stream.column() : 0;
+    this.indent = stream ? stream.indentation() : 0;
+  }
+
+  function myIndent(state,textAfter) {
+    var indent = cmCfg.indentUnit;
+    var outdentWords = ["after","catch"];
+    var token = (peekToken(state)).token;
+    var wordAfter = takewhile(textAfter,/[^a-z]/);
+
+    if (isMember(token,openParenWords)) {
+      return (peekToken(state)).column+token.length;
+    }else if (token == "." || token == ""){
+      return 0;
+    }else if (token == "->") {
+      if (wordAfter == "end") {
+        return peekToken(state,2).column;
+      }else if (peekToken(state,2).token == "fun") {
+        return peekToken(state,2).column+indent;
+      }else{
+        return (peekToken(state)).indent+indent;
+      }
+    }else if (isMember(wordAfter,outdentWords)) {
+      return (peekToken(state)).indent;
+    }else{
+      return (peekToken(state)).column+indent;
+    }
+  }
+
+  function takewhile(str,re) {
+    var m = str.match(re);
+    return m ? str.slice(0,m.index) : str;
+  }
+
+  function popToken(state) {
+    return state.tokenStack.pop();
+  }
+
+  function peekToken(state,depth) {
+    var len = state.tokenStack.length;
+    var dep = (depth ? depth : 1);
+    if (len < dep) {
+      return new Token;
+    }else{
+      return state.tokenStack[len-dep];
+    }
+  }
+
+  function pushToken(state,stream) {
+    var token = stream.current();
+    var prev_token = peekToken(state).token;
+    if (isMember(token,ignoreWords)) {
+      return false;
+    }else if (drop_both(prev_token,token)) {
+      popToken(state);
+      return false;
+    }else if (drop_first(prev_token,token)) {
+      popToken(state);
+      return pushToken(state,stream);
+    }else{
+      state.tokenStack.push(new Token(stream));
+      return true;
+    }
+  }
+
+  function drop_first(open, close) {
+    switch (open+" "+close) {
+      case "when ->":       return true;
+      case "-> end":        return true;
+      case "-> .":          return true;
+      case ". .":           return true;
+      default:              return false;
+    }
+  }
+
+  function drop_both(open, close) {
+    switch (open+" "+close) {
+      case "( )":         return true;
+      case "[ ]":         return true;
+      case "{ }":         return true;
+      case "<< >>":       return true;
+      case "begin end":   return true;
+      case "case end":    return true;
+      case "fun end":     return true;
+      case "if end":      return true;
+      case "receive end": return true;
+      case "try end":     return true;
+      case "-> ;":        return true;
+      default:            return false;
+    }
+  }
+
+  return {
+    startState:
+      function() {
+        return {tokenStack: [],
+                context: false,
+                lastToken: null};
+      },
+
+    token:
+      function(stream, state) {
+        return tokenize(stream, state);
+      },
+
+    indent:
+      function(state, textAfter) {
+        return myIndent(state,textAfter);
+      },
+
+    lineComment: "%"
+  };
+});
diff --git a/third-party/codemirror-3.15/mode/erlang/index.html b/third-party/codemirror-3.15/mode/erlang/index.html
new file mode 100644 (file)
index 0000000..fd21521
--- /dev/null
@@ -0,0 +1,64 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Erlang mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../../addon/edit/matchbrackets.js"></script>
+    <script src="erlang.js"></script>
+    <link rel="stylesheet" href="../../theme/erlang-dark.css">
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Erlang mode</h1>
+
+<form><textarea id="code" name="code">
+%% -*- mode: erlang; erlang-indent-level: 2 -*-
+%%% Created :  7 May 2012 by mats cronqvist <masse@klarna.com>
+
+%% @doc
+%% Demonstrates how to print a record.
+%% @end
+
+-module('ex').
+-author('mats cronqvist').
+-export([demo/0,
+         rec_info/1]).
+
+-record(demo,{a="One",b="Two",c="Three",d="Four"}).
+
+rec_info(demo) -> record_info(fields,demo).
+
+demo() -> expand_recs(?MODULE,#demo{a="A",b="BB"}).
+  
+expand_recs(M,List) when is_list(List) ->
+  [expand_recs(M,L)||L<-List];
+expand_recs(M,Tup) when is_tuple(Tup) ->
+  case tuple_size(Tup) of
+    L when L < 1 -> Tup;
+    L ->
+      try Fields = M:rec_info(element(1,Tup)),
+          L = length(Fields)+1,
+          lists:zip(Fields,expand_recs(M,tl(tuple_to_list(Tup))))
+      catch _:_ ->
+          list_to_tuple(expand_recs(M,tuple_to_list(Tup)))
+      end
+  end;
+expand_recs(_,Term) ->
+  Term.
+</textarea></form>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        matchBrackets: true,
+        extraKeys: {"Tab":  "indentAuto"},
+        theme: "erlang-dark"
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-erlang</code>.</p>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/gas/gas.js b/third-party/codemirror-3.15/mode/gas/gas.js
new file mode 100644 (file)
index 0000000..a6e6892
--- /dev/null
@@ -0,0 +1,330 @@
+CodeMirror.defineMode("gas", function(_config, parserConfig) {
+  'use strict';
+
+  // If an architecture is specified, its initialization function may
+  // populate this array with custom parsing functions which will be
+  // tried in the event that the standard functions do not find a match.
+  var custom = [];
+
+  // The symbol used to start a line comment changes based on the target
+  // architecture.
+  // If no architecture is pased in "parserConfig" then only multiline
+  // comments will have syntax support.
+  var lineCommentStartSymbol = "";
+
+  // These directives are architecture independent.
+  // Machine specific directives should go in their respective
+  // architecture initialization function.
+  // Reference:
+  // http://sourceware.org/binutils/docs/as/Pseudo-Ops.html#Pseudo-Ops
+  var directives = {
+    ".abort" : "builtin",
+    ".align" : "builtin",
+    ".altmacro" : "builtin",
+    ".ascii" : "builtin",
+    ".asciz" : "builtin",
+    ".balign" : "builtin",
+    ".balignw" : "builtin",
+    ".balignl" : "builtin",
+    ".bundle_align_mode" : "builtin",
+    ".bundle_lock" : "builtin",
+    ".bundle_unlock" : "builtin",
+    ".byte" : "builtin",
+    ".cfi_startproc" : "builtin",
+    ".comm" : "builtin",
+    ".data" : "builtin",
+    ".def" : "builtin",
+    ".desc" : "builtin",
+    ".dim" : "builtin",
+    ".double" : "builtin",
+    ".eject" : "builtin",
+    ".else" : "builtin",
+    ".elseif" : "builtin",
+    ".end" : "builtin",
+    ".endef" : "builtin",
+    ".endfunc" : "builtin",
+    ".endif" : "builtin",
+    ".equ" : "builtin",
+    ".equiv" : "builtin",
+    ".eqv" : "builtin",
+    ".err" : "builtin",
+    ".error" : "builtin",
+    ".exitm" : "builtin",
+    ".extern" : "builtin",
+    ".fail" : "builtin",
+    ".file" : "builtin",
+    ".fill" : "builtin",
+    ".float" : "builtin",
+    ".func" : "builtin",
+    ".global" : "builtin",
+    ".gnu_attribute" : "builtin",
+    ".hidden" : "builtin",
+    ".hword" : "builtin",
+    ".ident" : "builtin",
+    ".if" : "builtin",
+    ".incbin" : "builtin",
+    ".include" : "builtin",
+    ".int" : "builtin",
+    ".internal" : "builtin",
+    ".irp" : "builtin",
+    ".irpc" : "builtin",
+    ".lcomm" : "builtin",
+    ".lflags" : "builtin",
+    ".line" : "builtin",
+    ".linkonce" : "builtin",
+    ".list" : "builtin",
+    ".ln" : "builtin",
+    ".loc" : "builtin",
+    ".loc_mark_labels" : "builtin",
+    ".local" : "builtin",
+    ".long" : "builtin",
+    ".macro" : "builtin",
+    ".mri" : "builtin",
+    ".noaltmacro" : "builtin",
+    ".nolist" : "builtin",
+    ".octa" : "builtin",
+    ".offset" : "builtin",
+    ".org" : "builtin",
+    ".p2align" : "builtin",
+    ".popsection" : "builtin",
+    ".previous" : "builtin",
+    ".print" : "builtin",
+    ".protected" : "builtin",
+    ".psize" : "builtin",
+    ".purgem" : "builtin",
+    ".pushsection" : "builtin",
+    ".quad" : "builtin",
+    ".reloc" : "builtin",
+    ".rept" : "builtin",
+    ".sbttl" : "builtin",
+    ".scl" : "builtin",
+    ".section" : "builtin",
+    ".set" : "builtin",
+    ".short" : "builtin",
+    ".single" : "builtin",
+    ".size" : "builtin",
+    ".skip" : "builtin",
+    ".sleb128" : "builtin",
+    ".space" : "builtin",
+    ".stab" : "builtin",
+    ".string" : "builtin",
+    ".struct" : "builtin",
+    ".subsection" : "builtin",
+    ".symver" : "builtin",
+    ".tag" : "builtin",
+    ".text" : "builtin",
+    ".title" : "builtin",
+    ".type" : "builtin",
+    ".uleb128" : "builtin",
+    ".val" : "builtin",
+    ".version" : "builtin",
+    ".vtable_entry" : "builtin",
+    ".vtable_inherit" : "builtin",
+    ".warning" : "builtin",
+    ".weak" : "builtin",
+    ".weakref" : "builtin",
+    ".word" : "builtin"
+  };
+
+  var registers = {};
+
+  function x86(_parserConfig) {
+    lineCommentStartSymbol = "#";
+
+    registers.ax  = "variable";
+    registers.eax = "variable-2";
+    registers.rax = "variable-3";
+
+    registers.bx  = "variable";
+    registers.ebx = "variable-2";
+    registers.rbx = "variable-3";
+
+    registers.cx  = "variable";
+    registers.ecx = "variable-2";
+    registers.rcx = "variable-3";
+
+    registers.dx  = "variable";
+    registers.edx = "variable-2";
+    registers.rdx = "variable-3";
+
+    registers.si  = "variable";
+    registers.esi = "variable-2";
+    registers.rsi = "variable-3";
+
+    registers.di  = "variable";
+    registers.edi = "variable-2";
+    registers.rdi = "variable-3";
+
+    registers.sp  = "variable";
+    registers.esp = "variable-2";
+    registers.rsp = "variable-3";
+
+    registers.bp  = "variable";
+    registers.ebp = "variable-2";
+    registers.rbp = "variable-3";
+
+    registers.ip  = "variable";
+    registers.eip = "variable-2";
+    registers.rip = "variable-3";
+
+    registers.cs  = "keyword";
+    registers.ds  = "keyword";
+    registers.ss  = "keyword";
+    registers.es  = "keyword";
+    registers.fs  = "keyword";
+    registers.gs  = "keyword";
+  }
+
+  function armv6(_parserConfig) {
+    // Reference:
+    // http://infocenter.arm.com/help/topic/com.arm.doc.qrc0001l/QRC0001_UAL.pdf
+    // http://infocenter.arm.com/help/topic/com.arm.doc.ddi0301h/DDI0301H_arm1176jzfs_r0p7_trm.pdf
+    lineCommentStartSymbol = "@";
+    directives.syntax = "builtin";
+
+    registers.r0  = "variable";
+    registers.r1  = "variable";
+    registers.r2  = "variable";
+    registers.r3  = "variable";
+    registers.r4  = "variable";
+    registers.r5  = "variable";
+    registers.r6  = "variable";
+    registers.r7  = "variable";
+    registers.r8  = "variable";
+    registers.r9  = "variable";
+    registers.r10 = "variable";
+    registers.r11 = "variable";
+    registers.r12 = "variable";
+
+    registers.sp  = "variable-2";
+    registers.lr  = "variable-2";
+    registers.pc  = "variable-2";
+    registers.r13 = registers.sp;
+    registers.r14 = registers.lr;
+    registers.r15 = registers.pc;
+
+    custom.push(function(ch, stream) {
+      if (ch === '#') {
+        stream.eatWhile(/\w/);
+        return "number";
+      }
+    });
+  }
+
+  var arch = parserConfig.architecture.toLowerCase();
+  if (arch === "x86") {
+    x86(parserConfig);
+  } else if (arch === "arm" || arch === "armv6") {
+    armv6(parserConfig);
+  }
+
+  function nextUntilUnescaped(stream, end) {
+    var escaped = false, next;
+    while ((next = stream.next()) != null) {
+      if (next === end && !escaped) {
+        return false;
+      }
+      escaped = !escaped && next === "\\";
+    }
+    return escaped;
+  }
+
+  function clikeComment(stream, state) {
+    var maybeEnd = false, ch;
+    while ((ch = stream.next()) != null) {
+      if (ch === "/" && maybeEnd) {
+        state.tokenize = null;
+        break;
+      }
+      maybeEnd = (ch === "*");
+    }
+    return "comment";
+  }
+
+  return {
+    startState: function() {
+      return {
+        tokenize: null
+      };
+    },
+
+    token: function(stream, state) {
+      if (state.tokenize) {
+        return state.tokenize(stream, state);
+      }
+
+      if (stream.eatSpace()) {
+        return null;
+      }
+
+      var style, cur, ch = stream.next();
+
+      if (ch === "/") {
+        if (stream.eat("*")) {
+          state.tokenize = clikeComment;
+          return clikeComment(stream, state);
+        }
+      }
+
+      if (ch === lineCommentStartSymbol) {
+        stream.skipToEnd();
+        return "comment";
+      }
+
+      if (ch === '"') {
+        nextUntilUnescaped(stream, '"');
+        return "string";
+      }
+
+      if (ch === '.') {
+        stream.eatWhile(/\w/);
+        cur = stream.current().toLowerCase();
+        style = directives[cur];
+        return style || null;
+      }
+
+      if (ch === '=') {
+        stream.eatWhile(/\w/);
+        return "tag";
+      }
+
+      if (ch === '{') {
+        return "braket";
+      }
+
+      if (ch === '}') {
+        return "braket";
+      }
+
+      if (/\d/.test(ch)) {
+        if (ch === "0" && stream.eat("x")) {
+          stream.eatWhile(/[0-9a-fA-F]/);
+          return "number";
+        }
+        stream.eatWhile(/\d/);
+        return "number";
+      }
+
+      if (/\w/.test(ch)) {
+        stream.eatWhile(/\w/);
+        if (stream.eat(":")) {
+          return 'tag';
+        }
+        cur = stream.current().toLowerCase();
+        style = registers[cur];
+        return style || null;
+      }
+
+      for (var i = 0; i < custom.length; i++) {
+        style = custom[i](ch, stream, state);
+        if (style) {
+          return style;
+        }
+      }
+    },
+
+    lineComment: lineCommentStartSymbol,
+    blockCommentStart: "/*",
+    blockCommentEnd: "*/"
+  };
+});
diff --git a/third-party/codemirror-3.15/mode/gas/index.html b/third-party/codemirror-3.15/mode/gas/index.html
new file mode 100644 (file)
index 0000000..7684bc1
--- /dev/null
@@ -0,0 +1,57 @@
+<!doctype html>
+<html>
+    <head>
+        <meta charset="utf-8">
+        <title>CodeMirror: Gas mode</title>
+        <link rel="stylesheet" href="../../lib/codemirror.css">
+        <script src="../../lib/codemirror.js"></script>
+        <script src="gas.js"></script>
+        <link rel="stylesheet" href="../../doc/docs.css">
+        <style>.CodeMirror {border: 2px inset #dee;}</style>
+    </head>
+    <body>
+        <h1>CodeMirror: Gas mode</h1>
+
+        <form>
+<textarea id="code" name="code">
+.syntax unified
+.global main
+
+/* 
+ *  A
+ *  multi-line
+ *  comment.
+ */
+
+@ A single line comment.
+
+main:
+        push    {sp, lr}
+        ldr     r0, =message
+        bl      puts
+        mov     r0, #0
+        pop     {sp, pc}
+
+message:
+        .asciz "Hello world!<br />"
+</textarea>
+        </form>
+
+        <script>
+            var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+                lineNumbers: true,
+                mode: {name: "gas", architecture: "ARMv6"},
+            });
+        </script>
+
+        <p>Handles AT&amp;T assembler syntax (more specifically this handles
+        the GNU Assembler (gas) syntax.)
+        It takes a single optional configuration parameter:
+        <code>architecture</code>, which can be one of <code>"ARM"</code>,
+        <code>"ARMv6"</code> or <code>"x86"</code>.
+        Including the parameter adds syntax for the registers and special
+        directives for the supplied architecture.
+
+        <p><strong>MIME types defined:</strong> <code>text/x-gas</code></p>
+    </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/gfm/gfm.js b/third-party/codemirror-3.15/mode/gfm/gfm.js
new file mode 100644 (file)
index 0000000..1179b53
--- /dev/null
@@ -0,0 +1,96 @@
+CodeMirror.defineMode("gfm", function(config) {
+  var codeDepth = 0;
+  function blankLine(state) {
+    state.code = false;
+    return null;
+  }
+  var gfmOverlay = {
+    startState: function() {
+      return {
+        code: false,
+        codeBlock: false,
+        ateSpace: false
+      };
+    },
+    copyState: function(s) {
+      return {
+        code: s.code,
+        codeBlock: s.codeBlock,
+        ateSpace: s.ateSpace
+      };
+    },
+    token: function(stream, state) {
+      // Hack to prevent formatting override inside code blocks (block and inline)
+      if (state.codeBlock) {
+        if (stream.match(/^```/)) {
+          state.codeBlock = false;
+          return null;
+        }
+        stream.skipToEnd();
+        return null;
+      }
+      if (stream.sol()) {
+        state.code = false;
+      }
+      if (stream.sol() && stream.match(/^```/)) {
+        stream.skipToEnd();
+        state.codeBlock = true;
+        return null;
+      }
+      // If this block is changed, it may need to be updated in Markdown mode
+      if (stream.peek() === '`') {
+        stream.next();
+        var before = stream.pos;
+        stream.eatWhile('`');
+        var difference = 1 + stream.pos - before;
+        if (!state.code) {
+          codeDepth = difference;
+          state.code = true;
+        } else {
+          if (difference === codeDepth) { // Must be exact
+            state.code = false;
+          }
+        }
+        return null;
+      } else if (state.code) {
+        stream.next();
+        return null;
+      }
+      // Check if space. If so, links can be formatted later on
+      if (stream.eatSpace()) {
+        state.ateSpace = true;
+        return null;
+      }
+      if (stream.sol() || state.ateSpace) {
+        state.ateSpace = false;
+        if(stream.match(/^(?:[a-zA-Z0-9\-_]+\/)?(?:[a-zA-Z0-9\-_]+@)?(?:[a-f0-9]{7,40}\b)/)) {
+          // User/Project@SHA
+          // User@SHA
+          // SHA
+          return "link";
+        } else if (stream.match(/^(?:[a-zA-Z0-9\-_]+\/)?(?:[a-zA-Z0-9\-_]+)?#[0-9]+\b/)) {
+          // User/Project#Num
+          // User#Num
+          // #Num
+          return "link";
+        }
+      }
+      if (stream.match(/^((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\([^\s()<>]*\))+(?:\([^\s()<>]*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/i)) {
+        // URLs
+        // Taken from http://daringfireball.net/2010/07/improved_regex_for_matching_urls
+        // And then (issue #1160) simplified to make it not crash the Chrome Regexp engine
+        return "link";
+      }
+      stream.next();
+      return null;
+    },
+    blankLine: blankLine
+  };
+  CodeMirror.defineMIME("gfmBase", {
+    name: "markdown",
+    underscoresBreakWords: false,
+    taskLists: true,
+    fencedCodeBlocks: true
+  });
+  return CodeMirror.overlayMode(CodeMirror.getMode(config, "gfmBase"), gfmOverlay);
+}, "markdown");
diff --git a/third-party/codemirror-3.15/mode/gfm/index.html b/third-party/codemirror-3.15/mode/gfm/index.html
new file mode 100644 (file)
index 0000000..826a96d
--- /dev/null
@@ -0,0 +1,74 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: GFM mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../../addon/mode/overlay.js"></script>
+    <script src="../xml/xml.js"></script>
+    <script src="../markdown/markdown.js"></script>
+    <script src="gfm.js"></script>
+    
+    <!-- Code block highlighting modes -->
+    <script src="../javascript/javascript.js"></script>
+    <script src="../css/css.js"></script>
+    <script src="../htmlmixed/htmlmixed.js"></script>
+    <script src="../clike/clike.js"></script>
+    
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: GFM mode</h1>
+
+<form><textarea id="code" name="code">
+GitHub Flavored Markdown
+========================
+
+Everything from markdown plus GFM features:
+
+## URL autolinking
+
+Underscores_are_allowed_between_words.
+
+## Fenced code blocks (and syntax highlighting)
+
+```javascript
+for (var i = 0; i &lt; items.length; i++) {
+    console.log(items[i], i); // log them
+}
+```
+
+## Task Lists
+
+- [ ] Incomplete task list item
+- [x] **Completed** task list item
+
+## A bit of GitHub spice
+
+* SHA: be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2
+* User@SHA ref: mojombo@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2
+* User/Project@SHA: mojombo/god@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2
+* \#Num: #1
+* User/#Num: mojombo#1
+* User/Project#Num: mojombo/god#1
+
+See http://github.github.com/github-flavored-markdown/.
+
+</textarea></form>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        mode: 'gfm',
+        lineNumbers: true,
+        theme: "default"
+      });
+    </script>
+
+    <p>Optionally depends on other modes for properly highlighted code blocks.</p>
+
+    <p><strong>Parsing/Highlighting Tests:</strong> <a href="../../test/index.html#gfm_*">normal</a>,  <a href="../../test/index.html#verbose,gfm_*">verbose</a>.</p>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/gfm/test.js b/third-party/codemirror-3.15/mode/gfm/test.js
new file mode 100644 (file)
index 0000000..3ccaec5
--- /dev/null
@@ -0,0 +1,112 @@
+(function() {
+  var mode = CodeMirror.getMode({tabSize: 4}, "gfm");
+  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }
+
+  MT("emInWordAsterisk",
+     "foo[em *bar*]hello");
+
+  MT("emInWordUnderscore",
+     "foo_bar_hello");
+
+  MT("emStrongUnderscore",
+     "[strong __][em&strong _foo__][em _] bar");
+
+  MT("fencedCodeBlocks",
+     "[comment ```]",
+     "[comment foo]",
+     "",
+     "[comment ```]",
+     "bar");
+
+  MT("fencedCodeBlockModeSwitching",
+     "[comment ```javascript]",
+     "[variable foo]",
+     "",
+     "[comment ```]",
+     "bar");
+
+  MT("taskListAsterisk",
+     "[variable-2 * []] foo]", // Invalid; must have space or x between []
+     "[variable-2 * [ ]]bar]", // Invalid; must have space after ]
+     "[variable-2 * [x]]hello]", // Invalid; must have space after ]
+     "[variable-2 * ][meta [ ]]][variable-2  [world]]]", // Valid; tests reference style links
+     "    [variable-3 * ][property [x]]][variable-3  foo]"); // Valid; can be nested
+
+  MT("taskListPlus",
+     "[variable-2 + []] foo]", // Invalid; must have space or x between []
+     "[variable-2 + [ ]]bar]", // Invalid; must have space after ]
+     "[variable-2 + [x]]hello]", // Invalid; must have space after ]
+     "[variable-2 + ][meta [ ]]][variable-2  [world]]]", // Valid; tests reference style links
+     "    [variable-3 + ][property [x]]][variable-3  foo]"); // Valid; can be nested
+
+  MT("taskListDash",
+     "[variable-2 - []] foo]", // Invalid; must have space or x between []
+     "[variable-2 - [ ]]bar]", // Invalid; must have space after ]
+     "[variable-2 - [x]]hello]", // Invalid; must have space after ]
+     "[variable-2 - ][meta [ ]]][variable-2  [world]]]", // Valid; tests reference style links
+     "    [variable-3 - ][property [x]]][variable-3  foo]"); // Valid; can be nested
+
+  MT("taskListNumber",
+     "[variable-2 1. []] foo]", // Invalid; must have space or x between []
+     "[variable-2 2. [ ]]bar]", // Invalid; must have space after ]
+     "[variable-2 3. [x]]hello]", // Invalid; must have space after ]
+     "[variable-2 4. ][meta [ ]]][variable-2  [world]]]", // Valid; tests reference style links
+     "    [variable-3 1. ][property [x]]][variable-3  foo]"); // Valid; can be nested
+
+  MT("SHA",
+     "foo [link be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2] bar");
+
+  MT("shortSHA",
+     "foo [link be6a8cc] bar");
+
+  MT("tooShortSHA",
+     "foo be6a8c bar");
+
+  MT("longSHA",
+     "foo be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd22 bar");
+
+  MT("badSHA",
+     "foo be6a8cc1c1ecfe9489fb51e4869af15a13fc2cg2 bar");
+
+  MT("userSHA",
+     "foo [link bar@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2] hello");
+
+  MT("userProjectSHA",
+     "foo [link bar/hello@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2] world");
+
+  MT("num",
+     "foo [link #1] bar");
+
+  MT("badNum",
+     "foo #1bar hello");
+
+  MT("userNum",
+     "foo [link bar#1] hello");
+
+  MT("userProjectNum",
+     "foo [link bar/hello#1] world");
+
+  MT("vanillaLink",
+     "foo [link http://www.example.com/] bar");
+
+  MT("vanillaLinkPunctuation",
+     "foo [link http://www.example.com/]. bar");
+
+  MT("vanillaLinkExtension",
+     "foo [link http://www.example.com/index.html] bar");
+
+  MT("notALink",
+     "[comment ```css]",
+     "[tag foo] {[property color][operator :][keyword black];}",
+     "[comment ```][link http://www.example.com/]");
+
+  MT("notALink",
+     "[comment ``foo `bar` http://www.example.com/``] hello");
+
+  MT("notALink",
+     "[comment `foo]",
+     "[link http://www.example.com/]",
+     "[comment `foo]",
+     "",
+     "[link http://www.example.com/]");
+})();
diff --git a/third-party/codemirror-3.15/mode/go/go.js b/third-party/codemirror-3.15/mode/go/go.js
new file mode 100644 (file)
index 0000000..6a458a6
--- /dev/null
@@ -0,0 +1,168 @@
+CodeMirror.defineMode("go", function(config) {
+  var indentUnit = config.indentUnit;
+
+  var keywords = {
+    "break":true, "case":true, "chan":true, "const":true, "continue":true,
+    "default":true, "defer":true, "else":true, "fallthrough":true, "for":true,
+    "func":true, "go":true, "goto":true, "if":true, "import":true,
+    "interface":true, "map":true, "package":true, "range":true, "return":true,
+    "select":true, "struct":true, "switch":true, "type":true, "var":true,
+    "bool":true, "byte":true, "complex64":true, "complex128":true,
+    "float32":true, "float64":true, "int8":true, "int16":true, "int32":true,
+    "int64":true, "string":true, "uint8":true, "uint16":true, "uint32":true,
+    "uint64":true, "int":true, "uint":true, "uintptr":true
+  };
+
+  var atoms = {
+    "true":true, "false":true, "iota":true, "nil":true, "append":true,
+    "cap":true, "close":true, "complex":true, "copy":true, "imag":true,
+    "len":true, "make":true, "new":true, "panic":true, "print":true,
+    "println":true, "real":true, "recover":true
+  };
+
+  var isOperatorChar = /[+\-*&^%:=<>!|\/]/;
+
+  var curPunc;
+
+  function tokenBase(stream, state) {
+    var ch = stream.next();
+    if (ch == '"' || ch == "'" || ch == "`") {
+      state.tokenize = tokenString(ch);
+      return state.tokenize(stream, state);
+    }
+    if (/[\d\.]/.test(ch)) {
+      if (ch == ".") {
+        stream.match(/^[0-9]+([eE][\-+]?[0-9]+)?/);
+      } else if (ch == "0") {
+        stream.match(/^[xX][0-9a-fA-F]+/) || stream.match(/^0[0-7]+/);
+      } else {
+        stream.match(/^[0-9]*\.?[0-9]*([eE][\-+]?[0-9]+)?/);
+      }
+      return "number";
+    }
+    if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
+      curPunc = ch;
+      return null;
+    }
+    if (ch == "/") {
+      if (stream.eat("*")) {
+        state.tokenize = tokenComment;
+        return tokenComment(stream, state);
+      }
+      if (stream.eat("/")) {
+        stream.skipToEnd();
+        return "comment";
+      }
+    }
+    if (isOperatorChar.test(ch)) {
+      stream.eatWhile(isOperatorChar);
+      return "operator";
+    }
+    stream.eatWhile(/[\w\$_]/);
+    var cur = stream.current();
+    if (keywords.propertyIsEnumerable(cur)) {
+      if (cur == "case" || cur == "default") curPunc = "case";
+      return "keyword";
+    }
+    if (atoms.propertyIsEnumerable(cur)) return "atom";
+    return "variable";
+  }
+
+  function tokenString(quote) {
+    return function(stream, state) {
+      var escaped = false, next, end = false;
+      while ((next = stream.next()) != null) {
+        if (next == quote && !escaped) {end = true; break;}
+        escaped = !escaped && next == "\\";
+      }
+      if (end || !(escaped || quote == "`"))
+        state.tokenize = tokenBase;
+      return "string";
+    };
+  }
+
+  function tokenComment(stream, state) {
+    var maybeEnd = false, ch;
+    while (ch = stream.next()) {
+      if (ch == "/" && maybeEnd) {
+        state.tokenize = tokenBase;
+        break;
+      }
+      maybeEnd = (ch == "*");
+    }
+    return "comment";
+  }
+
+  function Context(indented, column, type, align, prev) {
+    this.indented = indented;
+    this.column = column;
+    this.type = type;
+    this.align = align;
+    this.prev = prev;
+  }
+  function pushContext(state, col, type) {
+    return state.context = new Context(state.indented, col, type, null, state.context);
+  }
+  function popContext(state) {
+    var t = state.context.type;
+    if (t == ")" || t == "]" || t == "}")
+      state.indented = state.context.indented;
+    return state.context = state.context.prev;
+  }
+
+  // Interface
+
+  return {
+    startState: function(basecolumn) {
+      return {
+        tokenize: null,
+        context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
+        indented: 0,
+        startOfLine: true
+      };
+    },
+
+    token: function(stream, state) {
+      var ctx = state.context;
+      if (stream.sol()) {
+        if (ctx.align == null) ctx.align = false;
+        state.indented = stream.indentation();
+        state.startOfLine = true;
+        if (ctx.type == "case") ctx.type = "}";
+      }
+      if (stream.eatSpace()) return null;
+      curPunc = null;
+      var style = (state.tokenize || tokenBase)(stream, state);
+      if (style == "comment") return style;
+      if (ctx.align == null) ctx.align = true;
+
+      if (curPunc == "{") pushContext(state, stream.column(), "}");
+      else if (curPunc == "[") pushContext(state, stream.column(), "]");
+      else if (curPunc == "(") pushContext(state, stream.column(), ")");
+      else if (curPunc == "case") ctx.type = "case";
+      else if (curPunc == "}" && ctx.type == "}") ctx = popContext(state);
+      else if (curPunc == ctx.type) popContext(state);
+      state.startOfLine = false;
+      return style;
+    },
+
+    indent: function(state, textAfter) {
+      if (state.tokenize != tokenBase && state.tokenize != null) return 0;
+      var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
+      if (ctx.type == "case" && /^(?:case|default)\b/.test(textAfter)) {
+        state.context.type = "}";
+        return ctx.indented;
+      }
+      var closing = firstChar == ctx.type;
+      if (ctx.align) return ctx.column + (closing ? 0 : 1);
+      else return ctx.indented + (closing ? 0 : indentUnit);
+    },
+
+    electricChars: "{}:",
+    blockCommentStart: "/*",
+    blockCommentEnd: "*/",
+    lineComment: "//"
+  };
+});
+
+CodeMirror.defineMIME("text/x-go", "go");
diff --git a/third-party/codemirror-3.15/mode/go/index.html b/third-party/codemirror-3.15/mode/go/index.html
new file mode 100644 (file)
index 0000000..8a6aafc
--- /dev/null
@@ -0,0 +1,74 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Go mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <link rel="stylesheet" href="../../theme/elegant.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../../addon/edit/matchbrackets.js"></script>
+    <script src="go.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style>.CodeMirror {border:1px solid #999; background:#ffc}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: Go mode</h1>
+
+<form><textarea id="code" name="code">
+// Prime Sieve in Go.
+// Taken from the Go specification.
+// Copyright © The Go Authors.
+
+package main
+
+import "fmt"
+
+// Send the sequence 2, 3, 4, ... to channel 'ch'.
+func generate(ch chan&lt;- int) {
+       for i := 2; ; i++ {
+               ch &lt;- i  // Send 'i' to channel 'ch'
+       }
+}
+
+// Copy the values from channel 'src' to channel 'dst',
+// removing those divisible by 'prime'.
+func filter(src &lt;-chan int, dst chan&lt;- int, prime int) {
+       for i := range src {    // Loop over values received from 'src'.
+               if i%prime != 0 {
+                       dst &lt;- i  // Send 'i' to channel 'dst'.
+               }
+       }
+}
+
+// The prime sieve: Daisy-chain filter processes together.
+func sieve() {
+       ch := make(chan int)  // Create a new channel.
+       go generate(ch)       // Start generate() as a subprocess.
+       for {
+               prime := &lt;-ch
+               fmt.Print(prime, "\n")
+               ch1 := make(chan int)
+               go filter(ch, ch1, prime)
+               ch = ch1
+       }
+}
+
+func main() {
+       sieve()
+}
+</textarea></form>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        theme: "elegant",
+        matchBrackets: true,
+        indentUnit: 8,
+        tabSize: 8,
+        indentWithTabs: true,
+        mode: "text/x-go"
+      });
+    </script>
+
+    <p><strong>MIME type:</strong> <code>text/x-go</code></p>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/groovy/groovy.js b/third-party/codemirror-3.15/mode/groovy/groovy.js
new file mode 100644 (file)
index 0000000..6800e0a
--- /dev/null
@@ -0,0 +1,211 @@
+CodeMirror.defineMode("groovy", function(config) {
+  function words(str) {
+    var obj = {}, words = str.split(" ");
+    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
+    return obj;
+  }
+  var keywords = words(
+    "abstract as assert boolean break byte case catch char class const continue def default " +
+    "do double else enum extends final finally float for goto if implements import in " +
+    "instanceof int interface long native new package private protected public return " +
+    "short static strictfp super switch synchronized threadsafe throw throws transient " +
+    "try void volatile while");
+  var blockKeywords = words("catch class do else finally for if switch try while enum interface def");
+  var atoms = words("null true false this");
+
+  var curPunc;
+  function tokenBase(stream, state) {
+    var ch = stream.next();
+    if (ch == '"' || ch == "'") {
+      return startString(ch, stream, state);
+    }
+    if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
+      curPunc = ch;
+      return null;
+    }
+    if (/\d/.test(ch)) {
+      stream.eatWhile(/[\w\.]/);
+      if (stream.eat(/eE/)) { stream.eat(/\+\-/); stream.eatWhile(/\d/); }
+      return "number";
+    }
+    if (ch == "/") {
+      if (stream.eat("*")) {
+        state.tokenize.push(tokenComment);
+        return tokenComment(stream, state);
+      }
+      if (stream.eat("/")) {
+        stream.skipToEnd();
+        return "comment";
+      }
+      if (expectExpression(state.lastToken)) {
+        return startString(ch, stream, state);
+      }
+    }
+    if (ch == "-" && stream.eat(">")) {
+      curPunc = "->";
+      return null;
+    }
+    if (/[+\-*&%=<>!?|\/~]/.test(ch)) {
+      stream.eatWhile(/[+\-*&%=<>|~]/);
+      return "operator";
+    }
+    stream.eatWhile(/[\w\$_]/);
+    if (ch == "@") { stream.eatWhile(/[\w\$_\.]/); return "meta"; }
+    if (state.lastToken == ".") return "property";
+    if (stream.eat(":")) { curPunc = "proplabel"; return "property"; }
+    var cur = stream.current();
+    if (atoms.propertyIsEnumerable(cur)) { return "atom"; }
+    if (keywords.propertyIsEnumerable(cur)) {
+      if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
+      return "keyword";
+    }
+    return "variable";
+  }
+  tokenBase.isBase = true;
+
+  function startString(quote, stream, state) {
+    var tripleQuoted = false;
+    if (quote != "/" && stream.eat(quote)) {
+      if (stream.eat(quote)) tripleQuoted = true;
+      else return "string";
+    }
+    function t(stream, state) {
+      var escaped = false, next, end = !tripleQuoted;
+      while ((next = stream.next()) != null) {
+        if (next == quote && !escaped) {
+          if (!tripleQuoted) { break; }
+          if (stream.match(quote + quote)) { end = true; break; }
+        }
+        if (quote == '"' && next == "$" && !escaped && stream.eat("{")) {
+          state.tokenize.push(tokenBaseUntilBrace());
+          return "string";
+        }
+        escaped = !escaped && next == "\\";
+      }
+      if (end) state.tokenize.pop();
+      return "string";
+    }
+    state.tokenize.push(t);
+    return t(stream, state);
+  }
+
+  function tokenBaseUntilBrace() {
+    var depth = 1;
+    function t(stream, state) {
+      if (stream.peek() == "}") {
+        depth--;
+        if (depth == 0) {
+          state.tokenize.pop();
+          return state.tokenize[state.tokenize.length-1](stream, state);
+        }
+      } else if (stream.peek() == "{") {
+        depth++;
+      }
+      return tokenBase(stream, state);
+    }
+    t.isBase = true;
+    return t;
+  }
+
+  function tokenComment(stream, state) {
+    var maybeEnd = false, ch;
+    while (ch = stream.next()) {
+      if (ch == "/" && maybeEnd) {
+        state.tokenize.pop();
+        break;
+      }
+      maybeEnd = (ch == "*");
+    }
+    return "comment";
+  }
+
+  function expectExpression(last) {
+    return !last || last == "operator" || last == "->" || /[\.\[\{\(,;:]/.test(last) ||
+      last == "newstatement" || last == "keyword" || last == "proplabel";
+  }
+
+  function Context(indented, column, type, align, prev) {
+    this.indented = indented;
+    this.column = column;
+    this.type = type;
+    this.align = align;
+    this.prev = prev;
+  }
+  function pushContext(state, col, type) {
+    return state.context = new Context(state.indented, col, type, null, state.context);
+  }
+  function popContext(state) {
+    var t = state.context.type;
+    if (t == ")" || t == "]" || t == "}")
+      state.indented = state.context.indented;
+    return state.context = state.context.prev;
+  }
+
+  // Interface
+
+  return {
+    startState: function(basecolumn) {
+      return {
+        tokenize: [tokenBase],
+        context: new Context((basecolumn || 0) - config.indentUnit, 0, "top", false),
+        indented: 0,
+        startOfLine: true,
+        lastToken: null
+      };
+    },
+
+    token: function(stream, state) {
+      var ctx = state.context;
+      if (stream.sol()) {
+        if (ctx.align == null) ctx.align = false;
+        state.indented = stream.indentation();
+        state.startOfLine = true;
+        // Automatic semicolon insertion
+        if (ctx.type == "statement" && !expectExpression(state.lastToken)) {
+          popContext(state); ctx = state.context;
+        }
+      }
+      if (stream.eatSpace()) return null;
+      curPunc = null;
+      var style = state.tokenize[state.tokenize.length-1](stream, state);
+      if (style == "comment") return style;
+      if (ctx.align == null) ctx.align = true;
+
+      if ((curPunc == ";" || curPunc == ":") && ctx.type == "statement") popContext(state);
+      // Handle indentation for {x -> \n ... }
+      else if (curPunc == "->" && ctx.type == "statement" && ctx.prev.type == "}") {
+        popContext(state);
+        state.context.align = false;
+      }
+      else if (curPunc == "{") pushContext(state, stream.column(), "}");
+      else if (curPunc == "[") pushContext(state, stream.column(), "]");
+      else if (curPunc == "(") pushContext(state, stream.column(), ")");
+      else if (curPunc == "}") {
+        while (ctx.type == "statement") ctx = popContext(state);
+        if (ctx.type == "}") ctx = popContext(state);
+        while (ctx.type == "statement") ctx = popContext(state);
+      }
+      else if (curPunc == ctx.type) popContext(state);
+      else if (ctx.type == "}" || ctx.type == "top" || (ctx.type == "statement" && curPunc == "newstatement"))
+        pushContext(state, stream.column(), "statement");
+      state.startOfLine = false;
+      state.lastToken = curPunc || style;
+      return style;
+    },
+
+    indent: function(state, textAfter) {
+      if (!state.tokenize[state.tokenize.length-1].isBase) return 0;
+      var firstChar = textAfter && textAfter.charAt(0), ctx = state.context;
+      if (ctx.type == "statement" && !expectExpression(state.lastToken)) ctx = ctx.prev;
+      var closing = firstChar == ctx.type;
+      if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : config.indentUnit);
+      else if (ctx.align) return ctx.column + (closing ? 0 : 1);
+      else return ctx.indented + (closing ? 0 : config.indentUnit);
+    },
+
+    electricChars: "{}",
+    fold: "brace"
+  };
+});
+
+CodeMirror.defineMIME("text/x-groovy", "groovy");
diff --git a/third-party/codemirror-3.15/mode/groovy/index.html b/third-party/codemirror-3.15/mode/groovy/index.html
new file mode 100644 (file)
index 0000000..3d39595
--- /dev/null
@@ -0,0 +1,73 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Groovy mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../../addon/edit/matchbrackets.js"></script>
+    <script src="groovy.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style>.CodeMirror {border-top: 1px solid #500; border-bottom: 1px solid #500;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: Groovy mode</h1>
+
+<form><textarea id="code" name="code">
+//Pattern for groovy script
+def p = ~/.*\.groovy/
+new File( 'd:\\scripts' ).eachFileMatch(p) {f ->
+  // imports list
+  def imports = []
+  f.eachLine {
+    // condition to detect an import instruction
+    ln -> if ( ln =~ '^import .*' ) {
+      imports << "${ln - 'import '}"
+    }
+  }
+  // print thmen
+  if ( ! imports.empty ) {
+    println f
+    imports.each{ println "   $it" }
+  }
+}
+
+/* Coin changer demo code from http://groovy.codehaus.org */
+
+enum UsCoin {
+  quarter(25), dime(10), nickel(5), penny(1)
+  UsCoin(v) { value = v }
+  final value
+}
+
+enum OzzieCoin {
+  fifty(50), twenty(20), ten(10), five(5)
+  OzzieCoin(v) { value = v }
+  final value
+}
+
+def plural(word, count) {
+  if (count == 1) return word
+  word[-1] == 'y' ? word[0..-2] + "ies" : word + "s"
+}
+
+def change(currency, amount) {
+  currency.values().inject([]){ list, coin ->
+     int count = amount / coin.value
+     amount = amount % coin.value
+     list += "$count ${plural(coin.toString(), count)}"
+  }
+}
+</textarea></form>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        matchBrackets: true,
+        mode: "text/x-groovy"
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-groovy</code></p>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/haml/haml.js b/third-party/codemirror-3.15/mode/haml/haml.js
new file mode 100644 (file)
index 0000000..793308f
--- /dev/null
@@ -0,0 +1,153 @@
+(function() {
+  "use strict";
+
+  // full haml mode. This handled embeded ruby and html fragments too
+  CodeMirror.defineMode("haml", function(config) {
+    var htmlMode = CodeMirror.getMode(config, {name: "htmlmixed"});
+    var rubyMode = CodeMirror.getMode(config, "ruby");
+
+    function rubyInQuote(endQuote) {
+      return function(stream, state) {
+        var ch = stream.peek();
+        if (ch == endQuote && state.rubyState.tokenize.length == 1) {
+          // step out of ruby context as it seems to complete processing all the braces
+          stream.next();
+          state.tokenize = html;
+          return "closeAttributeTag";
+        } else {
+          return ruby(stream, state);
+        }
+      };
+    }
+
+    function ruby(stream, state) {
+      if (stream.match("-#")) {
+        stream.skipToEnd();
+        return "comment";
+      }
+      return rubyMode.token(stream, state.rubyState);
+    }
+
+    function html(stream, state) {
+      var ch = stream.peek();
+
+      // handle haml declarations. All declarations that cant be handled here
+      // will be passed to html mode
+      if (state.previousToken.style == "comment" ) {
+        if (state.indented > state.previousToken.indented) {
+          stream.skipToEnd();
+          return "commentLine";
+        }
+      }
+
+      if (state.startOfLine) {
+        if (ch == "!" && stream.match("!!")) {
+          stream.skipToEnd();
+          return "tag";
+        } else if (stream.match(/^%[\w:#\.]+=/)) {
+          state.tokenize = ruby;
+          return "hamlTag";
+        } else if (stream.match(/^%[\w:]+/)) {
+          return "hamlTag";
+        } else if (ch == "/" ) {
+          stream.skipToEnd();
+          return "comment";
+        }
+      }
+
+      if (state.startOfLine || state.previousToken.style == "hamlTag") {
+        if ( ch == "#" || ch == ".") {
+          stream.match(/[\w-#\.]*/);
+          return "hamlAttribute";
+        }
+      }
+
+      // donot handle --> as valid ruby, make it HTML close comment instead
+      if (state.startOfLine && !stream.match("-->", false) && (ch == "=" || ch == "-" )) {
+        state.tokenize = ruby;
+        return null;
+      }
+
+      if (state.previousToken.style == "hamlTag" ||
+          state.previousToken.style == "closeAttributeTag" ||
+          state.previousToken.style == "hamlAttribute") {
+        if (ch == "(") {
+          state.tokenize = rubyInQuote(")");
+          return null;
+        } else if (ch == "{") {
+          state.tokenize = rubyInQuote("}");
+          return null;
+        }
+      }
+
+      return htmlMode.token(stream, state.htmlState);
+    }
+
+    return {
+      // default to html mode
+      startState: function() {
+        var htmlState = htmlMode.startState();
+        var rubyState = rubyMode.startState();
+        return {
+          htmlState: htmlState,
+          rubyState: rubyState,
+          indented: 0,
+          previousToken: { style: null, indented: 0},
+          tokenize: html
+        };
+      },
+
+      copyState: function(state) {
+        return {
+          htmlState : CodeMirror.copyState(htmlMode, state.htmlState),
+          rubyState: CodeMirror.copyState(rubyMode, state.rubyState),
+          indented: state.indented,
+          previousToken: state.previousToken,
+          tokenize: state.tokenize
+        };
+      },
+
+      token: function(stream, state) {
+        if (stream.sol()) {
+          state.indented = stream.indentation();
+          state.startOfLine = true;
+        }
+        if (stream.eatSpace()) return null;
+        var style = state.tokenize(stream, state);
+        state.startOfLine = false;
+        // dont record comment line as we only want to measure comment line with
+        // the opening comment block
+        if (style && style != "commentLine") {
+          state.previousToken = { style: style, indented: state.indented };
+        }
+        // if current state is ruby and the previous token is not `,` reset the
+        // tokenize to html
+        if (stream.eol() && state.tokenize == ruby) {
+          stream.backUp(1);
+          var ch = stream.peek();
+          stream.next();
+          if (ch && ch != ",") {
+            state.tokenize = html;
+          }
+        }
+        // reprocess some of the specific style tag when finish setting previousToken
+        if (style == "hamlTag") {
+          style = "tag";
+        } else if (style == "commentLine") {
+          style = "comment";
+        } else if (style == "hamlAttribute") {
+          style = "attribute";
+        } else if (style == "closeAttributeTag") {
+          style = null;
+        }
+        return style;
+      },
+
+      indent: function(state) {
+        return state.indented;
+      }
+    };
+  }, "htmlmixed", "ruby");
+
+  CodeMirror.defineMIME("text/x-haml", "haml");
+})();
diff --git a/third-party/codemirror-3.15/mode/haml/index.html b/third-party/codemirror-3.15/mode/haml/index.html
new file mode 100644 (file)
index 0000000..7da378f
--- /dev/null
@@ -0,0 +1,67 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: HAML mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../xml/xml.js"></script>
+    <script src="../htmlmixed/htmlmixed.js"></script>
+    <script src="../javascript/javascript.js"></script>
+    <script src="../ruby/ruby.js"></script>
+    <script src="haml.js"></script>
+    <style>.CodeMirror {background: #f8f8f8;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: HAML mode</h1>
+    <form><textarea id="code" name="code">
+!!!
+#content
+.left.column(title="title"){:href => "/hello", :test => "#{hello}_#{world}"}
+    <!-- This is a comment -->
+    %h2 Welcome to our site!
+    %p= puts "HAML MODE"
+  .right.column
+    = render :partial => "sidebar"
+
+.container
+  .row
+    .span8
+      %h1.title= @page_title
+%p.title= @page_title
+%p
+  /
+    The same as HTML comment
+    Hello multiline comment
+
+  -# haml comment
+      This wont be displayed
+      nor will this
+  Date/Time:
+  - now = DateTime.now
+  %strong= now
+  - if now > DateTime.parse("December 31, 2006")
+    = "Happy new " + "year!"
+
+%title
+  = @title
+  \= @title
+  <h1>Title</h1>
+  <h1 title="HELLO">
+    Title
+  </h1>
+    </textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        mode: "text/x-haml"
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-haml</code>.</p>
+
+    <p><strong>Parsing/Highlighting Tests:</strong> <a href="../../test/index.html#haml_*">normal</a>,  <a href="../../test/index.html#verbose,haml_*">verbose</a>.</p>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/haml/test.js b/third-party/codemirror-3.15/mode/haml/test.js
new file mode 100644 (file)
index 0000000..b7178d4
--- /dev/null
@@ -0,0 +1,94 @@
+(function() {
+  var mode = CodeMirror.getMode({tabSize: 4}, "haml");
+  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }
+
+  // Requires at least one media query
+  MT("elementName",
+     "[tag %h1] Hey There");
+
+  MT("oneElementPerLine",
+     "[tag %h1] Hey There %h2");
+
+  MT("idSelector",
+     "[tag %h1][attribute #test] Hey There");
+
+  MT("classSelector",
+     "[tag %h1][attribute .hello] Hey There");
+
+  MT("docType",
+     "[tag !!! XML]");
+
+  MT("comment",
+     "[comment / Hello WORLD]");
+
+  MT("notComment",
+     "[tag %h1] This is not a / comment ");
+
+  MT("attributes",
+     "[tag %a]([variable title][operator =][string \"test\"]){[atom :title] [operator =>] [string \"test\"]}");
+
+  MT("htmlCode",
+     "[tag <h1>]Title[tag </h1>]");
+
+  MT("rubyBlock",
+     "[operator =][variable-2 @item]");
+
+  MT("selectorRubyBlock",
+     "[tag %a.selector=] [variable-2 @item]");
+
+  MT("nestedRubyBlock",
+      "[tag %a]",
+      "   [operator =][variable puts] [string \"test\"]");
+
+  MT("multilinePlaintext",
+      "[tag %p]",
+      "  Hello,",
+      "  World");
+
+  MT("multilineRuby",
+      "[tag %p]",
+      "  [comment -# this is a comment]",
+      "     [comment and this is a comment too]",
+      "  Date/Time",
+      "  [operator -] [variable now] [operator =] [tag DateTime][operator .][variable now]",
+      "  [tag %strong=] [variable now]",
+      "  [operator -] [keyword if] [variable now] [operator >] [tag DateTime][operator .][variable parse]([string \"December 31, 2006\"])",
+      "     [operator =][string \"Happy\"]",
+      "     [operator =][string \"Belated\"]",
+      "     [operator =][string \"Birthday\"]");
+
+  MT("multilineComment",
+      "[comment /]",
+      "  [comment Multiline]",
+      "  [comment Comment]");
+
+  MT("hamlComment",
+     "[comment -# this is a comment]");
+
+  MT("multilineHamlComment",
+     "[comment -# this is a comment]",
+     "   [comment and this is a comment too]");
+
+  MT("multilineHTMLComment",
+    "[comment <!--]",
+    "  [comment what a comment]",
+    "  [comment -->]");
+
+  MT("hamlAfterRubyTag",
+    "[attribute .block]",
+    "  [tag %strong=] [variable now]",
+    "  [attribute .test]",
+    "     [operator =][variable now]",
+    "  [attribute .right]");
+
+  MT("stretchedRuby",
+     "[operator =] [variable puts] [string \"Hello\"],",
+     "   [string \"World\"]");
+
+  MT("interpolationInHashAttribute",
+     //"[tag %div]{[atom :id] [operator =>] [string \"#{][variable test][string }_#{][variable ting][string }\"]} test");
+     "[tag %div]{[atom :id] [operator =>] [string \"#{][variable test][string }_#{][variable ting][string }\"]} test");
+
+  MT("interpolationInHTMLAttribute",
+     "[tag %div]([variable title][operator =][string \"#{][variable test][string }_#{][variable ting]()[string }\"]) Test");
+})();
diff --git a/third-party/codemirror-3.15/mode/haskell/haskell.js b/third-party/codemirror-3.15/mode/haskell/haskell.js
new file mode 100644 (file)
index 0000000..b18d5ce
--- /dev/null
@@ -0,0 +1,246 @@
+CodeMirror.defineMode("haskell", function() {
+
+  function switchState(source, setState, f) {
+    setState(f);
+    return f(source, setState);
+  }
+
+  // These should all be Unicode extended, as per the Haskell 2010 report
+  var smallRE = /[a-z_]/;
+  var largeRE = /[A-Z]/;
+  var digitRE = /[0-9]/;
+  var hexitRE = /[0-9A-Fa-f]/;
+  var octitRE = /[0-7]/;
+  var idRE = /[a-z_A-Z0-9']/;
+  var symbolRE = /[-!#$%&*+.\/<=>?@\\^|~:]/;
+  var specialRE = /[(),;[\]`{}]/;
+  var whiteCharRE = /[ \t\v\f]/; // newlines are handled in tokenizer
+
+  function normal(source, setState) {
+    if (source.eatWhile(whiteCharRE)) {
+      return null;
+    }
+
+    var ch = source.next();
+    if (specialRE.test(ch)) {
+      if (ch == '{' && source.eat('-')) {
+        var t = "comment";
+        if (source.eat('#')) {
+          t = "meta";
+        }
+        return switchState(source, setState, ncomment(t, 1));
+      }
+      return null;
+    }
+
+    if (ch == '\'') {
+      if (source.eat('\\')) {
+        source.next();  // should handle other escapes here
+      }
+      else {
+        source.next();
+      }
+      if (source.eat('\'')) {
+        return "string";
+      }
+      return "error";
+    }
+
+    if (ch == '"') {
+      return switchState(source, setState, stringLiteral);
+    }
+
+    if (largeRE.test(ch)) {
+      source.eatWhile(idRE);
+      if (source.eat('.')) {
+        return "qualifier";
+      }
+      return "variable-2";
+    }
+
+    if (smallRE.test(ch)) {
+      source.eatWhile(idRE);
+      return "variable";
+    }
+
+    if (digitRE.test(ch)) {
+      if (ch == '0') {
+        if (source.eat(/[xX]/)) {
+          source.eatWhile(hexitRE); // should require at least 1
+          return "integer";
+        }
+        if (source.eat(/[oO]/)) {
+          source.eatWhile(octitRE); // should require at least 1
+          return "number";
+        }
+      }
+      source.eatWhile(digitRE);
+      var t = "number";
+      if (source.eat('.')) {
+        t = "number";
+        source.eatWhile(digitRE); // should require at least 1
+      }
+      if (source.eat(/[eE]/)) {
+        t = "number";
+        source.eat(/[-+]/);
+        source.eatWhile(digitRE); // should require at least 1
+      }
+      return t;
+    }
+
+    if (symbolRE.test(ch)) {
+      if (ch == '-' && source.eat(/-/)) {
+        source.eatWhile(/-/);
+        if (!source.eat(symbolRE)) {
+          source.skipToEnd();
+          return "comment";
+        }
+      }
+      var t = "variable";
+      if (ch == ':') {
+        t = "variable-2";
+      }
+      source.eatWhile(symbolRE);
+      return t;
+    }
+
+    return "error";
+  }
+
+  function ncomment(type, nest) {
+    if (nest == 0) {
+      return normal;
+    }
+    return function(source, setState) {
+      var currNest = nest;
+      while (!source.eol()) {
+        var ch = source.next();
+        if (ch == '{' && source.eat('-')) {
+          ++currNest;
+        }
+        else if (ch == '-' && source.eat('}')) {
+          --currNest;
+          if (currNest == 0) {
+            setState(normal);
+            return type;
+          }
+        }
+      }
+      setState(ncomment(type, currNest));
+      return type;
+    };
+  }
+
+  function stringLiteral(source, setState) {
+    while (!source.eol()) {
+      var ch = source.next();
+      if (ch == '"') {
+        setState(normal);
+        return "string";
+      }
+      if (ch == '\\') {
+        if (source.eol() || source.eat(whiteCharRE)) {
+          setState(stringGap);
+          return "string";
+        }
+        if (source.eat('&')) {
+        }
+        else {
+          source.next(); // should handle other escapes here
+        }
+      }
+    }
+    setState(normal);
+    return "error";
+  }
+
+  function stringGap(source, setState) {
+    if (source.eat('\\')) {
+      return switchState(source, setState, stringLiteral);
+    }
+    source.next();
+    setState(normal);
+    return "error";
+  }
+
+
+  var wellKnownWords = (function() {
+    var wkw = {};
+    function setType(t) {
+      return function () {
+        for (var i = 0; i < arguments.length; i++)
+          wkw[arguments[i]] = t;
+      };
+    }
+
+    setType("keyword")(
+      "case", "class", "data", "default", "deriving", "do", "else", "foreign",
+      "if", "import", "in", "infix", "infixl", "infixr", "instance", "let",
+      "module", "newtype", "of", "then", "type", "where", "_");
+
+    setType("keyword")(
+      "\.\.", ":", "::", "=", "\\", "\"", "<-", "->", "@", "~", "=>");
+
+    setType("builtin")(
+      "!!", "$!", "$", "&&", "+", "++", "-", ".", "/", "/=", "<", "<=", "=<<",
+      "==", ">", ">=", ">>", ">>=", "^", "^^", "||", "*", "**");
+
+    setType("builtin")(
+      "Bool", "Bounded", "Char", "Double", "EQ", "Either", "Enum", "Eq",
+      "False", "FilePath", "Float", "Floating", "Fractional", "Functor", "GT",
+      "IO", "IOError", "Int", "Integer", "Integral", "Just", "LT", "Left",
+      "Maybe", "Monad", "Nothing", "Num", "Ord", "Ordering", "Rational", "Read",
+      "ReadS", "Real", "RealFloat", "RealFrac", "Right", "Show", "ShowS",
+      "String", "True");
+
+    setType("builtin")(
+      "abs", "acos", "acosh", "all", "and", "any", "appendFile", "asTypeOf",
+      "asin", "asinh", "atan", "atan2", "atanh", "break", "catch", "ceiling",
+      "compare", "concat", "concatMap", "const", "cos", "cosh", "curry",
+      "cycle", "decodeFloat", "div", "divMod", "drop", "dropWhile", "either",
+      "elem", "encodeFloat", "enumFrom", "enumFromThen", "enumFromThenTo",
+      "enumFromTo", "error", "even", "exp", "exponent", "fail", "filter",
+      "flip", "floatDigits", "floatRadix", "floatRange", "floor", "fmap",
+      "foldl", "foldl1", "foldr", "foldr1", "fromEnum", "fromInteger",
+      "fromIntegral", "fromRational", "fst", "gcd", "getChar", "getContents",
+      "getLine", "head", "id", "init", "interact", "ioError", "isDenormalized",
+      "isIEEE", "isInfinite", "isNaN", "isNegativeZero", "iterate", "last",
+      "lcm", "length", "lex", "lines", "log", "logBase", "lookup", "map",
+      "mapM", "mapM_", "max", "maxBound", "maximum", "maybe", "min", "minBound",
+      "minimum", "mod", "negate", "not", "notElem", "null", "odd", "or",
+      "otherwise", "pi", "pred", "print", "product", "properFraction",
+      "putChar", "putStr", "putStrLn", "quot", "quotRem", "read", "readFile",
+      "readIO", "readList", "readLn", "readParen", "reads", "readsPrec",
+      "realToFrac", "recip", "rem", "repeat", "replicate", "return", "reverse",
+      "round", "scaleFloat", "scanl", "scanl1", "scanr", "scanr1", "seq",
+      "sequence", "sequence_", "show", "showChar", "showList", "showParen",
+      "showString", "shows", "showsPrec", "significand", "signum", "sin",
+      "sinh", "snd", "span", "splitAt", "sqrt", "subtract", "succ", "sum",
+      "tail", "take", "takeWhile", "tan", "tanh", "toEnum", "toInteger",
+      "toRational", "truncate", "uncurry", "undefined", "unlines", "until",
+      "unwords", "unzip", "unzip3", "userError", "words", "writeFile", "zip",
+      "zip3", "zipWith", "zipWith3");
+
+    return wkw;
+  })();
+
+
+
+  return {
+    startState: function ()  { return { f: normal }; },
+    copyState:  function (s) { return { f: s.f }; },
+
+    token: function(stream, state) {
+      var t = state.f(stream, function(s) { state.f = s; });
+      var w = stream.current();
+      return (w in wellKnownWords) ? wellKnownWords[w] : t;
+    },
+
+    blockCommentStart: "{-",
+    blockCommentEnd: "-}",
+    lineComment: "--"
+  };
+
+});
+
+CodeMirror.defineMIME("text/x-haskell", "haskell");
diff --git a/third-party/codemirror-3.15/mode/haskell/index.html b/third-party/codemirror-3.15/mode/haskell/index.html
new file mode 100644 (file)
index 0000000..56307b8
--- /dev/null
@@ -0,0 +1,62 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Haskell mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../../addon/edit/matchbrackets.js"></script>
+    <script src="haskell.js"></script>
+    <link rel="stylesheet" href="../../theme/elegant.css">
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Haskell mode</h1>
+
+<form><textarea id="code" name="code">
+module UniquePerms (
+    uniquePerms
+    )
+where
+
+-- | Find all unique permutations of a list where there might be duplicates.
+uniquePerms :: (Eq a) => [a] -> [[a]]
+uniquePerms = permBag . makeBag
+
+-- | An unordered collection where duplicate values are allowed,
+-- but represented with a single value and a count.
+type Bag a = [(a, Int)]
+
+makeBag :: (Eq a) => [a] -> Bag a
+makeBag [] = []
+makeBag (a:as) = mix a $ makeBag as
+  where
+    mix a []                        = [(a,1)]
+    mix a (bn@(b,n):bs) | a == b    = (b,n+1):bs
+                        | otherwise = bn : mix a bs
+
+permBag :: Bag a -> [[a]]
+permBag [] = [[]]
+permBag bs = concatMap (\(f,cs) -> map (f:) $ permBag cs) . oneOfEach $ bs
+  where
+    oneOfEach [] = []
+    oneOfEach (an@(a,n):bs) =
+        let bs' = if n == 1 then bs else (a,n-1):bs
+        in (a,bs') : mapSnd (an:) (oneOfEach bs)
+    
+    apSnd f (a,b) = (a, f b)
+    mapSnd = map . apSnd
+</textarea></form>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        matchBrackets: true,
+        theme: "elegant"
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-haskell</code>.</p>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/haxe/haxe.js b/third-party/codemirror-3.15/mode/haxe/haxe.js
new file mode 100644 (file)
index 0000000..28f9b00
--- /dev/null
@@ -0,0 +1,429 @@
+CodeMirror.defineMode("haxe", function(config, parserConfig) {
+  var indentUnit = config.indentUnit;
+
+  // Tokenizer
+
+  var keywords = function(){
+    function kw(type) {return {type: type, style: "keyword"};}
+    var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c");
+    var operator = kw("operator"), atom = {type: "atom", style: "atom"}, attribute = {type:"attribute", style: "attribute"};
+  var type = kw("typedef");
+    return {
+      "if": A, "while": A, "else": B, "do": B, "try": B,
+      "return": C, "break": C, "continue": C, "new": C, "throw": C,
+      "var": kw("var"), "inline":attribute, "static": attribute, "using":kw("import"),
+    "public": attribute, "private": attribute, "cast": kw("cast"), "import": kw("import"), "macro": kw("macro"),
+      "function": kw("function"), "catch": kw("catch"), "untyped": kw("untyped"), "callback": kw("cb"),
+      "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"),
+      "in": operator, "never": kw("property_access"), "trace":kw("trace"),
+    "class": type, "enum":type, "interface":type, "typedef":type, "extends":type, "implements":type, "dynamic":type,
+      "true": atom, "false": atom, "null": atom
+    };
+  }();
+
+  var isOperatorChar = /[+\-*&%=<>!?|]/;
+
+  function chain(stream, state, f) {
+    state.tokenize = f;
+    return f(stream, state);
+  }
+
+  function nextUntilUnescaped(stream, end) {
+    var escaped = false, next;
+    while ((next = stream.next()) != null) {
+      if (next == end && !escaped)
+        return false;
+      escaped = !escaped && next == "\\";
+    }
+    return escaped;
+  }
+
+  // Used as scratch variables to communicate multiple values without
+  // consing up tons of objects.
+  var type, content;
+  function ret(tp, style, cont) {
+    type = tp; content = cont;
+    return style;
+  }
+
+  function haxeTokenBase(stream, state) {
+    var ch = stream.next();
+    if (ch == '"' || ch == "'")
+      return chain(stream, state, haxeTokenString(ch));
+    else if (/[\[\]{}\(\),;\:\.]/.test(ch))
+      return ret(ch);
+    else if (ch == "0" && stream.eat(/x/i)) {
+      stream.eatWhile(/[\da-f]/i);
+      return ret("number", "number");
+    }
+    else if (/\d/.test(ch) || ch == "-" && stream.eat(/\d/)) {
+      stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/);
+      return ret("number", "number");
+    }
+    else if (state.reAllowed && (ch == "~" && stream.eat(/\//))) {
+      nextUntilUnescaped(stream, "/");
+      stream.eatWhile(/[gimsu]/);
+      return ret("regexp", "string-2");
+    }
+    else if (ch == "/") {
+      if (stream.eat("*")) {
+        return chain(stream, state, haxeTokenComment);
+      }
+      else if (stream.eat("/")) {
+        stream.skipToEnd();
+        return ret("comment", "comment");
+      }
+      else {
+        stream.eatWhile(isOperatorChar);
+        return ret("operator", null, stream.current());
+      }
+    }
+    else if (ch == "#") {
+        stream.skipToEnd();
+        return ret("conditional", "meta");
+    }
+    else if (ch == "@") {
+      stream.eat(/:/);
+      stream.eatWhile(/[\w_]/);
+      return ret ("metadata", "meta");
+    }
+    else if (isOperatorChar.test(ch)) {
+      stream.eatWhile(isOperatorChar);
+      return ret("operator", null, stream.current());
+    }
+    else {
+    var word;
+    if(/[A-Z]/.test(ch))
+    {
+      stream.eatWhile(/[\w_<>]/);
+      word = stream.current();
+      return ret("type", "variable-3", word);
+    }
+    else
+    {
+        stream.eatWhile(/[\w_]/);
+        var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word];
+        return (known && state.kwAllowed) ? ret(known.type, known.style, word) :
+                       ret("variable", "variable", word);
+    }
+    }
+  }
+
+  function haxeTokenString(quote) {
+    return function(stream, state) {
+      if (!nextUntilUnescaped(stream, quote))
+        state.tokenize = haxeTokenBase;
+      return ret("string", "string");
+    };
+  }
+
+  function haxeTokenComment(stream, state) {
+    var maybeEnd = false, ch;
+    while (ch = stream.next()) {
+      if (ch == "/" && maybeEnd) {
+        state.tokenize = haxeTokenBase;
+        break;
+      }
+      maybeEnd = (ch == "*");
+    }
+    return ret("comment", "comment");
+  }
+
+  // Parser
+
+  var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true};
+
+  function HaxeLexical(indented, column, type, align, prev, info) {
+    this.indented = indented;
+    this.column = column;
+    this.type = type;
+    this.prev = prev;
+    this.info = info;
+    if (align != null) this.align = align;
+  }
+
+  function inScope(state, varname) {
+    for (var v = state.localVars; v; v = v.next)
+      if (v.name == varname) return true;
+  }
+
+  function parseHaxe(state, style, type, content, stream) {
+    var cc = state.cc;
+    // Communicate our context to the combinators.
+    // (Less wasteful than consing up a hundred closures on every call.)
+    cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc;
+
+    if (!state.lexical.hasOwnProperty("align"))
+      state.lexical.align = true;
+
+    while(true) {
+      var combinator = cc.length ? cc.pop() : statement;
+      if (combinator(type, content)) {
+        while(cc.length && cc[cc.length - 1].lex)
+          cc.pop()();
+        if (cx.marked) return cx.marked;
+        if (type == "variable" && inScope(state, content)) return "variable-2";
+    if (type == "variable" && imported(state, content)) return "variable-3";
+        return style;
+      }
+    }
+  }
+
+  function imported(state, typename)
+  {
+  if (/[a-z]/.test(typename.charAt(0)))
+    return false;
+  var len = state.importedtypes.length;
+  for (var i = 0; i<len; i++)
+    if(state.importedtypes[i]==typename) return true;
+  }
+
+
+  function registerimport(importname) {
+  var state = cx.state;
+  for (var t = state.importedtypes; t; t = t.next)
+    if(t.name == importname) return;
+  state.importedtypes = { name: importname, next: state.importedtypes };
+  }
+  // Combinator utils
+
+  var cx = {state: null, column: null, marked: null, cc: null};
+  function pass() {
+    for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);
+  }
+  function cont() {
+    pass.apply(null, arguments);
+    return true;
+  }
+  function register(varname) {
+    var state = cx.state;
+    if (state.context) {
+      cx.marked = "def";
+      for (var v = state.localVars; v; v = v.next)
+        if (v.name == varname) return;
+      state.localVars = {name: varname, next: state.localVars};
+    }
+  }
+
+  // Combinators
+
+  var defaultVars = {name: "this", next: null};
+  function pushcontext() {
+    if (!cx.state.context) cx.state.localVars = defaultVars;
+    cx.state.context = {prev: cx.state.context, vars: cx.state.localVars};
+  }
+  function popcontext() {
+    cx.state.localVars = cx.state.context.vars;
+    cx.state.context = cx.state.context.prev;
+  }
+  function pushlex(type, info) {
+    var result = function() {
+      var state = cx.state;
+      state.lexical = new HaxeLexical(state.indented, cx.stream.column(), type, null, state.lexical, info);
+    };
+    result.lex = true;
+    return result;
+  }
+  function poplex() {
+    var state = cx.state;
+    if (state.lexical.prev) {
+      if (state.lexical.type == ")")
+        state.indented = state.lexical.indented;
+      state.lexical = state.lexical.prev;
+    }
+  }
+  poplex.lex = true;
+
+  function expect(wanted) {
+    return function(type) {
+      if (type == wanted) return cont();
+      else if (wanted == ";") return pass();
+      else return cont(arguments.callee);
+    };
+  }
+
+  function statement(type) {
+    if (type == "@") return cont(metadef);
+    if (type == "var") return cont(pushlex("vardef"), vardef1, expect(";"), poplex);
+    if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex);
+    if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
+    if (type == "{") return cont(pushlex("}"), pushcontext, block, poplex, popcontext);
+    if (type == ";") return cont();
+    if (type == "attribute") return cont(maybeattribute);
+    if (type == "function") return cont(functiondef);
+    if (type == "for") return cont(pushlex("form"), expect("("), pushlex(")"), forspec1, expect(")"),
+                                      poplex, statement, poplex);
+    if (type == "variable") return cont(pushlex("stat"), maybelabel);
+    if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"),
+                                         block, poplex, poplex);
+    if (type == "case") return cont(expression, expect(":"));
+    if (type == "default") return cont(expect(":"));
+    if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"),
+                                        statement, poplex, popcontext);
+    if (type == "import") return cont(importdef, expect(";"));
+    if (type == "typedef") return cont(typedef);
+    return pass(pushlex("stat"), expression, expect(";"), poplex);
+  }
+  function expression(type) {
+    if (atomicTypes.hasOwnProperty(type)) return cont(maybeoperator);
+    if (type == "function") return cont(functiondef);
+    if (type == "keyword c") return cont(maybeexpression);
+    if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeoperator);
+    if (type == "operator") return cont(expression);
+    if (type == "[") return cont(pushlex("]"), commasep(expression, "]"), poplex, maybeoperator);
+    if (type == "{") return cont(pushlex("}"), commasep(objprop, "}"), poplex, maybeoperator);
+    return cont();
+  }
+  function maybeexpression(type) {
+    if (type.match(/[;\}\)\],]/)) return pass();
+    return pass(expression);
+  }
+
+  function maybeoperator(type, value) {
+    if (type == "operator" && /\+\+|--/.test(value)) return cont(maybeoperator);
+    if (type == "operator" || type == ":") return cont(expression);
+    if (type == ";") return;
+    if (type == "(") return cont(pushlex(")"), commasep(expression, ")"), poplex, maybeoperator);
+    if (type == ".") return cont(property, maybeoperator);
+    if (type == "[") return cont(pushlex("]"), expression, expect("]"), poplex, maybeoperator);
+  }
+
+  function maybeattribute(type) {
+    if (type == "attribute") return cont(maybeattribute);
+    if (type == "function") return cont(functiondef);
+    if (type == "var") return cont(vardef1);
+  }
+
+  function metadef(type) {
+    if(type == ":") return cont(metadef);
+    if(type == "variable") return cont(metadef);
+    if(type == "(") return cont(pushlex(")"), comasep(metaargs, ")"), poplex, statement);
+  }
+  function metaargs(type) {
+    if(type == "variable") return cont();
+  }
+
+  function importdef (type, value) {
+  if(type == "variable" && /[A-Z]/.test(value.charAt(0))) { registerimport(value); return cont(); }
+  else if(type == "variable" || type == "property" || type == ".") return cont(importdef);
+  }
+
+  function typedef (type, value)
+  {
+  if(type == "variable" && /[A-Z]/.test(value.charAt(0))) { registerimport(value); return cont(); }
+  }
+
+  function maybelabel(type) {
+    if (type == ":") return cont(poplex, statement);
+    return pass(maybeoperator, expect(";"), poplex);
+  }
+  function property(type) {
+    if (type == "variable") {cx.marked = "property"; return cont();}
+  }
+  function objprop(type) {
+    if (type == "variable") cx.marked = "property";
+    if (atomicTypes.hasOwnProperty(type)) return cont(expect(":"), expression);
+  }
+  function commasep(what, end) {
+    function proceed(type) {
+      if (type == ",") return cont(what, proceed);
+      if (type == end) return cont();
+      return cont(expect(end));
+    }
+    return function(type) {
+      if (type == end) return cont();
+      else return pass(what, proceed);
+    };
+  }
+  function block(type) {
+    if (type == "}") return cont();
+    return pass(statement, block);
+  }
+  function vardef1(type, value) {
+    if (type == "variable"){register(value); return cont(typeuse, vardef2);}
+    return cont();
+  }
+  function vardef2(type, value) {
+    if (value == "=") return cont(expression, vardef2);
+    if (type == ",") return cont(vardef1);
+  }
+  function forspec1(type, value) {
+  if (type == "variable") {
+    register(value);
+  }
+  return cont(pushlex(")"), pushcontext, forin, expression, poplex, statement, popcontext);
+  }
+  function forin(_type, value) {
+    if (value == "in") return cont();
+  }
+  function functiondef(type, value) {
+    if (type == "variable") {register(value); return cont(functiondef);}
+    if (value == "new") return cont(functiondef);
+    if (type == "(") return cont(pushlex(")"), pushcontext, commasep(funarg, ")"), poplex, typeuse, statement, popcontext);
+  }
+  function typeuse(type) {
+    if(type == ":") return cont(typestring);
+  }
+  function typestring(type) {
+    if(type == "type") return cont();
+    if(type == "variable") return cont();
+    if(type == "{") return cont(pushlex("}"), commasep(typeprop, "}"), poplex);
+  }
+  function typeprop(type) {
+    if(type == "variable") return cont(typeuse);
+  }
+  function funarg(type, value) {
+    if (type == "variable") {register(value); return cont(typeuse);}
+  }
+
+  // Interface
+
+  return {
+    startState: function(basecolumn) {
+    var defaulttypes = ["Int", "Float", "String", "Void", "Std", "Bool", "Dynamic", "Array"];
+      return {
+        tokenize: haxeTokenBase,
+        reAllowed: true,
+        kwAllowed: true,
+        cc: [],
+        lexical: new HaxeLexical((basecolumn || 0) - indentUnit, 0, "block", false),
+        localVars: parserConfig.localVars,
+    importedtypes: defaulttypes,
+        context: parserConfig.localVars && {vars: parserConfig.localVars},
+        indented: 0
+      };
+    },
+
+    token: function(stream, state) {
+      if (stream.sol()) {
+        if (!state.lexical.hasOwnProperty("align"))
+          state.lexical.align = false;
+        state.indented = stream.indentation();
+      }
+      if (stream.eatSpace()) return null;
+      var style = state.tokenize(stream, state);
+      if (type == "comment") return style;
+      state.reAllowed = !!(type == "operator" || type == "keyword c" || type.match(/^[\[{}\(,;:]$/));
+      state.kwAllowed = type != '.';
+      return parseHaxe(state, style, type, content, stream);
+    },
+
+    indent: function(state, textAfter) {
+      if (state.tokenize != haxeTokenBase) return 0;
+      var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical;
+      if (lexical.type == "stat" && firstChar == "}") lexical = lexical.prev;
+      var type = lexical.type, closing = firstChar == type;
+      if (type == "vardef") return lexical.indented + 4;
+      else if (type == "form" && firstChar == "{") return lexical.indented;
+      else if (type == "stat" || type == "form") return lexical.indented + indentUnit;
+      else if (lexical.info == "switch" && !closing)
+        return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);
+      else if (lexical.align) return lexical.column + (closing ? 0 : 1);
+      else return lexical.indented + (closing ? 0 : indentUnit);
+    },
+
+    electricChars: "{}"
+  };
+});
+
+CodeMirror.defineMIME("text/x-haxe", "haxe");
diff --git a/third-party/codemirror-3.15/mode/haxe/index.html b/third-party/codemirror-3.15/mode/haxe/index.html
new file mode 100644 (file)
index 0000000..1125741
--- /dev/null
@@ -0,0 +1,90 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Haxe mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="haxe.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: Haxe mode</h1>
+
+<div><textarea id="code" name="code">
+import one.two.Three;
+
+@attr("test")
+class Foo&lt;T&gt; extends Three
+{
+       public function new()
+       {
+               noFoo = 12;
+       }
+       
+       public static inline function doFoo(obj:{k:Int, l:Float}):Int
+       {
+               for(i in 0...10)
+               {
+                       obj.k++;
+                       trace(i);
+                       var var1 = new Array();
+                       if(var1.length > 1)
+                               throw "Error";
+               }
+               // The following line should not be colored, the variable is scoped out
+               var1;
+               /* Multi line
+                * Comment test
+                */
+               return obj.k;
+       }
+       private function bar():Void
+       {
+               #if flash
+               var t1:String = "1.21";
+               #end
+               try {
+                       doFoo({k:3, l:1.2});
+               }
+               catch (e : String) {
+                       trace(e);
+               }
+               var t2:Float = cast(3.2);
+               var t3:haxe.Timer = new haxe.Timer();
+               var t4 = {k:Std.int(t2), l:Std.parseFloat(t1)};
+               var t5 = ~/123+.*$/i;
+               doFoo(t4);
+               untyped t1 = 4;
+               bob = new Foo&lt;Int&gt;
+       }
+       public var okFoo(default, never):Float;
+       var noFoo(getFoo, null):Int;
+       function getFoo():Int {
+               return noFoo;
+       }
+       
+       public var three:Int;
+}
+enum Color
+{
+       red;
+       green;
+       blue;
+       grey( v : Int );
+       rgb (r:Int,g:Int,b:Int);
+}
+</textarea></div>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        indentUnit: 4,
+        indentWithTabs: true
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-haxe</code>.</p>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/htmlembedded/htmlembedded.js b/third-party/codemirror-3.15/mode/htmlembedded/htmlembedded.js
new file mode 100644 (file)
index 0000000..ff6dfd2
--- /dev/null
@@ -0,0 +1,73 @@
+CodeMirror.defineMode("htmlembedded", function(config, parserConfig) {
+
+  //config settings
+  var scriptStartRegex = parserConfig.scriptStartRegex || /^<%/i,
+      scriptEndRegex = parserConfig.scriptEndRegex || /^%>/i;
+
+  //inner modes
+  var scriptingMode, htmlMixedMode;
+
+  //tokenizer when in html mode
+  function htmlDispatch(stream, state) {
+      if (stream.match(scriptStartRegex, false)) {
+          state.token=scriptingDispatch;
+          return scriptingMode.token(stream, state.scriptState);
+          }
+      else
+          return htmlMixedMode.token(stream, state.htmlState);
+    }
+
+  //tokenizer when in scripting mode
+  function scriptingDispatch(stream, state) {
+      if (stream.match(scriptEndRegex, false))  {
+          state.token=htmlDispatch;
+          return htmlMixedMode.token(stream, state.htmlState);
+         }
+      else
+          return scriptingMode.token(stream, state.scriptState);
+         }
+
+
+  return {
+    startState: function() {
+      scriptingMode = scriptingMode || CodeMirror.getMode(config, parserConfig.scriptingModeSpec);
+      htmlMixedMode = htmlMixedMode || CodeMirror.getMode(config, "htmlmixed");
+      return {
+          token :  parserConfig.startOpen ? scriptingDispatch : htmlDispatch,
+          htmlState : CodeMirror.startState(htmlMixedMode),
+          scriptState : CodeMirror.startState(scriptingMode)
+      };
+    },
+
+    token: function(stream, state) {
+      return state.token(stream, state);
+    },
+
+    indent: function(state, textAfter) {
+      if (state.token == htmlDispatch)
+        return htmlMixedMode.indent(state.htmlState, textAfter);
+      else if (scriptingMode.indent)
+        return scriptingMode.indent(state.scriptState, textAfter);
+    },
+
+    copyState: function(state) {
+      return {
+       token : state.token,
+       htmlState : CodeMirror.copyState(htmlMixedMode, state.htmlState),
+       scriptState : CodeMirror.copyState(scriptingMode, state.scriptState)
+      };
+    },
+
+    electricChars: "/{}:",
+
+    innerMode: function(state) {
+      if (state.token == scriptingDispatch) return {state: state.scriptState, mode: scriptingMode};
+      else return {state: state.htmlState, mode: htmlMixedMode};
+    }
+  };
+}, "htmlmixed");
+
+CodeMirror.defineMIME("application/x-ejs", { name: "htmlembedded", scriptingModeSpec:"javascript"});
+CodeMirror.defineMIME("application/x-aspx", { name: "htmlembedded", scriptingModeSpec:"text/x-csharp"});
+CodeMirror.defineMIME("application/x-jsp", { name: "htmlembedded", scriptingModeSpec:"text/x-java"});
+CodeMirror.defineMIME("application/x-erb", { name: "htmlembedded", scriptingModeSpec:"ruby"});
diff --git a/third-party/codemirror-3.15/mode/htmlembedded/index.html b/third-party/codemirror-3.15/mode/htmlembedded/index.html
new file mode 100644 (file)
index 0000000..5a37dd6
--- /dev/null
@@ -0,0 +1,49 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Html Embedded Scripts mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../xml/xml.js"></script>
+    <script src="../javascript/javascript.js"></script>
+    <script src="../css/css.js"></script>
+    <script src="../htmlmixed/htmlmixed.js"></script>
+    <script src="htmlembedded.js"></script>
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Html Embedded Scripts mode</h1>
+
+<form><textarea id="code" name="code">
+<%
+function hello(who) {
+       return "Hello " + who;
+}
+%>
+This is an example of EJS (embedded javascript)
+<p>The program says <%= hello("world") %>.</p>
+<script>
+       alert("And here is some normal JS code"); // also colored
+</script>
+</textarea></form>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        mode: "application/x-ejs",
+        indentUnit: 4,
+        indentWithTabs: true,
+        enterMode: "keep",
+        tabMode: "shift"
+      });
+    </script>
+
+    <p>Mode for html embedded scripts like JSP and ASP.NET. Depends on HtmlMixed which in turn depends on
+    JavaScript, CSS and XML.<br />Other dependancies include those of the scriping language chosen.</p>
+
+    <p><strong>MIME types defined:</strong> <code>application/x-aspx</code> (ASP.NET), 
+    <code>application/x-ejs</code> (Embedded Javascript), <code>application/x-jsp</code> (JavaServer Pages)</p>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/htmlmixed/htmlmixed.js b/third-party/codemirror-3.15/mode/htmlmixed/htmlmixed.js
new file mode 100644 (file)
index 0000000..ec0c21d
--- /dev/null
@@ -0,0 +1,104 @@
+CodeMirror.defineMode("htmlmixed", function(config, parserConfig) {
+  var htmlMode = CodeMirror.getMode(config, {name: "xml", htmlMode: true});
+  var cssMode = CodeMirror.getMode(config, "css");
+
+  var scriptTypes = [], scriptTypesConf = parserConfig && parserConfig.scriptTypes;
+  scriptTypes.push({matches: /^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^$/i,
+                    mode: CodeMirror.getMode(config, "javascript")});
+  if (scriptTypesConf) for (var i = 0; i < scriptTypesConf.length; ++i) {
+    var conf = scriptTypesConf[i];
+    scriptTypes.push({matches: conf.matches, mode: conf.mode && CodeMirror.getMode(config, conf.mode)});
+  }
+  scriptTypes.push({matches: /./,
+                    mode: CodeMirror.getMode(config, "text/plain")});
+
+  function html(stream, state) {
+    var tagName = state.htmlState.tagName;
+    var style = htmlMode.token(stream, state.htmlState);
+    if (tagName == "script" && /\btag\b/.test(style) && stream.current() == ">") {
+      // Script block: mode to change to depends on type attribute
+      var scriptType = stream.string.slice(Math.max(0, stream.pos - 100), stream.pos).match(/\btype\s*=\s*("[^"]+"|'[^']+'|\S+)[^<]*$/i);
+      scriptType = scriptType ? scriptType[1] : "";
+      if (scriptType && /[\"\']/.test(scriptType.charAt(0))) scriptType = scriptType.slice(1, scriptType.length - 1);
+      for (var i = 0; i < scriptTypes.length; ++i) {
+        var tp = scriptTypes[i];
+        if (typeof tp.matches == "string" ? scriptType == tp.matches : tp.matches.test(scriptType)) {
+          if (tp.mode) {
+            state.token = script;
+            state.localMode = tp.mode;
+            state.localState = tp.mode.startState && tp.mode.startState(htmlMode.indent(state.htmlState, ""));
+          }
+          break;
+        }
+      }
+    } else if (tagName == "style" && /\btag\b/.test(style) && stream.current() == ">") {
+      state.token = css;
+      state.localMode = cssMode;
+      state.localState = cssMode.startState(htmlMode.indent(state.htmlState, ""));
+    }
+    return style;
+  }
+  function maybeBackup(stream, pat, style) {
+    var cur = stream.current();
+    var close = cur.search(pat), m;
+    if (close > -1) stream.backUp(cur.length - close);
+    else if (m = cur.match(/<\/?$/)) {
+      stream.backUp(cur.length);
+      if (!stream.match(pat, false)) stream.match(cur[0]);
+    }
+    return style;
+  }
+  function script(stream, state) {
+    if (stream.match(/^<\/\s*script\s*>/i, false)) {
+      state.token = html;
+      state.localState = state.localMode = null;
+      return html(stream, state);
+    }
+    return maybeBackup(stream, /<\/\s*script\s*>/,
+                       state.localMode.token(stream, state.localState));
+  }
+  function css(stream, state) {
+    if (stream.match(/^<\/\s*style\s*>/i, false)) {
+      state.token = html;
+      state.localState = state.localMode = null;
+      return html(stream, state);
+    }
+    return maybeBackup(stream, /<\/\s*style\s*>/,
+                       cssMode.token(stream, state.localState));
+  }
+
+  return {
+    startState: function() {
+      var state = htmlMode.startState();
+      return {token: html, localMode: null, localState: null, htmlState: state};
+    },
+
+    copyState: function(state) {
+      if (state.localState)
+        var local = CodeMirror.copyState(state.localMode, state.localState);
+      return {token: state.token, localMode: state.localMode, localState: local,
+              htmlState: CodeMirror.copyState(htmlMode, state.htmlState)};
+    },
+
+    token: function(stream, state) {
+      return state.token(stream, state);
+    },
+
+    indent: function(state, textAfter) {
+      if (!state.localMode || /^\s*<\//.test(textAfter))
+        return htmlMode.indent(state.htmlState, textAfter);
+      else if (state.localMode.indent)
+        return state.localMode.indent(state.localState, textAfter);
+      else
+        return CodeMirror.Pass;
+    },
+
+    electricChars: "/{}:",
+
+    innerMode: function(state) {
+      return {state: state.localState || state.htmlState, mode: state.localMode || htmlMode};
+    }
+  };
+}, "xml", "javascript", "css");
+
+CodeMirror.defineMIME("text/html", "htmlmixed");
diff --git a/third-party/codemirror-3.15/mode/htmlmixed/index.html b/third-party/codemirror-3.15/mode/htmlmixed/index.html
new file mode 100644 (file)
index 0000000..c56559e
--- /dev/null
@@ -0,0 +1,73 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: HTML mixed mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../xml/xml.js"></script>
+    <script src="../javascript/javascript.js"></script>
+    <script src="../css/css.js"></script>
+    <script src="../vbscript/vbscript.js"></script>
+    <script src="htmlmixed.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: HTML mixed mode</h1>
+    <form><textarea id="code" name="code">
+<html style="color: green">
+  <!-- this is a comment -->
+  <head>
+    <title>Mixed HTML Example</title>
+    <style type="text/css">
+      h1 {font-family: comic sans; color: #f0f;}
+      div {background: yellow !important;}
+      body {
+        max-width: 50em;
+        margin: 1em 2em 1em 5em;
+      }
+    </style>
+  </head>
+  <body>
+    <h1>Mixed HTML Example</h1>
+    <script>
+      function jsFunc(arg1, arg2) {
+        if (arg1 && arg2) document.body.innerHTML = "achoo";
+      }
+    </script>
+  </body>
+</html>
+</textarea></form>
+    <script>
+      // Define an extended mixed-mode that understands vbscript and
+      // leaves mustache/handlebars embedded templates in html mode
+      var mixedMode = {
+        name: "htmlmixed",
+        scriptTypes: [{matches: /\/x-handlebars-template|\/x-mustache/i,
+                       mode: null},
+                      {matches: /(text|application)\/(x-)?vb(a|script)/i,
+                       mode: "vbscript"}]
+      };
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {mode: mixedMode, tabMode: "indent"});
+    </script>
+
+    <p>The HTML mixed mode depends on the XML, JavaScript, and CSS modes.</p>
+
+    <p>It takes an optional mode configuration
+    option, <code>scriptTypes</code>, which can be used to add custom
+    behavior for specific <code>&lt;script type="..."></code> tags. If
+    given, it should hold an array of <code>{matches, mode}</code>
+    objects, where <code>matches</code> is a string or regexp that
+    matches the script type, and <code>mode</code> is
+    either <code>null</code>, for script types that should stay in
+    HTML mode, or a <a href="../../doc/manual.html#option_mode">mode
+    spec</a> corresponding to the mode that should be used for the
+    script.</p>
+
+    <p><strong>MIME types defined:</strong> <code>text/html</code>
+    (redefined, only takes effect if you load this parser after the
+    XML parser).</p>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/http/http.js b/third-party/codemirror-3.15/mode/http/http.js
new file mode 100644 (file)
index 0000000..5a51636
--- /dev/null
@@ -0,0 +1,98 @@
+CodeMirror.defineMode("http", function() {
+  function failFirstLine(stream, state) {
+    stream.skipToEnd();
+    state.cur = header;
+    return "error";
+  }
+
+  function start(stream, state) {
+    if (stream.match(/^HTTP\/\d\.\d/)) {
+      state.cur = responseStatusCode;
+      return "keyword";
+    } else if (stream.match(/^[A-Z]+/) && /[ \t]/.test(stream.peek())) {
+      state.cur = requestPath;
+      return "keyword";
+    } else {
+      return failFirstLine(stream, state);
+    }
+  }
+
+  function responseStatusCode(stream, state) {
+    var code = stream.match(/^\d+/);
+    if (!code) return failFirstLine(stream, state);
+
+    state.cur = responseStatusText;
+    var status = Number(code[0]);
+    if (status >= 100 && status < 200) {
+      return "positive informational";
+    } else if (status >= 200 && status < 300) {
+      return "positive success";
+    } else if (status >= 300 && status < 400) {
+      return "positive redirect";
+    } else if (status >= 400 && status < 500) {
+      return "negative client-error";
+    } else if (status >= 500 && status < 600) {
+      return "negative server-error";
+    } else {
+      return "error";
+    }
+  }
+
+  function responseStatusText(stream, state) {
+    stream.skipToEnd();
+    state.cur = header;
+    return null;
+  }
+
+  function requestPath(stream, state) {
+    stream.eatWhile(/\S/);
+    state.cur = requestProtocol;
+    return "string-2";
+  }
+
+  function requestProtocol(stream, state) {
+    if (stream.match(/^HTTP\/\d\.\d$/)) {
+      state.cur = header;
+      return "keyword";
+    } else {
+      return failFirstLine(stream, state);
+    }
+  }
+
+  function header(stream) {
+    if (stream.sol() && !stream.eat(/[ \t]/)) {
+      if (stream.match(/^.*?:/)) {
+        return "atom";
+      } else {
+        stream.skipToEnd();
+        return "error";
+      }
+    } else {
+      stream.skipToEnd();
+      return "string";
+    }
+  }
+
+  function body(stream) {
+    stream.skipToEnd();
+    return null;
+  }
+
+  return {
+    token: function(stream, state) {
+      var cur = state.cur;
+      if (cur != header && cur != body && stream.eatSpace()) return null;
+      return cur(stream, state);
+    },
+
+    blankLine: function(state) {
+      state.cur = body;
+    },
+
+    startState: function() {
+      return {cur: start};
+    }
+  };
+});
+
+CodeMirror.defineMIME("message/http", "http");
diff --git a/third-party/codemirror-3.15/mode/http/index.html b/third-party/codemirror-3.15/mode/http/index.html
new file mode 100644 (file)
index 0000000..124eb84
--- /dev/null
@@ -0,0 +1,32 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: HTTP mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="http.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: HTTP mode</h1>
+
+<div><textarea id="code" name="code">
+POST /somewhere HTTP/1.1
+Host: example.com
+If-Modified-Since: Sat, 29 Oct 1994 19:43:31 GMT
+Content-Type: application/x-www-form-urlencoded;
+       charset=utf-8
+User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.11 (KHTML, like Gecko) Ubuntu/12.04 Chromium/20.0.1132.47 Chrome/20.0.1132.47 Safari/536.11
+
+This is the request body!
+</textarea></div>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>message/http</code>.</p>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/jade/index.html b/third-party/codemirror-3.15/mode/jade/index.html
new file mode 100644 (file)
index 0000000..0e68ba8
--- /dev/null
@@ -0,0 +1,54 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Jade Templating Mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="jade.js"></script>
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Jade Templating Mode</h1>
+    <form><textarea id="code" name="code">
+doctype 5
+  html
+    head
+      title= "Jade Templating CodeMirror Mode Example"
+      link(rel='stylesheet', href='/css/bootstrap.min.css')
+      link(rel='stylesheet', href='/css/index.css')
+      script(type='text/javascript', src='/js/jquery-1.9.1.min.js')
+      script(type='text/javascript', src='/js/bootstrap.min.js')
+    body
+      div.header
+        h1 Welcome to this Example
+      div.spots
+        if locals.spots
+          each spot in spots
+            div.spot.well
+         div
+           if spot.logo
+             img.img-rounded.logo(src=spot.logo)
+           else
+             img.img-rounded.logo(src="img/placeholder.png")
+         h3
+           a(href=spot.hash) ##{spot.hash}
+           if spot.title
+             span.title #{spot.title}
+           if spot.desc
+             div #{spot.desc}
+        else
+          h3 There are no spots currently available.
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        mode: {name: "jade", alignCDATA: true},
+        lineNumbers: true
+      });
+    </script>
+    <h3>The Jade Templating Mode</h3>
+      <p> Created by Drew Bratcher. Managed as part of an Adobe Brackets extension at <a href="https://github.com/dbratcher/brackets-jade">https://github.com/dbratcher/brackets-jade</a>.</p>
+    <p><strong>MIME type defined:</strong> <code>text/x-jade</code>.</p>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/jade/jade.js b/third-party/codemirror-3.15/mode/jade/jade.js
new file mode 100644 (file)
index 0000000..61abb27
--- /dev/null
@@ -0,0 +1,90 @@
+CodeMirror.defineMode("jade", function () {
+  var symbol_regex1 = /^(?:~|!|%|\^|\*|\+|=|\\|:|;|,|\/|\?|&|<|>|\|)/;
+  var open_paren_regex = /^(\(|\[)/;
+  var close_paren_regex = /^(\)|\])/;
+  var keyword_regex1 = /^(if|else|return|var|function|include|doctype|each)/;
+  var keyword_regex2 = /^(#|{|}|\.)/;
+  var keyword_regex3 = /^(in)/;
+  var html_regex1 = /^(html|head|title|meta|link|script|body|br|div|input|span|a|img)/;
+  var html_regex2 = /^(h1|h2|h3|h4|h5|p|strong|em)/;
+  return {
+    startState: function () {
+      return {
+        inString: false,
+        stringType: "",
+        beforeTag: true,
+        justMatchedKeyword: false,
+        afterParen: false
+      };
+    },
+    token: function (stream, state) {
+      //check for state changes
+      if (!state.inString && ((stream.peek() == '"') || (stream.peek() == "'"))) {
+        state.stringType = stream.peek();
+        stream.next(); // Skip quote
+        state.inString = true; // Update state
+      }
+
+      //return state
+      if (state.inString) {
+        if (stream.skipTo(state.stringType)) { // Quote found on this line
+          stream.next(); // Skip quote
+          state.inString = false; // Clear flag
+        } else {
+          stream.skipToEnd(); // Rest of line is string
+        }
+        state.justMatchedKeyword = false;
+        return "string"; // Token style
+      } else if (stream.sol() && stream.eatSpace()) {
+        if (stream.match(keyword_regex1)) {
+          state.justMatchedKeyword = true;
+          stream.eatSpace();
+          return "keyword";
+        }
+        if (stream.match(html_regex1) || stream.match(html_regex2)) {
+          state.justMatchedKeyword = true;
+          return "variable";
+        }
+      } else if (stream.sol() && stream.match(keyword_regex1)) {
+        state.justMatchedKeyword = true;
+        stream.eatSpace();
+        return "keyword";
+      } else if (stream.sol() && (stream.match(html_regex1) || stream.match(html_regex2))) {
+        state.justMatchedKeyword = true;
+        return "variable";
+      } else if (stream.eatSpace()) {
+        state.justMatchedKeyword = false;
+        if (stream.match(keyword_regex3) && stream.eatSpace()) {
+          state.justMatchedKeyword = true;
+          return "keyword";
+        }
+      } else if (stream.match(symbol_regex1)) {
+        state.justMatchedKeyword = false;
+        return "atom";
+      } else if (stream.match(open_paren_regex)) {
+        state.afterParen = true;
+        state.justMatchedKeyword = true;
+        return "def";
+      } else if (stream.match(close_paren_regex)) {
+        state.afterParen = false;
+        state.justMatchedKeyword = true;
+        return "def";
+      } else if (stream.match(keyword_regex2)) {
+        state.justMatchedKeyword = true;
+        return "keyword";
+      } else if (stream.eatSpace()) {
+        state.justMatchedKeyword = false;
+      } else {
+        stream.next();
+        if (state.justMatchedKeyword) {
+          return "property";
+        } else if (state.afterParen) {
+          return "property";
+        }
+      }
+      return null;
+    }
+  };
+});
+
+CodeMirror.defineMIME('text/x-jade', 'jade');
diff --git a/third-party/codemirror-3.15/mode/javascript/index.html b/third-party/codemirror-3.15/mode/javascript/index.html
new file mode 100644 (file)
index 0000000..db063b7
--- /dev/null
@@ -0,0 +1,94 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: JavaScript mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../../addon/edit/matchbrackets.js"></script>
+    <script src="../../addon/edit/continuecomment.js"></script>
+    <script src="../../addon/comment/comment.js"></script>
+    <script src="javascript.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: JavaScript mode</h1>
+
+<div><textarea id="code" name="code">
+// Demo code (the actual new parser character stream implementation)
+
+function StringStream(string) {
+  this.pos = 0;
+  this.string = string;
+}
+
+StringStream.prototype = {
+  done: function() {return this.pos >= this.string.length;},
+  peek: function() {return this.string.charAt(this.pos);},
+  next: function() {
+    if (this.pos &lt; this.string.length)
+      return this.string.charAt(this.pos++);
+  },
+  eat: function(match) {
+    var ch = this.string.charAt(this.pos);
+    if (typeof match == "string") var ok = ch == match;
+    else var ok = ch &amp;&amp; match.test ? match.test(ch) : match(ch);
+    if (ok) {this.pos++; return ch;}
+  },
+  eatWhile: function(match) {
+    var start = this.pos;
+    while (this.eat(match));
+    if (this.pos > start) return this.string.slice(start, this.pos);
+  },
+  backUp: function(n) {this.pos -= n;},
+  column: function() {return this.pos;},
+  eatSpace: function() {
+    var start = this.pos;
+    while (/\s/.test(this.string.charAt(this.pos))) this.pos++;
+    return this.pos - start;
+  },
+  match: function(pattern, consume, caseInsensitive) {
+    if (typeof pattern == "string") {
+      function cased(str) {return caseInsensitive ? str.toLowerCase() : str;}
+      if (cased(this.string).indexOf(cased(pattern), this.pos) == this.pos) {
+        if (consume !== false) this.pos += str.length;
+        return true;
+      }
+    }
+    else {
+      var match = this.string.slice(this.pos).match(pattern);
+      if (match &amp;&amp; consume !== false) this.pos += match[0].length;
+      return match;
+    }
+  }
+};
+</textarea></div>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        matchBrackets: true,
+        continueComments: "Enter",
+        extraKeys: {"Ctrl-Q": "toggleComment"}
+      });
+    </script>
+
+    <p>
+      JavaScript mode supports a two configuration
+      options:
+      <ul>
+        <li><code>json</code> which will set the mode to expect JSON
+        data rather than a JavaScript program.</li>
+        <li><code>typescript</code> which will activate additional
+        syntax highlighting and some other things for TypeScript code
+        (<a href="typescript.html">demo</a>).</li>
+        <li><code>statementIndent</code> which (given a number) will
+        determine the amount of indentation to use for statements
+        continued on a new line.</li>
+      </ul>
+    </p>
+
+    <p><strong>MIME types defined:</strong> <code>text/javascript</code>, <code>application/json</code>, <code>text/typescript</code>, <code>application/typescript</code>.</p>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/javascript/javascript.js b/third-party/codemirror-3.15/mode/javascript/javascript.js
new file mode 100644 (file)
index 0000000..0be9b79
--- /dev/null
@@ -0,0 +1,479 @@
+// TODO actually recognize syntax of TypeScript constructs
+
+CodeMirror.defineMode("javascript", function(config, parserConfig) {
+  var indentUnit = config.indentUnit;
+  var statementIndent = parserConfig.statementIndent;
+  var jsonMode = parserConfig.json;
+  var isTS = parserConfig.typescript;
+
+  // Tokenizer
+
+  var keywords = function(){
+    function kw(type) {return {type: type, style: "keyword"};}
+    var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c");
+    var operator = kw("operator"), atom = {type: "atom", style: "atom"};
+
+    var jsKeywords = {
+      "if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B,
+      "return": C, "break": C, "continue": C, "new": C, "delete": C, "throw": C,
+      "var": kw("var"), "const": kw("var"), "let": kw("var"),
+      "function": kw("function"), "catch": kw("catch"),
+      "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"),
+      "in": operator, "typeof": operator, "instanceof": operator,
+      "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom,
+      "this": kw("this")
+    };
+
+    // Extend the 'normal' keywords with the TypeScript language extensions
+    if (isTS) {
+      var type = {type: "variable", style: "variable-3"};
+      var tsKeywords = {
+        // object-like things
+        "interface": kw("interface"),
+        "class": kw("class"),
+        "extends": kw("extends"),
+        "constructor": kw("constructor"),
+
+        // scope modifiers
+        "public": kw("public"),
+        "private": kw("private"),
+        "protected": kw("protected"),
+        "static": kw("static"),
+
+        "super": kw("super"),
+
+        // types
+        "string": type, "number": type, "bool": type, "any": type
+      };
+
+      for (var attr in tsKeywords) {
+        jsKeywords[attr] = tsKeywords[attr];
+      }
+    }
+
+    return jsKeywords;
+  }();
+
+  var isOperatorChar = /[+\-*&%=<>!?|~^]/;
+
+  function chain(stream, state, f) {
+    state.tokenize = f;
+    return f(stream, state);
+  }
+
+  function nextUntilUnescaped(stream, end) {
+    var escaped = false, next;
+    while ((next = stream.next()) != null) {
+      if (next == end && !escaped)
+        return false;
+      escaped = !escaped && next == "\\";
+    }
+    return escaped;
+  }
+
+  // Used as scratch variables to communicate multiple values without
+  // consing up tons of objects.
+  var type, content;
+  function ret(tp, style, cont) {
+    type = tp; content = cont;
+    return style;
+  }
+
+  function jsTokenBase(stream, state) {
+    var ch = stream.next();
+    if (ch == '"' || ch == "'")
+      return chain(stream, state, jsTokenString(ch));
+    else if (/[\[\]{}\(\),;\:\.]/.test(ch))
+      return ret(ch);
+    else if (ch == "0" && stream.eat(/x/i)) {
+      stream.eatWhile(/[\da-f]/i);
+      return ret("number", "number");
+    }
+    else if (/\d/.test(ch) || ch == "-" && stream.eat(/\d/)) {
+      stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/);
+      return ret("number", "number");
+    }
+    else if (ch == "/") {
+      if (stream.eat("*")) {
+        return chain(stream, state, jsTokenComment);
+      }
+      else if (stream.eat("/")) {
+        stream.skipToEnd();
+        return ret("comment", "comment");
+      }
+      else if (state.lastType == "operator" || state.lastType == "keyword c" ||
+               /^[\[{}\(,;:]$/.test(state.lastType)) {
+        nextUntilUnescaped(stream, "/");
+        stream.eatWhile(/[gimy]/); // 'y' is "sticky" option in Mozilla
+        return ret("regexp", "string-2");
+      }
+      else {
+        stream.eatWhile(isOperatorChar);
+        return ret("operator", null, stream.current());
+      }
+    }
+    else if (ch == "#") {
+      stream.skipToEnd();
+      return ret("error", "error");
+    }
+    else if (isOperatorChar.test(ch)) {
+      stream.eatWhile(isOperatorChar);
+      return ret("operator", null, stream.current());
+    }
+    else {
+      stream.eatWhile(/[\w\$_]/);
+      var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word];
+      return (known && state.lastType != ".") ? ret(known.type, known.style, word) :
+                     ret("variable", "variable", word);
+    }
+  }
+
+  function jsTokenString(quote) {
+    return function(stream, state) {
+      if (!nextUntilUnescaped(stream, quote))
+        state.tokenize = jsTokenBase;
+      return ret("string", "string");
+    };
+  }
+
+  function jsTokenComment(stream, state) {
+    var maybeEnd = false, ch;
+    while (ch = stream.next()) {
+      if (ch == "/" && maybeEnd) {
+        state.tokenize = jsTokenBase;
+        break;
+      }
+      maybeEnd = (ch == "*");
+    }
+    return ret("comment", "comment");
+  }
+
+  // Parser
+
+  var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true};
+
+  function JSLexical(indented, column, type, align, prev, info) {
+    this.indented = indented;
+    this.column = column;
+    this.type = type;
+    this.prev = prev;
+    this.info = info;
+    if (align != null) this.align = align;
+  }
+
+  function inScope(state, varname) {
+    for (var v = state.localVars; v; v = v.next)
+      if (v.name == varname) return true;
+  }
+
+  function parseJS(state, style, type, content, stream) {
+    var cc = state.cc;
+    // Communicate our context to the combinators.
+    // (Less wasteful than consing up a hundred closures on every call.)
+    cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc;
+
+    if (!state.lexical.hasOwnProperty("align"))
+      state.lexical.align = true;
+
+    while(true) {
+      var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement;
+      if (combinator(type, content)) {
+        while(cc.length && cc[cc.length - 1].lex)
+          cc.pop()();
+        if (cx.marked) return cx.marked;
+        if (type == "variable" && inScope(state, content)) return "variable-2";
+        return style;
+      }
+    }
+  }
+
+  // Combinator utils
+
+  var cx = {state: null, column: null, marked: null, cc: null};
+  function pass() {
+    for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);
+  }
+  function cont() {
+    pass.apply(null, arguments);
+    return true;
+  }
+  function register(varname) {
+    function inList(list) {
+      for (var v = list; v; v = v.next)
+        if (v.name == varname) return true;
+      return false;
+    }
+    var state = cx.state;
+    if (state.context) {
+      cx.marked = "def";
+      if (inList(state.localVars)) return;
+      state.localVars = {name: varname, next: state.localVars};
+    } else {
+      if (inList(state.globalVars)) return;
+      state.globalVars = {name: varname, next: state.globalVars};
+    }
+  }
+
+  // Combinators
+
+  var defaultVars = {name: "this", next: {name: "arguments"}};
+  function pushcontext() {
+    cx.state.context = {prev: cx.state.context, vars: cx.state.localVars};
+    cx.state.localVars = defaultVars;
+  }
+  function popcontext() {
+    cx.state.localVars = cx.state.context.vars;
+    cx.state.context = cx.state.context.prev;
+  }
+  function pushlex(type, info) {
+    var result = function() {
+      var state = cx.state, indent = state.indented;
+      if (state.lexical.type == "stat") indent = state.lexical.indented;
+      state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info);
+    };
+    result.lex = true;
+    return result;
+  }
+  function poplex() {
+    var state = cx.state;
+    if (state.lexical.prev) {
+      if (state.lexical.type == ")")
+        state.indented = state.lexical.indented;
+      state.lexical = state.lexical.prev;
+    }
+  }
+  poplex.lex = true;
+
+  function expect(wanted) {
+    return function(type) {
+      if (type == wanted) return cont();
+      else if (wanted == ";") return pass();
+      else return cont(arguments.callee);
+    };
+  }
+
+  function statement(type) {
+    if (type == "var") return cont(pushlex("vardef"), vardef1, expect(";"), poplex);
+    if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex);
+    if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
+    if (type == "{") return cont(pushlex("}"), block, poplex);
+    if (type == ";") return cont();
+    if (type == "if") return cont(pushlex("form"), expression, statement, poplex, maybeelse);
+    if (type == "function") return cont(functiondef);
+    if (type == "for") return cont(pushlex("form"), expect("("), pushlex(")"), forspec1, expect(")"),
+                                   poplex, statement, poplex);
+    if (type == "variable") return cont(pushlex("stat"), maybelabel);
+    if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"),
+                                      block, poplex, poplex);
+    if (type == "case") return cont(expression, expect(":"));
+    if (type == "default") return cont(expect(":"));
+    if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"),
+                                     statement, poplex, popcontext);
+    return pass(pushlex("stat"), expression, expect(";"), poplex);
+  }
+  function expression(type) {
+    return expressionInner(type, false);
+  }
+  function expressionNoComma(type) {
+    return expressionInner(type, true);
+  }
+  function expressionInner(type, noComma) {
+    var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma;
+    if (atomicTypes.hasOwnProperty(type)) return cont(maybeop);
+    if (type == "function") return cont(functiondef);
+    if (type == "keyword c") return cont(noComma ? maybeexpressionNoComma : maybeexpression);
+    if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop);
+    if (type == "operator") return cont(noComma ? expressionNoComma : expression);
+    if (type == "[") return cont(pushlex("]"), commasep(expressionNoComma, "]"), poplex, maybeop);
+    if (type == "{") return cont(pushlex("}"), commasep(objprop, "}"), poplex, maybeop);
+    return cont();
+  }
+  function maybeexpression(type) {
+    if (type.match(/[;\}\)\],]/)) return pass();
+    return pass(expression);
+  }
+  function maybeexpressionNoComma(type) {
+    if (type.match(/[;\}\)\],]/)) return pass();
+    return pass(expressionNoComma);
+  }
+
+  function maybeoperatorComma(type, value) {
+    if (type == ",") return cont(expression);
+    return maybeoperatorNoComma(type, value, false);
+  }
+  function maybeoperatorNoComma(type, value, noComma) {
+    var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma;
+    var expr = noComma == false ? expression : expressionNoComma;
+    if (type == "operator") {
+      if (/\+\+|--/.test(value)) return cont(me);
+      if (value == "?") return cont(expression, expect(":"), expr);
+      return cont(expr);
+    }
+    if (type == ";") return;
+    if (type == "(") return cont(pushlex(")", "call"), commasep(expressionNoComma, ")"), poplex, me);
+    if (type == ".") return cont(property, me);
+    if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me);
+  }
+  function maybelabel(type) {
+    if (type == ":") return cont(poplex, statement);
+    return pass(maybeoperatorComma, expect(";"), poplex);
+  }
+  function property(type) {
+    if (type == "variable") {cx.marked = "property"; return cont();}
+  }
+  function objprop(type, value) {
+    if (type == "variable") {
+      cx.marked = "property";
+      if (value == "get" || value == "set") return cont(getterSetter);
+    } else if (type == "number" || type == "string") {
+      cx.marked = type + " property";
+    }
+    if (atomicTypes.hasOwnProperty(type)) return cont(expect(":"), expressionNoComma);
+  }
+  function getterSetter(type) {
+    if (type == ":") return cont(expression);
+    if (type != "variable") return cont(expect(":"), expression);
+    cx.marked = "property";
+    return cont(functiondef);
+  }
+  function commasep(what, end) {
+    function proceed(type) {
+      if (type == ",") {
+        var lex = cx.state.lexical;
+        if (lex.info == "call") lex.pos = (lex.pos || 0) + 1;
+        return cont(what, proceed);
+      }
+      if (type == end) return cont();
+      return cont(expect(end));
+    }
+    return function(type) {
+      if (type == end) return cont();
+      else return pass(what, proceed);
+    };
+  }
+  function block(type) {
+    if (type == "}") return cont();
+    return pass(statement, block);
+  }
+  function maybetype(type) {
+    if (type == ":") return cont(typedef);
+    return pass();
+  }
+  function typedef(type) {
+    if (type == "variable"){cx.marked = "variable-3"; return cont();}
+    return pass();
+  }
+  function vardef1(type, value) {
+    if (type == "variable") {
+      register(value);
+      return isTS ? cont(maybetype, vardef2) : cont(vardef2);
+    }
+    return pass();
+  }
+  function vardef2(type, value) {
+    if (value == "=") return cont(expressionNoComma, vardef2);
+    if (type == ",") return cont(vardef1);
+  }
+  function maybeelse(type, value) {
+    if (type == "keyword b" && value == "else") return cont(pushlex("form"), statement, poplex);
+  }
+  function forspec1(type) {
+    if (type == "var") return cont(vardef1, expect(";"), forspec2);
+    if (type == ";") return cont(forspec2);
+    if (type == "variable") return cont(formaybein);
+    return pass(expression, expect(";"), forspec2);
+  }
+  function formaybein(_type, value) {
+    if (value == "in") return cont(expression);
+    return cont(maybeoperatorComma, forspec2);
+  }
+  function forspec2(type, value) {
+    if (type == ";") return cont(forspec3);
+    if (value == "in") return cont(expression);
+    return pass(expression, expect(";"), forspec3);
+  }
+  function forspec3(type) {
+    if (type != ")") cont(expression);
+  }
+  function functiondef(type, value) {
+    if (type == "variable") {register(value); return cont(functiondef);}
+    if (type == "(") return cont(pushlex(")"), pushcontext, commasep(funarg, ")"), poplex, statement, popcontext);
+  }
+  function funarg(type, value) {
+    if (type == "variable") {register(value); return isTS ? cont(maybetype) : cont();}
+  }
+
+  // Interface
+
+  return {
+    startState: function(basecolumn) {
+      return {
+        tokenize: jsTokenBase,
+        lastType: null,
+        cc: [],
+        lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false),
+        localVars: parserConfig.localVars,
+        globalVars: parserConfig.globalVars,
+        context: parserConfig.localVars && {vars: parserConfig.localVars},
+        indented: 0
+      };
+    },
+
+    token: function(stream, state) {
+      if (stream.sol()) {
+        if (!state.lexical.hasOwnProperty("align"))
+          state.lexical.align = false;
+        state.indented = stream.indentation();
+      }
+      if (state.tokenize != jsTokenComment && stream.eatSpace()) return null;
+      var style = state.tokenize(stream, state);
+      if (type == "comment") return style;
+      state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type;
+      return parseJS(state, style, type, content, stream);
+    },
+
+    indent: function(state, textAfter) {
+      if (state.tokenize == jsTokenComment) return CodeMirror.Pass;
+      if (state.tokenize != jsTokenBase) return 0;
+      var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical;
+      // Kludge to prevent 'maybelse' from blocking lexical scope pops
+      for (var i = state.cc.length - 1; i >= 0; --i) {
+        var c = state.cc[i];
+        if (c == poplex) lexical = lexical.prev;
+        else if (c != maybeelse || /^else\b/.test(textAfter)) break;
+      }
+      if (lexical.type == "stat" && firstChar == "}") lexical = lexical.prev;
+      if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat")
+        lexical = lexical.prev;
+      var type = lexical.type, closing = firstChar == type;
+
+      if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? 4 : 0);
+      else if (type == "form" && firstChar == "{") return lexical.indented;
+      else if (type == "form") return lexical.indented + indentUnit;
+      else if (type == "stat")
+        return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? statementIndent || indentUnit : 0);
+      else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false)
+        return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);
+      else if (lexical.align) return lexical.column + (closing ? 0 : 1);
+      else return lexical.indented + (closing ? 0 : indentUnit);
+    },
+
+    electricChars: ":{}",
+    blockCommentStart: jsonMode ? null : "/*",
+    blockCommentEnd: jsonMode ? null : "*/",
+    lineComment: jsonMode ? null : "//",
+    fold: "brace",
+
+    helperType: jsonMode ? "json" : "javascript",
+    jsonMode: jsonMode
+  };
+});
+
+CodeMirror.defineMIME("text/javascript", "javascript");
+CodeMirror.defineMIME("text/ecmascript", "javascript");
+CodeMirror.defineMIME("application/javascript", "javascript");
+CodeMirror.defineMIME("application/ecmascript", "javascript");
+CodeMirror.defineMIME("application/json", {name: "javascript", json: true});
+CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true});
+CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true });
+CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true });
diff --git a/third-party/codemirror-3.15/mode/javascript/test.js b/third-party/codemirror-3.15/mode/javascript/test.js
new file mode 100644 (file)
index 0000000..a2af527
--- /dev/null
@@ -0,0 +1,10 @@
+(function() {
+  var mode = CodeMirror.getMode({indentUnit: 2}, "javascript");
+  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }
+
+  MT("locals",
+     "[keyword function] [variable foo]([def a], [def b]) { [keyword var] [def c] = [number 10]; [keyword return] [variable-2 a] + [variable-2 c] + [variable d]; }");
+
+  MT("comma-and-binop",
+     "[keyword function](){ [keyword var] [def x] = [number 1] + [number 2], [def y]; }");
+})();
diff --git a/third-party/codemirror-3.15/mode/javascript/typescript.html b/third-party/codemirror-3.15/mode/javascript/typescript.html
new file mode 100644 (file)
index 0000000..58315e7
--- /dev/null
@@ -0,0 +1,48 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: TypeScript mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="javascript.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: TypeScript mode</h1>
+
+<div><textarea id="code" name="code">
+class Greeter {
+       greeting: string;
+       constructor (message: string) {
+               this.greeting = message;
+       }
+       greet() {
+               return "Hello, " + this.greeting;
+       }
+}   
+
+var greeter = new Greeter("world");
+
+var button = document.createElement('button')
+button.innerText = "Say Hello"
+button.onclick = function() {
+       alert(greeter.greet())
+}
+
+document.body.appendChild(button)
+
+</textarea></div>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        matchBrackets: true,
+        mode: "text/typescript"
+      });
+    </script>
+
+    <p>This is a specialization of the <a href="index.html">JavaScript mode</a>.</p>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/jinja2/index.html b/third-party/codemirror-3.15/mode/jinja2/index.html
new file mode 100644 (file)
index 0000000..7cd1da2
--- /dev/null
@@ -0,0 +1,38 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Jinja2 mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="jinja2.js"></script>
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Jinja2 mode</h1>
+    <form><textarea id="code" name="code">
+&lt;html style="color: green"&gt;
+  &lt;!-- this is a comment --&gt;
+  &lt;head&gt;
+    &lt;title&gt;Jinja2 Example&lt;/title&gt;
+  &lt;/head&gt;
+  &lt;body&gt;
+    &lt;ul&gt;
+    {# this is a comment #}
+    {%- for item in li -%}
+      &lt;li&gt;
+        {{ item.label }}
+      &lt;/li&gt;
+    {% endfor -%}
+    &lt;/ul&gt;
+  &lt;/body&gt;
+&lt;/html&gt;
+</textarea></form>
+    <script>
+      var editor =
+      CodeMirror.fromTextArea(document.getElementById("code"), {mode:
+        {name: "jinja2", htmlMode: true}});
+    </script>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/jinja2/jinja2.js b/third-party/codemirror-3.15/mode/jinja2/jinja2.js
new file mode 100644 (file)
index 0000000..16b06c4
--- /dev/null
@@ -0,0 +1,42 @@
+CodeMirror.defineMode("jinja2", function() {
+    var keywords = ["block", "endblock", "for", "endfor", "in", "true", "false",
+                    "loop", "none", "self", "super", "if", "as", "not", "and",
+                    "else", "import", "with", "without", "context"];
+    keywords = new RegExp("^((" + keywords.join(")|(") + "))\\b");
+
+    function tokenBase (stream, state) {
+        var ch = stream.next();
+        if (ch == "{") {
+            if (ch = stream.eat(/\{|%|#/)) {
+                stream.eat("-");
+                state.tokenize = inTag(ch);
+                return "tag";
+            }
+        }
+    }
+    function inTag (close) {
+        if (close == "{") {
+            close = "}";
+        }
+        return function (stream, state) {
+            var ch = stream.next();
+            if ((ch == close || (ch == "-" && stream.eat(close)))
+                && stream.eat("}")) {
+                state.tokenize = tokenBase;
+                return "tag";
+            }
+            if (stream.match(keywords)) {
+                return "keyword";
+            }
+            return close == "#" ? "comment" : "string";
+        };
+    }
+    return {
+        startState: function () {
+            return {tokenize: tokenBase};
+        },
+        token: function (stream, state) {
+            return state.tokenize(stream, state);
+        }
+    };
+});
diff --git a/third-party/codemirror-3.15/mode/less/index.html b/third-party/codemirror-3.15/mode/less/index.html
new file mode 100644 (file)
index 0000000..78c1e53
--- /dev/null
@@ -0,0 +1,741 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: LESS mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../../addon/edit/matchbrackets.js"></script>
+    <script src="less.js"></script>
+    <style>.CodeMirror {background: #f8f8f8; border: 1px solid #ddd; font-size:12px; height: 400px}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <link rel="stylesheet" href="../../theme/lesser-dark.css">
+  </head>
+  <body>
+    <h1>CodeMirror: LESS mode</h1>
+    <form><textarea id="code" name="code">@media screen and (device-aspect-ratio: 16/9) { … }
+@media screen and (device-aspect-ratio: 32/18) { … }
+@media screen and (device-aspect-ratio: 1280/720) { … }
+@media screen and (device-aspect-ratio: 2560/1440) { … }
+
+html:lang(fr-be)
+html:lang(de)
+:lang(fr-be) > q
+:lang(de) > q
+
+tr:nth-child(2n+1) /* represents every odd row of an HTML table */
+tr:nth-child(odd)  /* same */
+tr:nth-child(2n+0) /* represents every even row of an HTML table */
+tr:nth-child(even) /* same */
+
+/* Alternate paragraph colours in CSS */
+p:nth-child(4n+1) { color: navy; }
+p:nth-child(4n+2) { color: green; }
+p:nth-child(4n+3) { color: maroon; }
+p:nth-child(4n+4) { color: purple; }
+
+:nth-child(10n-1)  /* represents the 9th, 19th, 29th, etc, element */
+:nth-child(10n+9)  /* Same */
+:nth-child(10n+-1) /* Syntactically invalid, and would be ignored */
+
+:nth-child( 3n + 1 )
+:nth-child( +3n - 2 )
+:nth-child( -n+ 6)
+:nth-child( +6 )
+
+html|tr:nth-child(-n+6)  /* represents the 6 first rows of XHTML tables */
+
+img:nth-of-type(2n+1) { float: right; }
+img:nth-of-type(2n) { float: left; }
+
+body > h2:nth-of-type(n+2):nth-last-of-type(n+2)
+body > h2:not(:first-of-type):not(:last-of-type)
+
+html|*:not(:link):not(:visited)
+*|*:not(:hover)
+p::first-line { text-transform: uppercase }
+
+p { color: red; font-size: 12pt }
+p::first-letter { color: green; font-size: 200% }
+p::first-line { color: blue }
+
+p { line-height: 1.1 }
+p::first-letter { font-size: 3em; font-weight: normal }
+span { font-weight: bold }
+
+*               /* a=0 b=0 c=0 -> specificity =   0 */
+LI              /* a=0 b=0 c=1 -> specificity =   1 */
+UL LI           /* a=0 b=0 c=2 -> specificity =   2 */
+UL OL+LI        /* a=0 b=0 c=3 -> specificity =   3 */
+H1 + *[REL=up]  /* a=0 b=1 c=1 -> specificity =  11 */
+UL OL LI.red    /* a=0 b=1 c=3 -> specificity =  13 */
+LI.red.level    /* a=0 b=2 c=1 -> specificity =  21 */
+#x34y           /* a=1 b=0 c=0 -> specificity = 100 */
+#s12:not(FOO)   /* a=1 b=0 c=1 -> specificity = 101 */
+
+@namespace foo url(http://www.example.com);
+foo|h1 { color: blue }  /* first rule */
+foo|* { color: yellow } /* second rule */
+|h1 { color: red }      /* ...*/
+*|h1 { color: green }
+h1 { color: green }
+
+span[hello="Ocean"][goodbye="Land"]
+
+a[rel~="copyright"] { ... }
+a[href="http://www.w3.org/"] { ... }
+
+DIALOGUE[character=romeo]
+DIALOGUE[character=juliet]
+
+[att^=val]
+[att$=val]
+[att*=val]
+
+@namespace foo "http://www.example.com";
+[foo|att=val] { color: blue }
+[*|att] { color: yellow }
+[|att] { color: green }
+[att] { color: green }
+
+
+*:target { color : red }
+*:target::before { content : url(target.png) }
+
+E[foo]{
+  padding:65px;
+}
+E[foo] ~ F{
+  padding:65px;
+}
+E#myid{
+  padding:65px;
+}
+input[type="search"]::-webkit-search-decoration,
+input[type="search"]::-webkit-search-cancel-button {
+  -webkit-appearance: none; // Inner-padding issues in Chrome OSX, Safari 5
+}
+button::-moz-focus-inner,
+input::-moz-focus-inner { // Inner padding and border oddities in FF3/4
+  padding: 0;
+  border: 0;
+}
+.btn {
+  // reset here as of 2.0.3 due to Recess property order
+  border-color: #ccc;
+  border-color: rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);
+}
+fieldset span button, fieldset span input[type="file"] {
+  font-size:12px;
+       font-family:Arial, Helvetica, sans-serif;
+}
+.el tr:nth-child(even):last-child td:first-child{
+       -moz-border-radius-bottomleft:3px;
+       -webkit-border-bottom-left-radius:3px;
+       border-bottom-left-radius:3px;
+}
+
+/* Some LESS code */
+
+button {
+    width:  32px;
+    height: 32px;
+    border: 0;
+    margin: 4px;
+    cursor: pointer;
+}
+button.icon-plus { background: url(http://dahlström.net/tmp/sharp-icons/svg-icon-target.svg#plus) no-repeat; }
+button.icon-chart { background: url(http://dahlström.net/tmp/sharp-icons/svg-icon-target.svg#chart) no-repeat; }
+
+button:hover { background-color: #999; }
+button:active { background-color: #666; }
+
+@test_a: #eeeQQQ;//this is not a valid hex value and thus parsed as an element id
+@test_b: #eeeFFF //this is a valid hex value but the declaration doesn't end with a semicolon and thus parsed as an element id
+
+#eee aaa .box
+{
+  #test bbb {
+    width: 500px;
+    height: 250px;
+    background-image: url(dir/output/sheep.png), url( betweengrassandsky.png );
+    background-position: center bottom, left top;
+    background-repeat: no-repeat;
+  }
+}
+
+@base: #f938ab;
+
+.box-shadow(@style, @c) when (iscolor(@c)) {
+  box-shadow:         @style @c;
+  -webkit-box-shadow: @style @c;
+  -moz-box-shadow:    @style @c;
+}
+.box-shadow(@style, @alpha: 50%) when (isnumber(@alpha)) {
+  .box-shadow(@style, rgba(0, 0, 0, @alpha));
+}
+
+@color: #4D926F;
+
+#header {
+  color: @color;
+  color: #000000;
+}
+h2 {
+  color: @color;
+}
+
+.rounded-corners (@radius: 5px) {
+  border-radius: @radius;
+  -webkit-border-radius: @radius;
+  -moz-border-radius: @radius;
+}
+
+#header {
+  .rounded-corners;
+}
+#footer {
+  .rounded-corners(10px);
+}
+
+.box-shadow (@x: 0, @y: 0, @blur: 1px, @alpha) {
+  @val: @x @y @blur rgba(0, 0, 0, @alpha);
+
+  box-shadow:         @val;
+  -webkit-box-shadow: @val;
+  -moz-box-shadow:    @val;
+}
+.box { @base: #f938ab;
+  color:        saturate(@base, 5%);
+  border-color: lighten(@base, 30%);
+  div { .box-shadow(0, 0, 5px, 0.4) }
+}
+
+@import url("something.css");
+
+@light-blue:   hsl(190, 50%, 65%);
+@light-yellow: desaturate(#fefec8, 10%);
+@dark-yellow:  desaturate(darken(@light-yellow, 10%), 40%);
+@darkest:      hsl(20, 0%, 15%);
+@dark:         hsl(190, 20%, 30%);
+@medium:       hsl(10, 60%, 30%);
+@light:        hsl(90, 40%, 20%);
+@lightest:     hsl(90, 20%, 90%);
+@highlight:    hsl(80, 50%, 90%);
+@blue:         hsl(210, 60%, 20%);
+@alpha-blue:   hsla(210, 60%, 40%, 0.5);
+
+.box-shadow (@x, @y, @blur, @alpha) {
+  @value: @x @y @blur rgba(0, 0, 0, @alpha);
+  box-shadow:         @value;
+  -moz-box-shadow:    @value;
+  -webkit-box-shadow: @value;
+}
+.border-radius (@radius) {
+  border-radius: @radius;
+  -moz-border-radius: @radius;
+  -webkit-border-radius: @radius;
+}
+
+.border-radius (@radius, bottom) {
+  border-top-right-radius: 0;
+  border-top-left-radius: 0;
+  -moz-border-top-right-radius: 0;
+  -moz-border-top-left-radius: 0;
+  -webkit-border-top-left-radius: 0;
+  -webkit-border-top-right-radius: 0;
+}
+.border-radius (@radius, right) {
+  border-bottom-left-radius: 0;
+  border-top-left-radius: 0;
+  -moz-border-bottom-left-radius: 0;
+  -moz-border-top-left-radius: 0;
+  -webkit-border-bottom-left-radius: 0;
+  -webkit-border-top-left-radius: 0;
+}
+.box-shadow-inset (@x, @y, @blur, @color) {
+  box-shadow: @x @y @blur @color inset;
+  -moz-box-shadow: @x @y @blur @color inset;
+  -webkit-box-shadow: @x @y @blur @color inset;
+}
+.code () {
+  font-family: 'Bitstream Vera Sans Mono',
+               'DejaVu Sans Mono',
+               'Monaco',
+               Courier,
+               monospace !important;
+}
+.wrap () {
+  text-wrap: wrap;
+  white-space: pre-wrap;       /* css-3 */
+  white-space: -moz-pre-wrap;  /* Mozilla, since 1999 */
+  white-space: -pre-wrap;      /* Opera 4-6 */
+  white-space: -o-pre-wrap;    /* Opera 7 */
+  word-wrap: break-word;       /* Internet Explorer 5.5+ */
+}
+
+html { margin: 0 }
+body {
+  background-color: @darkest;
+  margin: 0 auto;
+  font-family: Arial, sans-serif;
+  font-size: 100%;
+  overflow-x: hidden;
+}
+nav, header, footer, section, article {
+  display: block;
+}
+a {
+  color: #b83000;
+}
+h1 a {
+  color: black;
+  text-decoration: none;
+}
+a:hover {
+  text-decoration: underline;
+}
+h1, h2, h3, h4 {
+  margin: 0;
+  font-weight: normal;
+}
+ul, li {
+  list-style-type: none;
+}
+code { .code; }
+code {
+  .string, .regexp { color: @dark }
+  .keyword { font-weight: bold }
+  .comment { color: rgba(0, 0, 0, 0.5) }
+  .number { color: @blue }
+  .class, .special { color: rgba(0, 50, 100, 0.8) }
+}
+pre {
+  padding: 0 30px;
+  .wrap;
+}
+blockquote {
+  font-style: italic;
+}
+body > footer {
+  text-align: left;
+  margin-left: 10px;
+  font-style: italic;
+  font-size: 18px;
+  color: #888;
+}
+
+#logo {
+  margin-top: 30px;
+  margin-bottom: 30px;
+  display: block;
+  width: 199px;
+  height: 81px;
+  background: url(/images/logo.png) no-repeat;
+}
+nav {
+  margin-left: 15px;
+}
+nav a, #dropdown li {
+  display: inline-block;
+  color: white;
+  line-height: 42px;
+  margin: 0;
+  padding: 0px 15px;
+  text-shadow: -1px -1px 1px rgba(0, 0, 0, 0.5);
+  text-decoration: none;
+  border: 2px solid transparent;
+  border-width: 0 2px;
+  &:hover {
+    .dark-red; 
+    text-decoration: none;
+  }
+}
+.dark-red {
+    @red: @medium;
+    border: 2px solid darken(@red, 25%);
+    border-left-color: darken(@red, 15%);
+    border-right-color: darken(@red, 15%);
+    border-bottom: 0;
+    border-top: 0;
+    background-color: darken(@red, 10%);
+}
+
+.content {
+  margin: 0 auto;
+  width: 980px;
+}
+
+#menu {
+  position: absolute;
+  width: 100%;
+  z-index: 3;
+  clear: both;
+  display: block;
+  background-color: @blue;
+  height: 42px;
+  border-top: 2px solid lighten(@alpha-blue, 20%);
+  border-bottom: 2px solid darken(@alpha-blue, 25%);
+  .box-shadow(0, 1px, 8px, 0.6);
+  -moz-box-shadow: 0 0 0 #000; // Because firefox sucks.
+
+  &.docked {
+    background-color: hsla(210, 60%, 40%, 0.4);
+  }
+  &:hover {
+    background-color: @blue;
+  }
+
+  #dropdown {
+    margin: 0 0 0 117px;
+    padding: 0;
+    padding-top: 5px;
+    display: none;
+    width: 190px;
+    border-top: 2px solid @medium;
+    color: @highlight;
+    border: 2px solid darken(@medium, 25%);
+    border-left-color: darken(@medium, 15%);
+    border-right-color: darken(@medium, 15%);
+    border-top-width: 0;
+    background-color: darken(@medium, 10%);
+    ul {
+      padding: 0px;  
+    }
+    li {
+      font-size: 14px;
+      display: block;
+      text-align: left;
+      padding: 0;
+      border: 0;
+      a {
+        display: block;
+        padding: 0px 15px;  
+        text-decoration: none;
+        color: white;  
+        &:hover {
+          background-color: darken(@medium, 15%);
+          text-decoration: none;
+        }
+      }
+    }
+    .border-radius(5px, bottom);
+    .box-shadow(0, 6px, 8px, 0.5);
+  }
+}
+
+#main {
+  margin: 0 auto;
+  width: 100%;
+  background-color: @light-blue;
+  border-top: 8px solid darken(@light-blue, 5%);
+
+  #intro {
+    background-color: lighten(@light-blue, 25%);
+    float: left;
+    margin-top: -8px;
+    margin-right: 5px;
+
+    height: 380px;
+    position: relative;
+    z-index: 2;
+    font-family: 'Droid Serif', 'Georgia';
+    width: 395px;
+    padding: 45px 20px 23px 30px;
+    border: 2px dashed darken(@light-blue, 10%);
+    .box-shadow(1px, 0px, 6px, 0.5);
+    border-bottom: 0;
+    border-top: 0;
+    #download { color: transparent; border: 0; float: left; display: inline-block; margin: 15px 0 15px -5px; }
+    #download img { display: inline-block}
+    #download-info {
+      code {
+        font-size: 13px;  
+      }
+      color: @blue + #333; display: inline; float: left; margin: 36px 0 0 15px }
+  }
+  h2 {
+    span {
+      color: @medium;  
+    }
+    color: @blue;
+    margin: 20px 0;
+    font-size: 24px;
+    line-height: 1.2em;
+  }
+  h3 {
+    color: @blue;
+    line-height: 1.4em;
+    margin: 30px 0 15px 0;
+    font-size: 1em;
+    text-shadow: 0px 0px 0px @lightest;
+    span { color: @medium }
+  }
+  #example {
+    p {
+      font-size: 18px;
+      color: @blue;
+      font-weight: bold;
+      text-shadow: 0px 1px 1px @lightest;
+    }
+    pre {
+      margin: 0;
+      text-shadow: 0 -1px 1px @darkest;
+      margin-top: 20px;
+      background-color: desaturate(@darkest, 8%);
+      border: 0;
+      width: 450px;
+      color: lighten(@lightest, 2%);
+      background-repeat: repeat;
+      padding: 15px;
+      border: 1px dashed @lightest;
+      line-height: 15px;
+      .box-shadow(0, 0px, 15px, 0.5);
+      .code;
+      .border-radius(2px);
+      code .attribute { color: hsl(40, 50%, 70%) }
+      code .variable  { color: hsl(120, 10%, 50%) }
+      code .element   { color: hsl(170, 20%, 50%) }
+
+      code .string, .regexp { color: hsl(75, 50%, 65%) }
+      code .class { color: hsl(40, 40%, 60%); font-weight: normal }
+      code .id { color: hsl(50, 40%, 60%); font-weight: normal }
+      code .comment { color: rgba(255, 255, 255, 0.2) }
+      code .number, .color { color: hsl(10, 40%, 50%) }
+      code .class, code .mixin, .special { color: hsl(190, 20%, 50%) }
+      #time { color: #aaa }
+    }
+    float: right;
+    font-size: 12px;
+    margin: 0;
+    margin-top: 15px;
+    padding: 0;
+    width: 500px;
+  }
+}
+
+
+.page {
+  .content {
+    width: 870px;
+    padding: 45px;
+  }
+  margin: 0 auto;
+  font-family: 'Georgia', serif;
+  font-size: 18px;
+  line-height: 26px;
+  padding: 0 60px;
+  code {
+    font-size: 16px;  
+  }
+  pre {
+    border-width: 1px;
+    border-style: dashed;
+    padding: 15px;
+    margin: 15px 0;
+  }
+  h1 {
+    text-align: left;
+    font-size: 40px;
+    margin-top: 15px;
+    margin-bottom: 35px;
+  }
+  p + h1 { margin-top: 60px }
+  h2, h3 {
+    margin: 30px 0 15px 0;
+  }
+  p + h2, pre + h2, code + h2 {
+    border-top: 6px solid rgba(255, 255, 255, 0.1);
+    padding-top: 30px;
+  }
+  h3 {
+    margin: 15px 0;
+  }
+}
+
+
+#docs {
+  @bg: lighten(@light-blue, 5%);
+  border-top: 2px solid lighten(@bg, 5%);
+  color: @blue;
+  background-color: @light-blue;
+  .box-shadow(0, -2px, 5px, 0.2);
+
+  h1 {
+    font-family: 'Droid Serif', 'Georgia', serif;
+    padding-top: 30px;
+    padding-left: 45px;
+    font-size: 44px;
+    text-align: left;
+    margin: 30px 0 !important;
+    text-shadow: 0px 1px 1px @lightest;
+    font-weight: bold;
+  }
+  .content {
+    clear: both;
+    border-color: transparent;
+    background-color: lighten(@light-blue, 25%);
+    .box-shadow(0, 5px, 5px, 0.4);
+  }
+  pre {
+    @background: lighten(@bg, 30%);
+    color: lighten(@blue, 10%);
+    background-color: @background;
+    border-color: lighten(@light-blue, 25%);
+    border-width: 2px;
+    code .attribute { color: hsl(40, 50%, 30%) }
+    code .variable  { color: hsl(120, 10%, 30%) }
+    code .element   { color: hsl(170, 20%, 30%) }
+
+    code .string, .regexp { color: hsl(75, 50%, 35%) }
+    code .class { color: hsl(40, 40%, 30%); font-weight: normal }
+    code .id { color: hsl(50, 40%, 30%); font-weight: normal }
+    code .comment { color: rgba(0, 0, 0, 0.4) }
+    code .number, .color { color: hsl(10, 40%, 30%) }
+    code .class, code .mixin, .special { color: hsl(190, 20%, 30%) }
+  }
+  pre code                    { font-size: 15px  }
+  p + h2, pre + h2, code + h2 { border-top-color: rgba(0, 0, 0, 0.1) }
+}
+
+td {
+  padding-right: 30px;  
+}
+#synopsis {
+  .box-shadow(0, 5px, 5px, 0.2);
+}
+#synopsis, #about {
+  h2 {
+    font-size: 30px;  
+    padding: 10px 0;
+  }
+  h1 + h2 {
+      margin-top: 15px;  
+  }
+  h3 { font-size: 22px }
+
+  .code-example {
+    border-spacing: 0;
+    border-width: 1px;
+    border-style: dashed;
+    padding: 0;
+    pre { border: 0; margin: 0 }
+    td {
+      border: 0;
+      margin: 0;
+      background-color: desaturate(darken(@darkest, 5%), 20%);
+      vertical-align: top;
+      padding: 0;
+    }
+    tr { padding: 0 }
+  }
+  .css-output {
+    td {
+      border-left: 0;  
+    }
+  }
+  .less-example {
+    //border-right: 1px dotted rgba(255, 255, 255, 0.5) !important;
+  }
+  .css-output, .less-example {
+    width: 390px;
+  }
+  pre {
+    padding: 20px;
+    line-height: 20px;
+    font-size: 14px;
+  }
+}
+#about, #synopsis, #guide {
+  a {
+    text-decoration: none;
+    color: @light-yellow;
+    border-bottom: 1px dashed rgba(255, 255, 255, 0.2);
+    &:hover {
+      text-decoration: none;
+      border-bottom: 1px dashed @light-yellow;
+    }
+  }
+  @bg: desaturate(darken(@darkest, 5%), 20%);
+  text-shadow: 0 -1px 1px lighten(@bg, 5%);
+  color: @highlight;
+  background-color: @bg;
+  .content {
+    background-color: desaturate(@darkest, 20%);
+    clear: both;
+    .box-shadow(0, 5px, 5px, 0.4);
+  }
+  h1, h2, h3 {
+    color: @dark-yellow;
+  }
+  pre {
+      code .attribute { color: hsl(40, 50%, 70%) }
+      code .variable  { color: hsl(120, 10%, 50%) }
+      code .element   { color: hsl(170, 20%, 50%) }
+
+      code .string, .regexp { color: hsl(75, 50%, 65%) }
+      code .class { color: hsl(40, 40%, 60%); font-weight: normal }
+      code .id { color: hsl(50, 40%, 60%); font-weight: normal }
+      code .comment { color: rgba(255, 255, 255, 0.2) }
+      code .number, .color { color: hsl(10, 40%, 50%) }
+      code .class, code .mixin, .special { color: hsl(190, 20%, 50%) }
+    background-color: @bg;
+    border-color: darken(@light-yellow, 5%);
+  }
+  code {
+    color: darken(@dark-yellow, 5%);
+    .string, .regexp { color: desaturate(@light-blue, 15%) }
+    .keyword { color: hsl(40, 40%, 60%); font-weight: normal }
+    .comment { color: rgba(255, 255, 255, 0.2) }
+    .number { color: lighten(@blue, 10%) }
+    .class, .special { color: hsl(190, 20%, 50%) }
+  }
+}
+#guide {
+  background-color: @darkest;
+  .content {
+    background-color: transparent;
+  }
+
+}
+
+#about {
+  background-color: @darkest !important;
+  .content {
+    background-color: desaturate(lighten(@darkest, 3%), 5%);
+  }
+}
+#synopsis {
+  background-color: desaturate(lighten(@darkest, 3%), 5%) !important;
+  .content {
+    background-color: desaturate(lighten(@darkest, 3%), 5%);
+  }
+  pre {}
+}
+#synopsis, #guide {
+  .content {
+    .box-shadow(0, 0px, 0px, 0.0);
+  }
+}
+#about footer {
+  margin-top: 30px;
+  padding-top: 30px;
+  border-top: 6px solid rgba(0, 0, 0, 0.1);
+  text-align: center;
+  font-size: 16px;
+  color: rgba(255, 255, 255, 0.35);
+  #copy { font-size: 12px }
+  text-shadow: -1px -1px 1px rgba(0, 0, 0, 0.02);
+}
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        theme: "lesser-dark",
+        lineNumbers : true,
+        matchBrackets : true
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-less</code>, <code>text/css</code> (if not previously defined).</p>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/less/less.js b/third-party/codemirror-3.15/mode/less/less.js
new file mode 100644 (file)
index 0000000..09f510e
--- /dev/null
@@ -0,0 +1,258 @@
+/*
+  LESS mode - http://www.lesscss.org/
+  Ported to CodeMirror by Peter Kroon <plakroon@gmail.com>
+  Report bugs/issues here: https://github.com/marijnh/CodeMirror/issues  GitHub: @peterkroon
+*/
+
+CodeMirror.defineMode("less", function(config) {
+  var indentUnit = config.indentUnit, type;
+  function ret(style, tp) {type = tp; return style;}
+
+  var selectors = /(^\:root$|^\:nth\-child$|^\:nth\-last\-child$|^\:nth\-of\-type$|^\:nth\-last\-of\-type$|^\:first\-child$|^\:last\-child$|^\:first\-of\-type$|^\:last\-of\-type$|^\:only\-child$|^\:only\-of\-type$|^\:empty$|^\:link|^\:visited$|^\:active$|^\:hover$|^\:focus$|^\:target$|^\:lang$|^\:enabled^\:disabled$|^\:checked$|^\:first\-line$|^\:first\-letter$|^\:before$|^\:after$|^\:not$|^\:required$|^\:invalid$)/;
+
+  function tokenBase(stream, state) {
+    var ch = stream.next();
+
+    if (ch == "@") {stream.eatWhile(/[\w\-]/); return ret("meta", stream.current());}
+    else if (ch == "/" && stream.eat("*")) {
+      state.tokenize = tokenCComment;
+      return tokenCComment(stream, state);
+    }
+    else if (ch == "<" && stream.eat("!")) {
+      state.tokenize = tokenSGMLComment;
+      return tokenSGMLComment(stream, state);
+    }
+    else if (ch == "=") ret(null, "compare");
+    else if (ch == "|" && stream.eat("=")) return ret(null, "compare");
+    else if (ch == "\"" || ch == "'") {
+      state.tokenize = tokenString(ch);
+      return state.tokenize(stream, state);
+    }
+    else if (ch == "/") { // e.g.: .png will not be parsed as a class
+      if(stream.eat("/")){
+        state.tokenize = tokenSComment;
+        return tokenSComment(stream, state);
+      }else{
+        if(type == "string" || type == "(")return ret("string", "string");
+        if(state.stack[state.stack.length-1] != undefined)return ret(null, ch);
+        stream.eatWhile(/[\a-zA-Z0-9\-_.\s]/);
+        if( /\/|\)|#/.test(stream.peek() || (stream.eatSpace() && stream.peek() == ")"))  || stream.eol() )return ret("string", "string"); // let url(/images/logo.png) without quotes return as string
+      }
+    }
+    else if (ch == "!") {
+      stream.match(/^\s*\w*/);
+      return ret("keyword", "important");
+    }
+    else if (/\d/.test(ch)) {
+      stream.eatWhile(/[\w.%]/);
+      return ret("number", "unit");
+    }
+    else if (/[,+<>*\/]/.test(ch)) {
+      if(stream.peek() == "=" || type == "a")return ret("string", "string");
+      return ret(null, "select-op");
+    }
+    else if (/[;{}:\[\]()~\|]/.test(ch)) {
+      if(ch == ":"){
+        stream.eatWhile(/[a-z\\\-]/);
+        if( selectors.test(stream.current()) ){
+          return ret("tag", "tag");
+        }else if(stream.peek() == ":"){//::-webkit-search-decoration
+          stream.next();
+          stream.eatWhile(/[a-z\\\-]/);
+          if(stream.current().match(/\:\:\-(o|ms|moz|webkit)\-/))return ret("string", "string");
+          if( selectors.test(stream.current().substring(1)) )return ret("tag", "tag");
+          return ret(null, ch);
+        }else{
+          return ret(null, ch);
+        }
+      }else if(ch == "~"){
+        if(type == "r")return ret("string", "string");
+      }else{
+        return ret(null, ch);
+      }
+    }
+    else if (ch == ".") {
+      if(type == "(" || type == "string")return ret("string", "string"); // allow url(../image.png)
+      stream.eatWhile(/[\a-zA-Z0-9\-_]/);
+      if(stream.peek() == " ")stream.eatSpace();
+      if(stream.peek() == ")")return ret("number", "unit");//rgba(0,0,0,.25);
+      return ret("tag", "tag");
+    }
+    else if (ch == "#") {
+      //we don't eat white-space, we want the hex color and or id only
+      stream.eatWhile(/[A-Za-z0-9]/);
+      //check if there is a proper hex color length e.g. #eee || #eeeEEE
+      if(stream.current().length == 4 || stream.current().length == 7){
+        if(stream.current().match(/[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3}/,false) != null){//is there a valid hex color value present in the current stream
+          //when not a valid hex value, parse as id
+          if(stream.current().substring(1) != stream.current().match(/[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3}/,false))return ret("atom", "tag");
+          //eat white-space
+          stream.eatSpace();
+          //when hex value declaration doesn't end with [;,] but is does with a slash/cc comment treat it as an id, just like the other hex values that don't end with[;,]
+          if( /[\/<>.(){!$%^&*_\-\\?=+\|#'~`]/.test(stream.peek()) )return ret("atom", "tag");
+          //#time { color: #aaa }
+          else if(stream.peek() == "}" )return ret("number", "unit");
+          //we have a valid hex color value, parse as id whenever an element/class is defined after the hex(id) value e.g. #eee aaa || #eee .aaa
+          else if( /[a-zA-Z\\]/.test(stream.peek()) )return ret("atom", "tag");
+          //when a hex value is on the end of a line, parse as id
+          else if(stream.eol())return ret("atom", "tag");
+          //default
+          else return ret("number", "unit");
+        }else{//when not a valid hexvalue in the current stream e.g. #footer
+          stream.eatWhile(/[\w\\\-]/);
+          return ret("atom", "tag");
+        }
+      }else{//when not a valid hexvalue length
+        stream.eatWhile(/[\w\\\-]/);
+        return ret("atom", "tag");
+      }
+    }
+    else if (ch == "&") {
+      stream.eatWhile(/[\w\-]/);
+      return ret(null, ch);
+    }
+    else {
+      stream.eatWhile(/[\w\\\-_%.{]/);
+      if(type == "string"){
+        return ret("string", "string");
+      }else if(stream.current().match(/(^http$|^https$)/) != null){
+        stream.eatWhile(/[\w\\\-_%.{:\/]/);
+        return ret("string", "string");
+      }else if(stream.peek() == "<" || stream.peek() == ">"){
+        return ret("tag", "tag");
+      }else if( /\(/.test(stream.peek()) ){
+        return ret(null, ch);
+      }else if (stream.peek() == "/" && state.stack[state.stack.length-1] != undefined){ // url(dir/center/image.png)
+        return ret("string", "string");
+      }else if( stream.current().match(/\-\d|\-.\d/) ){ // match e.g.: -5px -0.4 etc... only colorize the minus sign
+        //commment out these 2 comment if you want the minus sign to be parsed as null -500px
+        //stream.backUp(stream.current().length-1);
+        //return ret(null, ch); //console.log( stream.current() );
+        return ret("number", "unit");
+      }else if( /\/|[\s\)]/.test(stream.peek() || stream.eol() || (stream.eatSpace() && stream.peek() == "/")) && stream.current().indexOf(".") !== -1){
+        if(stream.current().substring(stream.current().length-1,stream.current().length) == "{"){
+          stream.backUp(1);
+          return ret("tag", "tag");
+        }//end if
+        stream.eatSpace();
+        if( /[{<>.a-zA-Z\/]/.test(stream.peek())  || stream.eol() )return ret("tag", "tag"); // e.g. button.icon-plus
+        return ret("string", "string"); // let url(/images/logo.png) without quotes return as string
+      }else if( stream.eol() || stream.peek() == "[" || stream.peek() == "#" || type == "tag" ){
+        if(stream.current().substring(stream.current().length-1,stream.current().length) == "{")stream.backUp(1);
+        return ret("tag", "tag");
+      }else if(type == "compare" || type == "a" || type == "("){
+        return ret("string", "string");
+      }else if(type == "|" || stream.current() == "-" || type == "["){
+        return ret(null, ch);
+      }else if(stream.peek() == ":") {
+        stream.next();
+        var t_v = stream.peek() == ":" ? true : false;
+        if(!t_v){
+          var old_pos = stream.pos;
+          var sc = stream.current().length;
+          stream.eatWhile(/[a-z\\\-]/);
+          var new_pos = stream.pos;
+          if(stream.current().substring(sc-1).match(selectors) != null){
+            stream.backUp(new_pos-(old_pos-1));
+            return ret("tag", "tag");
+          } else stream.backUp(new_pos-(old_pos-1));
+        }else{
+          stream.backUp(1);
+        }
+        if(t_v)return ret("tag", "tag"); else return ret("variable", "variable");
+      }else{
+        return ret("variable", "variable");
+      }
+    }
+  }
+
+  function tokenSComment(stream, state) { // SComment = Slash comment
+    stream.skipToEnd();
+    state.tokenize = tokenBase;
+    return ret("comment", "comment");
+  }
+
+  function tokenCComment(stream, state) {
+    var maybeEnd = false, ch;
+    while ((ch = stream.next()) != null) {
+      if (maybeEnd && ch == "/") {
+        state.tokenize = tokenBase;
+        break;
+      }
+      maybeEnd = (ch == "*");
+    }
+    return ret("comment", "comment");
+  }
+
+  function tokenSGMLComment(stream, state) {
+    var dashes = 0, ch;
+    while ((ch = stream.next()) != null) {
+      if (dashes >= 2 && ch == ">") {
+        state.tokenize = tokenBase;
+        break;
+      }
+      dashes = (ch == "-") ? dashes + 1 : 0;
+    }
+    return ret("comment", "comment");
+  }
+
+  function tokenString(quote) {
+    return function(stream, state) {
+      var escaped = false, ch;
+      while ((ch = stream.next()) != null) {
+        if (ch == quote && !escaped)
+          break;
+        escaped = !escaped && ch == "\\";
+      }
+      if (!escaped) state.tokenize = tokenBase;
+      return ret("string", "string");
+    };
+  }
+
+  return {
+    startState: function(base) {
+      return {tokenize: tokenBase,
+              baseIndent: base || 0,
+              stack: []};
+    },
+
+    token: function(stream, state) {
+      if (stream.eatSpace()) return null;
+      var style = state.tokenize(stream, state);
+
+      var context = state.stack[state.stack.length-1];
+      if (type == "hash" && context == "rule") style = "atom";
+      else if (style == "variable") {
+        if (context == "rule") style = null; //"tag"
+        else if (!context || context == "@media{") {
+          style = stream.current() == "when"  ? "variable" :
+          /[\s,|\s\)|\s]/.test(stream.peek()) ? "tag"      : type;
+        }
+      }
+
+      if (context == "rule" && /^[\{\};]$/.test(type))
+        state.stack.pop();
+      if (type == "{") {
+        if (context == "@media") state.stack[state.stack.length-1] = "@media{";
+        else state.stack.push("{");
+      }
+      else if (type == "}") state.stack.pop();
+      else if (type == "@media") state.stack.push("@media");
+      else if (context == "{" && type != "comment") state.stack.push("rule");
+      return style;
+    },
+
+    indent: function(state, textAfter) {
+      var n = state.stack.length;
+      if (/^\}/.test(textAfter))
+        n -= state.stack[state.stack.length-1] == "rule" ? 2 : 1;
+      return state.baseIndent + n * indentUnit;
+    },
+
+    electricChars: "}"
+  };
+});
+
+CodeMirror.defineMIME("text/x-less", "less");
+if (!CodeMirror.mimeModes.hasOwnProperty("text/css"))
+  CodeMirror.defineMIME("text/css", "less");
diff --git a/third-party/codemirror-3.15/mode/livescript/LICENSE b/third-party/codemirror-3.15/mode/livescript/LICENSE
new file mode 100644 (file)
index 0000000..a675c40
--- /dev/null
@@ -0,0 +1,23 @@
+The MIT License
+
+Copyright (c) 2013 Kenneth Bentley
+Modified from the CoffeeScript CodeMirror mode, Copyright (c) 2011 Jeff Pickhardt
+Modified from the Python CodeMirror mode, Copyright (c) 2010 Timothy Farrell
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/third-party/codemirror-3.15/mode/livescript/index.html b/third-party/codemirror-3.15/mode/livescript/index.html
new file mode 100644 (file)
index 0000000..3054e35
--- /dev/null
@@ -0,0 +1,446 @@
+<!doctype html>
+<html>
+  <head>
+    <title>CodeMirror: LiveScript mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="livescript.js"></script>
+    <style>.CodeMirror {font-size: 80%;border-top: 1px solid silver; border-bottom: 1px solid silver;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <link rel="stylesheet" href="../../theme/solarized.css">
+  </head>
+  <body>
+    <h1>CodeMirror: LiveScript mode</h1>
+    <form><textarea id="code" name="code">
+# LiveScript mode for CodeMirror
+# The following script, prelude.ls, is used to
+# demonstrate LiveScript mode for CodeMirror.
+#   https://github.com/gkz/prelude-ls
+
+export objToFunc = objToFunc = (obj) ->
+  (key) -> obj[key]
+
+export each = (f, xs) -->
+  if typeof! xs is \Object
+    for , x of xs then f x
+  else
+    for x in xs then f x
+  xs
+
+export map = (f, xs) -->
+  f = objToFunc f if typeof! f isnt \Function
+  type = typeof! xs
+  if type is \Object
+    {[key, f x] for key, x of xs}
+  else
+    result = [f x for x in xs]
+    if type is \String then result * '' else result
+
+export filter = (f, xs) -->
+  f = objToFunc f if typeof! f isnt \Function
+  type = typeof! xs
+  if type is \Object
+    {[key, x] for key, x of xs when f x}
+  else
+    result = [x for x in xs when f x]
+    if type is \String then result * '' else result
+
+export reject = (f, xs) -->
+  f = objToFunc f if typeof! f isnt \Function
+  type = typeof! xs
+  if type is \Object
+    {[key, x] for key, x of xs when not f x}
+  else
+    result = [x for x in xs when not f x]
+    if type is \String then result * '' else result
+
+export partition = (f, xs) -->
+  f = objToFunc f if typeof! f isnt \Function
+  type = typeof! xs
+  if type is \Object
+    passed = {}
+    failed = {}
+    for key, x of xs
+      (if f x then passed else failed)[key] = x
+  else
+    passed = []
+    failed = []
+    for x in xs
+      (if f x then passed else failed)push x
+    if type is \String
+      passed *= ''
+      failed *= ''
+  [passed, failed]
+
+export find = (f, xs) -->
+  f = objToFunc f if typeof! f isnt \Function
+  if typeof! xs is \Object
+    for , x of xs when f x then return x
+  else
+    for x in xs when f x then return x
+  void
+
+export head = export first = (xs) ->
+  return void if not xs.length
+  xs.0
+
+export tail = (xs) ->
+  return void if not xs.length
+  xs.slice 1
+
+export last = (xs) ->
+  return void if not xs.length
+  xs[*-1]
+
+export initial = (xs) ->
+  return void if not xs.length
+  xs.slice 0 xs.length - 1
+
+export empty = (xs) ->
+  if typeof! xs is \Object
+    for x of xs then return false
+    return yes
+  not xs.length
+
+export values = (obj) ->
+  [x for , x of obj]
+
+export keys = (obj) ->
+  [x for x of obj]
+
+export len = (xs) ->
+  xs = values xs if typeof! xs is \Object
+  xs.length
+
+export cons = (x, xs) -->
+  if typeof! xs is \String then x + xs else [x] ++ xs
+
+export append = (xs, ys) -->
+  if typeof! ys is \String then xs + ys else xs ++ ys
+
+export join = (sep, xs) -->
+  xs = values xs if typeof! xs is \Object
+  xs.join sep
+
+export reverse = (xs) ->
+  if typeof! xs is \String
+  then (xs / '')reverse! * ''
+  else xs.slice!reverse!
+
+export fold = export foldl = (f, memo, xs) -->
+  if typeof! xs is \Object
+    for , x of xs then memo = f memo, x
+  else
+    for x in xs then memo = f memo, x
+  memo
+
+export fold1 = export foldl1 = (f, xs) --> fold f, xs.0, xs.slice 1
+
+export foldr = (f, memo, xs) --> fold f, memo, xs.slice!reverse!
+
+export foldr1 = (f, xs) -->
+  xs.=slice!reverse!
+  fold f, xs.0, xs.slice 1
+
+export unfoldr = export unfold = (f, b) -->
+  if (f b)?
+    [that.0] ++ unfoldr f, that.1
+  else
+    []
+
+export andList = (xs) ->
+  for x in xs when not x
+    return false
+  true
+
+export orList = (xs) ->
+  for x in xs when x
+    return true
+  false
+
+export any = (f, xs) -->
+  f = objToFunc f if typeof! f isnt \Function
+  for x in xs when f x
+    return yes
+  no
+
+export all = (f, xs) -->
+  f = objToFunc f if typeof! f isnt \Function
+  for x in xs when not f x
+    return no
+  yes
+
+export unique = (xs) ->
+  result = []
+  if typeof! xs is \Object
+    for , x of xs when x not in result then result.push x
+  else
+    for x   in xs when x not in result then result.push x
+  if typeof! xs is \String then result * '' else result
+
+export sort = (xs) ->
+  xs.concat!sort (x, y) ->
+    | x > y =>  1
+    | x < y => -1
+    | _     =>  0
+
+export sortBy = (f, xs) -->
+  return [] unless xs.length
+  xs.concat!sort f
+
+export compare = (f, x, y) -->
+  | (f x) > (f y) =>  1
+  | (f x) < (f y) => -1
+  | otherwise     =>  0
+
+export sum = (xs) ->
+  result = 0
+  if typeof! xs is \Object
+    for , x of xs then result += x
+  else
+    for x   in xs then result += x
+  result
+
+export product = (xs) ->
+  result = 1
+  if typeof! xs is \Object
+    for , x of xs then result *= x
+  else
+    for x   in xs then result *= x
+  result
+
+export mean = export average = (xs) -> (sum xs) / len xs
+
+export concat = (xss) -> fold append, [], xss
+
+export concatMap = (f, xs) --> fold ((memo, x) -> append memo, f x), [], xs
+
+export listToObj = (xs) ->
+  {[x.0, x.1] for x in xs}
+
+export maximum = (xs) -> fold1 (>?), xs
+
+export minimum = (xs) -> fold1 (<?), xs
+
+export scan = export scanl = (f, memo, xs) -->
+  last = memo
+  if typeof! xs is \Object
+  then [memo] ++ [last = f last, x for , x of xs]
+  else [memo] ++ [last = f last, x for x in xs]
+
+export scan1 = export scanl1 = (f, xs) --> scan f, xs.0, xs.slice 1
+
+export scanr = (f, memo, xs) -->
+  xs.=slice!reverse!
+  scan f, memo, xs .reverse!
+
+export scanr1 = (f, xs) -->
+  xs.=slice!reverse!
+  scan f, xs.0, xs.slice 1 .reverse!
+
+export replicate = (n, x) -->
+  result = []
+  i = 0
+  while i < n, ++i then result.push x
+  result
+
+export take = (n, xs) -->
+  | n <= 0
+    if typeof! xs is \String then '' else []
+  | not xs.length => xs
+  | otherwise     => xs.slice 0, n
+
+export drop = (n, xs) -->
+  | n <= 0        => xs
+  | not xs.length => xs
+  | otherwise     => xs.slice n
+
+export splitAt = (n, xs) --> [(take n, xs), (drop n, xs)]
+
+export takeWhile = (p, xs) -->
+  return xs if not xs.length
+  p = objToFunc p if typeof! p isnt \Function
+  result = []
+  for x in xs
+    break if not p x
+    result.push x
+  if typeof! xs is \String then result * '' else result
+
+export dropWhile = (p, xs) -->
+  return xs if not xs.length
+  p = objToFunc p if typeof! p isnt \Function
+  i = 0
+  for x in xs
+    break if not p x
+    ++i
+  drop i, xs
+
+export span = (p, xs) --> [(takeWhile p, xs), (dropWhile p, xs)]
+
+export breakIt = (p, xs) --> span (not) << p, xs
+
+export zip = (xs, ys) -->
+  result = []
+  for zs, i in [xs, ys]
+    for z, j in zs
+      result.push [] if i is 0
+      result[j]?push z
+  result
+
+export zipWith = (f,xs, ys) -->
+  f = objToFunc f if typeof! f isnt \Function
+  if not xs.length or not ys.length
+    []
+  else
+    [f.apply this, zs for zs in zip.call this, xs, ys]
+
+export zipAll = (...xss) ->
+  result = []
+  for xs, i in xss
+    for x, j in xs
+      result.push [] if i is 0
+      result[j]?push x
+  result
+
+export zipAllWith = (f, ...xss) ->
+  f = objToFunc f if typeof! f isnt \Function
+  if not xss.0.length or not xss.1.length
+    []
+  else
+    [f.apply this, xs for xs in zipAll.apply this, xss]
+
+export compose = (...funcs) ->
+  ->
+    args = arguments
+    for f in funcs
+      args = [f.apply this, args]
+    args.0
+
+export curry = (f) ->
+  curry$ f # using util method curry$ from livescript
+
+export id = (x) -> x
+
+export flip = (f, x, y) --> f y, x
+
+export fix = (f) ->
+  ( (g, x) -> -> f(g g) ...arguments ) do
+    (g, x) -> -> f(g g) ...arguments
+
+export lines = (str) ->
+  return [] if not str.length
+  str / \\n
+
+export unlines = (strs) -> strs * \\n
+
+export words = (str) ->
+  return [] if not str.length
+  str / /[ ]+/
+
+export unwords = (strs) -> strs * ' '
+
+export max = (>?)
+
+export min = (<?)
+
+export negate = (x) -> -x
+
+export abs = Math.abs
+
+export signum = (x) ->
+  | x < 0     => -1
+  | x > 0     =>  1
+  | otherwise =>  0
+
+export quot = (x, y) --> ~~(x / y)
+
+export rem = (%)
+
+export div = (x, y) --> Math.floor x / y
+
+export mod = (%%)
+
+export recip = (1 /)
+
+export pi = Math.PI
+
+export tau = pi * 2
+
+export exp = Math.exp
+
+export sqrt = Math.sqrt
+
+# changed from log as log is a
+# common function for logging things
+export ln = Math.log
+
+export pow = (^)
+
+export sin = Math.sin
+
+export tan = Math.tan
+
+export cos = Math.cos
+
+export asin = Math.asin
+
+export acos = Math.acos
+
+export atan = Math.atan
+
+export atan2 = (x, y) --> Math.atan2 x, y
+
+# sinh
+# tanh
+# cosh
+# asinh
+# atanh
+# acosh
+
+export truncate = (x) -> ~~x
+
+export round = Math.round
+
+export ceiling = Math.ceil
+
+export floor = Math.floor
+
+export isItNaN = (x) -> x isnt x
+
+export even = (x) -> x % 2 == 0
+
+export odd = (x) -> x % 2 != 0
+
+export gcd = (x, y) -->
+  x = Math.abs x
+  y = Math.abs y
+  until y is 0
+    z = x % y
+    x = y
+    y = z
+  x
+
+export lcm = (x, y) -->
+  Math.abs Math.floor (x / (gcd x, y) * y)
+
+# meta
+export installPrelude = !(target) ->
+  unless target.prelude?isInstalled
+    target <<< out$ # using out$ generated by livescript
+    target <<< target.prelude.isInstalled = true
+
+export prelude = out$
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        theme: "solarized light",
+        lineNumbers: true
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-livescript</code>.</p>
+
+    <p>The LiveScript mode was written by Kenneth Bentley (<a href="LICENSE">license</a>).</p>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/livescript/livescript.js b/third-party/codemirror-3.15/mode/livescript/livescript.js
new file mode 100644 (file)
index 0000000..c000324
--- /dev/null
@@ -0,0 +1,267 @@
+/**
+ * Link to the project's GitHub page:
+ * https://github.com/duralog/CodeMirror
+ */
+(function() {
+  CodeMirror.defineMode('livescript', function(){
+    var tokenBase, external;
+    tokenBase = function(stream, state){
+      var next_rule, nr, i$, len$, r, m;
+      if (next_rule = state.next || 'start') {
+        state.next = state.next;
+        if (Array.isArray(nr = Rules[next_rule])) {
+          for (i$ = 0, len$ = nr.length; i$ < len$; ++i$) {
+            r = nr[i$];
+            if (r.regex && (m = stream.match(r.regex))) {
+              state.next = r.next;
+              return r.token;
+            }
+          }
+          stream.next();
+          return 'error';
+        }
+        if (stream.match(r = Rules[next_rule])) {
+          if (r.regex && stream.match(r.regex)) {
+            state.next = r.next;
+            return r.token;
+          } else {
+            stream.next();
+            return 'error';
+          }
+        }
+      }
+      stream.next();
+      return 'error';
+    };
+    external = {
+      startState: function(){
+        return {
+          next: 'start',
+          lastToken: null
+        };
+      },
+      token: function(stream, state){
+        var style;
+        style = tokenBase(stream, state);
+        state.lastToken = {
+          style: style,
+          indent: stream.indentation(),
+          content: stream.current()
+        };
+        return style.replace(/\./g, ' ');
+      },
+      indent: function(state){
+        var indentation;
+        indentation = state.lastToken.indent;
+        if (state.lastToken.content.match(indenter)) {
+          indentation += 2;
+        }
+        return indentation;
+      }
+    };
+    return external;
+  });
+
+  var identifier = '(?![\\d\\s])[$\\w\\xAA-\\uFFDC](?:(?!\\s)[$\\w\\xAA-\\uFFDC]|-[A-Za-z])*';
+  var indenter = RegExp('(?:[({[=:]|[-~]>|\\b(?:e(?:lse|xport)|d(?:o|efault)|t(?:ry|hen)|finally|import(?:\\s*all)?|const|var|let|new|catch(?:\\s*' + identifier + ')?))\\s*$');
+  var keywordend = '(?![$\\w]|-[A-Za-z]|\\s*:(?![:=]))';
+  var stringfill = {
+    token: 'string',
+    regex: '.+'
+  };
+  var Rules = {
+    start: [
+      {
+        token: 'comment.doc',
+        regex: '/\\*',
+        next: 'comment'
+      }, {
+        token: 'comment',
+        regex: '#.*'
+      }, {
+        token: 'keyword',
+        regex: '(?:t(?:h(?:is|row|en)|ry|ypeof!?)|c(?:on(?:tinue|st)|a(?:se|tch)|lass)|i(?:n(?:stanceof)?|mp(?:ort(?:\\s+all)?|lements)|[fs])|d(?:e(?:fault|lete|bugger)|o)|f(?:or(?:\\s+own)?|inally|unction)|s(?:uper|witch)|e(?:lse|x(?:tends|port)|val)|a(?:nd|rguments)|n(?:ew|ot)|un(?:less|til)|w(?:hile|ith)|o[fr]|return|break|let|var|loop)' + keywordend
+      }, {
+        token: 'constant.language',
+        regex: '(?:true|false|yes|no|on|off|null|void|undefined)' + keywordend
+      }, {
+        token: 'invalid.illegal',
+        regex: '(?:p(?:ackage|r(?:ivate|otected)|ublic)|i(?:mplements|nterface)|enum|static|yield)' + keywordend
+      }, {
+        token: 'language.support.class',
+        regex: '(?:R(?:e(?:gExp|ferenceError)|angeError)|S(?:tring|yntaxError)|E(?:rror|valError)|Array|Boolean|Date|Function|Number|Object|TypeError|URIError)' + keywordend
+      }, {
+        token: 'language.support.function',
+        regex: '(?:is(?:NaN|Finite)|parse(?:Int|Float)|Math|JSON|(?:en|de)codeURI(?:Component)?)' + keywordend
+      }, {
+        token: 'variable.language',
+        regex: '(?:t(?:hat|il|o)|f(?:rom|allthrough)|it|by|e)' + keywordend
+      }, {
+        token: 'identifier',
+        regex: identifier + '\\s*:(?![:=])'
+      }, {
+        token: 'variable',
+        regex: identifier
+      }, {
+        token: 'keyword.operator',
+        regex: '(?:\\.{3}|\\s+\\?)'
+      }, {
+        token: 'keyword.variable',
+        regex: '(?:@+|::|\\.\\.)',
+        next: 'key'
+      }, {
+        token: 'keyword.operator',
+        regex: '\\.\\s*',
+        next: 'key'
+      }, {
+        token: 'string',
+        regex: '\\\\\\S[^\\s,;)}\\]]*'
+      }, {
+        token: 'string.doc',
+        regex: '\'\'\'',
+        next: 'qdoc'
+      }, {
+        token: 'string.doc',
+        regex: '"""',
+        next: 'qqdoc'
+      }, {
+        token: 'string',
+        regex: '\'',
+        next: 'qstring'
+      }, {
+        token: 'string',
+        regex: '"',
+        next: 'qqstring'
+      }, {
+        token: 'string',
+        regex: '`',
+        next: 'js'
+      }, {
+        token: 'string',
+        regex: '<\\[',
+        next: 'words'
+      }, {
+        token: 'string.regex',
+        regex: '//',
+        next: 'heregex'
+      }, {
+        token: 'string.regex',
+        regex: '\\/(?:[^[\\/\\n\\\\]*(?:(?:\\\\.|\\[[^\\]\\n\\\\]*(?:\\\\.[^\\]\\n\\\\]*)*\\])[^[\\/\\n\\\\]*)*)\\/[gimy$]{0,4}',
+        next: 'key'
+      }, {
+        token: 'constant.numeric',
+        regex: '(?:0x[\\da-fA-F][\\da-fA-F_]*|(?:[2-9]|[12]\\d|3[0-6])r[\\da-zA-Z][\\da-zA-Z_]*|(?:\\d[\\d_]*(?:\\.\\d[\\d_]*)?|\\.\\d[\\d_]*)(?:e[+-]?\\d[\\d_]*)?[\\w$]*)'
+      }, {
+        token: 'lparen',
+        regex: '[({[]'
+      }, {
+        token: 'rparen',
+        regex: '[)}\\]]',
+        next: 'key'
+      }, {
+        token: 'keyword.operator',
+        regex: '\\S+'
+      }, {
+        token: 'text',
+        regex: '\\s+'
+      }
+    ],
+    heregex: [
+      {
+        token: 'string.regex',
+        regex: '.*?//[gimy$?]{0,4}',
+        next: 'start'
+      }, {
+        token: 'string.regex',
+        regex: '\\s*#{'
+      }, {
+        token: 'comment.regex',
+        regex: '\\s+(?:#.*)?'
+      }, {
+        token: 'string.regex',
+        regex: '\\S+'
+      }
+    ],
+    key: [
+      {
+        token: 'keyword.operator',
+        regex: '[.?@!]+'
+      }, {
+        token: 'identifier',
+        regex: identifier,
+        next: 'start'
+      }, {
+        token: 'text',
+        regex: '.',
+        next: 'start'
+      }
+    ],
+    comment: [
+      {
+        token: 'comment.doc',
+        regex: '.*?\\*/',
+        next: 'start'
+      }, {
+        token: 'comment.doc',
+        regex: '.+'
+      }
+    ],
+    qdoc: [
+      {
+        token: 'string',
+        regex: ".*?'''",
+        next: 'key'
+      }, stringfill
+    ],
+    qqdoc: [
+      {
+        token: 'string',
+        regex: '.*?"""',
+        next: 'key'
+      }, stringfill
+    ],
+    qstring: [
+      {
+        token: 'string',
+        regex: '[^\\\\\']*(?:\\\\.[^\\\\\']*)*\'',
+        next: 'key'
+      }, stringfill
+    ],
+    qqstring: [
+      {
+        token: 'string',
+        regex: '[^\\\\"]*(?:\\\\.[^\\\\"]*)*"',
+        next: 'key'
+      }, stringfill
+    ],
+    js: [
+      {
+        token: 'string',
+        regex: '[^\\\\`]*(?:\\\\.[^\\\\`]*)*`',
+        next: 'key'
+      }, stringfill
+    ],
+    words: [
+      {
+        token: 'string',
+        regex: '.*?\\]>',
+        next: 'key'
+      }, stringfill
+    ]
+  };
+  for (var idx in Rules) {
+    var r = Rules[idx];
+    if (Array.isArray(r)) {
+      for (var i = 0, len = r.length; i < len; ++i) {
+        var rr = r[i];
+        if (rr.regex) {
+          Rules[idx][i].regex = new RegExp('^' + rr.regex);
+        }
+      }
+    } else if (r.regex) {
+      Rules[idx].regex = new RegExp('^' + r.regex);
+    }
+  }
+})();
+
+CodeMirror.defineMIME('text/x-livescript', 'livescript');
diff --git a/third-party/codemirror-3.15/mode/livescript/livescript.ls b/third-party/codemirror-3.15/mode/livescript/livescript.ls
new file mode 100644 (file)
index 0000000..0652423
--- /dev/null
@@ -0,0 +1,266 @@
+/**
+ * Link to the project's GitHub page:
+ * https://github.com/duralog/CodeMirror
+ */
+CodeMirror.defineMode 'livescript', (conf) ->
+  tokenBase = (stream, state) ->
+    #indent =
+    if next_rule = state.next or \start
+      state.next = state.next
+      if Array.isArray nr = Rules[next_rule]
+        for r in nr
+          if r.regex and m = stream.match r.regex
+            state.next = r.next
+            return r.token
+        stream.next!
+        return \error
+      if stream.match r = Rules[next_rule]
+        if r.regex and stream.match r.regex
+          state.next = r.next
+          return r.token
+        else
+          stream.next!
+          return \error
+    stream.next!
+    return 'error'
+  external = {
+    startState: (basecolumn) ->
+      {
+        next: \start
+        lastToken: null
+      }
+    token: (stream, state) ->
+      style = tokenBase stream, state #tokenLexer stream, state
+      state.lastToken = {
+        style: style
+        indent: stream.indentation!
+        content: stream.current!
+      }
+      style.replace /\./g, ' '
+    indent: (state, textAfter) ->
+      # XXX this won't work with backcalls
+      indentation = state.lastToken.indent
+      if state.lastToken.content.match indenter then indentation += 2
+      return indentation
+  }
+  external
+
+### Highlight Rules
+# taken from mode-ls.ls
+
+indenter = // (?
+    : [({[=:]
+    | [-~]>
+    | \b (?: e(?:lse|xport) | d(?:o|efault) | t(?:ry|hen) | finally |
+             import (?:\s* all)? | const | var |
+             let | new | catch (?:\s* #identifier)? )
+  ) \s* $ //
+
+identifier = /(?![\d\s])[$\w\xAA-\uFFDC](?:(?!\s)[$\w\xAA-\uFFDC]|-[A-Za-z])*/$
+keywordend = /(?![$\w]|-[A-Za-z]|\s*:(?![:=]))/$
+stringfill = token: \string, regex: '.+'
+
+Rules =
+  start:
+    * token: \comment.doc
+      regex: '/\\*'
+      next : \comment
+
+    * token: \comment
+      regex: '#.*'
+
+    * token: \keyword
+      regex: //(?
+        :t(?:h(?:is|row|en)|ry|ypeof!?)
+        |c(?:on(?:tinue|st)|a(?:se|tch)|lass)
+        |i(?:n(?:stanceof)?|mp(?:ort(?:\s+all)?|lements)|[fs])
+        |d(?:e(?:fault|lete|bugger)|o)
+        |f(?:or(?:\s+own)?|inally|unction)
+        |s(?:uper|witch)
+        |e(?:lse|x(?:tends|port)|val)
+        |a(?:nd|rguments)
+        |n(?:ew|ot)
+        |un(?:less|til)
+        |w(?:hile|ith)
+        |o[fr]|return|break|let|var|loop
+      )//$ + keywordend
+
+    * token: \constant.language
+      regex: '(?:true|false|yes|no|on|off|null|void|undefined)' + keywordend
+
+    * token: \invalid.illegal
+      regex: '(?
+        :p(?:ackage|r(?:ivate|otected)|ublic)
+        |i(?:mplements|nterface)
+        |enum|static|yield
+      )' + keywordend
+
+    * token: \language.support.class
+      regex: '(?
+        :R(?:e(?:gExp|ferenceError)|angeError)
+        |S(?:tring|yntaxError)
+        |E(?:rror|valError)
+        |Array|Boolean|Date|Function|Number|Object|TypeError|URIError
+      )' + keywordend
+
+    * token: \language.support.function
+      regex: '(?
+        :is(?:NaN|Finite)
+        |parse(?:Int|Float)
+        |Math|JSON
+        |(?:en|de)codeURI(?:Component)?
+      )' + keywordend
+
+    * token: \variable.language
+      regex: '(?:t(?:hat|il|o)|f(?:rom|allthrough)|it|by|e)' + keywordend
+
+    * token: \identifier
+      regex: identifier + /\s*:(?![:=])/$
+
+    * token: \variable
+      regex: identifier
+
+    * token: \keyword.operator
+      regex: /(?:\.{3}|\s+\?)/$
+
+    * token: \keyword.variable
+      regex: /(?:@+|::|\.\.)/$
+      next : \key
+
+    * token: \keyword.operator
+      regex: /\.\s*/$
+      next : \key
+
+    * token: \string
+      regex: /\\\S[^\s,;)}\]]*/$
+
+    * token: \string.doc
+      regex: \'''
+      next : \qdoc
+
+    * token: \string.doc
+      regex: \"""
+      next : \qqdoc
+
+    * token: \string
+      regex: \'
+      next : \qstring
+
+    * token: \string
+      regex: \"
+      next : \qqstring
+
+    * token: \string
+      regex: \`
+      next : \js
+
+    * token: \string
+      regex: '<\\['
+      next : \words
+
+    * token: \string.regex
+      regex: \//
+      next : \heregex
+
+    * token: \string.regex
+      regex: //
+        /(?: [^ [ / \n \\ ]*
+          (?: (?: \\.
+                | \[ [^\]\n\\]* (?:\\.[^\]\n\\]*)* \]
+              ) [^ [ / \n \\ ]*
+          )*
+        )/ [gimy$]{0,4}
+      //$
+      next : \key
+
+    * token: \constant.numeric
+      regex: '(?:0x[\\da-fA-F][\\da-fA-F_]*
+                |(?:[2-9]|[12]\\d|3[0-6])r[\\da-zA-Z][\\da-zA-Z_]*
+                |(?:\\d[\\d_]*(?:\\.\\d[\\d_]*)?|\\.\\d[\\d_]*)
+                 (?:e[+-]?\\d[\\d_]*)?[\\w$]*)'
+
+    * token: \lparen
+      regex: '[({[]'
+
+    * token: \rparen
+      regex: '[)}\\]]'
+      next : \key
+
+    * token: \keyword.operator
+      regex: \\\S+
+
+    * token: \text
+      regex: \\\s+
+
+  heregex:
+    * token: \string.regex
+      regex: '.*?//[gimy$?]{0,4}'
+      next : \start
+    * token: \string.regex
+      regex: '\\s*#{'
+    * token: \comment.regex
+      regex: '\\s+(?:#.*)?'
+    * token: \string.regex
+      regex: '\\S+'
+
+  key:
+    * token: \keyword.operator
+      regex: '[.?@!]+'
+    * token: \identifier
+      regex: identifier
+      next : \start
+    * token: \text
+      regex: '.'
+      next : \start
+
+  comment:
+    * token: \comment.doc
+      regex: '.*?\\*/'
+      next : \start
+    * token: \comment.doc
+      regex: '.+'
+
+  qdoc:
+    token: \string
+    regex: ".*?'''"
+    next : \key
+    stringfill
+
+  qqdoc:
+    token: \string
+    regex: '.*?"""'
+    next : \key
+    stringfill
+
+  qstring:
+    token: \string
+    regex: /[^\\']*(?:\\.[^\\']*)*'/$
+    next : \key
+    stringfill
+
+  qqstring:
+    token: \string
+    regex: /[^\\"]*(?:\\.[^\\"]*)*"/$
+    next : \key
+    stringfill
+
+  js:
+    token: \string
+    regex: /[^\\`]*(?:\\.[^\\`]*)*`/$
+    next : \key
+    stringfill
+
+  words:
+    token: \string
+    regex: '.*?\\]>'
+    next : \key
+    stringfill
+
+# for optimization, precompile the regexps
+for idx, r of Rules
+  if Array.isArray r
+    for rr, i in r
+      if rr.regex then Rules[idx][i].regex = new RegExp '^'+rr.regex
+  else if r.regex then Rules[idx].regex = new RegExp '^'+r.regex
+
+CodeMirror.defineMIME 'text/x-livescript', 'livescript'
diff --git a/third-party/codemirror-3.15/mode/lua/index.html b/third-party/codemirror-3.15/mode/lua/index.html
new file mode 100644 (file)
index 0000000..a0a42d9
--- /dev/null
@@ -0,0 +1,74 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Lua mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../addon/edit/matchbrackets.js"></script>
+    <script src="../../lib/codemirror.js"></script>
+    <script src="lua.js"></script>
+    <link rel="stylesheet" href="../../theme/neat.css">
+    <style>.CodeMirror {border: 1px solid black;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Lua mode</h1>
+    <form><textarea id="code" name="code">
+--[[
+example useless code to show lua syntax highlighting
+this is multiline comment
+]]
+
+function blahblahblah(x)
+
+  local table = {
+    "asd" = 123,
+    "x" = 0.34,  
+  }
+  if x ~= 3 then
+    print( x )
+  elseif x == "string"
+    my_custom_function( 0x34 )
+  else
+    unknown_function( "some string" )
+  end
+
+  --single line comment
+  
+end
+
+function blablabla3()
+
+  for k,v in ipairs( table ) do
+    --abcde..
+    y=[=[
+  x=[[
+      x is a multi line string
+   ]]
+  but its definition is iside a highest level string!
+  ]=]
+    print(" \"\" ")
+
+    s = math.sin( x )
+  end
+
+end
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        tabMode: "indent",
+        matchBrackets: true,
+        theme: "neat"
+      });
+    </script>
+
+    <p>Loosely based on Franciszek
+    Wawrzak's <a href="http://codemirror.net/1/contrib/lua">CodeMirror
+    1 mode</a>. One configuration parameter is
+    supported, <code>specials</code>, to which you can provide an
+    array of strings to have those identifiers highlighted with
+    the <code>lua-special</code> style.</p>
+    <p><strong>MIME types defined:</strong> <code>text/x-lua</code>.</p>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/lua/lua.js b/third-party/codemirror-3.15/mode/lua/lua.js
new file mode 100644 (file)
index 0000000..b8deaa2
--- /dev/null
@@ -0,0 +1,144 @@
+// LUA mode. Ported to CodeMirror 2 from Franciszek Wawrzak's
+// CodeMirror 1 mode.
+// highlights keywords, strings, comments (no leveling supported! ("[==[")), tokens, basic indenting
+
+CodeMirror.defineMode("lua", function(config, parserConfig) {
+  var indentUnit = config.indentUnit;
+
+  function prefixRE(words) {
+    return new RegExp("^(?:" + words.join("|") + ")", "i");
+  }
+  function wordRE(words) {
+    return new RegExp("^(?:" + words.join("|") + ")$", "i");
+  }
+  var specials = wordRE(parserConfig.specials || []);
+
+  // long list of standard functions from lua manual
+  var builtins = wordRE([
+    "_G","_VERSION","assert","collectgarbage","dofile","error","getfenv","getmetatable","ipairs","load",
+    "loadfile","loadstring","module","next","pairs","pcall","print","rawequal","rawget","rawset","require",
+    "select","setfenv","setmetatable","tonumber","tostring","type","unpack","xpcall",
+
+    "coroutine.create","coroutine.resume","coroutine.running","coroutine.status","coroutine.wrap","coroutine.yield",
+
+    "debug.debug","debug.getfenv","debug.gethook","debug.getinfo","debug.getlocal","debug.getmetatable",
+    "debug.getregistry","debug.getupvalue","debug.setfenv","debug.sethook","debug.setlocal","debug.setmetatable",
+    "debug.setupvalue","debug.traceback",
+
+    "close","flush","lines","read","seek","setvbuf","write",
+
+    "io.close","io.flush","io.input","io.lines","io.open","io.output","io.popen","io.read","io.stderr","io.stdin",
+    "io.stdout","io.tmpfile","io.type","io.write",
+
+    "math.abs","math.acos","math.asin","math.atan","math.atan2","math.ceil","math.cos","math.cosh","math.deg",
+    "math.exp","math.floor","math.fmod","math.frexp","math.huge","math.ldexp","math.log","math.log10","math.max",
+    "math.min","math.modf","math.pi","math.pow","math.rad","math.random","math.randomseed","math.sin","math.sinh",
+    "math.sqrt","math.tan","math.tanh",
+
+    "os.clock","os.date","os.difftime","os.execute","os.exit","os.getenv","os.remove","os.rename","os.setlocale",
+    "os.time","os.tmpname",
+
+    "package.cpath","package.loaded","package.loaders","package.loadlib","package.path","package.preload",
+    "package.seeall",
+
+    "string.byte","string.char","string.dump","string.find","string.format","string.gmatch","string.gsub",
+    "string.len","string.lower","string.match","string.rep","string.reverse","string.sub","string.upper",
+
+    "table.concat","table.insert","table.maxn","table.remove","table.sort"
+  ]);
+  var keywords = wordRE(["and","break","elseif","false","nil","not","or","return",
+                         "true","function", "end", "if", "then", "else", "do",
+                         "while", "repeat", "until", "for", "in", "local" ]);
+
+  var indentTokens = wordRE(["function", "if","repeat","do", "\\(", "{"]);
+  var dedentTokens = wordRE(["end", "until", "\\)", "}"]);
+  var dedentPartial = prefixRE(["end", "until", "\\)", "}", "else", "elseif"]);
+
+  function readBracket(stream) {
+    var level = 0;
+    while (stream.eat("=")) ++level;
+    stream.eat("[");
+    return level;
+  }
+
+  function normal(stream, state) {
+    var ch = stream.next();
+    if (ch == "-" && stream.eat("-")) {
+      if (stream.eat("[") && stream.eat("["))
+        return (state.cur = bracketed(readBracket(stream), "comment"))(stream, state);
+      stream.skipToEnd();
+      return "comment";
+    }
+    if (ch == "\"" || ch == "'")
+      return (state.cur = string(ch))(stream, state);
+    if (ch == "[" && /[\[=]/.test(stream.peek()))
+      return (state.cur = bracketed(readBracket(stream), "string"))(stream, state);
+    if (/\d/.test(ch)) {
+      stream.eatWhile(/[\w.%]/);
+      return "number";
+    }
+    if (/[\w_]/.test(ch)) {
+      stream.eatWhile(/[\w\\\-_.]/);
+      return "variable";
+    }
+    return null;
+  }
+
+  function bracketed(level, style) {
+    return function(stream, state) {
+      var curlev = null, ch;
+      while ((ch = stream.next()) != null) {
+        if (curlev == null) {if (ch == "]") curlev = 0;}
+        else if (ch == "=") ++curlev;
+        else if (ch == "]" && curlev == level) { state.cur = normal; break; }
+        else curlev = null;
+      }
+      return style;
+    };
+  }
+
+  function string(quote) {
+    return function(stream, state) {
+      var escaped = false, ch;
+      while ((ch = stream.next()) != null) {
+        if (ch == quote && !escaped) break;
+        escaped = !escaped && ch == "\\";
+      }
+      if (!escaped) state.cur = normal;
+      return "string";
+    };
+  }
+
+  return {
+    startState: function(basecol) {
+      return {basecol: basecol || 0, indentDepth: 0, cur: normal};
+    },
+
+    token: function(stream, state) {
+      if (stream.eatSpace()) return null;
+      var style = state.cur(stream, state);
+      var word = stream.current();
+      if (style == "variable") {
+        if (keywords.test(word)) style = "keyword";
+        else if (builtins.test(word)) style = "builtin";
+        else if (specials.test(word)) style = "variable-2";
+      }
+      if ((style != "comment") && (style != "string")){
+        if (indentTokens.test(word)) ++state.indentDepth;
+        else if (dedentTokens.test(word)) --state.indentDepth;
+      }
+      return style;
+    },
+
+    indent: function(state, textAfter) {
+      var closing = dedentPartial.test(textAfter);
+      return state.basecol + indentUnit * (state.indentDepth - (closing ? 1 : 0));
+    },
+
+    lineComment: "--",
+    blockCommentStart: "--[[",
+    blockCommentEnd: "]]"
+  };
+});
+
+CodeMirror.defineMIME("text/x-lua", "lua");
diff --git a/third-party/codemirror-3.15/mode/markdown/index.html b/third-party/codemirror-3.15/mode/markdown/index.html
new file mode 100644 (file)
index 0000000..bb785b1
--- /dev/null
@@ -0,0 +1,349 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Markdown mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../../addon/edit/continuelist.js"></script>
+    <script src="../xml/xml.js"></script>
+    <script src="markdown.js"></script>
+    <style type="text/css">
+      .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}
+      .cm-s-default .cm-trailing-space-a:before,
+      .cm-s-default .cm-trailing-space-b:before {position: absolute; content: "\00B7"; color: #777;}
+      .cm-s-default .cm-trailing-space-new-line:before {position: absolute; content: "\21B5"; color: #777;}
+    </style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Markdown mode</h1>
+
+<!-- source: http://daringfireball.net/projects/markdown/basics.text -->
+<form><textarea id="code" name="code">
+Markdown: Basics
+================
+
+&lt;ul id="ProjectSubmenu"&gt;
+    &lt;li&gt;&lt;a href="/projects/markdown/" title="Markdown Project Page"&gt;Main&lt;/a&gt;&lt;/li&gt;
+    &lt;li&gt;&lt;a class="selected" title="Markdown Basics"&gt;Basics&lt;/a&gt;&lt;/li&gt;
+    &lt;li&gt;&lt;a href="/projects/markdown/syntax" title="Markdown Syntax Documentation"&gt;Syntax&lt;/a&gt;&lt;/li&gt;
+    &lt;li&gt;&lt;a href="/projects/markdown/license" title="Pricing and License Information"&gt;License&lt;/a&gt;&lt;/li&gt;
+    &lt;li&gt;&lt;a href="/projects/markdown/dingus" title="Online Markdown Web Form"&gt;Dingus&lt;/a&gt;&lt;/li&gt;
+&lt;/ul&gt;
+
+
+Getting the Gist of Markdown's Formatting Syntax
+------------------------------------------------
+
+This page offers a brief overview of what it's like to use Markdown.
+The [syntax page] [s] provides complete, detailed documentation for
+every feature, but Markdown should be very easy to pick up simply by
+looking at a few examples of it in action. The examples on this page
+are written in a before/after style, showing example syntax and the
+HTML output produced by Markdown.
+
+It's also helpful to simply try Markdown out; the [Dingus] [d] is a
+web application that allows you type your own Markdown-formatted text
+and translate it to XHTML.
+
+**Note:** This document is itself written using Markdown; you
+can [see the source for it by adding '.text' to the URL] [src].
+
+  [s]: /projects/markdown/syntax  "Markdown Syntax"
+  [d]: /projects/markdown/dingus  "Markdown Dingus"
+  [src]: /projects/markdown/basics.text
+
+
+## Paragraphs, Headers, Blockquotes ##
+
+A paragraph is simply one or more consecutive lines of text, separated
+by one or more blank lines. (A blank line is any line that looks like
+a blank line -- a line containing nothing but spaces or tabs is
+considered blank.) Normal paragraphs should not be indented with
+spaces or tabs.
+
+Markdown offers two styles of headers: *Setext* and *atx*.
+Setext-style headers for `&lt;h1&gt;` and `&lt;h2&gt;` are created by
+"underlining" with equal signs (`=`) and hyphens (`-`), respectively.
+To create an atx-style header, you put 1-6 hash marks (`#`) at the
+beginning of the line -- the number of hashes equals the resulting
+HTML header level.
+
+Blockquotes are indicated using email-style '`&gt;`' angle brackets.
+
+Markdown:
+
+    A First Level Header
+    ====================
+    
+    A Second Level Header
+    ---------------------
+
+    Now is the time for all good men to come to
+    the aid of their country. This is just a
+    regular paragraph.
+
+    The quick brown fox jumped over the lazy
+    dog's back.
+    
+    ### Header 3
+
+    &gt; This is a blockquote.
+    &gt; 
+    &gt; This is the second paragraph in the blockquote.
+    &gt;
+    &gt; ## This is an H2 in a blockquote
+
+
+Output:
+
+    &lt;h1&gt;A First Level Header&lt;/h1&gt;
+    
+    &lt;h2&gt;A Second Level Header&lt;/h2&gt;
+    
+    &lt;p&gt;Now is the time for all good men to come to
+    the aid of their country. This is just a
+    regular paragraph.&lt;/p&gt;
+    
+    &lt;p&gt;The quick brown fox jumped over the lazy
+    dog's back.&lt;/p&gt;
+    
+    &lt;h3&gt;Header 3&lt;/h3&gt;
+    
+    &lt;blockquote&gt;
+        &lt;p&gt;This is a blockquote.&lt;/p&gt;
+        
+        &lt;p&gt;This is the second paragraph in the blockquote.&lt;/p&gt;
+        
+        &lt;h2&gt;This is an H2 in a blockquote&lt;/h2&gt;
+    &lt;/blockquote&gt;
+
+
+
+### Phrase Emphasis ###
+
+Markdown uses asterisks and underscores to indicate spans of emphasis.
+
+Markdown:
+
+    Some of these words *are emphasized*.
+    Some of these words _are emphasized also_.
+    
+    Use two asterisks for **strong emphasis**.
+    Or, if you prefer, __use two underscores instead__.
+
+Output:
+
+    &lt;p&gt;Some of these words &lt;em&gt;are emphasized&lt;/em&gt;.
+    Some of these words &lt;em&gt;are emphasized also&lt;/em&gt;.&lt;/p&gt;
+    
+    &lt;p&gt;Use two asterisks for &lt;strong&gt;strong emphasis&lt;/strong&gt;.
+    Or, if you prefer, &lt;strong&gt;use two underscores instead&lt;/strong&gt;.&lt;/p&gt;
+   
+
+
+## Lists ##
+
+Unordered (bulleted) lists use asterisks, pluses, and hyphens (`*`,
+`+`, and `-`) as list markers. These three markers are
+interchangable; this:
+
+    *   Candy.
+    *   Gum.
+    *   Booze.
+
+this:
+
+    +   Candy.
+    +   Gum.
+    +   Booze.
+
+and this:
+
+    -   Candy.
+    -   Gum.
+    -   Booze.
+
+all produce the same output:
+
+    &lt;ul&gt;
+    &lt;li&gt;Candy.&lt;/li&gt;
+    &lt;li&gt;Gum.&lt;/li&gt;
+    &lt;li&gt;Booze.&lt;/li&gt;
+    &lt;/ul&gt;
+
+Ordered (numbered) lists use regular numbers, followed by periods, as
+list markers:
+
+    1.  Red
+    2.  Green
+    3.  Blue
+
+Output:
+
+    &lt;ol&gt;
+    &lt;li&gt;Red&lt;/li&gt;
+    &lt;li&gt;Green&lt;/li&gt;
+    &lt;li&gt;Blue&lt;/li&gt;
+    &lt;/ol&gt;
+
+If you put blank lines between items, you'll get `&lt;p&gt;` tags for the
+list item text. You can create multi-paragraph list items by indenting
+the paragraphs by 4 spaces or 1 tab:
+
+    *   A list item.
+    
+        With multiple paragraphs.
+
+    *   Another item in the list.
+
+Output:
+
+    &lt;ul&gt;
+    &lt;li&gt;&lt;p&gt;A list item.&lt;/p&gt;
+    &lt;p&gt;With multiple paragraphs.&lt;/p&gt;&lt;/li&gt;
+    &lt;li&gt;&lt;p&gt;Another item in the list.&lt;/p&gt;&lt;/li&gt;
+    &lt;/ul&gt;
+    
+
+
+### Links ###
+
+Markdown supports two styles for creating links: *inline* and
+*reference*. With both styles, you use square brackets to delimit the
+text you want to turn into a link.
+
+Inline-style links use parentheses immediately after the link text.
+For example:
+
+    This is an [example link](http://example.com/).
+
+Output:
+
+    &lt;p&gt;This is an &lt;a href="http://example.com/"&gt;
+    example link&lt;/a&gt;.&lt;/p&gt;
+
+Optionally, you may include a title attribute in the parentheses:
+
+    This is an [example link](http://example.com/ "With a Title").
+
+Output:
+
+    &lt;p&gt;This is an &lt;a href="http://example.com/" title="With a Title"&gt;
+    example link&lt;/a&gt;.&lt;/p&gt;
+
+Reference-style links allow you to refer to your links by names, which
+you define elsewhere in your document:
+
+    I get 10 times more traffic from [Google][1] than from
+    [Yahoo][2] or [MSN][3].
+
+    [1]: http://google.com/        "Google"
+    [2]: http://search.yahoo.com/  "Yahoo Search"
+    [3]: http://search.msn.com/    "MSN Search"
+
+Output:
+
+    &lt;p&gt;I get 10 times more traffic from &lt;a href="http://google.com/"
+    title="Google"&gt;Google&lt;/a&gt; than from &lt;a href="http://search.yahoo.com/"
+    title="Yahoo Search"&gt;Yahoo&lt;/a&gt; or &lt;a href="http://search.msn.com/"
+    title="MSN Search"&gt;MSN&lt;/a&gt;.&lt;/p&gt;
+
+The title attribute is optional. Link names may contain letters,
+numbers and spaces, but are *not* case sensitive:
+
+    I start my morning with a cup of coffee and
+    [The New York Times][NY Times].
+
+    [ny times]: http://www.nytimes.com/
+
+Output:
+
+    &lt;p&gt;I start my morning with a cup of coffee and
+    &lt;a href="http://www.nytimes.com/"&gt;The New York Times&lt;/a&gt;.&lt;/p&gt;
+
+
+### Images ###
+
+Image syntax is very much like link syntax.
+
+Inline (titles are optional):
+
+    ![alt text](/path/to/img.jpg "Title")
+
+Reference-style:
+
+    ![alt text][id]
+
+    [id]: /path/to/img.jpg "Title"
+
+Both of the above examples produce the same output:
+
+    &lt;img src="/path/to/img.jpg" alt="alt text" title="Title" /&gt;
+
+
+
+### Code ###
+
+In a regular paragraph, you can create code span by wrapping text in
+backtick quotes. Any ampersands (`&amp;`) and angle brackets (`&lt;` or
+`&gt;`) will automatically be translated into HTML entities. This makes
+it easy to use Markdown to write about HTML example code:
+
+    I strongly recommend against using any `&lt;blink&gt;` tags.
+
+    I wish SmartyPants used named entities like `&amp;mdash;`
+    instead of decimal-encoded entites like `&amp;#8212;`.
+
+Output:
+
+    &lt;p&gt;I strongly recommend against using any
+    &lt;code&gt;&amp;lt;blink&amp;gt;&lt;/code&gt; tags.&lt;/p&gt;
+    
+    &lt;p&gt;I wish SmartyPants used named entities like
+    &lt;code&gt;&amp;amp;mdash;&lt;/code&gt; instead of decimal-encoded
+    entites like &lt;code&gt;&amp;amp;#8212;&lt;/code&gt;.&lt;/p&gt;
+
+
+To specify an entire block of pre-formatted code, indent every line of
+the block by 4 spaces or 1 tab. Just like with code spans, `&amp;`, `&lt;`,
+and `&gt;` characters will be escaped automatically.
+
+Markdown:
+
+    If you want your page to validate under XHTML 1.0 Strict,
+    you've got to put paragraph tags in your blockquotes:
+
+        &lt;blockquote&gt;
+            &lt;p&gt;For example.&lt;/p&gt;
+        &lt;/blockquote&gt;
+
+Output:
+
+    &lt;p&gt;If you want your page to validate under XHTML 1.0 Strict,
+    you've got to put paragraph tags in your blockquotes:&lt;/p&gt;
+    
+    &lt;pre&gt;&lt;code&gt;&amp;lt;blockquote&amp;gt;
+        &amp;lt;p&amp;gt;For example.&amp;lt;/p&amp;gt;
+    &amp;lt;/blockquote&amp;gt;
+    &lt;/code&gt;&lt;/pre&gt;
+</textarea></form>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        mode: 'markdown',
+        lineNumbers: true,
+        theme: "default",
+        extraKeys: {"Enter": "newlineAndIndentContinueMarkdownList"}
+      });
+    </script>
+
+    <p>Optionally depends on the XML mode for properly highlighted inline XML blocks.</p>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-markdown</code>.</p>
+
+    <p><strong>Parsing/Highlighting Tests:</strong> <a href="../../test/index.html#markdown_*">normal</a>,  <a href="../../test/index.html#verbose,markdown_*">verbose</a>.</p>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/markdown/markdown.js b/third-party/codemirror-3.15/mode/markdown/markdown.js
new file mode 100644 (file)
index 0000000..bf1750d
--- /dev/null
@@ -0,0 +1,551 @@
+CodeMirror.defineMode("markdown", function(cmCfg, modeCfg) {
+
+  var htmlFound = CodeMirror.modes.hasOwnProperty("xml");
+  var htmlMode = CodeMirror.getMode(cmCfg, htmlFound ? {name: "xml", htmlMode: true} : "text/plain");
+  var aliases = {
+    html: "htmlmixed",
+    js: "javascript",
+    json: "application/json",
+    c: "text/x-csrc",
+    "c++": "text/x-c++src",
+    java: "text/x-java",
+    csharp: "text/x-csharp",
+    "c#": "text/x-csharp",
+    scala: "text/x-scala"
+  };
+
+  var getMode = (function () {
+    var i, modes = {}, mimes = {}, mime;
+
+    var list = [];
+    for (var m in CodeMirror.modes)
+      if (CodeMirror.modes.propertyIsEnumerable(m)) list.push(m);
+    for (i = 0; i < list.length; i++) {
+      modes[list[i]] = list[i];
+    }
+    var mimesList = [];
+    for (var m in CodeMirror.mimeModes)
+      if (CodeMirror.mimeModes.propertyIsEnumerable(m))
+        mimesList.push({mime: m, mode: CodeMirror.mimeModes[m]});
+    for (i = 0; i < mimesList.length; i++) {
+      mime = mimesList[i].mime;
+      mimes[mime] = mimesList[i].mime;
+    }
+
+    for (var a in aliases) {
+      if (aliases[a] in modes || aliases[a] in mimes)
+        modes[a] = aliases[a];
+    }
+
+    return function (lang) {
+      return modes[lang] ? CodeMirror.getMode(cmCfg, modes[lang]) : null;
+    };
+  }());
+
+  // Should underscores in words open/close em/strong?
+  if (modeCfg.underscoresBreakWords === undefined)
+    modeCfg.underscoresBreakWords = true;
+
+  // Turn on fenced code blocks? ("```" to start/end)
+  if (modeCfg.fencedCodeBlocks === undefined) modeCfg.fencedCodeBlocks = false;
+
+  // Turn on task lists? ("- [ ] " and "- [x] ")
+  if (modeCfg.taskLists === undefined) modeCfg.taskLists = false;
+
+  var codeDepth = 0;
+
+  var header   = 'header'
+  ,   code     = 'comment'
+  ,   quote1   = 'atom'
+  ,   quote2   = 'number'
+  ,   list1    = 'variable-2'
+  ,   list2    = 'variable-3'
+  ,   list3    = 'keyword'
+  ,   hr       = 'hr'
+  ,   image    = 'tag'
+  ,   linkinline = 'link'
+  ,   linkemail = 'link'
+  ,   linktext = 'link'
+  ,   linkhref = 'string'
+  ,   em       = 'em'
+  ,   strong   = 'strong';
+
+  var hrRE = /^([*\-=_])(?:\s*\1){2,}\s*$/
+  ,   ulRE = /^[*\-+]\s+/
+  ,   olRE = /^[0-9]+\.\s+/
+  ,   taskListRE = /^\[(x| )\](?=\s)/ // Must follow ulRE or olRE
+  ,   headerRE = /^(?:\={1,}|-{1,})$/
+  ,   textRE = /^[^!\[\]*_\\<>` "'(]+/;
+
+  function switchInline(stream, state, f) {
+    state.f = state.inline = f;
+    return f(stream, state);
+  }
+
+  function switchBlock(stream, state, f) {
+    state.f = state.block = f;
+    return f(stream, state);
+  }
+
+
+  // Blocks
+
+  function blankLine(state) {
+    // Reset linkTitle state
+    state.linkTitle = false;
+    // Reset EM state
+    state.em = false;
+    // Reset STRONG state
+    state.strong = false;
+    // Reset state.quote
+    state.quote = 0;
+    if (!htmlFound && state.f == htmlBlock) {
+      state.f = inlineNormal;
+      state.block = blockNormal;
+    }
+    // Reset state.trailingSpace
+    state.trailingSpace = 0;
+    state.trailingSpaceNewLine = false;
+    // Mark this line as blank
+    state.thisLineHasContent = false;
+    return null;
+  }
+
+  function blockNormal(stream, state) {
+
+    var prevLineIsList = (state.list !== false);
+    if (state.list !== false && state.indentationDiff >= 0) { // Continued list
+      if (state.indentationDiff < 4) { // Only adjust indentation if *not* a code block
+        state.indentation -= state.indentationDiff;
+      }
+      state.list = null;
+    } else if (state.list !== false && state.indentation > 0) {
+      state.list = null;
+      state.listDepth = Math.floor(state.indentation / 4);
+    } else if (state.list !== false) { // No longer a list
+      state.list = false;
+      state.listDepth = 0;
+    }
+
+    if (state.indentationDiff >= 4) {
+      state.indentation -= 4;
+      stream.skipToEnd();
+      return code;
+    } else if (stream.eatSpace()) {
+      return null;
+    } else if (stream.peek() === '#' || (state.prevLineHasContent && stream.match(headerRE)) ) {
+      state.header = true;
+    } else if (stream.eat('>')) {
+      state.indentation++;
+      state.quote = 1;
+      stream.eatSpace();
+      while (stream.eat('>')) {
+        stream.eatSpace();
+        state.quote++;
+      }
+    } else if (stream.peek() === '[') {
+      return switchInline(stream, state, footnoteLink);
+    } else if (stream.match(hrRE, true)) {
+      return hr;
+    } else if ((!state.prevLineHasContent || prevLineIsList) && (stream.match(ulRE, true) || stream.match(olRE, true))) {
+      state.indentation += 4;
+      state.list = true;
+      state.listDepth++;
+      if (modeCfg.taskLists && stream.match(taskListRE, false)) {
+        state.taskList = true;
+      }
+    } else if (modeCfg.fencedCodeBlocks && stream.match(/^```([\w+#]*)/, true)) {
+      // try switching mode
+      state.localMode = getMode(RegExp.$1);
+      if (state.localMode) state.localState = state.localMode.startState();
+      switchBlock(stream, state, local);
+      return code;
+    }
+
+    return switchInline(stream, state, state.inline);
+  }
+
+  function htmlBlock(stream, state) {
+    var style = htmlMode.token(stream, state.htmlState);
+    if (htmlFound && style === 'tag' && state.htmlState.type !== 'openTag' && !state.htmlState.context) {
+      state.f = inlineNormal;
+      state.block = blockNormal;
+    }
+    if (state.md_inside && stream.current().indexOf(">")!=-1) {
+      state.f = inlineNormal;
+      state.block = blockNormal;
+      state.htmlState.context = undefined;
+    }
+    return style;
+  }
+
+  function local(stream, state) {
+    if (stream.sol() && stream.match(/^```/, true)) {
+      state.localMode = state.localState = null;
+      state.f = inlineNormal;
+      state.block = blockNormal;
+      return code;
+    } else if (state.localMode) {
+      return state.localMode.token(stream, state.localState);
+    } else {
+      stream.skipToEnd();
+      return code;
+    }
+  }
+
+  // Inline
+  function getType(state) {
+    var styles = [];
+
+    if (state.taskOpen) { return "meta"; }
+    if (state.taskClosed) { return "property"; }
+
+    if (state.strong) { styles.push(strong); }
+    if (state.em) { styles.push(em); }
+
+    if (state.linkText) { styles.push(linktext); }
+
+    if (state.code) { styles.push(code); }
+
+    if (state.header) { styles.push(header); }
+    if (state.quote) { styles.push(state.quote % 2 ? quote1 : quote2); }
+    if (state.list !== false) {
+      var listMod = (state.listDepth - 1) % 3;
+      if (!listMod) {
+        styles.push(list1);
+      } else if (listMod === 1) {
+        styles.push(list2);
+      } else {
+        styles.push(list3);
+      }
+    }
+
+    if (state.trailingSpaceNewLine) {
+      styles.push("trailing-space-new-line");
+    } else if (state.trailingSpace) {
+      styles.push("trailing-space-" + (state.trailingSpace % 2 ? "a" : "b"));
+    }
+
+    return styles.length ? styles.join(' ') : null;
+  }
+
+  function handleText(stream, state) {
+    if (stream.match(textRE, true)) {
+      return getType(state);
+    }
+    return undefined;
+  }
+
+  function inlineNormal(stream, state) {
+    var style = state.text(stream, state);
+    if (typeof style !== 'undefined')
+      return style;
+
+    if (state.list) { // List marker (*, +, -, 1., etc)
+      state.list = null;
+      return getType(state);
+    }
+
+    if (state.taskList) {
+      var taskOpen = stream.match(taskListRE, true)[1] !== "x";
+      if (taskOpen) state.taskOpen = true;
+      else state.taskClosed = true;
+      state.taskList = false;
+      return getType(state);
+    }
+
+    state.taskOpen = false;
+    state.taskClosed = false;
+
+    var ch = stream.next();
+
+    if (ch === '\\') {
+      stream.next();
+      return getType(state);
+    }
+
+    // Matches link titles present on next line
+    if (state.linkTitle) {
+      state.linkTitle = false;
+      var matchCh = ch;
+      if (ch === '(') {
+        matchCh = ')';
+      }
+      matchCh = (matchCh+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
+      var regex = '^\\s*(?:[^' + matchCh + '\\\\]+|\\\\\\\\|\\\\.)' + matchCh;
+      if (stream.match(new RegExp(regex), true)) {
+        return linkhref;
+      }
+    }
+
+    // If this block is changed, it may need to be updated in GFM mode
+    if (ch === '`') {
+      var t = getType(state);
+      var before = stream.pos;
+      stream.eatWhile('`');
+      var difference = 1 + stream.pos - before;
+      if (!state.code) {
+        codeDepth = difference;
+        state.code = true;
+        return getType(state);
+      } else {
+        if (difference === codeDepth) { // Must be exact
+          state.code = false;
+          return t;
+        }
+        return getType(state);
+      }
+    } else if (state.code) {
+      return getType(state);
+    }
+
+    if (ch === '!' && stream.match(/\[[^\]]*\] ?(?:\(|\[)/, false)) {
+      stream.match(/\[[^\]]*\]/);
+      state.inline = state.f = linkHref;
+      return image;
+    }
+
+    if (ch === '[' && stream.match(/.*\](\(| ?\[)/, false)) {
+      state.linkText = true;
+      return getType(state);
+    }
+
+    if (ch === ']' && state.linkText) {
+      var type = getType(state);
+      state.linkText = false;
+      state.inline = state.f = linkHref;
+      return type;
+    }
+
+    if (ch === '<' && stream.match(/^(https?|ftps?):\/\/(?:[^\\>]|\\.)+>/, false)) {
+      return switchInline(stream, state, inlineElement(linkinline, '>'));
+    }
+
+    if (ch === '<' && stream.match(/^[^> \\]+@(?:[^\\>]|\\.)+>/, false)) {
+      return switchInline(stream, state, inlineElement(linkemail, '>'));
+    }
+
+    if (ch === '<' && stream.match(/^\w/, false)) {
+      if (stream.string.indexOf(">")!=-1) {
+        var atts = stream.string.substring(1,stream.string.indexOf(">"));
+        if (/markdown\s*=\s*('|"){0,1}1('|"){0,1}/.test(atts)) {
+          state.md_inside = true;
+        }
+      }
+      stream.backUp(1);
+      return switchBlock(stream, state, htmlBlock);
+    }
+
+    if (ch === '<' && stream.match(/^\/\w*?>/)) {
+      state.md_inside = false;
+      return "tag";
+    }
+
+    var ignoreUnderscore = false;
+    if (!modeCfg.underscoresBreakWords) {
+      if (ch === '_' && stream.peek() !== '_' && stream.match(/(\w)/, false)) {
+        var prevPos = stream.pos - 2;
+        if (prevPos >= 0) {
+          var prevCh = stream.string.charAt(prevPos);
+          if (prevCh !== '_' && prevCh.match(/(\w)/, false)) {
+            ignoreUnderscore = true;
+          }
+        }
+      }
+    }
+    var t = getType(state);
+    if (ch === '*' || (ch === '_' && !ignoreUnderscore)) {
+      if (state.strong === ch && stream.eat(ch)) { // Remove STRONG
+        state.strong = false;
+        return t;
+      } else if (!state.strong && stream.eat(ch)) { // Add STRONG
+        state.strong = ch;
+        return getType(state);
+      } else if (state.em === ch) { // Remove EM
+        state.em = false;
+        return t;
+      } else if (!state.em) { // Add EM
+        state.em = ch;
+        return getType(state);
+      }
+    } else if (ch === ' ') {
+      if (stream.eat('*') || stream.eat('_')) { // Probably surrounded by spaces
+        if (stream.peek() === ' ') { // Surrounded by spaces, ignore
+          return getType(state);
+        } else { // Not surrounded by spaces, back up pointer
+          stream.backUp(1);
+        }
+      }
+    }
+
+    if (ch === ' ') {
+      if (stream.match(/ +$/, false)) {
+        state.trailingSpace++;
+      } else if (state.trailingSpace) {
+        state.trailingSpaceNewLine = true;
+      }
+    }
+
+    return getType(state);
+  }
+
+  function linkHref(stream, state) {
+    // Check if space, and return NULL if so (to avoid marking the space)
+    if(stream.eatSpace()){
+      return null;
+    }
+    var ch = stream.next();
+    if (ch === '(' || ch === '[') {
+      return switchInline(stream, state, inlineElement(linkhref, ch === '(' ? ')' : ']'));
+    }
+    return 'error';
+  }
+
+  function footnoteLink(stream, state) {
+    if (stream.match(/^[^\]]*\]:/, true)) {
+      state.f = footnoteUrl;
+      return linktext;
+    }
+    return switchInline(stream, state, inlineNormal);
+  }
+
+  function footnoteUrl(stream, state) {
+    // Check if space, and return NULL if so (to avoid marking the space)
+    if(stream.eatSpace()){
+      return null;
+    }
+    // Match URL
+    stream.match(/^[^\s]+/, true);
+    // Check for link title
+    if (stream.peek() === undefined) { // End of line, set flag to check next line
+      state.linkTitle = true;
+    } else { // More content on line, check if link title
+      stream.match(/^(?:\s+(?:"(?:[^"\\]|\\\\|\\.)+"|'(?:[^'\\]|\\\\|\\.)+'|\((?:[^)\\]|\\\\|\\.)+\)))?/, true);
+    }
+    state.f = state.inline = inlineNormal;
+    return linkhref;
+  }
+
+  var savedInlineRE = [];
+  function inlineRE(endChar) {
+    if (!savedInlineRE[endChar]) {
+      // Escape endChar for RegExp (taken from http://stackoverflow.com/a/494122/526741)
+      endChar = (endChar+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
+      // Match any non-endChar, escaped character, as well as the closing
+      // endChar.
+      savedInlineRE[endChar] = new RegExp('^(?:[^\\\\]|\\\\.)*?(' + endChar + ')');
+    }
+    return savedInlineRE[endChar];
+  }
+
+  function inlineElement(type, endChar, next) {
+    next = next || inlineNormal;
+    return function(stream, state) {
+      stream.match(inlineRE(endChar));
+      state.inline = state.f = next;
+      return type;
+    };
+  }
+
+  return {
+    startState: function() {
+      return {
+        f: blockNormal,
+
+        prevLineHasContent: false,
+        thisLineHasContent: false,
+
+        block: blockNormal,
+        htmlState: CodeMirror.startState(htmlMode),
+        indentation: 0,
+
+        inline: inlineNormal,
+        text: handleText,
+
+        linkText: false,
+        linkTitle: false,
+        em: false,
+        strong: false,
+        header: false,
+        taskList: false,
+        list: false,
+        listDepth: 0,
+        quote: 0,
+        trailingSpace: 0,
+        trailingSpaceNewLine: false
+      };
+    },
+
+    copyState: function(s) {
+      return {
+        f: s.f,
+
+        prevLineHasContent: s.prevLineHasContent,
+        thisLineHasContent: s.thisLineHasContent,
+
+        block: s.block,
+        htmlState: CodeMirror.copyState(htmlMode, s.htmlState),
+        indentation: s.indentation,
+
+        localMode: s.localMode,
+        localState: s.localMode ? CodeMirror.copyState(s.localMode, s.localState) : null,
+
+        inline: s.inline,
+        text: s.text,
+        linkTitle: s.linkTitle,
+        em: s.em,
+        strong: s.strong,
+        header: s.header,
+        taskList: s.taskList,
+        list: s.list,
+        listDepth: s.listDepth,
+        quote: s.quote,
+        trailingSpace: s.trailingSpace,
+        trailingSpaceNewLine: s.trailingSpaceNewLine,
+        md_inside: s.md_inside
+      };
+    },
+
+    token: function(stream, state) {
+      if (stream.sol()) {
+        if (stream.match(/^\s*$/, true)) {
+          state.prevLineHasContent = false;
+          return blankLine(state);
+        } else {
+          state.prevLineHasContent = state.thisLineHasContent;
+          state.thisLineHasContent = true;
+        }
+
+        // Reset state.header
+        state.header = false;
+
+        // Reset state.taskList
+        state.taskList = false;
+
+        // Reset state.code
+        state.code = false;
+
+        // Reset state.trailingSpace
+        state.trailingSpace = 0;
+        state.trailingSpaceNewLine = false;
+
+        state.f = state.block;
+        var indentation = stream.match(/^\s*/, true)[0].replace(/\t/g, '    ').length;
+        var difference = Math.floor((indentation - state.indentation) / 4) * 4;
+        if (difference > 4) difference = 4;
+        var adjustedIndentation = state.indentation + difference;
+        state.indentationDiff = adjustedIndentation - state.indentation;
+        state.indentation = adjustedIndentation;
+        if (indentation > 0) return null;
+      }
+      return state.f(stream, state);
+    },
+
+    blankLine: blankLine,
+
+    getType: getType
+  };
+
+}, "xml");
+
+CodeMirror.defineMIME("text/x-markdown", "markdown");
diff --git a/third-party/codemirror-3.15/mode/markdown/test.js b/third-party/codemirror-3.15/mode/markdown/test.js
new file mode 100644 (file)
index 0000000..f167917
--- /dev/null
@@ -0,0 +1,656 @@
+(function() {
+  var mode = CodeMirror.getMode({tabSize: 4}, "markdown");
+  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }
+
+  MT("plainText",
+     "foo");
+
+  // Don't style single trailing space
+  MT("trailingSpace1",
+     "foo ");
+
+  // Two or more trailing spaces should be styled with line break character
+  MT("trailingSpace2",
+     "foo[trailing-space-a  ][trailing-space-new-line  ]");
+
+  MT("trailingSpace3",
+     "foo[trailing-space-a  ][trailing-space-b  ][trailing-space-new-line  ]");
+
+  MT("trailingSpace4",
+     "foo[trailing-space-a  ][trailing-space-b  ][trailing-space-a  ][trailing-space-new-line  ]");
+
+  // Code blocks using 4 spaces (regardless of CodeMirror.tabSize value)
+  MT("codeBlocksUsing4Spaces",
+     "    [comment foo]");
+
+  // Code blocks using 4 spaces with internal indentation
+  MT("codeBlocksUsing4SpacesIndentation",
+     "    [comment bar]",
+     "        [comment hello]",
+     "            [comment world]",
+     "    [comment foo]",
+     "bar");
+
+  // Code blocks using 4 spaces with internal indentation
+  MT("codeBlocksUsing4SpacesIndentation",
+     " foo",
+     "    [comment bar]",
+     "        [comment hello]",
+     "    [comment world]");
+
+  // Code blocks using 1 tab (regardless of CodeMirror.indentWithTabs value)
+  MT("codeBlocksUsing1Tab",
+     "\t[comment foo]");
+
+  // Inline code using backticks
+  MT("inlineCodeUsingBackticks",
+     "foo [comment `bar`]");
+
+  // Block code using single backtick (shouldn't work)
+  MT("blockCodeSingleBacktick",
+     "[comment `]",
+     "foo",
+     "[comment `]");
+
+  // Unclosed backticks
+  // Instead of simply marking as CODE, it would be nice to have an
+  // incomplete flag for CODE, that is styled slightly different.
+  MT("unclosedBackticks",
+     "foo [comment `bar]");
+
+  // Per documentation: "To include a literal backtick character within a
+  // code span, you can use multiple backticks as the opening and closing
+  // delimiters"
+  MT("doubleBackticks",
+     "[comment ``foo ` bar``]");
+
+  // Tests based on Dingus
+  // http://daringfireball.net/projects/markdown/dingus
+  //
+  // Multiple backticks within an inline code block
+  MT("consecutiveBackticks",
+     "[comment `foo```bar`]");
+
+  // Multiple backticks within an inline code block with a second code block
+  MT("consecutiveBackticks",
+     "[comment `foo```bar`] hello [comment `world`]");
+
+  // Unclosed with several different groups of backticks
+  MT("unclosedBackticks",
+     "[comment ``foo ``` bar` hello]");
+
+  // Closed with several different groups of backticks
+  MT("closedBackticks",
+     "[comment ``foo ``` bar` hello``] world");
+
+  // atx headers
+  // http://daringfireball.net/projects/markdown/syntax#header
+
+  MT("atxH1",
+     "[header # foo]");
+
+  MT("atxH2",
+     "[header ## foo]");
+
+  MT("atxH3",
+     "[header ### foo]");
+
+  MT("atxH4",
+     "[header #### foo]");
+
+  MT("atxH5",
+     "[header ##### foo]");
+
+  MT("atxH6",
+     "[header ###### foo]");
+
+  // H6 - 7x '#' should still be H6, per Dingus
+  // http://daringfireball.net/projects/markdown/dingus
+  MT("atxH6NotH7",
+     "[header ####### foo]");
+
+  // Setext headers - H1, H2
+  // Per documentation, "Any number of underlining =’s or -’s will work."
+  // http://daringfireball.net/projects/markdown/syntax#header
+  // Ideally, the text would be marked as `header` as well, but this is
+  // not really feasible at the moment. So, instead, we're testing against
+  // what works today, to avoid any regressions.
+  //
+  // Check if single underlining = works
+  MT("setextH1",
+     "foo",
+     "[header =]");
+
+  // Check if 3+ ='s work
+  MT("setextH1",
+     "foo",
+     "[header ===]");
+
+  // Check if single underlining - works
+  MT("setextH2",
+     "foo",
+     "[header -]");
+
+  // Check if 3+ -'s work
+  MT("setextH2",
+     "foo",
+     "[header ---]");
+
+  // Single-line blockquote with trailing space
+  MT("blockquoteSpace",
+     "[atom > foo]");
+
+  // Single-line blockquote
+  MT("blockquoteNoSpace",
+     "[atom >foo]");
+
+  // No blank line before blockquote
+  MT("blockquoteNoBlankLine",
+     "foo",
+     "[atom > bar]");
+
+  // Nested blockquote
+  MT("blockquoteSpace",
+     "[atom > foo]",
+     "[number > > foo]",
+     "[atom > > > foo]");
+
+  // Single-line blockquote followed by normal paragraph
+  MT("blockquoteThenParagraph",
+     "[atom >foo]",
+     "",
+     "bar");
+
+  // Multi-line blockquote (lazy mode)
+  MT("multiBlockquoteLazy",
+     "[atom >foo]",
+     "[atom bar]");
+
+  // Multi-line blockquote followed by normal paragraph (lazy mode)
+  MT("multiBlockquoteLazyThenParagraph",
+     "[atom >foo]",
+     "[atom bar]",
+     "",
+     "hello");
+
+  // Multi-line blockquote (non-lazy mode)
+  MT("multiBlockquote",
+     "[atom >foo]",
+     "[atom >bar]");
+
+  // Multi-line blockquote followed by normal paragraph (non-lazy mode)
+  MT("multiBlockquoteThenParagraph",
+     "[atom >foo]",
+     "[atom >bar]",
+     "",
+     "hello");
+
+  // Check list types
+
+  MT("listAsterisk",
+     "foo",
+     "bar",
+     "",
+     "[variable-2 * foo]",
+     "[variable-2 * bar]");
+
+  MT("listPlus",
+     "foo",
+     "bar",
+     "",
+     "[variable-2 + foo]",
+     "[variable-2 + bar]");
+
+  MT("listDash",
+     "foo",
+     "bar",
+     "",
+     "[variable-2 - foo]",
+     "[variable-2 - bar]");
+
+  MT("listNumber",
+     "foo",
+     "bar",
+     "",
+     "[variable-2 1. foo]",
+     "[variable-2 2. bar]");
+
+  // Lists require a preceding blank line (per Dingus)
+  MT("listBogus",
+     "foo",
+     "1. bar",
+     "2. hello");
+
+  // Formatting in lists (*)
+  MT("listAsteriskFormatting",
+     "[variable-2 * ][variable-2&em *foo*][variable-2  bar]",
+     "[variable-2 * ][variable-2&strong **foo**][variable-2  bar]",
+     "[variable-2 * ][variable-2&strong **][variable-2&em&strong *foo**][variable-2&em *][variable-2  bar]",
+     "[variable-2 * ][variable-2&comment `foo`][variable-2  bar]");
+
+  // Formatting in lists (+)
+  MT("listPlusFormatting",
+     "[variable-2 + ][variable-2&em *foo*][variable-2  bar]",
+     "[variable-2 + ][variable-2&strong **foo**][variable-2  bar]",
+     "[variable-2 + ][variable-2&strong **][variable-2&em&strong *foo**][variable-2&em *][variable-2  bar]",
+     "[variable-2 + ][variable-2&comment `foo`][variable-2  bar]");
+
+  // Formatting in lists (-)
+  MT("listDashFormatting",
+     "[variable-2 - ][variable-2&em *foo*][variable-2  bar]",
+     "[variable-2 - ][variable-2&strong **foo**][variable-2  bar]",
+     "[variable-2 - ][variable-2&strong **][variable-2&em&strong *foo**][variable-2&em *][variable-2  bar]",
+     "[variable-2 - ][variable-2&comment `foo`][variable-2  bar]");
+
+  // Formatting in lists (1.)
+  MT("listNumberFormatting",
+     "[variable-2 1. ][variable-2&em *foo*][variable-2  bar]",
+     "[variable-2 2. ][variable-2&strong **foo**][variable-2  bar]",
+     "[variable-2 3. ][variable-2&strong **][variable-2&em&strong *foo**][variable-2&em *][variable-2  bar]",
+     "[variable-2 4. ][variable-2&comment `foo`][variable-2  bar]");
+
+  // Paragraph lists
+  MT("listParagraph",
+     "[variable-2 * foo]",
+     "",
+     "[variable-2 * bar]");
+
+  // Multi-paragraph lists
+  //
+  // 4 spaces
+  MT("listMultiParagraph",
+     "[variable-2 * foo]",
+     "",
+     "[variable-2 * bar]",
+     "",
+     "    [variable-2 hello]");
+
+  // 4 spaces, extra blank lines (should still be list, per Dingus)
+  MT("listMultiParagraphExtra",
+     "[variable-2 * foo]",
+     "",
+     "[variable-2 * bar]",
+     "",
+     "",
+     "    [variable-2 hello]");
+
+  // 4 spaces, plus 1 space (should still be list, per Dingus)
+  MT("listMultiParagraphExtraSpace",
+     "[variable-2 * foo]",
+     "",
+     "[variable-2 * bar]",
+     "",
+     "     [variable-2 hello]",
+     "",
+     "    [variable-2 world]");
+
+  // 1 tab
+  MT("listTab",
+     "[variable-2 * foo]",
+     "",
+     "[variable-2 * bar]",
+     "",
+     "\t[variable-2 hello]");
+
+  // No indent
+  MT("listNoIndent",
+     "[variable-2 * foo]",
+     "",
+     "[variable-2 * bar]",
+     "",
+     "hello");
+
+  // Blockquote
+  MT("blockquote",
+     "[variable-2 * foo]",
+     "",
+     "[variable-2 * bar]",
+     "",
+     "    [variable-2&atom > hello]");
+
+  // Code block
+  MT("blockquoteCode",
+     "[variable-2 * foo]",
+     "",
+     "[variable-2 * bar]",
+     "",
+     "        [comment > hello]",
+     "",
+     "    [variable-2 world]");
+
+  // Code block followed by text
+  MT("blockquoteCodeText",
+     "[variable-2 * foo]",
+     "",
+     "    [variable-2 bar]",
+     "",
+     "        [comment hello]",
+     "",
+     "    [variable-2 world]");
+
+  // Nested list
+
+  MT("listAsteriskNested",
+     "[variable-2 * foo]",
+     "",
+     "    [variable-3 * bar]");
+
+  MT("listPlusNested",
+     "[variable-2 + foo]",
+     "",
+     "    [variable-3 + bar]");
+
+  MT("listDashNested",
+     "[variable-2 - foo]",
+     "",
+     "    [variable-3 - bar]");
+
+  MT("listNumberNested",
+     "[variable-2 1. foo]",
+     "",
+     "    [variable-3 2. bar]");
+
+  MT("listMixed",
+     "[variable-2 * foo]",
+     "",
+     "    [variable-3 + bar]",
+     "",
+     "        [keyword - hello]",
+     "",
+     "            [variable-2 1. world]");
+
+  MT("listBlockquote",
+     "[variable-2 * foo]",
+     "",
+     "    [variable-3 + bar]",
+     "",
+     "        [atom&variable-3 > hello]");
+
+  MT("listCode",
+     "[variable-2 * foo]",
+     "",
+     "    [variable-3 + bar]",
+     "",
+     "            [comment hello]");
+
+  // Code with internal indentation
+  MT("listCodeIndentation",
+     "[variable-2 * foo]",
+     "",
+     "        [comment bar]",
+     "            [comment hello]",
+     "                [comment world]",
+     "        [comment foo]",
+     "    [variable-2 bar]");
+
+  // List nesting edge cases
+  MT("listNested",
+    "[variable-2 * foo]",
+    "",
+    "    [variable-3 * bar]",
+    "",
+    "       [variable-2 hello]"
+  );
+  MT("listNested",
+    "[variable-2 * foo]",
+    "",
+    "    [variable-3 * bar]",
+    "",
+    "      [variable-3 * foo]"
+  );
+
+  // Code followed by text
+  MT("listCodeText",
+     "[variable-2 * foo]",
+     "",
+     "        [comment bar]",
+     "",
+     "hello");
+
+  // Following tests directly from official Markdown documentation
+  // http://daringfireball.net/projects/markdown/syntax#hr
+
+  MT("hrSpace",
+     "[hr * * *]");
+
+  MT("hr",
+     "[hr ***]");
+
+  MT("hrLong",
+     "[hr *****]");
+
+  MT("hrSpaceDash",
+     "[hr - - -]");
+
+  MT("hrDashLong",
+     "[hr ---------------------------------------]");
+
+  // Inline link with title
+  MT("linkTitle",
+     "[link [[foo]]][string (http://example.com/ \"bar\")] hello");
+
+  // Inline link without title
+  MT("linkNoTitle",
+     "[link [[foo]]][string (http://example.com/)] bar");
+
+  // Inline link with image
+  MT("linkImage",
+     "[link [[][tag ![[foo]]][string (http://example.com/)][link ]]][string (http://example.com/)] bar");
+
+  // Inline link with Em
+  MT("linkEm",
+     "[link [[][link&em *foo*][link ]]][string (http://example.com/)] bar");
+
+  // Inline link with Strong
+  MT("linkStrong",
+     "[link [[][link&strong **foo**][link ]]][string (http://example.com/)] bar");
+
+  // Inline link with EmStrong
+  MT("linkEmStrong",
+     "[link [[][link&strong **][link&em&strong *foo**][link&em *][link ]]][string (http://example.com/)] bar");
+
+  // Image with title
+  MT("imageTitle",
+     "[tag ![[foo]]][string (http://example.com/ \"bar\")] hello");
+
+  // Image without title
+  MT("imageNoTitle",
+     "[tag ![[foo]]][string (http://example.com/)] bar");
+
+  // Image with asterisks
+  MT("imageAsterisks",
+     "[tag ![[*foo*]]][string (http://example.com/)] bar");
+
+  // Not a link. Should be normal text due to square brackets being used
+  // regularly in text, especially in quoted material, and no space is allowed
+  // between square brackets and parentheses (per Dingus).
+  MT("notALink",
+     "[[foo]] (bar)");
+
+  // Reference-style links
+  MT("linkReference",
+     "[link [[foo]]][string [[bar]]] hello");
+
+  // Reference-style links with Em
+  MT("linkReferenceEm",
+     "[link [[][link&em *foo*][link ]]][string [[bar]]] hello");
+
+  // Reference-style links with Strong
+  MT("linkReferenceStrong",
+     "[link [[][link&strong **foo**][link ]]][string [[bar]]] hello");
+
+  // Reference-style links with EmStrong
+  MT("linkReferenceEmStrong",
+     "[link [[][link&strong **][link&em&strong *foo**][link&em *][link ]]][string [[bar]]] hello");
+
+  // Reference-style links with optional space separator (per docuentation)
+  // "You can optionally use a space to separate the sets of brackets"
+  MT("linkReferenceSpace",
+     "[link [[foo]]] [string [[bar]]] hello");
+
+  // Should only allow a single space ("...use *a* space...")
+  MT("linkReferenceDoubleSpace",
+     "[[foo]]  [[bar]] hello");
+
+  // Reference-style links with implicit link name
+  MT("linkImplicit",
+     "[link [[foo]]][string [[]]] hello");
+
+  // @todo It would be nice if, at some point, the document was actually
+  // checked to see if the referenced link exists
+
+  // Link label, for reference-style links (taken from documentation)
+
+  MT("labelNoTitle",
+     "[link [[foo]]:] [string http://example.com/]");
+
+  MT("labelIndented",
+     "   [link [[foo]]:] [string http://example.com/]");
+
+  MT("labelSpaceTitle",
+     "[link [[foo bar]]:] [string http://example.com/ \"hello\"]");
+
+  MT("labelDoubleTitle",
+     "[link [[foo bar]]:] [string http://example.com/ \"hello\"] \"world\"");
+
+  MT("labelTitleDoubleQuotes",
+     "[link [[foo]]:] [string http://example.com/  \"bar\"]");
+
+  MT("labelTitleSingleQuotes",
+     "[link [[foo]]:] [string http://example.com/  'bar']");
+
+  MT("labelTitleParenthese",
+     "[link [[foo]]:] [string http://example.com/  (bar)]");
+
+  MT("labelTitleInvalid",
+     "[link [[foo]]:] [string http://example.com/] bar");
+
+  MT("labelLinkAngleBrackets",
+     "[link [[foo]]:] [string <http://example.com/>  \"bar\"]");
+
+  MT("labelTitleNextDoubleQuotes",
+     "[link [[foo]]:] [string http://example.com/]",
+     "[string \"bar\"] hello");
+
+  MT("labelTitleNextSingleQuotes",
+     "[link [[foo]]:] [string http://example.com/]",
+     "[string 'bar'] hello");
+
+  MT("labelTitleNextParenthese",
+     "[link [[foo]]:] [string http://example.com/]",
+     "[string (bar)] hello");
+
+  MT("labelTitleNextMixed",
+     "[link [[foo]]:] [string http://example.com/]",
+     "(bar\" hello");
+
+  MT("linkWeb",
+     "[link <http://example.com/>] foo");
+
+  MT("linkWebDouble",
+     "[link <http://example.com/>] foo [link <http://example.com/>]");
+
+  MT("linkEmail",
+     "[link <user@example.com>] foo");
+
+  MT("linkEmailDouble",
+     "[link <user@example.com>] foo [link <user@example.com>]");
+
+  MT("emAsterisk",
+     "[em *foo*] bar");
+
+  MT("emUnderscore",
+     "[em _foo_] bar");
+
+  MT("emInWordAsterisk",
+     "foo[em *bar*]hello");
+
+  MT("emInWordUnderscore",
+     "foo[em _bar_]hello");
+
+  // Per documentation: "...surround an * or _ with spaces, it’ll be
+  // treated as a literal asterisk or underscore."
+
+  MT("emEscapedBySpaceIn",
+     "foo [em _bar _ hello_] world");
+
+  MT("emEscapedBySpaceOut",
+     "foo _ bar[em _hello_]world");
+
+  // Unclosed emphasis characters
+  // Instead of simply marking as EM / STRONG, it would be nice to have an
+  // incomplete flag for EM and STRONG, that is styled slightly different.
+  MT("emIncompleteAsterisk",
+     "foo [em *bar]");
+
+  MT("emIncompleteUnderscore",
+     "foo [em _bar]");
+
+  MT("strongAsterisk",
+     "[strong **foo**] bar");
+
+  MT("strongUnderscore",
+     "[strong __foo__] bar");
+
+  MT("emStrongAsterisk",
+     "[em *foo][em&strong **bar*][strong hello**] world");
+
+  MT("emStrongUnderscore",
+     "[em _foo][em&strong __bar_][strong hello__] world");
+
+  // "...same character must be used to open and close an emphasis span.""
+  MT("emStrongMixed",
+     "[em _foo][em&strong **bar*hello__ world]");
+
+  MT("emStrongMixed",
+     "[em *foo][em&strong __bar_hello** world]");
+
+  // These characters should be escaped:
+  // \   backslash
+  // `   backtick
+  // *   asterisk
+  // _   underscore
+  // {}  curly braces
+  // []  square brackets
+  // ()  parentheses
+  // #   hash mark
+  // +   plus sign
+  // -   minus sign (hyphen)
+  // .   dot
+  // !   exclamation mark
+
+  MT("escapeBacktick",
+     "foo \\`bar\\`");
+
+  MT("doubleEscapeBacktick",
+     "foo \\\\[comment `bar\\\\`]");
+
+  MT("escapeAsterisk",
+     "foo \\*bar\\*");
+
+  MT("doubleEscapeAsterisk",
+     "foo \\\\[em *bar\\\\*]");
+
+  MT("escapeUnderscore",
+     "foo \\_bar\\_");
+
+  MT("doubleEscapeUnderscore",
+     "foo \\\\[em _bar\\\\_]");
+
+  MT("escapeHash",
+     "\\# foo");
+
+  MT("doubleEscapeHash",
+     "\\\\# foo");
+
+
+  // Tests to make sure GFM-specific things aren't getting through
+
+  MT("taskList",
+     "[variable-2 * [ ]] bar]");
+
+  MT("fencedCodeBlocks",
+     "[comment ```]",
+     "foo",
+     "[comment ```]");
+})();
diff --git a/third-party/codemirror-3.15/mode/meta.js b/third-party/codemirror-3.15/mode/meta.js
new file mode 100644 (file)
index 0000000..8e8c8f5
--- /dev/null
@@ -0,0 +1,81 @@
+CodeMirror.modeInfo = [
+  {name: 'APL', mime: 'text/apl', mode: 'apl'},
+  {name: 'Asterisk', mime: 'text/x-asterisk', mode: 'asterisk'},
+  {name: 'C', mime: 'text/x-csrc', mode: 'clike'},
+  {name: 'C++', mime: 'text/x-c++src', mode: 'clike'},
+  {name: 'Cobol', mime: 'text/x-cobol', mode: 'cobol'},
+  {name: 'Java', mime: 'text/x-java', mode: 'clike'},
+  {name: 'C#', mime: 'text/x-csharp', mode: 'clike'},
+  {name: 'Scala', mime: 'text/x-scala', mode: 'clike'},
+  {name: 'Clojure', mime: 'text/x-clojure', mode: 'clojure'},
+  {name: 'CoffeeScript', mime: 'text/x-coffeescript', mode: 'coffeescript'},
+  {name: 'Common Lisp', mime: 'text/x-common-lisp', mode: 'commonlisp'},
+  {name: 'CSS', mime: 'text/css', mode: 'css'},
+  {name: 'D', mime: 'text/x-d', mode: 'd'},
+  {name: 'diff', mime: 'text/x-diff', mode: 'diff'},
+  {name: 'ECL', mime: 'text/x-ecl', mode: 'ecl'},
+  {name: 'Erlang', mime: 'text/x-erlang', mode: 'erlang'},
+  {name: 'Gas', mime: 'text/x-gas', mode: 'gas'},
+  {name: 'GitHub Flavored Markdown', mime: 'text/x-gfm', mode: 'gfm'},
+  {name: 'GO', mime: 'text/x-go', mode: 'go'},
+  {name: 'Groovy', mime: 'text/x-groovy', mode: 'groovy'},
+  {name: 'Haskell', mime: 'text/x-haskell', mode: 'haskell'},
+  {name: 'Haxe', mime: 'text/x-haxe', mode: 'haxe'},
+  {name: 'ASP.NET', mime: 'application/x-aspx', mode: 'htmlembedded'},
+  {name: 'Embedded Javascript', mime: 'application/x-ejs', mode: 'htmlembedded'},
+  {name: 'JavaServer Pages', mime: 'application/x-jsp', mode: 'htmlembedded'},
+  {name: 'HTML', mime: 'text/html', mode: 'htmlmixed'},
+  {name: 'HTTP', mime: 'message/http', mode: 'http'},
+  {name: 'Jade', mime: 'text/x-jade', mode: 'jade'},
+  {name: 'JavaScript', mime: 'text/javascript', mode: 'javascript'},
+  {name: 'JSON', mime: 'application/x-json', mode: 'javascript'},
+  {name: 'JSON', mime: 'application/json', mode: 'javascript'},
+  {name: 'TypeScript', mime: 'application/typescript', mode: 'javascript'},
+  {name: 'Jinja2', mime: 'jinja2', mode: 'jinja2'},
+  {name: 'LESS', mime: 'text/x-less', mode: 'less'},
+  {name: 'LiveScript', mime: 'text/x-livescript', mode: 'livescript'},
+  {name: 'Lua', mime: 'text/x-lua', mode: 'lua'},
+  {name: 'Markdown (GitHub-flavour)', mime: 'text/x-markdown', mode: 'markdown'},
+  {name: 'mIRC', mime: 'text/mirc', mode: 'mirc'},
+  {name: 'Nginx', mime: 'text/x-nginx-conf', mode: 'nginx'},
+  {name: 'NTriples', mime: 'text/n-triples', mode: 'ntriples'},
+  {name: 'OCaml', mime: 'text/x-ocaml', mode: 'ocaml'},
+  {name: 'Pascal', mime: 'text/x-pascal', mode: 'pascal'},
+  {name: 'Perl', mime: 'text/x-perl', mode: 'perl'},
+  {name: 'PHP', mime: 'text/x-php', mode: 'php'},
+  {name: 'PHP(HTML)', mime: 'application/x-httpd-php', mode: 'php'},
+  {name: 'Pig', mime: 'text/x-pig', mode: 'pig'},
+  {name: 'Plain Text', mime: 'text/plain', mode: 'null'},
+  {name: 'Properties files', mime: 'text/x-properties', mode: 'clike'},
+  {name: 'Python', mime: 'text/x-python', mode: 'python'},
+  {name: 'Cython', mime: 'text/x-cython', mode: 'python'},
+  {name: 'R', mime: 'text/x-rsrc', mode: 'r'},
+  {name: 'reStructuredText', mime: 'text/x-rst', mode: 'rst'},
+  {name: 'Ruby', mime: 'text/x-ruby', mode: 'ruby'},
+  {name: 'Rust', mime: 'text/x-rustsrc', mode: 'rust'},
+  {name: 'Sass', mime: 'text/x-sass', mode: 'sass'},
+  {name: 'Scheme', mime: 'text/x-scheme', mode: 'scheme'},
+  {name: 'SCSS', mime: 'text/x-scss', mode: 'css'},
+  {name: 'Shell', mime: 'text/x-sh', mode: 'shell'},
+  {name: 'Sieve', mime: 'application/sieve', mode: 'sieve'},
+  {name: 'Smalltalk', mime: 'text/x-stsrc', mode: 'smalltalk'},
+  {name: 'Smarty', mime: 'text/x-smarty', mode: 'smarty'},
+  {name: 'SmartyMixed', mime: 'text/x-smarty', mode: 'smartymixed'},
+  {name: 'SPARQL', mime: 'application/x-sparql-query', mode: 'sparql'},
+  {name: 'SQL', mime: 'text/x-sql', mode: 'sql'},
+  {name: 'MariaDB', mime: 'text/x-mariadb', mode: 'sql'},
+  {name: 'sTeX', mime: 'text/x-stex', mode: 'stex'},
+  {name: 'LaTeX', mime: 'text/x-latex', mode: 'stex'},
+  {name: 'Tcl', mime: 'text/x-tcl', mode: 'tcl'},
+  {name: 'TiddlyWiki ', mime: 'text/x-tiddlywiki', mode: 'tiddlywiki'},
+  {name: 'Tiki wiki', mime: 'text/tiki', mode: 'tiki'},
+  {name: 'VB.NET', mime: 'text/x-vb', mode: 'vb'},
+  {name: 'VBScript', mime: 'text/vbscript', mode: 'vbscript'},
+  {name: 'Velocity', mime: 'text/velocity', mode: 'velocity'},
+  {name: 'Verilog', mime: 'text/x-verilog', mode: 'verilog'},
+  {name: 'XML', mime: 'application/xml', mode: 'xml'},
+  {name: 'HTML', mime: 'text/html', mode: 'xml'},
+  {name: 'XQuery', mime: 'application/xquery', mode: 'xquery'},
+  {name: 'YAML', mime: 'text/x-yaml', mode: 'yaml'},
+  {name: 'Z80', mime: 'text/x-z80', mode: 'z80'}
+];
diff --git a/third-party/codemirror-3.15/mode/mirc/index.html b/third-party/codemirror-3.15/mode/mirc/index.html
new file mode 100644 (file)
index 0000000..0ff5ec9
--- /dev/null
@@ -0,0 +1,149 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: mIRC mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="mirc.js"></script>
+    <link rel="stylesheet" href="../../theme/twilight.css">
+    <style>.CodeMirror {border: 1px solid black;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: mIRC mode</h1>
+    <form><textarea id="code" name="code">
+;AKA Nick Tracker by Ford_Lawnmower irc.GeekShed.net #Script-Help
+;*****************************************************************************;
+;**Start Setup
+;Change JoinDisplay, below, for On Join AKA Display. On = 1 - Off = 0
+alias -l JoinDisplay { return 1 }
+;Change MaxNicks, below, to the number of nicknames you want to store for each hostmask. I wouldn't go over 400 with this ;/
+alias -l MaxNicks { return 20 }
+;Change AKALogo, below, To the text you want displayed before each AKA result.
+alias -l AKALogo { return \ 306\a \ 305A\ 306K\ 307A \ 306\a }
+;**End Setup
+;*****************************************************************************;
+On *:Join:#: {
+  if ($nick == $me) { .timer 1 1 ialupdateCheck $chan }
+  NickNamesAdd $nick $+($network,$wildsite)
+  if ($JoinDisplay) { .timerNickNames $+ $nick 1 2 NickNames.display $nick $chan $network $wildsite }
+}
+on *:Nick: { NickNamesAdd $newnick $+($network,$wildsite) $nick }
+alias -l NickNames.display {
+  if ($gettok($hget(NickNames,$+($3,$4)),0,126) > 1) {
+    echo -g $2 $AKALogo $+(\ 309,$1) $AKALogo \ 307 $mid($replace($hget(NickNames,$+($3,$4)),$chr(126),$chr(44)),2,-1)
+  }
+}
+alias -l NickNamesAdd {
+  if ($hget(NickNames,$2)) {
+    if (!$regex($hget(NickNames,$2),/~\Q $+ $replacecs($1,\E,\E\\E\Q) $+ \E~/i)) {
+      if ($gettok($hget(NickNames,$2),0,126) <= $MaxNicks) {
+        hadd NickNames $2 $+($hget(NickNames,$2),$1,~)
+      }
+      else {
+        hadd NickNames $2 $+($mid($hget(NickNames,$2),$pos($hget(NickNames,$2),~,2)),$1,~)
+      }
+    }
+  }
+  else {
+    hadd -m NickNames $2 $+(~,$1,~,$iif($3,$+($3,~)))
+  }
+}
+alias -l Fix.All.MindUser {
+  var %Fix.Count = $hfind(NickNames,/[^~]+[0-9]{4}~/,0,r).data
+  while (%Fix.Count) {
+    if ($Fix.MindUser($hget(NickNames,$hfind(NickNames,/[^~]+[0-9]{4}~/,%Fix.Count,r).data))) {
+      echo -ag Record %Fix.Count - $v1 - Was Cleaned
+      hadd NickNames $hfind(NickNames,/[^~]+[0-9]{4}~/,%Fix.Count,r).data $v1
+    }
+    dec %Fix.Count
+  }
+}
+alias -l Fix.MindUser { return $regsubex($1,/[^~]+[0-9]{4}~/g,$null) }
+menu nicklist,query {
+  -
+  .AKA
+  ..Check $$1: {
+    if ($gettok($hget(NickNames,$+($network,$address($1,2))),0,126) > 1) {
+      NickNames.display $1 $active $network $address($1,2)
+    }
+    else { echo -ag $AKALogo $+(\ 309,$1) \ 307has not been known by any other nicknames while I have been watching. }
+  }
+  ..Cleanup $$1:hadd NickNames $+($network,$address($1,2)) $fix.minduser($hget(NickNames,$+($network,$address($1,2))))
+  ..Clear $$1:hadd NickNames $+($network,$address($1,2)) $+(~,$1,~)
+  ..AKA Search Dialog:dialog $iif($dialog(AKA_Search),-v,-m) AKA_Search AKA_Search
+  -
+}
+menu status,channel {
+  -
+  .AKA
+  ..AKA Search Dialog:dialog $iif($dialog(AKA_Search),-v,-m) AKA_Search AKA_Search
+  ..Clean All Records:Fix.All.Minduser
+  -
+}
+dialog AKA_Search {
+  title "AKA Search Engine"
+  size -1 -1 206 221
+  option dbu
+  edit "", 1, 8 5 149 10, autohs
+  button "Search", 2, 163 4 32 12
+  radio "Search HostMask", 4, 61 22 55 10
+  radio "Search Nicknames", 5, 123 22 56 10
+  list 6, 8 38 190 169, sort extsel vsbar
+  button "Check Selected", 7, 67 206 40 12
+  button "Close", 8, 160 206 38 12, cancel
+  box "Search Type", 3, 11 17 183 18
+  button "Copy to Clipboard", 9, 111 206 46 12
+}
+On *:Dialog:Aka_Search:init:*: { did -c $dname 5 }
+On *:Dialog:Aka_Search:Sclick:2,7,9: {
+  if ($did == 2) && ($did($dname,1)) {
+    did -r $dname 6
+    var %search $+(*,$v1,*), %type $iif($did($dname,5).state,data,item), %matches = $hfind(NickNames,%search,0,w). [ $+ [ %type ] ]
+    while (%matches) {
+      did -a $dname 6 $hfind(NickNames,%search,%matches,w). [ $+ [ %type ] ]
+      dec %matches
+    }
+    did -c $dname 6 1
+  }
+  elseif ($did == 7) && ($did($dname,6).seltext) { echo -ga $AKALogo \ 307 $mid($replace($hget(NickNames,$v1),$chr(126),$chr(44)),2,-1) }
+  elseif ($did == 9) && ($did($dname,6).seltext) { clipboard $mid($v1,$pos($v1,*,1)) }
+}
+On *:Start:{
+  if (!$hget(NickNames)) { hmake NickNames 10 }
+  if ($isfile(NickNames.hsh)) { hload  NickNames NickNames.hsh }
+}
+On *:Exit: { if ($hget(NickNames)) { hsave NickNames NickNames.hsh } }
+On *:Disconnect: { if ($hget(NickNames)) { hsave NickNames NickNames.hsh } }
+On *:Unload: { hfree NickNames }
+alias -l ialupdateCheck {
+  inc -z $+(%,ialupdateCheck,$network) $calc($nick($1,0) / 4)
+  ;If your ial is already being updated on join .who $1 out.
+  ;If you are using /names to update ial you will still need this line.
+  .who $1
+}
+Raw 352:*: {
+  if ($($+(%,ialupdateCheck,$network),2)) haltdef
+  NickNamesAdd $6 $+($network,$address($6,2))
+}
+Raw 315:*: {
+  if ($($+(%,ialupdateCheck,$network),2)) haltdef
+}
+
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        tabMode: "indent",
+               theme: "twilight",
+        lineNumbers: true,
+               matchBrackets: true,
+        indentUnit: 4,
+        mode: "text/mirc"
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/mirc</code>.</p>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/mirc/mirc.js b/third-party/codemirror-3.15/mode/mirc/mirc.js
new file mode 100644 (file)
index 0000000..fc88bc5
--- /dev/null
@@ -0,0 +1,177 @@
+//mIRC mode by Ford_Lawnmower :: Based on Velocity mode by Steve O'Hara
+CodeMirror.defineMIME("text/mirc", "mirc");
+CodeMirror.defineMode("mirc", function() {
+  function parseWords(str) {
+    var obj = {}, words = str.split(" ");
+    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
+    return obj;
+  }
+  var specials = parseWords("$! $$ $& $? $+ $abook $abs $active $activecid " +
+                            "$activewid $address $addtok $agent $agentname $agentstat $agentver " +
+                            "$alias $and $anick $ansi2mirc $aop $appactive $appstate $asc $asctime " +
+                            "$asin $atan $avoice $away $awaymsg $awaytime $banmask $base $bfind " +
+                            "$binoff $biton $bnick $bvar $bytes $calc $cb $cd $ceil $chan $chanmodes " +
+                            "$chantypes $chat $chr $cid $clevel $click $cmdbox $cmdline $cnick $color " +
+                            "$com $comcall $comchan $comerr $compact $compress $comval $cos $count " +
+                            "$cr $crc $creq $crlf $ctime $ctimer $ctrlenter $date $day $daylight " +
+                            "$dbuh $dbuw $dccignore $dccport $dde $ddename $debug $decode $decompress " +
+                            "$deltok $devent $dialog $did $didreg $didtok $didwm $disk $dlevel $dll " +
+                            "$dllcall $dname $dns $duration $ebeeps $editbox $emailaddr $encode $error " +
+                            "$eval $event $exist $feof $ferr $fgetc $file $filename $filtered $finddir " +
+                            "$finddirn $findfile $findfilen $findtok $fline $floor $fopen $fread $fserve " +
+                            "$fulladdress $fulldate $fullname $fullscreen $get $getdir $getdot $gettok $gmt " +
+                            "$group $halted $hash $height $hfind $hget $highlight $hnick $hotline " +
+                            "$hotlinepos $ial $ialchan $ibl $idle $iel $ifmatch $ignore $iif $iil " +
+                            "$inelipse $ini $inmidi $inpaste $inpoly $input $inrect $inroundrect " +
+                            "$insong $instok $int $inwave $ip $isalias $isbit $isdde $isdir $isfile " +
+                            "$isid $islower $istok $isupper $keychar $keyrpt $keyval $knick $lactive " +
+                            "$lactivecid $lactivewid $left $len $level $lf $line $lines $link $lock " +
+                            "$lock $locked $log $logstamp $logstampfmt $longfn $longip $lower $ltimer " +
+                            "$maddress $mask $matchkey $matchtok $md5 $me $menu $menubar $menucontext " +
+                            "$menutype $mid $middir $mircdir $mircexe $mircini $mklogfn $mnick $mode " +
+                            "$modefirst $modelast $modespl $mouse $msfile $network $newnick $nick $nofile " +
+                            "$nopath $noqt $not $notags $notify $null $numeric $numok $oline $onpoly " +
+                            "$opnick $or $ord $os $passivedcc $pic $play $pnick $port $portable $portfree " +
+                            "$pos $prefix $prop $protect $puttok $qt $query $rand $r $rawmsg $read $readomo " +
+                            "$readn $regex $regml $regsub $regsubex $remove $remtok $replace $replacex " +
+                            "$reptok $result $rgb $right $round $scid $scon $script $scriptdir $scriptline " +
+                            "$sdir $send $server $serverip $sfile $sha1 $shortfn $show $signal $sin " +
+                            "$site $sline $snick $snicks $snotify $sock $sockbr $sockerr $sockname " +
+                            "$sorttok $sound $sqrt $ssl $sreq $sslready $status $strip $str $stripped " +
+                            "$syle $submenu $switchbar $tan $target $ticks $time $timer $timestamp " +
+                            "$timestampfmt $timezone $tip $titlebar $toolbar $treebar $trust $ulevel " +
+                            "$ulist $upper $uptime $url $usermode $v1 $v2 $var $vcmd $vcmdstat $vcmdver " +
+                            "$version $vnick $vol $wid $width $wildsite $wildtok $window $wrap $xor");
+  var keywords = parseWords("abook ajinvite alias aline ame amsg anick aop auser autojoin avoice " +
+                            "away background ban bcopy beep bread break breplace bset btrunc bunset bwrite " +
+                            "channel clear clearall cline clipboard close cnick color comclose comopen " +
+                            "comreg continue copy creq ctcpreply ctcps dcc dccserver dde ddeserver " +
+                            "debug dec describe dialog did didtok disable disconnect dlevel dline dll " +
+                            "dns dqwindow drawcopy drawdot drawfill drawline drawpic drawrect drawreplace " +
+                            "drawrot drawsave drawscroll drawtext ebeeps echo editbox emailaddr enable " +
+                            "events exit fclose filter findtext finger firewall flash flist flood flush " +
+                            "flushini font fopen fseek fsend fserve fullname fwrite ghide gload gmove " +
+                            "gopts goto gplay gpoint gqreq groups gshow gsize gstop gtalk gunload hadd " +
+                            "halt haltdef hdec hdel help hfree hinc hload hmake hop hsave ial ialclear " +
+                            "ialmark identd if ignore iline inc invite iuser join kick linesep links list " +
+                            "load loadbuf localinfo log mdi me menubar mkdir mnick mode msg nick noop notice " +
+                            "notify omsg onotice part partall pdcc perform play playctrl pop protect pvoice " +
+                            "qme qmsg query queryn quit raw reload remini remote remove rename renwin " +
+                            "reseterror resetidle return rlevel rline rmdir run ruser save savebuf saveini " +
+                            "say scid scon server set showmirc signam sline sockaccept sockclose socklist " +
+                            "socklisten sockmark sockopen sockpause sockread sockrename sockudp sockwrite " +
+                            "sound speak splay sreq strip switchbar timer timestamp titlebar tnick tokenize " +
+                            "toolbar topic tray treebar ulist unload unset unsetall updatenl url uwho " +
+                            "var vcadd vcmd vcrem vol while whois window winhelp write writeint if isalnum " +
+                            "isalpha isaop isavoice isban ischan ishop isignore isin isincs isletter islower " +
+                            "isnotify isnum ison isop isprotect isreg isupper isvoice iswm iswmcs " +
+                            "elseif else goto menu nicklist status title icon size option text edit " +
+                            "button check radio box scroll list combo link tab item");
+  var functions = parseWords("if elseif else and not or eq ne in ni for foreach while switch");
+  var isOperatorChar = /[+\-*&%=<>!?^\/\|]/;
+  function chain(stream, state, f) {
+    state.tokenize = f;
+    return f(stream, state);
+  }
+  function tokenBase(stream, state) {
+    var beforeParams = state.beforeParams;
+    state.beforeParams = false;
+    var ch = stream.next();
+    if (/[\[\]{}\(\),\.]/.test(ch)) {
+      if (ch == "(" && beforeParams) state.inParams = true;
+      else if (ch == ")") state.inParams = false;
+      return null;
+    }
+    else if (/\d/.test(ch)) {
+      stream.eatWhile(/[\w\.]/);
+      return "number";
+    }
+    else if (ch == "\\") {
+      stream.eat("\\");
+      stream.eat(/./);
+      return "number";
+    }
+    else if (ch == "/" && stream.eat("*")) {
+      return chain(stream, state, tokenComment);
+    }
+    else if (ch == ";" && stream.match(/ *\( *\(/)) {
+      return chain(stream, state, tokenUnparsed);
+    }
+    else if (ch == ";" && !state.inParams) {
+      stream.skipToEnd();
+      return "comment";
+    }
+    else if (ch == '"') {
+      stream.eat(/"/);
+      return "keyword";
+    }
+    else if (ch == "$") {
+      stream.eatWhile(/[$_a-z0-9A-Z\.:]/);
+      if (specials && specials.propertyIsEnumerable(stream.current().toLowerCase())) {
+        return "keyword";
+      }
+      else {
+        state.beforeParams = true;
+        return "builtin";
+      }
+    }
+    else if (ch == "%") {
+      stream.eatWhile(/[^,^\s^\(^\)]/);
+      state.beforeParams = true;
+      return "string";
+    }
+    else if (isOperatorChar.test(ch)) {
+      stream.eatWhile(isOperatorChar);
+      return "operator";
+    }
+    else {
+      stream.eatWhile(/[\w\$_{}]/);
+      var word = stream.current().toLowerCase();
+      if (keywords && keywords.propertyIsEnumerable(word))
+        return "keyword";
+      if (functions && functions.propertyIsEnumerable(word)) {
+        state.beforeParams = true;
+        return "keyword";
+      }
+      return null;
+    }
+  }
+  function tokenComment(stream, state) {
+    var maybeEnd = false, ch;
+    while (ch = stream.next()) {
+      if (ch == "/" && maybeEnd) {
+        state.tokenize = tokenBase;
+        break;
+      }
+      maybeEnd = (ch == "*");
+    }
+    return "comment";
+  }
+  function tokenUnparsed(stream, state) {
+    var maybeEnd = 0, ch;
+    while (ch = stream.next()) {
+      if (ch == ";" && maybeEnd == 2) {
+        state.tokenize = tokenBase;
+        break;
+      }
+      if (ch == ")")
+        maybeEnd++;
+      else if (ch != " ")
+        maybeEnd = 0;
+    }
+    return "meta";
+  }
+  return {
+    startState: function() {
+      return {
+        tokenize: tokenBase,
+        beforeParams: false,
+        inParams: false
+      };
+    },
+    token: function(stream, state) {
+      if (stream.eatSpace()) return null;
+      return state.tokenize(stream, state);
+    }
+  };
+});
diff --git a/third-party/codemirror-3.15/mode/nginx/index.html b/third-party/codemirror-3.15/mode/nginx/index.html
new file mode 100644 (file)
index 0000000..aa712e1
--- /dev/null
@@ -0,0 +1,167 @@
+<!doctype html>
+<html>
+  <head>
+    <title>CodeMirror: NGINX mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="nginx.js"></script>
+    <style>.CodeMirror {background: #f8f8f8;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+
+  <style>
+    body {
+      margin: 0em auto;
+    }
+
+    .CodeMirror, .CodeMirror-scroll {
+      height: 600px;
+    }
+  </style>
+
+  <body>
+    <h1>CodeMirror: NGINX mode</h1>
+    <form><textarea id="code" name="code" style="height: 800px;">
+server {
+  listen 173.255.219.235:80;
+  server_name website.com.au;
+  rewrite / $scheme://www.$host$request_uri permanent; ## Forcibly prepend a www
+}
+
+server {
+  listen 173.255.219.235:443;
+  server_name website.com.au;
+  rewrite / $scheme://www.$host$request_uri permanent; ## Forcibly prepend a www
+}
+
+server {
+
+  listen      173.255.219.235:80;
+  server_name www.website.com.au;
+
+
+
+  root        /data/www;
+  index       index.html index.php;
+
+  location / {
+    index index.html index.php;     ## Allow a static html file to be shown first
+    try_files $uri $uri/ @handler;  ## If missing pass the URI to Magento's front handler
+    expires 30d;                    ## Assume all files are cachable
+  }
+
+  ## These locations would be hidden by .htaccess normally
+  location /app/                { deny all; }
+  location /includes/           { deny all; }
+  location /lib/                { deny all; }
+  location /media/downloadable/ { deny all; }
+  location /pkginfo/            { deny all; }
+  location /report/config.xml   { deny all; }
+  location /var/                { deny all; }
+
+  location /var/export/ { ## Allow admins only to view export folder
+    auth_basic           "Restricted"; ## Message shown in login window
+    auth_basic_user_file /rs/passwords/testfile; ## See /etc/nginx/htpassword
+    autoindex            on;
+  }
+
+  location  /. { ## Disable .htaccess and other hidden files
+    return 404;
+  }
+
+  location @handler { ## Magento uses a common front handler
+    rewrite / /index.php;
+  }
+
+  location ~ .php/ { ## Forward paths like /js/index.php/x.js to relevant handler
+    rewrite ^/(.*.php)/ /$1 last;
+  }
+
+  location ~ \.php$ {
+    if (!-e $request_filename) { rewrite / /index.php last; } ## Catch 404s that try_files miss
+
+    fastcgi_pass   127.0.0.1:9000;
+    fastcgi_index  index.php;
+    fastcgi_param PATH_INFO $fastcgi_script_name;
+    fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
+    include        /rs/confs/nginx/fastcgi_params;
+  }
+
+}
+
+
+server {
+
+  listen              173.255.219.235:443;
+  server_name         website.com.au www.website.com.au;
+
+  root   /data/www;
+  index index.html index.php;
+
+  ssl                 on;
+  ssl_certificate     /rs/ssl/ssl.crt;
+  ssl_certificate_key /rs/ssl/ssl.key;
+
+  ssl_session_timeout  5m;
+
+  ssl_protocols  SSLv2 SSLv3 TLSv1;
+  ssl_ciphers  ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
+  ssl_prefer_server_ciphers   on;
+
+
+
+  location / {
+    index index.html index.php; ## Allow a static html file to be shown first
+    try_files $uri $uri/ @handler; ## If missing pass the URI to Magento's front handler
+    expires 30d; ## Assume all files are cachable
+  }
+
+  ## These locations would be hidden by .htaccess normally
+  location /app/                { deny all; }
+  location /includes/           { deny all; }
+  location /lib/                { deny all; }
+  location /media/downloadable/ { deny all; }
+  location /pkginfo/            { deny all; }
+  location /report/config.xml   { deny all; }
+  location /var/                { deny all; }
+
+  location /var/export/ { ## Allow admins only to view export folder
+    auth_basic           "Restricted"; ## Message shown in login window
+    auth_basic_user_file htpasswd; ## See /etc/nginx/htpassword
+    autoindex            on;
+  }
+
+  location  /. { ## Disable .htaccess and other hidden files
+    return 404;
+  }
+
+  location @handler { ## Magento uses a common front handler
+    rewrite / /index.php;
+  }
+
+  location ~ .php/ { ## Forward paths like /js/index.php/x.js to relevant handler
+    rewrite ^/(.*.php)/ /$1 last;
+  }
+
+  location ~ .php$ { ## Execute PHP scripts
+    if (!-e $request_filename) { rewrite  /index.php last; } ## Catch 404s that try_files miss
+
+    fastcgi_pass 127.0.0.1:9000;
+    fastcgi_index  index.php;
+    fastcgi_param PATH_INFO $fastcgi_script_name;
+    fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
+    include        /rs/confs/nginx/fastcgi_params;
+
+    fastcgi_param HTTPS on;
+  }
+
+}
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/nginx</code>.</p>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/nginx/nginx.js b/third-party/codemirror-3.15/mode/nginx/nginx.js
new file mode 100644 (file)
index 0000000..c98c8a1
--- /dev/null
@@ -0,0 +1,163 @@
+CodeMirror.defineMode("nginx", function(config) {
+
+  function words(str) {
+    var obj = {}, words = str.split(" ");
+    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
+    return obj;
+  }
+
+  var keywords = words(
+    /* ngxDirectiveControl */ "break return rewrite set" +
+    /* ngxDirective */ " accept_mutex accept_mutex_delay access_log add_after_body add_before_body add_header addition_types aio alias allow ancient_browser ancient_browser_value auth_basic auth_basic_user_file auth_http auth_http_header auth_http_timeout autoindex autoindex_exact_size autoindex_localtime charset charset_types client_body_buffer_size client_body_in_file_only client_body_in_single_buffer client_body_temp_path client_body_timeout client_header_buffer_size client_header_timeout client_max_body_size connection_pool_size create_full_put_path daemon dav_access dav_methods debug_connection debug_points default_type degradation degrade deny devpoll_changes devpoll_events directio directio_alignment empty_gif env epoll_events error_log eventport_events expires fastcgi_bind fastcgi_buffer_size fastcgi_buffers fastcgi_busy_buffers_size fastcgi_cache fastcgi_cache_key fastcgi_cache_methods fastcgi_cache_min_uses fastcgi_cache_path fastcgi_cache_use_stale fastcgi_cache_valid fastcgi_catch_stderr fastcgi_connect_timeout fastcgi_hide_header fastcgi_ignore_client_abort fastcgi_ignore_headers fastcgi_index fastcgi_intercept_errors fastcgi_max_temp_file_size fastcgi_next_upstream fastcgi_param fastcgi_pass_header fastcgi_pass_request_body fastcgi_pass_request_headers fastcgi_read_timeout fastcgi_send_lowat fastcgi_send_timeout fastcgi_split_path_info fastcgi_store fastcgi_store_access fastcgi_temp_file_write_size fastcgi_temp_path fastcgi_upstream_fail_timeout fastcgi_upstream_max_fails flv geoip_city geoip_country google_perftools_profiles gzip gzip_buffers gzip_comp_level gzip_disable gzip_hash gzip_http_version gzip_min_length gzip_no_buffer gzip_proxied gzip_static gzip_types gzip_vary gzip_window if_modified_since ignore_invalid_headers image_filter image_filter_buffer image_filter_jpeg_quality image_filter_transparency imap_auth imap_capabilities imap_client_buffer index ip_hash keepalive_requests keepalive_timeout kqueue_changes kqueue_events large_client_header_buffers limit_conn limit_conn_log_level limit_rate limit_rate_after limit_req limit_req_log_level limit_req_zone limit_zone lingering_time lingering_timeout lock_file log_format log_not_found log_subrequest map_hash_bucket_size map_hash_max_size master_process memcached_bind memcached_buffer_size memcached_connect_timeout memcached_next_upstream memcached_read_timeout memcached_send_timeout memcached_upstream_fail_timeout memcached_upstream_max_fails merge_slashes min_delete_depth modern_browser modern_browser_value msie_padding msie_refresh multi_accept open_file_cache open_file_cache_errors open_file_cache_events open_file_cache_min_uses open_file_cache_valid open_log_file_cache output_buffers override_charset perl perl_modules perl_require perl_set pid pop3_auth pop3_capabilities port_in_redirect postpone_gzipping postpone_output protocol proxy proxy_bind proxy_buffer proxy_buffer_size proxy_buffering proxy_buffers proxy_busy_buffers_size proxy_cache proxy_cache_key proxy_cache_methods proxy_cache_min_uses proxy_cache_path proxy_cache_use_stale proxy_cache_valid proxy_connect_timeout proxy_headers_hash_bucket_size proxy_headers_hash_max_size proxy_hide_header proxy_ignore_client_abort proxy_ignore_headers proxy_intercept_errors proxy_max_temp_file_size proxy_method proxy_next_upstream proxy_pass_error_message proxy_pass_header proxy_pass_request_body proxy_pass_request_headers proxy_read_timeout proxy_redirect proxy_send_lowat proxy_send_timeout proxy_set_body proxy_set_header proxy_ssl_session_reuse proxy_store proxy_store_access proxy_temp_file_write_size proxy_temp_path proxy_timeout proxy_upstream_fail_timeout proxy_upstream_max_fails random_index read_ahead real_ip_header recursive_error_pages request_pool_size reset_timedout_connection resolver resolver_timeout rewrite_log rtsig_overflow_events rtsig_overflow_test rtsig_overflow_threshold rtsig_signo satisfy secure_link_secret send_lowat send_timeout sendfile sendfile_max_chunk server_name_in_redirect server_names_hash_bucket_size server_names_hash_max_size server_tokens set_real_ip_from smtp_auth smtp_capabilities smtp_client_buffer smtp_greeting_delay so_keepalive source_charset ssi ssi_ignore_recycled_buffers ssi_min_file_chunk ssi_silent_errors ssi_types ssi_value_length ssl ssl_certificate ssl_certificate_key ssl_ciphers ssl_client_certificate ssl_crl ssl_dhparam ssl_engine ssl_prefer_server_ciphers ssl_protocols ssl_session_cache ssl_session_timeout ssl_verify_client ssl_verify_depth starttls stub_status sub_filter sub_filter_once sub_filter_types tcp_nodelay tcp_nopush thread_stack_size timeout timer_resolution types_hash_bucket_size types_hash_max_size underscores_in_headers uninitialized_variable_warn use user userid userid_domain userid_expires userid_mark userid_name userid_p3p userid_path userid_service valid_referers variables_hash_bucket_size variables_hash_max_size worker_connections worker_cpu_affinity worker_priority worker_processes worker_rlimit_core worker_rlimit_nofile worker_rlimit_sigpending worker_threads working_directory xclient xml_entities xslt_stylesheet xslt_typesdrew@li229-23"
+    );
+
+  var keywords_block = words(
+    /* ngxDirectiveBlock */ "http mail events server types location upstream charset_map limit_except if geo map"
+    );
+
+  var keywords_important = words(
+    /* ngxDirectiveImportant */ "include root server server_name listen internal proxy_pass memcached_pass fastcgi_pass try_files"
+    );
+
+  var indentUnit = config.indentUnit, type;
+  function ret(style, tp) {type = tp; return style;}
+
+  function tokenBase(stream, state) {
+
+
+    stream.eatWhile(/[\w\$_]/);
+
+    var cur = stream.current();
+
+
+    if (keywords.propertyIsEnumerable(cur)) {
+      return "keyword";
+    }
+    else if (keywords_block.propertyIsEnumerable(cur)) {
+      return "variable-2";
+    }
+    else if (keywords_important.propertyIsEnumerable(cur)) {
+      return "string-2";
+    }
+    /**/
+
+    var ch = stream.next();
+    if (ch == "@") {stream.eatWhile(/[\w\\\-]/); return ret("meta", stream.current());}
+    else if (ch == "/" && stream.eat("*")) {
+      state.tokenize = tokenCComment;
+      return tokenCComment(stream, state);
+    }
+    else if (ch == "<" && stream.eat("!")) {
+      state.tokenize = tokenSGMLComment;
+      return tokenSGMLComment(stream, state);
+    }
+    else if (ch == "=") ret(null, "compare");
+    else if ((ch == "~" || ch == "|") && stream.eat("=")) return ret(null, "compare");
+    else if (ch == "\"" || ch == "'") {
+      state.tokenize = tokenString(ch);
+      return state.tokenize(stream, state);
+    }
+    else if (ch == "#") {
+      stream.skipToEnd();
+      return ret("comment", "comment");
+    }
+    else if (ch == "!") {
+      stream.match(/^\s*\w*/);
+      return ret("keyword", "important");
+    }
+    else if (/\d/.test(ch)) {
+      stream.eatWhile(/[\w.%]/);
+      return ret("number", "unit");
+    }
+    else if (/[,.+>*\/]/.test(ch)) {
+      return ret(null, "select-op");
+    }
+    else if (/[;{}:\[\]]/.test(ch)) {
+      return ret(null, ch);
+    }
+    else {
+      stream.eatWhile(/[\w\\\-]/);
+      return ret("variable", "variable");
+    }
+  }
+
+  function tokenCComment(stream, state) {
+    var maybeEnd = false, ch;
+    while ((ch = stream.next()) != null) {
+      if (maybeEnd && ch == "/") {
+        state.tokenize = tokenBase;
+        break;
+      }
+      maybeEnd = (ch == "*");
+    }
+    return ret("comment", "comment");
+  }
+
+  function tokenSGMLComment(stream, state) {
+    var dashes = 0, ch;
+    while ((ch = stream.next()) != null) {
+      if (dashes >= 2 && ch == ">") {
+        state.tokenize = tokenBase;
+        break;
+      }
+      dashes = (ch == "-") ? dashes + 1 : 0;
+    }
+    return ret("comment", "comment");
+  }
+
+  function tokenString(quote) {
+    return function(stream, state) {
+      var escaped = false, ch;
+      while ((ch = stream.next()) != null) {
+        if (ch == quote && !escaped)
+          break;
+        escaped = !escaped && ch == "\\";
+      }
+      if (!escaped) state.tokenize = tokenBase;
+      return ret("string", "string");
+    };
+  }
+
+  return {
+    startState: function(base) {
+      return {tokenize: tokenBase,
+              baseIndent: base || 0,
+              stack: []};
+    },
+
+    token: function(stream, state) {
+      if (stream.eatSpace()) return null;
+      type = null;
+      var style = state.tokenize(stream, state);
+
+      var context = state.stack[state.stack.length-1];
+      if (type == "hash" && context == "rule") style = "atom";
+      else if (style == "variable") {
+        if (context == "rule") style = "number";
+        else if (!context || context == "@media{") style = "tag";
+      }
+
+      if (context == "rule" && /^[\{\};]$/.test(type))
+        state.stack.pop();
+      if (type == "{") {
+        if (context == "@media") state.stack[state.stack.length-1] = "@media{";
+        else state.stack.push("{");
+      }
+      else if (type == "}") state.stack.pop();
+      else if (type == "@media") state.stack.push("@media");
+      else if (context == "{" && type != "comment") state.stack.push("rule");
+      return style;
+    },
+
+    indent: function(state, textAfter) {
+      var n = state.stack.length;
+      if (/^\}/.test(textAfter))
+        n -= state.stack[state.stack.length-1] == "rule" ? 2 : 1;
+      return state.baseIndent + n * indentUnit;
+    },
+
+    electricChars: "}"
+  };
+});
+
+CodeMirror.defineMIME("text/nginx", "text/x-nginx-conf");
diff --git a/third-party/codemirror-3.15/mode/ntriples/index.html b/third-party/codemirror-3.15/mode/ntriples/index.html
new file mode 100644 (file)
index 0000000..052a53d
--- /dev/null
@@ -0,0 +1,33 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: NTriples mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="ntriples.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style type="text/css">
+      .CodeMirror {
+        border: 1px solid #eee;
+      }
+    </style>   
+  </head>
+  <body>
+    <h1>CodeMirror: NTriples mode</h1>
+<form>
+<textarea id="ntriples" name="ntriples">    
+<http://Sub1>     <http://pred1>     <http://obj> .
+<http://Sub2>     <http://pred2#an2> "literal 1" .
+<http://Sub3#an3> <http://pred3>     _:bnode3 .
+_:bnode4          <http://pred4>     "literal 2"@lang .
+_:bnode5          <http://pred5>     "literal 3"^^<http://type> .
+</textarea>
+</form>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("ntriples"), {});
+    </script>
+    <p><strong>MIME types defined:</strong> <code>text/n-triples</code>.</p>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/ntriples/ntriples.js b/third-party/codemirror-3.15/mode/ntriples/ntriples.js
new file mode 100644 (file)
index 0000000..ed0cee3
--- /dev/null
@@ -0,0 +1,170 @@
+/**********************************************************
+* This script provides syntax highlighting support for
+* the Ntriples format.
+* Ntriples format specification:
+*     http://www.w3.org/TR/rdf-testcases/#ntriples
+***********************************************************/
+
+/*
+    The following expression defines the defined ASF grammar transitions.
+
+    pre_subject ->
+        {
+        ( writing_subject_uri | writing_bnode_uri )
+            -> pre_predicate
+                -> writing_predicate_uri
+                    -> pre_object
+                        -> writing_object_uri | writing_object_bnode |
+                          (
+                            writing_object_literal
+                                -> writing_literal_lang | writing_literal_type
+                          )
+                            -> post_object
+                                -> BEGIN
+         } otherwise {
+             -> ERROR
+         }
+*/
+CodeMirror.defineMode("ntriples", function() {
+
+  var Location = {
+    PRE_SUBJECT         : 0,
+    WRITING_SUB_URI     : 1,
+    WRITING_BNODE_URI   : 2,
+    PRE_PRED            : 3,
+    WRITING_PRED_URI    : 4,
+    PRE_OBJ             : 5,
+    WRITING_OBJ_URI     : 6,
+    WRITING_OBJ_BNODE   : 7,
+    WRITING_OBJ_LITERAL : 8,
+    WRITING_LIT_LANG    : 9,
+    WRITING_LIT_TYPE    : 10,
+    POST_OBJ            : 11,
+    ERROR               : 12
+  };
+  function transitState(currState, c) {
+    var currLocation = currState.location;
+    var ret;
+
+    // Opening.
+    if     (currLocation == Location.PRE_SUBJECT && c == '<') ret = Location.WRITING_SUB_URI;
+    else if(currLocation == Location.PRE_SUBJECT && c == '_') ret = Location.WRITING_BNODE_URI;
+    else if(currLocation == Location.PRE_PRED    && c == '<') ret = Location.WRITING_PRED_URI;
+    else if(currLocation == Location.PRE_OBJ     && c == '<') ret = Location.WRITING_OBJ_URI;
+    else if(currLocation == Location.PRE_OBJ     && c == '_') ret = Location.WRITING_OBJ_BNODE;
+    else if(currLocation == Location.PRE_OBJ     && c == '"') ret = Location.WRITING_OBJ_LITERAL;
+
+    // Closing.
+    else if(currLocation == Location.WRITING_SUB_URI     && c == '>') ret = Location.PRE_PRED;
+    else if(currLocation == Location.WRITING_BNODE_URI   && c == ' ') ret = Location.PRE_PRED;
+    else if(currLocation == Location.WRITING_PRED_URI    && c == '>') ret = Location.PRE_OBJ;
+    else if(currLocation == Location.WRITING_OBJ_URI     && c == '>') ret = Location.POST_OBJ;
+    else if(currLocation == Location.WRITING_OBJ_BNODE   && c == ' ') ret = Location.POST_OBJ;
+    else if(currLocation == Location.WRITING_OBJ_LITERAL && c == '"') ret = Location.POST_OBJ;
+    else if(currLocation == Location.WRITING_LIT_LANG && c == ' ') ret = Location.POST_OBJ;
+    else if(currLocation == Location.WRITING_LIT_TYPE && c == '>') ret = Location.POST_OBJ;
+
+    // Closing typed and language literal.
+    else if(currLocation == Location.WRITING_OBJ_LITERAL && c == '@') ret = Location.WRITING_LIT_LANG;
+    else if(currLocation == Location.WRITING_OBJ_LITERAL && c == '^') ret = Location.WRITING_LIT_TYPE;
+
+    // Spaces.
+    else if( c == ' ' &&
+             (
+               currLocation == Location.PRE_SUBJECT ||
+               currLocation == Location.PRE_PRED    ||
+               currLocation == Location.PRE_OBJ     ||
+               currLocation == Location.POST_OBJ
+             )
+           ) ret = currLocation;
+
+    // Reset.
+    else if(currLocation == Location.POST_OBJ && c == '.') ret = Location.PRE_SUBJECT;
+
+    // Error
+    else ret = Location.ERROR;
+
+    currState.location=ret;
+  }
+
+  return {
+    startState: function() {
+       return {
+           location : Location.PRE_SUBJECT,
+           uris     : [],
+           anchors  : [],
+           bnodes   : [],
+           langs    : [],
+           types    : []
+       };
+    },
+    token: function(stream, state) {
+      var ch = stream.next();
+      if(ch == '<') {
+         transitState(state, ch);
+         var parsedURI = '';
+         stream.eatWhile( function(c) { if( c != '#' && c != '>' ) { parsedURI += c; return true; } return false;} );
+         state.uris.push(parsedURI);
+         if( stream.match('#', false) ) return 'variable';
+         stream.next();
+         transitState(state, '>');
+         return 'variable';
+      }
+      if(ch == '#') {
+        var parsedAnchor = '';
+        stream.eatWhile(function(c) { if(c != '>' && c != ' ') { parsedAnchor+= c; return true; } return false;});
+        state.anchors.push(parsedAnchor);
+        return 'variable-2';
+      }
+      if(ch == '>') {
+          transitState(state, '>');
+          return 'variable';
+      }
+      if(ch == '_') {
+          transitState(state, ch);
+          var parsedBNode = '';
+          stream.eatWhile(function(c) { if( c != ' ' ) { parsedBNode += c; return true; } return false;});
+          state.bnodes.push(parsedBNode);
+          stream.next();
+          transitState(state, ' ');
+          return 'builtin';
+      }
+      if(ch == '"') {
+          transitState(state, ch);
+          stream.eatWhile( function(c) { return c != '"'; } );
+          stream.next();
+          if( stream.peek() != '@' && stream.peek() != '^' ) {
+              transitState(state, '"');
+          }
+          return 'string';
+      }
+      if( ch == '@' ) {
+          transitState(state, '@');
+          var parsedLang = '';
+          stream.eatWhile(function(c) { if( c != ' ' ) { parsedLang += c; return true; } return false;});
+          state.langs.push(parsedLang);
+          stream.next();
+          transitState(state, ' ');
+          return 'string-2';
+      }
+      if( ch == '^' ) {
+          stream.next();
+          transitState(state, '^');
+          var parsedType = '';
+          stream.eatWhile(function(c) { if( c != '>' ) { parsedType += c; return true; } return false;} );
+          state.types.push(parsedType);
+          stream.next();
+          transitState(state, '>');
+          return 'variable';
+      }
+      if( ch == ' ' ) {
+          transitState(state, ch);
+      }
+      if( ch == '.' ) {
+          transitState(state, ch);
+      }
+    }
+  };
+});
+
+CodeMirror.defineMIME("text/n-triples", "ntriples");
diff --git a/third-party/codemirror-3.15/mode/ocaml/index.html b/third-party/codemirror-3.15/mode/ocaml/index.html
new file mode 100644 (file)
index 0000000..c10a84f
--- /dev/null
@@ -0,0 +1,131 @@
+<!doctype html>
+<meta charset=utf-8>
+<title>CodeMirror: OCaml mode</title>
+
+<link rel=stylesheet href=../../lib/codemirror.css>
+<link rel=stylesheet href=../../doc/docs.css>
+
+<style type=text/css>
+  .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}
+</style>
+
+<script src=../../lib/codemirror.js></script>
+<script src=../../addon/edit/matchbrackets.js></script>
+<script src=ocaml.js></script>
+
+<h1>CodeMirror: OCaml mode</h1>
+
+<textarea id=code>
+(* Summing a list of integers *)
+let rec sum xs =
+  match xs with
+    | []       -&gt; 0
+    | x :: xs' -&gt; x + sum xs'
+
+(* Quicksort *)
+let rec qsort = function
+   | [] -&gt; []
+   | pivot :: rest -&gt;
+       let is_less x = x &lt; pivot in
+       let left, right = List.partition is_less rest in
+       qsort left @ [pivot] @ qsort right
+
+(* Fibonacci Sequence *)
+let rec fib_aux n a b =
+  match n with
+  | 0 -&gt; a
+  | _ -&gt; fib_aux (n - 1) (a + b) a
+let fib n = fib_aux n 0 1
+
+(* Birthday paradox *)
+let year_size = 365.
+
+let rec birthday_paradox prob people =
+    let prob' = (year_size -. float people) /. year_size *. prob  in
+    if prob' &lt; 0.5 then
+        Printf.printf "answer = %d\n" (people+1)
+    else
+        birthday_paradox prob' (people+1) ;;
+
+birthday_paradox 1.0 1
+
+(* Church numerals *)
+let zero f x = x
+let succ n f x = f (n f x)
+let one = succ zero
+let two = succ (succ zero)
+let add n1 n2 f x = n1 f (n2 f x)
+let to_string n = n (fun k -&gt; "S" ^ k) "0"
+let _ = to_string (add (succ two) two)
+
+(* Elementary functions *)
+let square x = x * x;;
+let rec fact x =
+  if x &lt;= 1 then 1 else x * fact (x - 1);;
+
+(* Automatic memory management *)
+let l = 1 :: 2 :: 3 :: [];;
+[1; 2; 3];;
+5 :: l;;
+
+(* Polymorphism: sorting lists *)
+let rec sort = function
+  | [] -&gt; []
+  | x :: l -&gt; insert x (sort l)
+
+and insert elem = function
+  | [] -&gt; [elem]
+  | x :: l -&gt; 
+      if elem &lt; x then elem :: x :: l else x :: insert elem l;;
+
+(* Imperative features *)
+let add_polynom p1 p2 =
+  let n1 = Array.length p1
+  and n2 = Array.length p2 in
+  let result = Array.create (max n1 n2) 0 in
+  for i = 0 to n1 - 1 do result.(i) &lt;- p1.(i) done;
+  for i = 0 to n2 - 1 do result.(i) &lt;- result.(i) + p2.(i) done;
+  result;;
+add_polynom [| 1; 2 |] [| 1; 2; 3 |];;
+
+(* We may redefine fact using a reference cell and a for loop *)
+let fact n =
+  let result = ref 1 in
+  for i = 2 to n do
+    result := i * !result
+   done;
+   !result;;
+fact 5;;
+
+(* Triangle (graphics) *)
+let () =
+  ignore( Glut.init Sys.argv );
+  Glut.initDisplayMode ~double_buffer:true ();
+  ignore (Glut.createWindow ~title:"OpenGL Demo");
+  let angle t = 10. *. t *. t in
+  let render () =
+    GlClear.clear [ `color ];
+    GlMat.load_identity ();
+    GlMat.rotate ~angle: (angle (Sys.time ())) ~z:1. ();
+    GlDraw.begins `triangles;
+    List.iter GlDraw.vertex2 [-1., -1.; 0., 1.; 1., -1.];
+    GlDraw.ends ();
+    Glut.swapBuffers () in
+  GlMat.mode `modelview;
+  Glut.displayFunc ~cb:render;
+  Glut.idleFunc ~cb:(Some Glut.postRedisplay);
+  Glut.mainLoop ()
+
+(* A Hundred Lines of Caml - http://caml.inria.fr/about/taste.en.html *)
+(* OCaml page on Wikipedia - http://en.wikipedia.org/wiki/OCaml *)
+</textarea>
+
+<script>
+  var editor = CodeMirror.fromTextArea(document.getElementById('code'), {
+    mode: 'ocaml',
+    lineNumbers: true,
+    matchBrackets: true
+  });
+</script>
+
+<p><strong>MIME types defined:</strong> <code>text/x-ocaml</code>.</p>
diff --git a/third-party/codemirror-3.15/mode/ocaml/ocaml.js b/third-party/codemirror-3.15/mode/ocaml/ocaml.js
new file mode 100644 (file)
index 0000000..32cbc0b
--- /dev/null
@@ -0,0 +1,116 @@
+CodeMirror.defineMode('ocaml', function() {
+
+  var words = {
+    'true': 'atom',
+    'false': 'atom',
+    'let': 'keyword',
+    'rec': 'keyword',
+    'in': 'keyword',
+    'of': 'keyword',
+    'and': 'keyword',
+    'succ': 'keyword',
+    'if': 'keyword',
+    'then': 'keyword',
+    'else': 'keyword',
+    'for': 'keyword',
+    'to': 'keyword',
+    'while': 'keyword',
+    'do': 'keyword',
+    'done': 'keyword',
+    'fun': 'keyword',
+    'function': 'keyword',
+    'val': 'keyword',
+    'type': 'keyword',
+    'mutable': 'keyword',
+    'match': 'keyword',
+    'with': 'keyword',
+    'try': 'keyword',
+    'raise': 'keyword',
+    'begin': 'keyword',
+    'end': 'keyword',
+    'open': 'builtin',
+    'trace': 'builtin',
+    'ignore': 'builtin',
+    'exit': 'builtin',
+    'print_string': 'builtin',
+    'print_endline': 'builtin'
+  };
+
+  function tokenBase(stream, state) {
+    var ch = stream.next();
+
+    if (ch === '"') {
+      state.tokenize = tokenString;
+      return state.tokenize(stream, state);
+    }
+    if (ch === '(') {
+      if (stream.eat('*')) {
+        state.commentLevel++;
+        state.tokenize = tokenComment;
+        return state.tokenize(stream, state);
+      }
+    }
+    if (ch === '~') {
+      stream.eatWhile(/\w/);
+      return 'variable-2';
+    }
+    if (ch === '`') {
+      stream.eatWhile(/\w/);
+      return 'quote';
+    }
+    if (/\d/.test(ch)) {
+      stream.eatWhile(/[\d]/);
+      if (stream.eat('.')) {
+        stream.eatWhile(/[\d]/);
+      }
+      return 'number';
+    }
+    if ( /[+\-*&%=<>!?|]/.test(ch)) {
+      return 'operator';
+    }
+    stream.eatWhile(/\w/);
+    var cur = stream.current();
+    return words[cur] || 'variable';
+  }
+
+  function tokenString(stream, state) {
+    var next, end = false, escaped = false;
+    while ((next = stream.next()) != null) {
+      if (next === '"' && !escaped) {
+        end = true;
+        break;
+      }
+      escaped = !escaped && next === '\\';
+    }
+    if (end && !escaped) {
+      state.tokenize = tokenBase;
+    }
+    return 'string';
+  };
+
+  function tokenComment(stream, state) {
+    var prev, next;
+    while(state.commentLevel > 0 && (next = stream.next()) != null) {
+      if (prev === '(' && next === '*') state.commentLevel++;
+      if (prev === '*' && next === ')') state.commentLevel--;
+      prev = next;
+    }
+    if (state.commentLevel <= 0) {
+      state.tokenize = tokenBase;
+    }
+    return 'comment';
+  }
+
+  return {
+    startState: function() {return {tokenize: tokenBase, commentLevel: 0};},
+    token: function(stream, state) {
+      if (stream.eatSpace()) return null;
+      return state.tokenize(stream, state);
+    },
+
+    blockCommentStart: "(*",
+    blockCommentEnd: "*)"
+  };
+});
+
+CodeMirror.defineMIME('text/x-ocaml', 'ocaml');
diff --git a/third-party/codemirror-3.15/mode/pascal/LICENSE b/third-party/codemirror-3.15/mode/pascal/LICENSE
new file mode 100644 (file)
index 0000000..8e3747e
--- /dev/null
@@ -0,0 +1,7 @@
+Copyright (c) 2011 souceLair <support@sourcelair.com>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/third-party/codemirror-3.15/mode/pascal/index.html b/third-party/codemirror-3.15/mode/pascal/index.html
new file mode 100644 (file)
index 0000000..b3016af
--- /dev/null
@@ -0,0 +1,48 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Pascal mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="pascal.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: Pascal mode</h1>
+
+<div><textarea id="code" name="code">
+(* Example Pascal code *)
+
+while a <> b do writeln('Waiting');
+if a > b then 
+  writeln('Condition met')
+else 
+  writeln('Condition not met');
+for i := 1 to 10 do 
+  writeln('Iteration: ', i:1);
+repeat
+  a := a + 1
+until a = 10;
+case i of
+  0: write('zero');
+  1: write('one');
+  2: write('two')
+end;
+</textarea></div>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        mode: "text/x-pascal"
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-pascal</code>.</p>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/pascal/pascal.js b/third-party/codemirror-3.15/mode/pascal/pascal.js
new file mode 100644 (file)
index 0000000..09d9b06
--- /dev/null
@@ -0,0 +1,94 @@
+CodeMirror.defineMode("pascal", function() {
+  function words(str) {
+    var obj = {}, words = str.split(" ");
+    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
+    return obj;
+  }
+  var keywords = words("and array begin case const div do downto else end file for forward integer " +
+                       "boolean char function goto if in label mod nil not of or packed procedure " +
+                       "program record repeat set string then to type until var while with");
+  var atoms = {"null": true};
+
+  var isOperatorChar = /[+\-*&%=<>!?|\/]/;
+
+  function tokenBase(stream, state) {
+    var ch = stream.next();
+    if (ch == "#" && state.startOfLine) {
+      stream.skipToEnd();
+      return "meta";
+    }
+    if (ch == '"' || ch == "'") {
+      state.tokenize = tokenString(ch);
+      return state.tokenize(stream, state);
+    }
+    if (ch == "(" && stream.eat("*")) {
+      state.tokenize = tokenComment;
+      return tokenComment(stream, state);
+    }
+    if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
+      return null;
+    }
+    if (/\d/.test(ch)) {
+      stream.eatWhile(/[\w\.]/);
+      return "number";
+    }
+    if (ch == "/") {
+      if (stream.eat("/")) {
+        stream.skipToEnd();
+        return "comment";
+      }
+    }
+    if (isOperatorChar.test(ch)) {
+      stream.eatWhile(isOperatorChar);
+      return "operator";
+    }
+    stream.eatWhile(/[\w\$_]/);
+    var cur = stream.current();
+    if (keywords.propertyIsEnumerable(cur)) return "keyword";
+    if (atoms.propertyIsEnumerable(cur)) return "atom";
+    return "variable";
+  }
+
+  function tokenString(quote) {
+    return function(stream, state) {
+      var escaped = false, next, end = false;
+      while ((next = stream.next()) != null) {
+        if (next == quote && !escaped) {end = true; break;}
+        escaped = !escaped && next == "\\";
+      }
+      if (end || !escaped) state.tokenize = null;
+      return "string";
+    };
+  }
+
+  function tokenComment(stream, state) {
+    var maybeEnd = false, ch;
+    while (ch = stream.next()) {
+      if (ch == ")" && maybeEnd) {
+        state.tokenize = null;
+        break;
+      }
+      maybeEnd = (ch == "*");
+    }
+    return "comment";
+  }
+
+  // Interface
+
+  return {
+    startState: function() {
+      return {tokenize: null};
+    },
+
+    token: function(stream, state) {
+      if (stream.eatSpace()) return null;
+      var style = (state.tokenize || tokenBase)(stream, state);
+      if (style == "comment" || style == "meta") return style;
+      return style;
+    },
+
+    electricChars: "{}"
+  };
+});
+
+CodeMirror.defineMIME("text/x-pascal", "pascal");
diff --git a/third-party/codemirror-3.15/mode/perl/LICENSE b/third-party/codemirror-3.15/mode/perl/LICENSE
new file mode 100644 (file)
index 0000000..96f4115
--- /dev/null
@@ -0,0 +1,19 @@
+Copyright (C) 2011 by Sabaca <mail@sabaca.com> under the MIT license.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/third-party/codemirror-3.15/mode/perl/index.html b/third-party/codemirror-3.15/mode/perl/index.html
new file mode 100644 (file)
index 0000000..13c7af6
--- /dev/null
@@ -0,0 +1,62 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Perl mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="perl.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: Perl mode</h1>
+
+<div><textarea id="code" name="code">
+#!/usr/bin/perl
+
+use Something qw(func1 func2);
+
+# strings
+my $s1 = qq'single line';
+our $s2 = q(multi-
+              line);
+
+=item Something
+       Example.
+=cut
+
+my $html=<<'HTML'
+<html>
+<title>hi!</title>
+</html>
+HTML
+
+print "first,".join(',', 'second', qq~third~);
+
+if($s1 =~ m[(?<!\s)(l.ne)\z]o) {
+       $h->{$1}=$$.' predefined variables';
+       $s2 =~ s/\-line//ox;
+       $s1 =~ s[
+                 line ]
+               [
+                 block
+               ]ox;
+}
+
+1; # numbers and comments
+
+__END__
+something...
+
+</textarea></div>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-perl</code>.</p>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/perl/perl.js b/third-party/codemirror-3.15/mode/perl/perl.js
new file mode 100644 (file)
index 0000000..5954b1a
--- /dev/null
@@ -0,0 +1,816 @@
+// CodeMirror2 mode/perl/perl.js (text/x-perl) beta 0.10 (2011-11-08)
+// This is a part of CodeMirror from https://github.com/sabaca/CodeMirror_mode_perl (mail@sabaca.com)
+CodeMirror.defineMode("perl",function(){
+        // http://perldoc.perl.org
+        var PERL={                                      //   null - magic touch
+                                                        //   1 - keyword
+                                                        //   2 - def
+                                                        //   3 - atom
+                                                        //   4 - operator
+                                                        //   5 - variable-2 (predefined)
+                                                        //   [x,y] - x=1,2,3; y=must be defined if x{...}
+                                                //      PERL operators
+                '->'                            :   4,
+                '++'                            :   4,
+                '--'                            :   4,
+                '**'                            :   4,
+                                                        //   ! ~ \ and unary + and -
+                '=~'                            :   4,
+                '!~'                            :   4,
+                '*'                             :   4,
+                '/'                             :   4,
+                '%'                             :   4,
+                'x'                             :   4,
+                '+'                             :   4,
+                '-'                             :   4,
+                '.'                             :   4,
+                '<<'                            :   4,
+                '>>'                            :   4,
+                                                        //   named unary operators
+                '<'                             :   4,
+                '>'                             :   4,
+                '<='                            :   4,
+                '>='                            :   4,
+                'lt'                            :   4,
+                'gt'                            :   4,
+                'le'                            :   4,
+                'ge'                            :   4,
+                '=='                            :   4,
+                '!='                            :   4,
+                '<=>'                           :   4,
+                'eq'                            :   4,
+                'ne'                            :   4,
+                'cmp'                           :   4,
+                '~~'                            :   4,
+                '&'                             :   4,
+                '|'                             :   4,
+                '^'                             :   4,
+                '&&'                            :   4,
+                '||'                            :   4,
+                '//'                            :   4,
+                '..'                            :   4,
+                '...'                           :   4,
+                '?'                             :   4,
+                ':'                             :   4,
+                '='                             :   4,
+                '+='                            :   4,
+                '-='                            :   4,
+                '*='                            :   4,  //   etc. ???
+                ','                             :   4,
+                '=>'                            :   4,
+                '::'                            :   4,
+                                                        //   list operators (rightward)
+                'not'                           :   4,
+                'and'                           :   4,
+                'or'                            :   4,
+                'xor'                           :   4,
+                                                //      PERL predefined variables (I know, what this is a paranoid idea, but may be needed for people, who learn PERL, and for me as well, ...and may be for you?;)
+                'BEGIN'                         :   [5,1],
+                'END'                           :   [5,1],
+                'PRINT'                         :   [5,1],
+                'PRINTF'                        :   [5,1],
+                'GETC'                          :   [5,1],
+                'READ'                          :   [5,1],
+                'READLINE'                      :   [5,1],
+                'DESTROY'                       :   [5,1],
+                'TIE'                           :   [5,1],
+                'TIEHANDLE'                     :   [5,1],
+                'UNTIE'                         :   [5,1],
+                'STDIN'                         :    5,
+                'STDIN_TOP'                     :    5,
+                'STDOUT'                        :    5,
+                'STDOUT_TOP'                    :    5,
+                'STDERR'                        :    5,
+                'STDERR_TOP'                    :    5,
+                '$ARG'                          :    5,
+                '$_'                            :    5,
+                '@ARG'                          :    5,
+                '@_'                            :    5,
+                '$LIST_SEPARATOR'               :    5,
+                '$"'                            :    5,
+                '$PROCESS_ID'                   :    5,
+                '$PID'                          :    5,
+                '$$'                            :    5,
+                '$REAL_GROUP_ID'                :    5,
+                '$GID'                          :    5,
+                '$('                            :    5,
+                '$EFFECTIVE_GROUP_ID'           :    5,
+                '$EGID'                         :    5,
+                '$)'                            :    5,
+                '$PROGRAM_NAME'                 :    5,
+                '$0'                            :    5,
+                '$SUBSCRIPT_SEPARATOR'          :    5,
+                '$SUBSEP'                       :    5,
+                '$;'                            :    5,
+                '$REAL_USER_ID'                 :    5,
+                '$UID'                          :    5,
+                '$<'                            :    5,
+                '$EFFECTIVE_USER_ID'            :    5,
+                '$EUID'                         :    5,
+                '$>'                            :    5,
+                '$a'                            :    5,
+                '$b'                            :    5,
+                '$COMPILING'                    :    5,
+                '$^C'                           :    5,
+                '$DEBUGGING'                    :    5,
+                '$^D'                           :    5,
+                '${^ENCODING}'                  :    5,
+                '$ENV'                          :    5,
+                '%ENV'                          :    5,
+                '$SYSTEM_FD_MAX'                :    5,
+                '$^F'                           :    5,
+                '@F'                            :    5,
+                '${^GLOBAL_PHASE}'              :    5,
+                '$^H'                           :    5,
+                '%^H'                           :    5,
+                '@INC'                          :    5,
+                '%INC'                          :    5,
+                '$INPLACE_EDIT'                 :    5,
+                '$^I'                           :    5,
+                '$^M'                           :    5,
+                '$OSNAME'                       :    5,
+                '$^O'                           :    5,
+                '${^OPEN}'                      :    5,
+                '$PERLDB'                       :    5,
+                '$^P'                           :    5,
+                '$SIG'                          :    5,
+                '%SIG'                          :    5,
+                '$BASETIME'                     :    5,
+                '$^T'                           :    5,
+                '${^TAINT}'                     :    5,
+                '${^UNICODE}'                   :    5,
+                '${^UTF8CACHE}'                 :    5,
+                '${^UTF8LOCALE}'                :    5,
+                '$PERL_VERSION'                 :    5,
+                '$^V'                           :    5,
+                '${^WIN32_SLOPPY_STAT}'         :    5,
+                '$EXECUTABLE_NAME'              :    5,
+                '$^X'                           :    5,
+                '$1'                            :    5, // - regexp $1, $2...
+                '$MATCH'                        :    5,
+                '$&'                            :    5,
+                '${^MATCH}'                     :    5,
+                '$PREMATCH'                     :    5,
+                '$`'                            :    5,
+                '${^PREMATCH}'                  :    5,
+                '$POSTMATCH'                    :    5,
+                "$'"                            :    5,
+                '${^POSTMATCH}'                 :    5,
+                '$LAST_PAREN_MATCH'             :    5,
+                '$+'                            :    5,
+                '$LAST_SUBMATCH_RESULT'         :    5,
+                '$^N'                           :    5,
+                '@LAST_MATCH_END'               :    5,
+                '@+'                            :    5,
+                '%LAST_PAREN_MATCH'             :    5,
+                '%+'                            :    5,
+                '@LAST_MATCH_START'             :    5,
+                '@-'                            :    5,
+                '%LAST_MATCH_START'             :    5,
+                '%-'                            :    5,
+                '$LAST_REGEXP_CODE_RESULT'      :    5,
+                '$^R'                           :    5,
+                '${^RE_DEBUG_FLAGS}'            :    5,
+                '${^RE_TRIE_MAXBUF}'            :    5,
+                '$ARGV'                         :    5,
+                '@ARGV'                         :    5,
+                'ARGV'                          :    5,
+                'ARGVOUT'                       :    5,
+                '$OUTPUT_FIELD_SEPARATOR'       :    5,
+                '$OFS'                          :    5,
+                '$,'                            :    5,
+                '$INPUT_LINE_NUMBER'            :    5,
+                '$NR'                           :    5,
+                '$.'                            :    5,
+                '$INPUT_RECORD_SEPARATOR'       :    5,
+                '$RS'                           :    5,
+                '$/'                            :    5,
+                '$OUTPUT_RECORD_SEPARATOR'      :    5,
+                '$ORS'                          :    5,
+                '$\\'                           :    5,
+                '$OUTPUT_AUTOFLUSH'             :    5,
+                '$|'                            :    5,
+                '$ACCUMULATOR'                  :    5,
+                '$^A'                           :    5,
+                '$FORMAT_FORMFEED'              :    5,
+                '$^L'                           :    5,
+                '$FORMAT_PAGE_NUMBER'           :    5,
+                '$%'                            :    5,
+                '$FORMAT_LINES_LEFT'            :    5,
+                '$-'                            :    5,
+                '$FORMAT_LINE_BREAK_CHARACTERS' :    5,
+                '$:'                            :    5,
+                '$FORMAT_LINES_PER_PAGE'        :    5,
+                '$='                            :    5,
+                '$FORMAT_TOP_NAME'              :    5,
+                '$^'                            :    5,
+                '$FORMAT_NAME'                  :    5,
+                '$~'                            :    5,
+                '${^CHILD_ERROR_NATIVE}'        :    5,
+                '$EXTENDED_OS_ERROR'            :    5,
+                '$^E'                           :    5,
+                '$EXCEPTIONS_BEING_CAUGHT'      :    5,
+                '$^S'                           :    5,
+                '$WARNING'                      :    5,
+                '$^W'                           :    5,
+                '${^WARNING_BITS}'              :    5,
+                '$OS_ERROR'                     :    5,
+                '$ERRNO'                        :    5,
+                '$!'                            :    5,
+                '%OS_ERROR'                     :    5,
+                '%ERRNO'                        :    5,
+                '%!'                            :    5,
+                '$CHILD_ERROR'                  :    5,
+                '$?'                            :    5,
+                '$EVAL_ERROR'                   :    5,
+                '$@'                            :    5,
+                '$OFMT'                         :    5,
+                '$#'                            :    5,
+                '$*'                            :    5,
+                '$ARRAY_BASE'                   :    5,
+                '$['                            :    5,
+                '$OLD_PERL_VERSION'             :    5,
+                '$]'                            :    5,
+                                                //      PERL blocks
+                'if'                            :[1,1],
+                elsif                           :[1,1],
+                'else'                          :[1,1],
+                'while'                         :[1,1],
+                unless                          :[1,1],
+                'for'                           :[1,1],
+                foreach                         :[1,1],
+                                                //      PERL functions
+                'abs'                           :1,     // - absolute value function
+                accept                          :1,     // - accept an incoming socket connect
+                alarm                           :1,     // - schedule a SIGALRM
+                'atan2'                         :1,     // - arctangent of Y/X in the range -PI to PI
+                bind                            :1,     // - binds an address to a socket
+                binmode                         :1,     // - prepare binary files for I/O
+                bless                           :1,     // - create an object
+                bootstrap                       :1,     //
+                'break'                         :1,     // - break out of a "given" block
+                caller                          :1,     // - get context of the current subroutine call
+                chdir                           :1,     // - change your current working directory
+                chmod                           :1,     // - changes the permissions on a list of files
+                chomp                           :1,     // - remove a trailing record separator from a string
+                chop                            :1,     // - remove the last character from a string
+                chown                           :1,     // - change the owership on a list of files
+                chr                             :1,     // - get character this number represents
+                chroot                          :1,     // - make directory new root for path lookups
+                close                           :1,     // - close file (or pipe or socket) handle
+                closedir                        :1,     // - close directory handle
+                connect                         :1,     // - connect to a remote socket
+                'continue'                      :[1,1], // - optional trailing block in a while or foreach
+                'cos'                           :1,     // - cosine function
+                crypt                           :1,     // - one-way passwd-style encryption
+                dbmclose                        :1,     // - breaks binding on a tied dbm file
+                dbmopen                         :1,     // - create binding on a tied dbm file
+                'default'                       :1,     //
+                defined                         :1,     // - test whether a value, variable, or function is defined
+                'delete'                        :1,     // - deletes a value from a hash
+                die                             :1,     // - raise an exception or bail out
+                'do'                            :1,     // - turn a BLOCK into a TERM
+                dump                            :1,     // - create an immediate core dump
+                each                            :1,     // - retrieve the next key/value pair from a hash
+                endgrent                        :1,     // - be done using group file
+                endhostent                      :1,     // - be done using hosts file
+                endnetent                       :1,     // - be done using networks file
+                endprotoent                     :1,     // - be done using protocols file
+                endpwent                        :1,     // - be done using passwd file
+                endservent                      :1,     // - be done using services file
+                eof                             :1,     // - test a filehandle for its end
+                'eval'                          :1,     // - catch exceptions or compile and run code
+                'exec'                          :1,     // - abandon this program to run another
+                exists                          :1,     // - test whether a hash key is present
+                exit                            :1,     // - terminate this program
+                'exp'                           :1,     // - raise I to a power
+                fcntl                           :1,     // - file control system call
+                fileno                          :1,     // - return file descriptor from filehandle
+                flock                           :1,     // - lock an entire file with an advisory lock
+                fork                            :1,     // - create a new process just like this one
+                format                          :1,     // - declare a picture format with use by the write() function
+                formline                        :1,     // - internal function used for formats
+                getc                            :1,     // - get the next character from the filehandle
+                getgrent                        :1,     // - get next group record
+                getgrgid                        :1,     // - get group record given group user ID
+                getgrnam                        :1,     // - get group record given group name
+                gethostbyaddr                   :1,     // - get host record given its address
+                gethostbyname                   :1,     // - get host record given name
+                gethostent                      :1,     // - get next hosts record
+                getlogin                        :1,     // - return who logged in at this tty
+                getnetbyaddr                    :1,     // - get network record given its address
+                getnetbyname                    :1,     // - get networks record given name
+                getnetent                       :1,     // - get next networks record
+                getpeername                     :1,     // - find the other end of a socket connection
+                getpgrp                         :1,     // - get process group
+                getppid                         :1,     // - get parent process ID
+                getpriority                     :1,     // - get current nice value
+                getprotobyname                  :1,     // - get protocol record given name
+                getprotobynumber                :1,     // - get protocol record numeric protocol
+                getprotoent                     :1,     // - get next protocols record
+                getpwent                        :1,     // - get next passwd record
+                getpwnam                        :1,     // - get passwd record given user login name
+                getpwuid                        :1,     // - get passwd record given user ID
+                getservbyname                   :1,     // - get services record given its name
+                getservbyport                   :1,     // - get services record given numeric port
+                getservent                      :1,     // - get next services record
+                getsockname                     :1,     // - retrieve the sockaddr for a given socket
+                getsockopt                      :1,     // - get socket options on a given socket
+                given                           :1,     //
+                glob                            :1,     // - expand filenames using wildcards
+                gmtime                          :1,     // - convert UNIX time into record or string using Greenwich time
+                'goto'                          :1,     // - create spaghetti code
+                grep                            :1,     // - locate elements in a list test true against a given criterion
+                hex                             :1,     // - convert a string to a hexadecimal number
+                'import'                        :1,     // - patch a module's namespace into your own
+                index                           :1,     // - find a substring within a string
+                'int'                           :1,     // - get the integer portion of a number
+                ioctl                           :1,     // - system-dependent device control system call
+                'join'                          :1,     // - join a list into a string using a separator
+                keys                            :1,     // - retrieve list of indices from a hash
+                kill                            :1,     // - send a signal to a process or process group
+                last                            :1,     // - exit a block prematurely
+                lc                              :1,     // - return lower-case version of a string
+                lcfirst                         :1,     // - return a string with just the next letter in lower case
+                length                          :1,     // - return the number of bytes in a string
+                'link'                          :1,     // - create a hard link in the filesytem
+                listen                          :1,     // - register your socket as a server
+                local                           : 2,    // - create a temporary value for a global variable (dynamic scoping)
+                localtime                       :1,     // - convert UNIX time into record or string using local time
+                lock                            :1,     // - get a thread lock on a variable, subroutine, or method
+                'log'                           :1,     // - retrieve the natural logarithm for a number
+                lstat                           :1,     // - stat a symbolic link
+                m                               :null,  // - match a string with a regular expression pattern
+                map                             :1,     // - apply a change to a list to get back a new list with the changes
+                mkdir                           :1,     // - create a directory
+                msgctl                          :1,     // - SysV IPC message control operations
+                msgget                          :1,     // - get SysV IPC message queue
+                msgrcv                          :1,     // - receive a SysV IPC message from a message queue
+                msgsnd                          :1,     // - send a SysV IPC message to a message queue
+                my                              : 2,    // - declare and assign a local variable (lexical scoping)
+                'new'                           :1,     //
+                next                            :1,     // - iterate a block prematurely
+                no                              :1,     // - unimport some module symbols or semantics at compile time
+                oct                             :1,     // - convert a string to an octal number
+                open                            :1,     // - open a file, pipe, or descriptor
+                opendir                         :1,     // - open a directory
+                ord                             :1,     // - find a character's numeric representation
+                our                             : 2,    // - declare and assign a package variable (lexical scoping)
+                pack                            :1,     // - convert a list into a binary representation
+                'package'                       :1,     // - declare a separate global namespace
+                pipe                            :1,     // - open a pair of connected filehandles
+                pop                             :1,     // - remove the last element from an array and return it
+                pos                             :1,     // - find or set the offset for the last/next m//g search
+                print                           :1,     // - output a list to a filehandle
+                printf                          :1,     // - output a formatted list to a filehandle
+                prototype                       :1,     // - get the prototype (if any) of a subroutine
+                push                            :1,     // - append one or more elements to an array
+                q                               :null,  // - singly quote a string
+                qq                              :null,  // - doubly quote a string
+                qr                              :null,  // - Compile pattern
+                quotemeta                       :null,  // - quote regular expression magic characters
+                qw                              :null,  // - quote a list of words
+                qx                              :null,  // - backquote quote a string
+                rand                            :1,     // - retrieve the next pseudorandom number
+                read                            :1,     // - fixed-length buffered input from a filehandle
+                readdir                         :1,     // - get a directory from a directory handle
+                readline                        :1,     // - fetch a record from a file
+                readlink                        :1,     // - determine where a symbolic link is pointing
+                readpipe                        :1,     // - execute a system command and collect standard output
+                recv                            :1,     // - receive a message over a Socket
+                redo                            :1,     // - start this loop iteration over again
+                ref                             :1,     // - find out the type of thing being referenced
+                rename                          :1,     // - change a filename
+                require                         :1,     // - load in external functions from a library at runtime
+                reset                           :1,     // - clear all variables of a given name
+                'return'                        :1,     // - get out of a function early
+                reverse                         :1,     // - flip a string or a list
+                rewinddir                       :1,     // - reset directory handle
+                rindex                          :1,     // - right-to-left substring search
+                rmdir                           :1,     // - remove a directory
+                s                               :null,  // - replace a pattern with a string
+                say                             :1,     // - print with newline
+                scalar                          :1,     // - force a scalar context
+                seek                            :1,     // - reposition file pointer for random-access I/O
+                seekdir                         :1,     // - reposition directory pointer
+                select                          :1,     // - reset default output or do I/O multiplexing
+                semctl                          :1,     // - SysV semaphore control operations
+                semget                          :1,     // - get set of SysV semaphores
+                semop                           :1,     // - SysV semaphore operations
+                send                            :1,     // - send a message over a socket
+                setgrent                        :1,     // - prepare group file for use
+                sethostent                      :1,     // - prepare hosts file for use
+                setnetent                       :1,     // - prepare networks file for use
+                setpgrp                         :1,     // - set the process group of a process
+                setpriority                     :1,     // - set a process's nice value
+                setprotoent                     :1,     // - prepare protocols file for use
+                setpwent                        :1,     // - prepare passwd file for use
+                setservent                      :1,     // - prepare services file for use
+                setsockopt                      :1,     // - set some socket options
+                shift                           :1,     // - remove the first element of an array, and return it
+                shmctl                          :1,     // - SysV shared memory operations
+                shmget                          :1,     // - get SysV shared memory segment identifier
+                shmread                         :1,     // - read SysV shared memory
+                shmwrite                        :1,     // - write SysV shared memory
+                shutdown                        :1,     // - close down just half of a socket connection
+                'sin'                           :1,     // - return the sine of a number
+                sleep                           :1,     // - block for some number of seconds
+                socket                          :1,     // - create a socket
+                socketpair                      :1,     // - create a pair of sockets
+                'sort'                          :1,     // - sort a list of values
+                splice                          :1,     // - add or remove elements anywhere in an array
+                'split'                         :1,     // - split up a string using a regexp delimiter
+                sprintf                         :1,     // - formatted print into a string
+                'sqrt'                          :1,     // - square root function
+                srand                           :1,     // - seed the random number generator
+                stat                            :1,     // - get a file's status information
+                state                           :1,     // - declare and assign a state variable (persistent lexical scoping)
+                study                           :1,     // - optimize input data for repeated searches
+                'sub'                           :1,     // - declare a subroutine, possibly anonymously
+                'substr'                        :1,     // - get or alter a portion of a stirng
+                symlink                         :1,     // - create a symbolic link to a file
+                syscall                         :1,     // - execute an arbitrary system call
+                sysopen                         :1,     // - open a file, pipe, or descriptor
+                sysread                         :1,     // - fixed-length unbuffered input from a filehandle
+                sysseek                         :1,     // - position I/O pointer on handle used with sysread and syswrite
+                system                          :1,     // - run a separate program
+                syswrite                        :1,     // - fixed-length unbuffered output to a filehandle
+                tell                            :1,     // - get current seekpointer on a filehandle
+                telldir                         :1,     // - get current seekpointer on a directory handle
+                tie                             :1,     // - bind a variable to an object class
+                tied                            :1,     // - get a reference to the object underlying a tied variable
+                time                            :1,     // - return number of seconds since 1970
+                times                           :1,     // - return elapsed time for self and child processes
+                tr                              :null,  // - transliterate a string
+                truncate                        :1,     // - shorten a file
+                uc                              :1,     // - return upper-case version of a string
+                ucfirst                         :1,     // - return a string with just the next letter in upper case
+                umask                           :1,     // - set file creation mode mask
+                undef                           :1,     // - remove a variable or function definition
+                unlink                          :1,     // - remove one link to a file
+                unpack                          :1,     // - convert binary structure into normal perl variables
+                unshift                         :1,     // - prepend more elements to the beginning of a list
+                untie                           :1,     // - break a tie binding to a variable
+                use                             :1,     // - load in a module at compile time
+                utime                           :1,     // - set a file's last access and modify times
+                values                          :1,     // - return a list of the values in a hash
+                vec                             :1,     // - test or set particular bits in a string
+                wait                            :1,     // - wait for any child process to die
+                waitpid                         :1,     // - wait for a particular child process to die
+                wantarray                       :1,     // - get void vs scalar vs list context of current subroutine call
+                warn                            :1,     // - print debugging info
+                when                            :1,     //
+                write                           :1,     // - print a picture record
+                y                               :null}; // - transliterate a string
+
+        var RXstyle="string-2";
+        var RXmodifiers=/[goseximacplud]/;              // NOTE: "m", "s", "y" and "tr" need to correct real modifiers for each regexp type
+
+        function tokenChain(stream,state,chain,style,tail){     // NOTE: chain.length > 2 is not working now (it's for s[...][...]geos;)
+                state.chain=null;                               //                                                          12   3tail
+                state.style=null;
+                state.tail=null;
+                state.tokenize=function(stream,state){
+                        var e=false,c,i=0;
+                        while(c=stream.next()){
+                                if(c===chain[i]&&!e){
+                                        if(chain[++i]!==undefined){
+                                                state.chain=chain[i];
+                                                state.style=style;
+                                                state.tail=tail;}
+                                        else if(tail)
+                                                stream.eatWhile(tail);
+                                        state.tokenize=tokenPerl;
+                                        return style;}
+                                e=!e&&c=="\\";}
+                        return style;};
+                return state.tokenize(stream,state);}
+
+        function tokenSOMETHING(stream,state,string){
+                state.tokenize=function(stream,state){
+                        if(stream.string==string)
+                                state.tokenize=tokenPerl;
+                        stream.skipToEnd();
+                        return "string";};
+                return state.tokenize(stream,state);}
+
+        function tokenPerl(stream,state){
+                if(stream.eatSpace())
+                        return null;
+                if(state.chain)
+                        return tokenChain(stream,state,state.chain,state.style,state.tail);
+                if(stream.match(/^\-?[\d\.]/,false))
+                        if(stream.match(/^(\-?(\d*\.\d+(e[+-]?\d+)?|\d+\.\d*)|0x[\da-fA-F]+|0b[01]+|\d+(e[+-]?\d+)?)/))
+                                return 'number';
+                if(stream.match(/^<<(?=\w)/)){                  // NOTE: <<SOMETHING\n...\nSOMETHING\n
+                        stream.eatWhile(/\w/);
+                        return tokenSOMETHING(stream,state,stream.current().substr(2));}
+                if(stream.sol()&&stream.match(/^\=item(?!\w)/)){// NOTE: \n=item...\n=cut\n
+                        return tokenSOMETHING(stream,state,'=cut');}
+                var ch=stream.next();
+                if(ch=='"'||ch=="'"){                           // NOTE: ' or " or <<'SOMETHING'\n...\nSOMETHING\n or <<"SOMETHING"\n...\nSOMETHING\n
+                        if(stream.prefix(3)=="<<"+ch){
+                                var p=stream.pos;
+                                stream.eatWhile(/\w/);
+                                var n=stream.current().substr(1);
+                                if(n&&stream.eat(ch))
+                                        return tokenSOMETHING(stream,state,n);
+                                stream.pos=p;}
+                        return tokenChain(stream,state,[ch],"string");}
+                if(ch=="q"){
+                        var c=stream.look(-2);
+                        if(!(c&&/\w/.test(c))){
+                                c=stream.look(0);
+                                if(c=="x"){
+                                        c=stream.look(1);
+                                        if(c=="("){
+                                                stream.eatSuffix(2);
+                                                return tokenChain(stream,state,[")"],RXstyle,RXmodifiers);}
+                                        if(c=="["){
+                                                stream.eatSuffix(2);
+                                                return tokenChain(stream,state,["]"],RXstyle,RXmodifiers);}
+                                        if(c=="{"){
+                                                stream.eatSuffix(2);
+                                                return tokenChain(stream,state,["}"],RXstyle,RXmodifiers);}
+                                        if(c=="<"){
+                                                stream.eatSuffix(2);
+                                                return tokenChain(stream,state,[">"],RXstyle,RXmodifiers);}
+                                        if(/[\^'"!~\/]/.test(c)){
+                                                stream.eatSuffix(1);
+                                                return tokenChain(stream,state,[stream.eat(c)],RXstyle,RXmodifiers);}}
+                                else if(c=="q"){
+                                        c=stream.look(1);
+                                        if(c=="("){
+                                                stream.eatSuffix(2);
+                                                return tokenChain(stream,state,[")"],"string");}
+                                        if(c=="["){
+                                                stream.eatSuffix(2);
+                                                return tokenChain(stream,state,["]"],"string");}
+                                        if(c=="{"){
+stream.eatSuffix(2);
+                                                return tokenChain(stream,state,["}"],"string");}
+                                        if(c=="<"){
+                                                stream.eatSuffix(2);
+                                                return tokenChain(stream,state,[">"],"string");}
+                                        if(/[\^'"!~\/]/.test(c)){
+                                                stream.eatSuffix(1);
+                                                return tokenChain(stream,state,[stream.eat(c)],"string");}}
+                                else if(c=="w"){
+                                        c=stream.look(1);
+                                        if(c=="("){
+                                                stream.eatSuffix(2);
+                                                return tokenChain(stream,state,[")"],"bracket");}
+                                        if(c=="["){
+                                                stream.eatSuffix(2);
+                                                return tokenChain(stream,state,["]"],"bracket");}
+                                        if(c=="{"){
+                                                stream.eatSuffix(2);
+                                                return tokenChain(stream,state,["}"],"bracket");}
+                                        if(c=="<"){
+                                                stream.eatSuffix(2);
+                                                return tokenChain(stream,state,[">"],"bracket");}
+                                        if(/[\^'"!~\/]/.test(c)){
+                                                stream.eatSuffix(1);
+                                                return tokenChain(stream,state,[stream.eat(c)],"bracket");}}
+                                else if(c=="r"){
+                                        c=stream.look(1);
+                                        if(c=="("){
+                                                stream.eatSuffix(2);
+                                                return tokenChain(stream,state,[")"],RXstyle,RXmodifiers);}
+                                        if(c=="["){
+                                                stream.eatSuffix(2);
+                                                return tokenChain(stream,state,["]"],RXstyle,RXmodifiers);}
+                                        if(c=="{"){
+                                                stream.eatSuffix(2);
+                                                return tokenChain(stream,state,["}"],RXstyle,RXmodifiers);}
+                                        if(c=="<"){
+                                                stream.eatSuffix(2);
+                                                return tokenChain(stream,state,[">"],RXstyle,RXmodifiers);}
+                                        if(/[\^'"!~\/]/.test(c)){
+                                                stream.eatSuffix(1);
+                                                return tokenChain(stream,state,[stream.eat(c)],RXstyle,RXmodifiers);}}
+                                else if(/[\^'"!~\/(\[{<]/.test(c)){
+                                        if(c=="("){
+                                                stream.eatSuffix(1);
+                                                return tokenChain(stream,state,[")"],"string");}
+                                        if(c=="["){
+                                                stream.eatSuffix(1);
+                                                return tokenChain(stream,state,["]"],"string");}
+                                        if(c=="{"){
+                                                stream.eatSuffix(1);
+                                                return tokenChain(stream,state,["}"],"string");}
+                                        if(c=="<"){
+                                                stream.eatSuffix(1);
+                                                return tokenChain(stream,state,[">"],"string");}
+                                        if(/[\^'"!~\/]/.test(c)){
+                                                return tokenChain(stream,state,[stream.eat(c)],"string");}}}}
+                if(ch=="m"){
+                        var c=stream.look(-2);
+                        if(!(c&&/\w/.test(c))){
+                                c=stream.eat(/[(\[{<\^'"!~\/]/);
+                                if(c){
+                                        if(/[\^'"!~\/]/.test(c)){
+                                                return tokenChain(stream,state,[c],RXstyle,RXmodifiers);}
+                                        if(c=="("){
+                                                return tokenChain(stream,state,[")"],RXstyle,RXmodifiers);}
+                                        if(c=="["){
+                                                return tokenChain(stream,state,["]"],RXstyle,RXmodifiers);}
+                                        if(c=="{"){
+                                                return tokenChain(stream,state,["}"],RXstyle,RXmodifiers);}
+                                        if(c=="<"){
+                                                return tokenChain(stream,state,[">"],RXstyle,RXmodifiers);}}}}
+                if(ch=="s"){
+                        var c=/[\/>\]})\w]/.test(stream.look(-2));
+                        if(!c){
+                                c=stream.eat(/[(\[{<\^'"!~\/]/);
+                                if(c){
+                                        if(c=="[")
+                                                return tokenChain(stream,state,["]","]"],RXstyle,RXmodifiers);
+                                        if(c=="{")
+                                                return tokenChain(stream,state,["}","}"],RXstyle,RXmodifiers);
+                                        if(c=="<")
+                                                return tokenChain(stream,state,[">",">"],RXstyle,RXmodifiers);
+                                        if(c=="(")
+                                                return tokenChain(stream,state,[")",")"],RXstyle,RXmodifiers);
+                                        return tokenChain(stream,state,[c,c],RXstyle,RXmodifiers);}}}
+                if(ch=="y"){
+                        var c=/[\/>\]})\w]/.test(stream.look(-2));
+                        if(!c){
+                                c=stream.eat(/[(\[{<\^'"!~\/]/);
+                                if(c){
+                                        if(c=="[")
+                                                return tokenChain(stream,state,["]","]"],RXstyle,RXmodifiers);
+                                        if(c=="{")
+                                                return tokenChain(stream,state,["}","}"],RXstyle,RXmodifiers);
+                                        if(c=="<")
+                                                return tokenChain(stream,state,[">",">"],RXstyle,RXmodifiers);
+                                        if(c=="(")
+                                                return tokenChain(stream,state,[")",")"],RXstyle,RXmodifiers);
+                                        return tokenChain(stream,state,[c,c],RXstyle,RXmodifiers);}}}
+                if(ch=="t"){
+                        var c=/[\/>\]})\w]/.test(stream.look(-2));
+                        if(!c){
+                                c=stream.eat("r");if(c){
+                                c=stream.eat(/[(\[{<\^'"!~\/]/);
+                                if(c){
+                                        if(c=="[")
+                                                return tokenChain(stream,state,["]","]"],RXstyle,RXmodifiers);
+                                        if(c=="{")
+                                                return tokenChain(stream,state,["}","}"],RXstyle,RXmodifiers);
+                                        if(c=="<")
+                                                return tokenChain(stream,state,[">",">"],RXstyle,RXmodifiers);
+                                        if(c=="(")
+                                                return tokenChain(stream,state,[")",")"],RXstyle,RXmodifiers);
+                                        return tokenChain(stream,state,[c,c],RXstyle,RXmodifiers);}}}}
+                if(ch=="`"){
+                        return tokenChain(stream,state,[ch],"variable-2");}
+                if(ch=="/"){
+                        if(!/~\s*$/.test(stream.prefix()))
+                                return "operator";
+                        else
+                                return tokenChain(stream,state,[ch],RXstyle,RXmodifiers);}
+                if(ch=="$"){
+                        var p=stream.pos;
+                        if(stream.eatWhile(/\d/)||stream.eat("{")&&stream.eatWhile(/\d/)&&stream.eat("}"))
+                                return "variable-2";
+                        else
+                                stream.pos=p;}
+                if(/[$@%]/.test(ch)){
+                        var p=stream.pos;
+                        if(stream.eat("^")&&stream.eat(/[A-Z]/)||!/[@$%&]/.test(stream.look(-2))&&stream.eat(/[=|\\\-#?@;:&`~\^!\[\]*'"$+.,\/<>()]/)){
+                                var c=stream.current();
+                                if(PERL[c])
+                                        return "variable-2";}
+                        stream.pos=p;}
+                if(/[$@%&]/.test(ch)){
+                        if(stream.eatWhile(/[\w$\[\]]/)||stream.eat("{")&&stream.eatWhile(/[\w$\[\]]/)&&stream.eat("}")){
+                                var c=stream.current();
+                                if(PERL[c])
+                                        return "variable-2";
+                                else
+                                        return "variable";}}
+                if(ch=="#"){
+                        if(stream.look(-2)!="$"){
+                                stream.skipToEnd();
+                                return "comment";}}
+                if(/[:+\-\^*$&%@=<>!?|\/~\.]/.test(ch)){
+                        var p=stream.pos;
+                        stream.eatWhile(/[:+\-\^*$&%@=<>!?|\/~\.]/);
+                        if(PERL[stream.current()])
+                                return "operator";
+                        else
+                                stream.pos=p;}
+                if(ch=="_"){
+                        if(stream.pos==1){
+                                if(stream.suffix(6)=="_END__"){
+                                        return tokenChain(stream,state,['\0'],"comment");}
+                                else if(stream.suffix(7)=="_DATA__"){
+                                        return tokenChain(stream,state,['\0'],"variable-2");}
+                                else if(stream.suffix(7)=="_C__"){
+                                        return tokenChain(stream,state,['\0'],"string");}}}
+                if(/\w/.test(ch)){
+                        var p=stream.pos;
+                        if(stream.look(-2)=="{"&&(stream.look(0)=="}"||stream.eatWhile(/\w/)&&stream.look(0)=="}"))
+                                return "string";
+                        else
+                                stream.pos=p;}
+                if(/[A-Z]/.test(ch)){
+                        var l=stream.look(-2);
+                        var p=stream.pos;
+                        stream.eatWhile(/[A-Z_]/);
+                        if(/[\da-z]/.test(stream.look(0))){
+                                stream.pos=p;}
+                        else{
+                                var c=PERL[stream.current()];
+                                if(!c)
+                                        return "meta";
+                                if(c[1])
+                                        c=c[0];
+                                if(l!=":"){
+                                        if(c==1)
+                                                return "keyword";
+                                        else if(c==2)
+                                                return "def";
+                                        else if(c==3)
+                                                return "atom";
+                                        else if(c==4)
+                                                return "operator";
+                                        else if(c==5)
+                                                return "variable-2";
+                                        else
+                                                return "meta";}
+                                else
+                                        return "meta";}}
+                if(/[a-zA-Z_]/.test(ch)){
+                        var l=stream.look(-2);
+                        stream.eatWhile(/\w/);
+                        var c=PERL[stream.current()];
+                        if(!c)
+                                return "meta";
+                        if(c[1])
+                                c=c[0];
+                        if(l!=":"){
+                                if(c==1)
+                                        return "keyword";
+                                else if(c==2)
+                                        return "def";
+                                else if(c==3)
+                                        return "atom";
+                                else if(c==4)
+                                        return "operator";
+                                else if(c==5)
+                                        return "variable-2";
+                                else
+                                        return "meta";}
+                        else
+                                return "meta";}
+                return null;}
+
+        return{
+                startState:function(){
+                        return{
+                                tokenize:tokenPerl,
+                                chain:null,
+                                style:null,
+                                tail:null};},
+                token:function(stream,state){
+                        return (state.tokenize||tokenPerl)(stream,state);},
+                electricChars:"{}"};});
+
+CodeMirror.defineMIME("text/x-perl", "perl");
+
+// it's like "peek", but need for look-ahead or look-behind if index < 0
+CodeMirror.StringStream.prototype.look=function(c){
+        return this.string.charAt(this.pos+(c||0));};
+
+// return a part of prefix of current stream from current position
+CodeMirror.StringStream.prototype.prefix=function(c){
+        if(c){
+                var x=this.pos-c;
+                return this.string.substr((x>=0?x:0),c);}
+        else{
+                return this.string.substr(0,this.pos-1);}};
+
+// return a part of suffix of current stream from current position
+CodeMirror.StringStream.prototype.suffix=function(c){
+        var y=this.string.length;
+        var x=y-this.pos+1;
+        return this.string.substr(this.pos,(c&&c<y?c:x));};
+
+// return a part of suffix of current stream from current position and change current position
+CodeMirror.StringStream.prototype.nsuffix=function(c){
+        var p=this.pos;
+        var l=c||(this.string.length-this.pos+1);
+        this.pos+=l;
+        return this.string.substr(p,l);};
+
+// eating and vomiting a part of stream from current position
+CodeMirror.StringStream.prototype.eatSuffix=function(c){
+        var x=this.pos+c;
+        var y;
+        if(x<=0)
+                this.pos=0;
+        else if(x>=(y=this.string.length-1))
+                this.pos=y;
+        else
+                this.pos=x;};
diff --git a/third-party/codemirror-3.15/mode/php/index.html b/third-party/codemirror-3.15/mode/php/index.html
new file mode 100644 (file)
index 0000000..3d4c336
--- /dev/null
@@ -0,0 +1,51 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: PHP mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../../addon/edit/matchbrackets.js"></script>
+    <script src="../htmlmixed/htmlmixed.js"></script>
+    <script src="../xml/xml.js"></script>
+    <script src="../javascript/javascript.js"></script>
+    <script src="../css/css.js"></script>
+    <script src="../clike/clike.js"></script>
+    <script src="php.js"></script>
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: PHP mode</h1>
+
+<form><textarea id="code" name="code">
+<?php
+function hello($who) {
+       return "Hello " . $who;
+}
+?>
+<p>The program says <?= hello("World") ?>.</p>
+<script>
+       alert("And here is some JS code"); // also colored
+</script>
+</textarea></form>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        matchBrackets: true,
+        mode: "application/x-httpd-php",
+        indentUnit: 4,
+        indentWithTabs: true,
+        enterMode: "keep",
+        tabMode: "shift"
+      });
+    </script>
+
+    <p>Simple HTML/PHP mode based on
+    the <a href="../clike/">C-like</a> mode. Depends on XML,
+    JavaScript, CSS, HTMLMixed, and C-like modes.</p>
+
+    <p><strong>MIME types defined:</strong> <code>application/x-httpd-php</code> (HTML with PHP code), <code>text/x-php</code> (plain, non-wrapped PHP code).</p>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/php/php.js b/third-party/codemirror-3.15/mode/php/php.js
new file mode 100644 (file)
index 0000000..fa0db5b
--- /dev/null
@@ -0,0 +1,132 @@
+(function() {
+  function keywords(str) {
+    var obj = {}, words = str.split(" ");
+    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
+    return obj;
+  }
+  function heredoc(delim) {
+    return function(stream, state) {
+      if (stream.match(delim)) state.tokenize = null;
+      else stream.skipToEnd();
+      return "string";
+    };
+  }
+  var phpConfig = {
+    name: "clike",
+    keywords: keywords("abstract and array as break case catch class clone const continue declare default " +
+                       "do else elseif enddeclare endfor endforeach endif endswitch endwhile extends final " +
+                       "for foreach function global goto if implements interface instanceof namespace " +
+                       "new or private protected public static switch throw trait try use var while xor " +
+                       "die echo empty exit eval include include_once isset list require require_once return " +
+                       "print unset __halt_compiler self static parent"),
+    blockKeywords: keywords("catch do else elseif for foreach if switch try while"),
+    atoms: keywords("true false null TRUE FALSE NULL __CLASS__ __DIR__ __FILE__ __LINE__ __METHOD__ __FUNCTION__ __NAMESPACE__"),
+    builtin: keywords("func_num_args func_get_arg func_get_args strlen strcmp strncmp strcasecmp strncasecmp each error_reporting define defined trigger_error user_error set_error_handler restore_error_handler get_declared_classes get_loaded_extensions extension_loaded get_extension_funcs debug_backtrace constant bin2hex sleep usleep time mktime gmmktime strftime gmstrftime strtotime date gmdate getdate localtime checkdate flush wordwrap htmlspecialchars htmlentities html_entity_decode md5 md5_file crc32 getimagesize image_type_to_mime_type phpinfo phpversion phpcredits strnatcmp strnatcasecmp substr_count strspn strcspn strtok strtoupper strtolower strpos strrpos strrev hebrev hebrevc nl2br basename dirname pathinfo stripslashes stripcslashes strstr stristr strrchr str_shuffle str_word_count strcoll substr substr_replace quotemeta ucfirst ucwords strtr addslashes addcslashes rtrim str_replace str_repeat count_chars chunk_split trim ltrim strip_tags similar_text explode implode setlocale localeconv parse_str str_pad chop strchr sprintf printf vprintf vsprintf sscanf fscanf parse_url urlencode urldecode rawurlencode rawurldecode readlink linkinfo link unlink exec system escapeshellcmd escapeshellarg passthru shell_exec proc_open proc_close rand srand getrandmax mt_rand mt_srand mt_getrandmax base64_decode base64_encode abs ceil floor round is_finite is_nan is_infinite bindec hexdec octdec decbin decoct dechex base_convert number_format fmod ip2long long2ip getenv putenv getopt microtime gettimeofday getrusage uniqid quoted_printable_decode set_time_limit get_cfg_var magic_quotes_runtime set_magic_quotes_runtime get_magic_quotes_gpc get_magic_quotes_runtime import_request_variables error_log serialize unserialize memory_get_usage var_dump var_export debug_zval_dump print_r highlight_file show_source highlight_string ini_get ini_get_all ini_set ini_alter ini_restore get_include_path set_include_path restore_include_path setcookie header headers_sent connection_aborted connection_status ignore_user_abort parse_ini_file is_uploaded_file move_uploaded_file intval floatval doubleval strval gettype settype is_null is_resource is_bool is_long is_float is_int is_integer is_double is_real is_numeric is_string is_array is_object is_scalar ereg ereg_replace eregi eregi_replace split spliti join sql_regcase dl pclose popen readfile rewind rmdir umask fclose feof fgetc fgets fgetss fread fopen fpassthru ftruncate fstat fseek ftell fflush fwrite fputs mkdir rename copy tempnam tmpfile file file_get_contents stream_select stream_context_create stream_context_set_params stream_context_set_option stream_context_get_options stream_filter_prepend stream_filter_append fgetcsv flock get_meta_tags stream_set_write_buffer set_file_buffer set_socket_blocking stream_set_blocking socket_set_blocking stream_get_meta_data stream_register_wrapper stream_wrapper_register stream_set_timeout socket_set_timeout socket_get_status realpath fnmatch fsockopen pfsockopen pack unpack get_browser crypt opendir closedir chdir getcwd rewinddir readdir dir glob fileatime filectime filegroup fileinode filemtime fileowner fileperms filesize filetype file_exists is_writable is_writeable is_readable is_executable is_file is_dir is_link stat lstat chown touch clearstatcache mail ob_start ob_flush ob_clean ob_end_flush ob_end_clean ob_get_flush ob_get_clean ob_get_length ob_get_level ob_get_status ob_get_contents ob_implicit_flush ob_list_handlers ksort krsort natsort natcasesort asort arsort sort rsort usort uasort uksort shuffle array_walk count end prev next reset current key min max in_array array_search extract compact array_fill range array_multisort array_push array_pop array_shift array_unshift array_splice array_slice array_merge array_merge_recursive array_keys array_values array_count_values array_reverse array_reduce array_pad array_flip array_change_key_case array_rand array_unique array_intersect array_intersect_assoc array_diff array_diff_assoc array_sum array_filter array_map array_chunk array_key_exists pos sizeof key_exists assert assert_options version_compare ftok str_rot13 aggregate session_name session_module_name session_save_path session_id session_regenerate_id session_decode session_register session_unregister session_is_registered session_encode session_start session_destroy session_unset session_set_save_handler session_cache_limiter session_cache_expire session_set_cookie_params session_get_cookie_params session_write_close preg_match preg_match_all preg_replace preg_replace_callback preg_split preg_quote preg_grep overload ctype_alnum ctype_alpha ctype_cntrl ctype_digit ctype_lower ctype_graph ctype_print ctype_punct ctype_space ctype_upper ctype_xdigit virtual apache_request_headers apache_note apache_lookup_uri apache_child_terminate apache_setenv apache_response_headers apache_get_version getallheaders mysql_connect mysql_pconnect mysql_close mysql_select_db mysql_create_db mysql_drop_db mysql_query mysql_unbuffered_query mysql_db_query mysql_list_dbs mysql_list_tables mysql_list_fields mysql_list_processes mysql_error mysql_errno mysql_affected_rows mysql_insert_id mysql_result mysql_num_rows mysql_num_fields mysql_fetch_row mysql_fetch_array mysql_fetch_assoc mysql_fetch_object mysql_data_seek mysql_fetch_lengths mysql_fetch_field mysql_field_seek mysql_free_result mysql_field_name mysql_field_table mysql_field_len mysql_field_type mysql_field_flags mysql_escape_string mysql_real_escape_string mysql_stat mysql_thread_id mysql_client_encoding mysql_get_client_info mysql_get_host_info mysql_get_proto_info mysql_get_server_info mysql_info mysql mysql_fieldname mysql_fieldtable mysql_fieldlen mysql_fieldtype mysql_fieldflags mysql_selectdb mysql_createdb mysql_dropdb mysql_freeresult mysql_numfields mysql_numrows mysql_listdbs mysql_listtables mysql_listfields mysql_db_name mysql_dbname mysql_tablename mysql_table_name pg_connect pg_pconnect pg_close pg_connection_status pg_connection_busy pg_connection_reset pg_host pg_dbname pg_port pg_tty pg_options pg_ping pg_query pg_send_query pg_cancel_query pg_fetch_result pg_fetch_row pg_fetch_assoc pg_fetch_array pg_fetch_object pg_fetch_all pg_affected_rows pg_get_result pg_result_seek pg_result_status pg_free_result pg_last_oid pg_num_rows pg_num_fields pg_field_name pg_field_num pg_field_size pg_field_type pg_field_prtlen pg_field_is_null pg_get_notify pg_get_pid pg_result_error pg_last_error pg_last_notice pg_put_line pg_end_copy pg_copy_to pg_copy_from pg_trace pg_untrace pg_lo_create pg_lo_unlink pg_lo_open pg_lo_close pg_lo_read pg_lo_write pg_lo_read_all pg_lo_import pg_lo_export pg_lo_seek pg_lo_tell pg_escape_string pg_escape_bytea pg_unescape_bytea pg_client_encoding pg_set_client_encoding pg_meta_data pg_convert pg_insert pg_update pg_delete pg_select pg_exec pg_getlastoid pg_cmdtuples pg_errormessage pg_numrows pg_numfields pg_fieldname pg_fieldsize pg_fieldtype pg_fieldnum pg_fieldprtlen pg_fieldisnull pg_freeresult pg_result pg_loreadall pg_locreate pg_lounlink pg_loopen pg_loclose pg_loread pg_lowrite pg_loimport pg_loexport echo print global static exit array empty eval isset unset die include require include_once require_once"),
+    multiLineStrings: true,
+    hooks: {
+      "$": function(stream) {
+        stream.eatWhile(/[\w\$_]/);
+        return "variable-2";
+      },
+      "<": function(stream, state) {
+        if (stream.match(/<</)) {
+          stream.eatWhile(/[\w\.]/);
+          state.tokenize = heredoc(stream.current().slice(3));
+          return state.tokenize(stream, state);
+        }
+        return false;
+      },
+      "#": function(stream) {
+        while (!stream.eol() && !stream.match("?>", false)) stream.next();
+        return "comment";
+      },
+      "/": function(stream) {
+        if (stream.eat("/")) {
+          while (!stream.eol() && !stream.match("?>", false)) stream.next();
+          return "comment";
+        }
+        return false;
+      }
+    }
+  };
+
+  CodeMirror.defineMode("php", function(config, parserConfig) {
+    var htmlMode = CodeMirror.getMode(config, "text/html");
+    var phpMode = CodeMirror.getMode(config, phpConfig);
+
+    function dispatch(stream, state) {
+      var isPHP = state.curMode == phpMode;
+      if (stream.sol() && state.pending != '"') state.pending = null;
+      if (!isPHP) {
+        if (stream.match(/^<\?\w*/)) {
+          state.curMode = phpMode;
+          state.curState = state.php;
+          return "meta";
+        }
+        if (state.pending == '"') {
+          while (!stream.eol() && stream.next() != '"') {}
+          var style = "string";
+        } else if (state.pending && stream.pos < state.pending.end) {
+          stream.pos = state.pending.end;
+          var style = state.pending.style;
+        } else {
+          var style = htmlMode.token(stream, state.curState);
+        }
+        state.pending = null;
+        var cur = stream.current(), openPHP = cur.search(/<\?/);
+        if (openPHP != -1) {
+          if (style == "string" && /\"$/.test(cur) && !/\?>/.test(cur)) state.pending = '"';
+          else state.pending = {end: stream.pos, style: style};
+          stream.backUp(cur.length - openPHP);
+        }
+        return style;
+      } else if (isPHP && state.php.tokenize == null && stream.match("?>")) {
+        state.curMode = htmlMode;
+        state.curState = state.html;
+        return "meta";
+      } else {
+        return phpMode.token(stream, state.curState);
+      }
+    }
+
+    return {
+      startState: function() {
+        var html = CodeMirror.startState(htmlMode), php = CodeMirror.startState(phpMode);
+        return {html: html,
+                php: php,
+                curMode: parserConfig.startOpen ? phpMode : htmlMode,
+                curState: parserConfig.startOpen ? php : html,
+                pending: null};
+      },
+
+      copyState: function(state) {
+        var html = state.html, htmlNew = CodeMirror.copyState(htmlMode, html),
+            php = state.php, phpNew = CodeMirror.copyState(phpMode, php), cur;
+        if (state.curMode == htmlMode) cur = htmlNew;
+        else cur = phpNew;
+        return {html: htmlNew, php: phpNew, curMode: state.curMode, curState: cur,
+                pending: state.pending};
+      },
+
+      token: dispatch,
+
+      indent: function(state, textAfter) {
+        if ((state.curMode != phpMode && /^\s*<\//.test(textAfter)) ||
+            (state.curMode == phpMode && /^\?>/.test(textAfter)))
+          return htmlMode.indent(state.html, textAfter);
+        return state.curMode.indent(state.curState, textAfter);
+      },
+
+      electricChars: "/{}:",
+      blockCommentStart: "/*",
+      blockCommentEnd: "*/",
+      lineComment: "//",
+
+      innerMode: function(state) { return {state: state.curState, mode: state.curMode}; }
+    };
+  }, "htmlmixed", "clike");
+
+  CodeMirror.defineMIME("application/x-httpd-php", "php");
+  CodeMirror.defineMIME("application/x-httpd-php-open", {name: "php", startOpen: true});
+  CodeMirror.defineMIME("text/x-php", phpConfig);
+})();
diff --git a/third-party/codemirror-3.15/mode/pig/index.html b/third-party/codemirror-3.15/mode/pig/index.html
new file mode 100644 (file)
index 0000000..1b0c602
--- /dev/null
@@ -0,0 +1,42 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Pig Latin mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="pig.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style>.CodeMirror {border: 2px inset #dee;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: Pig Latin mode</h1>
+
+<form><textarea id="code" name="code">
+-- Apache Pig (Pig Latin Language) Demo
+/* 
+This is a multiline comment.
+*/
+a = LOAD "\path\to\input" USING PigStorage('\t') AS (x:long, y:chararray, z:bytearray);
+b = GROUP a BY (x,y,3+4);
+c = FOREACH b GENERATE flatten(group) as (x,y), SUM(group.$2) as z;
+STORE c INTO "\path\to\output";
+
+--
+</textarea></form>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        indentUnit: 4,
+        mode: "text/x-pig"
+      });
+    </script>
+
+    <p>
+        Simple mode that handles Pig Latin language.
+    </p>
+
+    <p><strong>MIME type defined:</strong> <code>text/x-pig</code>
+    (PIG code)
+</html>
diff --git a/third-party/codemirror-3.15/mode/pig/pig.js b/third-party/codemirror-3.15/mode/pig/pig.js
new file mode 100644 (file)
index 0000000..c2f611a
--- /dev/null
@@ -0,0 +1,171 @@
+/*
+ *      Pig Latin Mode for CodeMirror 2
+ *      @author Prasanth Jayachandran
+ *      @link   https://github.com/prasanthj/pig-codemirror-2
+ *  This implementation is adapted from PL/SQL mode in CodeMirror 2.
+ */
+CodeMirror.defineMode("pig", function(_config, parserConfig) {
+  var keywords = parserConfig.keywords,
+  builtins = parserConfig.builtins,
+  types = parserConfig.types,
+  multiLineStrings = parserConfig.multiLineStrings;
+
+  var isOperatorChar = /[*+\-%<>=&?:\/!|]/;
+
+  function chain(stream, state, f) {
+    state.tokenize = f;
+    return f(stream, state);
+  }
+
+  var type;
+  function ret(tp, style) {
+    type = tp;
+    return style;
+  }
+
+  function tokenComment(stream, state) {
+    var isEnd = false;
+    var ch;
+    while(ch = stream.next()) {
+      if(ch == "/" && isEnd) {
+        state.tokenize = tokenBase;
+        break;
+      }
+      isEnd = (ch == "*");
+    }
+    return ret("comment", "comment");
+  }
+
+  function tokenString(quote) {
+    return function(stream, state) {
+      var escaped = false, next, end = false;
+      while((next = stream.next()) != null) {
+        if (next == quote && !escaped) {
+          end = true; break;
+        }
+        escaped = !escaped && next == "\\";
+      }
+      if (end || !(escaped || multiLineStrings))
+        state.tokenize = tokenBase;
+      return ret("string", "error");
+    };
+  }
+
+  function tokenBase(stream, state) {
+    var ch = stream.next();
+
+    // is a start of string?
+    if (ch == '"' || ch == "'")
+      return chain(stream, state, tokenString(ch));
+    // is it one of the special chars
+    else if(/[\[\]{}\(\),;\.]/.test(ch))
+      return ret(ch);
+    // is it a number?
+    else if(/\d/.test(ch)) {
+      stream.eatWhile(/[\w\.]/);
+      return ret("number", "number");
+    }
+    // multi line comment or operator
+    else if (ch == "/") {
+      if (stream.eat("*")) {
+        return chain(stream, state, tokenComment);
+      }
+      else {
+        stream.eatWhile(isOperatorChar);
+        return ret("operator", "operator");
+      }
+    }
+    // single line comment or operator
+    else if (ch=="-") {
+      if(stream.eat("-")){
+        stream.skipToEnd();
+        return ret("comment", "comment");
+      }
+      else {
+        stream.eatWhile(isOperatorChar);
+        return ret("operator", "operator");
+      }
+    }
+    // is it an operator
+    else if (isOperatorChar.test(ch)) {
+      stream.eatWhile(isOperatorChar);
+      return ret("operator", "operator");
+    }
+    else {
+      // get the while word
+      stream.eatWhile(/[\w\$_]/);
+      // is it one of the listed keywords?
+      if (keywords && keywords.propertyIsEnumerable(stream.current().toUpperCase())) {
+        if (stream.eat(")") || stream.eat(".")) {
+          //keywords can be used as variables like flatten(group), group.$0 etc..
+        }
+        else {
+          return ("keyword", "keyword");
+        }
+      }
+      // is it one of the builtin functions?
+      if (builtins && builtins.propertyIsEnumerable(stream.current().toUpperCase()))
+      {
+        return ("keyword", "variable-2");
+      }
+      // is it one of the listed types?
+      if (types && types.propertyIsEnumerable(stream.current().toUpperCase()))
+        return ("keyword", "variable-3");
+      // default is a 'variable'
+      return ret("variable", "pig-word");
+    }
+  }
+
+  // Interface
+  return {
+    startState: function() {
+      return {
+        tokenize: tokenBase,
+        startOfLine: true
+      };
+    },
+
+    token: function(stream, state) {
+      if(stream.eatSpace()) return null;
+      var style = state.tokenize(stream, state);
+      return style;
+    }
+  };
+});
+
+(function() {
+  function keywords(str) {
+    var obj = {}, words = str.split(" ");
+    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
+    return obj;
+  }
+
+  // builtin funcs taken from trunk revision 1303237
+  var pBuiltins = "ABS ACOS ARITY ASIN ATAN AVG BAGSIZE BINSTORAGE BLOOM BUILDBLOOM CBRT CEIL "
+    + "CONCAT COR COS COSH COUNT COUNT_STAR COV CONSTANTSIZE CUBEDIMENSIONS DIFF DISTINCT DOUBLEABS "
+    + "DOUBLEAVG DOUBLEBASE DOUBLEMAX DOUBLEMIN DOUBLEROUND DOUBLESUM EXP FLOOR FLOATABS FLOATAVG "
+    + "FLOATMAX FLOATMIN FLOATROUND FLOATSUM GENERICINVOKER INDEXOF INTABS INTAVG INTMAX INTMIN "
+    + "INTSUM INVOKEFORDOUBLE INVOKEFORFLOAT INVOKEFORINT INVOKEFORLONG INVOKEFORSTRING INVOKER "
+    + "ISEMPTY JSONLOADER JSONMETADATA JSONSTORAGE LAST_INDEX_OF LCFIRST LOG LOG10 LOWER LONGABS "
+    + "LONGAVG LONGMAX LONGMIN LONGSUM MAX MIN MAPSIZE MONITOREDUDF NONDETERMINISTIC OUTPUTSCHEMA  "
+    + "PIGSTORAGE PIGSTREAMING RANDOM REGEX_EXTRACT REGEX_EXTRACT_ALL REPLACE ROUND SIN SINH SIZE "
+    + "SQRT STRSPLIT SUBSTRING SUM STRINGCONCAT STRINGMAX STRINGMIN STRINGSIZE TAN TANH TOBAG "
+    + "TOKENIZE TOMAP TOP TOTUPLE TRIM TEXTLOADER TUPLESIZE UCFIRST UPPER UTF8STORAGECONVERTER ";
+
+  // taken from QueryLexer.g
+  var pKeywords = "VOID IMPORT RETURNS DEFINE LOAD FILTER FOREACH ORDER CUBE DISTINCT COGROUP "
+    + "JOIN CROSS UNION SPLIT INTO IF OTHERWISE ALL AS BY USING INNER OUTER ONSCHEMA PARALLEL "
+    + "PARTITION GROUP AND OR NOT GENERATE FLATTEN ASC DESC IS STREAM THROUGH STORE MAPREDUCE "
+    + "SHIP CACHE INPUT OUTPUT STDERROR STDIN STDOUT LIMIT SAMPLE LEFT RIGHT FULL EQ GT LT GTE LTE "
+    + "NEQ MATCHES TRUE FALSE ";
+
+  // data types
+  var pTypes = "BOOLEAN INT LONG FLOAT DOUBLE CHARARRAY BYTEARRAY BAG TUPLE MAP ";
+
+  CodeMirror.defineMIME("text/x-pig", {
+    name: "pig",
+    builtins: keywords(pBuiltins),
+    keywords: keywords(pKeywords),
+    types: keywords(pTypes)
+  });
+}());
diff --git a/third-party/codemirror-3.15/mode/properties/index.html b/third-party/codemirror-3.15/mode/properties/index.html
new file mode 100644 (file)
index 0000000..e21e02a
--- /dev/null
@@ -0,0 +1,41 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Properties files mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="properties.js"></script>
+    <style>.CodeMirror {border-top: 1px solid #ddd; border-bottom: 1px solid #ddd;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Properties files mode</h1>
+    <form><textarea id="code" name="code">
+# This is a properties file
+a.key = A value
+another.key = http://example.com
+! Exclamation mark as comment
+but.not=Within ! A value # indeed
+   # Spaces at the beginning of a line
+   spaces.before.key=value
+backslash=Used for multi\
+          line entries,\
+          that's convenient.
+# Unicode sequences
+unicode.key=This is \u0020 Unicode
+no.multiline=here
+# Colons
+colons : can be used too
+# Spaces
+spaces\ in\ keys=Not very common...
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-properties</code>,
+    <code>text/x-ini</code>.</p>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/properties/properties.js b/third-party/codemirror-3.15/mode/properties/properties.js
new file mode 100644 (file)
index 0000000..d3a13c7
--- /dev/null
@@ -0,0 +1,63 @@
+CodeMirror.defineMode("properties", function() {
+  return {
+    token: function(stream, state) {
+      var sol = stream.sol() || state.afterSection;
+      var eol = stream.eol();
+
+      state.afterSection = false;
+
+      if (sol) {
+        if (state.nextMultiline) {
+          state.inMultiline = true;
+          state.nextMultiline = false;
+        } else {
+          state.position = "def";
+        }
+      }
+
+      if (eol && ! state.nextMultiline) {
+        state.inMultiline = false;
+        state.position = "def";
+      }
+
+      if (sol) {
+        while(stream.eatSpace());
+      }
+
+      var ch = stream.next();
+
+      if (sol && (ch === "#" || ch === "!" || ch === ";")) {
+        state.position = "comment";
+        stream.skipToEnd();
+        return "comment";
+      } else if (sol && ch === "[") {
+        state.afterSection = true;
+        stream.skipTo("]"); stream.eat("]");
+        return "header";
+      } else if (ch === "=" || ch === ":") {
+        state.position = "quote";
+        return null;
+      } else if (ch === "\\" && state.position === "quote") {
+        if (stream.next() !== "u") {    // u = Unicode sequence \u1234
+          // Multiline value
+          state.nextMultiline = true;
+        }
+      }
+
+      return state.position;
+    },
+
+    startState: function() {
+      return {
+        position : "def",       // Current position, "def", "quote" or "comment"
+        nextMultiline : false,  // Is the next line multiline value
+        inMultiline : false,    // Is the current line a multiline value
+        afterSection : false    // Did we just open a section
+      };
+    }
+
+  };
+});
+
+CodeMirror.defineMIME("text/x-properties", "properties");
+CodeMirror.defineMIME("text/x-ini", "properties");
diff --git a/third-party/codemirror-3.15/mode/python/LICENSE.txt b/third-party/codemirror-3.15/mode/python/LICENSE.txt
new file mode 100644 (file)
index 0000000..918866b
--- /dev/null
@@ -0,0 +1,21 @@
+The MIT License
+
+Copyright (c) 2010 Timothy Farrell
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
\ No newline at end of file
diff --git a/third-party/codemirror-3.15/mode/python/index.html b/third-party/codemirror-3.15/mode/python/index.html
new file mode 100644 (file)
index 0000000..1229a8b
--- /dev/null
@@ -0,0 +1,175 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Python mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../../addon/edit/matchbrackets.js"></script>
+    <script src="python.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: Python mode</h1>
+    <h2>Python mode</h2>
+    <div><textarea id="code" name="code">
+# Literals
+1234
+0.0e101
+.123
+0b01010011100
+0o01234567
+0x0987654321abcdef
+7
+2147483647
+3L
+79228162514264337593543950336L
+0x100000000L
+79228162514264337593543950336
+0xdeadbeef
+3.14j
+10.j
+10j
+.001j
+1e100j
+3.14e-10j
+
+
+# String Literals
+'For\''
+"God\""
+"""so loved
+the world"""
+'''that he gave
+his only begotten\' '''
+'that whosoever believeth \
+in him'
+''
+
+# Identifiers
+__a__
+a.b
+a.b.c
+
+# Operators
++ - * / % & | ^ ~ < >
+== != <= >= <> << >> // **
+and or not in is
+
+# Delimiters
+() [] {} , : ` = ; @ .  # Note that @ and . require the proper context.
++= -= *= /= %= &= |= ^=
+//= >>= <<= **=
+
+# Keywords
+as assert break class continue def del elif else except
+finally for from global if import lambda pass raise
+return try while with yield
+
+# Python 2 Keywords (otherwise Identifiers)
+exec print
+
+# Python 3 Keywords (otherwise Identifiers)
+nonlocal
+
+# Types
+bool classmethod complex dict enumerate float frozenset int list object
+property reversed set slice staticmethod str super tuple type
+
+# Python 2 Types (otherwise Identifiers)
+basestring buffer file long unicode xrange
+
+# Python 3 Types (otherwise Identifiers)
+bytearray bytes filter map memoryview open range zip
+
+# Some Example code
+import os
+from package import ParentClass
+
+@nonsenseDecorator
+def doesNothing():
+    pass
+
+class ExampleClass(ParentClass):
+    @staticmethod
+    def example(inputStr):
+        a = list(inputStr)
+        a.reverse()
+        return ''.join(a)
+
+    def __init__(self, mixin = 'Hello'):
+        self.mixin = mixin
+
+</textarea></div>
+
+
+<h2>Cython mode</h2>
+
+<div><textarea id="code-cython" name="code-cython">
+
+import numpy as np
+cimport cython
+from libc.math cimport sqrt
+
+@cython.boundscheck(False)
+@cython.wraparound(False)
+def pairwise_cython(double[:, ::1] X):
+    cdef int M = X.shape[0]
+    cdef int N = X.shape[1]
+    cdef double tmp, d
+    cdef double[:, ::1] D = np.empty((M, M), dtype=np.float64)
+    for i in range(M):
+        for j in range(M):
+            d = 0.0
+            for k in range(N):
+                tmp = X[i, k] - X[j, k]
+                d += tmp * tmp
+            D[i, j] = sqrt(d)
+    return np.asarray(D)
+
+</textarea></div>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        mode: {name: "python",
+               version: 2,
+               singleLineStringErrors: false},
+        lineNumbers: true,
+        indentUnit: 4,
+        tabMode: "shift",
+        matchBrackets: true
+    });
+
+    CodeMirror.fromTextArea(document.getElementById("code-cython"), {
+        mode: {name: "text/x-cython",
+               version: 2,
+               singleLineStringErrors: false},
+        lineNumbers: true,
+        indentUnit: 4,
+        tabMode: "shift",
+        matchBrackets: true
+      });
+    </script>
+    <h2>Configuration Options for Python mode:</h2>
+    <ul>
+      <li>version - 2/3 - The version of Python to recognize.  Default is 2.</li>
+      <li>singleLineStringErrors - true/false - If you have a single-line string that is not terminated at the end of the line, this will show subsequent lines as errors if true, otherwise it will consider the newline as the end of the string. Default is false.</li>
+    </ul>
+    <h2>Advanced Configuration Options:</h2>
+    <p>Usefull for superset of python syntax like Enthought enaml, IPython magics and  questionmark help</p>
+    <ul>
+      <li>singleOperators - RegEx - Regular Expression for single operator matching,  default : <pre>^[\\+\\-\\*/%&amp;|\\^~&lt;&gt;!]</pre></li>
+      <li>singleDelimiters - RegEx - Regular Expression for single delimiter matching, default :  <pre>^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]</pre></li>
+      <li>doubleOperators - RegEx - Regular Expression for double operators matching, default : <pre>^((==)|(!=)|(&lt;=)|(&gt;=)|(&lt;&gt;)|(&lt;&lt;)|(&gt;&gt;)|(//)|(\\*\\*))</pre></li>
+      <li>doubleDelimiters - RegEx - Regular Expressoin for double delimiters matching, default : <pre>^((\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&amp;=)|(\\|=)|(\\^=))</pre></li>
+      <li>tripleDelimiters - RegEx - Regular Expression for triple delimiters matching, default : <pre>^((//=)|(&gt;&gt;=)|(&lt;&lt;=)|(\\*\\*=))</pre></li>
+      <li>identifiers - RegEx - Regular Expression for identifier, default : <pre>^[_A-Za-z][_A-Za-z0-9]*</pre></li>
+      <li>extra_keywords - list of string - List of extra words ton consider as keywords</li>
+      <li>extra_builtins - list of string - List of extra words ton consider as builtins</li>
+    </ul>
+
+
+    <p><strong>MIME types defined:</strong> <code>text/x-python</code> and <code>text/x-cython</code>.</p>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/python/python.js b/third-party/codemirror-3.15/mode/python/python.js
new file mode 100644 (file)
index 0000000..4fe4d28
--- /dev/null
@@ -0,0 +1,358 @@
+CodeMirror.defineMode("python", function(conf, parserConf) {
+    var ERRORCLASS = 'error';
+
+    function wordRegexp(words) {
+        return new RegExp("^((" + words.join(")|(") + "))\\b");
+    }
+
+    var singleOperators = parserConf.singleOperators || new RegExp("^[\\+\\-\\*/%&|\\^~<>!]");
+    var singleDelimiters = parserConf.singleDelimiters || new RegExp('^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]');
+    var doubleOperators = parserConf.doubleOperators || new RegExp("^((==)|(!=)|(<=)|(>=)|(<>)|(<<)|(>>)|(//)|(\\*\\*))");
+    var doubleDelimiters = parserConf.doubleDelimiters || new RegExp("^((\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))");
+    var tripleDelimiters = parserConf.tripleDelimiters || new RegExp("^((//=)|(>>=)|(<<=)|(\\*\\*=))");
+    var identifiers = parserConf.identifiers|| new RegExp("^[_A-Za-z][_A-Za-z0-9]*");
+
+    var wordOperators = wordRegexp(['and', 'or', 'not', 'is', 'in']);
+    var commonkeywords = ['as', 'assert', 'break', 'class', 'continue',
+                          'def', 'del', 'elif', 'else', 'except', 'finally',
+                          'for', 'from', 'global', 'if', 'import',
+                          'lambda', 'pass', 'raise', 'return',
+                          'try', 'while', 'with', 'yield'];
+    var commonBuiltins = ['abs', 'all', 'any', 'bin', 'bool', 'bytearray', 'callable', 'chr',
+                          'classmethod', 'compile', 'complex', 'delattr', 'dict', 'dir', 'divmod',
+                          'enumerate', 'eval', 'filter', 'float', 'format', 'frozenset',
+                          'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id',
+                          'input', 'int', 'isinstance', 'issubclass', 'iter', 'len',
+                          'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next',
+                          'object', 'oct', 'open', 'ord', 'pow', 'property', 'range',
+                          'repr', 'reversed', 'round', 'set', 'setattr', 'slice',
+                          'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple',
+                          'type', 'vars', 'zip', '__import__', 'NotImplemented',
+                          'Ellipsis', '__debug__'];
+    var py2 = {'builtins': ['apply', 'basestring', 'buffer', 'cmp', 'coerce', 'execfile',
+                            'file', 'intern', 'long', 'raw_input', 'reduce', 'reload',
+                            'unichr', 'unicode', 'xrange', 'False', 'True', 'None'],
+               'keywords': ['exec', 'print']};
+    var py3 = {'builtins': ['ascii', 'bytes', 'exec', 'print'],
+               'keywords': ['nonlocal', 'False', 'True', 'None']};
+
+    if(parserConf.extra_keywords != undefined){
+        commonkeywords = commonkeywords.concat(parserConf.extra_keywords);
+    }
+    if(parserConf.extra_builtins != undefined){
+        commonBuiltins = commonBuiltins.concat(parserConf.extra_builtins);
+    }
+    if (!!parserConf.version && parseInt(parserConf.version, 10) === 3) {
+        commonkeywords = commonkeywords.concat(py3.keywords);
+        commonBuiltins = commonBuiltins.concat(py3.builtins);
+        var stringPrefixes = new RegExp("^(([rb]|(br))?('{3}|\"{3}|['\"]))", "i");
+    } else {
+        commonkeywords = commonkeywords.concat(py2.keywords);
+        commonBuiltins = commonBuiltins.concat(py2.builtins);
+        var stringPrefixes = new RegExp("^(([rub]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i");
+    }
+    var keywords = wordRegexp(commonkeywords);
+    var builtins = wordRegexp(commonBuiltins);
+
+    var indentInfo = null;
+
+    // tokenizers
+    function tokenBase(stream, state) {
+        // Handle scope changes
+        if (stream.sol()) {
+            var scopeOffset = state.scopes[0].offset;
+            if (stream.eatSpace()) {
+                var lineOffset = stream.indentation();
+                if (lineOffset > scopeOffset) {
+                    indentInfo = 'indent';
+                } else if (lineOffset < scopeOffset) {
+                    indentInfo = 'dedent';
+                }
+                return null;
+            } else {
+                if (scopeOffset > 0) {
+                    dedent(stream, state);
+                }
+            }
+        }
+        if (stream.eatSpace()) {
+            return null;
+        }
+
+        var ch = stream.peek();
+
+        // Handle Comments
+        if (ch === '#') {
+            stream.skipToEnd();
+            return 'comment';
+        }
+
+        // Handle Number Literals
+        if (stream.match(/^[0-9\.]/, false)) {
+            var floatLiteral = false;
+            // Floats
+            if (stream.match(/^\d*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; }
+            if (stream.match(/^\d+\.\d*/)) { floatLiteral = true; }
+            if (stream.match(/^\.\d+/)) { floatLiteral = true; }
+            if (floatLiteral) {
+                // Float literals may be "imaginary"
+                stream.eat(/J/i);
+                return 'number';
+            }
+            // Integers
+            var intLiteral = false;
+            // Hex
+            if (stream.match(/^0x[0-9a-f]+/i)) { intLiteral = true; }
+            // Binary
+            if (stream.match(/^0b[01]+/i)) { intLiteral = true; }
+            // Octal
+            if (stream.match(/^0o[0-7]+/i)) { intLiteral = true; }
+            // Decimal
+            if (stream.match(/^[1-9]\d*(e[\+\-]?\d+)?/)) {
+                // Decimal literals may be "imaginary"
+                stream.eat(/J/i);
+                // TODO - Can you have imaginary longs?
+                intLiteral = true;
+            }
+            // Zero by itself with no other piece of number.
+            if (stream.match(/^0(?![\dx])/i)) { intLiteral = true; }
+            if (intLiteral) {
+                // Integer literals may be "long"
+                stream.eat(/L/i);
+                return 'number';
+            }
+        }
+
+        // Handle Strings
+        if (stream.match(stringPrefixes)) {
+            state.tokenize = tokenStringFactory(stream.current());
+            return state.tokenize(stream, state);
+        }
+
+        // Handle operators and Delimiters
+        if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters)) {
+            return null;
+        }
+        if (stream.match(doubleOperators)
+            || stream.match(singleOperators)
+            || stream.match(wordOperators)) {
+            return 'operator';
+        }
+        if (stream.match(singleDelimiters)) {
+            return null;
+        }
+
+        if (stream.match(keywords)) {
+            return 'keyword';
+        }
+
+        if (stream.match(builtins)) {
+            return 'builtin';
+        }
+
+        if (stream.match(identifiers)) {
+            return 'variable';
+        }
+
+        // Handle non-detected items
+        stream.next();
+        return ERRORCLASS;
+    }
+
+    function tokenStringFactory(delimiter) {
+        while ('rub'.indexOf(delimiter.charAt(0).toLowerCase()) >= 0) {
+            delimiter = delimiter.substr(1);
+        }
+        var singleline = delimiter.length == 1;
+        var OUTCLASS = 'string';
+
+        function tokenString(stream, state) {
+            while (!stream.eol()) {
+                stream.eatWhile(/[^'"\\]/);
+                if (stream.eat('\\')) {
+                    stream.next();
+                    if (singleline && stream.eol()) {
+                        return OUTCLASS;
+                    }
+                } else if (stream.match(delimiter)) {
+                    state.tokenize = tokenBase;
+                    return OUTCLASS;
+                } else {
+                    stream.eat(/['"]/);
+                }
+            }
+            if (singleline) {
+                if (parserConf.singleLineStringErrors) {
+                    return ERRORCLASS;
+                } else {
+                    state.tokenize = tokenBase;
+                }
+            }
+            return OUTCLASS;
+        }
+        tokenString.isString = true;
+        return tokenString;
+    }
+
+    function indent(stream, state, type) {
+        type = type || 'py';
+        var indentUnit = 0;
+        if (type === 'py') {
+            if (state.scopes[0].type !== 'py') {
+                state.scopes[0].offset = stream.indentation();
+                return;
+            }
+            for (var i = 0; i < state.scopes.length; ++i) {
+                if (state.scopes[i].type === 'py') {
+                    indentUnit = state.scopes[i].offset + conf.indentUnit;
+                    break;
+                }
+            }
+        } else {
+            indentUnit = stream.column() + stream.current().length;
+        }
+        state.scopes.unshift({
+            offset: indentUnit,
+            type: type
+        });
+    }
+
+    function dedent(stream, state, type) {
+        type = type || 'py';
+        if (state.scopes.length == 1) return;
+        if (state.scopes[0].type === 'py') {
+            var _indent = stream.indentation();
+            var _indent_index = -1;
+            for (var i = 0; i < state.scopes.length; ++i) {
+                if (_indent === state.scopes[i].offset) {
+                    _indent_index = i;
+                    break;
+                }
+            }
+            if (_indent_index === -1) {
+                return true;
+            }
+            while (state.scopes[0].offset !== _indent) {
+                state.scopes.shift();
+            }
+            return false;
+        } else {
+            if (type === 'py') {
+                state.scopes[0].offset = stream.indentation();
+                return false;
+            } else {
+                if (state.scopes[0].type != type) {
+                    return true;
+                }
+                state.scopes.shift();
+                return false;
+            }
+        }
+    }
+
+    function tokenLexer(stream, state) {
+        indentInfo = null;
+        var style = state.tokenize(stream, state);
+        var current = stream.current();
+
+        // Handle '.' connected identifiers
+        if (current === '.') {
+            style = stream.match(identifiers, false) ? null : ERRORCLASS;
+            if (style === null && state.lastToken === 'meta') {
+                // Apply 'meta' style to '.' connected identifiers when
+                // appropriate.
+                style = 'meta';
+            }
+            return style;
+        }
+
+        // Handle decorators
+        if (current === '@') {
+            return stream.match(identifiers, false) ? 'meta' : ERRORCLASS;
+        }
+
+        if ((style === 'variable' || style === 'builtin')
+            && state.lastToken === 'meta') {
+            style = 'meta';
+        }
+
+        // Handle scope changes.
+        if (current === 'pass' || current === 'return') {
+            state.dedent += 1;
+        }
+        if (current === 'lambda') state.lambda = true;
+        if ((current === ':' && !state.lambda && state.scopes[0].type == 'py')
+            || indentInfo === 'indent') {
+            indent(stream, state);
+        }
+        var delimiter_index = '[({'.indexOf(current);
+        if (delimiter_index !== -1) {
+            indent(stream, state, '])}'.slice(delimiter_index, delimiter_index+1));
+        }
+        if (indentInfo === 'dedent') {
+            if (dedent(stream, state)) {
+                return ERRORCLASS;
+            }
+        }
+        delimiter_index = '])}'.indexOf(current);
+        if (delimiter_index !== -1) {
+            if (dedent(stream, state, current)) {
+                return ERRORCLASS;
+            }
+        }
+        if (state.dedent > 0 && stream.eol() && state.scopes[0].type == 'py') {
+            if (state.scopes.length > 1) state.scopes.shift();
+            state.dedent -= 1;
+        }
+
+        return style;
+    }
+
+    var external = {
+        startState: function(basecolumn) {
+            return {
+              tokenize: tokenBase,
+              scopes: [{offset:basecolumn || 0, type:'py'}],
+              lastToken: null,
+              lambda: false,
+              dedent: 0
+          };
+        },
+
+        token: function(stream, state) {
+            var style = tokenLexer(stream, state);
+
+            state.lastToken = style;
+
+            if (stream.eol() && state.lambda) {
+                state.lambda = false;
+            }
+
+            return style;
+        },
+
+        indent: function(state) {
+            if (state.tokenize != tokenBase) {
+                return state.tokenize.isString ? CodeMirror.Pass : 0;
+            }
+
+            return state.scopes[0].offset;
+        },
+
+        lineComment: "#",
+        fold: "indent"
+    };
+    return external;
+});
+
+CodeMirror.defineMIME("text/x-python", "python");
+
+var words = function(str){return str.split(' ');};
+
+
+CodeMirror.defineMIME("text/x-cython", {
+  name: "python",
+  extra_keywords: words("by cdef cimport cpdef ctypedef enum except"+
+                        "extern gil include nogil property public"+
+                        "readonly struct union DEF IF ELIF ELSE")
+});
diff --git a/third-party/codemirror-3.15/mode/q/index.html b/third-party/codemirror-3.15/mode/q/index.html
new file mode 100644 (file)
index 0000000..303ec1d
--- /dev/null
@@ -0,0 +1,131 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Q mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../../addon/edit/matchbrackets.js"></script>
+    <script src="q.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: Q mode</h1>
+
+<div><textarea id="code" name="code">
+/ utilities to quickly load a csv file - for more exhaustive analysis of the csv contents see csvguess.q
+/ 2009.09.20 - updated to match latest csvguess.q 
+
+/ .csv.colhdrs[file] - return a list of colhdrs from file
+/ info:.csv.info[file] - return a table of information about the file
+/ columns are: 
+/      c - column name; ci - column index; t - load type; mw - max width; 
+/      dchar - distinct characters in values; rule - rule that caught the type
+/      maybe - needs checking, _could_ be say a date, but perhaps just a float?
+/ .csv.info0[file;onlycols] - like .csv.info except that it only analyses <onlycols>
+/ example:
+/      info:.csv.info0[file;(.csv.colhdrs file)like"*price"]
+/      info:.csv.infolike[file;"*price"]
+/      show delete from info where t=" "
+/ .csv.data[file;info] - use the info from .csv.info to read the data
+/ .csv.data10[file;info] - like .csv.data but only returns the first 10 rows
+/ bulkload[file;info] - bulk loads file into table DATA (which must be already defined :: DATA:() )
+/ .csv.read[file]/read10[file] - for when you don't care about checking/tweaking the <info> before reading 
+
+\d .csv
+DELIM:","
+ZAPHDRS:0b / lowercase and remove _ from colhdrs (junk characters are always removed)
+WIDTHHDR:25000 / number of characters read to get the header
+READLINES:222 / number of lines read and used to guess the types
+SYMMAXWIDTH:11 / character columns narrower than this are stored as symbols
+SYMMAXGR:10 / max symbol granularity% before we give up and keep as a * string
+FORCECHARWIDTH:30 / every field (of any type) with values this wide or more is forced to character "*"
+DISCARDEMPTY:0b / completely ignore empty columns if true else set them to "C"
+CHUNKSIZE:50000000 / used in fs2 (modified .Q.fs)
+
+k)nameltrim:{$[~@x;.z.s'x;~(*x)in aA:.Q.a,.Q.A;(+/&\~x in aA)_x;x]}
+k)fs2:{[f;s]((-7!s)>){[f;s;x]i:1+last@&0xa=r:1:(s;x;CHUNKSIZE);f@`\:i#r;x+i}[f;s]/0j}
+cleanhdrs:{{$[ZAPHDRS;lower x except"_";x]}x where x in DELIM,.Q.an}
+cancast:{nw:x$"";if[not x in"BXCS";nw:(min 0#;max 0#;::)@\:nw];$[not any nw in x$(11&count y)#y;$[11<count y;not any nw in x$y;1b];0b]}
+
+read:{[file]data[file;info[file]]}  
+read10:{[file]data10[file;info[file]]}  
+
+colhdrs:{[file]
+       `$nameltrim DELIM vs cleanhdrs first read0(file;0;1+first where 0xa=read1(file;0;WIDTHHDR))}
+data:{[file;info]
+       (exec c from info where not t=" ")xcol(exec t from info;enlist DELIM)0:file}
+data10:{[file;info]
+       data[;info](file;0;1+last 11#where 0xa=read1(file;0;15*WIDTHHDR))}
+info0:{[file;onlycols]
+       colhdrs:`$nameltrim DELIM vs cleanhdrs first head:read0(file;0;1+last where 0xa=read1(file;0;WIDTHHDR));
+       loadfmts:(count colhdrs)#"S";if[count onlycols;loadfmts[where not colhdrs in onlycols]:"C"];
+       breaks:where 0xa=read1(file;0;floor(10+READLINES)*WIDTHHDR%count head);
+       nas:count as:colhdrs xcol(loadfmts;enlist DELIM)0:(file;0;1+last((1+READLINES)&count breaks)#breaks);
+       info:([]c:key flip as;v:value flip as);as:();
+       reserved:key`.q;reserved,:.Q.res;reserved,:`i;
+       info:update res:c in reserved from info;
+       info:update ci:i,t:"?",ipa:0b,mdot:0,mw:0,rule:0,gr:0,ndv:0,maybe:0b,empty:0b,j10:0b,j12:0b from info;
+       info:update ci:`s#ci from info;
+       if[count onlycols;info:update t:" ",rule:10 from info where not c in onlycols];
+       info:update sdv:{string(distinct x)except`}peach v from info; 
+       info:update ndv:count each sdv from info;
+       info:update gr:floor 0.5+100*ndv%nas,mw:{max count each x}peach sdv from info where 0<ndv;
+       info:update t:"*",rule:20 from info where mw>.csv.FORCECHARWIDTH; / long values
+       info:update t:"C "[.csv.DISCARDEMPTY],rule:30,empty:1b from info where t="?",mw=0; / empty columns
+       info:update dchar:{asc distinct raze x}peach sdv from info where t="?";
+       info:update mdot:{max sum each"."=x}peach sdv from info where t="?",{"."in x}each dchar;
+       info:update t:"n",rule:40 from info where t="?",{any x in"0123456789"}each dchar; / vaguely numeric..
+       info:update t:"I",rule:50,ipa:1b from info where t="n",mw within 7 15,mdot=3,{all x in".0123456789"}each dchar,.csv.cancast["I"]peach sdv; / ip-address
+       info:update t:"J",rule:60 from info where t="n",mdot=0,{all x in"+-0123456789"}each dchar,.csv.cancast["J"]peach sdv;
+       info:update t:"I",rule:70 from info where t="J",mw<12,.csv.cancast["I"]peach sdv;
+       info:update t:"H",rule:80 from info where t="I",mw<7,.csv.cancast["H"]peach sdv;
+       info:update t:"F",rule:90 from info where t="n",mdot<2,mw>1,.csv.cancast["F"]peach sdv;
+       info:update t:"E",rule:100,maybe:1b from info where t="F",mw<9;
+       info:update t:"M",rule:110,maybe:1b from info where t in"nIHEF",mdot<2,mw within 4 7,.csv.cancast["M"]peach sdv; 
+       info:update t:"D",rule:120,maybe:1b from info where t in"nI",mdot in 0 2,mw within 6 11,.csv.cancast["D"]peach sdv; 
+       info:update t:"V",rule:130,maybe:1b from info where t="I",mw in 5 6,7<count each dchar,{all x like"*[0-9][0-5][0-9][0-5][0-9]"}peach sdv,.csv.cancast["V"]peach sdv; / 235959 12345        
+       info:update t:"U",rule:140,maybe:1b from info where t="H",mw in 3 4,7<count each dchar,{all x like"*[0-9][0-5][0-9]"}peach sdv,.csv.cancast["U"]peach sdv; /2359
+       info:update t:"U",rule:150,maybe:0b from info where t="n",mw in 4 5,mdot=0,{all x like"*[0-9]:[0-5][0-9]"}peach sdv,.csv.cancast["U"]peach sdv;
+       info:update t:"T",rule:160,maybe:0b from info where t="n",mw within 7 12,mdot<2,{all x like"*[0-9]:[0-5][0-9]:[0-5][0-9]*"}peach sdv,.csv.cancast["T"]peach sdv;
+       info:update t:"V",rule:170,maybe:0b from info where t="T",mw in 7 8,mdot=0,.csv.cancast["V"]peach sdv;
+       info:update t:"T",rule:180,maybe:1b from info where t in"EF",mw within 7 10,mdot=1,{all x like"*[0-9][0-5][0-9][0-5][0-9].*"}peach sdv,.csv.cancast["T"]peach sdv;
+       info:update t:"Z",rule:190,maybe:0b from info where t="n",mw within 11 24,mdot<4,.csv.cancast["Z"]peach sdv;
+       info:update t:"P",rule:200,maybe:1b from info where t="n",mw within 12 29,mdot<4,{all x like"[12]*"}peach sdv,.csv.cancast["P"]peach sdv;
+       info:update t:"N",rule:210,maybe:1b from info where t="n",mw within 3 28,mdot=1,.csv.cancast["N"]peach sdv;
+       info:update t:"?",rule:220,maybe:0b from info where t="n"; / reset remaining maybe numeric
+       info:update t:"C",rule:230,maybe:0b from info where t="?",mw=1; / char
+       info:update t:"B",rule:240,maybe:0b from info where t in"HC",mw=1,mdot=0,{$[all x in"01tTfFyYnN";(any"0fFnN"in x)and any"1tTyY"in x;0b]}each dchar; / boolean
+       info:update t:"B",rule:250,maybe:1b from info where t in"HC",mw=1,mdot=0,{all x in"01tTfFyYnN"}each dchar; / boolean
+       info:update t:"X",rule:260,maybe:0b from info where t="?",mw=2,{$[all x in"0123456789abcdefABCDEF";(any .Q.n in x)and any"abcdefABCDEF"in x;0b]}each dchar; /hex
+       info:update t:"S",rule:270,maybe:1b from info where t="?",mw<.csv.SYMMAXWIDTH,mw>1,gr<.csv.SYMMAXGR; / symbols (max width permitting)
+       info:update t:"*",rule:280,maybe:0b from info where t="?"; / the rest as strings
+       / flag those S/* columns which could be encoded to integers (.Q.j10/x10/j12/x12) to avoid symbols
+       info:update j12:1b from info where t in"S*",mw<13,{all x in .Q.nA}each dchar;
+       info:update j10:1b from info where t in"S*",mw<11,{all x in .Q.b6}each dchar; 
+       select c,ci,t,maybe,empty,res,j10,j12,ipa,mw,mdot,rule,gr,ndv,dchar from info}
+info:info0[;()] / by default don't restrict columns
+infolike:{[file;pattern] info0[file;{x where x like y}[lower colhdrs[file];pattern]]} / .csv.infolike[file;"*time"]
+
+\d .
+/ DATA:()
+bulkload:{[file;info]
+       if[not`DATA in system"v";'`DATA.not.defined];
+       if[count DATA;'`DATA.not.empty];
+       loadhdrs:exec c from info where not t=" ";loadfmts:exec t from info;
+       .csv.fs2[{[file;loadhdrs;loadfmts] `DATA insert $[count DATA;flip loadhdrs!(loadfmts;.csv.DELIM)0:file;loadhdrs xcol(loadfmts;enlist .csv.DELIM)0:file]}[file;loadhdrs;loadfmts]];
+       count DATA}
+@[.:;"\\l csvutil.custom.q";::]; / save your custom settings in csvutil.custom.q to override those set at the beginning of the file 
+</textarea></div>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        matchBrackets: true
+      });
+    </script>
+
+    <p><strong>MIME type defined:</strong> <code>text/x-q</code>.</p>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/q/q.js b/third-party/codemirror-3.15/mode/q/q.js
new file mode 100644 (file)
index 0000000..56017e3
--- /dev/null
@@ -0,0 +1,124 @@
+CodeMirror.defineMode("q",function(config){
+  var indentUnit=config.indentUnit,
+      curPunc,
+      keywords=buildRE(["abs","acos","aj","aj0","all","and","any","asc","asin","asof","atan","attr","avg","avgs","bin","by","ceiling","cols","cor","cos","count","cov","cross","csv","cut","delete","deltas","desc","dev","differ","distinct","div","do","each","ej","enlist","eval","except","exec","exit","exp","fby","fills","first","fkeys","flip","floor","from","get","getenv","group","gtime","hclose","hcount","hdel","hopen","hsym","iasc","idesc","if","ij","in","insert","inter","inv","key","keys","last","like","list","lj","load","log","lower","lsq","ltime","ltrim","mavg","max","maxs","mcount","md5","mdev","med","meta","min","mins","mmax","mmin","mmu","mod","msum","neg","next","not","null","or","over","parse","peach","pj","plist","prd","prds","prev","prior","rand","rank","ratios","raze","read0","read1","reciprocal","reverse","rload","rotate","rsave","rtrim","save","scan","select","set","setenv","show","signum","sin","sqrt","ss","ssr","string","sublist","sum","sums","sv","system","tables","tan","til","trim","txf","type","uj","ungroup","union","update","upper","upsert","value","var","view","views","vs","wavg","where","where","while","within","wj","wj1","wsum","xasc","xbar","xcol","xcols","xdesc","xexp","xgroup","xkey","xlog","xprev","xrank"]),
+      E=/[|/&^!+:\\\-*%$=~#;@><,?_\'\"\[\(\]\)\s{}]/;
+  function buildRE(w){return new RegExp("^("+w.join("|")+")$");}
+  function tokenBase(stream,state){
+    var sol=stream.sol(),c=stream.next();
+    curPunc=null;
+    if(sol)
+      if(c=="/")
+        return(state.tokenize=tokenLineComment)(stream,state);
+      else if(c=="\\"){
+        if(stream.eol()||/\s/.test(stream.peek()))
+          return stream.skipToEnd(),/^\\\s*$/.test(stream.current())?(state.tokenize=tokenCommentToEOF)(stream, state):state.tokenize=tokenBase,"comment";
+        else
+          return state.tokenize=tokenBase,"builtin";
+      }
+    if(/\s/.test(c))
+      return stream.peek()=="/"?(stream.skipToEnd(),"comment"):"whitespace";
+    if(c=='"')
+      return(state.tokenize=tokenString)(stream,state);
+    if(c=='`')
+      return stream.eatWhile(/[A-Z|a-z|\d|_|:|\/|\.]/),"symbol";
+    if(("."==c&&/\d/.test(stream.peek()))||/\d/.test(c)){
+      var t=null;
+      stream.backUp(1);
+      if(stream.match(/^\d{4}\.\d{2}(m|\.\d{2}([D|T](\d{2}(:\d{2}(:\d{2}(\.\d{1,9})?)?)?)?)?)/)
+      || stream.match(/^\d+D(\d{2}(:\d{2}(:\d{2}(\.\d{1,9})?)?)?)/)
+      || stream.match(/^\d{2}:\d{2}(:\d{2}(\.\d{1,9})?)?/)
+      || stream.match(/^\d+[ptuv]{1}/))
+        t="temporal";
+      else if(stream.match(/^0[NwW]{1}/)
+      || stream.match(/^0x[\d|a-f|A-F]*/)
+      || stream.match(/^[0|1]+[b]{1}/)
+      || stream.match(/^\d+[chijn]{1}/)
+      || stream.match(/-?\d*(\.\d*)?(e[+\-]?\d+)?(e|f)?/))
+        t="number";
+      return(t&&(!(c=stream.peek())||E.test(c)))?t:(stream.next(),"error");
+    }
+    if(/[A-Z|a-z]|\./.test(c))
+      return stream.eatWhile(/[A-Z|a-z|\.|_|\d]/),keywords.test(stream.current())?"keyword":"variable";
+    if(/[|/&^!+:\\\-*%$=~#;@><\.,?_\']/.test(c))
+      return null;
+    if(/[{}\(\[\]\)]/.test(c))
+      return null;
+    return"error";
+  }
+  function tokenLineComment(stream,state){
+    return stream.skipToEnd(),/\/\s*$/.test(stream.current())?(state.tokenize=tokenBlockComment)(stream,state):(state.tokenize=tokenBase),"comment";
+  }
+  function tokenBlockComment(stream,state){
+    var f=stream.sol()&&stream.peek()=="\\";
+    stream.skipToEnd();
+    if(f&&/^\\\s*$/.test(stream.current()))
+      state.tokenize=tokenBase;
+    return"comment";
+  }
+  function tokenCommentToEOF(stream){return stream.skipToEnd(),"comment";}
+  function tokenString(stream,state){
+    var escaped=false,next,end=false;
+    while((next=stream.next())){
+      if(next=="\""&&!escaped){end=true;break;}
+      escaped=!escaped&&next=="\\";
+    }
+    if(end)state.tokenize=tokenBase;
+    return"string";
+  }
+  function pushContext(state,type,col){state.context={prev:state.context,indent:state.indent,col:col,type:type};}
+  function popContext(state){state.indent=state.context.indent;state.context=state.context.prev;}
+  return{
+    startState:function(){
+      return{tokenize:tokenBase,
+             context:null,
+             indent:0,
+             col:0};
+    },
+    token:function(stream,state){
+      if(stream.sol()){
+        if(state.context&&state.context.align==null)
+          state.context.align=false;
+        state.indent=stream.indentation();
+      }
+      //if (stream.eatSpace()) return null;
+      var style=state.tokenize(stream,state);
+      if(style!="comment"&&state.context&&state.context.align==null&&state.context.type!="pattern"){
+        state.context.align=true;
+      }
+      if(curPunc=="(")pushContext(state,")",stream.column());
+      else if(curPunc=="[")pushContext(state,"]",stream.column());
+      else if(curPunc=="{")pushContext(state,"}",stream.column());
+      else if(/[\]\}\)]/.test(curPunc)){
+        while(state.context&&state.context.type=="pattern")popContext(state);
+        if(state.context&&curPunc==state.context.type)popContext(state);
+      }
+      else if(curPunc=="."&&state.context&&state.context.type=="pattern")popContext(state);
+      else if(/atom|string|variable/.test(style)&&state.context){
+        if(/[\}\]]/.test(state.context.type))
+          pushContext(state,"pattern",stream.column());
+        else if(state.context.type=="pattern"&&!state.context.align){
+          state.context.align=true;
+          state.context.col=stream.column();
+        }
+      }
+      return style;
+    },
+    indent:function(state,textAfter){
+      var firstChar=textAfter&&textAfter.charAt(0);
+      var context=state.context;
+      if(/[\]\}]/.test(firstChar))
+        while (context&&context.type=="pattern")context=context.prev;
+      var closing=context&&firstChar==context.type;
+      if(!context)
+        return 0;
+      else if(context.type=="pattern")
+        return context.col;
+      else if(context.align)
+        return context.col+(closing?0:1);
+      else
+        return context.indent+(closing?0:indentUnit);
+    }
+  };
+});
+CodeMirror.defineMIME("text/x-q","q");
diff --git a/third-party/codemirror-3.15/mode/r/LICENSE b/third-party/codemirror-3.15/mode/r/LICENSE
new file mode 100644 (file)
index 0000000..2510ae1
--- /dev/null
@@ -0,0 +1,24 @@
+Copyright (c) 2011, Ubalo, Inc.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+    * Redistributions of source code must retain the above copyright
+      notice, this list of conditions and the following disclaimer.
+    * Redistributions in binary form must reproduce the above copyright
+      notice, this list of conditions and the following disclaimer in the
+      documentation and/or other materials provided with the distribution.
+    * Neither the name of the Ubalo, Inc nor the names of its
+      contributors may be used to endorse or promote products derived
+      from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL UBALO, INC BE LIABLE FOR ANY
+DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/third-party/codemirror-3.15/mode/r/index.html b/third-party/codemirror-3.15/mode/r/index.html
new file mode 100644 (file)
index 0000000..1281955
--- /dev/null
@@ -0,0 +1,74 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: R mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="r.js"></script>
+    <style>
+      .CodeMirror { border-top: 1px solid silver; border-bottom: 1px solid silver; }
+      .cm-s-default span.cm-semi { color: blue; font-weight: bold; }
+      .cm-s-default span.cm-dollar { color: orange; font-weight: bold; }
+      .cm-s-default span.cm-arrow { color: brown; }
+      .cm-s-default span.cm-arg-is { color: brown; }
+    </style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: R mode</h1>
+    <form><textarea id="code" name="code">
+# Code from http://www.mayin.org/ajayshah/KB/R/
+
+# FIRST LEARN ABOUT LISTS --
+X = list(height=5.4, weight=54)
+print("Use default printing --")
+print(X)
+print("Accessing individual elements --")
+cat("Your height is ", X$height, " and your weight is ", X$weight, "\n")
+
+# FUNCTIONS --
+square <- function(x) {
+  return(x*x)
+}
+cat("The square of 3 is ", square(3), "\n")
+
+                 # default value of the arg is set to 5.
+cube <- function(x=5) {
+  return(x*x*x);
+}
+cat("Calling cube with 2 : ", cube(2), "\n")    # will give 2^3
+cat("Calling cube        : ", cube(), "\n")     # will default to 5^3.
+
+# LEARN ABOUT FUNCTIONS THAT RETURN MULTIPLE OBJECTS --
+powers <- function(x) {
+  parcel = list(x2=x*x, x3=x*x*x, x4=x*x*x*x);
+  return(parcel);
+}
+
+X = powers(3);
+print("Showing powers of 3 --"); print(X);
+
+# WRITING THIS COMPACTLY (4 lines instead of 7)
+
+powerful <- function(x) {
+  return(list(x2=x*x, x3=x*x*x, x4=x*x*x*x));
+}
+print("Showing powers of 3 --"); print(powerful(3));
+
+# In R, the last expression in a function is, by default, what is
+# returned. So you could equally just say:
+powerful <- function(x) {list(x2=x*x, x3=x*x*x, x4=x*x*x*x)}
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-rsrc</code>.</p>
+
+    <p>Development of the CodeMirror R mode was kindly sponsored
+    by <a href="http://ubalo.com/">Ubalo</a>, who hold
+    the <a href="LICENSE">license</a>.</p>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/r/r.js b/third-party/codemirror-3.15/mode/r/r.js
new file mode 100644 (file)
index 0000000..6410efb
--- /dev/null
@@ -0,0 +1,141 @@
+CodeMirror.defineMode("r", function(config) {
+  function wordObj(str) {
+    var words = str.split(" "), res = {};
+    for (var i = 0; i < words.length; ++i) res[words[i]] = true;
+    return res;
+  }
+  var atoms = wordObj("NULL NA Inf NaN NA_integer_ NA_real_ NA_complex_ NA_character_");
+  var builtins = wordObj("list quote bquote eval return call parse deparse");
+  var keywords = wordObj("if else repeat while function for in next break");
+  var blockkeywords = wordObj("if else repeat while function for");
+  var opChars = /[+\-*\/^<>=!&|~$:]/;
+  var curPunc;
+
+  function tokenBase(stream, state) {
+    curPunc = null;
+    var ch = stream.next();
+    if (ch == "#") {
+      stream.skipToEnd();
+      return "comment";
+    } else if (ch == "0" && stream.eat("x")) {
+      stream.eatWhile(/[\da-f]/i);
+      return "number";
+    } else if (ch == "." && stream.eat(/\d/)) {
+      stream.match(/\d*(?:e[+\-]?\d+)?/);
+      return "number";
+    } else if (/\d/.test(ch)) {
+      stream.match(/\d*(?:\.\d+)?(?:e[+\-]\d+)?L?/);
+      return "number";
+    } else if (ch == "'" || ch == '"') {
+      state.tokenize = tokenString(ch);
+      return "string";
+    } else if (ch == "." && stream.match(/.[.\d]+/)) {
+      return "keyword";
+    } else if (/[\w\.]/.test(ch) && ch != "_") {
+      stream.eatWhile(/[\w\.]/);
+      var word = stream.current();
+      if (atoms.propertyIsEnumerable(word)) return "atom";
+      if (keywords.propertyIsEnumerable(word)) {
+        if (blockkeywords.propertyIsEnumerable(word)) curPunc = "block";
+        return "keyword";
+      }
+      if (builtins.propertyIsEnumerable(word)) return "builtin";
+      return "variable";
+    } else if (ch == "%") {
+      if (stream.skipTo("%")) stream.next();
+      return "variable-2";
+    } else if (ch == "<" && stream.eat("-")) {
+      return "arrow";
+    } else if (ch == "=" && state.ctx.argList) {
+      return "arg-is";
+    } else if (opChars.test(ch)) {
+      if (ch == "$") return "dollar";
+      stream.eatWhile(opChars);
+      return "operator";
+    } else if (/[\(\){}\[\];]/.test(ch)) {
+      curPunc = ch;
+      if (ch == ";") return "semi";
+      return null;
+    } else {
+      return null;
+    }
+  }
+
+  function tokenString(quote) {
+    return function(stream, state) {
+      if (stream.eat("\\")) {
+        var ch = stream.next();
+        if (ch == "x") stream.match(/^[a-f0-9]{2}/i);
+        else if ((ch == "u" || ch == "U") && stream.eat("{") && stream.skipTo("}")) stream.next();
+        else if (ch == "u") stream.match(/^[a-f0-9]{4}/i);
+        else if (ch == "U") stream.match(/^[a-f0-9]{8}/i);
+        else if (/[0-7]/.test(ch)) stream.match(/^[0-7]{1,2}/);
+        return "string-2";
+      } else {
+        var next;
+        while ((next = stream.next()) != null) {
+          if (next == quote) { state.tokenize = tokenBase; break; }
+          if (next == "\\") { stream.backUp(1); break; }
+        }
+        return "string";
+      }
+    };
+  }
+
+  function push(state, type, stream) {
+    state.ctx = {type: type,
+                 indent: state.indent,
+                 align: null,
+                 column: stream.column(),
+                 prev: state.ctx};
+  }
+  function pop(state) {
+    state.indent = state.ctx.indent;
+    state.ctx = state.ctx.prev;
+  }
+
+  return {
+    startState: function() {
+      return {tokenize: tokenBase,
+              ctx: {type: "top",
+                    indent: -config.indentUnit,
+                    align: false},
+              indent: 0,
+              afterIdent: false};
+    },
+
+    token: function(stream, state) {
+      if (stream.sol()) {
+        if (state.ctx.align == null) state.ctx.align = false;
+        state.indent = stream.indentation();
+      }
+      if (stream.eatSpace()) return null;
+      var style = state.tokenize(stream, state);
+      if (style != "comment" && state.ctx.align == null) state.ctx.align = true;
+
+      var ctype = state.ctx.type;
+      if ((curPunc == ";" || curPunc == "{" || curPunc == "}") && ctype == "block") pop(state);
+      if (curPunc == "{") push(state, "}", stream);
+      else if (curPunc == "(") {
+        push(state, ")", stream);
+        if (state.afterIdent) state.ctx.argList = true;
+      }
+      else if (curPunc == "[") push(state, "]", stream);
+      else if (curPunc == "block") push(state, "block", stream);
+      else if (curPunc == ctype) pop(state);
+      state.afterIdent = style == "variable" || style == "keyword";
+      return style;
+    },
+
+    indent: function(state, textAfter) {
+      if (state.tokenize != tokenBase) return 0;
+      var firstChar = textAfter && textAfter.charAt(0), ctx = state.ctx,
+          closing = firstChar == ctx.type;
+      if (ctx.type == "block") return ctx.indent + (firstChar == "{" ? 0 : config.indentUnit);
+      else if (ctx.align) return ctx.column + (closing ? 0 : 1);
+      else return ctx.indent + (closing ? 0 : config.indentUnit);
+    }
+  };
+});
+
+CodeMirror.defineMIME("text/x-rsrc", "r");
diff --git a/third-party/codemirror-3.15/mode/rpm/changes/changes.js b/third-party/codemirror-3.15/mode/rpm/changes/changes.js
new file mode 100644 (file)
index 0000000..14a08d9
--- /dev/null
@@ -0,0 +1,19 @@
+CodeMirror.defineMode("changes", function() {
+  var headerSeperator = /^-+$/;
+  var headerLine = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)  ?\d{1,2} \d{2}:\d{2}(:\d{2})? [A-Z]{3,4} \d{4} - /;
+  var simpleEmail = /^[\w+.-]+@[\w.-]+/;
+
+  return {
+    token: function(stream) {
+      if (stream.sol()) {
+        if (stream.match(headerSeperator)) { return 'tag'; }
+        if (stream.match(headerLine)) { return 'tag'; }
+      }
+      if (stream.match(simpleEmail)) { return 'string'; }
+      stream.next();
+      return null;
+    }
+  };
+});
+
+CodeMirror.defineMIME("text/x-rpm-changes", "changes");
diff --git a/third-party/codemirror-3.15/mode/rpm/changes/index.html b/third-party/codemirror-3.15/mode/rpm/changes/index.html
new file mode 100644 (file)
index 0000000..e0e2d87
--- /dev/null
@@ -0,0 +1,53 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: RPM changes mode</title>
+    <link rel="stylesheet" href="../../../lib/codemirror.css">
+    <script src="../../../lib/codemirror.js"></script>
+    <script src="changes.js"></script>
+    <link rel="stylesheet" href="../../../doc/docs.css">
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: RPM changes mode</h1>
+    
+    <div><textarea id="code" name="code">
+-------------------------------------------------------------------
+Tue Oct 18 13:58:40 UTC 2011 - misterx@example.com
+
+- Update to r60.3
+- Fixes bug in the reflect package
+  * disallow Interface method on Value obtained via unexported name
+
+-------------------------------------------------------------------
+Thu Oct  6 08:14:24 UTC 2011 - misterx@example.com
+
+- Update to r60.2
+- Fixes memory leak in certain map types
+
+-------------------------------------------------------------------
+Wed Oct  5 14:34:10 UTC 2011 - misterx@example.com
+
+- Tweaks for gdb debugging
+- go.spec changes:
+  - move %go_arch definition to %prep section
+  - pass correct location of go specific gdb pretty printer and
+    functions to cpp as HOST_EXTRA_CFLAGS macro
+  - install go gdb functions & printer
+- gdb-printer.patch
+  - patch linker (src/cmd/ld/dwarf.c) to emit correct location of go
+    gdb functions and pretty printer
+</textarea></div>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        mode: {name: "changes"},
+        lineNumbers: true,
+        indentUnit: 4,
+        tabMode: "shift"
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-rpm-changes</code>.</p>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/rpm/spec/index.html b/third-party/codemirror-3.15/mode/rpm/spec/index.html
new file mode 100644 (file)
index 0000000..8be98b6
--- /dev/null
@@ -0,0 +1,99 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: RPM spec mode</title>
+    <link rel="stylesheet" href="../../../lib/codemirror.css">
+    <script src="../../../lib/codemirror.js"></script>
+    <script src="spec.js"></script>
+    <link rel="stylesheet" href="spec.css">
+    <link rel="stylesheet" href="../../../doc/docs.css">
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: RPM spec mode</h1>
+    
+    <div><textarea id="code" name="code">
+#
+# spec file for package minidlna
+#
+# Copyright (c) 2011, Sascha Peilicke <saschpe@gmx.de>
+#
+# All modifications and additions to the file contributed by third parties
+# remain the property of their copyright owners, unless otherwise agreed
+# upon. The license for this file, and modifications and additions to the
+# file, is the same license as for the pristine package itself (unless the
+# license for the pristine package is not an Open Source License, in which
+# case the license is the MIT License). An "Open Source License" is a
+# license that conforms to the Open Source Definition (Version 1.9)
+# published by the Open Source Initiative.
+
+
+Name:           libupnp6
+Version:        1.6.13
+Release:        0
+Summary:        Portable Universal Plug and Play (UPnP) SDK
+Group:          System/Libraries
+License:        BSD-3-Clause
+Url:            http://sourceforge.net/projects/pupnp/
+Source0:        http://downloads.sourceforge.net/pupnp/libupnp-%{version}.tar.bz2
+BuildRoot:      %{_tmppath}/%{name}-%{version}-build
+
+%description
+The portable Universal Plug and Play (UPnP) SDK provides support for building
+UPnP-compliant control points, devices, and bridges on several operating
+systems.
+
+%package -n libupnp-devel
+Summary:        Portable Universal Plug and Play (UPnP) SDK
+Group:          Development/Libraries/C and C++
+Provides:       pkgconfig(libupnp)
+Requires:       %{name} = %{version}
+
+%description -n libupnp-devel
+The portable Universal Plug and Play (UPnP) SDK provides support for building
+UPnP-compliant control points, devices, and bridges on several operating
+systems.
+
+%prep
+%setup -n libupnp-%{version}
+
+%build
+%configure --disable-static
+make %{?_smp_mflags}
+
+%install
+%makeinstall
+find %{buildroot} -type f -name '*.la' -exec rm -f {} ';'
+
+%post -p /sbin/ldconfig
+
+%postun -p /sbin/ldconfig
+
+%files
+%defattr(-,root,root,-)
+%doc ChangeLog NEWS README TODO
+%{_libdir}/libixml.so.*
+%{_libdir}/libthreadutil.so.*
+%{_libdir}/libupnp.so.*
+
+%files -n libupnp-devel
+%defattr(-,root,root,-)
+%{_libdir}/pkgconfig/libupnp.pc
+%{_libdir}/libixml.so
+%{_libdir}/libthreadutil.so
+%{_libdir}/libupnp.so
+%{_includedir}/upnp/
+
+%changelog</textarea></div>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        mode: {name: "spec"},
+        lineNumbers: true,
+        indentUnit: 4
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-rpm-spec</code>.</p>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/rpm/spec/spec.css b/third-party/codemirror-3.15/mode/rpm/spec/spec.css
new file mode 100644 (file)
index 0000000..d0a5d43
--- /dev/null
@@ -0,0 +1,5 @@
+.cm-s-default span.cm-preamble {color: #b26818; font-weight: bold;}
+.cm-s-default span.cm-macro {color: #b218b2;}
+.cm-s-default span.cm-section {color: green; font-weight: bold;}
+.cm-s-default span.cm-script {color: red;}
+.cm-s-default span.cm-issue {color: yellow;}
diff --git a/third-party/codemirror-3.15/mode/rpm/spec/spec.js b/third-party/codemirror-3.15/mode/rpm/spec/spec.js
new file mode 100644 (file)
index 0000000..9f339c2
--- /dev/null
@@ -0,0 +1,66 @@
+// Quick and dirty spec file highlighting
+
+CodeMirror.defineMode("spec", function() {
+  var arch = /^(i386|i586|i686|x86_64|ppc64|ppc|ia64|s390x|s390|sparc64|sparcv9|sparc|noarch|alphaev6|alpha|hppa|mipsel)/;
+
+  var preamble = /^(Name|Version|Release|License|Summary|Url|Group|Source|BuildArch|BuildRequires|BuildRoot|AutoReqProv|Provides|Requires(\(\w+\))?|Obsoletes|Conflicts|Recommends|Source\d*|Patch\d*|ExclusiveArch|NoSource|Supplements):/;
+  var section = /^%(debug_package|package|description|prep|build|install|files|clean|changelog|preun|postun|pre|post|triggerin|triggerun|pretrans|posttrans|verifyscript|check|triggerpostun|triggerprein|trigger)/;
+  var control_flow_complex = /^%(ifnarch|ifarch|if)/; // rpm control flow macros
+  var control_flow_simple = /^%(else|endif)/; // rpm control flow macros
+  var operators = /^(\!|\?|\<\=|\<|\>\=|\>|\=\=|\&\&|\|\|)/; // operators in control flow macros
+
+  return {
+    startState: function () {
+        return {
+          controlFlow: false,
+          macroParameters: false,
+          section: false
+        };
+    },
+    token: function (stream, state) {
+      var ch = stream.peek();
+      if (ch == "#") { stream.skipToEnd(); return "comment"; }
+
+      if (stream.sol()) {
+        if (stream.match(preamble)) { return "preamble"; }
+        if (stream.match(section)) { return "section"; }
+      }
+
+      if (stream.match(/^\$\w+/)) { return "def"; } // Variables like '$RPM_BUILD_ROOT'
+      if (stream.match(/^\$\{\w+\}/)) { return "def"; } // Variables like '${RPM_BUILD_ROOT}'
+
+      if (stream.match(control_flow_simple)) { return "keyword"; }
+      if (stream.match(control_flow_complex)) {
+        state.controlFlow = true;
+        return "keyword";
+      }
+      if (state.controlFlow) {
+        if (stream.match(operators)) { return "operator"; }
+        if (stream.match(/^(\d+)/)) { return "number"; }
+        if (stream.eol()) { state.controlFlow = false; }
+      }
+
+      if (stream.match(arch)) { return "number"; }
+
+      // Macros like '%make_install' or '%attr(0775,root,root)'
+      if (stream.match(/^%[\w]+/)) {
+        if (stream.match(/^\(/)) { state.macroParameters = true; }
+        return "macro";
+      }
+      if (state.macroParameters) {
+        if (stream.match(/^\d+/)) { return "number";}
+        if (stream.match(/^\)/)) {
+          state.macroParameters = false;
+          return "macro";
+        }
+      }
+      if (stream.match(/^%\{\??[\w \-]+\}/)) { return "macro"; } // Macros like '%{defined fedora}'
+
+      //TODO: Include bash script sub-parser (CodeMirror supports that)
+      stream.next();
+      return null;
+    }
+  };
+});
+
+CodeMirror.defineMIME("text/x-rpm-spec", "spec");
diff --git a/third-party/codemirror-3.15/mode/rst/LICENSE.txt b/third-party/codemirror-3.15/mode/rst/LICENSE.txt
new file mode 100644 (file)
index 0000000..c40984a
--- /dev/null
@@ -0,0 +1,21 @@
+The MIT License
+
+Copyright (c) 2013 Hasan Karahan <hasan.karahan81@gmail.com>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
\ No newline at end of file
diff --git a/third-party/codemirror-3.15/mode/rst/index.html b/third-party/codemirror-3.15/mode/rst/index.html
new file mode 100644 (file)
index 0000000..b3ab64b
--- /dev/null
@@ -0,0 +1,524 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: reStructuredText mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="rst.js"></script>
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: reStructuredText mode</h1>
+
+<form><textarea id="code" name="code">
+.. This is an excerpt from Sphinx documentation: http://sphinx.pocoo.org/_sources/rest.txt
+
+.. highlightlang:: rest
+
+.. _rst-primer:
+
+reStructuredText Primer
+=======================
+
+This section is a brief introduction to reStructuredText (reST) concepts and
+syntax, intended to provide authors with enough information to author documents
+productively.  Since reST was designed to be a simple, unobtrusive markup
+language, this will not take too long.
+
+.. seealso::
+
+   The authoritative `reStructuredText User Documentation
+   &lt;http://docutils.sourceforge.net/rst.html&gt;`_.  The "ref" links in this
+   document link to the description of the individual constructs in the reST
+   reference.
+
+
+Paragraphs
+----------
+
+The paragraph (:duref:`ref &lt;paragraphs&gt;`) is the most basic block in a reST
+document.  Paragraphs are simply chunks of text separated by one or more blank
+lines.  As in Python, indentation is significant in reST, so all lines of the
+same paragraph must be left-aligned to the same level of indentation.
+
+
+.. _inlinemarkup:
+
+Inline markup
+-------------
+
+The standard reST inline markup is quite simple: use
+
+* one asterisk: ``*text*`` for emphasis (italics),
+* two asterisks: ``**text**`` for strong emphasis (boldface), and
+* backquotes: ````text```` for code samples.
+
+If asterisks or backquotes appear in running text and could be confused with
+inline markup delimiters, they have to be escaped with a backslash.
+
+Be aware of some restrictions of this markup:
+
+* it may not be nested,
+* content may not start or end with whitespace: ``* text*`` is wrong,
+* it must be separated from surrounding text by non-word characters.  Use a
+  backslash escaped space to work around that: ``thisis\ *one*\ word``.
+
+These restrictions may be lifted in future versions of the docutils.
+
+reST also allows for custom "interpreted text roles"', which signify that the
+enclosed text should be interpreted in a specific way.  Sphinx uses this to
+provide semantic markup and cross-referencing of identifiers, as described in
+the appropriate section.  The general syntax is ``:rolename:`content```.
+
+Standard reST provides the following roles:
+
+* :durole:`emphasis` -- alternate spelling for ``*emphasis*``
+* :durole:`strong` -- alternate spelling for ``**strong**``
+* :durole:`literal` -- alternate spelling for ````literal````
+* :durole:`subscript` -- subscript text
+* :durole:`superscript` -- superscript text
+* :durole:`title-reference` -- for titles of books, periodicals, and other
+  materials
+
+See :ref:`inline-markup` for roles added by Sphinx.
+
+
+Lists and Quote-like blocks
+---------------------------
+
+List markup (:duref:`ref &lt;bullet-lists&gt;`) is natural: just place an asterisk at
+the start of a paragraph and indent properly.  The same goes for numbered lists;
+they can also be autonumbered using a ``#`` sign::
+
+   * This is a bulleted list.
+   * It has two items, the second
+     item uses two lines.
+
+   1. This is a numbered list.
+   2. It has two items too.
+
+   #. This is a numbered list.
+   #. It has two items too.
+
+
+Nested lists are possible, but be aware that they must be separated from the
+parent list items by blank lines::
+
+   * this is
+   * a list
+
+     * with a nested list
+     * and some subitems
+
+   * and here the parent list continues
+
+Definition lists (:duref:`ref &lt;definition-lists&gt;`) are created as follows::
+
+   term (up to a line of text)
+      Definition of the term, which must be indented
+
+      and can even consist of multiple paragraphs
+
+   next term
+      Description.
+
+Note that the term cannot have more than one line of text.
+
+Quoted paragraphs (:duref:`ref &lt;block-quotes&gt;`) are created by just indenting
+them more than the surrounding paragraphs.
+
+Line blocks (:duref:`ref &lt;line-blocks&gt;`) are a way of preserving line breaks::
+
+   | These lines are
+   | broken exactly like in
+   | the source file.
+
+There are also several more special blocks available:
+
+* field lists (:duref:`ref &lt;field-lists&gt;`)
+* option lists (:duref:`ref &lt;option-lists&gt;`)
+* quoted literal blocks (:duref:`ref &lt;quoted-literal-blocks&gt;`)
+* doctest blocks (:duref:`ref &lt;doctest-blocks&gt;`)
+
+
+Source Code
+-----------
+
+Literal code blocks (:duref:`ref &lt;literal-blocks&gt;`) are introduced by ending a
+paragraph with the special marker ``::``.  The literal block must be indented
+(and, like all paragraphs, separated from the surrounding ones by blank lines)::
+
+   This is a normal text paragraph. The next paragraph is a code sample::
+
+      It is not processed in any way, except
+      that the indentation is removed.
+
+      It can span multiple lines.
+
+   This is a normal text paragraph again.
+
+The handling of the ``::`` marker is smart:
+
+* If it occurs as a paragraph of its own, that paragraph is completely left
+  out of the document.
+* If it is preceded by whitespace, the marker is removed.
+* If it is preceded by non-whitespace, the marker is replaced by a single
+  colon.
+
+That way, the second sentence in the above example's first paragraph would be
+rendered as "The next paragraph is a code sample:".
+
+
+.. _rst-tables:
+
+Tables
+------
+
+Two forms of tables are supported.  For *grid tables* (:duref:`ref
+&lt;grid-tables&gt;`), you have to "paint" the cell grid yourself.  They look like
+this::
+
+   +------------------------+------------+----------+----------+
+   | Header row, column 1   | Header 2   | Header 3 | Header 4 |
+   | (header rows optional) |            |          |          |
+   +========================+============+==========+==========+
+   | body row 1, column 1   | column 2   | column 3 | column 4 |
+   +------------------------+------------+----------+----------+
+   | body row 2             | ...        | ...      |          |
+   +------------------------+------------+----------+----------+
+
+*Simple tables* (:duref:`ref &lt;simple-tables&gt;`) are easier to write, but
+limited: they must contain more than one row, and the first column cannot
+contain multiple lines.  They look like this::
+
+   =====  =====  =======
+   A      B      A and B
+   =====  =====  =======
+   False  False  False
+   True   False  False
+   False  True   False
+   True   True   True
+   =====  =====  =======
+
+
+Hyperlinks
+----------
+
+External links
+^^^^^^^^^^^^^^
+
+Use ```Link text &lt;http://example.com/&gt;`_`` for inline web links.  If the link
+text should be the web address, you don't need special markup at all, the parser
+finds links and mail addresses in ordinary text.
+
+You can also separate the link and the target definition (:duref:`ref
+&lt;hyperlink-targets&gt;`), like this::
+
+   This is a paragraph that contains `a link`_.
+
+   .. _a link: http://example.com/
+
+
+Internal links
+^^^^^^^^^^^^^^
+
+Internal linking is done via a special reST role provided by Sphinx, see the
+section on specific markup, :ref:`ref-role`.
+
+
+Sections
+--------
+
+Section headers (:duref:`ref &lt;sections&gt;`) are created by underlining (and
+optionally overlining) the section title with a punctuation character, at least
+as long as the text::
+
+   =================
+   This is a heading
+   =================
+
+Normally, there are no heading levels assigned to certain characters as the
+structure is determined from the succession of headings.  However, for the
+Python documentation, this convention is used which you may follow:
+
+* ``#`` with overline, for parts
+* ``*`` with overline, for chapters
+* ``=``, for sections
+* ``-``, for subsections
+* ``^``, for subsubsections
+* ``"``, for paragraphs
+
+Of course, you are free to use your own marker characters (see the reST
+documentation), and use a deeper nesting level, but keep in mind that most
+target formats (HTML, LaTeX) have a limited supported nesting depth.
+
+
+Explicit Markup
+---------------
+
+"Explicit markup" (:duref:`ref &lt;explicit-markup-blocks&gt;`) is used in reST for
+most constructs that need special handling, such as footnotes,
+specially-highlighted paragraphs, comments, and generic directives.
+
+An explicit markup block begins with a line starting with ``..`` followed by
+whitespace and is terminated by the next paragraph at the same level of
+indentation.  (There needs to be a blank line between explicit markup and normal
+paragraphs.  This may all sound a bit complicated, but it is intuitive enough
+when you write it.)
+
+
+.. _directives:
+
+Directives
+----------
+
+A directive (:duref:`ref &lt;directives&gt;`) is a generic block of explicit markup.
+Besides roles, it is one of the extension mechanisms of reST, and Sphinx makes
+heavy use of it.
+
+Docutils supports the following directives:
+
+* Admonitions: :dudir:`attention`, :dudir:`caution`, :dudir:`danger`,
+  :dudir:`error`, :dudir:`hint`, :dudir:`important`, :dudir:`note`,
+  :dudir:`tip`, :dudir:`warning` and the generic :dudir:`admonition`.
+  (Most themes style only "note" and "warning" specially.)
+
+* Images:
+
+  - :dudir:`image` (see also Images_ below)
+  - :dudir:`figure` (an image with caption and optional legend)
+
+* Additional body elements:
+
+  - :dudir:`contents` (a local, i.e. for the current file only, table of
+    contents)
+  - :dudir:`container` (a container with a custom class, useful to generate an
+    outer ``&lt;div&gt;`` in HTML)
+  - :dudir:`rubric` (a heading without relation to the document sectioning)
+  - :dudir:`topic`, :dudir:`sidebar` (special highlighted body elements)
+  - :dudir:`parsed-literal` (literal block that supports inline markup)
+  - :dudir:`epigraph` (a block quote with optional attribution line)
+  - :dudir:`highlights`, :dudir:`pull-quote` (block quotes with their own
+    class attribute)
+  - :dudir:`compound` (a compound paragraph)
+
+* Special tables:
+
+  - :dudir:`table` (a table with title)
+  - :dudir:`csv-table` (a table generated from comma-separated values)
+  - :dudir:`list-table` (a table generated from a list of lists)
+
+* Special directives:
+
+  - :dudir:`raw` (include raw target-format markup)
+  - :dudir:`include` (include reStructuredText from another file)
+    -- in Sphinx, when given an absolute include file path, this directive takes
+    it as relative to the source directory
+  - :dudir:`class` (assign a class attribute to the next element) [1]_
+
+* HTML specifics:
+
+  - :dudir:`meta` (generation of HTML ``&lt;meta&gt;`` tags)
+  - :dudir:`title` (override document title)
+
+* Influencing markup:
+
+  - :dudir:`default-role` (set a new default role)
+  - :dudir:`role` (create a new role)
+
+  Since these are only per-file, better use Sphinx' facilities for setting the
+  :confval:`default_role`.
+
+Do *not* use the directives :dudir:`sectnum`, :dudir:`header` and
+:dudir:`footer`.
+
+Directives added by Sphinx are described in :ref:`sphinxmarkup`.
+
+Basically, a directive consists of a name, arguments, options and content. (Keep
+this terminology in mind, it is used in the next chapter describing custom
+directives.)  Looking at this example, ::
+
+   .. function:: foo(x)
+                 foo(y, z)
+      :module: some.module.name
+
+      Return a line of text input from the user.
+
+``function`` is the directive name.  It is given two arguments here, the
+remainder of the first line and the second line, as well as one option
+``module`` (as you can see, options are given in the lines immediately following
+the arguments and indicated by the colons).  Options must be indented to the
+same level as the directive content.
+
+The directive content follows after a blank line and is indented relative to the
+directive start.
+
+
+Images
+------
+
+reST supports an image directive (:dudir:`ref &lt;image&gt;`), used like so::
+
+   .. image:: gnu.png
+      (options)
+
+When used within Sphinx, the file name given (here ``gnu.png``) must either be
+relative to the source file, or absolute which means that they are relative to
+the top source directory.  For example, the file ``sketch/spam.rst`` could refer
+to the image ``images/spam.png`` as ``../images/spam.png`` or
+``/images/spam.png``.
+
+Sphinx will automatically copy image files over to a subdirectory of the output
+directory on building (e.g. the ``_static`` directory for HTML output.)
+
+Interpretation of image size options (``width`` and ``height``) is as follows:
+if the size has no unit or the unit is pixels, the given size will only be
+respected for output channels that support pixels (i.e. not in LaTeX output).
+Other units (like ``pt`` for points) will be used for HTML and LaTeX output.
+
+Sphinx extends the standard docutils behavior by allowing an asterisk for the
+extension::
+
+   .. image:: gnu.*
+
+Sphinx then searches for all images matching the provided pattern and determines
+their type.  Each builder then chooses the best image out of these candidates.
+For instance, if the file name ``gnu.*`` was given and two files :file:`gnu.pdf`
+and :file:`gnu.png` existed in the source tree, the LaTeX builder would choose
+the former, while the HTML builder would prefer the latter.
+
+.. versionchanged:: 0.4
+   Added the support for file names ending in an asterisk.
+
+.. versionchanged:: 0.6
+   Image paths can now be absolute.
+
+
+Footnotes
+---------
+
+For footnotes (:duref:`ref &lt;footnotes&gt;`), use ``[#name]_`` to mark the footnote
+location, and add the footnote body at the bottom of the document after a
+"Footnotes" rubric heading, like so::
+
+   Lorem ipsum [#f1]_ dolor sit amet ... [#f2]_
+
+   .. rubric:: Footnotes
+
+   .. [#f1] Text of the first footnote.
+   .. [#f2] Text of the second footnote.
+
+You can also explicitly number the footnotes (``[1]_``) or use auto-numbered
+footnotes without names (``[#]_``).
+
+
+Citations
+---------
+
+Standard reST citations (:duref:`ref &lt;citations&gt;`) are supported, with the
+additional feature that they are "global", i.e. all citations can be referenced
+from all files.  Use them like so::
+
+   Lorem ipsum [Ref]_ dolor sit amet.
+
+   .. [Ref] Book or article reference, URL or whatever.
+
+Citation usage is similar to footnote usage, but with a label that is not
+numeric or begins with ``#``.
+
+
+Substitutions
+-------------
+
+reST supports "substitutions" (:duref:`ref &lt;substitution-definitions&gt;`), which
+are pieces of text and/or markup referred to in the text by ``|name|``.  They
+are defined like footnotes with explicit markup blocks, like this::
+
+   .. |name| replace:: replacement *text*
+
+or this::
+
+   .. |caution| image:: warning.png
+                :alt: Warning!
+
+See the :duref:`reST reference for substitutions &lt;substitution-definitions&gt;`
+for details.
+
+If you want to use some substitutions for all documents, put them into
+:confval:`rst_prolog` or put them into a separate file and include it into all
+documents you want to use them in, using the :rst:dir:`include` directive.  (Be
+sure to give the include file a file name extension differing from that of other
+source files, to avoid Sphinx finding it as a standalone document.)
+
+Sphinx defines some default substitutions, see :ref:`default-substitutions`.
+
+
+Comments
+--------
+
+Every explicit markup block which isn't a valid markup construct (like the
+footnotes above) is regarded as a comment (:duref:`ref &lt;comments&gt;`).  For
+example::
+
+   .. This is a comment.
+
+You can indent text after a comment start to form multiline comments::
+
+   ..
+      This whole indented block
+      is a comment.
+
+      Still in the comment.
+
+
+Source encoding
+---------------
+
+Since the easiest way to include special characters like em dashes or copyright
+signs in reST is to directly write them as Unicode characters, one has to
+specify an encoding.  Sphinx assumes source files to be encoded in UTF-8 by
+default; you can change this with the :confval:`source_encoding` config value.
+
+
+Gotchas
+-------
+
+There are some problems one commonly runs into while authoring reST documents:
+
+* **Separation of inline markup:** As said above, inline markup spans must be
+  separated from the surrounding text by non-word characters, you have to use a
+  backslash-escaped space to get around that.  See `the reference
+  &lt;http://docutils.sf.net/docs/ref/rst/restructuredtext.html#inline-markup&gt;`_
+  for the details.
+
+* **No nested inline markup:** Something like ``*see :func:`foo`*`` is not
+  possible.
+
+
+.. rubric:: Footnotes
+
+.. [1] When the default domain contains a :rst:dir:`class` directive, this directive
+       will be shadowed.  Therefore, Sphinx re-exports it as :rst:dir:`rst-class`.
+</textarea></form>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+      });
+    </script>
+    <p>
+        The <code>python</code> mode will be used for highlighting blocks
+        containing Python/IPython terminal sessions: blocks starting with
+        <code>&gt;&gt;&gt;</code> (for Python) or <code>In [num]:</code> (for
+        IPython).
+
+        Further, the <code>stex</code> mode will be used for highlighting
+        blocks containing LaTex code.
+    </p>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-rst</code>.</p>
+  </body>
+</html>
+
diff --git a/third-party/codemirror-3.15/mode/rst/rst.js b/third-party/codemirror-3.15/mode/rst/rst.js
new file mode 100644 (file)
index 0000000..508896d
--- /dev/null
@@ -0,0 +1,561 @@
+CodeMirror.defineMode('rst-base', function (config) {
+
+    ///////////////////////////////////////////////////////////////////////////
+    ///////////////////////////////////////////////////////////////////////////
+
+    function format(string) {
+        var args = Array.prototype.slice.call(arguments, 1);
+        return string.replace(/{(\d+)}/g, function (match, n) {
+            return typeof args[n] != 'undefined' ? args[n] : match;
+        });
+    }
+
+    function AssertException(message) {
+        this.message = message;
+    }
+
+    AssertException.prototype.toString = function () {
+        return 'AssertException: ' + this.message;
+    };
+
+    function assert(expression, message) {
+        if (!expression) throw new AssertException(message);
+        return expression;
+    }
+
+    ///////////////////////////////////////////////////////////////////////////
+    ///////////////////////////////////////////////////////////////////////////
+
+    var mode_python = CodeMirror.getMode(config, 'python');
+    var mode_stex = CodeMirror.getMode(config, 'stex');
+
+    ///////////////////////////////////////////////////////////////////////////
+    ///////////////////////////////////////////////////////////////////////////
+
+    var SEPA = "\\s+";
+    var TAIL = "(?:\\s*|\\W|$)",
+        rx_TAIL = new RegExp(format('^{0}', TAIL));
+
+    var NAME =
+        "(?:[^\\W\\d_](?:[\\w!\"#$%&'()\\*\\+,\\-\\.\/:;<=>\\?]*[^\\W_])?)",
+        rx_NAME = new RegExp(format('^{0}', NAME));
+    var NAME_WWS =
+        "(?:[^\\W\\d_](?:[\\w\\s!\"#$%&'()\\*\\+,\\-\\.\/:;<=>\\?]*[^\\W_])?)";
+    var REF_NAME = format('(?:{0}|`{1}`)', NAME, NAME_WWS);
+
+    var TEXT1 = "(?:[^\\s\\|](?:[^\\|]*[^\\s\\|])?)";
+    var TEXT2 = "(?:[^\\`]+)",
+        rx_TEXT2 = new RegExp(format('^{0}', TEXT2));
+
+    var rx_section = new RegExp(
+        "^([!'#$%&\"()*+,-./:;<=>?@\\[\\\\\\]^_`{|}~])\\1{3,}\\s*$");
+    var rx_explicit = new RegExp(
+        format('^\\.\\.{0}', SEPA));
+    var rx_link = new RegExp(
+        format('^_{0}:{1}|^__:{1}', REF_NAME, TAIL));
+    var rx_directive = new RegExp(
+        format('^{0}::{1}', REF_NAME, TAIL));
+    var rx_substitution = new RegExp(
+        format('^\\|{0}\\|{1}{2}::{3}', TEXT1, SEPA, REF_NAME, TAIL));
+    var rx_footnote = new RegExp(
+        format('^\\[(?:\\d+|#{0}?|\\*)]{1}', REF_NAME, TAIL));
+    var rx_citation = new RegExp(
+        format('^\\[{0}\\]{1}', REF_NAME, TAIL));
+
+    var rx_substitution_ref = new RegExp(
+        format('^\\|{0}\\|', TEXT1));
+    var rx_footnote_ref = new RegExp(
+        format('^\\[(?:\\d+|#{0}?|\\*)]_', REF_NAME));
+    var rx_citation_ref = new RegExp(
+        format('^\\[{0}\\]_', REF_NAME));
+    var rx_link_ref1 = new RegExp(
+        format('^{0}__?', REF_NAME));
+    var rx_link_ref2 = new RegExp(
+        format('^`{0}`_', TEXT2));
+
+    var rx_role_pre = new RegExp(
+        format('^:{0}:`{1}`{2}', NAME, TEXT2, TAIL));
+    var rx_role_suf = new RegExp(
+        format('^`{1}`:{0}:{2}', NAME, TEXT2, TAIL));
+    var rx_role = new RegExp(
+        format('^:{0}:{1}', NAME, TAIL));
+
+    var rx_directive_name = new RegExp(format('^{0}', REF_NAME));
+    var rx_directive_tail = new RegExp(format('^::{0}', TAIL));
+    var rx_substitution_text = new RegExp(format('^\\|{0}\\|', TEXT1));
+    var rx_substitution_sepa = new RegExp(format('^{0}', SEPA));
+    var rx_substitution_name = new RegExp(format('^{0}', REF_NAME));
+    var rx_substitution_tail = new RegExp(format('^::{0}', TAIL));
+    var rx_link_head = new RegExp("^_");
+    var rx_link_name = new RegExp(format('^{0}|_', REF_NAME));
+    var rx_link_tail = new RegExp(format('^:{0}', TAIL));
+
+    var rx_verbatim = new RegExp('^::\\s*$');
+    var rx_examples = new RegExp('^\\s+(?:>>>|In \\[\\d+\\]:)\\s');
+
+    ///////////////////////////////////////////////////////////////////////////
+    ///////////////////////////////////////////////////////////////////////////
+
+    function to_normal(stream, state) {
+        var token = null;
+
+        if (stream.sol() && stream.match(rx_examples, false)) {
+            change(state, to_mode, {
+                mode: mode_python, local: mode_python.startState()
+            });
+        } else if (stream.sol() && stream.match(rx_explicit)) {
+            change(state, to_explicit);
+            token = 'meta';
+        } else if (stream.sol() && stream.match(rx_section)) {
+            change(state, to_normal);
+            token = 'header';
+        } else if (phase(state) == rx_role_pre ||
+            stream.match(rx_role_pre, false)) {
+
+            switch (stage(state)) {
+                case 0:
+                    change(state, to_normal, context(rx_role_pre, 1));
+                    assert(stream.match(/^:/));
+                    token = 'meta';
+                    break;
+                case 1:
+                    change(state, to_normal, context(rx_role_pre, 2));
+                    assert(stream.match(rx_NAME));
+                    token = 'keyword';
+
+                    if (stream.current().match(/^(?:math|latex)/)) {
+                        state.tmp = {
+                            mode: mode_stex, local: mode_stex.startState()
+                        };
+                    }
+                    break;
+                case 2:
+                    change(state, to_normal, context(rx_role_pre, 3));
+                    assert(stream.match(/^:`/));
+                    token = 'meta';
+                    break;
+                case 3:
+                    if (state.tmp) {
+                        if (stream.peek() == '`') {
+                            change(state, to_normal, context(rx_role_pre, 4));
+                            state.tmp = undefined;
+                            break;
+                        }
+
+                        token = state.tmp.mode.token(stream, state.tmp.local);
+                        break;
+                    }
+
+                    change(state, to_normal, context(rx_role_pre, 4));
+                    assert(stream.match(rx_TEXT2));
+                    token = 'string';
+                    break;
+                case 4:
+                    change(state, to_normal, context(rx_role_pre, 5));
+                    assert(stream.match(/^`/));
+                    token = 'meta';
+                    break;
+                case 5:
+                    change(state, to_normal, context(rx_role_pre, 6));
+                    assert(stream.match(rx_TAIL));
+                    break;
+                default:
+                    change(state, to_normal);
+                    assert(stream.current() == '');
+            }
+        } else if (phase(state) == rx_role_suf ||
+            stream.match(rx_role_suf, false)) {
+
+            switch (stage(state)) {
+                case 0:
+                    change(state, to_normal, context(rx_role_suf, 1));
+                    assert(stream.match(/^`/));
+                    token = 'meta';
+                    break;
+                case 1:
+                    change(state, to_normal, context(rx_role_suf, 2));
+                    assert(stream.match(rx_TEXT2));
+                    token = 'string';
+                    break;
+                case 2:
+                    change(state, to_normal, context(rx_role_suf, 3));
+                    assert(stream.match(/^`:/));
+                    token = 'meta';
+                    break;
+                case 3:
+                    change(state, to_normal, context(rx_role_suf, 4));
+                    assert(stream.match(rx_NAME));
+                    token = 'keyword';
+                    break;
+                case 4:
+                    change(state, to_normal, context(rx_role_suf, 5));
+                    assert(stream.match(/^:/));
+                    token = 'meta';
+                    break;
+                case 5:
+                    change(state, to_normal, context(rx_role_suf, 6));
+                    assert(stream.match(rx_TAIL));
+                    break;
+                default:
+                    change(state, to_normal);
+                    assert(stream.current() == '');
+            }
+        } else if (phase(state) == rx_role || stream.match(rx_role, false)) {
+
+            switch (stage(state)) {
+                case 0:
+                    change(state, to_normal, context(rx_role, 1));
+                    assert(stream.match(/^:/));
+                    token = 'meta';
+                    break;
+                case 1:
+                    change(state, to_normal, context(rx_role, 2));
+                    assert(stream.match(rx_NAME));
+                    token = 'keyword';
+                    break;
+                case 2:
+                    change(state, to_normal, context(rx_role, 3));
+                    assert(stream.match(/^:/));
+                    token = 'meta';
+                    break;
+                case 3:
+                    change(state, to_normal, context(rx_role, 4));
+                    assert(stream.match(rx_TAIL));
+                    break;
+                default:
+                    change(state, to_normal);
+                    assert(stream.current() == '');
+            }
+        } else if (phase(state) == rx_substitution_ref ||
+            stream.match(rx_substitution_ref, false)) {
+
+            switch (stage(state)) {
+                case 0:
+                    change(state, to_normal, context(rx_substitution_ref, 1));
+                    assert(stream.match(rx_substitution_text));
+                    token = 'variable-2';
+                    break;
+                case 1:
+                    change(state, to_normal, context(rx_substitution_ref, 2));
+                    if (stream.match(/^_?_?/)) token = 'link';
+                    break;
+                default:
+                    change(state, to_normal);
+                    assert(stream.current() == '');
+            }
+        } else if (stream.match(rx_footnote_ref)) {
+            change(state, to_normal);
+            token = 'quote';
+        } else if (stream.match(rx_citation_ref)) {
+            change(state, to_normal);
+            token = 'quote';
+        } else if (stream.match(rx_link_ref1)) {
+            change(state, to_normal);
+            if (!stream.peek() || stream.peek().match(/^\W$/)) {
+                token = 'link';
+            }
+        } else if (phase(state) == rx_link_ref2 ||
+            stream.match(rx_link_ref2, false)) {
+
+            switch (stage(state)) {
+                case 0:
+                    if (!stream.peek() || stream.peek().match(/^\W$/)) {
+                        change(state, to_normal, context(rx_link_ref2, 1));
+                    } else {
+                        stream.match(rx_link_ref2);
+                    }
+                    break;
+                case 1:
+                    change(state, to_normal, context(rx_link_ref2, 2));
+                    assert(stream.match(/^`/));
+                    token = 'link';
+                    break;
+                case 2:
+                    change(state, to_normal, context(rx_link_ref2, 3));
+                    assert(stream.match(rx_TEXT2));
+                    break;
+                case 3:
+                    change(state, to_normal, context(rx_link_ref2, 4));
+                    assert(stream.match(/^`_/));
+                    token = 'link';
+                    break;
+                default:
+                    change(state, to_normal);
+                    assert(stream.current() == '');
+            }
+        } else if (stream.match(rx_verbatim)) {
+            change(state, to_verbatim);
+        }
+
+        else {
+            if (stream.next()) change(state, to_normal);
+        }
+
+        return token;
+    }
+
+    ///////////////////////////////////////////////////////////////////////////
+    ///////////////////////////////////////////////////////////////////////////
+
+    function to_explicit(stream, state) {
+        var token = null;
+
+        if (phase(state) == rx_substitution ||
+            stream.match(rx_substitution, false)) {
+
+            switch (stage(state)) {
+                case 0:
+                    change(state, to_explicit, context(rx_substitution, 1));
+                    assert(stream.match(rx_substitution_text));
+                    token = 'variable-2';
+                    break;
+                case 1:
+                    change(state, to_explicit, context(rx_substitution, 2));
+                    assert(stream.match(rx_substitution_sepa));
+                    break;
+                case 2:
+                    change(state, to_explicit, context(rx_substitution, 3));
+                    assert(stream.match(rx_substitution_name));
+                    token = 'keyword';
+                    break;
+                case 3:
+                    change(state, to_explicit, context(rx_substitution, 4));
+                    assert(stream.match(rx_substitution_tail));
+                    token = 'meta';
+                    break;
+                default:
+                    change(state, to_normal);
+                    assert(stream.current() == '');
+            }
+        } else if (phase(state) == rx_directive ||
+            stream.match(rx_directive, false)) {
+
+            switch (stage(state)) {
+                case 0:
+                    change(state, to_explicit, context(rx_directive, 1));
+                    assert(stream.match(rx_directive_name));
+                    token = 'keyword';
+
+                    if (stream.current().match(/^(?:math|latex)/))
+                        state.tmp_stex = true;
+                    else if (stream.current().match(/^python/))
+                        state.tmp_py = true;
+                    break;
+                case 1:
+                    change(state, to_explicit, context(rx_directive, 2));
+                    assert(stream.match(rx_directive_tail));
+                    token = 'meta';
+                    break;
+                default:
+                    if (stream.match(/^latex\s*$/) || state.tmp_stex) {
+                        state.tmp_stex = undefined;
+                        change(state, to_mode, {
+                            mode: mode_stex, local: mode_stex.startState()
+                        });
+                    } else if (stream.match(/^python\s*$/) || state.tmp_py) {
+                        state.tmp_py = undefined;
+                        change(state, to_mode, {
+                            mode: mode_python, local: mode_python.startState()
+                        });
+                    }
+
+                    else {
+                        change(state, to_normal);
+                        assert(stream.current() == '');
+                    }
+            }
+        } else if (phase(state) == rx_link || stream.match(rx_link, false)) {
+
+            switch (stage(state)) {
+                case 0:
+                    change(state, to_explicit, context(rx_link, 1));
+                    assert(stream.match(rx_link_head));
+                    assert(stream.match(rx_link_name));
+                    token = 'link';
+                    break;
+                case 1:
+                    change(state, to_explicit, context(rx_link, 2));
+                    assert(stream.match(rx_link_tail));
+                    token = 'meta';
+                    break;
+                default:
+                    change(state, to_normal);
+                    assert(stream.current() == '');
+            }
+        } else if (stream.match(rx_footnote)) {
+            change(state, to_normal);
+            token = 'quote';
+        } else if (stream.match(rx_citation)) {
+            change(state, to_normal);
+            token = 'quote';
+        }
+
+        else {
+            stream.eatSpace();
+            if (stream.eol()) {
+                change(state, to_normal);
+            } else {
+                stream.skipToEnd();
+                change(state, to_comment);
+                token = 'comment';
+            }
+        }
+
+        return token;
+    }
+
+    ///////////////////////////////////////////////////////////////////////////
+    ///////////////////////////////////////////////////////////////////////////
+
+    function to_comment(stream, state) {
+        return as_block(stream, state, 'comment');
+    }
+
+    function to_verbatim(stream, state) {
+        return as_block(stream, state, 'meta');
+    }
+
+    function as_block(stream, state, token) {
+        if (stream.eol() || stream.eatSpace()) {
+            stream.skipToEnd();
+            return token;
+        } else {
+            change(state, to_normal);
+            return null;
+        }
+    }
+
+    ///////////////////////////////////////////////////////////////////////////
+    ///////////////////////////////////////////////////////////////////////////
+
+    function to_mode(stream, state) {
+
+        if (state.ctx.mode && state.ctx.local) {
+
+            if (stream.sol()) {
+                if (!stream.eatSpace()) change(state, to_normal);
+                return null;
+            }
+
+            try {
+                return state.ctx.mode.token(stream, state.ctx.local);
+            } catch (ex) {
+                change(state, to_normal);
+                return null;
+            }
+        }
+
+        change(state, to_normal);
+        return null;
+    }
+
+    ///////////////////////////////////////////////////////////////////////////
+    ///////////////////////////////////////////////////////////////////////////
+
+    function context(phase, stage, mode, local) {
+        return {phase: phase, stage: stage, mode: mode, local: local};
+    }
+
+    function change(state, tok, ctx) {
+        state.tok = tok;
+        state.ctx = ctx || {};
+    }
+
+    function stage(state) {
+        return state.ctx.stage || 0;
+    }
+
+    function phase(state) {
+        return state.ctx.phase;
+    }
+
+    ///////////////////////////////////////////////////////////////////////////
+    ///////////////////////////////////////////////////////////////////////////
+
+    return {
+        startState: function () {
+            return {tok: to_normal, ctx: context(undefined, 0)};
+        },
+
+        copyState: function (state) {
+            return {tok: state.tok, ctx: state.ctx};
+        },
+
+        innerMode: function (state) {
+            return state.tmp ? {state: state.tmp.local, mode: state.tmp.mode}
+                 : state.ctx ? {state: state.ctx.local, mode: state.ctx.mode}
+                             : null;
+        },
+
+        token: function (stream, state) {
+            return state.tok(stream, state);
+        }
+    };
+}, 'python', 'stex');
+
+///////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////////
+
+CodeMirror.defineMode('rst', function (config, options) {
+
+    var rx_strong = /^\*\*[^\*\s](?:[^\*]*[^\*\s])?\*\*/;
+    var rx_emphasis = /^\*[^\*\s](?:[^\*]*[^\*\s])?\*/;
+    var rx_literal = /^``[^`\s](?:[^`]*[^`\s])``/;
+
+    var rx_number = /^(?:[\d]+(?:[\.,]\d+)*)/;
+    var rx_positive = /^(?:\s\+[\d]+(?:[\.,]\d+)*)/;
+    var rx_negative = /^(?:\s\-[\d]+(?:[\.,]\d+)*)/;
+
+    var rx_uri_protocol = "[Hh][Tt][Tt][Pp][Ss]?://";
+    var rx_uri_domain = "(?:[\\d\\w.-]+)\\.(?:\\w{2,6})";
+    var rx_uri_path = "(?:/[\\d\\w\\#\\%\\&\\-\\.\\,\\/\\:\\=\\?\\~]+)*";
+    var rx_uri = new RegExp("^" +
+        rx_uri_protocol + rx_uri_domain + rx_uri_path
+    );
+
+    var overlay = {
+        token: function (stream) {
+
+            if (stream.match(rx_strong) && stream.match (/\W+|$/, false))
+                return 'strong';
+            if (stream.match(rx_emphasis) && stream.match (/\W+|$/, false))
+                return 'em';
+            if (stream.match(rx_literal) && stream.match (/\W+|$/, false))
+                return 'string-2';
+            if (stream.match(rx_number))
+                return 'number';
+            if (stream.match(rx_positive))
+                return 'positive';
+            if (stream.match(rx_negative))
+                return 'negative';
+            if (stream.match(rx_uri))
+                return 'link';
+
+            while (stream.next() != null) {
+                if (stream.match(rx_strong, false)) break;
+                if (stream.match(rx_emphasis, false)) break;
+                if (stream.match(rx_literal, false)) break;
+                if (stream.match(rx_number, false)) break;
+                if (stream.match(rx_positive, false)) break;
+                if (stream.match(rx_negative, false)) break;
+                if (stream.match(rx_uri, false)) break;
+            }
+
+            return null;
+        }
+    };
+
+    var mode = CodeMirror.getMode(
+        config, options.backdrop || 'rst-base'
+    );
+
+    return CodeMirror.overlayMode(mode, overlay, true); // combine
+}, 'python', 'stex');
+
+///////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////////
+
+CodeMirror.defineMIME('text/x-rst', 'rst');
+
+///////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////////
diff --git a/third-party/codemirror-3.15/mode/ruby/LICENSE b/third-party/codemirror-3.15/mode/ruby/LICENSE
new file mode 100644 (file)
index 0000000..ac09fc4
--- /dev/null
@@ -0,0 +1,24 @@
+Copyright (c) 2011, Ubalo, Inc.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+    * Redistributions of source code must retain the above copyright
+      notice, this list of conditions and the following disclaimer.
+    * Redistributions in binary form must reproduce the above copyright
+      notice, this list of conditions and the following disclaimer in the
+      documentation and/or other materials provided with the distribution.
+    * Neither the name of the Ubalo, Inc. nor the names of its
+      contributors may be used to endorse or promote products derived
+      from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL UBALO, INC BE LIABLE FOR ANY
+DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/third-party/codemirror-3.15/mode/ruby/index.html b/third-party/codemirror-3.15/mode/ruby/index.html
new file mode 100644 (file)
index 0000000..64cfe5e
--- /dev/null
@@ -0,0 +1,173 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Ruby mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../../addon/edit/matchbrackets.js"></script>
+    <script src="ruby.js"></script>
+    <style>
+      .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}
+      .cm-s-default span.cm-arrow { color: red; }
+    </style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Ruby mode</h1>
+    <form><textarea id="code" name="code">
+# Code from http://sandbox.mc.edu/~bennet/ruby/code/poly_rb.html
+#
+# This program evaluates polynomials.  It first asks for the coefficients
+# of a polynomial, which must be entered on one line, highest-order first.
+# It then requests values of x and will compute the value of the poly for
+# each x.  It will repeatly ask for x values, unless you the user enters
+# a blank line.  It that case, it will ask for another polynomial.  If the
+# user types quit for either input, the program immediately exits.
+#
+
+#
+# Function to evaluate a polynomial at x.  The polynomial is given
+# as a list of coefficients, from the greatest to the least.
+def polyval(x, coef)
+    sum = 0
+    coef = coef.clone           # Don't want to destroy the original
+    while true
+        sum += coef.shift       # Add and remove the next coef
+        break if coef.empty?    # If no more, done entirely.
+        sum *= x                # This happens the right number of times.
+    end
+    return sum
+end
+
+#
+# Function to read a line containing a list of integers and return
+# them as an array of integers.  If the string conversion fails, it
+# throws TypeError.  If the input line is the word 'quit', then it
+# converts it to an end-of-file exception
+def readints(prompt)
+    # Read a line
+    print prompt
+    line = readline.chomp
+    raise EOFError.new if line == 'quit' # You can also use a real EOF.
+            
+    # Go through each item on the line, converting each one and adding it
+    # to retval.
+    retval = [ ]
+    for str in line.split(/\s+/)
+        if str =~ /^\-?\d+$/
+            retval.push(str.to_i)
+        else
+            raise TypeError.new
+        end
+    end
+
+    return retval
+end
+
+#
+# Take a coeff and an exponent and return the string representation, ignoring
+# the sign of the coefficient.
+def term_to_str(coef, exp)
+    ret = ""
+
+    # Show coeff, unless it's 1 or at the right
+    coef = coef.abs
+    ret = coef.to_s     unless coef == 1 && exp > 0
+    ret += "x" if exp > 0                               # x if exponent not 0
+    ret += "^" + exp.to_s if exp > 1                    # ^exponent, if > 1.
+
+    return ret
+end
+
+#
+# Create a string of the polynomial in sort-of-readable form.
+def polystr(p)
+    # Get the exponent of first coefficient, plus 1.
+    exp = p.length
+
+    # Assign exponents to each term, making pairs of coeff and exponent,
+    # Then get rid of the zero terms.
+    p = (p.map { |c| exp -= 1; [ c, exp ] }).select { |p| p[0] != 0 }
+
+    # If there's nothing left, it's a zero
+    return "0" if p.empty?
+
+    # *** Now p is a non-empty list of [ coef, exponent ] pairs. ***
+
+    # Convert the first term, preceded by a "-" if it's negative.
+    result = (if p[0][0] < 0 then "-" else "" end) + term_to_str(*p[0])
+
+    # Convert the rest of the terms, in each case adding the appropriate
+    # + or - separating them.  
+    for term in p[1...p.length]
+        # Add the separator then the rep. of the term.
+        result += (if term[0] < 0 then " - " else " + " end) + 
+                term_to_str(*term)
+    end
+
+    return result
+end
+        
+#
+# Run until some kind of endfile.
+begin
+    # Repeat until an exception or quit gets us out.
+    while true
+        # Read a poly until it works.  An EOF will except out of the
+        # program.
+        print "\n"
+        begin
+            poly = readints("Enter a polynomial coefficients: ")
+        rescue TypeError
+            print "Try again.\n"
+            retry
+        end
+        break if poly.empty?
+
+        # Read and evaluate x values until the user types a blank line.
+        # Again, an EOF will except out of the pgm.
+        while true
+            # Request an integer.
+            print "Enter x value or blank line: "
+            x = readline.chomp
+            break if x == ''
+            raise EOFError.new if x == 'quit'
+
+            # If it looks bad, let's try again.
+            if x !~ /^\-?\d+$/
+                print "That doesn't look like an integer.  Please try again.\n"
+                next
+            end
+
+            # Convert to an integer and print the result.
+            x = x.to_i
+            print "p(x) = ", polystr(poly), "\n"
+            print "p(", x, ") = ", polyval(x, poly), "\n"
+        end
+    end
+rescue EOFError
+    print "\n=== EOF ===\n"
+rescue Interrupt, SignalException
+    print "\n=== Interrupted ===\n"
+else
+    print "--- Bye ---\n"
+end
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        mode: "text/x-ruby",
+        tabMode: "indent",
+        matchBrackets: true,
+        indentUnit: 4
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-ruby</code>.</p>
+
+    <p>Development of the CodeMirror Ruby mode was kindly sponsored
+    by <a href="http://ubalo.com/">Ubalo</a>, who hold
+    the <a href="LICENSE">license</a>.</p>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/ruby/ruby.js b/third-party/codemirror-3.15/mode/ruby/ruby.js
new file mode 100644 (file)
index 0000000..96cdd5f
--- /dev/null
@@ -0,0 +1,247 @@
+CodeMirror.defineMode("ruby", function(config) {
+  function wordObj(words) {
+    var o = {};
+    for (var i = 0, e = words.length; i < e; ++i) o[words[i]] = true;
+    return o;
+  }
+  var keywords = wordObj([
+    "alias", "and", "BEGIN", "begin", "break", "case", "class", "def", "defined?", "do", "else",
+    "elsif", "END", "end", "ensure", "false", "for", "if", "in", "module", "next", "not", "or",
+    "redo", "rescue", "retry", "return", "self", "super", "then", "true", "undef", "unless",
+    "until", "when", "while", "yield", "nil", "raise", "throw", "catch", "fail", "loop", "callcc",
+    "caller", "lambda", "proc", "public", "protected", "private", "require", "load",
+    "require_relative", "extend", "autoload", "__END__", "__FILE__", "__LINE__", "__dir__"
+  ]);
+  var indentWords = wordObj(["def", "class", "case", "for", "while", "do", "module", "then",
+                             "catch", "loop", "proc", "begin"]);
+  var dedentWords = wordObj(["end", "until"]);
+  var matching = {"[": "]", "{": "}", "(": ")"};
+  var curPunc;
+
+  function chain(newtok, stream, state) {
+    state.tokenize.push(newtok);
+    return newtok(stream, state);
+  }
+
+  function tokenBase(stream, state) {
+    curPunc = null;
+    if (stream.sol() && stream.match("=begin") && stream.eol()) {
+      state.tokenize.push(readBlockComment);
+      return "comment";
+    }
+    if (stream.eatSpace()) return null;
+    var ch = stream.next(), m;
+    if (ch == "`" || ch == "'" || ch == '"') {
+      return chain(readQuoted(ch, "string", ch == '"' || ch == "`"), stream, state);
+    } else if (ch == "/" && !stream.eol() && stream.peek() != " ") {
+      return chain(readQuoted(ch, "string-2", true), stream, state);
+    } else if (ch == "%") {
+      var style = "string", embed = true;
+      if (stream.eat("s")) style = "atom";
+      else if (stream.eat(/[WQ]/)) style = "string";
+      else if (stream.eat(/[r]/)) style = "string-2";
+      else if (stream.eat(/[wxq]/)) { style = "string"; embed = false; }
+      var delim = stream.eat(/[^\w\s]/);
+      if (!delim) return "operator";
+      if (matching.propertyIsEnumerable(delim)) delim = matching[delim];
+      return chain(readQuoted(delim, style, embed, true), stream, state);
+    } else if (ch == "#") {
+      stream.skipToEnd();
+      return "comment";
+    } else if (ch == "<" && (m = stream.match(/^<-?[\`\"\']?([a-zA-Z_?]\w*)[\`\"\']?(?:;|$)/))) {
+      return chain(readHereDoc(m[1]), stream, state);
+    } else if (ch == "0") {
+      if (stream.eat("x")) stream.eatWhile(/[\da-fA-F]/);
+      else if (stream.eat("b")) stream.eatWhile(/[01]/);
+      else stream.eatWhile(/[0-7]/);
+      return "number";
+    } else if (/\d/.test(ch)) {
+      stream.match(/^[\d_]*(?:\.[\d_]+)?(?:[eE][+\-]?[\d_]+)?/);
+      return "number";
+    } else if (ch == "?") {
+      while (stream.match(/^\\[CM]-/)) {}
+      if (stream.eat("\\")) stream.eatWhile(/\w/);
+      else stream.next();
+      return "string";
+    } else if (ch == ":") {
+      if (stream.eat("'")) return chain(readQuoted("'", "atom", false), stream, state);
+      if (stream.eat('"')) return chain(readQuoted('"', "atom", true), stream, state);
+
+      // :> :>> :< :<< are valid symbols
+      if (stream.eat(/[\<\>]/)) {
+        stream.eat(/[\<\>]/);
+        return "atom";
+      }
+
+      // :+ :- :/ :* :| :& :! are valid symbols
+      if (stream.eat(/[\+\-\*\/\&\|\:\!]/)) {
+        return "atom";
+      }
+
+      // Symbols can't start by a digit
+      if (stream.eat(/[a-zA-Z$@_]/)) {
+        stream.eatWhile(/[\w]/);
+        // Only one ? ! = is allowed and only as the last character
+        stream.eat(/[\?\!\=]/);
+        return "atom";
+      }
+      return "operator";
+    } else if (ch == "@" && stream.match(/^@?[a-zA-Z_]/)) {
+      stream.eat("@");
+      stream.eatWhile(/[\w]/);
+      return "variable-2";
+    } else if (ch == "$") {
+      if (stream.eat(/[a-zA-Z_]/)) {
+        stream.eatWhile(/[\w]/);
+      } else if (stream.eat(/\d/)) {
+        stream.eat(/\d/);
+      } else {
+        stream.next(); // Must be a special global like $: or $!
+      }
+      return "variable-3";
+    } else if (/[a-zA-Z_]/.test(ch)) {
+      stream.eatWhile(/[\w]/);
+      stream.eat(/[\?\!]/);
+      if (stream.eat(":")) return "atom";
+      return "ident";
+    } else if (ch == "|" && (state.varList || state.lastTok == "{" || state.lastTok == "do")) {
+      curPunc = "|";
+      return null;
+    } else if (/[\(\)\[\]{}\\;]/.test(ch)) {
+      curPunc = ch;
+      return null;
+    } else if (ch == "-" && stream.eat(">")) {
+      return "arrow";
+    } else if (/[=+\-\/*:\.^%<>~|]/.test(ch)) {
+      stream.eatWhile(/[=+\-\/*:\.^%<>~|]/);
+      return "operator";
+    } else {
+      return null;
+    }
+  }
+
+  function tokenBaseUntilBrace() {
+    var depth = 1;
+    return function(stream, state) {
+      if (stream.peek() == "}") {
+        depth--;
+        if (depth == 0) {
+          state.tokenize.pop();
+          return state.tokenize[state.tokenize.length-1](stream, state);
+        }
+      } else if (stream.peek() == "{") {
+        depth++;
+      }
+      return tokenBase(stream, state);
+    };
+  }
+  function tokenBaseOnce() {
+    var alreadyCalled = false;
+    return function(stream, state) {
+      if (alreadyCalled) {
+        state.tokenize.pop();
+        return state.tokenize[state.tokenize.length-1](stream, state);
+      }
+      alreadyCalled = true;
+      return tokenBase(stream, state);
+    };
+  }
+  function readQuoted(quote, style, embed, unescaped) {
+    return function(stream, state) {
+      var escaped = false, ch;
+
+      if (state.context.type === 'read-quoted-paused') {
+        state.context = state.context.prev;
+        stream.eat("}");
+      }
+
+      while ((ch = stream.next()) != null) {
+        if (ch == quote && (unescaped || !escaped)) {
+          state.tokenize.pop();
+          break;
+        }
+        if (embed && ch == "#" && !escaped) {
+          if (stream.eat("{")) {
+            if (quote == "}") {
+              state.context = {prev: state.context, type: 'read-quoted-paused'};
+            }
+            state.tokenize.push(tokenBaseUntilBrace());
+            break;
+          } else if (/[@\$]/.test(stream.peek())) {
+            state.tokenize.push(tokenBaseOnce());
+            break;
+          }
+        }
+        escaped = !escaped && ch == "\\";
+      }
+      return style;
+    };
+  }
+  function readHereDoc(phrase) {
+    return function(stream, state) {
+      if (stream.match(phrase)) state.tokenize.pop();
+      else stream.skipToEnd();
+      return "string";
+    };
+  }
+  function readBlockComment(stream, state) {
+    if (stream.sol() && stream.match("=end") && stream.eol())
+      state.tokenize.pop();
+    stream.skipToEnd();
+    return "comment";
+  }
+
+  return {
+    startState: function() {
+      return {tokenize: [tokenBase],
+              indented: 0,
+              context: {type: "top", indented: -config.indentUnit},
+              continuedLine: false,
+              lastTok: null,
+              varList: false};
+    },
+
+    token: function(stream, state) {
+      if (stream.sol()) state.indented = stream.indentation();
+      var style = state.tokenize[state.tokenize.length-1](stream, state), kwtype;
+      if (style == "ident") {
+        var word = stream.current();
+        style = keywords.propertyIsEnumerable(stream.current()) ? "keyword"
+          : /^[A-Z]/.test(word) ? "tag"
+          : (state.lastTok == "def" || state.lastTok == "class" || state.varList) ? "def"
+          : "variable";
+        if (indentWords.propertyIsEnumerable(word)) kwtype = "indent";
+        else if (dedentWords.propertyIsEnumerable(word)) kwtype = "dedent";
+        else if ((word == "if" || word == "unless") && stream.column() == stream.indentation())
+          kwtype = "indent";
+      }
+      if (curPunc || (style && style != "comment")) state.lastTok = word || curPunc || style;
+      if (curPunc == "|") state.varList = !state.varList;
+
+      if (kwtype == "indent" || /[\(\[\{]/.test(curPunc))
+        state.context = {prev: state.context, type: curPunc || style, indented: state.indented};
+      else if ((kwtype == "dedent" || /[\)\]\}]/.test(curPunc)) && state.context.prev)
+        state.context = state.context.prev;
+
+      if (stream.eol())
+        state.continuedLine = (curPunc == "\\" || style == "operator");
+      return style;
+    },
+
+    indent: function(state, textAfter) {
+      if (state.tokenize[state.tokenize.length-1] != tokenBase) return 0;
+      var firstChar = textAfter && textAfter.charAt(0);
+      var ct = state.context;
+      var closing = ct.type == matching[firstChar] ||
+        ct.type == "keyword" && /^(?:end|until|else|elsif|when|rescue)\b/.test(textAfter);
+      return ct.indented + (closing ? 0 : config.indentUnit) +
+        (state.continuedLine ? config.indentUnit : 0);
+    },
+
+    electricChars: "}de", // enD and rescuE
+    lineComment: "#"
+  };
+});
+
+CodeMirror.defineMIME("text/x-ruby", "ruby");
+
diff --git a/third-party/codemirror-3.15/mode/rust/index.html b/third-party/codemirror-3.15/mode/rust/index.html
new file mode 100644 (file)
index 0000000..a6d47fe
--- /dev/null
@@ -0,0 +1,48 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Rust mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="rust.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: Rust mode</h1>
+
+<div><textarea id="code" name="code">
+// Demo code.
+
+type foo<T> = int;
+enum bar {
+    some(int, foo<float>),
+    none
+}
+
+fn check_crate(x: int) {
+    let v = 10;
+    alt foo {
+      1 to 3 {
+        print_foo();
+        if x {
+            blah() + 10;
+        }
+      }
+      (x, y) { "bye" }
+      _ { "hi" }
+    }
+}
+</textarea></div>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        tabMode: "indent"
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-rustsrc</code>.</p>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/rust/rust.js b/third-party/codemirror-3.15/mode/rust/rust.js
new file mode 100644 (file)
index 0000000..c7530b6
--- /dev/null
@@ -0,0 +1,436 @@
+CodeMirror.defineMode("rust", function() {
+  var indentUnit = 4, altIndentUnit = 2;
+  var valKeywords = {
+    "if": "if-style", "while": "if-style", "else": "else-style",
+    "do": "else-style", "ret": "else-style", "fail": "else-style",
+    "break": "atom", "cont": "atom", "const": "let", "resource": "fn",
+    "let": "let", "fn": "fn", "for": "for", "alt": "alt", "iface": "iface",
+    "impl": "impl", "type": "type", "enum": "enum", "mod": "mod",
+    "as": "op", "true": "atom", "false": "atom", "assert": "op", "check": "op",
+    "claim": "op", "native": "ignore", "unsafe": "ignore", "import": "else-style",
+    "export": "else-style", "copy": "op", "log": "op", "log_err": "op",
+    "use": "op", "bind": "op", "self": "atom"
+  };
+  var typeKeywords = function() {
+    var keywords = {"fn": "fn", "block": "fn", "obj": "obj"};
+    var atoms = "bool uint int i8 i16 i32 i64 u8 u16 u32 u64 float f32 f64 str char".split(" ");
+    for (var i = 0, e = atoms.length; i < e; ++i) keywords[atoms[i]] = "atom";
+    return keywords;
+  }();
+  var operatorChar = /[+\-*&%=<>!?|\.@]/;
+
+  // Tokenizer
+
+  // Used as scratch variable to communicate multiple values without
+  // consing up tons of objects.
+  var tcat, content;
+  function r(tc, style) {
+    tcat = tc;
+    return style;
+  }
+
+  function tokenBase(stream, state) {
+    var ch = stream.next();
+    if (ch == '"') {
+      state.tokenize = tokenString;
+      return state.tokenize(stream, state);
+    }
+    if (ch == "'") {
+      tcat = "atom";
+      if (stream.eat("\\")) {
+        if (stream.skipTo("'")) { stream.next(); return "string"; }
+        else { return "error"; }
+      } else {
+        stream.next();
+        return stream.eat("'") ? "string" : "error";
+      }
+    }
+    if (ch == "/") {
+      if (stream.eat("/")) { stream.skipToEnd(); return "comment"; }
+      if (stream.eat("*")) {
+        state.tokenize = tokenComment(1);
+        return state.tokenize(stream, state);
+      }
+    }
+    if (ch == "#") {
+      if (stream.eat("[")) { tcat = "open-attr"; return null; }
+      stream.eatWhile(/\w/);
+      return r("macro", "meta");
+    }
+    if (ch == ":" && stream.match(":<")) {
+      return r("op", null);
+    }
+    if (ch.match(/\d/) || (ch == "." && stream.eat(/\d/))) {
+      var flp = false;
+      if (!stream.match(/^x[\da-f]+/i) && !stream.match(/^b[01]+/)) {
+        stream.eatWhile(/\d/);
+        if (stream.eat(".")) { flp = true; stream.eatWhile(/\d/); }
+        if (stream.match(/^e[+\-]?\d+/i)) { flp = true; }
+      }
+      if (flp) stream.match(/^f(?:32|64)/);
+      else stream.match(/^[ui](?:8|16|32|64)/);
+      return r("atom", "number");
+    }
+    if (ch.match(/[()\[\]{}:;,]/)) return r(ch, null);
+    if (ch == "-" && stream.eat(">")) return r("->", null);
+    if (ch.match(operatorChar)) {
+      stream.eatWhile(operatorChar);
+      return r("op", null);
+    }
+    stream.eatWhile(/\w/);
+    content = stream.current();
+    if (stream.match(/^::\w/)) {
+      stream.backUp(1);
+      return r("prefix", "variable-2");
+    }
+    if (state.keywords.propertyIsEnumerable(content))
+      return r(state.keywords[content], content.match(/true|false/) ? "atom" : "keyword");
+    return r("name", "variable");
+  }
+
+  function tokenString(stream, state) {
+    var ch, escaped = false;
+    while (ch = stream.next()) {
+      if (ch == '"' && !escaped) {
+        state.tokenize = tokenBase;
+        return r("atom", "string");
+      }
+      escaped = !escaped && ch == "\\";
+    }
+    // Hack to not confuse the parser when a string is split in
+    // pieces.
+    return r("op", "string");
+  }
+
+  function tokenComment(depth) {
+    return function(stream, state) {
+      var lastCh = null, ch;
+      while (ch = stream.next()) {
+        if (ch == "/" && lastCh == "*") {
+          if (depth == 1) {
+            state.tokenize = tokenBase;
+            break;
+          } else {
+            state.tokenize = tokenComment(depth - 1);
+            return state.tokenize(stream, state);
+          }
+        }
+        if (ch == "*" && lastCh == "/") {
+          state.tokenize = tokenComment(depth + 1);
+          return state.tokenize(stream, state);
+        }
+        lastCh = ch;
+      }
+      return "comment";
+    };
+  }
+
+  // Parser
+
+  var cx = {state: null, stream: null, marked: null, cc: null};
+  function pass() {
+    for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);
+  }
+  function cont() {
+    pass.apply(null, arguments);
+    return true;
+  }
+
+  function pushlex(type, info) {
+    var result = function() {
+      var state = cx.state;
+      state.lexical = {indented: state.indented, column: cx.stream.column(),
+                       type: type, prev: state.lexical, info: info};
+    };
+    result.lex = true;
+    return result;
+  }
+  function poplex() {
+    var state = cx.state;
+    if (state.lexical.prev) {
+      if (state.lexical.type == ")")
+        state.indented = state.lexical.indented;
+      state.lexical = state.lexical.prev;
+    }
+  }
+  function typecx() { cx.state.keywords = typeKeywords; }
+  function valcx() { cx.state.keywords = valKeywords; }
+  poplex.lex = typecx.lex = valcx.lex = true;
+
+  function commasep(comb, end) {
+    function more(type) {
+      if (type == ",") return cont(comb, more);
+      if (type == end) return cont();
+      return cont(more);
+    }
+    return function(type) {
+      if (type == end) return cont();
+      return pass(comb, more);
+    };
+  }
+
+  function stat_of(comb, tag) {
+    return cont(pushlex("stat", tag), comb, poplex, block);
+  }
+  function block(type) {
+    if (type == "}") return cont();
+    if (type == "let") return stat_of(letdef1, "let");
+    if (type == "fn") return stat_of(fndef);
+    if (type == "type") return cont(pushlex("stat"), tydef, endstatement, poplex, block);
+    if (type == "enum") return stat_of(enumdef);
+    if (type == "mod") return stat_of(mod);
+    if (type == "iface") return stat_of(iface);
+    if (type == "impl") return stat_of(impl);
+    if (type == "open-attr") return cont(pushlex("]"), commasep(expression, "]"), poplex);
+    if (type == "ignore" || type.match(/[\]\);,]/)) return cont(block);
+    return pass(pushlex("stat"), expression, poplex, endstatement, block);
+  }
+  function endstatement(type) {
+    if (type == ";") return cont();
+    return pass();
+  }
+  function expression(type) {
+    if (type == "atom" || type == "name") return cont(maybeop);
+    if (type == "{") return cont(pushlex("}"), exprbrace, poplex);
+    if (type.match(/[\[\(]/)) return matchBrackets(type, expression);
+    if (type.match(/[\]\)\};,]/)) return pass();
+    if (type == "if-style") return cont(expression, expression);
+    if (type == "else-style" || type == "op") return cont(expression);
+    if (type == "for") return cont(pattern, maybetype, inop, expression, expression);
+    if (type == "alt") return cont(expression, altbody);
+    if (type == "fn") return cont(fndef);
+    if (type == "macro") return cont(macro);
+    return cont();
+  }
+  function maybeop(type) {
+    if (content == ".") return cont(maybeprop);
+    if (content == "::<"){return cont(typarams, maybeop);}
+    if (type == "op" || content == ":") return cont(expression);
+    if (type == "(" || type == "[") return matchBrackets(type, expression);
+    return pass();
+  }
+  function maybeprop() {
+    if (content.match(/^\w+$/)) {cx.marked = "variable"; return cont(maybeop);}
+    return pass(expression);
+  }
+  function exprbrace(type) {
+    if (type == "op") {
+      if (content == "|") return cont(blockvars, poplex, pushlex("}", "block"), block);
+      if (content == "||") return cont(poplex, pushlex("}", "block"), block);
+    }
+    if (content == "mutable" || (content.match(/^\w+$/) && cx.stream.peek() == ":"
+                                 && !cx.stream.match("::", false)))
+      return pass(record_of(expression));
+    return pass(block);
+  }
+  function record_of(comb) {
+    function ro(type) {
+      if (content == "mutable" || content == "with") {cx.marked = "keyword"; return cont(ro);}
+      if (content.match(/^\w*$/)) {cx.marked = "variable"; return cont(ro);}
+      if (type == ":") return cont(comb, ro);
+      if (type == "}") return cont();
+      return cont(ro);
+    }
+    return ro;
+  }
+  function blockvars(type) {
+    if (type == "name") {cx.marked = "def"; return cont(blockvars);}
+    if (type == "op" && content == "|") return cont();
+    return cont(blockvars);
+  }
+
+  function letdef1(type) {
+    if (type.match(/[\]\)\};]/)) return cont();
+    if (content == "=") return cont(expression, letdef2);
+    if (type == ",") return cont(letdef1);
+    return pass(pattern, maybetype, letdef1);
+  }
+  function letdef2(type) {
+    if (type.match(/[\]\)\};,]/)) return pass(letdef1);
+    else return pass(expression, letdef2);
+  }
+  function maybetype(type) {
+    if (type == ":") return cont(typecx, rtype, valcx);
+    return pass();
+  }
+  function inop(type) {
+    if (type == "name" && content == "in") {cx.marked = "keyword"; return cont();}
+    return pass();
+  }
+  function fndef(type) {
+    if (content == "@" || content == "~") {cx.marked = "keyword"; return cont(fndef);}
+    if (type == "name") {cx.marked = "def"; return cont(fndef);}
+    if (content == "<") return cont(typarams, fndef);
+    if (type == "{") return pass(expression);
+    if (type == "(") return cont(pushlex(")"), commasep(argdef, ")"), poplex, fndef);
+    if (type == "->") return cont(typecx, rtype, valcx, fndef);
+    if (type == ";") return cont();
+    return cont(fndef);
+  }
+  function tydef(type) {
+    if (type == "name") {cx.marked = "def"; return cont(tydef);}
+    if (content == "<") return cont(typarams, tydef);
+    if (content == "=") return cont(typecx, rtype, valcx);
+    return cont(tydef);
+  }
+  function enumdef(type) {
+    if (type == "name") {cx.marked = "def"; return cont(enumdef);}
+    if (content == "<") return cont(typarams, enumdef);
+    if (content == "=") return cont(typecx, rtype, valcx, endstatement);
+    if (type == "{") return cont(pushlex("}"), typecx, enumblock, valcx, poplex);
+    return cont(enumdef);
+  }
+  function enumblock(type) {
+    if (type == "}") return cont();
+    if (type == "(") return cont(pushlex(")"), commasep(rtype, ")"), poplex, enumblock);
+    if (content.match(/^\w+$/)) cx.marked = "def";
+    return cont(enumblock);
+  }
+  function mod(type) {
+    if (type == "name") {cx.marked = "def"; return cont(mod);}
+    if (type == "{") return cont(pushlex("}"), block, poplex);
+    return pass();
+  }
+  function iface(type) {
+    if (type == "name") {cx.marked = "def"; return cont(iface);}
+    if (content == "<") return cont(typarams, iface);
+    if (type == "{") return cont(pushlex("}"), block, poplex);
+    return pass();
+  }
+  function impl(type) {
+    if (content == "<") return cont(typarams, impl);
+    if (content == "of" || content == "for") {cx.marked = "keyword"; return cont(rtype, impl);}
+    if (type == "name") {cx.marked = "def"; return cont(impl);}
+    if (type == "{") return cont(pushlex("}"), block, poplex);
+    return pass();
+  }
+  function typarams() {
+    if (content == ">") return cont();
+    if (content == ",") return cont(typarams);
+    if (content == ":") return cont(rtype, typarams);
+    return pass(rtype, typarams);
+  }
+  function argdef(type) {
+    if (type == "name") {cx.marked = "def"; return cont(argdef);}
+    if (type == ":") return cont(typecx, rtype, valcx);
+    return pass();
+  }
+  function rtype(type) {
+    if (type == "name") {cx.marked = "variable-3"; return cont(rtypemaybeparam); }
+    if (content == "mutable") {cx.marked = "keyword"; return cont(rtype);}
+    if (type == "atom") return cont(rtypemaybeparam);
+    if (type == "op" || type == "obj") return cont(rtype);
+    if (type == "fn") return cont(fntype);
+    if (type == "{") return cont(pushlex("{"), record_of(rtype), poplex);
+    return matchBrackets(type, rtype);
+  }
+  function rtypemaybeparam() {
+    if (content == "<") return cont(typarams);
+    return pass();
+  }
+  function fntype(type) {
+    if (type == "(") return cont(pushlex("("), commasep(rtype, ")"), poplex, fntype);
+    if (type == "->") return cont(rtype);
+    return pass();
+  }
+  function pattern(type) {
+    if (type == "name") {cx.marked = "def"; return cont(patternmaybeop);}
+    if (type == "atom") return cont(patternmaybeop);
+    if (type == "op") return cont(pattern);
+    if (type.match(/[\]\)\};,]/)) return pass();
+    return matchBrackets(type, pattern);
+  }
+  function patternmaybeop(type) {
+    if (type == "op" && content == ".") return cont();
+    if (content == "to") {cx.marked = "keyword"; return cont(pattern);}
+    else return pass();
+  }
+  function altbody(type) {
+    if (type == "{") return cont(pushlex("}", "alt"), altblock1, poplex);
+    return pass();
+  }
+  function altblock1(type) {
+    if (type == "}") return cont();
+    if (type == "|") return cont(altblock1);
+    if (content == "when") {cx.marked = "keyword"; return cont(expression, altblock2);}
+    if (type.match(/[\]\);,]/)) return cont(altblock1);
+    return pass(pattern, altblock2);
+  }
+  function altblock2(type) {
+    if (type == "{") return cont(pushlex("}", "alt"), block, poplex, altblock1);
+    else return pass(altblock1);
+  }
+
+  function macro(type) {
+    if (type.match(/[\[\(\{]/)) return matchBrackets(type, expression);
+    return pass();
+  }
+  function matchBrackets(type, comb) {
+    if (type == "[") return cont(pushlex("]"), commasep(comb, "]"), poplex);
+    if (type == "(") return cont(pushlex(")"), commasep(comb, ")"), poplex);
+    if (type == "{") return cont(pushlex("}"), commasep(comb, "}"), poplex);
+    return cont();
+  }
+
+  function parse(state, stream, style) {
+    var cc = state.cc;
+    // Communicate our context to the combinators.
+    // (Less wasteful than consing up a hundred closures on every call.)
+    cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc;
+
+    while (true) {
+      var combinator = cc.length ? cc.pop() : block;
+      if (combinator(tcat)) {
+        while(cc.length && cc[cc.length - 1].lex)
+          cc.pop()();
+        return cx.marked || style;
+      }
+    }
+  }
+
+  return {
+    startState: function() {
+      return {
+        tokenize: tokenBase,
+        cc: [],
+        lexical: {indented: -indentUnit, column: 0, type: "top", align: false},
+        keywords: valKeywords,
+        indented: 0
+      };
+    },
+
+    token: function(stream, state) {
+      if (stream.sol()) {
+        if (!state.lexical.hasOwnProperty("align"))
+          state.lexical.align = false;
+        state.indented = stream.indentation();
+      }
+      if (stream.eatSpace()) return null;
+      tcat = content = null;
+      var style = state.tokenize(stream, state);
+      if (style == "comment") return style;
+      if (!state.lexical.hasOwnProperty("align"))
+        state.lexical.align = true;
+      if (tcat == "prefix") return style;
+      if (!content) content = stream.current();
+      return parse(state, stream, style);
+    },
+
+    indent: function(state, textAfter) {
+      if (state.tokenize != tokenBase) return 0;
+      var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical,
+          type = lexical.type, closing = firstChar == type;
+      if (type == "stat") return lexical.indented + indentUnit;
+      if (lexical.align) return lexical.column + (closing ? 0 : 1);
+      return lexical.indented + (closing ? 0 : (lexical.info == "alt" ? altIndentUnit : indentUnit));
+    },
+
+    electricChars: "{}",
+    blockCommentStart: "/*",
+    blockCommentEnd: "*/",
+    lineComment: "//",
+    fold: "brace"
+  };
+});
+
+CodeMirror.defineMIME("text/x-rustsrc", "rust");
diff --git a/third-party/codemirror-3.15/mode/sass/index.html b/third-party/codemirror-3.15/mode/sass/index.html
new file mode 100644 (file)
index 0000000..3af7bff
--- /dev/null
@@ -0,0 +1,54 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Sass mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../../addon/edit/matchbrackets.js"></script>
+    <script src="sass.js"></script>
+    <style>.CodeMirror {border: 1px solid #ddd; font-size:12px; height: 400px}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Sass mode</h1>
+    <form><textarea id="code" name="code">// Variable Definitions
+
+$page-width:    800px
+$sidebar-width: 200px
+$primary-color: #eeeeee
+
+// Global Attributes
+
+body
+  font:
+    family: sans-serif
+    size: 30em
+    weight: bold
+
+// Scoped Styles
+
+#contents
+  width: $page-width
+  #sidebar
+    float: right
+    width: $sidebar-width
+  #main
+    width: $page-width - $sidebar-width
+    background: $primary-color
+    h2
+      color: blue
+
+#footer
+  height: 200px
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers : true,
+        matchBrackets : true
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-sass</code>.</p>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/sass/sass.js b/third-party/codemirror-3.15/mode/sass/sass.js
new file mode 100644 (file)
index 0000000..9c9a0da
--- /dev/null
@@ -0,0 +1,330 @@
+CodeMirror.defineMode("sass", function(config) {
+  var tokenRegexp = function(words){
+    return new RegExp("^" + words.join("|"));
+  };
+
+  var keywords = ["true", "false", "null", "auto"];
+  var keywordsRegexp = new RegExp("^" + keywords.join("|"));
+
+  var operators = ["\\(", "\\)", "=", ">", "<", "==", ">=", "<=", "\\+", "-", "\\!=", "/", "\\*", "%", "and", "or", "not"];
+  var opRegexp = tokenRegexp(operators);
+
+  var pseudoElementsRegexp = /^::?[\w\-]+/;
+
+  var urlTokens = function(stream, state){
+    var ch = stream.peek();
+
+    if (ch === ")"){
+      stream.next();
+      state.tokenizer = tokenBase;
+      return "operator";
+    }else if (ch === "("){
+      stream.next();
+      stream.eatSpace();
+
+      return "operator";
+    }else if (ch === "'" || ch === '"'){
+      state.tokenizer = buildStringTokenizer(stream.next());
+      return "string";
+    }else{
+      state.tokenizer = buildStringTokenizer(")", false);
+      return "string";
+    }
+  };
+  var multilineComment = function(stream, state) {
+    if (stream.skipTo("*/")){
+      stream.next();
+      stream.next();
+      state.tokenizer = tokenBase;
+    }else {
+      stream.next();
+    }
+
+    return "comment";
+  };
+
+  var buildStringTokenizer = function(quote, greedy){
+    if(greedy == null){ greedy = true; }
+
+    function stringTokenizer(stream, state){
+      var nextChar = stream.next();
+      var peekChar = stream.peek();
+      var previousChar = stream.string.charAt(stream.pos-2);
+
+      var endingString = ((nextChar !== "\\" && peekChar === quote) || (nextChar === quote && previousChar !== "\\"));
+
+      /*
+      console.log("previousChar: " + previousChar);
+      console.log("nextChar: " + nextChar);
+      console.log("peekChar: " + peekChar);
+      console.log("ending: " + endingString);
+      */
+
+      if (endingString){
+        if (nextChar !== quote && greedy) { stream.next(); }
+        state.tokenizer = tokenBase;
+        return "string";
+      }else if (nextChar === "#" && peekChar === "{"){
+        state.tokenizer = buildInterpolationTokenizer(stringTokenizer);
+        stream.next();
+        return "operator";
+      }else {
+        return "string";
+      }
+    }
+
+    return stringTokenizer;
+  };
+
+  var buildInterpolationTokenizer = function(currentTokenizer){
+    return function(stream, state){
+      if (stream.peek() === "}"){
+        stream.next();
+        state.tokenizer = currentTokenizer;
+        return "operator";
+      }else{
+        return tokenBase(stream, state);
+      }
+    };
+  };
+
+  var indent = function(state){
+    if (state.indentCount == 0){
+      state.indentCount++;
+      var lastScopeOffset = state.scopes[0].offset;
+      var currentOffset = lastScopeOffset + config.indentUnit;
+      state.scopes.unshift({ offset:currentOffset });
+    }
+  };
+
+  var dedent = function(state){
+    if (state.scopes.length == 1) { return; }
+
+    state.scopes.shift();
+  };
+
+  var tokenBase = function(stream, state) {
+    var ch = stream.peek();
+
+    // Single line Comment
+    if (stream.match('//')) {
+      stream.skipToEnd();
+      return "comment";
+    }
+
+    // Multiline Comment
+    if (stream.match('/*')){
+      state.tokenizer = multilineComment;
+      return state.tokenizer(stream, state);
+    }
+
+    // Interpolation
+    if (stream.match('#{')){
+    state.tokenizer = buildInterpolationTokenizer(tokenBase);
+      return "operator";
+    }
+
+    if (ch === "."){
+      stream.next();
+
+      // Match class selectors
+      if (stream.match(/^[\w-]+/)){
+        indent(state);
+        return "atom";
+      }else if (stream.peek() === "#"){
+        indent(state);
+        return "atom";
+      }else{
+        return "operator";
+      }
+    }
+
+    if (ch === "#"){
+      stream.next();
+
+      // Hex numbers
+      if (stream.match(/[0-9a-fA-F]{6}|[0-9a-fA-F]{3}/)){
+        return "number";
+      }
+
+      // ID selectors
+      if (stream.match(/^[\w-]+/)){
+        indent(state);
+        return "atom";
+      }
+
+      if (stream.peek() === "#"){
+        indent(state);
+        return "atom";
+      }
+    }
+
+    // Numbers
+    if (stream.match(/^-?[0-9\.]+/)){
+      return "number";
+    }
+
+    // Units
+    if (stream.match(/^(px|em|in)\b/)){
+      return "unit";
+    }
+
+    if (stream.match(keywordsRegexp)){
+      return "keyword";
+    }
+
+    if (stream.match(/^url/) && stream.peek() === "("){
+      state.tokenizer = urlTokens;
+      return "atom";
+    }
+
+    // Variables
+    if (ch === "$"){
+      stream.next();
+      stream.eatWhile(/[\w-]/);
+
+      if (stream.peek() === ":"){
+        stream.next();
+        return "variable-2";
+      }else{
+        return "variable-3";
+      }
+    }
+
+    if (ch === "!"){
+      stream.next();
+
+      if (stream.match(/^[\w]+/)){
+        return "keyword";
+      }
+
+      return "operator";
+    }
+
+    if (ch === "="){
+      stream.next();
+
+      // Match shortcut mixin definition
+      if (stream.match(/^[\w-]+/)){
+        indent(state);
+        return "meta";
+      }else {
+        return "operator";
+      }
+    }
+
+    if (ch === "+"){
+      stream.next();
+
+      // Match shortcut mixin definition
+      if (stream.match(/^[\w-]+/)){
+        return "variable-3";
+      }else {
+        return "operator";
+      }
+    }
+
+    // Indent Directives
+    if (stream.match(/^@(else if|if|media|else|for|each|while|mixin|function)/)){
+      indent(state);
+      return "meta";
+    }
+
+    // Other Directives
+    if (ch === "@"){
+      stream.next();
+      stream.eatWhile(/[\w-]/);
+      return "meta";
+    }
+
+    // Strings
+    if (ch === '"' || ch === "'"){
+      stream.next();
+      state.tokenizer = buildStringTokenizer(ch);
+      return "string";
+    }
+
+    // Pseudo element selectors
+    if (ch == ':' && stream.match(pseudoElementsRegexp)){
+      return "keyword";
+    }
+
+    // atoms
+    if (stream.eatWhile(/[\w-&]/)){
+      // matches a property definition
+      if (stream.peek() === ":" && !stream.match(pseudoElementsRegexp, false))
+        return "property";
+      else
+        return "atom";
+    }
+
+    if (stream.match(opRegexp)){
+      return "operator";
+    }
+
+    // If we haven't returned by now, we move 1 character
+    // and return an error
+    stream.next();
+    return null;
+  };
+
+  var tokenLexer = function(stream, state) {
+    if (stream.sol()){
+      state.indentCount = 0;
+    }
+    var style = state.tokenizer(stream, state);
+    var current = stream.current();
+
+    if (current === "@return"){
+      dedent(state);
+    }
+
+    if (style === "atom"){
+      indent(state);
+    }
+
+    if (style !== null){
+      var startOfToken = stream.pos - current.length;
+      var withCurrentIndent = startOfToken + (config.indentUnit * state.indentCount);
+
+      var newScopes = [];
+
+      for (var i = 0; i < state.scopes.length; i++){
+        var scope = state.scopes[i];
+
+        if (scope.offset <= withCurrentIndent){
+          newScopes.push(scope);
+        }
+      }
+
+      state.scopes = newScopes;
+    }
+
+
+    return style;
+  };
+
+  return {
+    startState: function() {
+      return {
+        tokenizer: tokenBase,
+        scopes: [{offset: 0, type: 'sass'}],
+        definedVars: [],
+        definedMixins: []
+      };
+    },
+    token: function(stream, state) {
+      var style = tokenLexer(stream, state);
+
+      state.lastToken = { style: style, content: stream.current() };
+
+      return style;
+    },
+
+    indent: function(state) {
+      return state.scopes[0].offset;
+    }
+  };
+});
+
+CodeMirror.defineMIME("text/x-sass", "sass");
diff --git a/third-party/codemirror-3.15/mode/scheme/index.html b/third-party/codemirror-3.15/mode/scheme/index.html
new file mode 100644 (file)
index 0000000..5936a02
--- /dev/null
@@ -0,0 +1,65 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Scheme mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="scheme.js"></script>
+    <style>.CodeMirror {background: #f8f8f8;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Scheme mode</h1>
+    <form><textarea id="code" name="code">
+; See if the input starts with a given symbol.
+(define (match-symbol input pattern)
+  (cond ((null? (remain input)) #f)
+       ((eqv? (car (remain input)) pattern) (r-cdr input))
+       (else #f)))
+
+; Allow the input to start with one of a list of patterns.
+(define (match-or input pattern)
+  (cond ((null? pattern) #f)
+       ((match-pattern input (car pattern)))
+       (else (match-or input (cdr pattern)))))
+
+; Allow a sequence of patterns.
+(define (match-seq input pattern)
+  (if (null? pattern)
+      input
+      (let ((match (match-pattern input (car pattern))))
+       (if match (match-seq match (cdr pattern)) #f))))
+
+; Match with the pattern but no problem if it does not match.
+(define (match-opt input pattern)
+  (let ((match (match-pattern input (car pattern))))
+    (if match match input)))
+
+; Match anything (other than '()), until pattern is found. The rather
+; clumsy form of requiring an ending pattern is needed to decide where
+; the end of the match is. If none is given, this will match the rest
+; of the sentence.
+(define (match-any input pattern)
+  (cond ((null? (remain input)) #f)
+       ((null? pattern) (f-cons (remain input) (clear-remain input)))
+       (else
+        (let ((accum-any (collector)))
+          (define (match-pattern-any input pattern)
+            (cond ((null? (remain input)) #f)
+                  (else (accum-any (car (remain input)))
+                        (cond ((match-pattern (r-cdr input) pattern))
+                              (else (match-pattern-any (r-cdr input) pattern))))))
+          (let ((retval (match-pattern-any input (car pattern))))
+            (if retval
+                (f-cons (accum-any) retval)
+                #f))))))
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-scheme</code>.</p>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/scheme/scheme.js b/third-party/codemirror-3.15/mode/scheme/scheme.js
new file mode 100644 (file)
index 0000000..c5990ae
--- /dev/null
@@ -0,0 +1,232 @@
+/**
+ * Author: Koh Zi Han, based on implementation by Koh Zi Chun
+ */
+CodeMirror.defineMode("scheme", function () {
+    var BUILTIN = "builtin", COMMENT = "comment", STRING = "string",
+        ATOM = "atom", NUMBER = "number", BRACKET = "bracket";
+    var INDENT_WORD_SKIP = 2;
+
+    function makeKeywords(str) {
+        var obj = {}, words = str.split(" ");
+        for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
+        return obj;
+    }
+
+    var keywords = makeKeywords("λ case-lambda call/cc class define-class exit-handler field import inherit init-field interface let*-values let-values let/ec mixin opt-lambda override protect provide public rename require require-for-syntax syntax syntax-case syntax-error unit/sig unless when with-syntax and begin call-with-current-continuation call-with-input-file call-with-output-file case cond define define-syntax delay do dynamic-wind else for-each if lambda let let* let-syntax letrec letrec-syntax map or syntax-rules abs acos angle append apply asin assoc assq assv atan boolean? caar cadr call-with-input-file call-with-output-file call-with-values car cdddar cddddr cdr ceiling char->integer char-alphabetic? char-ci<=? char-ci<? char-ci=? char-ci>=? char-ci>? char-downcase char-lower-case? char-numeric? char-ready? char-upcase char-upper-case? char-whitespace? char<=? char<? char=? char>=? char>? char? close-input-port close-output-port complex? cons cos current-input-port current-output-port denominator display eof-object? eq? equal? eqv? eval even? exact->inexact exact? exp expt #f floor force gcd imag-part inexact->exact inexact? input-port? integer->char integer? interaction-environment lcm length list list->string list->vector list-ref list-tail list? load log magnitude make-polar make-rectangular make-string make-vector max member memq memv min modulo negative? newline not null-environment null? number->string number? numerator odd? open-input-file open-output-file output-port? pair? peek-char port? positive? procedure? quasiquote quote quotient rational? rationalize read read-char real-part real? remainder reverse round scheme-report-environment set! set-car! set-cdr! sin sqrt string string->list string->number string->symbol string-append string-ci<=? string-ci<? string-ci=? string-ci>=? string-ci>? string-copy string-fill! string-length string-ref string-set! string<=? string<? string=? string>=? string>? string? substring symbol->string symbol? #t tan transcript-off transcript-on truncate values vector vector->list vector-fill! vector-length vector-ref vector-set! with-input-from-file with-output-to-file write write-char zero?");
+    var indentKeys = makeKeywords("define let letrec let* lambda");
+
+    function stateStack(indent, type, prev) { // represents a state stack object
+        this.indent = indent;
+        this.type = type;
+        this.prev = prev;
+    }
+
+    function pushStack(state, indent, type) {
+        state.indentStack = new stateStack(indent, type, state.indentStack);
+    }
+
+    function popStack(state) {
+        state.indentStack = state.indentStack.prev;
+    }
+
+    var binaryMatcher = new RegExp(/^(?:[-+]i|[-+][01]+#*(?:\/[01]+#*)?i|[-+]?[01]+#*(?:\/[01]+#*)?@[-+]?[01]+#*(?:\/[01]+#*)?|[-+]?[01]+#*(?:\/[01]+#*)?[-+](?:[01]+#*(?:\/[01]+#*)?)?i|[-+]?[01]+#*(?:\/[01]+#*)?)(?=[()\s;"]|$)/i);
+    var octalMatcher = new RegExp(/^(?:[-+]i|[-+][0-7]+#*(?:\/[0-7]+#*)?i|[-+]?[0-7]+#*(?:\/[0-7]+#*)?@[-+]?[0-7]+#*(?:\/[0-7]+#*)?|[-+]?[0-7]+#*(?:\/[0-7]+#*)?[-+](?:[0-7]+#*(?:\/[0-7]+#*)?)?i|[-+]?[0-7]+#*(?:\/[0-7]+#*)?)(?=[()\s;"]|$)/i);
+    var hexMatcher = new RegExp(/^(?:[-+]i|[-+][\da-f]+#*(?:\/[\da-f]+#*)?i|[-+]?[\da-f]+#*(?:\/[\da-f]+#*)?@[-+]?[\da-f]+#*(?:\/[\da-f]+#*)?|[-+]?[\da-f]+#*(?:\/[\da-f]+#*)?[-+](?:[\da-f]+#*(?:\/[\da-f]+#*)?)?i|[-+]?[\da-f]+#*(?:\/[\da-f]+#*)?)(?=[()\s;"]|$)/i);
+    var decimalMatcher = new RegExp(/^(?:[-+]i|[-+](?:(?:(?:\d+#+\.?#*|\d+\.\d*#*|\.\d+#*|\d+)(?:[esfdl][-+]?\d+)?)|\d+#*\/\d+#*)i|[-+]?(?:(?:(?:\d+#+\.?#*|\d+\.\d*#*|\.\d+#*|\d+)(?:[esfdl][-+]?\d+)?)|\d+#*\/\d+#*)@[-+]?(?:(?:(?:\d+#+\.?#*|\d+\.\d*#*|\.\d+#*|\d+)(?:[esfdl][-+]?\d+)?)|\d+#*\/\d+#*)|[-+]?(?:(?:(?:\d+#+\.?#*|\d+\.\d*#*|\.\d+#*|\d+)(?:[esfdl][-+]?\d+)?)|\d+#*\/\d+#*)[-+](?:(?:(?:\d+#+\.?#*|\d+\.\d*#*|\.\d+#*|\d+)(?:[esfdl][-+]?\d+)?)|\d+#*\/\d+#*)?i|(?:(?:(?:\d+#+\.?#*|\d+\.\d*#*|\.\d+#*|\d+)(?:[esfdl][-+]?\d+)?)|\d+#*\/\d+#*))(?=[()\s;"]|$)/i);
+
+    function isBinaryNumber (stream) {
+        return stream.match(binaryMatcher);
+    }
+
+    function isOctalNumber (stream) {
+        return stream.match(octalMatcher);
+    }
+
+    function isDecimalNumber (stream, backup) {
+        if (backup === true) {
+            stream.backUp(1);
+        }
+        return stream.match(decimalMatcher);
+    }
+
+    function isHexNumber (stream) {
+        return stream.match(hexMatcher);
+    }
+
+    return {
+        startState: function () {
+            return {
+                indentStack: null,
+                indentation: 0,
+                mode: false,
+                sExprComment: false
+            };
+        },
+
+        token: function (stream, state) {
+            if (state.indentStack == null && stream.sol()) {
+                // update indentation, but only if indentStack is empty
+                state.indentation = stream.indentation();
+            }
+
+            // skip spaces
+            if (stream.eatSpace()) {
+                return null;
+            }
+            var returnType = null;
+
+            switch(state.mode){
+                case "string": // multi-line string parsing mode
+                    var next, escaped = false;
+                    while ((next = stream.next()) != null) {
+                        if (next == "\"" && !escaped) {
+
+                            state.mode = false;
+                            break;
+                        }
+                        escaped = !escaped && next == "\\";
+                    }
+                    returnType = STRING; // continue on in scheme-string mode
+                    break;
+                case "comment": // comment parsing mode
+                    var next, maybeEnd = false;
+                    while ((next = stream.next()) != null) {
+                        if (next == "#" && maybeEnd) {
+
+                            state.mode = false;
+                            break;
+                        }
+                        maybeEnd = (next == "|");
+                    }
+                    returnType = COMMENT;
+                    break;
+                case "s-expr-comment": // s-expr commenting mode
+                    state.mode = false;
+                    if(stream.peek() == "(" || stream.peek() == "["){
+                        // actually start scheme s-expr commenting mode
+                        state.sExprComment = 0;
+                    }else{
+                        // if not we just comment the entire of the next token
+                        stream.eatWhile(/[^/s]/); // eat non spaces
+                        returnType = COMMENT;
+                        break;
+                    }
+                default: // default parsing mode
+                    var ch = stream.next();
+
+                    if (ch == "\"") {
+                        state.mode = "string";
+                        returnType = STRING;
+
+                    } else if (ch == "'") {
+                        returnType = ATOM;
+                    } else if (ch == '#') {
+                        if (stream.eat("|")) {                    // Multi-line comment
+                            state.mode = "comment"; // toggle to comment mode
+                            returnType = COMMENT;
+                        } else if (stream.eat(/[tf]/i)) {            // #t/#f (atom)
+                            returnType = ATOM;
+                        } else if (stream.eat(';')) {                // S-Expr comment
+                            state.mode = "s-expr-comment";
+                            returnType = COMMENT;
+                        } else {
+                            var numTest = null, hasExactness = false, hasRadix = true;
+                            if (stream.eat(/[ei]/i)) {
+                                hasExactness = true;
+                            } else {
+                                stream.backUp(1);       // must be radix specifier
+                            }
+                            if (stream.match(/^#b/i)) {
+                                numTest = isBinaryNumber;
+                            } else if (stream.match(/^#o/i)) {
+                                numTest = isOctalNumber;
+                            } else if (stream.match(/^#x/i)) {
+                                numTest = isHexNumber;
+                            } else if (stream.match(/^#d/i)) {
+                                numTest = isDecimalNumber;
+                            } else if (stream.match(/^[-+0-9.]/, false)) {
+                                hasRadix = false;
+                                numTest = isDecimalNumber;
+                            // re-consume the intial # if all matches failed
+                            } else if (!hasExactness) {
+                                stream.eat('#');
+                            }
+                            if (numTest != null) {
+                                if (hasRadix && !hasExactness) {
+                                    // consume optional exactness after radix
+                                    stream.match(/^#[ei]/i);
+                                }
+                                if (numTest(stream))
+                                    returnType = NUMBER;
+                            }
+                        }
+                    } else if (/^[-+0-9.]/.test(ch) && isDecimalNumber(stream, true)) { // match non-prefixed number, must be decimal
+                        returnType = NUMBER;
+                    } else if (ch == ";") { // comment
+                        stream.skipToEnd(); // rest of the line is a comment
+                        returnType = COMMENT;
+                    } else if (ch == "(" || ch == "[") {
+                      var keyWord = ''; var indentTemp = stream.column(), letter;
+                        /**
+                        Either
+                        (indent-word ..
+                        (non-indent-word ..
+                        (;something else, bracket, etc.
+                        */
+
+                        while ((letter = stream.eat(/[^\s\(\[\;\)\]]/)) != null) {
+                            keyWord += letter;
+                        }
+
+                        if (keyWord.length > 0 && indentKeys.propertyIsEnumerable(keyWord)) { // indent-word
+
+                            pushStack(state, indentTemp + INDENT_WORD_SKIP, ch);
+                        } else { // non-indent word
+                            // we continue eating the spaces
+                            stream.eatSpace();
+                            if (stream.eol() || stream.peek() == ";") {
+                                // nothing significant after
+                                // we restart indentation 1 space after
+                                pushStack(state, indentTemp + 1, ch);
+                            } else {
+                                pushStack(state, indentTemp + stream.current().length, ch); // else we match
+                            }
+                        }
+                        stream.backUp(stream.current().length - 1); // undo all the eating
+
+                        if(typeof state.sExprComment == "number") state.sExprComment++;
+
+                        returnType = BRACKET;
+                    } else if (ch == ")" || ch == "]") {
+                        returnType = BRACKET;
+                        if (state.indentStack != null && state.indentStack.type == (ch == ")" ? "(" : "[")) {
+                            popStack(state);
+
+                            if(typeof state.sExprComment == "number"){
+                                if(--state.sExprComment == 0){
+                                    returnType = COMMENT; // final closing bracket
+                                    state.sExprComment = false; // turn off s-expr commenting mode
+                                }
+                            }
+                        }
+                    } else {
+                        stream.eatWhile(/[\w\$_\-!$%&*+\.\/:<=>?@\^~]/);
+
+                        if (keywords && keywords.propertyIsEnumerable(stream.current())) {
+                            returnType = BUILTIN;
+                        } else returnType = "variable";
+                    }
+            }
+            return (typeof state.sExprComment == "number") ? COMMENT : returnType;
+        },
+
+        indent: function (state) {
+            if (state.indentStack == null) return state.indentation;
+            return state.indentStack.indent;
+        },
+
+        lineComment: ";;"
+    };
+});
+
+CodeMirror.defineMIME("text/x-scheme", "scheme");
diff --git a/third-party/codemirror-3.15/mode/shell/index.html b/third-party/codemirror-3.15/mode/shell/index.html
new file mode 100644 (file)
index 0000000..9a2ef7c
--- /dev/null
@@ -0,0 +1,51 @@
+<!doctype html>
+<meta charset=utf-8>
+<title>CodeMirror: Shell mode</title>
+
+<link rel=stylesheet href=../../lib/codemirror.css>
+<link rel=stylesheet href=../../doc/docs.css>
+
+<style type=text/css>
+  .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}
+</style>
+
+<script src=../../lib/codemirror.js></script>
+<script src="../../addon/edit/matchbrackets.js"></script>
+<script src=shell.js></script>
+
+<h1>CodeMirror: Shell mode</h1>
+
+<textarea id=code>
+#!/bin/bash
+
+# clone the repository
+git clone http://github.com/garden/tree
+
+# generate HTTPS credentials
+cd tree
+openssl genrsa -aes256 -out https.key 1024
+openssl req -new -nodes -key https.key -out https.csr
+openssl x509 -req -days 365 -in https.csr -signkey https.key -out https.crt
+cp https.key{,.orig}
+openssl rsa -in https.key.orig -out https.key
+
+# start the server in HTTPS mode
+cd web
+sudo node ../server.js 443 'yes' &gt;&gt; ../node.log &amp;
+
+# here is how to stop the server
+for pid in `ps aux | grep 'node ../server.js' | awk '{print $2}'` ; do
+  sudo kill -9 $pid 2&gt; /dev/null
+done
+
+exit 0</textarea>
+
+<script>
+  var editor = CodeMirror.fromTextArea(document.getElementById('code'), {
+    mode: 'shell',
+    lineNumbers: true,
+    matchBrackets: true
+  });
+</script>
+
+<p><strong>MIME types defined:</strong> <code>text/x-sh</code>.</p>
diff --git a/third-party/codemirror-3.15/mode/shell/shell.js b/third-party/codemirror-3.15/mode/shell/shell.js
new file mode 100644 (file)
index 0000000..abfd214
--- /dev/null
@@ -0,0 +1,118 @@
+CodeMirror.defineMode('shell', function() {
+
+  var words = {};
+  function define(style, string) {
+    var split = string.split(' ');
+    for(var i = 0; i < split.length; i++) {
+      words[split[i]] = style;
+    }
+  };
+
+  // Atoms
+  define('atom', 'true false');
+
+  // Keywords
+  define('keyword', 'if then do else elif while until for in esac fi fin ' +
+    'fil done exit set unset export function');
+
+  // Commands
+  define('builtin', 'ab awk bash beep cat cc cd chown chmod chroot clear cp ' +
+    'curl cut diff echo find gawk gcc get git grep kill killall ln ls make ' +
+    'mkdir openssl mv nc node npm ping ps restart rm rmdir sed service sh ' +
+    'shopt shred source sort sleep ssh start stop su sudo tee telnet top ' +
+    'touch vi vim wall wc wget who write yes zsh');
+
+  function tokenBase(stream, state) {
+
+    var sol = stream.sol();
+    var ch = stream.next();
+
+    if (ch === '\'' || ch === '"' || ch === '`') {
+      state.tokens.unshift(tokenString(ch));
+      return tokenize(stream, state);
+    }
+    if (ch === '#') {
+      if (sol && stream.eat('!')) {
+        stream.skipToEnd();
+        return 'meta'; // 'comment'?
+      }
+      stream.skipToEnd();
+      return 'comment';
+    }
+    if (ch === '$') {
+      state.tokens.unshift(tokenDollar);
+      return tokenize(stream, state);
+    }
+    if (ch === '+' || ch === '=') {
+      return 'operator';
+    }
+    if (ch === '-') {
+      stream.eat('-');
+      stream.eatWhile(/\w/);
+      return 'attribute';
+    }
+    if (/\d/.test(ch)) {
+      stream.eatWhile(/\d/);
+      if(!/\w/.test(stream.peek())) {
+        return 'number';
+      }
+    }
+    stream.eatWhile(/[\w-]/);
+    var cur = stream.current();
+    if (stream.peek() === '=' && /\w+/.test(cur)) return 'def';
+    return words.hasOwnProperty(cur) ? words[cur] : null;
+  }
+
+  function tokenString(quote) {
+    return function(stream, state) {
+      var next, end = false, escaped = false;
+      while ((next = stream.next()) != null) {
+        if (next === quote && !escaped) {
+          end = true;
+          break;
+        }
+        if (next === '$' && !escaped && quote !== '\'') {
+          escaped = true;
+          stream.backUp(1);
+          state.tokens.unshift(tokenDollar);
+          break;
+        }
+        escaped = !escaped && next === '\\';
+      }
+      if (end || !escaped) {
+        state.tokens.shift();
+      }
+      return (quote === '`' || quote === ')' ? 'quote' : 'string');
+    };
+  };
+
+  var tokenDollar = function(stream, state) {
+    if (state.tokens.length > 1) stream.eat('$');
+    var ch = stream.next(), hungry = /\w/;
+    if (ch === '{') hungry = /[^}]/;
+    if (ch === '(') {
+      state.tokens[0] = tokenString(')');
+      return tokenize(stream, state);
+    }
+    if (!/\d/.test(ch)) {
+      stream.eatWhile(hungry);
+      stream.eat('}');
+    }
+    state.tokens.shift();
+    return 'def';
+  };
+
+  function tokenize(stream, state) {
+    return (state.tokens[0] || tokenBase) (stream, state);
+  };
+
+  return {
+    startState: function() {return {tokens:[]};},
+    token: function(stream, state) {
+      if (stream.eatSpace()) return null;
+      return tokenize(stream, state);
+    }
+  };
+});
+
+CodeMirror.defineMIME('text/x-sh', 'shell');
diff --git a/third-party/codemirror-3.15/mode/sieve/LICENSE b/third-party/codemirror-3.15/mode/sieve/LICENSE
new file mode 100644 (file)
index 0000000..8a74612
--- /dev/null
@@ -0,0 +1,19 @@
+Copyright (C) 2012 Thomas Schmid <schmid-thomas@gmx.net>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/third-party/codemirror-3.15/mode/sieve/index.html b/third-party/codemirror-3.15/mode/sieve/index.html
new file mode 100644 (file)
index 0000000..8b54981
--- /dev/null
@@ -0,0 +1,81 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Sieve (RFC5228) mode</title>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="sieve.js"></script>
+    <style>.CodeMirror {background: #f8f8f8;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: Sieve (RFC5228) mode</h1>
+    <form><textarea id="code" name="code">
+#
+# Example Sieve Filter
+# Declare any optional features or extension used by the script
+#
+
+require ["fileinto", "reject"];
+
+#
+# Reject any large messages (note that the four leading dots get
+# "stuffed" to three)
+#
+if size :over 1M
+{
+  reject text:
+Please do not send me large attachments.
+Put your file on a server and send me the URL.
+Thank you.
+.... Fred
+.
+;
+  stop;
+}
+
+#
+# Handle messages from known mailing lists
+# Move messages from IETF filter discussion list to filter folder
+#
+if header :is "Sender" "owner-ietf-mta-filters@imc.org"
+{
+  fileinto "filter";  # move to "filter" folder
+}
+#
+# Keep all messages to or from people in my company
+#
+elsif address :domain :is ["From", "To"] "example.com"
+{
+  keep;               # keep in "In" folder
+}
+
+#
+# Try and catch unsolicited email.  If a message is not to me,
+# or it contains a subject known to be spam, file it away.
+#
+elsif anyof (not address :all :contains
+               ["To", "Cc", "Bcc"] "me@example.com",
+             header :matches "subject"
+               ["*make*money*fast*", "*university*dipl*mas*"])
+{
+  # If message header does not contain my address,
+  # it's from a list.
+  fileinto "spam";   # move to "spam" folder
+}
+else
+{
+  # Move all other (non-company) mail to "personal"
+  # folder.
+  fileinto "personal";
+}
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>application/sieve</code>.</p>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/sieve/sieve.js b/third-party/codemirror-3.15/mode/sieve/sieve.js
new file mode 100644 (file)
index 0000000..8ca2a4c
--- /dev/null
@@ -0,0 +1,183 @@
+/*
+ * See LICENSE in this directory for the license under which this code
+ * is released.
+ */
+
+CodeMirror.defineMode("sieve", function(config) {
+  function words(str) {
+    var obj = {}, words = str.split(" ");
+    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
+    return obj;
+  }
+
+  var keywords = words("if elsif else stop require");
+  var atoms = words("true false not");
+  var indentUnit = config.indentUnit;
+
+  function tokenBase(stream, state) {
+
+    var ch = stream.next();
+    if (ch == "/" && stream.eat("*")) {
+      state.tokenize = tokenCComment;
+      return tokenCComment(stream, state);
+    }
+
+    if (ch === '#') {
+      stream.skipToEnd();
+      return "comment";
+    }
+
+    if (ch == "\"") {
+      state.tokenize = tokenString(ch);
+      return state.tokenize(stream, state);
+    }
+
+    if (ch == "(") {
+      state._indent.push("(");
+      // add virtual angel wings so that editor behaves...
+      // ...more sane incase of broken brackets
+      state._indent.push("{");
+      return null;
+    }
+
+    if (ch === "{") {
+      state._indent.push("{");
+      return null;
+    }
+
+    if (ch == ")")  {
+      state._indent.pop();
+      state._indent.pop();
+    }
+
+    if (ch === "}") {
+      state._indent.pop();
+      return null;
+    }
+
+    if (ch == ",")
+      return null;
+
+    if (ch == ";")
+      return null;
+
+
+    if (/[{}\(\),;]/.test(ch))
+      return null;
+
+    // 1*DIGIT "K" / "M" / "G"
+    if (/\d/.test(ch)) {
+      stream.eatWhile(/[\d]/);
+      stream.eat(/[KkMmGg]/);
+      return "number";
+    }
+
+    // ":" (ALPHA / "_") *(ALPHA / DIGIT / "_")
+    if (ch == ":") {
+      stream.eatWhile(/[a-zA-Z_]/);
+      stream.eatWhile(/[a-zA-Z0-9_]/);
+
+      return "operator";
+    }
+
+    stream.eatWhile(/\w/);
+    var cur = stream.current();
+
+    // "text:" *(SP / HTAB) (hash-comment / CRLF)
+    // *(multiline-literal / multiline-dotstart)
+    // "." CRLF
+    if ((cur == "text") && stream.eat(":"))
+    {
+      state.tokenize = tokenMultiLineString;
+      return "string";
+    }
+
+    if (keywords.propertyIsEnumerable(cur))
+      return "keyword";
+
+    if (atoms.propertyIsEnumerable(cur))
+      return "atom";
+
+    return null;
+  }
+
+  function tokenMultiLineString(stream, state)
+  {
+    state._multiLineString = true;
+    // the first line is special it may contain a comment
+    if (!stream.sol()) {
+      stream.eatSpace();
+
+      if (stream.peek() == "#") {
+        stream.skipToEnd();
+        return "comment";
+      }
+
+      stream.skipToEnd();
+      return "string";
+    }
+
+    if ((stream.next() == ".")  && (stream.eol()))
+    {
+      state._multiLineString = false;
+      state.tokenize = tokenBase;
+    }
+
+    return "string";
+  }
+
+  function tokenCComment(stream, state) {
+    var maybeEnd = false, ch;
+    while ((ch = stream.next()) != null) {
+      if (maybeEnd && ch == "/") {
+        state.tokenize = tokenBase;
+        break;
+      }
+      maybeEnd = (ch == "*");
+    }
+    return "comment";
+  }
+
+  function tokenString(quote) {
+    return function(stream, state) {
+      var escaped = false, ch;
+      while ((ch = stream.next()) != null) {
+        if (ch == quote && !escaped)
+          break;
+        escaped = !escaped && ch == "\\";
+      }
+      if (!escaped) state.tokenize = tokenBase;
+      return "string";
+    };
+  }
+
+  return {
+    startState: function(base) {
+      return {tokenize: tokenBase,
+              baseIndent: base || 0,
+              _indent: []};
+    },
+
+    token: function(stream, state) {
+      if (stream.eatSpace())
+        return null;
+
+      return (state.tokenize || tokenBase)(stream, state);;
+    },
+
+    indent: function(state, _textAfter) {
+      var length = state._indent.length;
+      if (_textAfter && (_textAfter[0] == "}"))
+        length--;
+
+      if (length <0)
+        length = 0;
+
+      return length * indentUnit;
+    },
+
+    electricChars: "}"
+  };
+});
+
+CodeMirror.defineMIME("application/sieve", "sieve");
diff --git a/third-party/codemirror-3.15/mode/smalltalk/index.html b/third-party/codemirror-3.15/mode/smalltalk/index.html
new file mode 100644 (file)
index 0000000..b7aebdb
--- /dev/null
@@ -0,0 +1,57 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Smalltalk mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../../addon/edit/matchbrackets.js"></script>
+    <script src="smalltalk.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style>
+      .CodeMirror {border: 2px solid #dee; border-right-width: 10px;}
+      .CodeMirror-gutter {border: none; background: #dee;}
+      .CodeMirror-gutter pre {color: white; font-weight: bold;}
+    </style>
+  </head>
+  <body>
+    <h1>CodeMirror: Smalltalk mode</h1>
+
+<form><textarea id="code" name="code">
+" 
+    This is a test of the Smalltalk code
+"
+Seaside.WAComponent subclass: #MyCounter [
+    | count |
+    MyCounter class &gt;&gt; canBeRoot [ ^true ]
+
+    initialize [
+        super initialize.
+        count := 0.
+    ]
+    states [ ^{ self } ]
+    renderContentOn: html [
+        html heading: count.
+        html anchor callback: [ count := count + 1 ]; with: '++'.
+        html space.
+        html anchor callback: [ count := count - 1 ]; with: '--'.
+    ]
+]
+
+MyCounter registerAsApplication: 'mycounter'
+</textarea></form>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        matchBrackets: true,
+        mode: "text/x-stsrc",
+        indentUnit: 4
+      });
+    </script>
+
+    <p>Simple Smalltalk mode.</p>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-stsrc</code>.</p>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/smalltalk/smalltalk.js b/third-party/codemirror-3.15/mode/smalltalk/smalltalk.js
new file mode 100644 (file)
index 0000000..f2d4cb3
--- /dev/null
@@ -0,0 +1,151 @@
+CodeMirror.defineMode('smalltalk', function(config) {
+
+  var specialChars = /[+\-\/\\*~<>=@%|&?!.,:;^]/;
+  var keywords = /true|false|nil|self|super|thisContext/;
+
+  var Context = function(tokenizer, parent) {
+    this.next = tokenizer;
+    this.parent = parent;
+  };
+
+  var Token = function(name, context, eos) {
+    this.name = name;
+    this.context = context;
+    this.eos = eos;
+  };
+
+  var State = function() {
+    this.context = new Context(next, null);
+    this.expectVariable = true;
+    this.indentation = 0;
+    this.userIndentationDelta = 0;
+  };
+
+  State.prototype.userIndent = function(indentation) {
+    this.userIndentationDelta = indentation > 0 ? (indentation / config.indentUnit - this.indentation) : 0;
+  };
+
+  var next = function(stream, context, state) {
+    var token = new Token(null, context, false);
+    var aChar = stream.next();
+
+    if (aChar === '"') {
+      token = nextComment(stream, new Context(nextComment, context));
+
+    } else if (aChar === '\'') {
+      token = nextString(stream, new Context(nextString, context));
+
+    } else if (aChar === '#') {
+      if (stream.peek() === '\'') {
+        stream.next();
+        token = nextSymbol(stream, new Context(nextSymbol, context));
+      } else {
+        stream.eatWhile(/[^ .\[\]()]/);
+        token.name = 'string-2';
+      }
+
+    } else if (aChar === '$') {
+      if (stream.next() === '<') {
+        stream.eatWhile(/[^ >]/);
+        stream.next();
+      }
+      token.name = 'string-2';
+
+    } else if (aChar === '|' && state.expectVariable) {
+      token.context = new Context(nextTemporaries, context);
+
+    } else if (/[\[\]{}()]/.test(aChar)) {
+      token.name = 'bracket';
+      token.eos = /[\[{(]/.test(aChar);
+
+      if (aChar === '[') {
+        state.indentation++;
+      } else if (aChar === ']') {
+        state.indentation = Math.max(0, state.indentation - 1);
+      }
+
+    } else if (specialChars.test(aChar)) {
+      stream.eatWhile(specialChars);
+      token.name = 'operator';
+      token.eos = aChar !== ';'; // ; cascaded message expression
+
+    } else if (/\d/.test(aChar)) {
+      stream.eatWhile(/[\w\d]/);
+      token.name = 'number';
+
+    } else if (/[\w_]/.test(aChar)) {
+      stream.eatWhile(/[\w\d_]/);
+      token.name = state.expectVariable ? (keywords.test(stream.current()) ? 'keyword' : 'variable') : null;
+
+    } else {
+      token.eos = state.expectVariable;
+    }
+
+    return token;
+  };
+
+  var nextComment = function(stream, context) {
+    stream.eatWhile(/[^"]/);
+    return new Token('comment', stream.eat('"') ? context.parent : context, true);
+  };
+
+  var nextString = function(stream, context) {
+    stream.eatWhile(/[^']/);
+    return new Token('string', stream.eat('\'') ? context.parent : context, false);
+  };
+
+  var nextSymbol = function(stream, context) {
+    stream.eatWhile(/[^']/);
+    return new Token('string-2', stream.eat('\'') ? context.parent : context, false);
+  };
+
+  var nextTemporaries = function(stream, context) {
+    var token = new Token(null, context, false);
+    var aChar = stream.next();
+
+    if (aChar === '|') {
+      token.context = context.parent;
+      token.eos = true;
+
+    } else {
+      stream.eatWhile(/[^|]/);
+      token.name = 'variable';
+    }
+
+    return token;
+  };
+
+  return {
+    startState: function() {
+      return new State;
+    },
+
+    token: function(stream, state) {
+      state.userIndent(stream.indentation());
+
+      if (stream.eatSpace()) {
+        return null;
+      }
+
+      var token = state.context.next(stream, state.context, state);
+      state.context = token.context;
+      state.expectVariable = token.eos;
+
+      return token.name;
+    },
+
+    blankLine: function(state) {
+      state.userIndent(0);
+    },
+
+    indent: function(state, textAfter) {
+      var i = state.context.next === next && textAfter && textAfter.charAt(0) === ']' ? -1 : state.userIndentationDelta;
+      return (state.indentation + i) * config.indentUnit;
+    },
+
+    electricChars: ']'
+  };
+
+});
+
+CodeMirror.defineMIME('text/x-stsrc', {name: 'smalltalk'});
diff --git a/third-party/codemirror-3.15/mode/smarty/index.html b/third-party/codemirror-3.15/mode/smarty/index.html
new file mode 100644 (file)
index 0000000..9e41733
--- /dev/null
@@ -0,0 +1,126 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Smarty mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="smarty.js"></script>
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Smarty mode</h1>
+
+       <h3>Default settings (Smarty 2, <b>{</b> and <b>}</b> delimiters)</h3>
+    <form><textarea id="code" name="code">
+{extends file="parent.tpl"}
+{include file="template.tpl"}
+
+{* some example Smarty content *}
+{if isset($name) && $name == 'Blog'}
+  This is a {$var}.
+  {$integer = 451}, {$array[] = "a"}, {$stringvar = "string"}
+  {assign var='bob' value=$var.prop}
+{elseif $name == $foo}
+  {function name=menu level=0}
+    {foreach $data as $entry}
+      {if is_array($entry)}
+        - {$entry@key}
+        {menu data=$entry level=$level+1}
+      {else}
+        {$entry}
+      {/if}
+    {/foreach}
+  {/function}
+{/if}</textarea></form>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        mode: "smarty"
+      });
+    </script>
+
+    <br />
+
+       <h3>Smarty 2, custom delimiters</h3>
+    <form><textarea id="code2" name="code2">
+{--extends file="parent.tpl"--}
+{--include file="template.tpl"--}
+
+{--* some example Smarty content *--}
+{--if isset($name) && $name == 'Blog'--}
+  This is a {--$var--}.
+  {--$integer = 451--}, {--$array[] = "a"--}, {--$stringvar = "string"--}
+  {--assign var='bob' value=$var.prop--}
+{--elseif $name == $foo--}
+  {--function name=menu level=0--}
+    {--foreach $data as $entry--}
+      {--if is_array($entry)--}
+        - {--$entry@key--}
+        {--menu data=$entry level=$level+1--}
+      {--else--}
+        {--$entry--}
+      {--/if--}
+    {--/foreach--}
+  {--/function--}
+{--/if--}</textarea></form>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code2"), {
+        lineNumbers: true,
+        mode: {
+          name: "smarty",
+          leftDelimiter: "{--",
+          rightDelimiter: "--}"
+        }
+      });
+    </script>
+
+       <br />
+
+       <h3>Smarty 3</h3>
+
+       <textarea id="code3" name="code3">
+Nested tags {$foo={counter one=1 two={inception}}+3} are now valid in Smarty 3.
+
+<script>
+function test() {
+       console.log("Smarty 3 permits single curly braces followed by whitespace to NOT slip into Smarty mode.");
+}
+</script>
+
+{assign var=foo value=[1,2,3]}
+{assign var=foo value=['y'=>'yellow','b'=>'blue']}
+{assign var=foo value=[1,[9,8],3]}
+
+{$foo=$bar+2} {* a comment *}
+{$foo.bar=1}  {* another comment *}
+{$foo = myfunct(($x+$y)*3)}
+{$foo = strlen($bar)}
+{$foo.bar.baz=1}, {$foo[]=1}
+
+Smarty "dot" syntax (note: embedded {} are used to address ambiguities):
+
+{$foo.a.b.c}      => $foo['a']['b']['c']
+{$foo.a.$b.c}     => $foo['a'][$b]['c']
+{$foo.a.{$b+4}.c} => $foo['a'][$b+4]['c']
+{$foo.a.{$b.c}}   => $foo['a'][$b['c']]
+
+{$object->method1($x)->method2($y)}</textarea>
+
+       <script>
+               var editor = CodeMirror.fromTextArea(document.getElementById("code3"), {
+                       lineNumbers: true,
+                       mode: "smarty",
+                       smartyVersion: 3
+               });
+       </script>
+
+
+    <p>A plain text/Smarty version 2 or 3 mode, which allows for custom delimiter tags.</p>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-smarty</code></p>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/smarty/smarty.js b/third-party/codemirror-3.15/mode/smarty/smarty.js
new file mode 100644 (file)
index 0000000..826c2b9
--- /dev/null
@@ -0,0 +1,205 @@
+/**
+ * Smarty 2 and 3 mode.
+ */
+CodeMirror.defineMode("smarty", function(config) {
+  "use strict";
+
+  // our default settings; check to see if they're overridden
+  var settings = {
+    rightDelimiter: '}',
+    leftDelimiter: '{',
+    smartyVersion: 2 // for backward compatibility
+  };
+  if (config.hasOwnProperty("leftDelimiter")) {
+    settings.leftDelimiter = config.leftDelimiter;
+  }
+  if (config.hasOwnProperty("rightDelimiter")) {
+    settings.rightDelimiter = config.rightDelimiter;
+  }
+  if (config.hasOwnProperty("smartyVersion") && config.smartyVersion === 3) {
+    settings.smartyVersion = 3;
+  }
+
+  var keyFunctions = ["debug", "extends", "function", "include", "literal"];
+  var last;
+  var regs = {
+    operatorChars: /[+\-*&%=<>!?]/,
+    validIdentifier: /[a-zA-Z0-9_]/,
+    stringChar: /['"]/
+  };
+
+  var helpers = {
+    cont: function(style, lastType) {
+      last = lastType;
+      return style;
+    },
+    chain: function(stream, state, parser) {
+      state.tokenize = parser;
+      return parser(stream, state);
+    }
+  };
+
+
+  // our various parsers
+  var parsers = {
+
+    // the main tokenizer
+    tokenizer: function(stream, state) {
+      if (stream.match(settings.leftDelimiter, true)) {
+        if (stream.eat("*")) {
+          return helpers.chain(stream, state, parsers.inBlock("comment", "*" + settings.rightDelimiter));
+        } else {
+          // Smarty 3 allows { and } surrounded by whitespace to NOT slip into Smarty mode
+          state.depth++;
+          var isEol = stream.eol();
+          var isFollowedByWhitespace = /\s/.test(stream.peek());
+          if (settings.smartyVersion === 3 && settings.leftDelimiter === "{" && (isEol || isFollowedByWhitespace)) {
+            state.depth--;
+            return null;
+          } else {
+            state.tokenize = parsers.smarty;
+            last = "startTag";
+            return "tag";
+          }
+        }
+      } else {
+        stream.next();
+        return null;
+      }
+    },
+
+    // parsing Smarty content
+    smarty: function(stream, state) {
+      if (stream.match(settings.rightDelimiter, true)) {
+        if (settings.smartyVersion === 3) {
+          state.depth--;
+          if (state.depth <= 0) {
+            state.tokenize = parsers.tokenizer;
+          }
+        } else {
+          state.tokenize = parsers.tokenizer;
+        }
+        return helpers.cont("tag", null);
+      }
+
+      if (stream.match(settings.leftDelimiter, true)) {
+        state.depth++;
+        return helpers.cont("tag", "startTag");
+      }
+
+      var ch = stream.next();
+      if (ch == "$") {
+        stream.eatWhile(regs.validIdentifier);
+        return helpers.cont("variable-2", "variable");
+      } else if (ch == "|") {
+        return helpers.cont("operator", "pipe");
+      } else if (ch == ".") {
+        return helpers.cont("operator", "property");
+      } else if (regs.stringChar.test(ch)) {
+        state.tokenize = parsers.inAttribute(ch);
+        return helpers.cont("string", "string");
+      } else if (regs.operatorChars.test(ch)) {
+        stream.eatWhile(regs.operatorChars);
+        return helpers.cont("operator", "operator");
+      } else if (ch == "[" || ch == "]") {
+        return helpers.cont("bracket", "bracket");
+      } else if (ch == "(" || ch == ")") {
+        return helpers.cont("bracket", "operator");
+      } else if (/\d/.test(ch)) {
+        stream.eatWhile(/\d/);
+        return helpers.cont("number", "number");
+      } else {
+
+        if (state.last == "variable") {
+          if (ch == "@") {
+            stream.eatWhile(regs.validIdentifier);
+            return helpers.cont("property", "property");
+          } else if (ch == "|") {
+            stream.eatWhile(regs.validIdentifier);
+            return helpers.cont("qualifier", "modifier");
+          }
+        } else if (state.last == "pipe") {
+          stream.eatWhile(regs.validIdentifier);
+          return helpers.cont("qualifier", "modifier");
+        } else if (state.last == "whitespace") {
+          stream.eatWhile(regs.validIdentifier);
+          return helpers.cont("attribute", "modifier");
+        } if (state.last == "property") {
+          stream.eatWhile(regs.validIdentifier);
+          return helpers.cont("property", null);
+        } else if (/\s/.test(ch)) {
+          last = "whitespace";
+          return null;
+        }
+
+        var str = "";
+        if (ch != "/") {
+          str += ch;
+        }
+        var c = null;
+        while (c = stream.eat(regs.validIdentifier)) {
+          str += c;
+        }
+        for (var i=0, j=keyFunctions.length; i<j; i++) {
+          if (keyFunctions[i] == str) {
+            return helpers.cont("keyword", "keyword");
+          }
+        }
+        if (/\s/.test(ch)) {
+          return null;
+        }
+        return helpers.cont("tag", "tag");
+      }
+    },
+
+    inAttribute: function(quote) {
+      return function(stream, state) {
+        var prevChar = null;
+        var currChar = null;
+        while (!stream.eol()) {
+          currChar = stream.peek();
+          if (stream.next() == quote && prevChar !== '\\') {
+            state.tokenize = parsers.smarty;
+            break;
+          }
+          prevChar = currChar;
+        }
+        return "string";
+      };
+    },
+
+    inBlock: function(style, terminator) {
+      return function(stream, state) {
+        while (!stream.eol()) {
+          if (stream.match(terminator)) {
+            state.tokenize = parsers.tokenizer;
+            break;
+          }
+          stream.next();
+        }
+        return style;
+      };
+    }
+  };
+
+
+  // the public API for CodeMirror
+  return {
+    startState: function() {
+      return {
+        tokenize: parsers.tokenizer,
+        mode: "smarty",
+        last: null,
+        depth: 0
+      };
+    },
+    token: function(stream, state) {
+      var style = state.tokenize(stream, state);
+      state.last = last;
+      return style;
+    },
+    electricChars: ""
+  };
+});
+
+CodeMirror.defineMIME("text/x-smarty", "smarty");
diff --git a/third-party/codemirror-3.15/mode/smartymixed/index.html b/third-party/codemirror-3.15/mode/smartymixed/index.html
new file mode 100644 (file)
index 0000000..6567b27
--- /dev/null
@@ -0,0 +1,107 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Smarty mixed mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+
+    <!-- smartymixed dependencies -->
+    <script src="../../mode/xml/xml.js"></script>
+    <script src="../../mode/javascript/javascript.js"></script>
+    <script src="../../mode/css/css.js"></script>
+    <script src="../../mode/htmlmixed/htmlmixed.js"></script>
+    <script src="../../mode/smarty/smarty.js"></script>
+
+    <!-- smartymixed -->
+    <script src="../../mode/smartymixed/smartymixed.js"></script>
+  </head>
+  <body>
+    <h1>CodeMirror: Smarty mixed mode</h1>
+    <form><textarea id="code" name="code">
+{**
+* @brief Smarty mixed mode
+* @author Ruslan Osmanov
+* @date 29.06.2013
+*}
+<html>
+<head>
+  <title>{$title|htmlspecialchars|truncate:30}</title>
+</head>
+<body>
+  {* Multiline smarty
+  * comment, no {$variables} here
+  *}
+  {literal}
+  {literal} is just an HTML text.
+  <script type="text/javascript">//<![CDATA[
+    var a = {$just_a_normal_js_object : "value"};
+    var myCodeMirror = CodeMirror.fromTextArea(document.getElementById("code"), {
+      mode           : "smartymixed",
+      tabSize        : 2,
+      indentUnit     : 2,
+      indentWithTabs : false,
+      lineNumbers    : true,
+      smartyVersion  : 3
+    });
+    // ]]>
+  </script>
+  <style>
+    /* CSS content 
+    {$no_smarty} */
+    .some-class { font-weight: bolder; color: "orange"; }
+  </style>
+  {/literal}
+
+  {extends file="parent.tpl"}
+  {include file="template.tpl"}
+
+  {* some example Smarty content *}
+  {if isset($name) && $name == 'Blog'}
+    This is a {$var}.
+    {$integer = 4511}, {$array[] = "a"}, {$stringvar = "string"}
+    {$integer = 4512} {$array[] = "a"} {$stringvar = "string"}
+    {assign var='bob' value=$var.prop}
+  {elseif $name == $foo}
+    {function name=menu level=0}
+    {foreach $data as $entry}
+      {if is_array($entry)}
+      - {$entry@key}
+      {menu data=$entry level=$level+1}
+      {else}
+      {$entry}
+      {* One
+      * Two
+      * Three
+      *}
+      {/if}
+    {/foreach}
+    {/function}
+  {/if}
+  </body>
+  <!-- R.O. -->
+</html>
+</textarea></form>
+
+    <script type="text/javascript">
+      var myCodeMirror = CodeMirror.fromTextArea(document.getElementById("code"), {
+        mode           : "smartymixed",
+        tabSize        : 2,
+        indentUnit     : 2,
+        indentWithTabs : false,
+        lineNumbers    : true,
+        smartyVersion  : 3,
+        matchBrackets  : true,
+      });
+    </script>
+
+    <p>The Smarty mixed mode depends on the Smarty and HTML mixed modes. HTML
+    mixed mode itself depends on XML, JavaScript, and CSS modes.</p>
+
+    <p>It takes the same options, as Smarty and HTML mixed modes.</p>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-smarty</code>.</p>
+  </body>
+</html>
+<!-- vim: set ft=html ts=2 sts=2 sw=2 et: -->
diff --git a/third-party/codemirror-3.15/mode/smartymixed/smartymixed.js b/third-party/codemirror-3.15/mode/smartymixed/smartymixed.js
new file mode 100644 (file)
index 0000000..c5d0088
--- /dev/null
@@ -0,0 +1,170 @@
+/**
+* @file smartymixed.js
+* @brief Smarty Mixed Codemirror mode (Smarty + Mixed HTML)
+* @author Ruslan Osmanov <rrosmanov at gmail dot com>
+* @version 3.0
+* @date 05.07.2013
+*/
+CodeMirror.defineMode("smartymixed", function(config) {
+  var settings, regs, helpers, parsers,
+  htmlMixedMode = CodeMirror.getMode(config, "htmlmixed"),
+  smartyMode = CodeMirror.getMode(config, "smarty"),
+
+  settings = {
+    rightDelimiter: '}',
+    leftDelimiter: '{'
+  };
+
+  if (config.hasOwnProperty("leftDelimiter")) {
+    settings.leftDelimiter = config.leftDelimiter;
+  }
+  if (config.hasOwnProperty("rightDelimiter")) {
+    settings.rightDelimiter = config.rightDelimiter;
+  }
+
+  regs = {
+    smartyComment: new RegExp("^" + settings.leftDelimiter + "\\*"),
+    literalOpen: new RegExp(settings.leftDelimiter + "literal" + settings.rightDelimiter),
+    literalClose: new RegExp(settings.leftDelimiter + "\/literal" + settings.rightDelimiter),
+    hasLeftDelimeter: new RegExp(".*" + settings.leftDelimiter),
+    htmlHasLeftDelimeter: new RegExp("[^<>]*" + settings.leftDelimiter)
+  };
+
+  helpers = {
+    chain: function(stream, state, parser) {
+      state.tokenize = parser;
+      return parser(stream, state);
+    },
+
+    cleanChain: function(stream, state, parser) {
+      state.tokenize = null;
+      state.localState = null;
+      state.localMode = null;
+      return (typeof parser == "string") ? (parser ? parser : null) : parser(stream, state);
+    },
+
+    maybeBackup: function(stream, pat, style) {
+      var cur = stream.current();
+      var close = cur.search(pat),
+      m;
+      if (close > - 1) stream.backUp(cur.length - close);
+      else if (m = cur.match(/<\/?$/)) {
+        stream.backUp(cur.length);
+        if (!stream.match(pat, false)) stream.match(cur[0]);
+      }
+      return style;
+    }
+  };
+
+  parsers = {
+    html: function(stream, state) {
+      if (!state.inLiteral && stream.match(regs.htmlHasLeftDelimeter, false)) {
+        state.tokenize = parsers.smarty;
+        state.localMode = smartyMode;
+        state.localState = smartyMode.startState(htmlMixedMode.indent(state.htmlMixedState, ""));
+        return helpers.maybeBackup(stream, settings.leftDelimiter, smartyMode.token(stream, state.localState));
+      }
+      return htmlMixedMode.token(stream, state.htmlMixedState);
+    },
+
+    smarty: function(stream, state) {
+      if (stream.match(settings.leftDelimiter, false)) {
+        if (stream.match(regs.smartyComment, false)) {
+          return helpers.chain(stream, state, parsers.inBlock("comment", "*" + settings.rightDelimiter));
+        }
+      } else if (stream.match(settings.rightDelimiter, false)) {
+        stream.eat(settings.rightDelimiter);
+        state.tokenize = parsers.html;
+        state.localMode = htmlMixedMode;
+        state.localState = state.htmlMixedState;
+        return "tag";
+      }
+
+      return helpers.maybeBackup(stream, settings.rightDelimiter, smartyMode.token(stream, state.localState));
+    },
+
+    inBlock: function(style, terminator) {
+      return function(stream, state) {
+        while (!stream.eol()) {
+          if (stream.match(terminator)) {
+            helpers.cleanChain(stream, state, "");
+            break;
+          }
+          stream.next();
+        }
+        return style;
+      };
+    }
+  };
+
+  return {
+    startState: function() {
+      var state = htmlMixedMode.startState();
+      return {
+        token: parsers.html,
+        localMode: null,
+        localState: null,
+        htmlMixedState: state,
+        tokenize: null,
+        inLiteral: false
+      };
+    },
+
+    copyState: function(state) {
+      var local = null, tok = (state.tokenize || state.token);
+      if (state.localState) {
+        local = CodeMirror.copyState((tok != parsers.html ? smartyMode : htmlMixedMode), state.localState);
+      }
+      return {
+        token: state.token,
+        tokenize: state.tokenize,
+        localMode: state.localMode,
+        localState: local,
+        htmlMixedState: CodeMirror.copyState(htmlMixedMode, state.htmlMixedState),
+        inLiteral: state.inLiteral
+      };
+    },
+
+    token: function(stream, state) {
+      if (stream.match(settings.leftDelimiter, false)) {
+        if (!state.inLiteral && stream.match(regs.literalOpen, true)) {
+          state.inLiteral = true;
+          return "keyword";
+        } else if (state.inLiteral && stream.match(regs.literalClose, true)) {
+          state.inLiteral = false;
+          return "keyword";
+        }
+      }
+      if (state.inLiteral && state.localState != state.htmlMixedState) {
+        state.tokenize = parsers.html;
+        state.localMode = htmlMixedMode;
+        state.localState = state.htmlMixedState;
+      }
+
+      var style = (state.tokenize || state.token)(stream, state);
+      return style;
+    },
+
+    indent: function(state, textAfter) {
+      if (state.localMode == smartyMode
+          || (state.inLiteral && !state.localMode)
+         || regs.hasLeftDelimeter.test(textAfter)) {
+        return CodeMirror.Pass;
+      }
+      return htmlMixedMode.indent(state.htmlMixedState, textAfter);
+    },
+
+    electricChars: "/{}:",
+
+    innerMode: function(state) {
+      return {
+        state: state.localState || state.htmlMixedState,
+        mode: state.localMode || htmlMixedMode
+      };
+    }
+  };
+},
+"htmlmixed");
+
+CodeMirror.defineMIME("text/x-smarty", "smartymixed");
+// vim: et ts=2 sts=2 sw=2
diff --git a/third-party/codemirror-3.15/mode/sparql/index.html b/third-party/codemirror-3.15/mode/sparql/index.html
new file mode 100644 (file)
index 0000000..e743387
--- /dev/null
@@ -0,0 +1,42 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: SPARQL mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../../addon/edit/matchbrackets.js"></script>
+    <script src="sparql.js"></script>
+    <style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: SPARQL mode</h1>
+    <form><textarea id="code" name="code">
+PREFIX a: &lt;http://www.w3.org/2000/10/annotation-ns#>
+PREFIX dc: &lt;http://purl.org/dc/elements/1.1/>
+PREFIX foaf: &lt;http://xmlns.com/foaf/0.1/>
+
+# Comment!
+
+SELECT ?given ?family
+WHERE {
+  ?annot a:annotates &lt;http://www.w3.org/TR/rdf-sparql-query/> .
+  ?annot dc:creator ?c .
+  OPTIONAL {?c foaf:given ?given ;
+               foaf:family ?family } .
+  FILTER isBlank(?c)
+}
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        mode: "application/x-sparql-query",
+        tabMode: "indent",
+        matchBrackets: true
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>application/x-sparql-query</code>.</p>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/sparql/sparql.js b/third-party/codemirror-3.15/mode/sparql/sparql.js
new file mode 100644 (file)
index 0000000..0329057
--- /dev/null
@@ -0,0 +1,145 @@
+CodeMirror.defineMode("sparql", function(config) {
+  var indentUnit = config.indentUnit;
+  var curPunc;
+
+  function wordRegexp(words) {
+    return new RegExp("^(?:" + words.join("|") + ")$", "i");
+  }
+  var ops = wordRegexp(["str", "lang", "langmatches", "datatype", "bound", "sameterm", "isiri", "isuri",
+                        "isblank", "isliteral", "a"]);
+  var keywords = wordRegexp(["base", "prefix", "select", "distinct", "reduced", "construct", "describe",
+                             "ask", "from", "named", "where", "order", "limit", "offset", "filter", "optional",
+                             "graph", "by", "asc", "desc", "as", "having", "undef", "values", "group",
+                             "minus", "in", "not", "service", "silent", "using", "insert", "delete", "union",
+                             "data", "copy", "to", "move", "add", "create", "drop", "clear", "load"]);
+  var operatorChars = /[*+\-<>=&|]/;
+
+  function tokenBase(stream, state) {
+    var ch = stream.next();
+    curPunc = null;
+    if (ch == "$" || ch == "?") {
+      stream.match(/^[\w\d]*/);
+      return "variable-2";
+    }
+    else if (ch == "<" && !stream.match(/^[\s\u00a0=]/, false)) {
+      stream.match(/^[^\s\u00a0>]*>?/);
+      return "atom";
+    }
+    else if (ch == "\"" || ch == "'") {
+      state.tokenize = tokenLiteral(ch);
+      return state.tokenize(stream, state);
+    }
+    else if (/[{}\(\),\.;\[\]]/.test(ch)) {
+      curPunc = ch;
+      return null;
+    }
+    else if (ch == "#") {
+      stream.skipToEnd();
+      return "comment";
+    }
+    else if (operatorChars.test(ch)) {
+      stream.eatWhile(operatorChars);
+      return null;
+    }
+    else if (ch == ":") {
+      stream.eatWhile(/[\w\d\._\-]/);
+      return "atom";
+    }
+    else {
+      stream.eatWhile(/[_\w\d]/);
+      if (stream.eat(":")) {
+        stream.eatWhile(/[\w\d_\-]/);
+        return "atom";
+      }
+      var word = stream.current();
+      if (ops.test(word))
+        return null;
+      else if (keywords.test(word))
+        return "keyword";
+      else
+        return "variable";
+    }
+  }
+
+  function tokenLiteral(quote) {
+    return function(stream, state) {
+      var escaped = false, ch;
+      while ((ch = stream.next()) != null) {
+        if (ch == quote && !escaped) {
+          state.tokenize = tokenBase;
+          break;
+        }
+        escaped = !escaped && ch == "\\";
+      }
+      return "string";
+    };
+  }
+
+  function pushContext(state, type, col) {
+    state.context = {prev: state.context, indent: state.indent, col: col, type: type};
+  }
+  function popContext(state) {
+    state.indent = state.context.indent;
+    state.context = state.context.prev;
+  }
+
+  return {
+    startState: function() {
+      return {tokenize: tokenBase,
+              context: null,
+              indent: 0,
+              col: 0};
+    },
+
+    token: function(stream, state) {
+      if (stream.sol()) {
+        if (state.context && state.context.align == null) state.context.align = false;
+        state.indent = stream.indentation();
+      }
+      if (stream.eatSpace()) return null;
+      var style = state.tokenize(stream, state);
+
+      if (style != "comment" && state.context && state.context.align == null && state.context.type != "pattern") {
+        state.context.align = true;
+      }
+
+      if (curPunc == "(") pushContext(state, ")", stream.column());
+      else if (curPunc == "[") pushContext(state, "]", stream.column());
+      else if (curPunc == "{") pushContext(state, "}", stream.column());
+      else if (/[\]\}\)]/.test(curPunc)) {
+        while (state.context && state.context.type == "pattern") popContext(state);
+        if (state.context && curPunc == state.context.type) popContext(state);
+      }
+      else if (curPunc == "." && state.context && state.context.type == "pattern") popContext(state);
+      else if (/atom|string|variable/.test(style) && state.context) {
+        if (/[\}\]]/.test(state.context.type))
+          pushContext(state, "pattern", stream.column());
+        else if (state.context.type == "pattern" && !state.context.align) {
+          state.context.align = true;
+          state.context.col = stream.column();
+        }
+      }
+
+      return style;
+    },
+
+    indent: function(state, textAfter) {
+      var firstChar = textAfter && textAfter.charAt(0);
+      var context = state.context;
+      if (/[\]\}]/.test(firstChar))
+        while (context && context.type == "pattern") context = context.prev;
+
+      var closing = context && firstChar == context.type;
+      if (!context)
+        return 0;
+      else if (context.type == "pattern")
+        return context.col;
+      else if (context.align)
+        return context.col + (closing ? 0 : 1);
+      else
+        return context.indent + (closing ? 0 : indentUnit);
+    }
+  };
+});
+
+CodeMirror.defineMIME("application/x-sparql-query", "sparql");
diff --git a/third-party/codemirror-3.15/mode/sql/index.html b/third-party/codemirror-3.15/mode/sql/index.html
new file mode 100644 (file)
index 0000000..acf60b8
--- /dev/null
@@ -0,0 +1,68 @@
+<!doctype html>
+<html>
+    <head>
+        <meta charset="utf-8">
+        <title>SQL Mode for CodeMirror</title>
+        <link rel="stylesheet" href="../../lib/codemirror.css" />
+        <script src="../../lib/codemirror.js"></script>
+        <script src="sql.js"></script>
+        <style>
+.CodeMirror {
+    border-top: 1px solid black;
+    border-bottom: 1px solid black;
+}
+        </style>
+        <link rel="stylesheet" href="../../doc/docs.css">
+        <script>
+var init = function() {
+    var mime = 'text/x-mariadb';
+
+    // get mime type
+    if (window.location.href.indexOf('mime=') > -1) {
+        mime = window.location.href.substr(window.location.href.indexOf('mime=') + 5);
+    }
+
+    window.editor = CodeMirror.fromTextArea(document.getElementById('code'), {
+        mode: mime,
+        indentWithTabs: true,
+        smartIndent: true,
+        lineNumbers: true,
+        matchBrackets : true,
+        autofocus: true
+    });
+};
+        </script>
+    </head>
+    <body onload="init();">
+        <h1>SQL Mode for CodeMirror</h1>
+        <form>
+            <textarea id="code" name="code">-- SQL Mode for CodeMirror
+SELECT SQL_NO_CACHE DISTINCT
+               @var1 AS `val1`, @'val2', @global.'sql_mode',
+               1.1 AS `float_val`, .14 AS `another_float`, 0.09e3 AS `int_with_esp`,
+               0xFA5 AS `hex`, x'fa5' AS `hex2`, 0b101 AS `bin`, b'101' AS `bin2`,
+               DATE '1994-01-01' AS `sql_date`, { T "1994-01-01" } AS `odbc_date`,
+               'my string', _utf8'your string', N'her string',
+        TRUE, FALSE, UNKNOWN
+       FROM DUAL
+       -- space needed after '--'
+       # 1 line comment
+       /* multiline
+       comment! */
+       LIMIT 1 OFFSET 0;
+</textarea>
+            </form>
+            <p><strong>MIME types defined:</strong> 
+            <code><a href="?mime=text/x-sql">text/x-sql</a></code>,
+            <code><a href="?mime=text/x-mysql">text/x-mysql</a></code>,
+            <code><a href="?mime=text/x-mariadb">text/x-mariadb</a></code>,
+            <code><a href="?mime=text/x-cassandra">text/x-cassandra</a></code>,
+            <code><a href="?mime=text/x-plsql">text/x-plsql</a></code>.
+        </p>
+        <p>
+            <strong>Tests:</strong>
+            <a href="../../test/index.html#sql_*">normal</a>,
+            <a href="../../test/index.html#verbose,sql_*">verbose</a>.
+        </p>
+    </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/sql/sql.js b/third-party/codemirror-3.15/mode/sql/sql.js
new file mode 100644 (file)
index 0000000..9016cc7
--- /dev/null
@@ -0,0 +1,349 @@
+CodeMirror.defineMode("sql", function(config, parserConfig) {
+  "use strict";
+
+  var client         = parserConfig.client || {},
+      atoms          = parserConfig.atoms || {"false": true, "true": true, "null": true},
+      builtin        = parserConfig.builtin || {},
+      keywords       = parserConfig.keywords || {},
+      operatorChars  = parserConfig.operatorChars || /^[*+\-%<>!=&|~^]/,
+      support        = parserConfig.support || {},
+      hooks          = parserConfig.hooks || {},
+      dateSQL        = parserConfig.dateSQL || {"date" : true, "time" : true, "timestamp" : true};
+
+  function tokenBase(stream, state) {
+    var ch = stream.next();
+
+    // call hooks from the mime type
+    if (hooks[ch]) {
+      var result = hooks[ch](stream, state);
+      if (result !== false) return result;
+    }
+
+    if (support.hexNumber == true &&
+      ((ch == "0" && stream.match(/^[xX][0-9a-fA-F]+/))
+      || (ch == "x" || ch == "X") && stream.match(/^'[0-9a-fA-F]+'/))) {
+      // hex
+      // ref: http://dev.mysql.com/doc/refman/5.5/en/hexadecimal-literals.html
+      return "number";
+    } else if (support.binaryNumber == true &&
+      (((ch == "b" || ch == "B") && stream.match(/^'[01]+'/))
+      || (ch == "0" && stream.match(/^b[01]+/)))) {
+      // bitstring
+      // ref: http://dev.mysql.com/doc/refman/5.5/en/bit-field-literals.html
+      return "number";
+    } else if (ch.charCodeAt(0) > 47 && ch.charCodeAt(0) < 58) {
+      // numbers
+      // ref: http://dev.mysql.com/doc/refman/5.5/en/number-literals.html
+          stream.match(/^[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?/);
+      support.decimallessFloat == true && stream.eat('.');
+      return "number";
+    } else if (ch == "?" && (stream.eatSpace() || stream.eol() || stream.eat(";"))) {
+      // placeholders
+      return "variable-3";
+    } else if (ch == "'" || (ch == '"' && support.doubleQuote)) {
+      // strings
+      // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html
+      state.tokenize = tokenLiteral(ch);
+      return state.tokenize(stream, state);
+    } else if ((((support.nCharCast == true && (ch == "n" || ch == "N"))
+        || (support.charsetCast == true && ch == "_" && stream.match(/[a-z][a-z0-9]*/i)))
+        && (stream.peek() == "'" || stream.peek() == '"'))) {
+      // charset casting: _utf8'str', N'str', n'str'
+      // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html
+      return "keyword";
+    } else if (/^[\(\),\;\[\]]/.test(ch)) {
+      // no highlightning
+      return null;
+    } else if (support.commentSlashSlash && ch == "/" && stream.eat("/")) {
+      // 1-line comment
+      stream.skipToEnd();
+      return "comment";
+    } else if ((support.commentHash && ch == "#")
+        || (ch == "-" && stream.eat("-") && (!support.commentSpaceRequired || stream.eat(" ")))) {
+      // 1-line comments
+      // ref: https://kb.askmonty.org/en/comment-syntax/
+      stream.skipToEnd();
+      return "comment";
+    } else if (ch == "/" && stream.eat("*")) {
+      // multi-line comments
+      // ref: https://kb.askmonty.org/en/comment-syntax/
+      state.tokenize = tokenComment;
+      return state.tokenize(stream, state);
+    } else if (ch == ".") {
+      // .1 for 0.1
+      if (support.zerolessFloat == true && stream.match(/^(?:\d+(?:e[+-]?\d+)?)/i)) {
+        return "number";
+      }
+      // .table_name (ODBC)
+      // // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html
+      if (support.ODBCdotTable == true && stream.match(/^[a-zA-Z_]+/)) {
+        return "variable-2";
+      }
+    } else if (operatorChars.test(ch)) {
+      // operators
+      stream.eatWhile(operatorChars);
+      return null;
+    } else if (ch == '{' &&
+        (stream.match(/^( )*(d|D|t|T|ts|TS)( )*'[^']*'( )*}/) || stream.match(/^( )*(d|D|t|T|ts|TS)( )*"[^"]*"( )*}/))) {
+      // dates (weird ODBC syntax)
+      // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html
+      return "number";
+    } else {
+      stream.eatWhile(/^[_\w\d]/);
+      var word = stream.current().toLowerCase();
+      // dates (standard SQL syntax)
+      // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html
+      if (dateSQL.hasOwnProperty(word) && (stream.match(/^( )+'[^']*'/) || stream.match(/^( )+"[^"]*"/)))
+        return "number";
+      if (atoms.hasOwnProperty(word)) return "atom";
+      if (builtin.hasOwnProperty(word)) return "builtin";
+      if (keywords.hasOwnProperty(word)) return "keyword";
+      if (client.hasOwnProperty(word)) return "string-2";
+      return null;
+    }
+  }
+
+  // 'string', with char specified in quote escaped by '\'
+  function tokenLiteral(quote) {
+    return function(stream, state) {
+      var escaped = false, ch;
+      while ((ch = stream.next()) != null) {
+        if (ch == quote && !escaped) {
+          state.tokenize = tokenBase;
+          break;
+        }
+        escaped = !escaped && ch == "\\";
+      }
+      return "string";
+    };
+  }
+  function tokenComment(stream, state) {
+    while (true) {
+      if (stream.skipTo("*")) {
+        stream.next();
+        if (stream.eat("/")) {
+          state.tokenize = tokenBase;
+          break;
+        }
+      } else {
+        stream.skipToEnd();
+        break;
+      }
+    }
+    return "comment";
+  }
+
+  function pushContext(stream, state, type) {
+    state.context = {
+      prev: state.context,
+      indent: stream.indentation(),
+      col: stream.column(),
+      type: type
+    };
+  }
+
+  function popContext(state) {
+    state.indent = state.context.indent;
+    state.context = state.context.prev;
+  }
+
+  return {
+    startState: function() {
+      return {tokenize: tokenBase, context: null};
+    },
+
+    token: function(stream, state) {
+      if (stream.sol()) {
+        if (state.context && state.context.align == null)
+          state.context.align = false;
+      }
+      if (stream.eatSpace()) return null;
+
+      var style = state.tokenize(stream, state);
+      if (style == "comment") return style;
+
+      if (state.context && state.context.align == null)
+        state.context.align = true;
+
+      var tok = stream.current();
+      if (tok == "(")
+        pushContext(stream, state, ")");
+      else if (tok == "[")
+        pushContext(stream, state, "]");
+      else if (state.context && state.context.type == tok)
+        popContext(state);
+      return style;
+    },
+
+    indent: function(state, textAfter) {
+      var cx = state.context;
+      if (!cx) return CodeMirror.Pass;
+      if (cx.align) return cx.col + (textAfter.charAt(0) == cx.type ? 0 : 1);
+      else return cx.indent + config.indentUnit;
+    }
+  };
+});
+
+(function() {
+  "use strict";
+
+  // `identifier`
+  function hookIdentifier(stream) {
+    // MySQL/MariaDB identifiers
+    // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html
+    var ch;
+    while ((ch = stream.next()) != null) {
+      if (ch == "`" && !stream.eat("`")) return "variable-2";
+    }
+    return null;
+  }
+
+  // variable token
+  function hookVar(stream) {
+    // variables
+    // @@prefix.varName @varName
+    // varName can be quoted with ` or ' or "
+    // ref: http://dev.mysql.com/doc/refman/5.5/en/user-variables.html
+    if (stream.eat("@")) {
+      stream.match(/^session\./);
+      stream.match(/^local\./);
+      stream.match(/^global\./);
+    }
+
+    if (stream.eat("'")) {
+      stream.match(/^.*'/);
+      return "variable-2";
+    } else if (stream.eat('"')) {
+      stream.match(/^.*"/);
+      return "variable-2";
+    } else if (stream.eat("`")) {
+      stream.match(/^.*`/);
+      return "variable-2";
+    } else if (stream.match(/^[0-9a-zA-Z$\.\_]+/)) {
+      return "variable-2";
+    }
+    return null;
+  };
+
+  // short client keyword token
+  function hookClient(stream) {
+    // \N means NULL
+    // ref: http://dev.mysql.com/doc/refman/5.5/en/null-values.html
+    if (stream.eat("N")) {
+        return "atom";
+    }
+    // \g, etc
+    // ref: http://dev.mysql.com/doc/refman/5.5/en/mysql-commands.html
+    return stream.match(/^[a-zA-Z.#!?]/) ? "variable-2" : null;
+  }
+
+  // these keywords are used by all SQL dialects (however, a mode can still overwrite it)
+  var sqlKeywords = "alter and as asc between by count create delete desc distinct drop from having in insert into is join like not on or order select set table union update values where ";
+
+  // turn a space-separated list into an array
+  function set(str) {
+    var obj = {}, words = str.split(" ");
+    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
+    return obj;
+  }
+
+  // A generic SQL Mode. It's not a standard, it just try to support what is generally supported
+  CodeMirror.defineMIME("text/x-sql", {
+    name: "sql",
+    keywords: set(sqlKeywords + "begin"),
+    builtin: set("bool boolean bit blob enum long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision real date datetime year unsigned signed decimal numeric"),
+    atoms: set("false true null unknown"),
+    operatorChars: /^[*+\-%<>!=]/,
+    dateSQL: set("date time timestamp"),
+    support: set("ODBCdotTable doubleQuote binaryNumber hexNumber")
+  });
+
+  CodeMirror.defineMIME("text/x-mysql", {
+    name: "sql",
+    client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),
+    keywords: set(sqlKeywords + "accessible action add after algorithm all analyze asensitive at authors auto_increment autocommit avg avg_row_length before binary binlog both btree cache call cascade cascaded case catalog_name chain change changed character check checkpoint checksum class_origin client_statistics close coalesce code collate collation collations column columns comment commit committed completion concurrent condition connection consistent constraint contains continue contributors convert cross current_date current_time current_timestamp current_user cursor data database databases day_hour day_microsecond day_minute day_second deallocate dec declare default delay_key_write delayed delimiter des_key_file describe deterministic dev_pop dev_samp deviance directory disable discard distinctrow div dual dumpfile each elseif enable enclosed end ends engine engines enum errors escape escaped even event events every execute exists exit explain extended fast fetch field fields first flush for force foreign found_rows full fulltext function general global grant grants group groupby_concat handler hash help high_priority hosts hour_microsecond hour_minute hour_second if ignore ignore_server_ids import index index_statistics infile inner innodb inout insensitive insert_method install interval invoker isolation iterate key keys kill language last leading leave left level limit linear lines list load local localtime localtimestamp lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters match max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modifies modify mutex mysql_errno natural next no no_write_to_binlog offline offset one online open optimize option optionally out outer outfile pack_keys parser partition partitions password phase plugin plugins prepare preserve prev primary privileges procedure processlist profile profiles purge query quick range read read_write reads real rebuild recover references regexp relaylog release remove rename reorganize repair repeatable replace require resignal restrict resume return returns revoke right rlike rollback rollup row row_format rtree savepoint schedule schema schema_name schemas second_microsecond security sensitive separator serializable server session share show signal slave slow smallint snapshot soname spatial specific sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result sqlexception sqlstate sqlwarning ssl start starting starts status std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace temporary terminated to trailing transaction trigger triggers truncate uncommitted undo uninstall unique unlock upgrade usage use use_frm user user_resources user_statistics using utc_date utc_time utc_timestamp value variables varying view views warnings when while with work write xa xor year_month zerofill begin do then else loop repeat"),
+    builtin: set("bool boolean bit blob decimal double enum float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision date datetime year unsigned signed numeric"),
+    atoms: set("false true null unknown"),
+    operatorChars: /^[*+\-%<>!=&|^]/,
+    dateSQL: set("date time timestamp"),
+    support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired"),
+    hooks: {
+      "@":   hookVar,
+      "`":   hookIdentifier,
+      "\\":  hookClient
+    }
+  });
+
+  CodeMirror.defineMIME("text/x-mariadb", {
+    name: "sql",
+    client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),
+    keywords: set(sqlKeywords + "accessible action add after algorithm all always analyze asensitive at authors auto_increment autocommit avg avg_row_length before binary binlog both btree cache call cascade cascaded case catalog_name chain change changed character check checkpoint checksum class_origin client_statistics close coalesce code collate collation collations column columns comment commit committed completion concurrent condition connection consistent constraint contains continue contributors convert cross current_date current_time current_timestamp current_user cursor data database databases day_hour day_microsecond day_minute day_second deallocate dec declare default delay_key_write delayed delimiter des_key_file describe deterministic dev_pop dev_samp deviance directory disable discard distinctrow div dual dumpfile each elseif enable enclosed end ends engine engines enum errors escape escaped even event events every execute exists exit explain extended fast fetch field fields first flush for force foreign found_rows full fulltext function general generated global grant grants group groupby_concat handler hard hash help high_priority hosts hour_microsecond hour_minute hour_second if ignore ignore_server_ids import index index_statistics infile inner innodb inout insensitive insert_method install interval invoker isolation iterate key keys kill language last leading leave left level limit linear lines list load local localtime localtimestamp lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters match max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modifies modify mutex mysql_errno natural next no no_write_to_binlog offline offset one online open optimize option optionally out outer outfile pack_keys parser partition partitions password persistent phase plugin plugins prepare preserve prev primary privileges procedure processlist profile profiles purge query quick range read read_write reads real rebuild recover references regexp relaylog release remove rename reorganize repair repeatable replace require resignal restrict resume return returns revoke right rlike rollback rollup row row_format rtree savepoint schedule schema schema_name schemas second_microsecond security sensitive separator serializable server session share show signal slave slow smallint snapshot soft soname spatial specific sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result sqlexception sqlstate sqlwarning ssl start starting starts status std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace temporary terminated to trailing transaction trigger triggers truncate uncommitted undo uninstall unique unlock upgrade usage use use_frm user user_resources user_statistics using utc_date utc_time utc_timestamp value variables varying view views virtual warnings when while with work write xa xor year_month zerofill begin do then else loop repeat"),
+    builtin: set("bool boolean bit blob decimal double enum float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision date datetime year unsigned signed numeric"),
+    atoms: set("false true null unknown"),
+    operatorChars: /^[*+\-%<>!=&|^]/,
+    dateSQL: set("date time timestamp"),
+    support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired"),
+    hooks: {
+      "@":   hookVar,
+      "`":   hookIdentifier,
+      "\\":  hookClient
+    }
+  });
+
+  // the query language used by Apache Cassandra is called CQL, but this mime type
+  // is called Cassandra to avoid confusion with Contextual Query Language
+  CodeMirror.defineMIME("text/x-cassandra", {
+    name: "sql",
+    client: { },
+    keywords: set("use select from using consistency where limit first reversed first and in insert into values using consistency ttl update set delete truncate begin batch apply create keyspace with columnfamily primary key index on drop alter type add any one quorum all local_quorum each_quorum"),
+    builtin: set("ascii bigint blob boolean counter decimal double float int text timestamp uuid varchar varint"),
+    atoms: set("false true"),
+    operatorChars: /^[<>=]/,
+    dateSQL: { },
+    support: set("commentSlashSlash decimallessFloat"),
+    hooks: { }
+  });
+
+  // this is based on Peter Raganitsch's 'plsql' mode
+  CodeMirror.defineMIME("text/x-plsql", {
+    name:       "sql",
+    client:     set("appinfo arraysize autocommit autoprint autorecovery autotrace blockterminator break btitle cmdsep colsep compatibility compute concat copycommit copytypecheck define describe echo editfile embedded escape exec execute feedback flagger flush heading headsep instance linesize lno loboffset logsource long longchunksize markup native newpage numformat numwidth pagesize pause pno recsep recsepchar release repfooter repheader serveroutput shiftinout show showmode size spool sqlblanklines sqlcase sqlcode sqlcontinue sqlnumber sqlpluscompatibility sqlprefix sqlprompt sqlterminator suffix tab term termout time timing trimout trimspool ttitle underline verify version wrap"),
+    keywords:   set("abort accept access add all alter and any array arraylen as asc assert assign at attributes audit authorization avg base_table begin between binary_integer body boolean by case cast char char_base check close cluster clusters colauth column comment commit compress connect connected constant constraint crash create current currval cursor data_base database date dba deallocate debugoff debugon decimal declare default definition delay delete desc digits dispose distinct do drop else elsif enable end entry escape exception exception_init exchange exclusive exists exit external fast fetch file for force form from function generic goto grant group having identified if immediate in increment index indexes indicator initial initrans insert interface intersect into is key level library like limited local lock log logging long loop master maxextents maxtrans member minextents minus mislabel mode modify multiset new next no noaudit nocompress nologging noparallel not nowait number_base object of off offline on online only open option or order out package parallel partition pctfree pctincrease pctused pls_integer positive positiven pragma primary prior private privileges procedure public raise range raw read rebuild record ref references refresh release rename replace resource restrict return returning reverse revoke rollback row rowid rowlabel rownum rows run savepoint schema segment select separate session set share snapshot some space split sql start statement storage subtype successful synonym tabauth table tables tablespace task terminate then to trigger truncate type union unique unlimited unrecoverable unusable update use using validate value values variable view views when whenever where while with work"),
+    functions:  set("abs acos add_months ascii asin atan atan2 average bfilename ceil chartorowid chr concat convert cos cosh count decode deref dual dump dup_val_on_index empty error exp false floor found glb greatest hextoraw initcap instr instrb isopen last_day least lenght lenghtb ln lower lpad ltrim lub make_ref max min mod months_between new_time next_day nextval nls_charset_decl_len nls_charset_id nls_charset_name nls_initcap nls_lower nls_sort nls_upper nlssort no_data_found notfound null nvl others power rawtohex reftohex round rowcount rowidtochar rpad rtrim sign sin sinh soundex sqlcode sqlerrm sqrt stddev substr substrb sum sysdate tan tanh to_char to_date to_label to_multi_byte to_number to_single_byte translate true trunc uid upper user userenv variance vsize"),
+    builtin:    set("bfile blob character clob dec float int integer mlslabel natural naturaln nchar nclob number numeric nvarchar2 real rowtype signtype smallint string varchar varchar2"),
+    operatorChars: /^[*+\-%<>!=~]/,
+    dateSQL:    set("date time timestamp"),
+    support:    set("doubleQuote nCharCast zerolessFloat binaryNumber hexNumber")
+  });
+}());
+
+/*
+  How Properties of Mime Types are used by SQL Mode
+  =================================================
+
+  keywords:
+    A list of keywords you want to be highlighted.
+  functions:
+    A list of function names you want to be highlighted.
+  builtin:
+    A list of builtin types you want to be highlighted (if you want types to be of class "builtin" instead of "keyword").
+  operatorChars:
+    All characters that must be handled as operators.
+  client:
+    Commands parsed and executed by the client (not the server).
+  support:
+    A list of supported syntaxes which are not common, but are supported by more than 1 DBMS.
+    * ODBCdotTable: .tableName
+    * zerolessFloat: .1
+    * doubleQuote
+    * nCharCast: N'string'
+    * charsetCast: _utf8'string'
+    * commentHash: use # char for comments
+    * commentSlashSlash: use // for comments
+    * commentSpaceRequired: require a space after -- for comments
+  atoms:
+    Keywords that must be highlighted as atoms,. Some DBMS's support more atoms than others:
+    UNKNOWN, INFINITY, UNDERFLOW, NaN...
+  dateSQL:
+    Used for date/time SQL standard syntax, because not all DBMS's support same temporal types.
+*/
diff --git a/third-party/codemirror-3.15/mode/stex/index.html b/third-party/codemirror-3.15/mode/stex/index.html
new file mode 100644 (file)
index 0000000..2dafe69
--- /dev/null
@@ -0,0 +1,98 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: sTeX mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="stex.js"></script>
+    <style>.CodeMirror {background: #f8f8f8;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: sTeX mode</h1>
+     <form><textarea id="code" name="code">
+\begin{module}[id=bbt-size]
+\importmodule[balanced-binary-trees]{balanced-binary-trees}
+\importmodule[\KWARCslides{dmath/en/cardinality}]{cardinality}
+
+\begin{frame}
+  \frametitle{Size Lemma for Balanced Trees}
+  \begin{itemize}
+  \item
+    \begin{assertion}[id=size-lemma,type=lemma] 
+    Let $G=\tup{V,E}$ be a \termref[cd=binary-trees]{balanced binary tree} 
+    of \termref[cd=graph-depth,name=vertex-depth]{depth}$n>i$, then the set
+     $\defeq{\livar{V}i}{\setst{\inset{v}{V}}{\gdepth{v} = i}}$ of
+    \termref[cd=graphs-intro,name=node]{nodes} at 
+    \termref[cd=graph-depth,name=vertex-depth]{depth} $i$ has
+    \termref[cd=cardinality,name=cardinality]{cardinality} $\power2i$.
+   \end{assertion}
+  \item
+    \begin{sproof}[id=size-lemma-pf,proofend=,for=size-lemma]{via induction over the depth $i$.}
+      \begin{spfcases}{We have to consider two cases}
+        \begin{spfcase}{$i=0$}
+          \begin{spfstep}[display=flow]
+            then $\livar{V}i=\set{\livar{v}r}$, where $\livar{v}r$ is the root, so
+            $\eq{\card{\livar{V}0},\card{\set{\livar{v}r}},1,\power20}$.
+          \end{spfstep}
+        \end{spfcase}
+        \begin{spfcase}{$i>0$}
+          \begin{spfstep}[display=flow]
+           then $\livar{V}{i-1}$ contains $\power2{i-1}$ vertexes 
+           \begin{justification}[method=byIH](IH)\end{justification}
+          \end{spfstep}
+          \begin{spfstep}
+           By the \begin{justification}[method=byDef]definition of a binary
+              tree\end{justification}, each $\inset{v}{\livar{V}{i-1}}$ is a leaf or has
+            two children that are at depth $i$.
+          \end{spfstep}
+          \begin{spfstep}
+           As $G$ is \termref[cd=balanced-binary-trees,name=balanced-binary-tree]{balanced} and $\gdepth{G}=n>i$, $\livar{V}{i-1}$ cannot contain
+            leaves.
+          \end{spfstep}
+          \begin{spfstep}[type=conclusion]
+           Thus $\eq{\card{\livar{V}i},{\atimes[cdot]{2,\card{\livar{V}{i-1}}}},{\atimes[cdot]{2,\power2{i-1}}},\power2i}$.
+          \end{spfstep}
+        \end{spfcase}
+      \end{spfcases}
+    \end{sproof}
+  \item 
+    \begin{assertion}[id=fbbt,type=corollary]  
+      A fully balanced tree of depth $d$ has $\power2{d+1}-1$ nodes.
+    \end{assertion}
+  \item
+      \begin{sproof}[for=fbbt,id=fbbt-pf]{}
+        \begin{spfstep}
+          Let $\defeq{G}{\tup{V,E}}$ be a fully balanced tree
+        \end{spfstep}
+        \begin{spfstep}
+          Then $\card{V}=\Sumfromto{i}1d{\power2i}= \power2{d+1}-1$.
+        \end{spfstep}
+      \end{sproof}
+    \end{itemize}
+  \end{frame}
+\begin{note}
+  \begin{omtext}[type=conclusion,for=binary-tree]
+    This shows that balanced binary trees grow in breadth very quickly, a consequence of
+    this is that they are very shallow (and this compute very fast), which is the essence of
+    the next result.
+  \end{omtext}
+\end{note}
+\end{module}
+
+%%% Local Variables: 
+%%% mode: LaTeX
+%%% TeX-master: "all"
+%%% End: \end{document}
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-stex</code>.</p>
+
+    <p><strong>Parsing/Highlighting Tests:</strong> <a href="../../test/index.html#stex_*">normal</a>,  <a href="../../test/index.html#verbose,stex_*">verbose</a>.</p>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/stex/stex.js b/third-party/codemirror-3.15/mode/stex/stex.js
new file mode 100644 (file)
index 0000000..ca04c24
--- /dev/null
@@ -0,0 +1,246 @@
+/*
+ * Author: Constantin Jucovschi (c.jucovschi@jacobs-university.de)
+ * Licence: MIT
+ */
+
+CodeMirror.defineMode("stex", function() {
+    "use strict";
+
+    function pushCommand(state, command) {
+        state.cmdState.push(command);
+    }
+
+    function peekCommand(state) {
+        if (state.cmdState.length > 0) {
+            return state.cmdState[state.cmdState.length - 1];
+        } else {
+            return null;
+        }
+    }
+
+    function popCommand(state) {
+        var plug = state.cmdState.pop();
+        if (plug) {
+            plug.closeBracket();
+        }
+    }
+
+    // returns the non-default plugin closest to the end of the list
+    function getMostPowerful(state) {
+        var context = state.cmdState;
+        for (var i = context.length - 1; i >= 0; i--) {
+            var plug = context[i];
+            if (plug.name == "DEFAULT") {
+                continue;
+            }
+            return plug;
+        }
+        return { styleIdentifier: function() { return null; } };
+    }
+
+    function addPluginPattern(pluginName, cmdStyle, styles) {
+        return function () {
+            this.name = pluginName;
+            this.bracketNo = 0;
+            this.style = cmdStyle;
+            this.styles = styles;
+            this.argument = null;   // \begin and \end have arguments that follow. These are stored in the plugin
+
+            this.styleIdentifier = function() {
+                return this.styles[this.bracketNo - 1] || null;
+            };
+            this.openBracket = function() {
+                this.bracketNo++;
+                return "bracket";
+            };
+            this.closeBracket = function() {};
+        };
+    }
+
+    var plugins = {};
+
+    plugins["importmodule"] = addPluginPattern("importmodule", "tag", ["string", "builtin"]);
+    plugins["documentclass"] = addPluginPattern("documentclass", "tag", ["", "atom"]);
+    plugins["usepackage"] = addPluginPattern("usepackage", "tag", ["atom"]);
+    plugins["begin"] = addPluginPattern("begin", "tag", ["atom"]);
+    plugins["end"] = addPluginPattern("end", "tag", ["atom"]);
+
+    plugins["DEFAULT"] = function () {
+        this.name = "DEFAULT";
+        this.style = "tag";
+
+        this.styleIdentifier = this.openBracket = this.closeBracket = function() {};
+    };
+
+    function setState(state, f) {
+        state.f = f;
+    }
+
+    // called when in a normal (no environment) context
+    function normal(source, state) {
+        var plug;
+        // Do we look like '\command' ?  If so, attempt to apply the plugin 'command'
+        if (source.match(/^\\[a-zA-Z@]+/)) {
+            var cmdName = source.current().slice(1);
+            plug = plugins[cmdName] || plugins["DEFAULT"];
+            plug = new plug();
+            pushCommand(state, plug);
+            setState(state, beginParams);
+            return plug.style;
+        }
+
+        // escape characters
+        if (source.match(/^\\[$&%#{}_]/)) {
+          return "tag";
+        }
+
+        // white space control characters
+        if (source.match(/^\\[,;!\/\\]/)) {
+          return "tag";
+        }
+
+        // find if we're starting various math modes
+        if (source.match("\\[")) {
+            setState(state, function(source, state){ return inMathMode(source, state, "\\]"); });
+            return "keyword";
+        }
+        if (source.match("$$")) {
+            setState(state, function(source, state){ return inMathMode(source, state, "$$"); });
+            return "keyword";
+        }
+        if (source.match("$")) {
+            setState(state, function(source, state){ return inMathMode(source, state, "$"); });
+            return "keyword";
+        }
+
+        var ch = source.next();
+        if (ch == "%") {
+            // special case: % at end of its own line; stay in same state
+            if (!source.eol()) {
+              setState(state, inCComment);
+            }
+            return "comment";
+        }
+        else if (ch == '}' || ch == ']') {
+            plug = peekCommand(state);
+            if (plug) {
+                plug.closeBracket(ch);
+                setState(state, beginParams);
+            } else {
+                return "error";
+            }
+            return "bracket";
+        } else if (ch == '{' || ch == '[') {
+            plug = plugins["DEFAULT"];
+            plug = new plug();
+            pushCommand(state, plug);
+            return "bracket";
+        }
+        else if (/\d/.test(ch)) {
+            source.eatWhile(/[\w.%]/);
+            return "atom";
+        }
+        else {
+            source.eatWhile(/[\w\-_]/);
+            plug = getMostPowerful(state);
+            if (plug.name == 'begin') {
+                plug.argument = source.current();
+            }
+            return plug.styleIdentifier();
+        }
+    }
+
+    function inCComment(source, state) {
+        source.skipToEnd();
+        setState(state, normal);
+        return "comment";
+    }
+
+    function inMathMode(source, state, endModeSeq) {
+        if (source.eatSpace()) {
+            return null;
+        }
+        if (source.match(endModeSeq)) {
+            setState(state, normal);
+            return "keyword";
+        }
+        if (source.match(/^\\[a-zA-Z@]+/)) {
+            return "tag";
+        }
+        if (source.match(/^[a-zA-Z]+/)) {
+            return "variable-2";
+        }
+        // escape characters
+        if (source.match(/^\\[$&%#{}_]/)) {
+          return "tag";
+        }
+        // white space control characters
+        if (source.match(/^\\[,;!\/]/)) {
+          return "tag";
+        }
+        // special math-mode characters
+        if (source.match(/^[\^_&]/)) {
+          return "tag";
+        }
+        // non-special characters
+        if (source.match(/^[+\-<>|=,\/@!*:;'"`~#?]/)) {
+            return null;
+        }
+        if (source.match(/^(\d+\.\d*|\d*\.\d+|\d+)/)) {
+          return "number";
+        }
+        var ch = source.next();
+        if (ch == "{" || ch == "}" || ch == "[" || ch == "]" || ch == "(" || ch == ")") {
+            return "bracket";
+        }
+
+        // eat comments here, because inCComment returns us to normal state!
+        if (ch == "%") {
+            if (!source.eol()) {
+                source.skipToEnd();
+            }
+            return "comment";
+        }
+        return "error";
+    }
+
+    function beginParams(source, state) {
+        var ch = source.peek(), lastPlug;
+        if (ch == '{' || ch == '[') {
+            lastPlug = peekCommand(state);
+            lastPlug.openBracket(ch);
+            source.eat(ch);
+            setState(state, normal);
+            return "bracket";
+        }
+        if (/[ \t\r]/.test(ch)) {
+            source.eat(ch);
+            return null;
+        }
+        setState(state, normal);
+        popCommand(state);
+
+        return normal(source, state);
+    }
+
+    return {
+        startState: function() {
+            return {
+                cmdState: [],
+                f: normal
+            };
+        },
+        copyState: function(s) {
+            return {
+                cmdState: s.cmdState.slice(),
+                f: s.f
+            };
+        },
+        token: function(stream, state) {
+            return state.f(stream, state);
+        }
+    };
+});
+
+CodeMirror.defineMIME("text/x-stex", "stex");
+CodeMirror.defineMIME("text/x-latex", "stex");
diff --git a/third-party/codemirror-3.15/mode/stex/test.js b/third-party/codemirror-3.15/mode/stex/test.js
new file mode 100644 (file)
index 0000000..ab629e8
--- /dev/null
@@ -0,0 +1,120 @@
+(function() {
+  var mode = CodeMirror.getMode({tabSize: 4}, "stex");
+  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }
+
+  MT("word",
+     "foo");
+
+  MT("twoWords",
+     "foo bar");
+
+  MT("beginEndDocument",
+     "[tag \\begin][bracket {][atom document][bracket }]",
+     "[tag \\end][bracket {][atom document][bracket }]");
+
+  MT("beginEndEquation",
+     "[tag \\begin][bracket {][atom equation][bracket }]",
+     "  E=mc^2",
+     "[tag \\end][bracket {][atom equation][bracket }]");
+
+  MT("beginModule",
+     "[tag \\begin][bracket {][atom module][bracket }[[]]]");
+
+  MT("beginModuleId",
+     "[tag \\begin][bracket {][atom module][bracket }[[]id=bbt-size[bracket ]]]");
+
+  MT("importModule",
+     "[tag \\importmodule][bracket [[][string b-b-t][bracket ]]{][builtin b-b-t][bracket }]");
+
+  MT("importModulePath",
+     "[tag \\importmodule][bracket [[][tag \\KWARCslides][bracket {][string dmath/en/cardinality][bracket }]]{][builtin card][bracket }]");
+
+  MT("psForPDF",
+     "[tag \\PSforPDF][bracket [[][atom 1][bracket ]]{]#1[bracket }]");
+
+  MT("comment",
+     "[comment % foo]");
+
+  MT("tagComment",
+     "[tag \\item][comment % bar]");
+
+  MT("commentTag",
+     " [comment % \\item]");
+
+  MT("commentLineBreak",
+     "[comment %]",
+     "foo");
+
+  MT("tagErrorCurly",
+     "[tag \\begin][error }][bracket {]");
+
+  MT("tagErrorSquare",
+     "[tag \\item][error ]]][bracket {]");
+
+  MT("commentCurly",
+     "[comment % }]");
+
+  MT("tagHash",
+     "the [tag \\#] key");
+
+  MT("tagNumber",
+     "a [tag \\$][atom 5] stetson");
+
+  MT("tagPercent",
+     "[atom 100][tag \\%] beef");
+
+  MT("tagAmpersand",
+     "L [tag \\&] N");
+
+  MT("tagUnderscore",
+     "foo[tag \\_]bar");
+
+  MT("tagBracketOpen",
+     "[tag \\emph][bracket {][tag \\{][bracket }]");
+
+  MT("tagBracketClose",
+     "[tag \\emph][bracket {][tag \\}][bracket }]");
+
+  MT("tagLetterNumber",
+     "section [tag \\S][atom 1]");
+
+  MT("textTagNumber",
+     "para [tag \\P][atom 2]");
+
+  MT("thinspace",
+     "x[tag \\,]y");
+
+  MT("thickspace",
+     "x[tag \\;]y");
+
+  MT("negativeThinspace",
+     "x[tag \\!]y");
+
+  MT("periodNotSentence",
+     "J.\\ L.\\ is");
+
+  MT("periodSentence",
+     "X[tag \\@]. The");
+
+  MT("italicCorrection",
+     "[bracket {][tag \\em] If[tag \\/][bracket }] I");
+
+  MT("tagBracket",
+     "[tag \\newcommand][bracket {][tag \\pop][bracket }]");
+
+  MT("inlineMathTagFollowedByNumber",
+     "[keyword $][tag \\pi][number 2][keyword $]");
+
+  MT("inlineMath",
+     "[keyword $][number 3][variable-2 x][tag ^][number 2.45]-[tag \\sqrt][bracket {][tag \\$\\alpha][bracket }] = [number 2][keyword $] other text");
+
+  MT("displayMath",
+     "More [keyword $$]\t[variable-2 S][tag ^][variable-2 n][tag \\sum] [variable-2 i][keyword $$] other text");
+
+  MT("mathWithComment",
+     "[keyword $][variable-2 x] [comment % $]",
+     "[variable-2 y][keyword $] other text");
+
+  MT("lineBreakArgument",
+    "[tag \\\\][bracket [[][atom 1cm][bracket ]]]");
+})();
diff --git a/third-party/codemirror-3.15/mode/tcl/index.html b/third-party/codemirror-3.15/mode/tcl/index.html
new file mode 100644 (file)
index 0000000..e2e42a0
--- /dev/null
@@ -0,0 +1,129 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Tcl mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="tcl.js"></script>
+    <link rel="stylesheet" href="../../theme/night.css">
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Tcl mode</h1>
+    <form><textarea id="code" name="code">
+##############################################################################################
+##  ##     whois.tcl for eggdrop by Ford_Lawnmower irc.geekshed.net #Script-Help        ##  ##
+##############################################################################################
+## To use this script you must set channel flag +whois (ie .chanset #chan +whois)           ##
+##############################################################################################
+##      ____                __                 ###########################################  ##
+##     / __/___ _ ___ _ ___/ /____ ___   ___   ###########################################  ##
+##    / _/ / _ `// _ `// _  // __// _ \ / _ \  ###########################################  ##
+##   /___/ \_, / \_, / \_,_//_/   \___// .__/  ###########################################  ##
+##        /___/ /___/                 /_/      ###########################################  ##
+##                                             ###########################################  ##
+##############################################################################################
+##  ##                             Start Setup.                                         ##  ##
+##############################################################################################
+namespace eval whois {
+## change cmdchar to the trigger you want to use                                        ##  ##
+  variable cmdchar "!"
+## change command to the word trigger you would like to use.                            ##  ##
+## Keep in mind, This will also change the .chanset +/-command                          ##  ##
+  variable command "whois"
+## change textf to the colors you want for the text.                                    ##  ##
+  variable textf "\017\00304"
+## change tagf to the colors you want for tags:                                         ##  ##
+  variable tagf "\017\002"
+## Change logo to the logo you want at the start of the line.                           ##  ##
+  variable logo "\017\00304\002\[\00306W\003hois\00304\]\017"
+## Change lineout to the results you want. Valid results are channel users modes topic  ##  ##
+  variable lineout "channel users modes topic"
+##############################################################################################
+##  ##                           End Setup.                                              ## ##
+##############################################################################################
+  variable channel ""
+  setudef flag $whois::command
+  bind pub -|- [string trimleft $whois::cmdchar]${whois::command} whois::list
+  bind raw -|- "311" whois::311
+  bind raw -|- "312" whois::312
+  bind raw -|- "319" whois::319
+  bind raw -|- "317" whois::317
+  bind raw -|- "313" whois::multi
+  bind raw -|- "310" whois::multi
+  bind raw -|- "335" whois::multi
+  bind raw -|- "301" whois::301
+  bind raw -|- "671" whois::multi
+  bind raw -|- "320" whois::multi
+  bind raw -|- "401" whois::multi
+  bind raw -|- "318" whois::318
+  bind raw -|- "307" whois::307
+}
+proc whois::311 {from key text} {
+  if {[regexp -- {^[^\s]+\s(.+?)\s(.+?)\s(.+?)\s\*\s\:(.+)$} $text wholematch nick ident host realname]} {
+    putserv "PRIVMSG $whois::channel :${whois::logo} ${whois::tagf}Host:${whois::textf} \
+       $nick \(${ident}@${host}\) ${whois::tagf}Realname:${whois::textf} $realname"
+  }
+}
+proc whois::multi {from key text} {
+  if {[regexp {\:(.*)$} $text match $key]} {
+    putserv "PRIVMSG $whois::channel :${whois::logo} ${whois::tagf}Note:${whois::textf} [subst $$key]"
+       return 1
+  }
+}
+proc whois::312 {from key text} {
+  regexp {([^\s]+)\s\:} $text match server
+  putserv "PRIVMSG $whois::channel :${whois::logo} ${whois::tagf}Server:${whois::textf} $server"
+}
+proc whois::319 {from key text} {
+  if {[regexp {.+\:(.+)$} $text match channels]} {
+    putserv "PRIVMSG $whois::channel :${whois::logo} ${whois::tagf}Channels:${whois::textf} $channels"
+  }
+}
+proc whois::317 {from key text} {
+  if {[regexp -- {.*\s(\d+)\s(\d+)\s\:} $text wholematch idle signon]} {
+    putserv "PRIVMSG $whois::channel :${whois::logo} ${whois::tagf}Connected:${whois::textf} \
+       [ctime $signon] ${whois::tagf}Idle:${whois::textf} [duration $idle]"
+  }
+}
+proc whois::301 {from key text} {
+  if {[regexp {^.+\s[^\s]+\s\:(.*)$} $text match awaymsg]} {
+    putserv "PRIVMSG $whois::channel :${whois::logo} ${whois::tagf}Away:${whois::textf} $awaymsg"
+  }
+}
+proc whois::318 {from key text} {
+  namespace eval whois {
+       variable channel ""
+  }
+  variable whois::channel ""
+}
+proc whois::307 {from key text} {
+  putserv "PRIVMSG $whois::channel :${whois::logo} ${whois::tagf}Services:${whois::textf} Registered Nick"
+}
+proc whois::list {nick host hand chan text} {
+  if {[lsearch -exact [channel info $chan] "+${whois::command}"] != -1} {
+    namespace eval whois {
+         variable channel ""
+       }
+    variable whois::channel $chan
+    putserv "WHOIS $text"
+  }
+}
+putlog "\002*Loaded* \017\00304\002\[\00306W\003hois\00304\]\017 \002by \
+Ford_Lawnmower irc.GeekShed.net #Script-Help"
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        tabMode: "indent",
+               theme: "night",
+        lineNumbers: true,
+        indentUnit: 2,
+        mode: "text/x-tcl"
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-tcl</code>.</p>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/tcl/tcl.js b/third-party/codemirror-3.15/mode/tcl/tcl.js
new file mode 100644 (file)
index 0000000..ed2c697
--- /dev/null
@@ -0,0 +1,131 @@
+//tcl mode by Ford_Lawnmower :: Based on Velocity mode by Steve O'Hara
+CodeMirror.defineMode("tcl", function() {
+  function parseWords(str) {
+    var obj = {}, words = str.split(" ");
+    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
+    return obj;
+  }
+  var keywords = parseWords("Tcl safe after append array auto_execok auto_import auto_load " +
+        "auto_mkindex auto_mkindex_old auto_qualify auto_reset bgerror " +
+        "binary break catch cd close concat continue dde eof encoding error " +
+        "eval exec exit expr fblocked fconfigure fcopy file fileevent filename " +
+        "filename flush for foreach format gets glob global history http if " +
+        "incr info interp join lappend lindex linsert list llength load lrange " +
+        "lreplace lsearch lset lsort memory msgcat namespace open package parray " +
+        "pid pkg::create pkg_mkIndex proc puts pwd re_syntax read regex regexp " +
+        "registry regsub rename resource return scan seek set socket source split " +
+        "string subst switch tcl_endOfWord tcl_findLibrary tcl_startOfNextWord " +
+        "tcl_wordBreakAfter tcl_startOfPreviousWord tcl_wordBreakBefore tcltest " +
+        "tclvars tell time trace unknown unset update uplevel upvar variable " +
+    "vwait");
+    var functions = parseWords("if elseif else and not or eq ne in ni for foreach while switch");
+    var isOperatorChar = /[+\-*&%=<>!?^\/\|]/;
+    function chain(stream, state, f) {
+      state.tokenize = f;
+      return f(stream, state);
+    }
+    function tokenBase(stream, state) {
+      var beforeParams = state.beforeParams;
+      state.beforeParams = false;
+      var ch = stream.next();
+      if ((ch == '"' || ch == "'") && state.inParams)
+        return chain(stream, state, tokenString(ch));
+      else if (/[\[\]{}\(\),;\.]/.test(ch)) {
+        if (ch == "(" && beforeParams) state.inParams = true;
+        else if (ch == ")") state.inParams = false;
+          return null;
+      }
+      else if (/\d/.test(ch)) {
+        stream.eatWhile(/[\w\.]/);
+        return "number";
+      }
+      else if (ch == "#" && stream.eat("*")) {
+        return chain(stream, state, tokenComment);
+      }
+      else if (ch == "#" && stream.match(/ *\[ *\[/)) {
+        return chain(stream, state, tokenUnparsed);
+      }
+      else if (ch == "#" && stream.eat("#")) {
+        stream.skipToEnd();
+        return "comment";
+      }
+      else if (ch == '"') {
+        stream.skipTo(/"/);
+        return "comment";
+      }
+      else if (ch == "$") {
+        stream.eatWhile(/[$_a-z0-9A-Z\.{:]/);
+        stream.eatWhile(/}/);
+        state.beforeParams = true;
+        return "builtin";
+      }
+      else if (isOperatorChar.test(ch)) {
+        stream.eatWhile(isOperatorChar);
+        return "comment";
+      }
+      else {
+        stream.eatWhile(/[\w\$_{}]/);
+        var word = stream.current().toLowerCase();
+        if (keywords && keywords.propertyIsEnumerable(word))
+          return "keyword";
+        if (functions && functions.propertyIsEnumerable(word)) {
+          state.beforeParams = true;
+          return "keyword";
+        }
+        return null;
+      }
+    }
+    function tokenString(quote) {
+      return function(stream, state) {
+      var escaped = false, next, end = false;
+      while ((next = stream.next()) != null) {
+        if (next == quote && !escaped) {
+          end = true;
+          break;
+        }
+        escaped = !escaped && next == "\\";
+      }
+      if (end) state.tokenize = tokenBase;
+        return "string";
+      };
+    }
+    function tokenComment(stream, state) {
+      var maybeEnd = false, ch;
+      while (ch = stream.next()) {
+        if (ch == "#" && maybeEnd) {
+          state.tokenize = tokenBase;
+          break;
+        }
+        maybeEnd = (ch == "*");
+      }
+      return "comment";
+    }
+    function tokenUnparsed(stream, state) {
+      var maybeEnd = 0, ch;
+      while (ch = stream.next()) {
+        if (ch == "#" && maybeEnd == 2) {
+          state.tokenize = tokenBase;
+          break;
+        }
+        if (ch == "]")
+          maybeEnd++;
+        else if (ch != " ")
+          maybeEnd = 0;
+      }
+      return "meta";
+    }
+    return {
+      startState: function() {
+        return {
+          tokenize: tokenBase,
+          beforeParams: false,
+          inParams: false
+        };
+      },
+      token: function(stream, state) {
+        if (stream.eatSpace()) return null;
+        return state.tokenize(stream, state);
+      }
+    };
+});
+CodeMirror.defineMIME("text/x-tcl", "tcl");
diff --git a/third-party/codemirror-3.15/mode/tiddlywiki/index.html b/third-party/codemirror-3.15/mode/tiddlywiki/index.html
new file mode 100644 (file)
index 0000000..848f33a
--- /dev/null
@@ -0,0 +1,142 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: TiddlyWiki mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="../../addon/edit/matchbrackets.js"></script>
+    <script src="tiddlywiki.js"></script>
+    <link rel="stylesheet" href="tiddlywiki.css">
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: TiddlyWiki mode</h1>
+
+<div><textarea id="code" name="code">
+!TiddlyWiki Formatting
+* Rendered versions can be found at: http://www.tiddlywiki.com/#Reference
+
+|!Option            | !Syntax            |
+|bold font          | ''bold''           |
+|italic type        | //italic//         |
+|underlined text    | __underlined__     |
+|strikethrough text | --strikethrough--  |
+|superscript text   | super^^script^^    |
+|subscript text     | sub~~script~~      |
+|highlighted text   | @@highlighted@@    |
+|preformatted text  | {{{preformatted}}} |
+
+!Block Elements
+<<<
+!Heading 1
+
+!!Heading 2
+
+!!!Heading 3
+
+!!!!Heading 4
+
+!!!!!Heading 5
+<<<
+
+!!Lists
+<<<
+* unordered list, level 1
+** unordered list, level 2
+*** unordered list, level 3
+
+# ordered list, level 1
+## ordered list, level 2
+### unordered list, level 3
+
+; definition list, term
+: definition list, description
+<<<
+
+!!Blockquotes
+<<<
+> blockquote, level 1
+>> blockquote, level 2
+>>> blockquote, level 3
+
+> blockquote
+<<<
+
+!!Preformatted Text
+<<<
+{{{
+preformatted (e.g. code)
+}}}
+<<<
+
+!!Code Sections
+<<<
+{{{
+Text style code
+}}}
+
+//{{{
+JS styled code. TiddlyWiki mixed mode should support highlighter switching in the future.
+//}}}
+
+<!--{{{-->
+XML styled code. TiddlyWiki mixed mode should support highlighter switching in the future.
+<!--}}}-->
+<<<
+
+!!Tables
+<<<
+|CssClass|k
+|!heading column 1|!heading column 2|
+|row 1, column 1|row 1, column 2|
+|row 2, column 1|row 2, column 2|
+|>|COLSPAN|
+|ROWSPAN| ... |
+|~| ... |
+|CssProperty:value;...| ... |
+|caption|c
+
+''Annotation:''
+* The {{{>}}} marker creates a "colspan", causing the current cell to merge with the one to the right.
+* The {{{~}}} marker creates a "rowspan", causing the current cell to merge with the one above.
+<<<
+!!Images /% TODO %/
+cf. [[TiddlyWiki.com|http://www.tiddlywiki.com/#EmbeddedImages]]
+
+!Hyperlinks
+* [[WikiWords|WikiWord]] are automatically transformed to hyperlinks to the respective tiddler
+** the automatic transformation can be suppressed by preceding the respective WikiWord with a tilde ({{{~}}}): {{{~WikiWord}}}
+* [[PrettyLinks]] are enclosed in square brackets and contain the desired tiddler name: {{{[[tiddler name]]}}}
+** optionally, a custom title or description can be added, separated by a pipe character ({{{|}}}): {{{[[title|target]]}}}<br>'''N.B.:''' In this case, the target can also be any website (i.e. URL).
+
+!Custom Styling
+* {{{@@CssProperty:value;CssProperty:value;...@@}}}<br>''N.B.:'' CSS color definitions should use lowercase letters to prevent the inadvertent creation of WikiWords.
+* <html><code>{{customCssClass{...}}}</code></html>
+* raw HTML can be inserted by enclosing the respective code in HTML tags: {{{<html> ... </html>}}}
+
+!Special Markers
+* {{{<br>}}} forces a manual line break
+* {{{----}}} creates a horizontal ruler
+* [[HTML entities|http://www.tiddlywiki.com/#HtmlEntities]]
+* [[HTML entities local|HtmlEntities]]
+* {{{<<macroName>>}}} calls the respective [[macro|Macros]]
+* To hide text within a tiddler so that it is not displayed, it can be wrapped in {{{/%}}} and {{{%/}}}.<br/>This can be a useful trick for hiding drafts or annotating complex markup.
+* To prevent wiki markup from taking effect for a particular section, that section can be enclosed in three double quotes: e.g. {{{"""WikiWord"""}}}.
+</textarea></div>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        mode: 'tiddlywiki',      
+        lineNumbers: true,
+        enterMode: 'keep',
+        matchBrackets: true
+      });
+    </script>
+
+    <p>TiddlyWiki mode supports a single configuration.</p>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-tiddlywiki</code>.</p>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/tiddlywiki/tiddlywiki.css b/third-party/codemirror-3.15/mode/tiddlywiki/tiddlywiki.css
new file mode 100644 (file)
index 0000000..9a69b63
--- /dev/null
@@ -0,0 +1,14 @@
+span.cm-underlined {
+  text-decoration: underline;
+}
+span.cm-strikethrough {
+  text-decoration: line-through;
+}
+span.cm-brace {
+  color: #170;
+  font-weight: bold;
+}
+span.cm-table {
+  color: blue;
+  font-weight: bold;
+}
diff --git a/third-party/codemirror-3.15/mode/tiddlywiki/tiddlywiki.js b/third-party/codemirror-3.15/mode/tiddlywiki/tiddlywiki.js
new file mode 100644 (file)
index 0000000..24a2478
--- /dev/null
@@ -0,0 +1,353 @@
+/***
+    |''Name''|tiddlywiki.js|
+    |''Description''|Enables TiddlyWikiy syntax highlighting using CodeMirror|
+    |''Author''|PMario|
+    |''Version''|0.1.7|
+    |''Status''|''stable''|
+    |''Source''|[[GitHub|https://github.com/pmario/CodeMirror2/blob/tw-syntax/mode/tiddlywiki]]|
+    |''Documentation''|http://codemirror.tiddlyspace.com/|
+    |''License''|[[MIT License|http://www.opensource.org/licenses/mit-license.php]]|
+    |''CoreVersion''|2.5.0|
+    |''Requires''|codemirror.js|
+    |''Keywords''|syntax highlighting color code mirror codemirror|
+    ! Info
+    CoreVersion parameter is needed for TiddlyWiki only!
+***/
+//{{{
+CodeMirror.defineMode("tiddlywiki", function () {
+  // Tokenizer
+  var textwords = {};
+
+  var keywords = function () {
+    function kw(type) {
+      return { type: type, style: "macro"};
+    }
+    return {
+      "allTags": kw('allTags'), "closeAll": kw('closeAll'), "list": kw('list'),
+      "newJournal": kw('newJournal'), "newTiddler": kw('newTiddler'),
+      "permaview": kw('permaview'), "saveChanges": kw('saveChanges'),
+      "search": kw('search'), "slider": kw('slider'),   "tabs": kw('tabs'),
+      "tag": kw('tag'), "tagging": kw('tagging'),       "tags": kw('tags'),
+      "tiddler": kw('tiddler'), "timeline": kw('timeline'),
+      "today": kw('today'), "version": kw('version'),   "option": kw('option'),
+
+      "with": kw('with'),
+      "filter": kw('filter')
+    };
+  }();
+
+  var isSpaceName = /[\w_\-]/i,
+  reHR = /^\-\-\-\-+$/,                                 // <hr>
+  reWikiCommentStart = /^\/\*\*\*$/,            // /***
+  reWikiCommentStop = /^\*\*\*\/$/,             // ***/
+  reBlockQuote = /^<<<$/,
+
+  reJsCodeStart = /^\/\/\{\{\{$/,                       // //{{{ js block start
+  reJsCodeStop = /^\/\/\}\}\}$/,                        // //}}} js stop
+  reXmlCodeStart = /^<!--\{\{\{-->$/,           // xml block start
+  reXmlCodeStop = /^<!--\}\}\}-->$/,            // xml stop
+
+  reCodeBlockStart = /^\{\{\{$/,                        // {{{ TW text div block start
+  reCodeBlockStop = /^\}\}\}$/,                 // }}} TW text stop
+
+  reUntilCodeStop = /.*?\}\}\}/;
+
+  function chain(stream, state, f) {
+    state.tokenize = f;
+    return f(stream, state);
+  }
+
+  // Used as scratch variables to communicate multiple values without
+  // consing up tons of objects.
+  var type, content;
+
+  function ret(tp, style, cont) {
+    type = tp;
+    content = cont;
+    return style;
+  }
+
+  function jsTokenBase(stream, state) {
+    var sol = stream.sol(), ch;
+
+    state.block = false;        // indicates the start of a code block.
+
+    ch = stream.peek();         // don't eat, to make matching simpler
+
+    // check start of  blocks
+    if (sol && /[<\/\*{}\-]/.test(ch)) {
+      if (stream.match(reCodeBlockStart)) {
+        state.block = true;
+        return chain(stream, state, twTokenCode);
+      }
+      if (stream.match(reBlockQuote)) {
+        return ret('quote', 'quote');
+      }
+      if (stream.match(reWikiCommentStart) || stream.match(reWikiCommentStop)) {
+        return ret('code', 'comment');
+      }
+      if (stream.match(reJsCodeStart) || stream.match(reJsCodeStop) || stream.match(reXmlCodeStart) || stream.match(reXmlCodeStop)) {
+        return ret('code', 'comment');
+      }
+      if (stream.match(reHR)) {
+        return ret('hr', 'hr');
+      }
+    } // sol
+    ch = stream.next();
+
+    if (sol && /[\/\*!#;:>|]/.test(ch)) {
+      if (ch == "!") { // tw header
+        stream.skipToEnd();
+        return ret("header", "header");
+      }
+      if (ch == "*") { // tw list
+        stream.eatWhile('*');
+        return ret("list", "comment");
+      }
+      if (ch == "#") { // tw numbered list
+        stream.eatWhile('#');
+        return ret("list", "comment");
+      }
+      if (ch == ";") { // definition list, term
+        stream.eatWhile(';');
+        return ret("list", "comment");
+      }
+      if (ch == ":") { // definition list, description
+        stream.eatWhile(':');
+        return ret("list", "comment");
+      }
+      if (ch == ">") { // single line quote
+        stream.eatWhile(">");
+        return ret("quote", "quote");
+      }
+      if (ch == '|') {
+        return ret('table', 'header');
+      }
+    }
+
+    if (ch == '{' && stream.match(/\{\{/)) {
+      return chain(stream, state, twTokenCode);
+    }
+
+    // rudimentary html:// file:// link matching. TW knows much more ...
+    if (/[hf]/i.test(ch)) {
+      if (/[ti]/i.test(stream.peek()) && stream.match(/\b(ttps?|tp|ile):\/\/[\-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i)) {
+        return ret("link", "link");
+      }
+    }
+    // just a little string indicator, don't want to have the whole string covered
+    if (ch == '"') {
+      return ret('string', 'string');
+    }
+    if (ch == '~') {    // _no_ CamelCase indicator should be bold
+      return ret('text', 'brace');
+    }
+    if (/[\[\]]/.test(ch)) { // check for [[..]]
+      if (stream.peek() == ch) {
+        stream.next();
+        return ret('brace', 'brace');
+      }
+    }
+    if (ch == "@") {    // check for space link. TODO fix @@...@@ highlighting
+      stream.eatWhile(isSpaceName);
+      return ret("link", "link");
+    }
+    if (/\d/.test(ch)) {        // numbers
+      stream.eatWhile(/\d/);
+      return ret("number", "number");
+    }
+    if (ch == "/") { // tw invisible comment
+      if (stream.eat("%")) {
+        return chain(stream, state, twTokenComment);
+      }
+      else if (stream.eat("/")) { //
+        return chain(stream, state, twTokenEm);
+      }
+    }
+    if (ch == "_") { // tw underline
+      if (stream.eat("_")) {
+        return chain(stream, state, twTokenUnderline);
+      }
+    }
+    // strikethrough and mdash handling
+    if (ch == "-") {
+      if (stream.eat("-")) {
+        // if strikethrough looks ugly, change CSS.
+        if (stream.peek() != ' ')
+          return chain(stream, state, twTokenStrike);
+        // mdash
+        if (stream.peek() == ' ')
+          return ret('text', 'brace');
+      }
+    }
+    if (ch == "'") { // tw bold
+      if (stream.eat("'")) {
+        return chain(stream, state, twTokenStrong);
+      }
+    }
+    if (ch == "<") { // tw macro
+      if (stream.eat("<")) {
+        return chain(stream, state, twTokenMacro);
+      }
+    }
+    else {
+      return ret(ch);
+    }
+
+    // core macro handling
+    stream.eatWhile(/[\w\$_]/);
+    var word = stream.current(),
+    known = textwords.propertyIsEnumerable(word) && textwords[word];
+
+    return known ? ret(known.type, known.style, word) : ret("text", null, word);
+
+  } // jsTokenBase()
+
+  // tw invisible comment
+  function twTokenComment(stream, state) {
+    var maybeEnd = false,
+    ch;
+    while (ch = stream.next()) {
+      if (ch == "/" && maybeEnd) {
+        state.tokenize = jsTokenBase;
+        break;
+      }
+      maybeEnd = (ch == "%");
+    }
+    return ret("comment", "comment");
+  }
+
+  // tw strong / bold
+  function twTokenStrong(stream, state) {
+    var maybeEnd = false,
+    ch;
+    while (ch = stream.next()) {
+      if (ch == "'" && maybeEnd) {
+        state.tokenize = jsTokenBase;
+        break;
+      }
+      maybeEnd = (ch == "'");
+    }
+    return ret("text", "strong");
+  }
+
+  // tw code
+  function twTokenCode(stream, state) {
+    var ch, sb = state.block;
+
+    if (sb && stream.current()) {
+      return ret("code", "comment");
+    }
+
+    if (!sb && stream.match(reUntilCodeStop)) {
+      state.tokenize = jsTokenBase;
+      return ret("code", "comment");
+    }
+
+    if (sb && stream.sol() && stream.match(reCodeBlockStop)) {
+      state.tokenize = jsTokenBase;
+      return ret("code", "comment");
+    }
+
+    ch = stream.next();
+    return (sb) ? ret("code", "comment") : ret("code", "comment");
+  }
+
+  // tw em / italic
+  function twTokenEm(stream, state) {
+    var maybeEnd = false,
+    ch;
+    while (ch = stream.next()) {
+      if (ch == "/" && maybeEnd) {
+        state.tokenize = jsTokenBase;
+        break;
+      }
+      maybeEnd = (ch == "/");
+    }
+    return ret("text", "em");
+  }
+
+  // tw underlined text
+  function twTokenUnderline(stream, state) {
+    var maybeEnd = false,
+    ch;
+    while (ch = stream.next()) {
+      if (ch == "_" && maybeEnd) {
+        state.tokenize = jsTokenBase;
+        break;
+      }
+      maybeEnd = (ch == "_");
+    }
+    return ret("text", "underlined");
+  }
+
+  // tw strike through text looks ugly
+  // change CSS if needed
+  function twTokenStrike(stream, state) {
+    var maybeEnd = false, ch;
+
+    while (ch = stream.next()) {
+      if (ch == "-" && maybeEnd) {
+        state.tokenize = jsTokenBase;
+        break;
+      }
+      maybeEnd = (ch == "-");
+    }
+    return ret("text", "strikethrough");
+  }
+
+  // macro
+  function twTokenMacro(stream, state) {
+    var ch, word, known;
+
+    if (stream.current() == '<<') {
+      return ret('brace', 'macro');
+    }
+
+    ch = stream.next();
+    if (!ch) {
+      state.tokenize = jsTokenBase;
+      return ret(ch);
+    }
+    if (ch == ">") {
+      if (stream.peek() == '>') {
+        stream.next();
+        state.tokenize = jsTokenBase;
+        return ret("brace", "macro");
+      }
+    }
+
+    stream.eatWhile(/[\w\$_]/);
+    word = stream.current();
+    known = keywords.propertyIsEnumerable(word) && keywords[word];
+
+    if (known) {
+      return ret(known.type, known.style, word);
+    }
+    else {
+      return ret("macro", null, word);
+    }
+  }
+
+  // Interface
+  return {
+    startState: function () {
+      return {
+        tokenize: jsTokenBase,
+        indented: 0,
+        level: 0
+      };
+    },
+
+    token: function (stream, state) {
+      if (stream.eatSpace()) return null;
+      var style = state.tokenize(stream, state);
+      return style;
+    },
+
+    electricChars: ""
+  };
+});
+
+CodeMirror.defineMIME("text/x-tiddlywiki", "tiddlywiki");
+//}}}
diff --git a/third-party/codemirror-3.15/mode/tiki/index.html b/third-party/codemirror-3.15/mode/tiki/index.html
new file mode 100644 (file)
index 0000000..7b85a44
--- /dev/null
@@ -0,0 +1,81 @@
+<html xmlns="http://www.w3.org/1999/xhtml">
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Tiki wiki mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="tiki.js"></script>
+    <link rel="stylesheet" href="tiki.css">
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+  </head>
+  <body style="padding: 20px;">
+    <h1>CodeMirror: Tiki wiki mode</h1>
+
+<div><textarea id="code" name="code">
+Headings
+!Header 1
+!!Header 2
+!!!Header 3
+!!!!Header 4
+!!!!!Header 5
+!!!!!!Header 6
+
+Styling
+-=titlebar=-
+^^ Box on multi
+lines
+of content^^
+__bold__
+''italic''
+===underline===
+::center::
+--Line Through--
+
+Operators
+~np~No parse~/np~
+
+Link
+[link|desc|nocache]
+
+Wiki
+((Wiki))
+((Wiki|desc))
+((Wiki|desc|timeout))
+
+Table
+||row1 col1|row1 col2|row1 col3
+row2 col1|row2 col2|row2 col3
+row3 col1|row3 col2|row3 col3||
+
+Lists:
+*bla
+**bla-1
+++continue-bla-1
+***bla-2
+++continue-bla-1
+*bla
++continue-bla
+#bla
+** tra-la-la
++continue-bla
+#bla
+
+Plugin (standard):
+{PLUGIN(attr="my attr")}
+Plugin Body
+{PLUGIN}
+
+Plugin (inline):
+{plugin attr="my attr"}
+</textarea></div>
+
+<script type="text/javascript">
+       var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        mode: 'tiki',      
+        lineNumbers: true
+    });
+</script>
+
+</body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/tiki/tiki.css b/third-party/codemirror-3.15/mode/tiki/tiki.css
new file mode 100644 (file)
index 0000000..0dbc3ea
--- /dev/null
@@ -0,0 +1,26 @@
+.cm-tw-syntaxerror {
+       color: #FFF;
+       background-color: #900;
+}
+
+.cm-tw-deleted {
+       text-decoration: line-through;
+}
+
+.cm-tw-header5 {
+       font-weight: bold;
+}
+.cm-tw-listitem:first-child { /*Added first child to fix duplicate padding when highlighting*/
+       padding-left: 10px;
+}
+
+.cm-tw-box {
+       border-top-width: 0px ! important;
+       border-style: solid;
+       border-width: 1px;
+       border-color: inherit;
+}
+
+.cm-tw-underline {
+       text-decoration: underline;
+}
\ No newline at end of file
diff --git a/third-party/codemirror-3.15/mode/tiki/tiki.js b/third-party/codemirror-3.15/mode/tiki/tiki.js
new file mode 100644 (file)
index 0000000..e789163
--- /dev/null
@@ -0,0 +1,308 @@
+CodeMirror.defineMode('tiki', function(config) {
+  function inBlock(style, terminator, returnTokenizer) {
+    return function(stream, state) {
+      while (!stream.eol()) {
+        if (stream.match(terminator)) {
+          state.tokenize = inText;
+          break;
+        }
+        stream.next();
+      }
+
+      if (returnTokenizer) state.tokenize = returnTokenizer;
+
+      return style;
+    };
+  }
+
+  function inLine(style) {
+    return function(stream, state) {
+      while(!stream.eol()) {
+        stream.next();
+      }
+      state.tokenize = inText;
+      return style;
+    };
+  }
+
+  function inText(stream, state) {
+    function chain(parser) {
+      state.tokenize = parser;
+      return parser(stream, state);
+    }
+
+    var sol = stream.sol();
+    var ch = stream.next();
+
+    //non start of line
+    switch (ch) { //switch is generally much faster than if, so it is used here
+    case "{": //plugin
+      stream.eat("/");
+      stream.eatSpace();
+      var tagName = "";
+      var c;
+      while ((c = stream.eat(/[^\s\u00a0=\"\'\/?(}]/))) tagName += c;
+      state.tokenize = inPlugin;
+      return "tag";
+      break;
+    case "_": //bold
+      if (stream.eat("_")) {
+        return chain(inBlock("strong", "__", inText));
+      }
+      break;
+    case "'": //italics
+      if (stream.eat("'")) {
+        // Italic text
+        return chain(inBlock("em", "''", inText));
+      }
+      break;
+    case "(":// Wiki Link
+      if (stream.eat("(")) {
+        return chain(inBlock("variable-2", "))", inText));
+      }
+      break;
+    case "[":// Weblink
+      return chain(inBlock("variable-3", "]", inText));
+      break;
+    case "|": //table
+      if (stream.eat("|")) {
+        return chain(inBlock("comment", "||"));
+      }
+      break;
+    case "-":
+      if (stream.eat("=")) {//titleBar
+        return chain(inBlock("header string", "=-", inText));
+      } else if (stream.eat("-")) {//deleted
+        return chain(inBlock("error tw-deleted", "--", inText));
+      }
+      break;
+    case "=": //underline
+      if (stream.match("==")) {
+        return chain(inBlock("tw-underline", "===", inText));
+      }
+      break;
+    case ":":
+      if (stream.eat(":")) {
+        return chain(inBlock("comment", "::"));
+      }
+      break;
+    case "^": //box
+      return chain(inBlock("tw-box", "^"));
+      break;
+    case "~": //np
+      if (stream.match("np~")) {
+        return chain(inBlock("meta", "~/np~"));
+      }
+      break;
+    }
+
+    //start of line types
+    if (sol) {
+      switch (ch) {
+      case "!": //header at start of line
+        if (stream.match('!!!!!')) {
+          return chain(inLine("header string"));
+        } else if (stream.match('!!!!')) {
+          return chain(inLine("header string"));
+        } else if (stream.match('!!!')) {
+          return chain(inLine("header string"));
+        } else if (stream.match('!!')) {
+          return chain(inLine("header string"));
+        } else {
+          return chain(inLine("header string"));
+        }
+        break;
+      case "*": //unordered list line item, or <li /> at start of line
+      case "#": //ordered list line item, or <li /> at start of line
+      case "+": //ordered list line item, or <li /> at start of line
+        return chain(inLine("tw-listitem bracket"));
+        break;
+      }
+    }
+
+    //stream.eatWhile(/[&{]/); was eating up plugins, turned off to act less like html and more like tiki
+    return null;
+  }
+
+  var indentUnit = config.indentUnit;
+
+  // Return variables for tokenizers
+  var pluginName, type;
+  function inPlugin(stream, state) {
+    var ch = stream.next();
+    var peek = stream.peek();
+
+    if (ch == "}") {
+      state.tokenize = inText;
+      //type = ch == ")" ? "endPlugin" : "selfclosePlugin"; inPlugin
+      return "tag";
+    } else if (ch == "(" || ch == ")") {
+      return "bracket";
+    } else if (ch == "=") {
+      type = "equals";
+
+      if (peek == ">") {
+        ch = stream.next();
+        peek = stream.peek();
+      }
+
+      //here we detect values directly after equal character with no quotes
+      if (!/[\'\"]/.test(peek)) {
+        state.tokenize = inAttributeNoQuote();
+      }
+      //end detect values
+
+      return "operator";
+    } else if (/[\'\"]/.test(ch)) {
+      state.tokenize = inAttribute(ch);
+      return state.tokenize(stream, state);
+    } else {
+      stream.eatWhile(/[^\s\u00a0=\"\'\/?]/);
+      return "keyword";
+    }
+  }
+
+  function inAttribute(quote) {
+    return function(stream, state) {
+      while (!stream.eol()) {
+        if (stream.next() == quote) {
+          state.tokenize = inPlugin;
+          break;
+        }
+      }
+      return "string";
+    };
+  }
+
+  function inAttributeNoQuote() {
+    return function(stream, state) {
+      while (!stream.eol()) {
+        var ch = stream.next();
+        var peek = stream.peek();
+        if (ch == " " || ch == "," || /[ )}]/.test(peek)) {
+      state.tokenize = inPlugin;
+      break;
+    }
+  }
+  return "string";
+};
+                     }
+
+var curState, setStyle;
+function pass() {
+  for (var i = arguments.length - 1; i >= 0; i--) curState.cc.push(arguments[i]);
+}
+
+function cont() {
+  pass.apply(null, arguments);
+  return true;
+}
+
+function pushContext(pluginName, startOfLine) {
+  var noIndent = curState.context && curState.context.noIndent;
+  curState.context = {
+    prev: curState.context,
+    pluginName: pluginName,
+    indent: curState.indented,
+    startOfLine: startOfLine,
+    noIndent: noIndent
+  };
+}
+
+function popContext() {
+  if (curState.context) curState.context = curState.context.prev;
+}
+
+function element(type) {
+  if (type == "openPlugin") {curState.pluginName = pluginName; return cont(attributes, endplugin(curState.startOfLine));}
+  else if (type == "closePlugin") {
+    var err = false;
+    if (curState.context) {
+      err = curState.context.pluginName != pluginName;
+      popContext();
+    } else {
+      err = true;
+    }
+    if (err) setStyle = "error";
+    return cont(endcloseplugin(err));
+  }
+  else if (type == "string") {
+    if (!curState.context || curState.context.name != "!cdata") pushContext("!cdata");
+    if (curState.tokenize == inText) popContext();
+    return cont();
+  }
+  else return cont();
+}
+
+function endplugin(startOfLine) {
+  return function(type) {
+    if (
+      type == "selfclosePlugin" ||
+        type == "endPlugin"
+    )
+      return cont();
+    if (type == "endPlugin") {pushContext(curState.pluginName, startOfLine); return cont();}
+    return cont();
+  };
+}
+
+function endcloseplugin(err) {
+  return function(type) {
+    if (err) setStyle = "error";
+    if (type == "endPlugin") return cont();
+    return pass();
+  };
+}
+
+function attributes(type) {
+  if (type == "keyword") {setStyle = "attribute"; return cont(attributes);}
+  if (type == "equals") return cont(attvalue, attributes);
+  return pass();
+}
+function attvalue(type) {
+  if (type == "keyword") {setStyle = "string"; return cont();}
+  if (type == "string") return cont(attvaluemaybe);
+  return pass();
+}
+function attvaluemaybe(type) {
+  if (type == "string") return cont(attvaluemaybe);
+  else return pass();
+}
+return {
+  startState: function() {
+    return {tokenize: inText, cc: [], indented: 0, startOfLine: true, pluginName: null, context: null};
+  },
+  token: function(stream, state) {
+    if (stream.sol()) {
+      state.startOfLine = true;
+      state.indented = stream.indentation();
+    }
+    if (stream.eatSpace()) return null;
+
+    setStyle = type = pluginName = null;
+    var style = state.tokenize(stream, state);
+    if ((style || type) && style != "comment") {
+      curState = state;
+      while (true) {
+        var comb = state.cc.pop() || element;
+        if (comb(type || style)) break;
+      }
+    }
+    state.startOfLine = false;
+    return setStyle || style;
+  },
+  indent: function(state, textAfter) {
+    var context = state.context;
+    if (context && context.noIndent) return 0;
+    if (context && /^{\//.test(textAfter))
+        context = context.prev;
+        while (context && !context.startOfLine)
+          context = context.prev;
+        if (context) return context.indent + indentUnit;
+        else return 0;
+       },
+    electricChars: "/"
+  };
+});
+
+CodeMirror.defineMIME("text/tiki", "tiki");
diff --git a/third-party/codemirror-3.15/mode/turtle/index.html b/third-party/codemirror-3.15/mode/turtle/index.html
new file mode 100644 (file)
index 0000000..5e56e57
--- /dev/null
@@ -0,0 +1,39 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Turtle mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="turtle.js"></script>
+    <style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Turtle mode</h1>
+    <form><textarea id="code" name="code">
+@prefix foaf: <http://xmlns.com/foaf/0.1/> .
+@prefix geo: <http://www.w3.org/2003/01/geo/wgs84_pos#> .
+@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
+
+<http://purl.org/net/bsletten> 
+    a foaf:Person;
+    foaf:interest <http://www.w3.org/2000/01/sw/>;
+    foaf:based_near [
+        geo:lat "34.0736111" ;
+        geo:lon "-118.3994444"
+   ]
+
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        mode: "text/turtle",
+        tabMode: "indent",
+        matchBrackets: true
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/turtle</code>.</p>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/turtle/turtle.js b/third-party/codemirror-3.15/mode/turtle/turtle.js
new file mode 100644 (file)
index 0000000..e118bfb
--- /dev/null
@@ -0,0 +1,145 @@
+CodeMirror.defineMode("turtle", function(config) {
+  var indentUnit = config.indentUnit;
+  var curPunc;
+
+  function wordRegexp(words) {
+    return new RegExp("^(?:" + words.join("|") + ")$", "i");
+  }
+  var ops = wordRegexp([]);
+  var keywords = wordRegexp(["@prefix", "@base", "a"]);
+  var operatorChars = /[*+\-<>=&|]/;
+
+  function tokenBase(stream, state) {
+    var ch = stream.next();
+    curPunc = null;
+    if (ch == "<" && !stream.match(/^[\s\u00a0=]/, false)) {
+      stream.match(/^[^\s\u00a0>]*>?/);
+      return "atom";
+    }
+    else if (ch == "\"" || ch == "'") {
+      state.tokenize = tokenLiteral(ch);
+      return state.tokenize(stream, state);
+    }
+    else if (/[{}\(\),\.;\[\]]/.test(ch)) {
+      curPunc = ch;
+      return null;
+    }
+    else if (ch == "#") {
+      stream.skipToEnd();
+      return "comment";
+    }
+    else if (operatorChars.test(ch)) {
+      stream.eatWhile(operatorChars);
+      return null;
+    }
+    else if (ch == ":") {
+          return "operator";
+        } else {
+      stream.eatWhile(/[_\w\d]/);
+      if(stream.peek() == ":") {
+        return "variable-3";
+      } else {
+             var word = stream.current();
+
+             if(keywords.test(word)) {
+                        return "meta";
+             }
+
+             if(ch >= "A" && ch <= "Z") {
+                    return "comment";
+                 } else {
+                        return "keyword";
+                 }
+      }
+      var word = stream.current();
+      if (ops.test(word))
+        return null;
+      else if (keywords.test(word))
+        return "meta";
+      else
+        return "variable";
+    }
+  }
+
+  function tokenLiteral(quote) {
+    return function(stream, state) {
+      var escaped = false, ch;
+      while ((ch = stream.next()) != null) {
+        if (ch == quote && !escaped) {
+          state.tokenize = tokenBase;
+          break;
+        }
+        escaped = !escaped && ch == "\\";
+      }
+      return "string";
+    };
+  }
+
+  function pushContext(state, type, col) {
+    state.context = {prev: state.context, indent: state.indent, col: col, type: type};
+  }
+  function popContext(state) {
+    state.indent = state.context.indent;
+    state.context = state.context.prev;
+  }
+
+  return {
+    startState: function() {
+      return {tokenize: tokenBase,
+              context: null,
+              indent: 0,
+              col: 0};
+    },
+
+    token: function(stream, state) {
+      if (stream.sol()) {
+        if (state.context && state.context.align == null) state.context.align = false;
+        state.indent = stream.indentation();
+      }
+      if (stream.eatSpace()) return null;
+      var style = state.tokenize(stream, state);
+
+      if (style != "comment" && state.context && state.context.align == null && state.context.type != "pattern") {
+        state.context.align = true;
+      }
+
+      if (curPunc == "(") pushContext(state, ")", stream.column());
+      else if (curPunc == "[") pushContext(state, "]", stream.column());
+      else if (curPunc == "{") pushContext(state, "}", stream.column());
+      else if (/[\]\}\)]/.test(curPunc)) {
+        while (state.context && state.context.type == "pattern") popContext(state);
+        if (state.context && curPunc == state.context.type) popContext(state);
+      }
+      else if (curPunc == "." && state.context && state.context.type == "pattern") popContext(state);
+      else if (/atom|string|variable/.test(style) && state.context) {
+        if (/[\}\]]/.test(state.context.type))
+          pushContext(state, "pattern", stream.column());
+        else if (state.context.type == "pattern" && !state.context.align) {
+          state.context.align = true;
+          state.context.col = stream.column();
+        }
+      }
+
+      return style;
+    },
+
+    indent: function(state, textAfter) {
+      var firstChar = textAfter && textAfter.charAt(0);
+      var context = state.context;
+      if (/[\]\}]/.test(firstChar))
+        while (context && context.type == "pattern") context = context.prev;
+
+      var closing = context && firstChar == context.type;
+      if (!context)
+        return 0;
+      else if (context.type == "pattern")
+        return context.col;
+      else if (context.align)
+        return context.col + (closing ? 0 : 1);
+      else
+        return context.indent + (closing ? 0 : indentUnit);
+    }
+  };
+});
+
+CodeMirror.defineMIME("text/turtle", "turtle");
diff --git a/third-party/codemirror-3.15/mode/vb/LICENSE.txt b/third-party/codemirror-3.15/mode/vb/LICENSE.txt
new file mode 100644 (file)
index 0000000..6083970
--- /dev/null
@@ -0,0 +1,21 @@
+The MIT License
+
+Copyright (c) 2012 Codility Limited, 107 Cheapside, London EC2V 6DN, UK
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/third-party/codemirror-3.15/mode/vb/index.html b/third-party/codemirror-3.15/mode/vb/index.html
new file mode 100644 (file)
index 0000000..74dd5e8
--- /dev/null
@@ -0,0 +1,88 @@
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: VB.NET mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="vb.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <link href="http://fonts.googleapis.com/css?family=Inconsolata" rel="stylesheet" type="text/css">
+    <style>
+      .CodeMirror {border: 1px solid #aaa; height:210px; height: auto;}
+      .CodeMirror-scroll { overflow-x: auto; overflow-y: hidden;}
+      .CodeMirror pre { font-family: Inconsolata; font-size: 14px}
+    </style> 
+    <script type="text/javascript" src="../../addon/runmode/runmode.js"></script>
+  </head>
+  <body onload="init()">
+    <h1>CodeMirror: VB.NET mode</h1>
+<script type="text/javascript">
+function test(golden, text) {
+  var ok = true;
+  var i = 0;
+  function callback(token, style, lineNo, pos){
+               //console.log(String(token) + " " + String(style) + " " + String(lineNo) + " " + String(pos));
+    var result = [String(token), String(style)];
+    if (golden[i][0] != result[0] || golden[i][1] != result[1]){
+      return "Error, expected: " + String(golden[i]) + ", got: " + String(result);
+      ok = false;
+    }
+    i++;
+  }
+  CodeMirror.runMode(text, "text/x-vb",callback); 
+
+  if (ok) return "Tests OK";
+}
+function testTypes() {
+  var golden = [['Integer','keyword'],[' ','null'],['Float','keyword']]
+  var text =  "Integer Float";
+  return test(golden,text);
+}
+function testIf(){
+  var golden = [['If','keyword'],[' ','null'],['True','keyword'],[' ','null'],['End','keyword'],[' ','null'],['If','keyword']];
+  var text = 'If True End If';
+  return test(golden, text);
+}
+function testDecl(){
+   var golden = [['Dim','keyword'],[' ','null'],['x','variable'],[' ','null'],['as','keyword'],[' ','null'],['Integer','keyword']];
+   var text = 'Dim x as Integer';
+   return test(golden, text);
+}
+function testAll(){
+  var result = "";
+
+  result += testTypes() + "\n";
+  result += testIf() + "\n";
+  result += testDecl() + "\n";
+  return result;
+
+}
+function initText(editor) {
+  var content = 'Class rocket\nPrivate quality as Double\nPublic Sub launch() as String\nif quality > 0.8\nlaunch = "Successful"\nElse\nlaunch = "Failed"\nEnd If\nEnd sub\nEnd class\n';
+  editor.setValue(content);
+  for (var i =0; i< editor.lineCount(); i++) editor.indentLine(i);
+}
+function init() {
+    editor = CodeMirror.fromTextArea(document.getElementById("solution"), {
+        lineNumbers: true,
+        mode: "text/x-vb",
+        readOnly: false,
+        tabMode: "shift"
+    });
+    runTest();
+}
+function runTest() {
+       document.getElementById('testresult').innerHTML = testAll();
+  initText(editor);
+       
+}
+</script>
+
+
+  <div id="edit">
+  <textarea style="width:95%;height:200px;padding:5px;" name="solution" id="solution" ></textarea>
+  </div>
+  <pre id="testresult"></pre>
+  <p>MIME type defined: <code>text/x-vb</code>.</p>
+
+</body></html>
diff --git a/third-party/codemirror-3.15/mode/vb/vb.js b/third-party/codemirror-3.15/mode/vb/vb.js
new file mode 100644 (file)
index 0000000..27b2271
--- /dev/null
@@ -0,0 +1,259 @@
+CodeMirror.defineMode("vb", function(conf, parserConf) {
+    var ERRORCLASS = 'error';
+
+    function wordRegexp(words) {
+        return new RegExp("^((" + words.join(")|(") + "))\\b", "i");
+    }
+
+    var singleOperators = new RegExp("^[\\+\\-\\*/%&\\\\|\\^~<>!]");
+    var singleDelimiters = new RegExp('^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]');
+    var doubleOperators = new RegExp("^((==)|(<>)|(<=)|(>=)|(<>)|(<<)|(>>)|(//)|(\\*\\*))");
+    var doubleDelimiters = new RegExp("^((\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))");
+    var tripleDelimiters = new RegExp("^((//=)|(>>=)|(<<=)|(\\*\\*=))");
+    var identifiers = new RegExp("^[_A-Za-z][_A-Za-z0-9]*");
+
+    var openingKeywords = ['class','module', 'sub','enum','select','while','if','function',  'get','set','property', 'try'];
+    var middleKeywords = ['else','elseif','case', 'catch'];
+    var endKeywords = ['next','loop'];
+
+    var wordOperators = wordRegexp(['and', 'or', 'not', 'xor', 'in']);
+    var commonkeywords = ['as', 'dim', 'break',  'continue','optional', 'then',  'until',
+                          'goto', 'byval','byref','new','handles','property', 'return',
+                          'const','private', 'protected', 'friend', 'public', 'shared', 'static', 'true','false'];
+    var commontypes = ['integer','string','double','decimal','boolean','short','char', 'float','single'];
+
+    var keywords = wordRegexp(commonkeywords);
+    var types = wordRegexp(commontypes);
+    var stringPrefixes = '"';
+
+    var opening = wordRegexp(openingKeywords);
+    var middle = wordRegexp(middleKeywords);
+    var closing = wordRegexp(endKeywords);
+    var doubleClosing = wordRegexp(['end']);
+    var doOpening = wordRegexp(['do']);
+
+    var indentInfo = null;
+
+
+
+
+    function indent(_stream, state) {
+      state.currentIndent++;
+    }
+
+    function dedent(_stream, state) {
+      state.currentIndent--;
+    }
+    // tokenizers
+    function tokenBase(stream, state) {
+        if (stream.eatSpace()) {
+            return null;
+        }
+
+        var ch = stream.peek();
+
+        // Handle Comments
+        if (ch === "'") {
+            stream.skipToEnd();
+            return 'comment';
+        }
+
+
+        // Handle Number Literals
+        if (stream.match(/^((&H)|(&O))?[0-9\.a-f]/i, false)) {
+            var floatLiteral = false;
+            // Floats
+            if (stream.match(/^\d*\.\d+F?/i)) { floatLiteral = true; }
+            else if (stream.match(/^\d+\.\d*F?/)) { floatLiteral = true; }
+            else if (stream.match(/^\.\d+F?/)) { floatLiteral = true; }
+
+            if (floatLiteral) {
+                // Float literals may be "imaginary"
+                stream.eat(/J/i);
+                return 'number';
+            }
+            // Integers
+            var intLiteral = false;
+            // Hex
+            if (stream.match(/^&H[0-9a-f]+/i)) { intLiteral = true; }
+            // Octal
+            else if (stream.match(/^&O[0-7]+/i)) { intLiteral = true; }
+            // Decimal
+            else if (stream.match(/^[1-9]\d*F?/)) {
+                // Decimal literals may be "imaginary"
+                stream.eat(/J/i);
+                // TODO - Can you have imaginary longs?
+                intLiteral = true;
+            }
+            // Zero by itself with no other piece of number.
+            else if (stream.match(/^0(?![\dx])/i)) { intLiteral = true; }
+            if (intLiteral) {
+                // Integer literals may be "long"
+                stream.eat(/L/i);
+                return 'number';
+            }
+        }
+
+        // Handle Strings
+        if (stream.match(stringPrefixes)) {
+            state.tokenize = tokenStringFactory(stream.current());
+            return state.tokenize(stream, state);
+        }
+
+        // Handle operators and Delimiters
+        if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters)) {
+            return null;
+        }
+        if (stream.match(doubleOperators)
+            || stream.match(singleOperators)
+            || stream.match(wordOperators)) {
+            return 'operator';
+        }
+        if (stream.match(singleDelimiters)) {
+            return null;
+        }
+        if (stream.match(doOpening)) {
+            indent(stream,state);
+            state.doInCurrentLine = true;
+            return 'keyword';
+        }
+        if (stream.match(opening)) {
+            if (! state.doInCurrentLine)
+              indent(stream,state);
+            else
+              state.doInCurrentLine = false;
+            return 'keyword';
+        }
+        if (stream.match(middle)) {
+            return 'keyword';
+        }
+
+        if (stream.match(doubleClosing)) {
+            dedent(stream,state);
+            dedent(stream,state);
+            return 'keyword';
+        }
+        if (stream.match(closing)) {
+            dedent(stream,state);
+            return 'keyword';
+        }
+
+        if (stream.match(types)) {
+            return 'keyword';
+        }
+
+        if (stream.match(keywords)) {
+            return 'keyword';
+        }
+
+        if (stream.match(identifiers)) {
+            return 'variable';
+        }
+
+        // Handle non-detected items
+        stream.next();
+        return ERRORCLASS;
+    }
+
+    function tokenStringFactory(delimiter) {
+        var singleline = delimiter.length == 1;
+        var OUTCLASS = 'string';
+
+        return function(stream, state) {
+            while (!stream.eol()) {
+                stream.eatWhile(/[^'"]/);
+                if (stream.match(delimiter)) {
+                    state.tokenize = tokenBase;
+                    return OUTCLASS;
+                } else {
+                    stream.eat(/['"]/);
+                }
+            }
+            if (singleline) {
+                if (parserConf.singleLineStringErrors) {
+                    return ERRORCLASS;
+                } else {
+                    state.tokenize = tokenBase;
+                }
+            }
+            return OUTCLASS;
+        };
+    }
+
+
+    function tokenLexer(stream, state) {
+        var style = state.tokenize(stream, state);
+        var current = stream.current();
+
+        // Handle '.' connected identifiers
+        if (current === '.') {
+            style = state.tokenize(stream, state);
+            current = stream.current();
+            if (style === 'variable') {
+                return 'variable';
+            } else {
+                return ERRORCLASS;
+            }
+        }
+
+
+        var delimiter_index = '[({'.indexOf(current);
+        if (delimiter_index !== -1) {
+            indent(stream, state );
+        }
+        if (indentInfo === 'dedent') {
+            if (dedent(stream, state)) {
+                return ERRORCLASS;
+            }
+        }
+        delimiter_index = '])}'.indexOf(current);
+        if (delimiter_index !== -1) {
+            if (dedent(stream, state)) {
+                return ERRORCLASS;
+            }
+        }
+
+        return style;
+    }
+
+    var external = {
+        electricChars:"dDpPtTfFeE ",
+        startState: function() {
+            return {
+              tokenize: tokenBase,
+              lastToken: null,
+              currentIndent: 0,
+              nextLineIndent: 0,
+              doInCurrentLine: false
+
+
+          };
+        },
+
+        token: function(stream, state) {
+            if (stream.sol()) {
+              state.currentIndent += state.nextLineIndent;
+              state.nextLineIndent = 0;
+              state.doInCurrentLine = 0;
+            }
+            var style = tokenLexer(stream, state);
+
+            state.lastToken = {style:style, content: stream.current()};
+
+
+
+            return style;
+        },
+
+        indent: function(state, textAfter) {
+            var trueText = textAfter.replace(/^\s+|\s+$/g, '') ;
+            if (trueText.match(closing) || trueText.match(doubleClosing) || trueText.match(middle)) return conf.indentUnit*(state.currentIndent-1);
+            if(state.currentIndent < 0) return 0;
+            return state.currentIndent * conf.indentUnit;
+        }
+
+    };
+    return external;
+});
+
+CodeMirror.defineMIME("text/x-vb", "vb");
diff --git a/third-party/codemirror-3.15/mode/vbscript/index.html b/third-party/codemirror-3.15/mode/vbscript/index.html
new file mode 100644 (file)
index 0000000..9ae4667
--- /dev/null
@@ -0,0 +1,43 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: VBScript mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="vbscript.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: VBScript mode</h1>
+
+<div><textarea id="code" name="code">
+' Pete Guhl
+' 03-04-2012
+'
+' Basic VBScript support for codemirror2
+
+Const ForReading = 1, ForWriting = 2, ForAppending = 8
+
+Call Sub020_PostBroadcastToUrbanAirship(strUserName, strPassword, intTransmitID, strResponse)
+
+If Not IsNull(strResponse) AND Len(strResponse) = 0 Then
+       boolTransmitOkYN = False
+Else
+       ' WScript.Echo "Oh Happy Day! Oh Happy DAY!"
+       boolTransmitOkYN = True
+End If
+</textarea></div>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        indentUnit: 4
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/vbscript</code>.</p>
+  </body>
+</html>
+
diff --git a/third-party/codemirror-3.15/mode/vbscript/vbscript.js b/third-party/codemirror-3.15/mode/vbscript/vbscript.js
new file mode 100644 (file)
index 0000000..0a97fb6
--- /dev/null
@@ -0,0 +1,334 @@
+/*
+For extra ASP classic objects, initialize CodeMirror instance with this option:
+    isASP: true
+
+E.G.:
+    var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        isASP: true
+      });
+*/
+CodeMirror.defineMode("vbscript", function(conf, parserConf) {
+    var ERRORCLASS = 'error';
+
+    function wordRegexp(words) {
+        return new RegExp("^((" + words.join(")|(") + "))\\b", "i");
+    }
+
+    var singleOperators = new RegExp("^[\\+\\-\\*/&\\\\\\^<>=]");
+    var doubleOperators = new RegExp("^((<>)|(<=)|(>=))");
+    var singleDelimiters = new RegExp('^[\\.,]');
+    var brakets = new RegExp('^[\\(\\)]');
+    var identifiers = new RegExp("^[A-Za-z][_A-Za-z0-9]*");
+
+    var openingKeywords = ['class','sub','select','while','if','function', 'property', 'with', 'for'];
+    var middleKeywords = ['else','elseif','case'];
+    var endKeywords = ['next','loop','wend'];
+
+    var wordOperators = wordRegexp(['and', 'or', 'not', 'xor', 'is', 'mod', 'eqv', 'imp']);
+    var commonkeywords = ['dim', 'redim', 'then',  'until', 'randomize',
+                          'byval','byref','new','property', 'exit', 'in',
+                          'const','private', 'public',
+                          'get','set','let', 'stop', 'on error resume next', 'on error goto 0', 'option explicit', 'call', 'me'];
+
+    //This list was from: http://msdn.microsoft.com/en-us/library/f8tbc79x(v=vs.84).aspx
+    var atomWords = ['true', 'false', 'nothing', 'empty', 'null'];
+    //This list was from: http://msdn.microsoft.com/en-us/library/3ca8tfek(v=vs.84).aspx
+    var builtinFuncsWords = ['abs', 'array', 'asc', 'atn', 'cbool', 'cbyte', 'ccur', 'cdate', 'cdbl', 'chr', 'cint', 'clng', 'cos', 'csng', 'cstr', 'date', 'dateadd', 'datediff', 'datepart',
+                        'dateserial', 'datevalue', 'day', 'escape', 'eval', 'execute', 'exp', 'filter', 'formatcurrency', 'formatdatetime', 'formatnumber', 'formatpercent', 'getlocale', 'getobject',
+                        'getref', 'hex', 'hour', 'inputbox', 'instr', 'instrrev', 'int', 'fix', 'isarray', 'isdate', 'isempty', 'isnull', 'isnumeric', 'isobject', 'join', 'lbound', 'lcase', 'left',
+                        'len', 'loadpicture', 'log', 'ltrim', 'rtrim', 'trim', 'maths', 'mid', 'minute', 'month', 'monthname', 'msgbox', 'now', 'oct', 'replace', 'rgb', 'right', 'rnd', 'round',
+                        'scriptengine', 'scriptenginebuildversion', 'scriptenginemajorversion', 'scriptengineminorversion', 'second', 'setlocale', 'sgn', 'sin', 'space', 'split', 'sqr', 'strcomp',
+                        'string', 'strreverse', 'tan', 'time', 'timer', 'timeserial', 'timevalue', 'typename', 'ubound', 'ucase', 'unescape', 'vartype', 'weekday', 'weekdayname', 'year'];
+
+    //This list was from: http://msdn.microsoft.com/en-us/library/ydz4cfk3(v=vs.84).aspx
+    var builtinConsts = ['vbBlack', 'vbRed', 'vbGreen', 'vbYellow', 'vbBlue', 'vbMagenta', 'vbCyan', 'vbWhite', 'vbBinaryCompare', 'vbTextCompare',
+                         'vbSunday', 'vbMonday', 'vbTuesday', 'vbWednesday', 'vbThursday', 'vbFriday', 'vbSaturday', 'vbUseSystemDayOfWeek', 'vbFirstJan1', 'vbFirstFourDays', 'vbFirstFullWeek',
+                         'vbGeneralDate', 'vbLongDate', 'vbShortDate', 'vbLongTime', 'vbShortTime', 'vbObjectError',
+                         'vbOKOnly', 'vbOKCancel', 'vbAbortRetryIgnore', 'vbYesNoCancel', 'vbYesNo', 'vbRetryCancel', 'vbCritical', 'vbQuestion', 'vbExclamation', 'vbInformation', 'vbDefaultButton1', 'vbDefaultButton2',
+                         'vbDefaultButton3', 'vbDefaultButton4', 'vbApplicationModal', 'vbSystemModal', 'vbOK', 'vbCancel', 'vbAbort', 'vbRetry', 'vbIgnore', 'vbYes', 'vbNo',
+                         'vbCr', 'VbCrLf', 'vbFormFeed', 'vbLf', 'vbNewLine', 'vbNullChar', 'vbNullString', 'vbTab', 'vbVerticalTab', 'vbUseDefault', 'vbTrue', 'vbFalse',
+                         'vbEmpty', 'vbNull', 'vbInteger', 'vbLong', 'vbSingle', 'vbDouble', 'vbCurrency', 'vbDate', 'vbString', 'vbObject', 'vbError', 'vbBoolean', 'vbVariant', 'vbDataObject', 'vbDecimal', 'vbByte', 'vbArray'];
+    //This list was from: http://msdn.microsoft.com/en-us/library/hkc375ea(v=vs.84).aspx
+    var builtinObjsWords = ['WScript', 'err', 'debug', 'RegExp'];
+    var knownProperties = ['description', 'firstindex', 'global', 'helpcontext', 'helpfile', 'ignorecase', 'length', 'number', 'pattern', 'source', 'value', 'count'];
+    var knownMethods = ['clear', 'execute', 'raise', 'replace', 'test', 'write', 'writeline', 'close', 'open', 'state', 'eof', 'update', 'addnew', 'end', 'createobject', 'quit'];
+
+    var aspBuiltinObjsWords = ['server', 'response', 'request', 'session', 'application'];
+    var aspKnownProperties = ['buffer', 'cachecontrol', 'charset', 'contenttype', 'expires', 'expiresabsolute', 'isclientconnected', 'pics', 'status', //response
+                              'clientcertificate', 'cookies', 'form', 'querystring', 'servervariables', 'totalbytes', //request
+                              'contents', 'staticobjects', //application
+                              'codepage', 'lcid', 'sessionid', 'timeout', //session
+                              'scripttimeout']; //server
+    var aspKnownMethods = ['addheader', 'appendtolog', 'binarywrite', 'end', 'flush', 'redirect', //response
+                           'binaryread', //request
+                           'remove', 'removeall', 'lock', 'unlock', //application
+                           'abandon', //session
+                           'getlasterror', 'htmlencode', 'mappath', 'transfer', 'urlencode']; //server
+
+    var knownWords = knownMethods.concat(knownProperties);
+
+    builtinObjsWords = builtinObjsWords.concat(builtinConsts);
+
+    if (conf.isASP){
+        builtinObjsWords = builtinObjsWords.concat(aspBuiltinObjsWords);
+        knownWords = knownWords.concat(aspKnownMethods, aspKnownProperties);
+    };
+
+    var keywords = wordRegexp(commonkeywords);
+    var atoms = wordRegexp(atomWords);
+    var builtinFuncs = wordRegexp(builtinFuncsWords);
+    var builtinObjs = wordRegexp(builtinObjsWords);
+    var known = wordRegexp(knownWords);
+    var stringPrefixes = '"';
+
+    var opening = wordRegexp(openingKeywords);
+    var middle = wordRegexp(middleKeywords);
+    var closing = wordRegexp(endKeywords);
+    var doubleClosing = wordRegexp(['end']);
+    var doOpening = wordRegexp(['do']);
+    var noIndentWords = wordRegexp(['on error resume next', 'exit']);
+    var comment = wordRegexp(['rem']);
+
+
+    function indent(_stream, state) {
+      state.currentIndent++;
+    }
+
+    function dedent(_stream, state) {
+      state.currentIndent--;
+    }
+    // tokenizers
+    function tokenBase(stream, state) {
+        if (stream.eatSpace()) {
+            return 'space';
+            //return null;
+        }
+
+        var ch = stream.peek();
+
+        // Handle Comments
+        if (ch === "'") {
+            stream.skipToEnd();
+            return 'comment';
+        }
+        if (stream.match(comment)){
+            stream.skipToEnd();
+            return 'comment';
+        }
+
+
+        // Handle Number Literals
+        if (stream.match(/^((&H)|(&O))?[0-9\.]/i, false) && !stream.match(/^((&H)|(&O))?[0-9\.]+[a-z_]/i, false)) {
+            var floatLiteral = false;
+            // Floats
+            if (stream.match(/^\d*\.\d+/i)) { floatLiteral = true; }
+            else if (stream.match(/^\d+\.\d*/)) { floatLiteral = true; }
+            else if (stream.match(/^\.\d+/)) { floatLiteral = true; }
+
+            if (floatLiteral) {
+                // Float literals may be "imaginary"
+                stream.eat(/J/i);
+                return 'number';
+            }
+            // Integers
+            var intLiteral = false;
+            // Hex
+            if (stream.match(/^&H[0-9a-f]+/i)) { intLiteral = true; }
+            // Octal
+            else if (stream.match(/^&O[0-7]+/i)) { intLiteral = true; }
+            // Decimal
+            else if (stream.match(/^[1-9]\d*F?/)) {
+                // Decimal literals may be "imaginary"
+                stream.eat(/J/i);
+                // TODO - Can you have imaginary longs?
+                intLiteral = true;
+            }
+            // Zero by itself with no other piece of number.
+            else if (stream.match(/^0(?![\dx])/i)) { intLiteral = true; }
+            if (intLiteral) {
+                // Integer literals may be "long"
+                stream.eat(/L/i);
+                return 'number';
+            }
+        }
+
+        // Handle Strings
+        if (stream.match(stringPrefixes)) {
+            state.tokenize = tokenStringFactory(stream.current());
+            return state.tokenize(stream, state);
+        }
+
+        // Handle operators and Delimiters
+        if (stream.match(doubleOperators)
+            || stream.match(singleOperators)
+            || stream.match(wordOperators)) {
+            return 'operator';
+        }
+        if (stream.match(singleDelimiters)) {
+            return null;
+        }
+
+        if (stream.match(brakets)) {
+            return "bracket";
+        }
+
+        if (stream.match(noIndentWords)) {
+            state.doInCurrentLine = true;
+
+            return 'keyword';
+        }
+
+        if (stream.match(doOpening)) {
+            indent(stream,state);
+            state.doInCurrentLine = true;
+
+            return 'keyword';
+        }
+        if (stream.match(opening)) {
+            if (! state.doInCurrentLine)
+              indent(stream,state);
+            else
+              state.doInCurrentLine = false;
+
+            return 'keyword';
+        }
+        if (stream.match(middle)) {
+            return 'keyword';
+        }
+
+
+        if (stream.match(doubleClosing)) {
+            dedent(stream,state);
+            dedent(stream,state);
+
+            return 'keyword';
+        }
+        if (stream.match(closing)) {
+            if (! state.doInCurrentLine)
+              dedent(stream,state);
+            else
+              state.doInCurrentLine = false;
+
+            return 'keyword';
+        }
+
+        if (stream.match(keywords)) {
+            return 'keyword';
+        }
+
+        if (stream.match(atoms)) {
+            return 'atom';
+        }
+
+        if (stream.match(known)) {
+            return 'variable-2';
+        }
+
+        if (stream.match(builtinFuncs)) {
+            return 'builtin';
+        }
+
+        if (stream.match(builtinObjs)){
+            return 'variable-2';
+        }
+
+        if (stream.match(identifiers)) {
+            return 'variable';
+        }
+
+        // Handle non-detected items
+        stream.next();
+        return ERRORCLASS;
+    }
+
+    function tokenStringFactory(delimiter) {
+        var singleline = delimiter.length == 1;
+        var OUTCLASS = 'string';
+
+        return function(stream, state) {
+            while (!stream.eol()) {
+                stream.eatWhile(/[^'"]/);
+                if (stream.match(delimiter)) {
+                    state.tokenize = tokenBase;
+                    return OUTCLASS;
+                } else {
+                    stream.eat(/['"]/);
+                }
+            }
+            if (singleline) {
+                if (parserConf.singleLineStringErrors) {
+                    return ERRORCLASS;
+                } else {
+                    state.tokenize = tokenBase;
+                }
+            }
+            return OUTCLASS;
+        };
+    }
+
+
+    function tokenLexer(stream, state) {
+        var style = state.tokenize(stream, state);
+        var current = stream.current();
+
+        // Handle '.' connected identifiers
+        if (current === '.') {
+            style = state.tokenize(stream, state);
+
+            current = stream.current();
+            if (style.substr(0, 8) === 'variable' || style==='builtin' || style==='keyword'){//|| knownWords.indexOf(current.substring(1)) > -1) {
+                if (style === 'builtin' || style === 'keyword') style='variable';
+                if (knownWords.indexOf(current.substr(1)) > -1) style='variable-2';
+
+                return style;
+            } else {
+                return ERRORCLASS;
+            }
+        }
+
+        return style;
+    }
+
+    var external = {
+        electricChars:"dDpPtTfFeE ",
+        startState: function() {
+            return {
+              tokenize: tokenBase,
+              lastToken: null,
+              currentIndent: 0,
+              nextLineIndent: 0,
+              doInCurrentLine: false,
+              ignoreKeyword: false
+
+
+          };
+        },
+
+        token: function(stream, state) {
+            if (stream.sol()) {
+              state.currentIndent += state.nextLineIndent;
+              state.nextLineIndent = 0;
+              state.doInCurrentLine = 0;
+            }
+            var style = tokenLexer(stream, state);
+
+            state.lastToken = {style:style, content: stream.current()};
+
+            if (style==='space') style=null;
+
+            return style;
+        },
+
+        indent: function(state, textAfter) {
+            var trueText = textAfter.replace(/^\s+|\s+$/g, '') ;
+            if (trueText.match(closing) || trueText.match(doubleClosing) || trueText.match(middle)) return conf.indentUnit*(state.currentIndent-1);
+            if(state.currentIndent < 0) return 0;
+            return state.currentIndent * conf.indentUnit;
+        }
+
+    };
+    return external;
+});
+
+CodeMirror.defineMIME("text/vbscript", "vbscript");
diff --git a/third-party/codemirror-3.15/mode/velocity/index.html b/third-party/codemirror-3.15/mode/velocity/index.html
new file mode 100644 (file)
index 0000000..fb59cb5
--- /dev/null
@@ -0,0 +1,103 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Velocity mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="velocity.js"></script>
+    <link rel="stylesheet" href="../../theme/night.css">
+    <style>.CodeMirror {border: 1px solid black;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: Velocity mode</h1>
+    <form><textarea id="code" name="code">
+## Velocity Code Demo
+#*
+   based on PL/SQL mode by Peter Raganitsch, adapted to Velocity by Steve O'Hara ( http://www.pivotal-solutions.co.uk )
+   August 2011
+*#
+
+#*
+   This is a multiline comment.
+   This is the second line
+*#
+
+#[[ hello steve
+   This has invalid syntax that would normally need "poor man's escaping" like:
+
+   #define()
+
+   ${blah
+]]#
+
+#include( "disclaimer.txt" "opinion.txt" )
+#include( $foo $bar )
+
+#parse( "lecorbusier.vm" )
+#parse( $foo )
+
+#evaluate( 'string with VTL #if(true)will be displayed#end' )
+
+#define( $hello ) Hello $who #end #set( $who = "World!") $hello ## displays Hello World!
+
+#foreach( $customer in $customerList )
+
+    $foreach.count $customer.Name
+
+    #if( $foo == ${bar})
+        it's true!
+        #break
+    #{else}
+        it's not!
+        #stop
+    #end
+
+    #if ($foreach.parent.hasNext)
+        $velocityCount
+    #end
+#end
+
+$someObject.getValues("this is a string split
+        across lines")
+
+#macro( tablerows $color $somelist )
+    #foreach( $something in $somelist )
+        <tr><td bgcolor=$color>$something</td></tr>
+    #end
+#end
+
+#tablerows("red" ["dadsdf","dsa"])
+
+   Variable reference: #set( $monkey = $bill )
+   String literal: #set( $monkey.Friend = 'monica' )
+   Property reference: #set( $monkey.Blame = $whitehouse.Leak )
+   Method reference: #set( $monkey.Plan = $spindoctor.weave($web) )
+   Number literal: #set( $monkey.Number = 123 )
+   Range operator: #set( $monkey.Numbers = [1..3] )
+   Object list: #set( $monkey.Say = ["Not", $my, "fault"] )
+   Object map: #set( $monkey.Map = {"banana" : "good", "roast beef" : "bad"})
+
+The RHS can also be a simple arithmetic expression, such as:
+Addition: #set( $value = $foo + 1 )
+   Subtraction: #set( $value = $bar - 1 )
+   Multiplication: #set( $value = $foo * $bar )
+   Division: #set( $value = $foo / $bar )
+   Remainder: #set( $value = $foo % $bar )
+
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        tabMode: "indent",
+        theme: "night",
+        lineNumbers: true,
+        indentUnit: 4,
+        mode: "text/velocity"
+      });
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/velocity</code>.</p>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/velocity/velocity.js b/third-party/codemirror-3.15/mode/velocity/velocity.js
new file mode 100644 (file)
index 0000000..43a97ba
--- /dev/null
@@ -0,0 +1,144 @@
+CodeMirror.defineMode("velocity", function() {
+    function parseWords(str) {
+        var obj = {}, words = str.split(" ");
+        for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
+        return obj;
+    }
+
+    var keywords = parseWords("#end #else #break #stop #[[ #]] " +
+                              "#{end} #{else} #{break} #{stop}");
+    var functions = parseWords("#if #elseif #foreach #set #include #parse #macro #define #evaluate " +
+                               "#{if} #{elseif} #{foreach} #{set} #{include} #{parse} #{macro} #{define} #{evaluate}");
+    var specials = parseWords("$foreach.count $foreach.hasNext $foreach.first $foreach.last $foreach.topmost $foreach.parent $velocityCount");
+    var isOperatorChar = /[+\-*&%=<>!?:\/|]/;
+
+    function chain(stream, state, f) {
+        state.tokenize = f;
+        return f(stream, state);
+    }
+    function tokenBase(stream, state) {
+        var beforeParams = state.beforeParams;
+        state.beforeParams = false;
+        var ch = stream.next();
+        // start of string?
+        if ((ch == '"' || ch == "'") && state.inParams)
+            return chain(stream, state, tokenString(ch));
+        // is it one of the special signs []{}().,;? Seperator?
+        else if (/[\[\]{}\(\),;\.]/.test(ch)) {
+            if (ch == "(" && beforeParams) state.inParams = true;
+            else if (ch == ")") state.inParams = false;
+            return null;
+        }
+        // start of a number value?
+        else if (/\d/.test(ch)) {
+            stream.eatWhile(/[\w\.]/);
+            return "number";
+        }
+        // multi line comment?
+        else if (ch == "#" && stream.eat("*")) {
+            return chain(stream, state, tokenComment);
+        }
+        // unparsed content?
+        else if (ch == "#" && stream.match(/ *\[ *\[/)) {
+            return chain(stream, state, tokenUnparsed);
+        }
+        // single line comment?
+        else if (ch == "#" && stream.eat("#")) {
+            stream.skipToEnd();
+            return "comment";
+        }
+        // variable?
+        else if (ch == "$") {
+            stream.eatWhile(/[\w\d\$_\.{}]/);
+            // is it one of the specials?
+            if (specials && specials.propertyIsEnumerable(stream.current().toLowerCase())) {
+                return "keyword";
+            }
+            else {
+                state.beforeParams = true;
+                return "builtin";
+            }
+        }
+        // is it a operator?
+        else if (isOperatorChar.test(ch)) {
+            stream.eatWhile(isOperatorChar);
+            return "operator";
+        }
+        else {
+            // get the whole word
+            stream.eatWhile(/[\w\$_{}]/);
+            var word = stream.current().toLowerCase();
+            // is it one of the listed keywords?
+            if (keywords && keywords.propertyIsEnumerable(word))
+                return "keyword";
+            // is it one of the listed functions?
+            if (functions && functions.propertyIsEnumerable(word) ||
+                stream.current().match(/^#[a-z0-9_]+ *$/i) && stream.peek()=="(") {
+                state.beforeParams = true;
+                return "keyword";
+            }
+            // default: just a "word"
+            return null;
+        }
+    }
+
+    function tokenString(quote) {
+        return function(stream, state) {
+            var escaped = false, next, end = false;
+            while ((next = stream.next()) != null) {
+                if (next == quote && !escaped) {
+                    end = true;
+                    break;
+                }
+                escaped = !escaped && next == "\\";
+            }
+            if (end) state.tokenize = tokenBase;
+            return "string";
+        };
+    }
+
+    function tokenComment(stream, state) {
+        var maybeEnd = false, ch;
+        while (ch = stream.next()) {
+            if (ch == "#" && maybeEnd) {
+                state.tokenize = tokenBase;
+                break;
+            }
+            maybeEnd = (ch == "*");
+        }
+        return "comment";
+    }
+
+    function tokenUnparsed(stream, state) {
+        var maybeEnd = 0, ch;
+        while (ch = stream.next()) {
+            if (ch == "#" && maybeEnd == 2) {
+                state.tokenize = tokenBase;
+                break;
+            }
+            if (ch == "]")
+                maybeEnd++;
+            else if (ch != " ")
+                maybeEnd = 0;
+        }
+        return "meta";
+    }
+    // Interface
+
+    return {
+        startState: function() {
+            return {
+                tokenize: tokenBase,
+                beforeParams: false,
+                inParams: false
+            };
+        },
+
+        token: function(stream, state) {
+            if (stream.eatSpace()) return null;
+            return state.tokenize(stream, state);
+        }
+    };
+});
+
+CodeMirror.defineMIME("text/velocity", "velocity");
diff --git a/third-party/codemirror-3.15/mode/verilog/index.html b/third-party/codemirror-3.15/mode/verilog/index.html
new file mode 100644 (file)
index 0000000..f7c88c6
--- /dev/null
@@ -0,0 +1,121 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Verilog mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="verilog.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style>.CodeMirror {border: 2px inset #dee;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: Verilog mode</h1>
+
+<form><textarea id="code" name="code">
+/* Verilog demo code */
+
+module butterfly
+  #(
+    parameter WIDTH = 32,
+    parameter MWIDTH = 1
+    )
+   (
+    input wire                     clk,
+    input wire                     rst_n,
+    // m_in contains data that passes through this block with no change.
+    input wire [MWIDTH-1:0]        m_in,
+    // The twiddle factor.
+    input wire signed [WIDTH-1:0]  w,
+    // XA
+    input wire signed [WIDTH-1:0]  xa,
+    // XB
+    input wire signed [WIDTH-1:0]  xb,
+    // Set to 1 when new data is present on inputs.
+    input wire                     x_nd,
+    // delayed version of m_in.
+    output reg [MWIDTH-1:0]        m_out,
+    // YA = XA + W*XB
+    // YB = XA - W*XB
+    output wire signed [WIDTH-1:0] ya,
+    output wire signed [WIDTH-1:0] yb,
+    output reg                     y_nd,
+    output reg                     error
+    );
+
+   // Set wire to the real and imag parts for convenience.
+   wire signed [WIDTH/2-1:0]        xa_re;
+   wire signed [WIDTH/2-1:0]        xa_im;
+   assign xa_re = xa[WIDTH-1:WIDTH/2];
+   assign xa_im = xa[WIDTH/2-1:0];
+   wire signed [WIDTH/2-1: 0]       ya_re;
+   wire signed [WIDTH/2-1: 0]       ya_im;
+   assign ya = {ya_re, ya_im};
+   wire signed [WIDTH/2-1: 0]       yb_re;
+   wire signed [WIDTH/2-1: 0]       yb_im;
+   assign yb = {yb_re, yb_im};
+
+   // Delayed stuff.
+   reg signed [WIDTH/2-1:0]         xa_re_z;
+   reg signed [WIDTH/2-1:0]         xa_im_z;
+   // Output of multiplier
+   wire signed [WIDTH-1:0]          xbw;
+   wire signed [WIDTH/2-1:0]        xbw_re;
+   wire signed [WIDTH/2-1:0]        xbw_im;
+   assign xbw_re = xbw[WIDTH-1:WIDTH/2];
+   assign xbw_im = xbw[WIDTH/2-1:0];
+   // Do summing
+   // I don't think we should get overflow here because of the
+   // size of the twiddle factors.
+   // If we do testing should catch it.
+   assign ya_re = xa_re_z + xbw_re;
+   assign ya_im = xa_im_z + xbw_im;
+   assign yb_re = xa_re_z - xbw_re;
+   assign yb_im = xa_im_z - xbw_im;
+   
+   // Create the multiply module.
+   multiply_complex #(WIDTH) multiply_complex_0
+     (.clk(clk),
+      .rst_n(rst_n),
+      .x(xb),
+      .y(w),
+      .z(xbw)
+      );
+
+  always @ (posedge clk)
+    begin
+       if (!rst_n)
+         begin
+            y_nd <= 1'b0;
+            error <= 1'b0;
+         end
+       else
+         begin
+            // Set delay for x_nd_old and m.
+            y_nd <= x_nd;
+            m_out <= m_in;
+            if (x_nd)
+              begin
+                 xa_re_z <= xa_re/2;
+                 xa_im_z <= xa_im/2;
+              end
+         end
+    end
+   
+endmodule
+</textarea></form>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        mode: "text/x-verilog"
+      });
+    </script>
+
+    <p>Simple mode that tries to handle Verilog-like languages as well as it
+    can. Takes one configuration parameters: <code>keywords</code>, an
+    object whose property names are the keywords in the language.</p>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-verilog</code> (Verilog code).</p>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/verilog/verilog.js b/third-party/codemirror-3.15/mode/verilog/verilog.js
new file mode 100644 (file)
index 0000000..708de23
--- /dev/null
@@ -0,0 +1,182 @@
+CodeMirror.defineMode("verilog", function(config, parserConfig) {
+  var indentUnit = config.indentUnit,
+      keywords = parserConfig.keywords || {},
+      blockKeywords = parserConfig.blockKeywords || {},
+      atoms = parserConfig.atoms || {},
+      hooks = parserConfig.hooks || {},
+      multiLineStrings = parserConfig.multiLineStrings;
+  var isOperatorChar = /[&|~><!\)\(*#%@+\/=?\:;}{,\.\^\-\[\]]/;
+
+  var curPunc;
+
+  function tokenBase(stream, state) {
+    var ch = stream.next();
+    if (hooks[ch]) {
+      var result = hooks[ch](stream, state);
+      if (result !== false) return result;
+    }
+    if (ch == '"') {
+      state.tokenize = tokenString(ch);
+      return state.tokenize(stream, state);
+    }
+    if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
+      curPunc = ch;
+      return null;
+    }
+    if (/[\d']/.test(ch)) {
+      stream.eatWhile(/[\w\.']/);
+      return "number";
+    }
+    if (ch == "/") {
+      if (stream.eat("*")) {
+        state.tokenize = tokenComment;
+        return tokenComment(stream, state);
+      }
+      if (stream.eat("/")) {
+        stream.skipToEnd();
+        return "comment";
+      }
+    }
+    if (isOperatorChar.test(ch)) {
+      stream.eatWhile(isOperatorChar);
+      return "operator";
+    }
+    stream.eatWhile(/[\w\$_]/);
+    var cur = stream.current();
+    if (keywords.propertyIsEnumerable(cur)) {
+      if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
+      return "keyword";
+    }
+    if (atoms.propertyIsEnumerable(cur)) return "atom";
+    return "variable";
+  }
+
+  function tokenString(quote) {
+    return function(stream, state) {
+      var escaped = false, next, end = false;
+      while ((next = stream.next()) != null) {
+        if (next == quote && !escaped) {end = true; break;}
+        escaped = !escaped && next == "\\";
+      }
+      if (end || !(escaped || multiLineStrings))
+        state.tokenize = tokenBase;
+      return "string";
+    };
+  }
+
+  function tokenComment(stream, state) {
+    var maybeEnd = false, ch;
+    while (ch = stream.next()) {
+      if (ch == "/" && maybeEnd) {
+        state.tokenize = tokenBase;
+        break;
+      }
+      maybeEnd = (ch == "*");
+    }
+    return "comment";
+  }
+
+  function Context(indented, column, type, align, prev) {
+    this.indented = indented;
+    this.column = column;
+    this.type = type;
+    this.align = align;
+    this.prev = prev;
+  }
+  function pushContext(state, col, type) {
+    return state.context = new Context(state.indented, col, type, null, state.context);
+  }
+  function popContext(state) {
+    var t = state.context.type;
+    if (t == ")" || t == "]" || t == "}")
+      state.indented = state.context.indented;
+    return state.context = state.context.prev;
+  }
+
+  // Interface
+
+  return {
+    startState: function(basecolumn) {
+      return {
+        tokenize: null,
+        context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
+        indented: 0,
+        startOfLine: true
+      };
+    },
+
+    token: function(stream, state) {
+      var ctx = state.context;
+      if (stream.sol()) {
+        if (ctx.align == null) ctx.align = false;
+        state.indented = stream.indentation();
+        state.startOfLine = true;
+      }
+      if (stream.eatSpace()) return null;
+      curPunc = null;
+      var style = (state.tokenize || tokenBase)(stream, state);
+      if (style == "comment" || style == "meta") return style;
+      if (ctx.align == null) ctx.align = true;
+
+      if ((curPunc == ";" || curPunc == ":") && ctx.type == "statement") popContext(state);
+      else if (curPunc == "{") pushContext(state, stream.column(), "}");
+      else if (curPunc == "[") pushContext(state, stream.column(), "]");
+      else if (curPunc == "(") pushContext(state, stream.column(), ")");
+      else if (curPunc == "}") {
+        while (ctx.type == "statement") ctx = popContext(state);
+        if (ctx.type == "}") ctx = popContext(state);
+        while (ctx.type == "statement") ctx = popContext(state);
+      }
+      else if (curPunc == ctx.type) popContext(state);
+      else if (ctx.type == "}" || ctx.type == "top" || (ctx.type == "statement" && curPunc == "newstatement"))
+        pushContext(state, stream.column(), "statement");
+      state.startOfLine = false;
+      return style;
+    },
+
+    indent: function(state, textAfter) {
+      if (state.tokenize != tokenBase && state.tokenize != null) return 0;
+      var firstChar = textAfter && textAfter.charAt(0), ctx = state.context, closing = firstChar == ctx.type;
+      if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : indentUnit);
+      else if (ctx.align) return ctx.column + (closing ? 0 : 1);
+      else return ctx.indented + (closing ? 0 : indentUnit);
+    },
+
+    electricChars: "{}"
+  };
+});
+
+(function() {
+  function words(str) {
+    var obj = {}, words = str.split(" ");
+    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
+    return obj;
+  }
+
+  var verilogKeywords = "always and assign automatic begin buf bufif0 bufif1 case casex casez cell cmos config " +
+    "deassign default defparam design disable edge else end endcase endconfig endfunction endgenerate endmodule " +
+    "endprimitive endspecify endtable endtask event for force forever fork function generate genvar highz0 " +
+    "highz1 if ifnone incdir include initial inout input instance integer join large liblist library localparam " +
+    "macromodule medium module nand negedge nmos nor noshowcancelled not notif0 notif1 or output parameter pmos " +
+    "posedge primitive pull0 pull1 pulldown pullup pulsestyle_onevent pulsestyle_ondetect rcmos real realtime " +
+    "reg release repeat rnmos rpmos rtran rtranif0 rtranif1 scalared showcancelled signed small specify specparam " +
+    "strong0 strong1 supply0 supply1 table task time tran tranif0 tranif1 tri tri0 tri1 triand trior trireg " +
+    "unsigned use vectored wait wand weak0 weak1 while wire wor xnor xor";
+
+  var verilogBlockKeywords = "begin bufif0 bufif1 case casex casez config else end endcase endconfig endfunction " +
+    "endgenerate endmodule endprimitive endspecify endtable endtask for forever function generate if ifnone " +
+    "macromodule module primitive repeat specify table task while";
+
+  function metaHook(stream) {
+    stream.eatWhile(/[\w\$_]/);
+    return "meta";
+  }
+
+  CodeMirror.defineMIME("text/x-verilog", {
+    name: "verilog",
+    keywords: words(verilogKeywords),
+    blockKeywords: words(verilogBlockKeywords),
+    atoms: words("null"),
+    hooks: {"`": metaHook, "$": metaHook}
+  });
+}());
diff --git a/third-party/codemirror-3.15/mode/xml/index.html b/third-party/codemirror-3.15/mode/xml/index.html
new file mode 100644 (file)
index 0000000..9628d95
--- /dev/null
@@ -0,0 +1,45 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: XML mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="xml.js"></script>
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: XML mode</h1>
+    <form><textarea id="code" name="code">
+&lt;html style="color: green"&gt;
+  &lt;!-- this is a comment --&gt;
+  &lt;head&gt;
+    &lt;title&gt;HTML Example&lt;/title&gt;
+  &lt;/head&gt;
+  &lt;body&gt;
+    The indentation tries to be &lt;em&gt;somewhat &amp;quot;do what
+    I mean&amp;quot;&lt;/em&gt;... but might not match your style.
+  &lt;/body&gt;
+&lt;/html&gt;
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        mode: {name: "xml", alignCDATA: true},
+        lineNumbers: true
+      });
+    </script>
+    <p>The XML mode supports two configuration parameters:</p>
+    <dl>
+      <dt><code>htmlMode (boolean)</code></dt>
+      <dd>This switches the mode to parse HTML instead of XML. This
+      means attributes do not have to be quoted, and some elements
+      (such as <code>br</code>) do not require a closing tag.</dd>
+      <dt><code>alignCDATA (boolean)</code></dt>
+      <dd>Setting this to true will force the opening tag of CDATA
+      blocks to not be indented.</dd>
+    </dl>
+
+    <p><strong>MIME types defined:</strong> <code>application/xml</code>, <code>text/html</code>.</p>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/xml/xml.js b/third-party/codemirror-3.15/mode/xml/xml.js
new file mode 100644 (file)
index 0000000..84f34a2
--- /dev/null
@@ -0,0 +1,341 @@
+CodeMirror.defineMode("xml", function(config, parserConfig) {
+  var indentUnit = config.indentUnit;
+  var multilineTagIndentFactor = parserConfig.multilineTagIndentFactor || 1;
+  var multilineTagIndentPastTag = parserConfig.multilineTagIndentPastTag || true;
+
+  var Kludges = parserConfig.htmlMode ? {
+    autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true,
+                      'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true,
+                      'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true,
+                      'track': true, 'wbr': true},
+    implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true,
+                       'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true,
+                       'th': true, 'tr': true},
+    contextGrabbers: {
+      'dd': {'dd': true, 'dt': true},
+      'dt': {'dd': true, 'dt': true},
+      'li': {'li': true},
+      'option': {'option': true, 'optgroup': true},
+      'optgroup': {'optgroup': true},
+      'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true,
+            'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true,
+            'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true,
+            'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true,
+            'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true},
+      'rp': {'rp': true, 'rt': true},
+      'rt': {'rp': true, 'rt': true},
+      'tbody': {'tbody': true, 'tfoot': true},
+      'td': {'td': true, 'th': true},
+      'tfoot': {'tbody': true},
+      'th': {'td': true, 'th': true},
+      'thead': {'tbody': true, 'tfoot': true},
+      'tr': {'tr': true}
+    },
+    doNotIndent: {"pre": true},
+    allowUnquoted: true,
+    allowMissing: true
+  } : {
+    autoSelfClosers: {},
+    implicitlyClosed: {},
+    contextGrabbers: {},
+    doNotIndent: {},
+    allowUnquoted: false,
+    allowMissing: false
+  };
+  var alignCDATA = parserConfig.alignCDATA;
+
+  // Return variables for tokenizers
+  var tagName, type;
+
+  function inText(stream, state) {
+    function chain(parser) {
+      state.tokenize = parser;
+      return parser(stream, state);
+    }
+
+    var ch = stream.next();
+    if (ch == "<") {
+      if (stream.eat("!")) {
+        if (stream.eat("[")) {
+          if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>"));
+          else return null;
+        } else if (stream.match("--")) {
+          return chain(inBlock("comment", "-->"));
+        } else if (stream.match("DOCTYPE", true, true)) {
+          stream.eatWhile(/[\w\._\-]/);
+          return chain(doctype(1));
+        } else {
+          return null;
+        }
+      } else if (stream.eat("?")) {
+        stream.eatWhile(/[\w\._\-]/);
+        state.tokenize = inBlock("meta", "?>");
+        return "meta";
+      } else {
+        var isClose = stream.eat("/");
+        tagName = "";
+        var c;
+        while ((c = stream.eat(/[^\s\u00a0=<>\"\'\/?]/))) tagName += c;
+        if (!tagName) return "error";
+        type = isClose ? "closeTag" : "openTag";
+        state.tokenize = inTag;
+        return "tag";
+      }
+    } else if (ch == "&") {
+      var ok;
+      if (stream.eat("#")) {
+        if (stream.eat("x")) {
+          ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";");
+        } else {
+          ok = stream.eatWhile(/[\d]/) && stream.eat(";");
+        }
+      } else {
+        ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";");
+      }
+      return ok ? "atom" : "error";
+    } else {
+      stream.eatWhile(/[^&<]/);
+      return null;
+    }
+  }
+
+  function inTag(stream, state) {
+    var ch = stream.next();
+    if (ch == ">" || (ch == "/" && stream.eat(">"))) {
+      state.tokenize = inText;
+      type = ch == ">" ? "endTag" : "selfcloseTag";
+      return "tag";
+    } else if (ch == "=") {
+      type = "equals";
+      return null;
+    } else if (ch == "<") {
+      return "error";
+    } else if (/[\'\"]/.test(ch)) {
+      state.tokenize = inAttribute(ch);
+      state.stringStartCol = stream.column();
+      return state.tokenize(stream, state);
+    } else {
+      stream.eatWhile(/[^\s\u00a0=<>\"\']/);
+      return "word";
+    }
+  }
+
+  function inAttribute(quote) {
+    var closure = function(stream, state) {
+      while (!stream.eol()) {
+        if (stream.next() == quote) {
+          state.tokenize = inTag;
+          break;
+        }
+      }
+      return "string";
+    };
+    closure.isInAttribute = true;
+    return closure;
+  }
+
+  function inBlock(style, terminator) {
+    return function(stream, state) {
+      while (!stream.eol()) {
+        if (stream.match(terminator)) {
+          state.tokenize = inText;
+          break;
+        }
+        stream.next();
+      }
+      return style;
+    };
+  }
+  function doctype(depth) {
+    return function(stream, state) {
+      var ch;
+      while ((ch = stream.next()) != null) {
+        if (ch == "<") {
+          state.tokenize = doctype(depth + 1);
+          return state.tokenize(stream, state);
+        } else if (ch == ">") {
+          if (depth == 1) {
+            state.tokenize = inText;
+            break;
+          } else {
+            state.tokenize = doctype(depth - 1);
+            return state.tokenize(stream, state);
+          }
+        }
+      }
+      return "meta";
+    };
+  }
+
+  var curState, curStream, setStyle;
+  function pass() {
+    for (var i = arguments.length - 1; i >= 0; i--) curState.cc.push(arguments[i]);
+  }
+  function cont() {
+    pass.apply(null, arguments);
+    return true;
+  }
+
+  function pushContext(tagName, startOfLine) {
+    var noIndent = Kludges.doNotIndent.hasOwnProperty(tagName) || (curState.context && curState.context.noIndent);
+    curState.context = {
+      prev: curState.context,
+      tagName: tagName,
+      indent: curState.indented,
+      startOfLine: startOfLine,
+      noIndent: noIndent
+    };
+  }
+  function popContext() {
+    if (curState.context) curState.context = curState.context.prev;
+  }
+
+  function element(type) {
+    if (type == "openTag") {
+      curState.tagName = tagName;
+      curState.tagStart = curStream.column();
+      return cont(attributes, endtag(curState.startOfLine));
+    } else if (type == "closeTag") {
+      var err = false;
+      if (curState.context) {
+        if (curState.context.tagName != tagName) {
+          if (Kludges.implicitlyClosed.hasOwnProperty(curState.context.tagName.toLowerCase())) {
+            popContext();
+          }
+          err = !curState.context || curState.context.tagName != tagName;
+        }
+      } else {
+        err = true;
+      }
+      if (err) setStyle = "error";
+      return cont(endclosetag(err));
+    }
+    return cont();
+  }
+  function endtag(startOfLine) {
+    return function(type) {
+      var tagName = curState.tagName;
+      curState.tagName = curState.tagStart = null;
+      if (type == "selfcloseTag" ||
+          (type == "endTag" && Kludges.autoSelfClosers.hasOwnProperty(tagName.toLowerCase()))) {
+        maybePopContext(tagName.toLowerCase());
+        return cont();
+      }
+      if (type == "endTag") {
+        maybePopContext(tagName.toLowerCase());
+        pushContext(tagName, startOfLine);
+        return cont();
+      }
+      return cont();
+    };
+  }
+  function endclosetag(err) {
+    return function(type) {
+      if (err) setStyle = "error";
+      if (type == "endTag") { popContext(); return cont(); }
+      setStyle = "error";
+      return cont(arguments.callee);
+    };
+  }
+  function maybePopContext(nextTagName) {
+    var parentTagName;
+    while (true) {
+      if (!curState.context) {
+        return;
+      }
+      parentTagName = curState.context.tagName.toLowerCase();
+      if (!Kludges.contextGrabbers.hasOwnProperty(parentTagName) ||
+          !Kludges.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) {
+        return;
+      }
+      popContext();
+    }
+  }
+
+  function attributes(type) {
+    if (type == "word") {setStyle = "attribute"; return cont(attribute, attributes);}
+    if (type == "endTag" || type == "selfcloseTag") return pass();
+    setStyle = "error";
+    return cont(attributes);
+  }
+  function attribute(type) {
+    if (type == "equals") return cont(attvalue, attributes);
+    if (!Kludges.allowMissing) setStyle = "error";
+    else if (type == "word") setStyle = "attribute";
+    return (type == "endTag" || type == "selfcloseTag") ? pass() : cont();
+  }
+  function attvalue(type) {
+    if (type == "string") return cont(attvaluemaybe);
+    if (type == "word" && Kludges.allowUnquoted) {setStyle = "string"; return cont();}
+    setStyle = "error";
+    return (type == "endTag" || type == "selfCloseTag") ? pass() : cont();
+  }
+  function attvaluemaybe(type) {
+    if (type == "string") return cont(attvaluemaybe);
+    else return pass();
+  }
+
+  return {
+    startState: function() {
+      return {tokenize: inText, cc: [], indented: 0, startOfLine: true, tagName: null, tagStart: null, context: null};
+    },
+
+    token: function(stream, state) {
+      if (!state.tagName && stream.sol()) {
+        state.startOfLine = true;
+        state.indented = stream.indentation();
+      }
+      if (stream.eatSpace()) return null;
+
+      setStyle = type = tagName = null;
+      var style = state.tokenize(stream, state);
+      state.type = type;
+      if ((style || type) && style != "comment") {
+        curState = state; curStream = stream;
+        while (true) {
+          var comb = state.cc.pop() || element;
+          if (comb(type || style)) break;
+        }
+      }
+      state.startOfLine = false;
+      return setStyle || style;
+    },
+
+    indent: function(state, textAfter, fullLine) {
+      var context = state.context;
+      // Indent multi-line strings (e.g. css).
+      if (state.tokenize.isInAttribute) {
+        return state.stringStartCol + 1;
+      }
+      if ((state.tokenize != inTag && state.tokenize != inText) ||
+          context && context.noIndent)
+        return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0;
+      // Indent the starts of attribute names.
+      if (state.tagName) {
+        if (multilineTagIndentPastTag)
+          return state.tagStart + state.tagName.length + 2;
+        else
+          return state.tagStart + indentUnit * multilineTagIndentFactor;
+      }
+      if (alignCDATA && /<!\[CDATA\[/.test(textAfter)) return 0;
+      if (context && /^<\//.test(textAfter))
+        context = context.prev;
+      while (context && !context.startOfLine)
+        context = context.prev;
+      if (context) return context.indent + indentUnit;
+      else return 0;
+    },
+
+    electricChars: "/",
+    blockCommentStart: "<!--",
+    blockCommentEnd: "-->",
+
+    configuration: parserConfig.htmlMode ? "html" : "xml",
+    helperType: parserConfig.htmlMode ? "html" : "xml"
+  };
+});
+
+CodeMirror.defineMIME("text/xml", "xml");
+CodeMirror.defineMIME("application/xml", "xml");
+if (!CodeMirror.mimeModes.hasOwnProperty("text/html"))
+  CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true});
diff --git a/third-party/codemirror-3.15/mode/xquery/LICENSE b/third-party/codemirror-3.15/mode/xquery/LICENSE
new file mode 100644 (file)
index 0000000..2a2d47b
--- /dev/null
@@ -0,0 +1,20 @@
+Copyright (C) 2011 by MarkLogic Corporation
+Author: Mike Brevoort <mike@brevoort.com>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
\ No newline at end of file
diff --git a/third-party/codemirror-3.15/mode/xquery/index.html b/third-party/codemirror-3.15/mode/xquery/index.html
new file mode 100644 (file)
index 0000000..27acb89
--- /dev/null
@@ -0,0 +1,221 @@
+<!doctype html> 
+<html> 
+<!--
+/*
+Copyright (C) 2011 by MarkLogic Corporation
+Author: Mike Brevoort <mike@brevoort.com>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+-->
+  <head> 
+    <meta charset="utf-8">
+    <title>CodeMirror: XQuery mode</title> 
+    <link rel="stylesheet" href="../../lib/codemirror.css"> 
+    <script src="../../lib/codemirror.js"></script> 
+    <script src="xquery.js"></script> 
+    <link rel="stylesheet" href="../../doc/docs.css"> 
+    <link rel="stylesheet" href="../../theme/xq-dark.css"> 
+    <style type="text/css">
+       .CodeMirror {
+         border-top: 1px solid black; border-bottom: 1px solid black;
+         height:400px;
+       }
+    </style> 
+  </head> 
+  <body> 
+    <h1>CodeMirror: XQuery mode</h1> 
+<div class="cm-s-default"> 
+       <textarea id="code" name="code"> 
+xquery version &quot;1.0-ml&quot;;
+(: this is
+ : a 
+   "comment" :)
+let $let := &lt;x attr=&quot;value&quot;&gt;&quot;test&quot;&lt;func&gt;function() $var {function()} {$var}&lt;/func&gt;&lt;/x&gt;
+let $joe:=1
+return element element {
+       attribute attribute { 1 },
+       element test { &#39;a&#39; }, 
+       attribute foo { &quot;bar&quot; },
+       fn:doc()[ foo/@bar eq $let ],
+       //x }    
+(: a more 'evil' test :)
+(: Modified Blakeley example (: with nested comment :) ... :)
+declare private function local:declare() {()};
+declare private function local:private() {()};
+declare private function local:function() {()};
+declare private function local:local() {()};
+let $let := &lt;let&gt;let $let := &quot;let&quot;&lt;/let&gt;
+return element element {
+       attribute attribute { try { xdmp:version() } catch($e) { xdmp:log($e) } },
+       attribute fn:doc { &quot;bar&quot; castable as xs:string },
+       element text { text { &quot;text&quot; } },
+       fn:doc()[ child::eq/(@bar | attribute::attribute) eq $let ],
+       //fn:doc
+}
+
+
+
+xquery version &quot;1.0-ml&quot;;
+
+(: Copyright 2006-2010 Mark Logic Corporation. :)
+
+(:
+ : Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);
+ : 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 &quot;AS IS&quot; 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.
+ :)
+
+module namespace json = &quot;http://marklogic.com/json&quot;;
+declare default function namespace &quot;http://www.w3.org/2005/xpath-functions&quot;;
+
+(: Need to backslash escape any double quotes, backslashes, and newlines :)
+declare function json:escape($s as xs:string) as xs:string {
+  let $s := replace($s, &quot;\\&quot;, &quot;\\\\&quot;)
+  let $s := replace($s, &quot;&quot;&quot;&quot;, &quot;\\&quot;&quot;&quot;)
+  let $s := replace($s, codepoints-to-string((13, 10)), &quot;\\n&quot;)
+  let $s := replace($s, codepoints-to-string(13), &quot;\\n&quot;)
+  let $s := replace($s, codepoints-to-string(10), &quot;\\n&quot;)
+  return $s
+};
+
+declare function json:atomize($x as element()) as xs:string {
+  if (count($x/node()) = 0) then 'null'
+  else if ($x/@type = &quot;number&quot;) then
+    let $castable := $x castable as xs:float or
+                     $x castable as xs:double or
+                     $x castable as xs:decimal
+    return
+    if ($castable) then xs:string($x)
+    else error(concat(&quot;Not a number: &quot;, xdmp:describe($x)))
+  else if ($x/@type = &quot;boolean&quot;) then
+    let $castable := $x castable as xs:boolean
+    return
+    if ($castable) then xs:string(xs:boolean($x))
+    else error(concat(&quot;Not a boolean: &quot;, xdmp:describe($x)))
+  else concat('&quot;', json:escape($x), '&quot;')
+};
+
+(: Print the thing that comes after the colon :)
+declare function json:print-value($x as element()) as xs:string {
+  if (count($x/*) = 0) then
+    json:atomize($x)
+  else if ($x/@quote = &quot;true&quot;) then
+    concat('&quot;', json:escape(xdmp:quote($x/node())), '&quot;')
+  else
+    string-join(('{',
+      string-join(for $i in $x/* return json:print-name-value($i), &quot;,&quot;),
+    '}'), &quot;&quot;)
+};
+
+(: Print the name and value both :)
+declare function json:print-name-value($x as element()) as xs:string? {
+  let $name := name($x)
+  let $first-in-array :=
+    count($x/preceding-sibling::*[name(.) = $name]) = 0 and
+    (count($x/following-sibling::*[name(.) = $name]) &gt; 0 or $x/@array = &quot;true&quot;)
+  let $later-in-array := count($x/preceding-sibling::*[name(.) = $name]) &gt; 0
+  return
+
+  if ($later-in-array) then
+    ()  (: I was handled previously :)
+  else if ($first-in-array) then
+    string-join(('&quot;', json:escape($name), '&quot;:[',
+      string-join((for $i in ($x, $x/following-sibling::*[name(.) = $name]) return json:print-value($i)), &quot;,&quot;),
+    ']'), &quot;&quot;)
+   else
+     string-join(('&quot;', json:escape($name), '&quot;:', json:print-value($x)), &quot;&quot;)
+};
+
+(:~
+  Transforms an XML element into a JSON string representation.  See http://json.org.
+  &lt;p/&gt;
+  Sample usage:
+  &lt;pre&gt;
+    xquery version &quot;1.0-ml&quot;;
+    import module namespace json=&quot;http://marklogic.com/json&quot; at &quot;json.xqy&quot;;
+    json:serialize(&amp;lt;foo&amp;gt;&amp;lt;bar&amp;gt;kid&amp;lt;/bar&amp;gt;&amp;lt;/foo&amp;gt;)
+  &lt;/pre&gt;
+  Sample transformations:
+  &lt;pre&gt;
+  &amp;lt;e/&amp;gt; becomes {&quot;e&quot;:null}
+  &amp;lt;e&amp;gt;text&amp;lt;/e&amp;gt; becomes {&quot;e&quot;:&quot;text&quot;}
+  &amp;lt;e&amp;gt;quote &quot; escaping&amp;lt;/e&amp;gt; becomes {&quot;e&quot;:&quot;quote \&quot; escaping&quot;}
+  &amp;lt;e&amp;gt;backslash \ escaping&amp;lt;/e&amp;gt; becomes {&quot;e&quot;:&quot;backslash \\ escaping&quot;}
+  &amp;lt;e&amp;gt;&amp;lt;a&amp;gt;text1&amp;lt;/a&amp;gt;&amp;lt;b&amp;gt;text2&amp;lt;/b&amp;gt;&amp;lt;/e&amp;gt; becomes {&quot;e&quot;:{&quot;a&quot;:&quot;text1&quot;,&quot;b&quot;:&quot;text2&quot;}}
+  &amp;lt;e&amp;gt;&amp;lt;a&amp;gt;text1&amp;lt;/a&amp;gt;&amp;lt;a&amp;gt;text2&amp;lt;/a&amp;gt;&amp;lt;/e&amp;gt; becomes {&quot;e&quot;:{&quot;a&quot;:[&quot;text1&quot;,&quot;text2&quot;]}}
+  &amp;lt;e&amp;gt;&amp;lt;a array=&quot;true&quot;&amp;gt;text1&amp;lt;/a&amp;gt;&amp;lt;/e&amp;gt; becomes {&quot;e&quot;:{&quot;a&quot;:[&quot;text1&quot;]}}
+  &amp;lt;e&amp;gt;&amp;lt;a type=&quot;boolean&quot;&amp;gt;false&amp;lt;/a&amp;gt;&amp;lt;/e&amp;gt; becomes {&quot;e&quot;:{&quot;a&quot;:false}}
+  &amp;lt;e&amp;gt;&amp;lt;a type=&quot;number&quot;&amp;gt;123.5&amp;lt;/a&amp;gt;&amp;lt;/e&amp;gt; becomes {&quot;e&quot;:{&quot;a&quot;:123.5}}
+  &amp;lt;e quote=&quot;true&quot;&amp;gt;&amp;lt;div attrib=&quot;value&quot;/&amp;gt;&amp;lt;/e&amp;gt; becomes {&quot;e&quot;:&quot;&amp;lt;div attrib=\&quot;value\&quot;/&amp;gt;&quot;}
+  &lt;/pre&gt;
+  &lt;p/&gt;
+  Namespace URIs are ignored.  Namespace prefixes are included in the JSON name.
+  &lt;p/&gt;
+  Attributes are ignored, except for the special attribute @array=&quot;true&quot; that
+  indicates the JSON serialization should write the node, even if single, as an
+  array, and the attribute @type that can be set to &quot;boolean&quot; or &quot;number&quot; to
+  dictate the value should be written as that type (unquoted).  There's also
+  an @quote attribute that when set to true writes the inner content as text
+  rather than as structured JSON, useful for sending some XHTML over the
+  wire.
+  &lt;p/&gt;
+  Text nodes within mixed content are ignored.
+
+  @param $x Element node to convert
+  @return String holding JSON serialized representation of $x
+
+  @author Jason Hunter
+  @version 1.0.1
+  
+  Ported to xquery 1.0-ml; double escaped backslashes in json:escape
+:)
+declare function json:serialize($x as element())  as xs:string {
+  string-join(('{', json:print-name-value($x), '}'), &quot;&quot;)
+};
+  </textarea> 
+</div> 
+    <script> 
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true,
+        matchBrackets: true,
+        theme: "xq-dark"
+      });
+    </script> 
+    <p><strong>MIME types defined:</strong> <code>application/xquery</code>.</p> 
+    <p>Development of the CodeMirror XQuery mode was sponsored by 
+      <a href="http://marklogic.com">MarkLogic</a> and developed by 
+      <a href="https://twitter.com/mbrevoort">Mike Brevoort</a>.
+    </p>
+  </body> 
+</html>
diff --git a/third-party/codemirror-3.15/mode/xquery/test.js b/third-party/codemirror-3.15/mode/xquery/test.js
new file mode 100644 (file)
index 0000000..41719dd
--- /dev/null
@@ -0,0 +1,64 @@
+// Don't take these too seriously -- the expected results appear to be
+// based on the results of actual runs without any serious manual
+// verification. If a change you made causes them to fail, the test is
+// as likely to wrong as the code.
+
+(function() {
+  var mode = CodeMirror.getMode({tabSize: 4}, "xquery");
+  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }
+
+  MT("eviltest",
+     "[keyword xquery] [keyword version] [variable &quot;1][keyword .][atom 0][keyword -][variable ml&quot;][def&variable ;]      [comment (: this is       : a          \"comment\" :)]",
+     "      [keyword let] [variable $let] [keyword :=] [variable &lt;x] [variable attr][keyword =][variable &quot;value&quot;&gt;&quot;test&quot;&lt;func&gt][def&variable ;function]() [variable $var] {[keyword function]()} {[variable $var]}[variable &lt;][keyword /][variable func&gt;&lt;][keyword /][variable x&gt;]",
+     "      [keyword let] [variable $joe][keyword :=][atom 1]",
+     "      [keyword return] [keyword element] [variable element] {",
+     "          [keyword attribute] [variable attribute] { [atom 1] },",
+     "          [keyword element] [variable test] { [variable &#39;a&#39;] },           [keyword attribute] [variable foo] { [variable &quot;bar&quot;] },",
+     "          [def&variable fn:doc]()[[ [variable foo][keyword /][variable @bar] [keyword eq] [variable $let] ]],",
+     "          [keyword //][variable x] }                 [comment (: a more 'evil' test :)]",
+     "      [comment (: Modified Blakeley example (: with nested comment :) ... :)]",
+     "      [keyword declare] [keyword private] [keyword function] [def&variable local:declare]() {()}[variable ;]",
+     "      [keyword declare] [keyword private] [keyword function] [def&variable local:private]() {()}[variable ;]",
+     "      [keyword declare] [keyword private] [keyword function] [def&variable local:function]() {()}[variable ;]",
+     "      [keyword declare] [keyword private] [keyword function] [def&variable local:local]() {()}[variable ;]",
+     "      [keyword let] [variable $let] [keyword :=] [variable &lt;let&gt;let] [variable $let] [keyword :=] [variable &quot;let&quot;&lt;][keyword /let][variable &gt;]",
+     "      [keyword return] [keyword element] [variable element] {",
+     "          [keyword attribute] [variable attribute] { [keyword try] { [def&variable xdmp:version]() } [keyword catch]([variable $e]) { [def&variable xdmp:log]([variable $e]) } },",
+     "          [keyword attribute] [variable fn:doc] { [variable &quot;bar&quot;] [variable castable] [keyword as] [atom xs:string] },",
+     "          [keyword element] [variable text] { [keyword text] { [variable &quot;text&quot;] } },",
+     "          [def&variable fn:doc]()[[ [qualifier child::][variable eq][keyword /]([variable @bar] [keyword |] [qualifier attribute::][variable attribute]) [keyword eq] [variable $let] ]],",
+     "          [keyword //][variable fn:doc]",
+     "      }");
+
+  MT("testEmptySequenceKeyword",
+     "[string \"foo\"] [keyword instance] [keyword of] [keyword empty-sequence]()");
+
+  MT("testMultiAttr",
+     "[tag <p ][attribute a1]=[string \"foo\"] [attribute a2]=[string \"bar\"][tag >][variable hello] [variable world][tag </p>]");
+
+  MT("test namespaced variable",
+     "[keyword declare] [keyword namespace] [variable e] [keyword =] [string \"http://example.com/ANamespace\"][variable ;declare] [keyword variable] [variable $e:exampleComThisVarIsNotRecognized] [keyword as] [keyword element]([keyword *]) [variable external;]");
+
+  MT("test EQName variable",
+     "[keyword declare] [keyword variable] [variable $\"http://www.example.com/ns/my\":var] [keyword :=] [atom 12][variable ;]",
+     "[tag <out>]{[variable $\"http://www.example.com/ns/my\":var]}[tag </out>]");
+
+  MT("test EQName function",
+     "[keyword declare] [keyword function] [def&variable \"http://www.example.com/ns/my\":fn] ([variable $a] [keyword as] [atom xs:integer]) [keyword as] [atom xs:integer] {",
+     "   [variable $a] [keyword +] [atom 2]",
+     "}[variable ;]",
+     "[tag <out>]{[def&variable \"http://www.example.com/ns/my\":fn]([atom 12])}[tag </out>]");
+
+  MT("test EQName function with single quotes",
+     "[keyword declare] [keyword function] [def&variable 'http://www.example.com/ns/my':fn] ([variable $a] [keyword as] [atom xs:integer]) [keyword as] [atom xs:integer] {",
+     "   [variable $a] [keyword +] [atom 2]",
+     "}[variable ;]",
+     "[tag <out>]{[def&variable 'http://www.example.com/ns/my':fn]([atom 12])}[tag </out>]");
+
+  MT("testProcessingInstructions",
+     "[def&variable data]([comment&meta <?target content?>]) [keyword instance] [keyword of] [atom xs:string]");
+
+  MT("testQuoteEscapeDouble",
+     "[keyword let] [variable $rootfolder] [keyword :=] [string \"c:\\builds\\winnt\\HEAD\\qa\\scripts\\\"]",
+     "[keyword let] [variable $keysfolder] [keyword :=] [def&variable concat]([variable $rootfolder], [string \"keys\\\"])");
+})();
diff --git a/third-party/codemirror-3.15/mode/xquery/xquery.js b/third-party/codemirror-3.15/mode/xquery/xquery.js
new file mode 100644 (file)
index 0000000..95decc1
--- /dev/null
@@ -0,0 +1,450 @@
+/*
+Copyright (C) 2011 by MarkLogic Corporation
+Author: Mike Brevoort <mike@brevoort.com>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+CodeMirror.defineMode("xquery", function() {
+
+  // The keywords object is set to the result of this self executing
+  // function. Each keyword is a property of the keywords object whose
+  // value is {type: atype, style: astyle}
+  var keywords = function(){
+    // conveinence functions used to build keywords object
+    function kw(type) {return {type: type, style: "keyword"};}
+    var A = kw("keyword a")
+      , B = kw("keyword b")
+      , C = kw("keyword c")
+      , operator = kw("operator")
+      , atom = {type: "atom", style: "atom"}
+      , punctuation = {type: "punctuation", style: null}
+      , qualifier = {type: "axis_specifier", style: "qualifier"};
+
+    // kwObj is what is return from this function at the end
+    var kwObj = {
+      'if': A, 'switch': A, 'while': A, 'for': A,
+      'else': B, 'then': B, 'try': B, 'finally': B, 'catch': B,
+      'element': C, 'attribute': C, 'let': C, 'implements': C, 'import': C, 'module': C, 'namespace': C,
+      'return': C, 'super': C, 'this': C, 'throws': C, 'where': C, 'private': C,
+      ',': punctuation,
+      'null': atom, 'fn:false()': atom, 'fn:true()': atom
+    };
+
+    // a list of 'basic' keywords. For each add a property to kwObj with the value of
+    // {type: basic[i], style: "keyword"} e.g. 'after' --> {type: "after", style: "keyword"}
+    var basic = ['after','ancestor','ancestor-or-self','and','as','ascending','assert','attribute','before',
+    'by','case','cast','child','comment','declare','default','define','descendant','descendant-or-self',
+    'descending','document','document-node','element','else','eq','every','except','external','following',
+    'following-sibling','follows','for','function','if','import','in','instance','intersect','item',
+    'let','module','namespace','node','node','of','only','or','order','parent','precedes','preceding',
+    'preceding-sibling','processing-instruction','ref','return','returns','satisfies','schema','schema-element',
+    'self','some','sortby','stable','text','then','to','treat','typeswitch','union','variable','version','where',
+    'xquery', 'empty-sequence'];
+    for(var i=0, l=basic.length; i < l; i++) { kwObj[basic[i]] = kw(basic[i]);};
+
+    // a list of types. For each add a property to kwObj with the value of
+    // {type: "atom", style: "atom"}
+    var types = ['xs:string', 'xs:float', 'xs:decimal', 'xs:double', 'xs:integer', 'xs:boolean', 'xs:date', 'xs:dateTime',
+    'xs:time', 'xs:duration', 'xs:dayTimeDuration', 'xs:time', 'xs:yearMonthDuration', 'numeric', 'xs:hexBinary',
+    'xs:base64Binary', 'xs:anyURI', 'xs:QName', 'xs:byte','xs:boolean','xs:anyURI','xf:yearMonthDuration'];
+    for(var i=0, l=types.length; i < l; i++) { kwObj[types[i]] = atom;};
+
+    // each operator will add a property to kwObj with value of {type: "operator", style: "keyword"}
+    var operators = ['eq', 'ne', 'lt', 'le', 'gt', 'ge', ':=', '=', '>', '>=', '<', '<=', '.', '|', '?', 'and', 'or', 'div', 'idiv', 'mod', '*', '/', '+', '-'];
+    for(var i=0, l=operators.length; i < l; i++) { kwObj[operators[i]] = operator;};
+
+    // each axis_specifiers will add a property to kwObj with value of {type: "axis_specifier", style: "qualifier"}
+    var axis_specifiers = ["self::", "attribute::", "child::", "descendant::", "descendant-or-self::", "parent::",
+    "ancestor::", "ancestor-or-self::", "following::", "preceding::", "following-sibling::", "preceding-sibling::"];
+    for(var i=0, l=axis_specifiers.length; i < l; i++) { kwObj[axis_specifiers[i]] = qualifier; };
+
+    return kwObj;
+  }();
+
+  // Used as scratch variables to communicate multiple values without
+  // consing up tons of objects.
+  var type, content;
+
+  function ret(tp, style, cont) {
+    type = tp; content = cont;
+    return style;
+  }
+
+  function chain(stream, state, f) {
+    state.tokenize = f;
+    return f(stream, state);
+  }
+
+  // the primary mode tokenizer
+  function tokenBase(stream, state) {
+    var ch = stream.next(),
+        mightBeFunction = false,
+        isEQName = isEQNameAhead(stream);
+
+    // an XML tag (if not in some sub, chained tokenizer)
+    if (ch == "<") {
+      if(stream.match("!--", true))
+        return chain(stream, state, tokenXMLComment);
+
+      if(stream.match("![CDATA", false)) {
+        state.tokenize = tokenCDATA;
+        return ret("tag", "tag");
+      }
+
+      if(stream.match("?", false)) {
+        return chain(stream, state, tokenPreProcessing);
+      }
+
+      var isclose = stream.eat("/");
+      stream.eatSpace();
+      var tagName = "", c;
+      while ((c = stream.eat(/[^\s\u00a0=<>\"\'\/?]/))) tagName += c;
+
+      return chain(stream, state, tokenTag(tagName, isclose));
+    }
+    // start code block
+    else if(ch == "{") {
+      pushStateStack(state,{ type: "codeblock"});
+      return ret("", null);
+    }
+    // end code block
+    else if(ch == "}") {
+      popStateStack(state);
+      return ret("", null);
+    }
+    // if we're in an XML block
+    else if(isInXmlBlock(state)) {
+      if(ch == ">")
+        return ret("tag", "tag");
+      else if(ch == "/" && stream.eat(">")) {
+        popStateStack(state);
+        return ret("tag", "tag");
+      }
+      else
+        return ret("word", "variable");
+    }
+    // if a number
+    else if (/\d/.test(ch)) {
+      stream.match(/^\d*(?:\.\d*)?(?:E[+\-]?\d+)?/);
+      return ret("number", "atom");
+    }
+    // comment start
+    else if (ch === "(" && stream.eat(":")) {
+      pushStateStack(state, { type: "comment"});
+      return chain(stream, state, tokenComment);
+    }
+    // quoted string
+    else if (  !isEQName && (ch === '"' || ch === "'"))
+      return chain(stream, state, tokenString(ch));
+    // variable
+    else if(ch === "$") {
+      return chain(stream, state, tokenVariable);
+    }
+    // assignment
+    else if(ch ===":" && stream.eat("=")) {
+      return ret("operator", "keyword");
+    }
+    // open paren
+    else if(ch === "(") {
+      pushStateStack(state, { type: "paren"});
+      return ret("", null);
+    }
+    // close paren
+    else if(ch === ")") {
+      popStateStack(state);
+      return ret("", null);
+    }
+    // open paren
+    else if(ch === "[") {
+      pushStateStack(state, { type: "bracket"});
+      return ret("", null);
+    }
+    // close paren
+    else if(ch === "]") {
+      popStateStack(state);
+      return ret("", null);
+    }
+    else {
+      var known = keywords.propertyIsEnumerable(ch) && keywords[ch];
+
+      // if there's a EQName ahead, consume the rest of the string portion, it's likely a function
+      if(isEQName && ch === '\"') while(stream.next() !== '"'){}
+      if(isEQName && ch === '\'') while(stream.next() !== '\''){}
+
+      // gobble up a word if the character is not known
+      if(!known) stream.eatWhile(/[\w\$_-]/);
+
+      // gobble a colon in the case that is a lib func type call fn:doc
+      var foundColon = stream.eat(":");
+
+      // if there's not a second colon, gobble another word. Otherwise, it's probably an axis specifier
+      // which should get matched as a keyword
+      if(!stream.eat(":") && foundColon) {
+        stream.eatWhile(/[\w\$_-]/);
+      }
+      // if the next non whitespace character is an open paren, this is probably a function (if not a keyword of other sort)
+      if(stream.match(/^[ \t]*\(/, false)) {
+        mightBeFunction = true;
+      }
+      // is the word a keyword?
+      var word = stream.current();
+      known = keywords.propertyIsEnumerable(word) && keywords[word];
+
+      // if we think it's a function call but not yet known,
+      // set style to variable for now for lack of something better
+      if(mightBeFunction && !known) known = {type: "function_call", style: "variable def"};
+
+      // if the previous word was element, attribute, axis specifier, this word should be the name of that
+      if(isInXmlConstructor(state)) {
+        popStateStack(state);
+        return ret("word", "variable", word);
+      }
+      // as previously checked, if the word is element,attribute, axis specifier, call it an "xmlconstructor" and
+      // push the stack so we know to look for it on the next word
+      if(word == "element" || word == "attribute" || known.type == "axis_specifier") pushStateStack(state, {type: "xmlconstructor"});
+
+      // if the word is known, return the details of that else just call this a generic 'word'
+      return known ? ret(known.type, known.style, word) :
+                     ret("word", "variable", word);
+    }
+  }
+
+  // handle comments, including nested
+  function tokenComment(stream, state) {
+    var maybeEnd = false, maybeNested = false, nestedCount = 0, ch;
+    while (ch = stream.next()) {
+      if (ch == ")" && maybeEnd) {
+        if(nestedCount > 0)
+          nestedCount--;
+        else {
+          popStateStack(state);
+          break;
+        }
+      }
+      else if(ch == ":" && maybeNested) {
+        nestedCount++;
+      }
+      maybeEnd = (ch == ":");
+      maybeNested = (ch == "(");
+    }
+
+    return ret("comment", "comment");
+  }
+
+  // tokenizer for string literals
+  // optionally pass a tokenizer function to set state.tokenize back to when finished
+  function tokenString(quote, f) {
+    return function(stream, state) {
+      var ch;
+
+      if(isInString(state) && stream.current() == quote) {
+        popStateStack(state);
+        if(f) state.tokenize = f;
+        return ret("string", "string");
+      }
+
+      pushStateStack(state, { type: "string", name: quote, tokenize: tokenString(quote, f) });
+
+      // if we're in a string and in an XML block, allow an embedded code block
+      if(stream.match("{", false) && isInXmlAttributeBlock(state)) {
+        state.tokenize = tokenBase;
+        return ret("string", "string");
+      }
+
+
+      while (ch = stream.next()) {
+        if (ch ==  quote) {
+          popStateStack(state);
+          if(f) state.tokenize = f;
+          break;
+        }
+        else {
+          // if we're in a string and in an XML block, allow an embedded code block in an attribute
+          if(stream.match("{", false) && isInXmlAttributeBlock(state)) {
+            state.tokenize = tokenBase;
+            return ret("string", "string");
+          }
+
+        }
+      }
+
+      return ret("string", "string");
+    };
+  }
+
+  // tokenizer for variables
+  function tokenVariable(stream, state) {
+    var isVariableChar = /[\w\$_-]/;
+
+    // a variable may start with a quoted EQName so if the next character is quote, consume to the next quote
+    if(stream.eat("\"")) {
+      while(stream.next() !== '\"'){};
+      stream.eat(":");
+    } else {
+      stream.eatWhile(isVariableChar);
+      if(!stream.match(":=", false)) stream.eat(":");
+    }
+    stream.eatWhile(isVariableChar);
+    state.tokenize = tokenBase;
+    return ret("variable", "variable");
+  }
+
+  // tokenizer for XML tags
+  function tokenTag(name, isclose) {
+    return function(stream, state) {
+      stream.eatSpace();
+      if(isclose && stream.eat(">")) {
+        popStateStack(state);
+        state.tokenize = tokenBase;
+        return ret("tag", "tag");
+      }
+      // self closing tag without attributes?
+      if(!stream.eat("/"))
+        pushStateStack(state, { type: "tag", name: name, tokenize: tokenBase});
+      if(!stream.eat(">")) {
+        state.tokenize = tokenAttribute;
+        return ret("tag", "tag");
+      }
+      else {
+        state.tokenize = tokenBase;
+      }
+      return ret("tag", "tag");
+    };
+  }
+
+  // tokenizer for XML attributes
+  function tokenAttribute(stream, state) {
+    var ch = stream.next();
+
+    if(ch == "/" && stream.eat(">")) {
+      if(isInXmlAttributeBlock(state)) popStateStack(state);
+      if(isInXmlBlock(state)) popStateStack(state);
+      return ret("tag", "tag");
+    }
+    if(ch == ">") {
+      if(isInXmlAttributeBlock(state)) popStateStack(state);
+      return ret("tag", "tag");
+    }
+    if(ch == "=")
+      return ret("", null);
+    // quoted string
+    if (ch == '"' || ch == "'")
+      return chain(stream, state, tokenString(ch, tokenAttribute));
+
+    if(!isInXmlAttributeBlock(state))
+      pushStateStack(state, { type: "attribute", name: name, tokenize: tokenAttribute});
+
+    stream.eat(/[a-zA-Z_:]/);
+    stream.eatWhile(/[-a-zA-Z0-9_:.]/);
+    stream.eatSpace();
+
+    // the case where the attribute has not value and the tag was closed
+    if(stream.match(">", false) || stream.match("/", false)) {
+      popStateStack(state);
+      state.tokenize = tokenBase;
+    }
+
+    return ret("attribute", "attribute");
+  }
+
+  // handle comments, including nested
+  function tokenXMLComment(stream, state) {
+    var ch;
+    while (ch = stream.next()) {
+      if (ch == "-" && stream.match("->", true)) {
+        state.tokenize = tokenBase;
+        return ret("comment", "comment");
+      }
+    }
+  }
+
+
+  // handle CDATA
+  function tokenCDATA(stream, state) {
+    var ch;
+    while (ch = stream.next()) {
+      if (ch == "]" && stream.match("]", true)) {
+        state.tokenize = tokenBase;
+        return ret("comment", "comment");
+      }
+    }
+  }
+
+  // handle preprocessing instructions
+  function tokenPreProcessing(stream, state) {
+    var ch;
+    while (ch = stream.next()) {
+      if (ch == "?" && stream.match(">", true)) {
+        state.tokenize = tokenBase;
+        return ret("comment", "comment meta");
+      }
+    }
+  }
+
+
+  // functions to test the current context of the state
+  function isInXmlBlock(state) { return isIn(state, "tag"); }
+  function isInXmlAttributeBlock(state) { return isIn(state, "attribute"); }
+  function isInXmlConstructor(state) { return isIn(state, "xmlconstructor"); }
+  function isInString(state) { return isIn(state, "string"); }
+
+  function isEQNameAhead(stream) {
+    // assume we've already eaten a quote (")
+    if(stream.current() === '"')
+      return stream.match(/^[^\"]+\"\:/, false);
+    else if(stream.current() === '\'')
+      return stream.match(/^[^\"]+\'\:/, false);
+    else
+      return false;
+  }
+
+  function isIn(state, type) {
+    return (state.stack.length && state.stack[state.stack.length - 1].type == type);
+  }
+
+  function pushStateStack(state, newState) {
+    state.stack.push(newState);
+  }
+
+  function popStateStack(state) {
+    state.stack.pop();
+    var reinstateTokenize = state.stack.length && state.stack[state.stack.length-1].tokenize;
+    state.tokenize = reinstateTokenize || tokenBase;
+  }
+
+  // the interface for the mode API
+  return {
+    startState: function() {
+      return {
+        tokenize: tokenBase,
+        cc: [],
+        stack: []
+      };
+    },
+
+    token: function(stream, state) {
+      if (stream.eatSpace()) return null;
+      var style = state.tokenize(stream, state);
+      return style;
+    }
+  };
+
+});
+
+CodeMirror.defineMIME("application/xquery", "xquery");
diff --git a/third-party/codemirror-3.15/mode/yaml/index.html b/third-party/codemirror-3.15/mode/yaml/index.html
new file mode 100644 (file)
index 0000000..65e1ea7
--- /dev/null
@@ -0,0 +1,68 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: YAML mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="yaml.js"></script>
+    <style>.CodeMirror { border-top: 1px solid #ddd; border-bottom: 1px solid #ddd; }</style>
+    <link rel="stylesheet" href="../../doc/docs.css">
+  </head>
+  <body>
+    <h1>CodeMirror: YAML mode</h1>
+    <form><textarea id="code" name="code">
+--- # Favorite movies
+- Casablanca
+- North by Northwest
+- The Man Who Wasn't There
+--- # Shopping list
+[milk, pumpkin pie, eggs, juice]
+--- # Indented Blocks, common in YAML data files, use indentation and new lines to separate the key: value pairs
+  name: John Smith
+  age: 33
+--- # Inline Blocks, common in YAML data streams, use commas to separate the key: value pairs between braces
+{name: John Smith, age: 33}
+---
+receipt:     Oz-Ware Purchase Invoice
+date:        2007-08-06
+customer:
+    given:   Dorothy
+    family:  Gale
+
+items:
+    - part_no:   A4786
+      descrip:   Water Bucket (Filled)
+      price:     1.47
+      quantity:  4
+
+    - part_no:   E1628
+      descrip:   High Heeled "Ruby" Slippers
+      size:       8
+      price:     100.27
+      quantity:  1
+
+bill-to:  &id001
+    street: |
+            123 Tornado Alley
+            Suite 16
+    city:   East Centerville
+    state:  KS
+
+ship-to:  *id001
+
+specialDelivery:  >
+    Follow the Yellow Brick
+    Road to the Emerald City.
+    Pay no attention to the
+    man behind the curtain.
+...
+</textarea></form>
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
+    </script>
+
+    <p><strong>MIME types defined:</strong> <code>text/x-yaml</code>.</p>
+
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/yaml/yaml.js b/third-party/codemirror-3.15/mode/yaml/yaml.js
new file mode 100644 (file)
index 0000000..7a095b3
--- /dev/null
@@ -0,0 +1,97 @@
+CodeMirror.defineMode("yaml", function() {
+
+  var cons = ['true', 'false', 'on', 'off', 'yes', 'no'];
+  var keywordRegex = new RegExp("\\b(("+cons.join(")|(")+"))$", 'i');
+
+  return {
+    token: function(stream, state) {
+      var ch = stream.peek();
+      var esc = state.escaped;
+      state.escaped = false;
+      /* comments */
+      if (ch == "#" && (stream.pos == 0 || /\s/.test(stream.string.charAt(stream.pos - 1)))) {
+        stream.skipToEnd(); return "comment";
+      }
+      if (state.literal && stream.indentation() > state.keyCol) {
+        stream.skipToEnd(); return "string";
+      } else if (state.literal) { state.literal = false; }
+      if (stream.sol()) {
+        state.keyCol = 0;
+        state.pair = false;
+        state.pairStart = false;
+        /* document start */
+        if(stream.match(/---/)) { return "def"; }
+        /* document end */
+        if (stream.match(/\.\.\./)) { return "def"; }
+        /* array list item */
+        if (stream.match(/\s*-\s+/)) { return 'meta'; }
+      }
+      /* pairs (associative arrays) -> key */
+      if (!state.pair && stream.match(/^\s*([a-z0-9\._-])+(?=\s*:)/i)) {
+        state.pair = true;
+        state.keyCol = stream.indentation();
+        return "atom";
+      }
+      if (state.pair && stream.match(/^:\s*/)) { state.pairStart = true; return 'meta'; }
+
+      /* inline pairs/lists */
+      if (stream.match(/^(\{|\}|\[|\])/)) {
+        if (ch == '{')
+          state.inlinePairs++;
+        else if (ch == '}')
+          state.inlinePairs--;
+        else if (ch == '[')
+          state.inlineList++;
+        else
+          state.inlineList--;
+        return 'meta';
+      }
+
+      /* list seperator */
+      if (state.inlineList > 0 && !esc && ch == ',') {
+        stream.next();
+        return 'meta';
+      }
+      /* pairs seperator */
+      if (state.inlinePairs > 0 && !esc && ch == ',') {
+        state.keyCol = 0;
+        state.pair = false;
+        state.pairStart = false;
+        stream.next();
+        return 'meta';
+      }
+
+      /* start of value of a pair */
+      if (state.pairStart) {
+        /* block literals */
+        if (stream.match(/^\s*(\||\>)\s*/)) { state.literal = true; return 'meta'; };
+        /* references */
+        if (stream.match(/^\s*(\&|\*)[a-z0-9\._-]+\b/i)) { return 'variable-2'; }
+        /* numbers */
+        if (state.inlinePairs == 0 && stream.match(/^\s*-?[0-9\.\,]+\s?$/)) { return 'number'; }
+        if (state.inlinePairs > 0 && stream.match(/^\s*-?[0-9\.\,]+\s?(?=(,|}))/)) { return 'number'; }
+        /* keywords */
+        if (stream.match(keywordRegex)) { return 'keyword'; }
+      }
+
+      /* nothing found, continue */
+      state.pairStart = false;
+      state.escaped = (ch == '\\');
+      stream.next();
+      return null;
+    },
+    startState: function() {
+      return {
+        pair: false,
+        pairStart: false,
+        keyCol: 0,
+        inlinePairs: 0,
+        inlineList: 0,
+        literal: false,
+        escaped: false
+      };
+    }
+  };
+});
+
+CodeMirror.defineMIME("text/x-yaml", "yaml");
diff --git a/third-party/codemirror-3.15/mode/z80/index.html b/third-party/codemirror-3.15/mode/z80/index.html
new file mode 100644 (file)
index 0000000..133c870
--- /dev/null
@@ -0,0 +1,39 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Z80 assembly mode</title>
+    <link rel="stylesheet" href="../../lib/codemirror.css">
+    <script src="../../lib/codemirror.js"></script>
+    <script src="z80.js"></script>
+    <link rel="stylesheet" href="../../doc/docs.css">
+    <style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
+  </head>
+  <body>
+    <h1>CodeMirror: Z80 assembly mode</h1>
+
+<div><textarea id="code" name="code">
+#include    "ti83plus.inc"
+#define     progStart   $9D95
+.org        progStart-2
+.db         $BB,$6D
+    bcall(_ClrLCDFull)
+    ld  HL, 0
+    ld  (PenCol),   HL
+    ld  HL, Message
+    bcall(_PutS) ; Displays the string
+    bcall(_NewLine)
+    ret
+Message:
+.db         "Hello world!",0
+</textarea></div>
+
+    <script>
+      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
+        lineNumbers: true
+      });
+    </script>
+
+    <p><strong>MIME type defined:</strong> <code>text/x-z80</code>.</p>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/mode/z80/z80.js b/third-party/codemirror-3.15/mode/z80/z80.js
new file mode 100644 (file)
index 0000000..ff43d32
--- /dev/null
@@ -0,0 +1,85 @@
+CodeMirror.defineMode('z80', function() {
+  var keywords1 = /^(exx?|(ld|cp|in)([di]r?)?|pop|push|ad[cd]|cpl|daa|dec|inc|neg|sbc|sub|and|bit|[cs]cf|x?or|res|set|r[lr]c?a?|r[lr]d|s[lr]a|srl|djnz|nop|rst|[de]i|halt|im|ot[di]r|out[di]?)\b/i;
+  var keywords2 = /^(call|j[pr]|ret[in]?)\b/i;
+  var keywords3 = /^b_?(call|jump)\b/i;
+  var variables1 = /^(af?|bc?|c|de?|e|hl?|l|i[xy]?|r|sp)\b/i;
+  var variables2 = /^(n?[zc]|p[oe]?|m)\b/i;
+  var errors = /^([hl][xy]|i[xy][hl]|slia|sll)\b/i;
+  var numbers = /^([\da-f]+h|[0-7]+o|[01]+b|\d+)\b/i;
+
+  return {
+    startState: function() {
+      return {context: 0};
+    },
+    token: function(stream, state) {
+      if (!stream.column())
+        state.context = 0;
+
+      if (stream.eatSpace())
+        return null;
+
+      var w;
+
+      if (stream.eatWhile(/\w/)) {
+        w = stream.current();
+
+        if (stream.indentation()) {
+          if (state.context == 1 && variables1.test(w))
+            return 'variable-2';
+
+          if (state.context == 2 && variables2.test(w))
+            return 'variable-3';
+
+          if (keywords1.test(w)) {
+            state.context = 1;
+            return 'keyword';
+          } else if (keywords2.test(w)) {
+            state.context = 2;
+            return 'keyword';
+          } else if (keywords3.test(w)) {
+            state.context = 3;
+            return 'keyword';
+          }
+
+          if (errors.test(w))
+            return 'error';
+        } else if (numbers.test(w)) {
+          return 'number';
+        } else {
+          return null;
+        }
+      } else if (stream.eat(';')) {
+        stream.skipToEnd();
+        return 'comment';
+      } else if (stream.eat('"')) {
+        while (w = stream.next()) {
+          if (w == '"')
+            break;
+
+          if (w == '\\')
+            stream.next();
+        }
+        return 'string';
+      } else if (stream.eat('\'')) {
+        if (stream.match(/\\?.'/))
+          return 'number';
+      } else if (stream.eat('.') || stream.sol() && stream.eat('#')) {
+        state.context = 4;
+
+        if (stream.eatWhile(/\w/))
+          return 'def';
+      } else if (stream.eat('$')) {
+        if (stream.eatWhile(/[\da-f]/i))
+          return 'number';
+      } else if (stream.eat('%')) {
+        if (stream.eatWhile(/[01]/))
+          return 'number';
+      } else {
+        stream.next();
+      }
+      return null;
+    }
+  };
+});
+
+CodeMirror.defineMIME("text/x-z80", "z80");
diff --git a/third-party/codemirror-3.15/package.json b/third-party/codemirror-3.15/package.json
new file mode 100644 (file)
index 0000000..7fc9070
--- /dev/null
@@ -0,0 +1,19 @@
+{
+    "name": "codemirror",
+    "version":"3.15.0",
+    "main": "lib/codemirror.js",
+    "description": "In-browser code editing made bearable",
+    "licenses": [{"type": "MIT",
+                  "url": "http://codemirror.net/LICENSE"}],
+    "directories": {"lib": "./lib"},
+    "scripts": {"test": "node ./test/run.js"},
+    "devDependencies": {"node-static": "0.6.0"},
+    "bugs": "http://github.com/marijnh/CodeMirror/issues",
+    "keywords": ["JavaScript", "CodeMirror", "Editor"],
+    "homepage": "http://codemirror.net",
+    "maintainers":[{"name": "Marijn Haverbeke",
+                    "email": "marijnh@gmail.com",
+                    "web": "http://marijnhaverbeke.nl"}],
+    "repository": {"type": "git",
+                   "url": "http://marijnhaverbeke.nl/git/codemirror"}
+}
diff --git a/third-party/codemirror-3.15/test/comment_test.js b/third-party/codemirror-3.15/test/comment_test.js
new file mode 100644 (file)
index 0000000..7ab3127
--- /dev/null
@@ -0,0 +1,51 @@
+namespace = "comment_";
+
+(function() {
+  function test(name, mode, run, before, after) {
+    return testCM(name, function(cm) {
+      run(cm);
+      eq(cm.getValue(), after);
+    }, {value: before, mode: mode});
+  }
+
+  var simpleProg = "function foo() {\n  return bar;\n}";
+
+  test("block", "javascript", function(cm) {
+    cm.blockComment(Pos(0, 3), Pos(3, 0), {blockCommentLead: " *"});
+  }, simpleProg + "\n", "/* function foo() {\n *   return bar;\n * }\n */");
+
+  test("blockToggle", "javascript", function(cm) {
+    cm.blockComment(Pos(0, 3), Pos(2, 0), {blockCommentLead: " *"});
+    cm.uncomment(Pos(0, 3), Pos(2, 0), {blockCommentLead: " *"});
+  }, simpleProg, simpleProg);
+
+  test("line", "javascript", function(cm) {
+    cm.lineComment(Pos(1, 1), Pos(1, 1));
+  }, simpleProg, "function foo() {\n//   return bar;\n}");
+
+  test("lineToggle", "javascript", function(cm) {
+    cm.lineComment(Pos(0, 0), Pos(2, 1));
+    cm.uncomment(Pos(0, 0), Pos(2, 1));
+  }, simpleProg, simpleProg);
+
+  test("fallbackToBlock", "css", function(cm) {
+    cm.lineComment(Pos(0, 0), Pos(2, 1));
+  }, "html {\n  border: none;\n}", "/* html {\n  border: none;\n} */");
+
+  test("fallbackToLine", "ruby", function(cm) {
+    cm.blockComment(Pos(0, 0), Pos(1));
+  }, "def blah()\n  return hah\n", "# def blah()\n#   return hah\n");
+
+  test("commentRange", "javascript", function(cm) {
+    cm.blockComment(Pos(1, 2), Pos(1, 13), {fullLines: false});
+  }, simpleProg, "function foo() {\n  /*return bar;*/\n}");
+
+  test("indented", "javascript", function(cm) {
+    cm.lineComment(Pos(1, 0), Pos(2), {indent: true});
+  }, simpleProg, "function foo() {\n  // return bar;\n  // }");
+
+  test("singleEmptyLine", "javascript", function(cm) {
+    cm.setCursor(1);
+    cm.execCommand("toggleComment");
+  }, "a;\n\nb;", "a;\n// \nb;");
+})();
diff --git a/third-party/codemirror-3.15/test/doc_test.js b/third-party/codemirror-3.15/test/doc_test.js
new file mode 100644 (file)
index 0000000..3e04e15
--- /dev/null
@@ -0,0 +1,329 @@
+(function() {
+  // A minilanguage for instantiating linked CodeMirror instances and Docs
+  function instantiateSpec(spec, place, opts) {
+    var names = {}, pos = 0, l = spec.length, editors = [];
+    while (spec) {
+      var m = spec.match(/^(\w+)(\*?)(?:='([^\']*)'|<(~?)(\w+)(?:\/(\d+)-(\d+))?)\s*/);
+      var name = m[1], isDoc = m[2], cur;
+      if (m[3]) {
+        cur = isDoc ? CodeMirror.Doc(m[3]) : CodeMirror(place, clone(opts, {value: m[3]}));
+      } else {
+        var other = m[5];
+        if (!names.hasOwnProperty(other)) {
+          names[other] = editors.length;
+          editors.push(CodeMirror(place, opts));
+        }
+        var doc = editors[names[other]].linkedDoc({
+          sharedHist: !m[4],
+          from: m[6] ? Number(m[6]) : null,
+          to: m[7] ? Number(m[7]) : null
+        });
+        cur = isDoc ? doc : CodeMirror(place, clone(opts, {value: doc}));
+      }
+      names[name] = editors.length;
+      editors.push(cur);
+      spec = spec.slice(m[0].length);
+    }
+    return editors;
+  }
+
+  function clone(obj, props) {
+    if (!obj) return;
+    clone.prototype = obj;
+    var inst = new clone();
+    if (props) for (var n in props) if (props.hasOwnProperty(n))
+      inst[n] = props[n];
+    return inst;
+  }
+
+  function eqAll(val) {
+    var end = arguments.length, msg = null;
+    if (typeof arguments[end-1] == "string")
+      msg = arguments[--end];
+    if (i == end) throw new Error("No editors provided to eqAll");
+    for (var i = 1; i < end; ++i)
+      eq(arguments[i].getValue(), val, msg)
+  }
+
+  function testDoc(name, spec, run, opts, expectFail) {
+    if (!opts) opts = {};
+
+    return test("doc_" + name, function() {
+      var place = document.getElementById("testground");
+      var editors = instantiateSpec(spec, place, opts);
+      var successful = false;
+
+      try {
+        run.apply(null, editors);
+        successful = true;
+      } finally {
+        if ((debug && !successful) || verbose) {
+          place.style.visibility = "visible";
+        } else {
+          for (var i = 0; i < editors.length; ++i)
+            if (editors[i] instanceof CodeMirror)
+              place.removeChild(editors[i].getWrapperElement());
+        }
+      }
+    }, expectFail);
+  }
+
+  var ie_lt8 = /MSIE [1-7]\b/.test(navigator.userAgent);
+
+  function testBasic(a, b) {
+    eqAll("x", a, b);
+    a.setValue("hey");
+    eqAll("hey", a, b);
+    b.setValue("wow");
+    eqAll("wow", a, b);
+    a.replaceRange("u\nv\nw", Pos(0, 3));
+    b.replaceRange("i", Pos(0, 4));
+    b.replaceRange("j", Pos(2, 1));
+    eqAll("wowui\nv\nwj", a, b);
+  }
+
+  testDoc("basic", "A='x' B<A", testBasic);
+  testDoc("basicSeparate", "A='x' B<~A", testBasic);
+
+  testDoc("sharedHist", "A='ab\ncd\nef' B<A", function(a, b) {
+    a.replaceRange("x", Pos(0));
+    b.replaceRange("y", Pos(1));
+    a.replaceRange("z", Pos(2));
+    eqAll("abx\ncdy\nefz", a, b);
+    a.undo();
+    a.undo();
+    eqAll("abx\ncd\nef", a, b);
+    a.redo();
+    eqAll("abx\ncdy\nef", a, b);
+    b.redo();
+    eqAll("abx\ncdy\nefz", a, b);
+    a.undo(); b.undo(); a.undo(); a.undo();
+    eqAll("ab\ncd\nef", a, b);
+  }, null, ie_lt8);
+
+  testDoc("undoIntact", "A='ab\ncd\nef' B<~A", function(a, b) {
+    a.replaceRange("x", Pos(0));
+    b.replaceRange("y", Pos(1));
+    a.replaceRange("z", Pos(2));
+    a.replaceRange("q", Pos(0));
+    eqAll("abxq\ncdy\nefz", a, b);
+    a.undo();
+    a.undo();
+    eqAll("abx\ncdy\nef", a, b);
+    b.undo();
+    eqAll("abx\ncd\nef", a, b);
+    a.redo();
+    eqAll("abx\ncd\nefz", a, b);
+    a.redo();
+    eqAll("abxq\ncd\nefz", a, b);
+    a.undo(); a.undo(); a.undo(); a.undo();
+    eqAll("ab\ncd\nef", a, b);
+    b.redo();
+    eqAll("ab\ncdy\nef", a, b);
+  });
+
+  testDoc("undoConflict", "A='ab\ncd\nef' B<~A", function(a, b) {
+    a.replaceRange("x", Pos(0));
+    a.replaceRange("z", Pos(2));
+    // This should clear the first undo event in a, but not the second
+    b.replaceRange("y", Pos(0));
+    a.undo(); a.undo();
+    eqAll("abxy\ncd\nef", a, b);
+    a.replaceRange("u", Pos(2));
+    a.replaceRange("v", Pos(0));
+    // This should clear both events in a
+    b.replaceRange("w", Pos(0));
+    a.undo(); a.undo();
+    eqAll("abxyvw\ncd\nefu", a, b);
+  });
+
+  testDoc("doubleRebase", "A='ab\ncd\nef\ng' B<~A C<B", function(a, b, c) {
+    c.replaceRange("u", Pos(3));
+    a.replaceRange("", Pos(0, 0), Pos(1, 0));
+    c.undo();
+    eqAll("cd\nef\ng", a, b, c);
+  });
+
+  testDoc("undoUpdate", "A='ab\ncd\nef' B<~A", function(a, b) {
+    a.replaceRange("x", Pos(2));
+    b.replaceRange("u\nv\nw\n", Pos(0, 0));
+    a.undo();
+    eqAll("u\nv\nw\nab\ncd\nef", a, b);
+    a.redo();
+    eqAll("u\nv\nw\nab\ncd\nefx", a, b);
+    a.undo();
+    eqAll("u\nv\nw\nab\ncd\nef", a, b);
+    b.undo();
+    a.redo();
+    eqAll("ab\ncd\nefx", a, b);
+    a.undo();
+    eqAll("ab\ncd\nef", a, b);
+  });
+
+  testDoc("undoKeepRanges", "A='abcdefg' B<A", function(a, b) {
+    var m = a.markText(Pos(0, 1), Pos(0, 3), {className: "foo"});
+    b.replaceRange("x", Pos(0, 0));
+    eqPos(m.find().from, Pos(0, 2));
+    b.replaceRange("yzzy", Pos(0, 1), Pos(0));
+    eq(m.find(), null);
+    b.undo();
+    eqPos(m.find().from, Pos(0, 2));
+    b.undo();
+    eqPos(m.find().from, Pos(0, 1));
+  });
+
+  testDoc("longChain", "A='uv' B<A C<B D<C", function(a, b, c, d) {
+    a.replaceSelection("X");
+    eqAll("Xuv", a, b, c, d);
+    d.replaceRange("Y", Pos(0));
+    eqAll("XuvY", a, b, c, d);
+  });
+
+  testDoc("broadCast", "B<A C<A D<A E<A", function(a, b, c, d, e) {
+    b.setValue("uu");
+    eqAll("uu", a, b, c, d, e);
+    a.replaceRange("v", Pos(0, 1));
+    eqAll("uvu", a, b, c, d, e);
+  });
+
+  // A and B share a history, C and D share a separate one
+  testDoc("islands", "A='x\ny\nz' B<A C<~A D<C", function(a, b, c, d) {
+    a.replaceRange("u", Pos(0));
+    d.replaceRange("v", Pos(2));
+    b.undo();
+    eqAll("x\ny\nzv", a, b, c, d);
+    c.undo();
+    eqAll("x\ny\nz", a, b, c, d);
+    a.redo();
+    eqAll("xu\ny\nz", a, b, c, d);
+    d.redo();
+    eqAll("xu\ny\nzv", a, b, c, d);
+  });
+
+  testDoc("unlink", "B<A C<A D<B", function(a, b, c, d) {
+    a.setValue("hi");
+    b.unlinkDoc(a);
+    d.setValue("aye");
+    eqAll("hi", a, c);
+    eqAll("aye", b, d);
+    a.setValue("oo");
+    eqAll("oo", a, c);
+    eqAll("aye", b, d);
+  });
+
+  testDoc("bareDoc", "A*='foo' B*<A C<B", function(a, b, c) {
+    is(a instanceof CodeMirror.Doc);
+    is(b instanceof CodeMirror.Doc);
+    is(c instanceof CodeMirror);
+    eqAll("foo", a, b, c);
+    a.replaceRange("hey", Pos(0, 0), Pos(0));
+    c.replaceRange("!", Pos(0));
+    eqAll("hey!", a, b, c);
+    b.unlinkDoc(a);
+    b.setValue("x");
+    eqAll("x", b, c);
+    eqAll("hey!", a);
+  });
+
+  testDoc("swapDoc", "A='a' B*='b' C<A", function(a, b, c) {
+    var d = a.swapDoc(b);
+    d.setValue("x");
+    eqAll("x", c, d);
+    eqAll("b", a, b);
+  });
+
+  testDoc("docKeepsScroll", "A='x' B*='y'", function(a, b) {
+    addDoc(a, 200, 200);
+    a.scrollIntoView(Pos(199, 200));
+    var c = a.swapDoc(b);
+    a.swapDoc(c);
+    var pos = a.getScrollInfo();
+    is(pos.left > 0, "not at left");
+    is(pos.top > 0, "not at top");
+  });
+
+  testDoc("copyDoc", "A='u'", function(a) {
+    var copy = a.getDoc().copy(true);
+    a.setValue("foo");
+    copy.setValue("bar");
+    var old = a.swapDoc(copy);
+    eq(a.getValue(), "bar");
+    a.undo();
+    eq(a.getValue(), "u");
+    a.swapDoc(old);
+    eq(a.getValue(), "foo");
+    eq(old.historySize().undo, 1);
+    eq(old.copy(false).historySize().undo, 0);
+  });
+
+  testDoc("docKeepsMode", "A='1+1'", function(a) {
+    var other = CodeMirror.Doc("hi", "text/x-markdown");
+    a.setOption("mode", "text/javascript");
+    var old = a.swapDoc(other);
+    eq(a.getOption("mode"), "text/x-markdown");
+    eq(a.getMode().name, "markdown");
+    a.swapDoc(old);
+    eq(a.getOption("mode"), "text/javascript");
+    eq(a.getMode().name, "javascript");
+  });
+
+  testDoc("subview", "A='1\n2\n3\n4\n5' B<~A/1-3", function(a, b) {
+    eq(b.getValue(), "2\n3");
+    eq(b.firstLine(), 1);
+    b.setCursor(Pos(4));
+    eqPos(b.getCursor(), Pos(2, 1));
+    a.replaceRange("-1\n0\n", Pos(0, 0));
+    eq(b.firstLine(), 3);
+    eqPos(b.getCursor(), Pos(4, 1));
+    a.undo();
+    eqPos(b.getCursor(), Pos(2, 1));
+    b.replaceRange("oyoy\n", Pos(2, 0));
+    eq(a.getValue(), "1\n2\noyoy\n3\n4\n5");
+    b.undo();
+    eq(a.getValue(), "1\n2\n3\n4\n5");
+  });
+
+  testDoc("subviewEditOnBoundary", "A='11\n22\n33\n44\n55' B<~A/1-4", function(a, b) {
+    a.replaceRange("x\nyy\nz", Pos(0, 1), Pos(2, 1));
+    eq(b.firstLine(), 2);
+    eq(b.lineCount(), 2);
+    eq(b.getValue(), "z3\n44");
+    a.replaceRange("q\nrr\ns", Pos(3, 1), Pos(4, 1));
+    eq(b.firstLine(), 2);
+    eq(b.getValue(), "z3\n4q");
+    eq(a.getValue(), "1x\nyy\nz3\n4q\nrr\ns5");
+    a.execCommand("selectAll");
+    a.replaceSelection("!");
+    eqAll("!", a, b);
+  });
+
+
+  testDoc("sharedMarker", "A='ab\ncd\nef\ngh' B<A C<~A/1-2", function(a, b, c) {
+    var mark = b.markText(Pos(0, 1), Pos(3, 1),
+                          {className: "cm-searching", shared: true});
+    var found = a.findMarksAt(Pos(0, 2));
+    eq(found.length, 1);
+    eq(found[0], mark);
+    eq(c.findMarksAt(Pos(1, 1)).length, 1);
+    eqPos(mark.find().from, Pos(0, 1));
+    eqPos(mark.find().to, Pos(3, 1));
+    b.replaceRange("x\ny\n", Pos(0, 0));
+    eqPos(mark.find().from, Pos(2, 1));
+    eqPos(mark.find().to, Pos(5, 1));
+    var cleared = 0;
+    CodeMirror.on(mark, "clear", function() {++cleared;});
+    b.operation(function(){mark.clear();});
+    eq(a.findMarksAt(Pos(3, 1)).length, 0);
+    eq(b.findMarksAt(Pos(3, 1)).length, 0);
+    eq(c.findMarksAt(Pos(3, 1)).length, 0);
+    eq(mark.find(), null);
+    eq(cleared, 1);
+  });
+
+  testDoc("undoInSubview", "A='line 0\nline 1\nline 2\nline 3\nline 4' B<A/1-4", function(a, b) {
+    b.replaceRange("x", Pos(2, 0));
+    a.undo();
+    eq(a.getValue(), "line 0\nline 1\nline 2\nline 3\nline 4");
+    eq(b.getValue(), "line 1\nline 2\nline 3");
+  });
+})();
diff --git a/third-party/codemirror-3.15/test/driver.js b/third-party/codemirror-3.15/test/driver.js
new file mode 100644 (file)
index 0000000..8c32ec7
--- /dev/null
@@ -0,0 +1,139 @@
+var tests = [], debug = null, debugUsed = new Array(), allNames = [];
+
+function Failure(why) {this.message = why;}
+Failure.prototype.toString = function() { return this.message; };
+
+function indexOf(collection, elt) {
+  if (collection.indexOf) return collection.indexOf(elt);
+  for (var i = 0, e = collection.length; i < e; ++i)
+    if (collection[i] == elt) return i;
+  return -1;
+}
+
+function test(name, run, expectedFail) {
+  // Force unique names
+  var originalName = name;
+  var i = 2; // Second function would be NAME_2
+  while (indexOf(allNames, name) !== -1){
+    name = originalName + "_" + i;
+    i++;
+  }
+  allNames.push(name);
+  // Add test
+  tests.push({name: name, func: run, expectedFail: expectedFail});
+  return name;
+}
+var namespace = "";
+function testCM(name, run, opts, expectedFail) {
+  return test(namespace + name, function() {
+    var place = document.getElementById("testground"), cm = window.cm = CodeMirror(place, opts);
+    var successful = false;
+    try {
+      run(cm);
+      successful = true;
+    } finally {
+      if ((debug && !successful) || verbose) {
+        place.style.visibility = "visible";
+      } else {
+        place.removeChild(cm.getWrapperElement());
+      }
+    }
+  }, expectedFail);
+}
+
+function runTests(callback) {
+  if (debug) {
+    if (indexOf(debug, "verbose") === 0) {
+      verbose = true;
+      debug.splice(0, 1);
+    }
+    if (debug.length < 1) {
+      debug = null;
+    }
+  }
+  var totalTime = 0;
+  function step(i) {
+    if (i === tests.length){
+      running = false;
+      return callback("done");
+    }
+    var test = tests[i], expFail = test.expectedFail, startTime = +new Date;
+    if (debug !== null) {
+      var debugIndex = indexOf(debug, test.name);
+      if (debugIndex !== -1) {
+        // Remove from array for reporting incorrect tests later
+        debug.splice(debugIndex, 1);
+      } else {
+        var wildcardName = test.name.split("_")[0] + "_*";
+        debugIndex = indexOf(debug, wildcardName);
+        if (debugIndex !== -1) {
+          // Remove from array for reporting incorrect tests later
+          debug.splice(debugIndex, 1);
+          debugUsed.push(wildcardName);
+        } else {
+          debugIndex = indexOf(debugUsed, wildcardName);
+          if (debugIndex == -1) return step(i + 1);
+        }
+      }
+    }
+    var threw = false;
+    try {
+      var message = test.func();
+    } catch(e) {
+      threw = true;
+      if (expFail) callback("expected", test.name);
+      else if (e instanceof Failure) callback("fail", test.name, e.message);
+      else {
+        var pos = /\bat .*?([^\/:]+):(\d+):/.exec(e.stack);
+        callback("error", test.name, e.toString() + (pos ? " (" + pos[1] + ":" + pos[2] + ")" : ""));
+      }
+    }
+    if (!threw) {
+      if (expFail) callback("fail", test.name, message || "expected failure, but succeeded");
+      else callback("ok", test.name, message);
+    }
+    if (!quit) { // Run next test
+      var delay = 0;
+      totalTime += (+new Date) - startTime;
+      if (totalTime > 500){
+        totalTime = 0;
+        delay = 50;
+      }
+      setTimeout(function(){step(i + 1);}, delay);
+    } else { // Quit tests
+      running = false;
+      return null;
+    }
+  }
+  step(0);
+}
+
+function label(str, msg) {
+  if (msg) return str + " (" + msg + ")";
+  return str;
+}
+function eq(a, b, msg) {
+  if (a != b) throw new Failure(label(a + " != " + b, msg));
+}
+function eqPos(a, b, msg) {
+  function str(p) { return "{line:" + p.line + ",ch:" + p.ch + "}"; }
+  if (a == b) return;
+  if (a == null) throw new Failure(label("comparing null to " + str(b), msg));
+  if (b == null) throw new Failure(label("comparing " + str(a) + " to null", msg));
+  if (a.line != b.line || a.ch != b.ch) throw new Failure(label(str(a) + " != " + str(b), msg));
+}
+function is(a, msg) {
+  if (!a) throw new Failure(label("assertion failed", msg));
+}
+
+function countTests() {
+  if (!debug) return tests.length;
+  var sum = 0;
+  for (var i = 0; i < tests.length; ++i) {
+    var name = tests[i].name;
+    if (indexOf(debug, name) != -1 ||
+        indexOf(debug, name.split("_")[0] + "_*") != -1)
+      ++sum;
+  }
+  return sum;
+}
diff --git a/third-party/codemirror-3.15/test/emacs_test.js b/third-party/codemirror-3.15/test/emacs_test.js
new file mode 100644 (file)
index 0000000..ab18241
--- /dev/null
@@ -0,0 +1,135 @@
+(function() {
+  "use strict";
+
+  var Pos = CodeMirror.Pos;
+  namespace = "emacs_";
+
+  var eventCache = {};
+  function fakeEvent(keyName) {
+    var event = eventCache[key];
+    if (event) return event;
+
+    var ctrl, shift, alt;
+    var key = keyName.replace(/\w+-/g, function(type) {
+      if (type == "Ctrl-") ctrl = true;
+      else if (type == "Alt-") alt = true;
+      else if (type == "Shift-") shift = true;
+      return "";
+    });
+    var code;
+    for (var c in CodeMirror.keyNames)
+      if (CodeMirror.keyNames[c] == key) { code = c; break; }
+    if (c == null) throw new Error("Unknown key: " + key);
+
+    return eventCache[keyName] = {
+      type: "keydown", keyCode: code, ctrlKey: ctrl, shiftKey: shift, altKey: alt,
+      preventDefault: function(){}, stopPropagation: function(){}
+    };
+  }
+
+  function sim(name, start /*, actions... */) {
+    var keys = Array.prototype.slice.call(arguments, 2);
+    testCM(name, function(cm) {
+      for (var i = 0; i < keys.length; ++i) {
+        var cur = keys[i];
+        if (cur instanceof Pos) cm.setCursor(cur);
+        else if (cur.call) cur(cm);
+        else cm.triggerOnKeyDown(fakeEvent(cur));
+      }
+    }, {keyMap: "emacs", value: start, mode: "javascript"});
+  }
+
+  function at(line, ch) { return function(cm) { eqPos(cm.getCursor(), Pos(line, ch)); }; }
+  function txt(str) { return function(cm) { eq(cm.getValue(), str); }; }
+
+  sim("motionHSimple", "abc", "Ctrl-F", "Ctrl-F", "Ctrl-B", at(0, 1));
+  sim("motionHMulti", "abcde",
+      "Ctrl-4", "Ctrl-F", at(0, 4), "Ctrl--", "Ctrl-2", "Ctrl-F", at(0, 2),
+      "Ctrl-5", "Ctrl-B", at(0, 0));
+
+  sim("motionHWord", "abc. def ghi",
+      "Alt-F", at(0, 3), "Alt-F", at(0, 8),
+      "Ctrl-B", "Alt-B", at(0, 5), "Alt-B", at(0, 0));
+  sim("motionHWordMulti", "abc. def ghi ",
+      "Ctrl-3", "Alt-F", at(0, 12), "Ctrl-2", "Alt-B", at(0, 5),
+      "Ctrl--", "Alt-B", at(0, 8));
+
+  sim("motionVSimple", "a\nb\nc\n", "Ctrl-N", "Ctrl-N", "Ctrl-P", at(1, 0));
+  sim("motionVMulti", "a\nb\nc\nd\ne\n",
+      "Ctrl-2", "Ctrl-N", at(2, 0), "Ctrl-F", "Ctrl--", "Ctrl-N", at(1, 1),
+      "Ctrl--", "Ctrl-3", "Ctrl-P", at(4, 1));
+
+  sim("killYank", "abc\ndef\nghi",
+      "Ctrl-F", "Ctrl-Space", "Ctrl-N", "Ctrl-N", "Ctrl-W", "Ctrl-E", "Ctrl-Y",
+      txt("ahibc\ndef\ng"));
+  sim("killRing", "abcdef",
+      "Ctrl-Space", "Ctrl-F", "Ctrl-W", "Ctrl-Space", "Ctrl-F", "Ctrl-W",
+      "Ctrl-Y", "Alt-Y",
+      txt("acdef"));
+  sim("copyYank", "abcd",
+      "Ctrl-Space", "Ctrl-E", "Alt-W", "Ctrl-Y",
+      txt("abcdabcd"));
+
+  sim("killLineSimple", "foo\nbar", "Ctrl-F", "Ctrl-K", txt("f\nbar"));
+  sim("killLineEmptyLine", "foo\n  \nbar", "Ctrl-N", "Ctrl-K", txt("foo\nbar"));
+  sim("killLineMulti", "foo\nbar\nbaz",
+      "Ctrl-F", "Ctrl-F", "Ctrl-K", "Ctrl-K", "Ctrl-K", "Ctrl-A", "Ctrl-Y",
+      txt("o\nbarfo\nbaz"));
+
+  sim("moveByParagraph", "abc\ndef\n\n\nhij\nklm\n\n",
+      "Ctrl-F", "Ctrl-Down", at(2, 0), "Ctrl-Down", at(6, 0),
+      "Ctrl-N", "Ctrl-Up", at(3, 0), "Ctrl-Up", at(0, 0),
+      Pos(1, 2), "Ctrl-Down", at(2, 0), Pos(4, 2), "Ctrl-Up", at(3, 0));
+  sim("moveByParagraphMulti", "abc\n\ndef\n\nhij\n\nklm",
+      "Ctrl-U", "2", "Ctrl-Down", at(3, 0),
+      "Shift-Alt-.", "Ctrl-3", "Ctrl-Up", at(1, 0));
+
+  sim("moveBySentence", "sentence one! sentence\ntwo\n\nparagraph two",
+      "Alt-E", at(0, 13), "Alt-E", at(1, 3), "Ctrl-F", "Alt-A", at(0, 13));
+
+  sim("moveByExpr", "function foo(a, b) {}",
+      "Ctrl-Alt-F", at(0, 8), "Ctrl-Alt-F", at(0, 12), "Ctrl-Alt-F", at(0, 18),
+      "Ctrl-Alt-B", at(0, 12), "Ctrl-Alt-B", at(0, 9));
+  sim("moveByExprMulti", "foo bar baz bug",
+      "Ctrl-2", "Ctrl-Alt-F", at(0, 7),
+      "Ctrl--", "Ctrl-Alt-F", at(0, 4),
+      "Ctrl--", "Ctrl-2", "Ctrl-Alt-B", at(0, 11));
+  sim("delExpr", "var x = [\n  a,\n  b\n  c\n];",
+      Pos(0, 8), "Ctrl-Alt-K", txt("var x = ;"), "Ctrl-/",
+      Pos(4, 1), "Ctrl-Alt-Backspace", txt("var x = ;"));
+  sim("delExprMulti", "foo bar baz",
+      "Ctrl-2", "Ctrl-Alt-K", txt(" baz"),
+      "Ctrl-/", "Ctrl-E", "Ctrl-2", "Ctrl-Alt-Backspace", txt("foo "));
+
+  sim("justOneSpace", "hi      bye  ",
+      Pos(0, 4), "Alt-Space", txt("hi bye  "),
+      Pos(0, 4), "Alt-Space", txt("hi b ye  "),
+      "Ctrl-A", "Alt-Space", "Ctrl-E", "Alt-Space", txt(" hi b ye "));
+
+  sim("openLine", "foo bar", "Alt-F", "Ctrl-O", txt("foo\n bar"))
+
+  sim("transposeChar", "abcd\n\ne",
+      "Ctrl-F", "Ctrl-T", "Ctrl-T", txt("bcad\n\ne"), at(0, 3),
+      "Ctrl-F", "Ctrl-T", "Ctrl-T", "Ctrl-T", txt("bcda\n\ne"), at(0, 4),
+      "Ctrl-F", "Ctrl-T", txt("bcd\na\ne"), at(1, 1));
+
+  sim("manipWordCase", "foo BAR bAZ",
+      "Alt-C", "Alt-L", "Alt-U", txt("Foo bar BAZ"),
+      "Ctrl-A", "Alt-U", "Alt-L", "Alt-C", txt("FOO bar Baz"));
+  sim("manipWordCaseMulti", "foo Bar bAz",
+      "Ctrl-2", "Alt-U", txt("FOO BAR bAz"),
+      "Ctrl-A", "Ctrl-3", "Alt-C", txt("Foo Bar Baz"));
+
+  sim("upExpr", "foo {\n  bar[];\n  baz(blah);\n}",
+      Pos(2, 7), "Ctrl-Alt-U", at(2, 5), "Ctrl-Alt-U", at(0, 4));
+  sim("transposeExpr", "do foo[bar] dah",
+      Pos(0, 6), "Ctrl-Alt-T", txt("do [bar]foo dah"));
+
+  testCM("save", function(cm) {
+    var saved = false;
+    CodeMirror.commands.save = function(cm) { saved = cm.getValue(); };
+    cm.triggerOnKeyDown(fakeEvent("Ctrl-X"));
+    cm.triggerOnKeyDown(fakeEvent("Ctrl-S"));
+    is(saved, "hi");
+  }, {value: "hi", keyMap: "emacs"});
+})();
diff --git a/third-party/codemirror-3.15/test/index.html b/third-party/codemirror-3.15/test/index.html
new file mode 100644 (file)
index 0000000..5ead383
--- /dev/null
@@ -0,0 +1,196 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>CodeMirror: Test Suite</title>
+    <link rel="stylesheet" href="../lib/codemirror.css">
+    <link rel="stylesheet" href="../doc/docs.css">
+    <link rel="stylesheet" href="mode_test.css">
+    <script src="../lib/codemirror.js"></script>
+    <script src="../addon/mode/overlay.js"></script>
+    <script src="../addon/mode/multiplex.js"></script>
+    <script src="../addon/search/searchcursor.js"></script>
+    <script src="../addon/dialog/dialog.js"></script>
+    <script src="../addon/edit/matchbrackets.js"></script>
+    <script src="../addon/comment/comment.js"></script>
+    <script src="../mode/javascript/javascript.js"></script>
+    <script src="../mode/xml/xml.js"></script>
+    <script src="../keymap/vim.js"></script>
+    <script src="../keymap/emacs.js"></script>
+
+    <style type="text/css">
+      .ok {color: #090;}
+      .fail {color: #e00;}
+      .error {color: #c90;}
+      .done {font-weight: bold;}
+      #progress {
+        background: #45d;
+        color: white;
+        text-shadow: 0 0 1px #45d, 0 0 2px #45d, 0 0 3px #45d;
+        font-weight: bold;
+        white-space: pre;
+      }
+      #testground {
+        visibility: hidden;
+      }
+      #testground.offscreen {
+        visibility: visible;
+        position: absolute;
+        left: -10000px;
+        top: -10000px;
+      }
+      .CodeMirror { border: 1px solid black; }
+    </style>
+  </head>
+  <body>
+    <h1>CodeMirror: Test Suite</h1>
+
+    <p>A limited set of programmatic sanity tests for CodeMirror.</p>
+
+    <div style="border: 1px solid black; padding: 1px; max-width: 700px;">
+      <div style="width: 0px;" id=progress><div style="padding: 3px;">Ran <span id="progress_ran">0</span><span id="progress_total"> of 0</span> tests</div></div>
+    </div>
+    <p id=status>Please enable JavaScript...</p>
+    <div id=output></div>
+
+    <div id=testground></div>
+
+    <script src="driver.js"></script>
+    <script src="test.js"></script>
+    <script src="doc_test.js"></script>
+    <script src="comment_test.js"></script>
+    <script src="mode_test.js"></script>
+    <script src="../mode/javascript/test.js"></script>
+    <script src="../mode/css/css.js"></script>
+    <script src="../mode/css/test.js"></script>
+    <script src="../mode/css/scss_test.js"></script>
+    <script src="../mode/xml/xml.js"></script>
+    <script src="../mode/htmlmixed/htmlmixed.js"></script>
+    <script src="../mode/ruby/ruby.js"></script>
+    <script src="../mode/haml/haml.js"></script>
+    <script src="../mode/haml/test.js"></script>
+    <script src="../mode/markdown/markdown.js"></script>
+    <script src="../mode/markdown/test.js"></script>
+    <script src="../mode/gfm/gfm.js"></script>
+    <script src="../mode/gfm/test.js"></script>
+    <script src="../mode/stex/stex.js"></script>
+    <script src="../mode/stex/test.js"></script>
+    <script src="../mode/xquery/xquery.js"></script>
+    <script src="../mode/xquery/test.js"></script>
+    <script src="../addon/mode/multiplex_test.js"></script>
+    <script src="vim_test.js"></script>
+    <script src="emacs_test.js"></script>
+    <script>
+      window.onload = runHarness;
+      CodeMirror.on(window, 'hashchange', runHarness);
+
+      function esc(str) {
+        return str.replace(/[<&]/, function(ch) { return ch == "<" ? "&lt;" : "&amp;"; });
+      }
+
+      var output = document.getElementById("output"),
+          progress = document.getElementById("progress"),
+          progressRan = document.getElementById("progress_ran").childNodes[0],
+          progressTotal = document.getElementById("progress_total").childNodes[0];
+      var count = 0,
+          failed = 0,
+          bad = "",
+          running = false, // Flag that states tests are running
+         quit = false, // Flag to quit tests ASAP
+         verbose = false; // Adds message for *every* test to output
+
+      function runHarness(){
+        if (running) {
+          quit = true;
+          setStatus("Restarting tests...", '', true);
+          setTimeout(function(){runHarness();}, 500);
+          return;
+        }
+        if (window.location.hash.substr(1)){
+          debug = window.location.hash.substr(1).split(",");
+        } else {
+          debug = null;
+        }
+        quit = false;
+        running = true;
+        setStatus("Loading tests...");
+        count = 0;
+        failed = 0;
+        bad = "";
+        verbose = false;
+        debugUsed = Array();
+        totalTests = countTests();
+        progressTotal.nodeValue = " of " + totalTests;
+        progressRan.nodeValue = count;
+        output.innerHTML = '';
+        document.getElementById("testground").innerHTML = "<form>" +
+          "<textarea id=\"code\" name=\"code\"></textarea>" +
+          "<input type=submit value=ok name=submit>" +
+          "</form>";
+        runTests(displayTest);
+      }
+
+      function setStatus(message, className, force){
+        if (quit && !force) return;
+        if (!message) throw("must provide message");
+        var status = document.getElementById("status").childNodes[0];
+        status.nodeValue = message;
+        status.parentNode.className = className;
+      }
+      function addOutput(name, className, code){
+        var newOutput = document.createElement("dl");
+        var newTitle = document.createElement("dt");
+        newTitle.className = className;
+        newTitle.appendChild(document.createTextNode(name));
+        newOutput.appendChild(newTitle);
+        var newMessage = document.createElement("dd");
+        newMessage.innerHTML = code;
+        newOutput.appendChild(newTitle);
+        newOutput.appendChild(newMessage);
+        output.appendChild(newOutput);
+      }
+      function displayTest(type, name, customMessage) {
+        var message = "???";
+        if (type != "done") ++count;
+        progress.style.width = (count * (progress.parentNode.clientWidth - 2) / totalTests) + "px";
+        progressRan.nodeValue = count;
+        if (type == "ok") {
+          message = "Test '" + name + "' succeeded";
+          if (!verbose) customMessage = false;
+        } else if (type == "expected") {
+          message = "Test '" + name + "' failed as expected";
+          if (!verbose) customMessage = false;
+        } else if (type == "error" || type == "fail") {
+          ++failed;
+          message = "Test '" + name + "' failed";
+        } else if (type == "done") {
+          if (failed) {
+            type += " fail";
+            message = failed + " failure" + (failed > 1 ? "s" : "");
+          } else if (count < totalTests) {
+            failed = totalTests - count;
+            type += " fail";
+            message = failed + " failure" + (failed > 1 ? "s" : "");
+          } else {
+            type += " ok";
+            message = "All passed";
+          }
+          if (debug && debug.length) {
+            var bogusTests = totalTests - count;
+            message += " — " + bogusTests + " nonexistent test" +
+              (bogusTests > 1 ? "s" : "") + " requested by location.hash: " +
+              "`" + debug.join("`, `") + "`";
+          } else {
+            progressTotal.nodeValue = '';
+          }
+          customMessage = true; // Hack to avoid adding to output
+        }
+        if (verbose && !customMessage)  customMessage = message;
+        setStatus(message, type);
+        if (customMessage && customMessage.length > 0) {
+          addOutput(name, type, customMessage);
+        }
+      }
+    </script>
+  </body>
+</html>
diff --git a/third-party/codemirror-3.15/test/lint/acorn.js b/third-party/codemirror-3.15/test/lint/acorn.js
new file mode 100644 (file)
index 0000000..6323b1f
--- /dev/null
@@ -0,0 +1,1593 @@
+// Acorn is a tiny, fast JavaScript parser written in JavaScript.
+//
+// Acorn was written by Marijn Haverbeke and released under an MIT
+// license. The Unicode regexps (for identifiers and whitespace) were
+// taken from [Esprima](http://esprima.org) by Ariya Hidayat.
+//
+// Git repositories for Acorn are available at
+//
+//     http://marijnhaverbeke.nl/git/acorn
+//     https://github.com/marijnh/acorn.git
+//
+// Please use the [github bug tracker][ghbt] to report issues.
+//
+// [ghbt]: https://github.com/marijnh/acorn/issues
+
+(function(exports) {
+  "use strict";
+
+  exports.version = "0.0.1";
+
+  // The main exported interface (under `window.acorn` when in the
+  // browser) is a `parse` function that takes a code string and
+  // returns an abstract syntax tree as specified by [Mozilla parser
+  // API][api], with the caveat that the SpiderMonkey-specific syntax
+  // (`let`, `yield`, inline XML, etc) is not recognized.
+  //
+  // [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
+
+  var options, input, inputLen, sourceFile;
+
+  exports.parse = function(inpt, opts) {
+    input = String(inpt); inputLen = input.length;
+    options = opts || {};
+    for (var opt in defaultOptions) if (!options.hasOwnProperty(opt))
+      options[opt] = defaultOptions[opt];
+    sourceFile = options.sourceFile || null;
+    return parseTopLevel(options.program);
+  };
+
+  // A second optional argument can be given to further configure
+  // the parser process. These options are recognized:
+
+  var defaultOptions = exports.defaultOptions = {
+    // `ecmaVersion` indicates the ECMAScript version to parse. Must
+    // be either 3 or 5. This
+    // influences support for strict mode, the set of reserved words, and
+    // support for getters and setter.
+    ecmaVersion: 5,
+    // Turn on `strictSemicolons` to prevent the parser from doing
+    // automatic semicolon insertion.
+    strictSemicolons: false,
+    // When `allowTrailingCommas` is false, the parser will not allow
+    // trailing commas in array and object literals.
+    allowTrailingCommas: true,
+    // By default, reserved words are not enforced. Enable
+    // `forbidReserved` to enforce them.
+    forbidReserved: false,
+    // When `trackComments` is turned on, the parser will attach
+    // `commentsBefore` and `commentsAfter` properties to AST nodes
+    // holding arrays of strings. A single comment may appear in both
+    // a `commentsBefore` and `commentsAfter` array (of the nodes
+    // after and before it), but never twice in the before (or after)
+    // array of different nodes.
+    trackComments: false,
+    // When `locations` is on, `loc` properties holding objects with
+    // `start` and `end` properties in `{line, column}` form (with
+    // line being 1-based and column 0-based) will be attached to the
+    // nodes.
+    locations: false,
+    // Nodes have their start and end characters offsets recorded in
+    // `start` and `end` properties (directly on the node, rather than
+    // the `loc` object, which holds line/column data. To also add a
+    // [semi-standardized][range] `range` property holding a `[start,
+    // end]` array with the same numbers, set the `ranges` option to
+    // `true`.
+    //
+    // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
+    ranges: false,
+    // It is possible to parse multiple files into a single AST by
+    // passing the tree produced by parsing the first file as
+    // `program` option in subsequent parses. This will add the
+    // toplevel forms of the parsed file to the `Program` (top) node
+    // of an existing parse tree.
+    program: null,
+    // When `location` is on, you can pass this to record the source
+    // file in every node's `loc` object.
+    sourceFile: null
+  };
+
+  // The `getLineInfo` function is mostly useful when the
+  // `locations` option is off (for performance reasons) and you
+  // want to find the line/column position for a given character
+  // offset. `input` should be the code string that the offset refers
+  // into.
+
+  var getLineInfo = exports.getLineInfo = function(input, offset) {
+    for (var line = 1, cur = 0;;) {
+      lineBreak.lastIndex = cur;
+      var match = lineBreak.exec(input);
+      if (match && match.index < offset) {
+        ++line;
+        cur = match.index + match[0].length;
+      } else break;
+    }
+    return {line: line, column: offset - cur};
+  };
+
+  // Acorn is organized as a tokenizer and a recursive-descent parser.
+  // Both use (closure-)global variables to keep their state and
+  // communicate. We already saw the `options`, `input`, and
+  // `inputLen` variables above (set in `parse`).
+
+  // The current position of the tokenizer in the input.
+
+  var tokPos;
+
+  // The start and end offsets of the current token.
+
+  var tokStart, tokEnd;
+
+  // When `options.locations` is true, these hold objects
+  // containing the tokens start and end line/column pairs.
+
+  var tokStartLoc, tokEndLoc;
+
+  // The type and value of the current token. Token types are objects,
+  // named by variables against which they can be compared, and
+  // holding properties that describe them (indicating, for example,
+  // the precedence of an infix operator, and the original name of a
+  // keyword token). The kind of value that's held in `tokVal` depends
+  // on the type of the token. For literals, it is the literal value,
+  // for operators, the operator name, and so on.
+
+  var tokType, tokVal;
+
+  // These are used to hold arrays of comments when
+  // `options.trackComments` is true.
+
+  var tokCommentsBefore, tokCommentsAfter;
+
+  // Interal state for the tokenizer. To distinguish between division
+  // operators and regular expressions, it remembers whether the last
+  // token was one that is allowed to be followed by an expression.
+  // (If it is, a slash is probably a regexp, if it isn't it's a
+  // division operator. See the `parseStatement` function for a
+  // caveat.)
+
+  var tokRegexpAllowed, tokComments;
+
+  // When `options.locations` is true, these are used to keep
+  // track of the current line, and know when a new line has been
+  // entered. See the `curLineLoc` function.
+
+  var tokCurLine, tokLineStart, tokLineStartNext;
+
+  // These store the position of the previous token, which is useful
+  // when finishing a node and assigning its `end` position.
+
+  var lastStart, lastEnd, lastEndLoc;
+
+  // This is the parser's state. `inFunction` is used to reject
+  // `return` statements outside of functions, `labels` to verify that
+  // `break` and `continue` have somewhere to jump to, and `strict`
+  // indicates whether strict mode is on.
+
+  var inFunction, labels, strict;
+
+  // This function is used to raise exceptions on parse errors. It
+  // takes either a `{line, column}` object or an offset integer (into
+  // the current `input`) as `pos` argument. It attaches the position
+  // to the end of the error message, and then raises a `SyntaxError`
+  // with that message.
+
+  function raise(pos, message) {
+    if (typeof pos == "number") pos = getLineInfo(input, pos);
+    message += " (" + pos.line + ":" + pos.column + ")";
+    throw new SyntaxError(message);
+  }
+
+  // ## Token types
+
+  // The assignment of fine-grained, information-carrying type objects
+  // allows the tokenizer to store the information it has about a
+  // token in a way that is very cheap for the parser to look up.
+
+  // All token type variables start with an underscore, to make them
+  // easy to recognize.
+
+  // These are the general types. The `type` property is only used to
+  // make them recognizeable when debugging.
+
+  var _num = {type: "num"}, _regexp = {type: "regexp"}, _string = {type: "string"};
+  var _name = {type: "name"}, _eof = {type: "eof"};
+
+  // Keyword tokens. The `keyword` property (also used in keyword-like
+  // operators) indicates that the token originated from an
+  // identifier-like word, which is used when parsing property names.
+  //
+  // The `beforeExpr` property is used to disambiguate between regular
+  // expressions and divisions. It is set on all token types that can
+  // be followed by an expression (thus, a slash after them would be a
+  // regular expression).
+  //
+  // `isLoop` marks a keyword as starting a loop, which is important
+  // to know when parsing a label, in order to allow or disallow
+  // continue jumps to that label.
+
+  var _break = {keyword: "break"}, _case = {keyword: "case", beforeExpr: true}, _catch = {keyword: "catch"};
+  var _continue = {keyword: "continue"}, _debugger = {keyword: "debugger"}, _default = {keyword: "default"};
+  var _do = {keyword: "do", isLoop: true}, _else = {keyword: "else", beforeExpr: true};
+  var _finally = {keyword: "finally"}, _for = {keyword: "for", isLoop: true}, _function = {keyword: "function"};
+  var _if = {keyword: "if"}, _return = {keyword: "return", beforeExpr: true}, _switch = {keyword: "switch"};
+  var _throw = {keyword: "throw", beforeExpr: true}, _try = {keyword: "try"}, _var = {keyword: "var"};
+  var _while = {keyword: "while", isLoop: true}, _with = {keyword: "with"}, _new = {keyword: "new", beforeExpr: true};
+  var _this = {keyword: "this"};
+
+  // The keywords that denote values.
+
+  var _null = {keyword: "null", atomValue: null}, _true = {keyword: "true", atomValue: true};
+  var _false = {keyword: "false", atomValue: false};
+
+  // Some keywords are treated as regular operators. `in` sometimes
+  // (when parsing `for`) needs to be tested against specifically, so
+  // we assign a variable name to it for quick comparing.
+
+  var _in = {keyword: "in", binop: 7, beforeExpr: true};
+
+  // Map keyword names to token types.
+
+  var keywordTypes = {"break": _break, "case": _case, "catch": _catch,
+                      "continue": _continue, "debugger": _debugger, "default": _default,
+                      "do": _do, "else": _else, "finally": _finally, "for": _for,
+                      "function": _function, "if": _if, "return": _return, "switch": _switch,
+                      "throw": _throw, "try": _try, "var": _var, "while": _while, "with": _with,
+                      "null": _null, "true": _true, "false": _false, "new": _new, "in": _in,
+                      "instanceof": {keyword: "instanceof", binop: 7}, "this": _this,
+                      "typeof": {keyword: "typeof", prefix: true},
+                      "void": {keyword: "void", prefix: true},
+                      "delete": {keyword: "delete", prefix: true}};
+
+  // Punctuation token types. Again, the `type` property is purely for debugging.
+
+  var _bracketL = {type: "[", beforeExpr: true}, _bracketR = {type: "]"}, _braceL = {type: "{", beforeExpr: true};
+  var _braceR = {type: "}"}, _parenL = {type: "(", beforeExpr: true}, _parenR = {type: ")"};
+  var _comma = {type: ",", beforeExpr: true}, _semi = {type: ";", beforeExpr: true};
+  var _colon = {type: ":", beforeExpr: true}, _dot = {type: "."}, _question = {type: "?", beforeExpr: true};
+
+  // Operators. These carry several kinds of properties to help the
+  // parser use them properly (the presence of these properties is
+  // what categorizes them as operators).
+  //
+  // `binop`, when present, specifies that this operator is a binary
+  // operator, and will refer to its precedence.
+  //
+  // `prefix` and `postfix` mark the operator as a prefix or postfix
+  // unary operator. `isUpdate` specifies that the node produced by
+  // the operator should be of type UpdateExpression rather than
+  // simply UnaryExpression (`++` and `--`).
+  //
+  // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
+  // binary operators with a very low precedence, that should result
+  // in AssignmentExpression nodes.
+
+  var _slash = {binop: 10, beforeExpr: true}, _eq = {isAssign: true, beforeExpr: true};
+  var _assign = {isAssign: true, beforeExpr: true}, _plusmin = {binop: 9, prefix: true, beforeExpr: true};
+  var _incdec = {postfix: true, prefix: true, isUpdate: true}, _prefix = {prefix: true, beforeExpr: true};
+  var _bin1 = {binop: 1, beforeExpr: true}, _bin2 = {binop: 2, beforeExpr: true};
+  var _bin3 = {binop: 3, beforeExpr: true}, _bin4 = {binop: 4, beforeExpr: true};
+  var _bin5 = {binop: 5, beforeExpr: true}, _bin6 = {binop: 6, beforeExpr: true};
+  var _bin7 = {binop: 7, beforeExpr: true}, _bin8 = {binop: 8, beforeExpr: true};
+  var _bin10 = {binop: 10, beforeExpr: true};
+
+  // This is a trick taken from Esprima. It turns out that, on
+  // non-Chrome browsers, to check whether a string is in a set, a
+  // predicate containing a big ugly `switch` statement is faster than
+  // a regular expression, and on Chrome the two are about on par.
+  // This function uses `eval` (non-lexical) to produce such a
+  // predicate from a space-separated string of words.
+  //
+  // It starts by sorting the words by length.
+
+  function makePredicate(words) {
+    words = words.split(" ");
+    var f = "", cats = [];
+    out: for (var i = 0; i < words.length; ++i) {
+      for (var j = 0; j < cats.length; ++j)
+        if (cats[j][0].length == words[i].length) {
+          cats[j].push(words[i]);
+          continue out;
+        }
+      cats.push([words[i]]);
+    }
+    function compareTo(arr) {
+      if (arr.length == 1) return f += "return str === " + JSON.stringify(arr[0]) + ";";
+      f += "switch(str){";
+      for (var i = 0; i < arr.length; ++i) f += "case " + JSON.stringify(arr[i]) + ":";
+      f += "return true}return false;";
+    }
+
+    // When there are more than three length categories, an outer
+    // switch first dispatches on the lengths, to save on comparisons.
+
+    if (cats.length > 3) {
+      cats.sort(function(a, b) {return b.length - a.length;});
+      f += "switch(str.length){";
+      for (var i = 0; i < cats.length; ++i) {
+        var cat = cats[i];
+        f += "case " + cat[0].length + ":";
+        compareTo(cat);
+      }
+      f += "}";
+
+    // Otherwise, simply generate a flat `switch` statement.
+
+    } else {
+      compareTo(words);
+    }
+    return new Function("str", f);
+  }
+
+  // The ECMAScript 3 reserved word list.
+
+  var isReservedWord3 = makePredicate("abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile");
+
+  // ECMAScript 5 reserved words.
+
+  var isReservedWord5 = makePredicate("class enum extends super const export import");
+
+  // The additional reserved words in strict mode.
+
+  var isStrictReservedWord = makePredicate("implements interface let package private protected public static yield");
+
+  // The forbidden variable names in strict mode.
+
+  var isStrictBadIdWord = makePredicate("eval arguments");
+
+  // And the keywords.
+
+  var isKeyword = makePredicate("break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this");
+
+  // ## Character categories
+
+  // Big ugly regular expressions that match characters in the
+  // whitespace, identifier, and identifier-start categories. These
+  // are only applied when a character is found to actually have a
+  // code point above 128.
+
+  var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]/;
+  var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc";
+  var nonASCIIidentifierChars = "\u0371-\u0374\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u0620-\u0649\u0672-\u06d3\u06e7-\u06e8\u06fb-\u06fc\u0730-\u074a\u0800-\u0814\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0840-\u0857\u08e4-\u08fe\u0900-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962-\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09d7\u09df-\u09e0\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5f-\u0b60\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2-\u0ce3\u0ce6-\u0cef\u0d02\u0d03\u0d46-\u0d48\u0d57\u0d62-\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e34-\u0e3a\u0e40-\u0e45\u0e50-\u0e59\u0eb4-\u0eb9\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f41-\u0f47\u0f71-\u0f84\u0f86-\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1029\u1040-\u1049\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u170e-\u1710\u1720-\u1730\u1740-\u1750\u1772\u1773\u1780-\u17b2\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1920-\u192b\u1930-\u193b\u1951-\u196d\u19b0-\u19c0\u19c8-\u19c9\u19d0-\u19d9\u1a00-\u1a15\u1a20-\u1a53\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1b46-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1bb0-\u1bb9\u1be6-\u1bf3\u1c00-\u1c22\u1c40-\u1c49\u1c5b-\u1c7d\u1cd0-\u1cd2\u1d00-\u1dbe\u1e01-\u1f15\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2d81-\u2d96\u2de0-\u2dff\u3021-\u3028\u3099\u309a\ua640-\ua66d\ua674-\ua67d\ua69f\ua6f0-\ua6f1\ua7f8-\ua800\ua806\ua80b\ua823-\ua827\ua880-\ua881\ua8b4-\ua8c4\ua8d0-\ua8d9\ua8f3-\ua8f7\ua900-\ua909\ua926-\ua92d\ua930-\ua945\ua980-\ua983\ua9b3-\ua9c0\uaa00-\uaa27\uaa40-\uaa41\uaa4c-\uaa4d\uaa50-\uaa59\uaa7b\uaae0-\uaae9\uaaf2-\uaaf3\uabc0-\uabe1\uabec\uabed\uabf0-\uabf9\ufb20-\ufb28\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
+  var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
+  var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
+
+  // Whether a single character denotes a newline.
+
+  var newline = /[\n\r\u2028\u2029]/;
+
+  // Matches a whole line break (where CRLF is considered a single
+  // line break). Used to count lines.
+
+  var lineBreak = /\r\n|[\n\r\u2028\u2029]/g;
+
+  // Test whether a given character code starts an identifier.
+
+  function isIdentifierStart(code) {
+    if (code < 65) return code === 36;
+    if (code < 91) return true;
+    if (code < 97) return code === 95;
+    if (code < 123)return true;
+    return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
+  }
+
+  // Test whether a given character is part of an identifier.
+
+  function isIdentifierChar(code) {
+    if (code < 48) return code === 36;
+    if (code < 58) return true;
+    if (code < 65) return false;
+    if (code < 91) return true;
+    if (code < 97) return code === 95;
+    if (code < 123)return true;
+    return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
+  }
+
+  // ## Tokenizer
+
+  // These are used when `options.locations` is on, in order to track
+  // the current line number and start of line offset, in order to set
+  // `tokStartLoc` and `tokEndLoc`.
+
+  function nextLineStart() {
+    lineBreak.lastIndex = tokLineStart;
+    var match = lineBreak.exec(input);
+    return match ? match.index + match[0].length : input.length + 1;
+  }
+
+  function curLineLoc() {
+    while (tokLineStartNext <= tokPos) {
+      ++tokCurLine;
+      tokLineStart = tokLineStartNext;
+      tokLineStartNext = nextLineStart();
+    }
+    return {line: tokCurLine, column: tokPos - tokLineStart};
+  }
+
+  // Reset the token state. Used at the start of a parse.
+
+  function initTokenState() {
+    tokCurLine = 1;
+    tokPos = tokLineStart = 0;
+    tokLineStartNext = nextLineStart();
+    tokRegexpAllowed = true;
+    tokComments = null;
+    skipSpace();
+  }
+
+  // Called at the end of every token. Sets `tokEnd`, `tokVal`,
+  // `tokCommentsAfter`, and `tokRegexpAllowed`, and skips the space
+  // after the token, so that the next one's `tokStart` will point at
+  // the right position.
+
+  function finishToken(type, val) {
+    tokEnd = tokPos;
+    if (options.locations) tokEndLoc = curLineLoc();
+    tokType = type;
+    skipSpace();
+    tokVal = val;
+    tokCommentsAfter = tokComments;
+    tokRegexpAllowed = type.beforeExpr;
+  }
+
+  function skipBlockComment() {
+    var end = input.indexOf("*/", tokPos += 2);
+    if (end === -1) raise(tokPos - 2, "Unterminated comment");
+    if (options.trackComments)
+      (tokComments || (tokComments = [])).push(input.slice(tokPos, end));
+    tokPos = end + 2;
+  }
+
+  function skipLineComment() {
+    var start = tokPos;
+    var ch = input.charCodeAt(tokPos+=2);
+    while (tokPos < inputLen && ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8329) {
+      ++tokPos;
+      ch = input.charCodeAt(tokPos);
+    }
+    (tokComments || (tokComments = [])).push(input.slice(start, tokPos));
+  }
+
+  // Called at the start of the parse and after every token. Skips
+  // whitespace and comments, and, if `options.trackComments` is on,
+  // will store all skipped comments in `tokComments`.
+
+  function skipSpace() {
+    tokComments = null;
+    while (tokPos < inputLen) {
+      var ch = input.charCodeAt(tokPos);
+      if (ch === 47) { // '/'
+        var next = input.charCodeAt(tokPos+1);
+        if (next === 42) { // '*'
+          skipBlockComment();
+        } else if (next === 47) { // '/'
+          skipLineComment();
+        } else break;
+      } else if (ch < 14 && ch > 8) {
+        ++tokPos;
+      } else if (ch === 32 || ch === 160) { // ' ', '\xa0'
+        ++tokPos;
+      } else if (ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
+        ++tokPos;
+      } else {
+        break;
+      }
+    }
+  }
+
+  // ### Token reading
+
+  // This is the function that is called to fetch the next token. It
+  // is somewhat obscure, because it works in character codes rather
+  // than characters, and because operator parsing has been inlined
+  // into it.
+  //
+  // All in the name of speed.
+  //
+  // The `forceRegexp` parameter is used in the one case where the
+  // `tokRegexpAllowed` trick does not work. See `parseStatement`.
+
+  function readToken(forceRegexp) {
+    tokStart = tokPos;
+    if (options.locations) tokStartLoc = curLineLoc();
+    tokCommentsBefore = tokComments;
+    if (forceRegexp) return readRegexp();
+    if (tokPos >= inputLen) return finishToken(_eof);
+
+    var code = input.charCodeAt(tokPos);
+    // Identifier or keyword. '\uXXXX' sequences are allowed in
+    // identifiers, so '\' also dispatches to that.
+    if (isIdentifierStart(code) || code === 92 /* '\' */) return readWord();
+    var next = input.charCodeAt(tokPos+1);
+
+    switch(code) {
+      // The interpretation of a dot depends on whether it is followed
+      // by a digit.
+    case 46: // '.'
+      if (next >= 48 && next <= 57) return readNumber(String.fromCharCode(code));
+      ++tokPos;
+      return finishToken(_dot);
+
+      // Punctuation tokens.
+    case 40: ++tokPos; return finishToken(_parenL);
+    case 41: ++tokPos; return finishToken(_parenR);
+    case 59: ++tokPos; return finishToken(_semi);
+    case 44: ++tokPos; return finishToken(_comma);
+    case 91: ++tokPos; return finishToken(_bracketL);
+    case 93: ++tokPos; return finishToken(_bracketR);
+    case 123: ++tokPos; return finishToken(_braceL);
+    case 125: ++tokPos; return finishToken(_braceR);
+    case 58: ++tokPos; return finishToken(_colon);
+    case 63: ++tokPos; return finishToken(_question);
+
+      // '0x' is a hexadecimal number.
+    case 48: // '0'
+      if (next === 120 || next === 88) return readHexNumber();
+      // Anything else beginning with a digit is an integer, octal
+      // number, or float.
+    case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
+      return readNumber(String.fromCharCode(code));
+
+      // Quotes produce strings.
+    case 34: case 39: // '"', "'"
+      return readString(code);
+
+    // Operators are parsed inline in tiny state machines. '=' (61) is
+    // often referred to. `finishOp` simply skips the amount of
+    // characters it is given as second argument, and returns a token
+    // of the type given by its first argument.
+
+    case 47: // '/'
+      if (tokRegexpAllowed) {++tokPos; return readRegexp();}
+      if (next === 61) return finishOp(_assign, 2);
+      return finishOp(_slash, 1);
+
+    case 37: case 42: // '%*'
+      if (next === 61) return finishOp(_assign, 2);
+      return finishOp(_bin10, 1);
+
+    case 124: case 38: // '|&'
+      if (next === code) return finishOp(code === 124 ? _bin1 : _bin2, 2);
+      if (next === 61) return finishOp(_assign, 2);
+      return finishOp(code === 124 ? _bin3 : _bin5, 1);
+
+    case 94: // '^'
+      if (next === 61) return finishOp(_assign, 2);
+      return finishOp(_bin4, 1);
+
+    case 43: case 45: // '+-'
+      if (next === code) return finishOp(_incdec, 2);
+      if (next === 61) return finishOp(_assign, 2);
+      return finishOp(_plusmin, 1);
+
+    case 60: case 62: // '<>'
+      var size = 1;
+      if (next === code) {
+        size = code === 62 && input.charCodeAt(tokPos+2) === 62 ? 3 : 2;
+        if (input.charCodeAt(tokPos + size) === 61) return finishOp(_assign, size + 1);
+        return finishOp(_bin8, size);
+      }
+      if (next === 61)
+        size = input.charCodeAt(tokPos+2) === 61 ? 3 : 2;
+      return finishOp(_bin7, size);
+
+    case 61: case 33: // '=!'
+      if (next === 61) return finishOp(_bin6, input.charCodeAt(tokPos+2) === 61 ? 3 : 2);
+      return finishOp(code === 61 ? _eq : _prefix, 1);
+
+    case 126: // '~'
+      return finishOp(_prefix, 1);
+    }
+
+    // If we are here, we either found a non-ASCII identifier
+    // character, or something that's entirely disallowed.
+    var ch = String.fromCharCode(code);
+    if (ch === "\\" || nonASCIIidentifierStart.test(ch)) return readWord();
+    raise(tokPos, "Unexpected character '" + ch + "'");
+  }
+
+  function finishOp(type, size) {
+    var str = input.slice(tokPos, tokPos + size);
+    tokPos += size;
+    finishToken(type, str);
+  }
+
+  // Parse a regular expression. Some context-awareness is necessary,
+  // since a '/' inside a '[]' set does not end the expression.
+
+  function readRegexp() {
+    var content = "", escaped, inClass, start = tokPos;
+    for (;;) {
+      if (tokPos >= inputLen) raise(start, "Unterminated regular expression");
+      var ch = input.charAt(tokPos);
+      if (newline.test(ch)) raise(start, "Unterminated regular expression");
+      if (!escaped) {
+        if (ch === "[") inClass = true;
+        else if (ch === "]" && inClass) inClass = false;
+        else if (ch === "/" && !inClass) break;
+        escaped = ch === "\\";
+      } else escaped = false;
+      ++tokPos;
+    }
+    var content = input.slice(start, tokPos);
+    ++tokPos;
+    // Need to use `readWord1` because '\uXXXX' sequences are allowed
+    // here (don't ask).
+    var mods = readWord1();
+    if (mods && !/^[gmsiy]*$/.test(mods)) raise(start, "Invalid regexp flag");
+    return finishToken(_regexp, new RegExp(content, mods));
+  }
+
+  // Read an integer in the given radix. Return null if zero digits
+  // were read, the integer value otherwise. When `len` is given, this
+  // will return `null` unless the integer has exactly `len` digits.
+
+  function readInt(radix, len) {
+    var start = tokPos, total = 0;
+    for (;;) {
+      var code = input.charCodeAt(tokPos), val;
+      if (code >= 97) val = code - 97 + 10; // a
+      else if (code >= 65) val = code - 65 + 10; // A
+      else if (code >= 48 && code <= 57) val = code - 48; // 0-9
+      else val = Infinity;
+      if (val >= radix) break;
+      ++tokPos;
+      total = total * radix + val;
+    }
+    if (tokPos === start || len != null && tokPos - start !== len) return null;
+
+    return total;
+  }
+
+  function readHexNumber() {
+    tokPos += 2; // 0x
+    var val = readInt(16);
+    if (val == null) raise(tokStart + 2, "Expected hexadecimal number");
+    if (isIdentifierStart(input.charCodeAt(tokPos))) raise(tokPos, "Identifier directly after number");
+    return finishToken(_num, val);
+  }
+
+  // Read an integer, octal integer, or floating-point number.
+  
+  function readNumber(ch) {
+    var start = tokPos, isFloat = ch === ".";
+    if (!isFloat && readInt(10) == null) raise(start, "Invalid number");
+    if (isFloat || input.charAt(tokPos) === ".") {
+      var next = input.charAt(++tokPos);
+      if (next === "-" || next === "+") ++tokPos;
+      if (readInt(10) === null && ch === ".") raise(start, "Invalid number");
+      isFloat = true;
+    }
+    if (/e/i.test(input.charAt(tokPos))) {
+      var next = input.charAt(++tokPos);
+      if (next === "-" || next === "+") ++tokPos;
+      if (readInt(10) === null) raise(start, "Invalid number")
+      isFloat = true;
+    }
+    if (isIdentifierStart(input.charCodeAt(tokPos))) raise(tokPos, "Identifier directly after number");
+
+    var str = input.slice(start, tokPos), val;
+    if (isFloat) val = parseFloat(str);
+    else if (ch !== "0" || str.length === 1) val = parseInt(str, 10);
+    else if (/[89]/.test(str) || strict) raise(start, "Invalid number");
+    else val = parseInt(str, 8);
+    return finishToken(_num, val);
+  }
+
+  // Read a string value, interpreting backslash-escapes.
+
+  function readString(quote) {
+    tokPos++;
+    var str = [];
+    for (;;) {
+      if (tokPos >= inputLen) raise(tokStart, "Unterminated string constant");
+      var ch = input.charCodeAt(tokPos);
+      if (ch === quote) {
+        ++tokPos;
+        return finishToken(_string, String.fromCharCode.apply(null, str));
+      }
+      if (ch === 92) { // '\'
+        ch = input.charCodeAt(++tokPos);
+        var octal = /^[0-7]+/.exec(input.slice(tokPos, tokPos + 3));
+        if (octal) octal = octal[0];
+        while (octal && parseInt(octal, 8) > 255) octal = octal.slice(0, octal.length - 1);
+        if (octal === "0") octal = null;
+        ++tokPos;
+        if (octal) {
+          if (strict) raise(tokPos - 2, "Octal literal in strict mode");
+          str.push(parseInt(octal, 8));
+          tokPos += octal.length - 1;
+        } else {
+          switch (ch) {
+          case 110: str.push(10); break; // 'n' -> '\n'
+          case 114: str.push(13); break; // 'r' -> '\r'
+          case 120: str.push(readHexChar(2)); break; // 'x'
+          case 117: str.push(readHexChar(4)); break; // 'u'
+          case 85: str.push(readHexChar(8)); break; // 'U'
+          case 116: str.push(9); break; // 't' -> '\t'
+          case 98: str.push(8); break; // 'b' -> '\b'
+          case 118: str.push(11); break; // 'v' -> '\u000b'
+          case 102: str.push(12); break; // 'f' -> '\f'
+          case 48: str.push(0); break; // 0 -> '\0'
+          case 13: if (input.charCodeAt(tokPos) === 10) ++tokPos; // '\r\n'
+          case 10: break; // ' \n'
+          default: str.push(ch); break;
+          }
+        }
+      } else {
+        if (ch === 13 || ch === 10 || ch === 8232 || ch === 8329) raise(tokStart, "Unterminated string constant");
+        if (ch !== 92) str.push(ch); // '\'
+        ++tokPos;
+      }
+    }
+  }
+
+  // Used to read character escape sequences ('\x', '\u', '\U').
+
+  function readHexChar(len) {
+    var n = readInt(16, len);
+    if (n === null) raise(tokStart, "Bad character escape sequence");
+    return n;
+  }
+
+  // Used to signal to callers of `readWord1` whether the word
+  // contained any escape sequences. This is needed because words with
+  // escape sequences must not be interpreted as keywords.
+
+  var containsEsc;
+
+  // Read an identifier, and return it as a string. Sets `containsEsc`
+  // to whether the word contained a '\u' escape.
+  //
+  // Only builds up the word character-by-character when it actually
+  // containeds an escape, as a micro-optimization.
+
+  function readWord1() {
+    containsEsc = false;
+    var word, first = true, start = tokPos;
+    for (;;) {
+      var ch = input.charCodeAt(tokPos);
+      if (isIdentifierChar(ch)) {
+        if (containsEsc) word += input.charAt(tokPos);
+        ++tokPos;
+      } else if (ch === 92) { // "\"
+        if (!containsEsc) word = input.slice(start, tokPos);
+        containsEsc = true;
+        if (input.charCodeAt(++tokPos) != 117) // "u"
+          raise(tokPos, "Expecting Unicode escape sequence \\uXXXX");
+        ++tokPos;
+        var esc = readHexChar(4);
+        var escStr = String.fromCharCode(esc);
+        if (!escStr) raise(tokPos - 1, "Invalid Unicode escape");
+        if (!(first ? isIdentifierStart(esc) : isIdentifierChar(esc)))
+          raise(tokPos - 4, "Invalid Unicode escape");
+        word += escStr;
+      } else {
+        break;
+      }
+      first = false;
+    }
+    return containsEsc ? word : input.slice(start, tokPos);
+  }
+
+  // Read an identifier or keyword token. Will check for reserved
+  // words when necessary.
+
+  function readWord() {
+    var word = readWord1();
+    var type = _name;
+    if (!containsEsc) {
+      if (isKeyword(word)) type = keywordTypes[word];
+      else if (options.forbidReserved &&
+               (options.ecmaVersion === 3 ? isReservedWord3 : isReservedWord5)(word) ||
+               strict && isStrictReservedWord(word))
+        raise(tokStart, "The keyword '" + word + "' is reserved");
+    }
+    return finishToken(type, word);
+  }
+
+  // ## Parser
+
+  // A recursive descent parser operates by defining functions for all
+  // syntactic elements, and recursively calling those, each function
+  // advancing the input stream and returning an AST node. Precedence
+  // of constructs (for example, the fact that `!x[1]` means `!(x[1])`
+  // instead of `(!x)[1]` is handled by the fact that the parser
+  // function that parses unary prefix operators is called first, and
+  // in turn calls the function that parses `[]` subscripts — that
+  // way, it'll receive the node for `x[1]` already parsed, and wraps
+  // *that* in the unary operator node.
+  //
+  // Acorn uses an [operator precedence parser][opp] to handle binary
+  // operator precedence, because it is much more compact than using
+  // the technique outlined above, which uses different, nesting
+  // functions to specify precedence, for all of the ten binary
+  // precedence levels that JavaScript defines.
+  //
+  // [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser
+
+  // ### Parser utilities
+
+  // Continue to the next token.
+  
+  function next() {
+    lastStart = tokStart;
+    lastEnd = tokEnd;
+    lastEndLoc = tokEndLoc;
+    readToken();
+  }
+
+  // Enter strict mode. Re-reads the next token to please pedantic
+  // tests ("use strict"; 010; -- should fail).
+
+  function setStrict(strct) {
+    strict = strct;
+    tokPos = lastEnd;
+    skipSpace();
+    readToken();
+  }
+
+  // Start an AST node, attaching a start offset and optionally a
+  // `commentsBefore` property to it.
+
+  function startNode() {
+    var node = {type: null, start: tokStart, end: null};
+    if (options.trackComments && tokCommentsBefore) {
+      node.commentsBefore = tokCommentsBefore;
+      tokCommentsBefore = null;
+    }
+    if (options.locations)
+      node.loc = {start: tokStartLoc, end: null, source: sourceFile};
+    if (options.ranges)
+      node.range = [tokStart, 0];
+    return node;
+  }
+
+  // Start a node whose start offset/comments information should be
+  // based on the start of another node. For example, a binary
+  // operator node is only started after its left-hand side has
+  // already been parsed.
+
+  function startNodeFrom(other) {
+    var node = {type: null, start: other.start};
+    if (other.commentsBefore) {
+      node.commentsBefore = other.commentsBefore;
+      other.commentsBefore = null;
+    }
+    if (options.locations)
+      node.loc = {start: other.loc.start, end: null, source: other.loc.source};
+    if (options.ranges)
+      node.range = [other.range[0], 0];
+
+    return node;
+  }
+
+  // Finish an AST node, adding `type`, `end`, and `commentsAfter`
+  // properties.
+  //
+  // We keep track of the last node that we finished, in order
+  // 'bubble' `commentsAfter` properties up to the biggest node. I.e.
+  // in '`1 + 1 // foo', the comment should be attached to the binary
+  // operator node, not the second literal node.
+
+  var lastFinishedNode;
+
+  function finishNode(node, type) {
+    node.type = type;
+    node.end = lastEnd;
+    if (options.trackComments) {
+      if (tokCommentsAfter) {
+        node.commentsAfter = tokCommentsAfter;
+        tokCommentsAfter = null;
+      } else if (lastFinishedNode && lastFinishedNode.end === lastEnd) {
+        node.commentsAfter = lastFinishedNode.commentsAfter;
+        lastFinishedNode.commentsAfter = null;
+      }
+      lastFinishedNode = node;
+    }
+    if (options.locations)
+      node.loc.end = lastEndLoc;
+    if (options.ranges)
+      node.range[1] = lastEnd;
+    return node;
+  }
+
+  // Test whether a statement node is the string literal `"use strict"`.
+
+  function isUseStrict(stmt) {
+    return options.ecmaVersion >= 5 && stmt.type === "ExpressionStatement" &&
+      stmt.expression.type === "Literal" && stmt.expression.value === "use strict";
+  }
+
+  // Predicate that tests whether the next token is of the given
+  // type, and if yes, consumes it as a side effect.
+
+  function eat(type) {
+    if (tokType === type) {
+      next();
+      return true;
+    }
+  }
+
+  // Test whether a semicolon can be inserted at the current position.
+
+  function canInsertSemicolon() {
+    return !options.strictSemicolons &&
+      (tokType === _eof || tokType === _braceR || newline.test(input.slice(lastEnd, tokStart)));
+  }
+
+  // Consume a semicolon, or, failing that, see if we are allowed to
+  // pretend that there is a semicolon at this position.
+
+  function semicolon() {
+    if (!eat(_semi) && !canInsertSemicolon()) unexpected();
+  }
+
+  // Expect a token of a given type. If found, consume it, otherwise,
+  // raise an unexpected token error.
+
+  function expect(type) {
+    if (tokType === type) next();
+    else unexpected();
+  }
+
+  // Raise an unexpected token error.
+
+  function unexpected() {
+    raise(tokStart, "Unexpected token");
+  }
+
+  // Verify that a node is an lval — something that can be assigned
+  // to.
+
+  function checkLVal(expr) {
+    if (expr.type !== "Identifier" && expr.type !== "MemberExpression")
+      raise(expr.start, "Assigning to rvalue");
+    if (strict && expr.type === "Identifier" && isStrictBadIdWord(expr.name))
+      raise(expr.start, "Assigning to " + expr.name + " in strict mode");
+  }
+
+  // ### Statement parsing
+
+  // Parse a program. Initializes the parser, reads any number of
+  // statements, and wraps them in a Program node.  Optionally takes a
+  // `program` argument.  If present, the statements will be appended
+  // to its body instead of creating a new node.
+
+  function parseTopLevel(program) {
+    initTokenState();
+    lastStart = lastEnd = tokPos;
+    if (options.locations) lastEndLoc = curLineLoc();
+    inFunction = strict = null;
+    labels = [];
+    readToken();
+
+    var node = program || startNode(), first = true;
+    if (!program) node.body = [];
+    while (tokType !== _eof) {
+      var stmt = parseStatement();
+      node.body.push(stmt);
+      if (first && isUseStrict(stmt)) setStrict(true);
+      first = false;
+    }
+    return finishNode(node, "Program");
+  };
+
+  var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
+
+  // Parse a single statement.
+  //
+  // If expecting a statement and finding a slash operator, parse a
+  // regular expression literal. This is to handle cases like
+  // `if (foo) /blah/.exec(foo);`, where looking at the previous token
+  // does not help.
+
+  function parseStatement() {
+    if (tokType === _slash)
+      readToken(true);
+
+    var starttype = tokType, node = startNode();
+
+    // Most types of statements are recognized by the keyword they
+    // start with. Many are trivial to parse, some require a bit of
+    // complexity.
+
+    switch (starttype) {
+    case _break: case _continue:
+      next();
+      var isBreak = starttype === _break;
+      if (eat(_semi) || canInsertSemicolon()) node.label = null;
+      else if (tokType !== _name) unexpected();
+      else {
+        node.label = parseIdent();
+        semicolon();
+      }
+
+      // Verify that there is an actual destination to break or
+      // continue to.
+      for (var i = 0; i < labels.length; ++i) {
+        var lab = labels[i];
+        if (node.label == null || lab.name === node.label.name) {
+          if (lab.kind != null && (isBreak || lab.kind === "loop")) break;
+          if (node.label && isBreak) break;
+        }
+      }
+      if (i === labels.length) raise(node.start, "Unsyntactic " + starttype.keyword);
+      return finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
+
+    case _debugger:
+      next();
+      return finishNode(node, "DebuggerStatement");
+
+    case _do:
+      next();
+      labels.push(loopLabel);
+      node.body = parseStatement();
+      labels.pop();
+      expect(_while);
+      node.test = parseParenExpression();
+      semicolon();
+      return finishNode(node, "DoWhileStatement");
+
+      // Disambiguating between a `for` and a `for`/`in` loop is
+      // non-trivial. Basically, we have to parse the init `var`
+      // statement or expression, disallowing the `in` operator (see
+      // the second parameter to `parseExpression`), and then check
+      // whether the next token is `in`. When there is no init part
+      // (semicolon immediately after the opening parenthesis), it is
+      // a regular `for` loop.
+
+    case _for:
+      next();
+      labels.push(loopLabel);
+      expect(_parenL);
+      if (tokType === _semi) return parseFor(node, null);
+      if (tokType === _var) {
+        var init = startNode();
+        next();
+        parseVar(init, true);
+        if (init.declarations.length === 1 && eat(_in))
+          return parseForIn(node, init);
+        return parseFor(node, init);
+      }
+      var init = parseExpression(false, true);
+      if (eat(_in)) {checkLVal(init); return parseForIn(node, init);}
+      return parseFor(node, init);
+
+    case _function:
+      next();
+      return parseFunction(node, true);
+
+    case _if:
+      next();
+      node.test = parseParenExpression();
+      node.consequent = parseStatement();
+      node.alternate = eat(_else) ? parseStatement() : null;
+      return finishNode(node, "IfStatement");
+
+    case _return:
+      if (!inFunction) raise(tokStart, "'return' outside of function");
+      next();
+
+      // In `return` (and `break`/`continue`), the keywords with
+      // optional arguments, we eagerly look for a semicolon or the
+      // possibility to insert one.
+      
+      if (eat(_semi) || canInsertSemicolon()) node.argument = null;
+      else { node.argument = parseExpression(); semicolon(); }
+      return finishNode(node, "ReturnStatement");
+
+    case _switch:
+      next();
+      node.discriminant = parseParenExpression();
+      node.cases = [];
+      expect(_braceL);
+      labels.push(switchLabel);
+
+      // Statements under must be grouped (by label) in SwitchCase
+      // nodes. `cur` is used to keep the node that we are currently
+      // adding statements to.
+      
+      for (var cur, sawDefault; tokType != _braceR;) {
+        if (tokType === _case || tokType === _default) {
+          var isCase = tokType === _case;
+          if (cur) finishNode(cur, "SwitchCase");
+          node.cases.push(cur = startNode());
+          cur.consequent = [];
+          next();
+          if (isCase) cur.test = parseExpression();
+          else {
+            if (sawDefault) raise(lastStart, "Multiple default clauses"); sawDefault = true;
+            cur.test = null;
+          }
+          expect(_colon);
+        } else {
+          if (!cur) unexpected();
+          cur.consequent.push(parseStatement());
+        }
+      }
+      if (cur) finishNode(cur, "SwitchCase");
+      next(); // Closing brace
+      labels.pop();
+      return finishNode(node, "SwitchStatement");
+
+    case _throw:
+      next();
+      if (newline.test(input.slice(lastEnd, tokStart)))
+        raise(lastEnd, "Illegal newline after throw");
+      node.argument = parseExpression();
+      return finishNode(node, "ThrowStatement");
+
+    case _try:
+      next();
+      node.block = parseBlock();
+      node.handlers = [];
+      while (tokType === _catch) {
+        var clause = startNode();
+        next();
+        expect(_parenL);
+        clause.param = parseIdent();
+        if (strict && isStrictBadIdWord(clause.param.name))
+          raise(clause.param.start, "Binding " + clause.param.name + " in strict mode");
+        expect(_parenR);
+        clause.guard = null;
+        clause.body = parseBlock();
+        node.handlers.push(finishNode(clause, "CatchClause"));
+      }
+      node.finalizer = eat(_finally) ? parseBlock() : null;
+      if (!node.handlers.length && !node.finalizer)
+        raise(node.start, "Missing catch or finally clause");
+      return finishNode(node, "TryStatement");
+
+    case _var:
+      next();
+      node = parseVar(node);
+      semicolon();
+      return node;
+
+    case _while:
+      next();
+      node.test = parseParenExpression();
+      labels.push(loopLabel);
+      node.body = parseStatement();
+      labels.pop();
+      return finishNode(node, "WhileStatement");
+
+    case _with:
+      if (strict) raise(tokStart, "'with' in strict mode");
+      next();
+      node.object = parseParenExpression();
+      node.body = parseStatement();
+      return finishNode(node, "WithStatement");
+
+    case _braceL:
+      return parseBlock();
+
+    case _semi:
+      next();
+      return finishNode(node, "EmptyStatement");
+
+      // If the statement does not start with a statement keyword or a
+      // brace, it's an ExpressionStatement or LabeledStatement. We
+      // simply start parsing an expression, and afterwards, if the
+      // next token is a colon and the expression was a simple
+      // Identifier node, we switch to interpreting it as a label.
+
+    default:
+      var maybeName = tokVal, expr = parseExpression();
+      if (starttype === _name && expr.type === "Identifier" && eat(_colon)) {
+        for (var i = 0; i < labels.length; ++i)
+          if (labels[i].name === maybeName) raise(expr.start, "Label '" + maybeName + "' is already declared");
+        var kind = tokType.isLoop ? "loop" : tokType === _switch ? "switch" : null;
+        labels.push({name: maybeName, kind: kind});
+        node.body = parseStatement();
+        node.label = expr;
+        return finishNode(node, "LabeledStatement");
+      } else {
+        node.expression = expr;
+        semicolon();
+        return finishNode(node, "ExpressionStatement");
+      }
+    }
+  }
+
+  // Used for constructs like `switch` and `if` that insist on
+  // parentheses around their expression.
+
+  function parseParenExpression() {
+    expect(_parenL);
+    var val = parseExpression();
+    expect(_parenR);
+    return val;
+  }
+
+  // Parse a semicolon-enclosed block of statements, handling `"use
+  // strict"` declarations when `allowStrict` is true (used for
+  // function bodies).
+
+  function parseBlock(allowStrict) {
+    var node = startNode(), first = true, strict = false, oldStrict;
+    node.body = [];
+    expect(_braceL);
+    while (!eat(_braceR)) {
+      var stmt = parseStatement();
+      node.body.push(stmt);
+      if (first && isUseStrict(stmt)) {
+        oldStrict = strict;
+        setStrict(strict = true);
+      }
+      first = false
+    }
+    if (strict && !oldStrict) setStrict(false);
+    return finishNode(node, "BlockStatement");
+  }
+
+  // Parse a regular `for` loop. The disambiguation code in
+  // `parseStatement` will already have parsed the init statement or
+  // expression.
+
+  function parseFor(node, init) {
+    node.init = init;
+    expect(_semi);
+    node.test = tokType === _semi ? null : parseExpression();
+    expect(_semi);
+    node.update = tokType === _parenR ? null : parseExpression();
+    expect(_parenR);
+    node.body = parseStatement();
+    labels.pop();
+    return finishNode(node, "ForStatement");
+  }
+
+  // Parse a `for`/`in` loop.
+
+  function parseForIn(node, init) {
+    node.left = init;
+    node.right = parseExpression();
+    expect(_parenR);
+    node.body = parseStatement();
+    labels.pop();
+    return finishNode(node, "ForInStatement");
+  }
+
+  // Parse a list of variable declarations.
+
+  function parseVar(node, noIn) {
+    node.declarations = [];
+    node.kind = "var";
+    for (;;) {
+      var decl = startNode();
+      decl.id = parseIdent();
+      if (strict && isStrictBadIdWord(decl.id.name))
+        raise(decl.id.start, "Binding " + decl.id.name + " in strict mode");
+      decl.init = eat(_eq) ? parseExpression(true, noIn) : null;
+      node.declarations.push(finishNode(decl, "VariableDeclarator"));
+      if (!eat(_comma)) break;
+    }
+    return finishNode(node, "VariableDeclaration");
+  }
+
+  // ### Expression parsing
+
+  // These nest, from the most general expression type at the top to
+  // 'atomic', nondivisible expression types at the bottom. Most of
+  // the functions will simply let the function(s) below them parse,
+  // and, *if* the syntactic construct they handle is present, wrap
+  // the AST node that the inner parser gave them in another node.
+
+  // Parse a full expression. The arguments are used to forbid comma
+  // sequences (in argument lists, array literals, or object literals)
+  // or the `in` operator (in for loops initalization expressions).
+
+  function parseExpression(noComma, noIn) {
+    var expr = parseMaybeAssign(noIn);
+    if (!noComma && tokType === _comma) {
+      var node = startNodeFrom(expr);
+      node.expressions = [expr];
+      while (eat(_comma)) node.expressions.push(parseMaybeAssign(noIn));
+      return finishNode(node, "SequenceExpression");
+    }
+    return expr;
+  }
+
+  // Parse an assignment expression. This includes applications of
+  // operators like `+=`.
+
+  function parseMaybeAssign(noIn) {
+    var left = parseMaybeConditional(noIn);
+    if (tokType.isAssign) {
+      var node = startNodeFrom(left);
+      node.operator = tokVal;
+      node.left = left;
+      next();
+      node.right = parseMaybeAssign(noIn);
+      checkLVal(left);
+      return finishNode(node, "AssignmentExpression");
+    }
+    return left;
+  }
+
+  // Parse a ternary conditional (`?:`) operator.
+
+  function parseMaybeConditional(noIn) {
+    var expr = parseExprOps(noIn);
+    if (eat(_question)) {
+      var node = startNodeFrom(expr);
+      node.test = expr;
+      node.consequent = parseExpression(true);
+      expect(_colon);
+      node.alternate = parseExpression(true, noIn);
+      return finishNode(node, "ConditionalExpression");
+    }
+    return expr;
+  }
+
+  // Start the precedence parser.
+
+  function parseExprOps(noIn) {
+    return parseExprOp(parseMaybeUnary(noIn), -1, noIn);
+  }
+
+  // Parse binary operators with the operator precedence parsing
+  // algorithm. `left` is the left-hand side of the operator.
+  // `minPrec` provides context that allows the function to stop and
+  // defer further parser to one of its callers when it encounters an
+  // operator that has a lower precedence than the set it is parsing.
+
+  function parseExprOp(left, minPrec, noIn) {
+    var prec = tokType.binop;
+    if (prec != null && (!noIn || tokType !== _in)) {
+      if (prec > minPrec) {
+        var node = startNodeFrom(left);
+        node.left = left;
+        node.operator = tokVal;
+        next();
+        node.right = parseExprOp(parseMaybeUnary(noIn), prec, noIn);
+        var node = finishNode(node, /&&|\|\|/.test(node.operator) ? "LogicalExpression" : "BinaryExpression");
+        return parseExprOp(node, minPrec, noIn);
+      }
+    }
+    return left;
+  }
+
+  // Parse unary operators, both prefix and postfix.
+
+  function parseMaybeUnary(noIn) {
+    if (tokType.prefix) {
+      var node = startNode(), update = tokType.isUpdate;
+      node.operator = tokVal;
+      node.prefix = true;
+      next();
+      node.argument = parseMaybeUnary(noIn);
+      if (update) checkLVal(node.argument);
+      else if (strict && node.operator === "delete" &&
+               node.argument.type === "Identifier")
+        raise(node.start, "Deleting local variable in strict mode");
+      return finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
+    }
+    var expr = parseExprSubscripts();
+    while (tokType.postfix && !canInsertSemicolon()) {
+      var node = startNodeFrom(expr);
+      node.operator = tokVal;
+      node.prefix = false;
+      node.argument = expr;
+      checkLVal(expr);
+      next();
+      expr = finishNode(node, "UpdateExpression");
+    }
+    return expr;
+  }
+
+  // Parse call, dot, and `[]`-subscript expressions.
+
+  function parseExprSubscripts() {
+    return parseSubscripts(parseExprAtom());
+  }
+
+  function parseSubscripts(base, noCalls) {
+    if (eat(_dot)) {
+      var node = startNodeFrom(base);
+      node.object = base;
+      node.property = parseIdent(true);
+      node.computed = false;
+      return parseSubscripts(finishNode(node, "MemberExpression"), noCalls);
+    } else if (eat(_bracketL)) {
+      var node = startNodeFrom(base);
+      node.object = base;
+      node.property = parseExpression();
+      node.computed = true;
+      expect(_bracketR);
+      return parseSubscripts(finishNode(node, "MemberExpression"), noCalls);
+    } else if (!noCalls && eat(_parenL)) {
+      var node = startNodeFrom(base);
+      node.callee = base;
+      node.arguments = parseExprList(_parenR, false);
+      return parseSubscripts(finishNode(node, "CallExpression"), noCalls);
+    } else return base;
+  }
+
+  // Parse an atomic expression — either a single token that is an
+  // expression, an expression started by a keyword like `function` or
+  // `new`, or an expression wrapped in punctuation like `()`, `[]`,
+  // or `{}`.
+
+  function parseExprAtom() {
+    switch (tokType) {
+    case _this:
+      var node = startNode();
+      next();
+      return finishNode(node, "ThisExpression");
+    case _name:
+      return parseIdent();
+    case _num: case _string: case _regexp:
+      var node = startNode();
+      node.value = tokVal;
+      node.raw = input.slice(tokStart, tokEnd);
+      next();
+      return finishNode(node, "Literal");
+
+    case _null: case _true: case _false:
+      var node = startNode();
+      node.value = tokType.atomValue;
+      next();
+      return finishNode(node, "Literal");
+
+    case _parenL:
+      next();
+      var val = parseExpression();
+      expect(_parenR);
+      return val;
+
+    case _bracketL:
+      var node = startNode();
+      next();
+      node.elements = parseExprList(_bracketR, true, true);
+      return finishNode(node, "ArrayExpression");
+
+    case _braceL:
+      return parseObj();
+
+    case _function:
+      var node = startNode();
+      next();
+      return parseFunction(node, false);
+
+    case _new:
+      return parseNew();
+
+    default:
+      unexpected();
+    }
+  }
+
+  // New's precedence is slightly tricky. It must allow its argument
+  // to be a `[]` or dot subscript expression, but not a call — at
+  // least, not without wrapping it in parentheses. Thus, it uses the 
+
+  function parseNew() {
+    var node = startNode();
+    next();
+    node.callee = parseSubscripts(parseExprAtom(false), true);
+    if (eat(_parenL)) node.arguments = parseExprList(_parenR, false);
+    else node.arguments = [];
+    return finishNode(node, "NewExpression");
+  }
+
+  // Parse an object literal.
+
+  function parseObj() {
+    var node = startNode(), first = true, sawGetSet = false;
+    node.properties = [];
+    next();
+    while (!eat(_braceR)) {
+      if (!first) {
+        expect(_comma);
+        if (options.allowTrailingCommas && eat(_braceR)) break;
+      } else first = false;
+
+      var prop = {key: parsePropertyName()}, isGetSet = false, kind;
+      if (eat(_colon)) {
+        prop.value = parseExpression(true);
+        kind = prop.kind = "init";
+      } else if (options.ecmaVersion >= 5 && prop.key.type === "Identifier" &&
+                 (prop.key.name === "get" || prop.key.name === "set")) {
+        isGetSet = sawGetSet = true;
+        kind = prop.kind = prop.key.name;
+        prop.key = parsePropertyName();
+        if (!tokType === _parenL) unexpected();
+        prop.value = parseFunction(startNode(), false);
+      } else unexpected();
+
+      // getters and setters are not allowed to clash — either with
+      // each other or with an init property — and in strict mode,
+      // init properties are also not allowed to be repeated.
+
+      if (prop.key.type === "Identifier" && (strict || sawGetSet)) {
+        for (var i = 0; i < node.properties.length; ++i) {
+          var other = node.properties[i];
+          if (other.key.name === prop.key.name) {
+            var conflict = kind == other.kind || isGetSet && other.kind === "init" ||
+              kind === "init" && (other.kind === "get" || other.kind === "set");
+            if (conflict && !strict && kind === "init" && other.kind === "init") conflict = false;
+            if (conflict) raise(prop.key.start, "Redefinition of property");
+          }
+        }
+      }
+      node.properties.push(prop);
+    }
+    return finishNode(node, "ObjectExpression");
+  }
+
+  function parsePropertyName() {
+    if (tokType === _num || tokType === _string) return parseExprAtom();
+    return parseIdent(true);
+  }
+
+  // Parse a function declaration or literal (depending on the
+  // `isStatement` parameter).
+
+  function parseFunction(node, isStatement) {
+    if (tokType === _name) node.id = parseIdent();
+    else if (isStatement) unexpected();
+    else node.id = null;
+    node.params = [];
+    var first = true;
+    expect(_parenL);
+    while (!eat(_parenR)) {
+      if (!first) expect(_comma); else first = false;
+      node.params.push(parseIdent());
+    }
+
+    // Start a new scope with regard to labels and the `inFunction`
+    // flag (restore them to their old value afterwards).
+    var oldInFunc = inFunction, oldLabels = labels;
+    inFunction = true; labels = [];
+    node.body = parseBlock(true);
+    inFunction = oldInFunc; labels = oldLabels;
+
+    // If this is a strict mode function, verify that argument names
+    // are not repeated, and it does not try to bind the words `eval`
+    // or `arguments`.
+    if (strict || node.body.body.length && isUseStrict(node.body.body[0])) {
+      for (var i = node.id ? -1 : 0; i < node.params.length; ++i) {
+        var id = i < 0 ? node.id : node.params[i];
+        if (isStrictReservedWord(id.name) || isStrictBadIdWord(id.name))
+          raise(id.start, "Defining '" + id.name + "' in strict mode");
+        if (i >= 0) for (var j = 0; j < i; ++j) if (id.name === node.params[j].name)
+          raise(id.start, "Argument name clash in strict mode");
+      }
+    }
+
+    return finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression");
+  }
+
+  // Parses a comma-separated list of expressions, and returns them as
+  // an array. `close` is the token type that ends the list, and
+  // `allowEmpty` can be turned on to allow subsequent commas with
+  // nothing in between them to be parsed as `null` (which is needed
+  // for array literals).
+
+  function parseExprList(close, allowTrailingComma, allowEmpty) {
+    var elts = [], first = true;
+    while (!eat(close)) {
+      if (!first) {
+        expect(_comma);
+        if (allowTrailingComma && options.allowTrailingCommas && eat(close)) break;
+      } else first = false;
+
+      if (allowEmpty && tokType === _comma) elts.push(null);
+      else elts.push(parseExpression(true));
+    }
+    return elts;
+  }
+
+  // Parse the next token as an identifier. If `liberal` is true (used
+  // when parsing properties), it will also convert keywords into
+  // identifiers.
+
+  function parseIdent(liberal) {
+    var node = startNode();
+    node.name = tokType === _name ? tokVal : (liberal && !options.forbidReserved && tokType.keyword) || unexpected();
+    next();
+    return finishNode(node, "Identifier");
+  }
+
+})(typeof exports === "undefined" ? (window.acorn = {}) : exports);
diff --git a/third-party/codemirror-3.15/test/lint/lint.js b/third-party/codemirror-3.15/test/lint/lint.js
new file mode 100644 (file)
index 0000000..4fc577f
--- /dev/null
@@ -0,0 +1,112 @@
+/*
+ Simple linter, based on the Acorn [1] parser module
+
+ All of the existing linters either cramp my style or have huge
+ dependencies (Closure). So here's a very simple, non-invasive one
+ that only spots
+
+  - missing semicolons and trailing commas
+  - variables or properties that are reserved words
+  - assigning to a variable you didn't declare
+
+ [1]: https://github.com/marijnh/acorn/
+*/
+
+var fs = require("fs"), acorn = require("./acorn.js"), walk = require("./walk.js");
+
+var scopePasser = walk.make({
+  ScopeBody: function(node, prev, c) { c(node, node.scope); }
+});
+
+function checkFile(fileName) {
+  var file = fs.readFileSync(fileName, "utf8"), notAllowed;
+  if (notAllowed = file.match(/[\x00-\x08\x0b\x0c\x0e-\x19\uFEFF\t]|[ \t]\n/)) {
+    var msg;
+    if (notAllowed[0] == "\t") msg = "Found tab character";
+    else if (notAllowed[0].indexOf("\n") > -1) msg = "Trailing whitespace";
+    else msg = "Undesirable character " + notAllowed[0].charCodeAt(0);
+    var info = acorn.getLineInfo(file, notAllowed.index);
+    fail(msg + " at line " + info.line + ", column " + info.column, {source: fileName});
+  }
+
+  try {
+    var parsed = acorn.parse(file, {
+      locations: true,
+      ecmaVersion: 3,
+      strictSemicolons: true,
+      allowTrailingCommas: false,
+      forbidReserved: true,
+      sourceFile: fileName
+    });
+  } catch (e) {
+    fail(e.message, {source: fileName});
+    return;
+  }
+
+  var scopes = [];
+
+  walk.simple(parsed, {
+    ScopeBody: function(node, scope) {
+      node.scope = scope;
+      scopes.push(scope);
+    }
+  }, walk.scopeVisitor, {vars: Object.create(null)});
+
+  var ignoredGlobals = Object.create(null);
+
+  function inScope(name, scope) {
+    for (var cur = scope; cur; cur = cur.prev)
+      if (name in cur.vars) return true;
+  }
+  function checkLHS(node, scope) {
+    if (node.type == "Identifier" && !(node.name in ignoredGlobals) &&
+        !inScope(node.name, scope)) {
+      ignoredGlobals[node.name] = true;
+      fail("Assignment to global variable", node.loc);
+    }
+  }
+
+  walk.simple(parsed, {
+    UpdateExpression: function(node, scope) {checkLHS(node.argument, scope);},
+    AssignmentExpression: function(node, scope) {checkLHS(node.left, scope);},
+    Identifier: function(node, scope) {
+      // Mark used identifiers
+      for (var cur = scope; cur; cur = cur.prev)
+        if (node.name in cur.vars) {
+          cur.vars[node.name].used = true;
+          return;
+        }
+    },
+    FunctionExpression: function(node) {
+      if (node.id) fail("Named function expression", node.loc);
+    }
+  }, scopePasser);
+
+  for (var i = 0; i < scopes.length; ++i) {
+    var scope = scopes[i];
+    for (var name in scope.vars) {
+      var info = scope.vars[name];
+      if (!info.used && info.type != "catch clause" && info.type != "function name" && name.charAt(0) != "_")
+        fail("Unused " + info.type + " " + name, info.node.loc);
+    }
+  }
+}
+
+var failed = false;
+function fail(msg, pos) {
+  if (pos.start) msg += " (" + pos.start.line + ":" + pos.start.column + ")";
+  console.log(pos.source + ": " + msg);
+  failed = true;
+}
+
+function checkDir(dir) {
+  fs.readdirSync(dir).forEach(function(file) {
+    var fname = dir + "/" + file;
+    if (/\.js$/.test(file)) checkFile(fname);
+    else if (file != "dep" && fs.lstatSync(fname).isDirectory()) checkDir(fname);
+  });
+}
+
+exports.checkDir = checkDir;
+exports.checkFile = checkFile;
+exports.success = function() { return !failed; };
diff --git a/third-party/codemirror-3.15/test/lint/parse-js.js b/third-party/codemirror-3.15/test/lint/parse-js.js
new file mode 100644 (file)
index 0000000..c165a27
--- /dev/null
@@ -0,0 +1,1372 @@
+/***********************************************************************
+
+  A JavaScript tokenizer / parser / beautifier / compressor.
+
+  This version is suitable for Node.js.  With minimal changes (the
+  exports stuff) it should work on any JS platform.
+
+  This file contains the tokenizer/parser.  It is a port to JavaScript
+  of parse-js [1], a JavaScript parser library written in Common Lisp
+  by Marijn Haverbeke.  Thank you Marijn!
+
+  [1] http://marijn.haverbeke.nl/parse-js/
+
+  Exported functions:
+
+    - tokenizer(code) -- returns a function.  Call the returned
+      function to fetch the next token.
+
+    - parse(code) -- returns an AST of the given JavaScript code.
+
+  -------------------------------- (C) ---------------------------------
+
+                           Author: Mihai Bazon
+                         <mihai.bazon@gmail.com>
+                       http://mihai.bazon.net/blog
+
+  Distributed under the BSD license:
+
+    Copyright 2010 (c) Mihai Bazon <mihai.bazon@gmail.com>
+    Based on parse-js (http://marijn.haverbeke.nl/parse-js/).
+
+    Redistribution and use in source and binary forms, with or without
+    modification, are permitted provided that the following conditions
+    are met:
+
+        * Redistributions of source code must retain the above
+          copyright notice, this list of conditions and the following
+          disclaimer.
+
+        * Redistributions in binary form must reproduce the above
+          copyright notice, this list of conditions and the following
+          disclaimer in the documentation and/or other materials
+          provided with the distribution.
+
+    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
+    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+    IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+    PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
+    LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
+    OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+    PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+    PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
+    TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
+    THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+    SUCH DAMAGE.
+
+ ***********************************************************************/
+
+/* -----[ Tokenizer (constants) ]----- */
+
+var KEYWORDS = array_to_hash([
+        "break",
+        "case",
+        "catch",
+        "const",
+        "continue",
+        "debugger",
+        "default",
+        "delete",
+        "do",
+        "else",
+        "finally",
+        "for",
+        "function",
+        "if",
+        "in",
+        "instanceof",
+        "new",
+        "return",
+        "switch",
+        "throw",
+        "try",
+        "typeof",
+        "var",
+        "void",
+        "while",
+        "with"
+]);
+
+var RESERVED_WORDS = array_to_hash([
+        "abstract",
+        "boolean",
+        "byte",
+        "char",
+        "class",
+        "double",
+        "enum",
+        "export",
+        "extends",
+        "final",
+        "float",
+        "goto",
+        "implements",
+        "import",
+        "int",
+        "interface",
+        "long",
+        "native",
+        "package",
+        "private",
+        "protected",
+        "public",
+        "short",
+        "static",
+        "super",
+        "synchronized",
+        "throws",
+        "transient",
+        "volatile"
+]);
+
+var KEYWORDS_BEFORE_EXPRESSION = array_to_hash([
+        "return",
+        "new",
+        "delete",
+        "throw",
+        "else",
+        "case"
+]);
+
+var KEYWORDS_ATOM = array_to_hash([
+        "false",
+        "null",
+        "true",
+        "undefined"
+]);
+
+var OPERATOR_CHARS = array_to_hash(characters("+-*&%=<>!?|~^"));
+
+var RE_HEX_NUMBER = /^0x[0-9a-f]+$/i;
+var RE_OCT_NUMBER = /^0[0-7]+$/;
+var RE_DEC_NUMBER = /^\d*\.?\d*(?:e[+-]?\d*(?:\d\.?|\.?\d)\d*)?$/i;
+
+var OPERATORS = array_to_hash([
+        "in",
+        "instanceof",
+        "typeof",
+        "new",
+        "void",
+        "delete",
+        "++",
+        "--",
+        "+",
+        "-",
+        "!",
+        "~",
+        "&",
+        "|",
+        "^",
+        "*",
+        "/",
+        "%",
+        ">>",
+        "<<",
+        ">>>",
+        "<",
+        ">",
+        "<=",
+        ">=",
+        "==",
+        "===",
+        "!=",
+        "!==",
+        "?",
+        "=",
+        "+=",
+        "-=",
+        "/=",
+        "*=",
+        "%=",
+        ">>=",
+        "<<=",
+        ">>>=",
+        "|=",
+        "^=",
+        "&=",
+        "&&",
+        "||"
+]);
+
+var WHITESPACE_CHARS = array_to_hash(characters(" \u00a0\n\r\t\f\u000b\u200b\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000"));
+
+var PUNC_BEFORE_EXPRESSION = array_to_hash(characters("[{(,.;:"));
+
+var PUNC_CHARS = array_to_hash(characters("[]{}(),;:"));
+
+var REGEXP_MODIFIERS = array_to_hash(characters("gmsiy"));
+
+/* -----[ Tokenizer ]----- */
+
+var UNICODE = {  // Unicode 6.1
+        letter: new RegExp("[\\u0041-\\u005A\\u0061-\\u007A\\u00AA\\u00B5\\u00BA\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u0527\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u08A0\\u08A2-\\u08AC\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0977\\u0979-\\u097F\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C33\\u0C35-\\u0C39\\u0C3D\\u0C58\\u0C59\\u0C60\\u0C61\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0CF1\\u0CF2\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D60\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F0\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191C\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19C1-\\u19C7\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1CE9-\\u1CEC\\u1CEE-\\u1CF1\\u1CF5\\u1CF6\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FCC\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA697\\uA6A0-\\uA6EF\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA78E\\uA790-\\uA793\\uA7A0-\\uA7AA\\uA7F8-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA80-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uABC0-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]"),
+        combining_mark: new RegExp("[\\u0300-\\u036F\\u0483-\\u0487\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u0610-\\u061A\\u064B-\\u065F\\u0670\\u06D6-\\u06DC\\u06DF-\\u06E4\\u06E7\\u06E8\\u06EA-\\u06ED\\u0711\\u0730-\\u074A\\u07A6-\\u07B0\\u07EB-\\u07F3\\u0816-\\u0819\\u081B-\\u0823\\u0825-\\u0827\\u0829-\\u082D\\u0859-\\u085B\\u08E4-\\u08FE\\u0900-\\u0903\\u093A-\\u093C\\u093E-\\u094F\\u0951-\\u0957\\u0962\\u0963\\u0981-\\u0983\\u09BC\\u09BE-\\u09C4\\u09C7\\u09C8\\u09CB-\\u09CD\\u09D7\\u09E2\\u09E3\\u0A01-\\u0A03\\u0A3C\\u0A3E-\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A70\\u0A71\\u0A75\\u0A81-\\u0A83\\u0ABC\\u0ABE-\\u0AC5\\u0AC7-\\u0AC9\\u0ACB-\\u0ACD\\u0AE2\\u0AE3\\u0B01-\\u0B03\\u0B3C\\u0B3E-\\u0B44\\u0B47\\u0B48\\u0B4B-\\u0B4D\\u0B56\\u0B57\\u0B62\\u0B63\\u0B82\\u0BBE-\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCD\\u0BD7\\u0C01-\\u0C03\\u0C3E-\\u0C44\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C62\\u0C63\\u0C82\\u0C83\\u0CBC\\u0CBE-\\u0CC4\\u0CC6-\\u0CC8\\u0CCA-\\u0CCD\\u0CD5\\u0CD6\\u0CE2\\u0CE3\\u0D02\\u0D03\\u0D3E-\\u0D44\\u0D46-\\u0D48\\u0D4A-\\u0D4D\\u0D57\\u0D62\\u0D63\\u0D82\\u0D83\\u0DCA\\u0DCF-\\u0DD4\\u0DD6\\u0DD8-\\u0DDF\\u0DF2\\u0DF3\\u0E31\\u0E34-\\u0E3A\\u0E47-\\u0E4E\\u0EB1\\u0EB4-\\u0EB9\\u0EBB\\u0EBC\\u0EC8-\\u0ECD\\u0F18\\u0F19\\u0F35\\u0F37\\u0F39\\u0F3E\\u0F3F\\u0F71-\\u0F84\\u0F86\\u0F87\\u0F8D-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u102B-\\u103E\\u1056-\\u1059\\u105E-\\u1060\\u1062-\\u1064\\u1067-\\u106D\\u1071-\\u1074\\u1082-\\u108D\\u108F\\u109A-\\u109D\\u135D-\\u135F\\u1712-\\u1714\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17B4-\\u17D3\\u17DD\\u180B-\\u180D\\u18A9\\u1920-\\u192B\\u1930-\\u193B\\u19B0-\\u19C0\\u19C8\\u19C9\\u1A17-\\u1A1B\\u1A55-\\u1A5E\\u1A60-\\u1A7C\\u1A7F\\u1B00-\\u1B04\\u1B34-\\u1B44\\u1B6B-\\u1B73\\u1B80-\\u1B82\\u1BA1-\\u1BAD\\u1BE6-\\u1BF3\\u1C24-\\u1C37\\u1CD0-\\u1CD2\\u1CD4-\\u1CE8\\u1CED\\u1CF2-\\u1CF4\\u1DC0-\\u1DE6\\u1DFC-\\u1DFF\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2CEF-\\u2CF1\\u2D7F\\u2DE0-\\u2DFF\\u302A-\\u302F\\u3099\\u309A\\uA66F\\uA674-\\uA67D\\uA69F\\uA6F0\\uA6F1\\uA802\\uA806\\uA80B\\uA823-\\uA827\\uA880\\uA881\\uA8B4-\\uA8C4\\uA8E0-\\uA8F1\\uA926-\\uA92D\\uA947-\\uA953\\uA980-\\uA983\\uA9B3-\\uA9C0\\uAA29-\\uAA36\\uAA43\\uAA4C\\uAA4D\\uAA7B\\uAAB0\\uAAB2-\\uAAB4\\uAAB7\\uAAB8\\uAABE\\uAABF\\uAAC1\\uAAEB-\\uAAEF\\uAAF5\\uAAF6\\uABE3-\\uABEA\\uABEC\\uABED\\uFB1E\\uFE00-\\uFE0F\\uFE20-\\uFE26]"),
+        connector_punctuation: new RegExp("[\\u005F\\u203F\\u2040\\u2054\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFF3F]"),
+        digit: new RegExp("[\\u0030-\\u0039\\u0660-\\u0669\\u06F0-\\u06F9\\u07C0-\\u07C9\\u0966-\\u096F\\u09E6-\\u09EF\\u0A66-\\u0A6F\\u0AE6-\\u0AEF\\u0B66-\\u0B6F\\u0BE6-\\u0BEF\\u0C66-\\u0C6F\\u0CE6-\\u0CEF\\u0D66-\\u0D6F\\u0E50-\\u0E59\\u0ED0-\\u0ED9\\u0F20-\\u0F29\\u1040-\\u1049\\u1090-\\u1099\\u17E0-\\u17E9\\u1810-\\u1819\\u1946-\\u194F\\u19D0-\\u19D9\\u1A80-\\u1A89\\u1A90-\\u1A99\\u1B50-\\u1B59\\u1BB0-\\u1BB9\\u1C40-\\u1C49\\u1C50-\\u1C59\\uA620-\\uA629\\uA8D0-\\uA8D9\\uA900-\\uA909\\uA9D0-\\uA9D9\\uAA50-\\uAA59\\uABF0-\\uABF9\\uFF10-\\uFF19]")
+};
+
+function is_letter(ch) {
+        return UNICODE.letter.test(ch);
+};
+
+function is_digit(ch) {
+        ch = ch.charCodeAt(0);
+        return ch >= 48 && ch <= 57;
+};
+
+function is_unicode_digit(ch) {
+        return UNICODE.digit.test(ch);
+}
+
+function is_alphanumeric_char(ch) {
+        return is_digit(ch) || is_letter(ch);
+};
+
+function is_unicode_combining_mark(ch) {
+        return UNICODE.combining_mark.test(ch);
+};
+
+function is_unicode_connector_punctuation(ch) {
+        return UNICODE.connector_punctuation.test(ch);
+};
+
+function is_identifier_start(ch) {
+        return ch == "$" || ch == "_" || is_letter(ch);
+};
+
+function is_identifier_char(ch) {
+        return is_identifier_start(ch)
+                || is_unicode_combining_mark(ch)
+                || is_unicode_digit(ch)
+                || is_unicode_connector_punctuation(ch)
+                || ch == "\u200c" // zero-width non-joiner <ZWNJ>
+                || ch == "\u200d" // zero-width joiner <ZWJ> (in my ECMA-262 PDF, this is also 200c)
+        ;
+};
+
+function parse_js_number(num) {
+        if (RE_HEX_NUMBER.test(num)) {
+                return parseInt(num.substr(2), 16);
+        } else if (RE_OCT_NUMBER.test(num)) {
+                return parseInt(num.substr(1), 8);
+        } else if (RE_DEC_NUMBER.test(num)) {
+                return parseFloat(num);
+        }
+};
+
+function JS_Parse_Error(message, line, col, pos) {
+        this.message = message;
+        this.line = line + 1;
+        this.col = col + 1;
+        this.pos = pos + 1;
+        this.stack = new Error().stack;
+};
+
+JS_Parse_Error.prototype.toString = function() {
+        return this.message + " (line: " + this.line + ", col: " + this.col + ", pos: " + this.pos + ")" + "\n\n" + this.stack;
+};
+
+function js_error(message, line, col, pos) {
+        throw new JS_Parse_Error(message, line, col, pos);
+};
+
+function is_token(token, type, val) {
+        return token.type == type && (val == null || token.value == val);
+};
+
+var EX_EOF = {};
+
+function tokenizer($TEXT) {
+
+        var S = {
+                text            : $TEXT.replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/^\uFEFF/, ''),
+                pos             : 0,
+                tokpos          : 0,
+                line            : 0,
+                tokline         : 0,
+                col             : 0,
+                tokcol          : 0,
+                newline_before  : false,
+                regex_allowed   : false,
+                comments_before : []
+        };
+
+        function peek() { return S.text.charAt(S.pos); };
+
+        function next(signal_eof, in_string) {
+                var ch = S.text.charAt(S.pos++);
+                if (signal_eof && !ch)
+                        throw EX_EOF;
+                if (ch == "\n") {
+                        S.newline_before = S.newline_before || !in_string;
+                        ++S.line;
+                        S.col = 0;
+                } else {
+                        ++S.col;
+                }
+                return ch;
+        };
+
+        function eof() {
+                return !S.peek();
+        };
+
+        function find(what, signal_eof) {
+                var pos = S.text.indexOf(what, S.pos);
+                if (signal_eof && pos == -1) throw EX_EOF;
+                return pos;
+        };
+
+        function start_token() {
+                S.tokline = S.line;
+                S.tokcol = S.col;
+                S.tokpos = S.pos;
+        };
+
+        function token(type, value, is_comment) {
+                S.regex_allowed = ((type == "operator" && !HOP(UNARY_POSTFIX, value)) ||
+                                   (type == "keyword" && HOP(KEYWORDS_BEFORE_EXPRESSION, value)) ||
+                                   (type == "punc" && HOP(PUNC_BEFORE_EXPRESSION, value)));
+                var ret = {
+                        type   : type,
+                        value  : value,
+                        line   : S.tokline,
+                        col    : S.tokcol,
+                        pos    : S.tokpos,
+                        endpos : S.pos,
+                        nlb    : S.newline_before
+                };
+                if (!is_comment) {
+                        ret.comments_before = S.comments_before;
+                        S.comments_before = [];
+                        // make note of any newlines in the comments that came before
+                        for (var i = 0, len = ret.comments_before.length; i < len; i++) {
+                                ret.nlb = ret.nlb || ret.comments_before[i].nlb;
+                        }
+                }
+                S.newline_before = false;
+                return ret;
+        };
+
+        function skip_whitespace() {
+                while (HOP(WHITESPACE_CHARS, peek()))
+                        next();
+        };
+
+        function read_while(pred) {
+                var ret = "", ch = peek(), i = 0;
+                while (ch && pred(ch, i++)) {
+                        ret += next();
+                        ch = peek();
+                }
+                return ret;
+        };
+
+        function parse_error(err) {
+                js_error(err, S.tokline, S.tokcol, S.tokpos);
+        };
+
+        function read_num(prefix) {
+                var has_e = false, after_e = false, has_x = false, has_dot = prefix == ".";
+                var num = read_while(function(ch, i){
+                        if (ch == "x" || ch == "X") {
+                                if (has_x) return false;
+                                return has_x = true;
+                        }
+                        if (!has_x && (ch == "E" || ch == "e")) {
+                                if (has_e) return false;
+                                return has_e = after_e = true;
+                        }
+                        if (ch == "-") {
+                                if (after_e || (i == 0 && !prefix)) return true;
+                                return false;
+                        }
+                        if (ch == "+") return after_e;
+                        after_e = false;
+                        if (ch == ".") {
+                                if (!has_dot && !has_x && !has_e)
+                                        return has_dot = true;
+                                return false;
+                        }
+                        return is_alphanumeric_char(ch);
+                });
+                if (prefix)
+                        num = prefix + num;
+                var valid = parse_js_number(num);
+                if (!isNaN(valid)) {
+                        return token("num", valid);
+                } else {
+                        parse_error("Invalid syntax: " + num);
+                }
+        };
+
+        function read_escaped_char(in_string) {
+                var ch = next(true, in_string);
+                switch (ch) {
+                    case "n" : return "\n";
+                    case "r" : return "\r";
+                    case "t" : return "\t";
+                    case "b" : return "\b";
+                    case "v" : return "\u000b";
+                    case "f" : return "\f";
+                    case "0" : return "\0";
+                    case "x" : return String.fromCharCode(hex_bytes(2));
+                    case "u" : return String.fromCharCode(hex_bytes(4));
+                    case "\n": return "";
+                    default  : return ch;
+                }
+        };
+
+        function hex_bytes(n) {
+                var num = 0;
+                for (; n > 0; --n) {
+                        var digit = parseInt(next(true), 16);
+                        if (isNaN(digit))
+                                parse_error("Invalid hex-character pattern in string");
+                        num = (num << 4) | digit;
+                }
+                return num;
+        };
+
+        function read_string() {
+                return with_eof_error("Unterminated string constant", function(){
+                        var quote = next(), ret = "";
+                        for (;;) {
+                                var ch = next(true);
+                                if (ch == "\\") {
+                                        // read OctalEscapeSequence (XXX: deprecated if "strict mode")
+                                        // https://github.com/mishoo/UglifyJS/issues/178
+                                        var octal_len = 0, first = null;
+                                        ch = read_while(function(ch){
+                                                if (ch >= "0" && ch <= "7") {
+                                                        if (!first) {
+                                                                first = ch;
+                                                                return ++octal_len;
+                                                        }
+                                                        else if (first <= "3" && octal_len <= 2) return ++octal_len;
+                                                        else if (first >= "4" && octal_len <= 1) return ++octal_len;
+                                                }
+                                                return false;
+                                        });
+                                        if (octal_len > 0) ch = String.fromCharCode(parseInt(ch, 8));
+                                        else ch = read_escaped_char(true);
+                                }
+                                else if (ch == quote) break;
+                                ret += ch;
+                        }
+                        return token("string", ret);
+                });
+        };
+
+        function read_line_comment() {
+                next();
+                var i = find("\n"), ret;
+                if (i == -1) {
+                        ret = S.text.substr(S.pos);
+                        S.pos = S.text.length;
+                } else {
+                        ret = S.text.substring(S.pos, i);
+                        S.pos = i;
+                }
+                return token("comment1", ret, true);
+        };
+
+        function read_multiline_comment() {
+                next();
+                return with_eof_error("Unterminated multiline comment", function(){
+                        var i = find("*/", true),
+                            text = S.text.substring(S.pos, i);
+                        S.pos = i + 2;
+                        S.line += text.split("\n").length - 1;
+                        S.newline_before = S.newline_before || text.indexOf("\n") >= 0;
+
+                        // https://github.com/mishoo/UglifyJS/issues/#issue/100
+                        if (/^@cc_on/i.test(text)) {
+                                warn("WARNING: at line " + S.line);
+                                warn("*** Found \"conditional comment\": " + text);
+                                warn("*** UglifyJS DISCARDS ALL COMMENTS.  This means your code might no longer work properly in Internet Explorer.");
+                        }
+
+                        return token("comment2", text, true);
+                });
+        };
+
+        function read_name() {
+                var backslash = false, name = "", ch, escaped = false, hex;
+                while ((ch = peek()) != null) {
+                        if (!backslash) {
+                                if (ch == "\\") escaped = backslash = true, next();
+                                else if (is_identifier_char(ch)) name += next();
+                                else break;
+                        }
+                        else {
+                                if (ch != "u") parse_error("Expecting UnicodeEscapeSequence -- uXXXX");
+                                ch = read_escaped_char();
+                                if (!is_identifier_char(ch)) parse_error("Unicode char: " + ch.charCodeAt(0) + " is not valid in identifier");
+                                name += ch;
+                                backslash = false;
+                        }
+                }
+                if (HOP(KEYWORDS, name) && escaped) {
+                        hex = name.charCodeAt(0).toString(16).toUpperCase();
+                        name = "\\u" + "0000".substr(hex.length) + hex + name.slice(1);
+                }
+                return name;
+        };
+
+        function read_regexp(regexp) {
+                return with_eof_error("Unterminated regular expression", function(){
+                        var prev_backslash = false, ch, in_class = false;
+                        while ((ch = next(true))) if (prev_backslash) {
+                                regexp += "\\" + ch;
+                                prev_backslash = false;
+                        } else if (ch == "[") {
+                                in_class = true;
+                                regexp += ch;
+                        } else if (ch == "]" && in_class) {
+                                in_class = false;
+                                regexp += ch;
+                        } else if (ch == "/" && !in_class) {
+                                break;
+                        } else if (ch == "\\") {
+                                prev_backslash = true;
+                        } else {
+                                regexp += ch;
+                        }
+                        var mods = read_name();
+                        return token("regexp", [ regexp, mods ]);
+                });
+        };
+
+        function read_operator(prefix) {
+                function grow(op) {
+                        if (!peek()) return op;
+                        var bigger = op + peek();
+                        if (HOP(OPERATORS, bigger)) {
+                                next();
+                                return grow(bigger);
+                        } else {
+                                return op;
+                        }
+                };
+                return token("operator", grow(prefix || next()));
+        };
+
+        function handle_slash() {
+                next();
+                var regex_allowed = S.regex_allowed;
+                switch (peek()) {
+                    case "/":
+                        S.comments_before.push(read_line_comment());
+                        S.regex_allowed = regex_allowed;
+                        return next_token();
+                    case "*":
+                        S.comments_before.push(read_multiline_comment());
+                        S.regex_allowed = regex_allowed;
+                        return next_token();
+                }
+                return S.regex_allowed ? read_regexp("") : read_operator("/");
+        };
+
+        function handle_dot() {
+                next();
+                return is_digit(peek())
+                        ? read_num(".")
+                        : token("punc", ".");
+        };
+
+        function read_word() {
+                var word = read_name();
+                return !HOP(KEYWORDS, word)
+                        ? token("name", word)
+                        : HOP(OPERATORS, word)
+                        ? token("operator", word)
+                        : HOP(KEYWORDS_ATOM, word)
+                        ? token("atom", word)
+                        : token("keyword", word);
+        };
+
+        function with_eof_error(eof_error, cont) {
+                try {
+                        return cont();
+                } catch(ex) {
+                        if (ex === EX_EOF) parse_error(eof_error);
+                        else throw ex;
+                }
+        };
+
+        function next_token(force_regexp) {
+                if (force_regexp != null)
+                        return read_regexp(force_regexp);
+                skip_whitespace();
+                start_token();
+                var ch = peek();
+                if (!ch) return token("eof");
+                if (is_digit(ch)) return read_num();
+                if (ch == '"' || ch == "'") return read_string();
+                if (HOP(PUNC_CHARS, ch)) return token("punc", next());
+                if (ch == ".") return handle_dot();
+                if (ch == "/") return handle_slash();
+                if (HOP(OPERATOR_CHARS, ch)) return read_operator();
+                if (ch == "\\" || is_identifier_start(ch)) return read_word();
+                parse_error("Unexpected character '" + ch + "'");
+        };
+
+        next_token.context = function(nc) {
+                if (nc) S = nc;
+                return S;
+        };
+
+        return next_token;
+
+};
+
+/* -----[ Parser (constants) ]----- */
+
+var UNARY_PREFIX = array_to_hash([
+        "typeof",
+        "void",
+        "delete",
+        "--",
+        "++",
+        "!",
+        "~",
+        "-",
+        "+"
+]);
+
+var UNARY_POSTFIX = array_to_hash([ "--", "++" ]);
+
+var ASSIGNMENT = (function(a, ret, i){
+        while (i < a.length) {
+                ret[a[i]] = a[i].substr(0, a[i].length - 1);
+                i++;
+        }
+        return ret;
+})(
+        ["+=", "-=", "/=", "*=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&="],
+        { "=": true },
+        0
+);
+
+var PRECEDENCE = (function(a, ret){
+        for (var i = 0, n = 1; i < a.length; ++i, ++n) {
+                var b = a[i];
+                for (var j = 0; j < b.length; ++j) {
+                        ret[b[j]] = n;
+                }
+        }
+        return ret;
+})(
+        [
+                ["||"],
+                ["&&"],
+                ["|"],
+                ["^"],
+                ["&"],
+                ["==", "===", "!=", "!=="],
+                ["<", ">", "<=", ">=", "in", "instanceof"],
+                [">>", "<<", ">>>"],
+                ["+", "-"],
+                ["*", "/", "%"]
+        ],
+        {}
+);
+
+var STATEMENTS_WITH_LABELS = array_to_hash([ "for", "do", "while", "switch" ]);
+
+var ATOMIC_START_TOKEN = array_to_hash([ "atom", "num", "string", "regexp", "name" ]);
+
+/* -----[ Parser ]----- */
+
+function NodeWithToken(str, start, end) {
+        this.name = str;
+        this.start = start;
+        this.end = end;
+};
+
+NodeWithToken.prototype.toString = function() { return this.name; };
+
+function parse($TEXT, exigent_mode, embed_tokens) {
+
+        var S = {
+                input         : typeof $TEXT == "string" ? tokenizer($TEXT, true) : $TEXT,
+                token         : null,
+                prev          : null,
+                peeked        : null,
+                in_function   : 0,
+                in_directives : true,
+                in_loop       : 0,
+                labels        : []
+        };
+
+        S.token = next();
+
+        function is(type, value) {
+                return is_token(S.token, type, value);
+        };
+
+        function peek() { return S.peeked || (S.peeked = S.input()); };
+
+        function next() {
+                S.prev = S.token;
+                if (S.peeked) {
+                        S.token = S.peeked;
+                        S.peeked = null;
+                } else {
+                        S.token = S.input();
+                }
+                S.in_directives = S.in_directives && (
+                        S.token.type == "string" || is("punc", ";")
+                );
+                return S.token;
+        };
+
+        function prev() {
+                return S.prev;
+        };
+
+        function croak(msg, line, col, pos) {
+                var ctx = S.input.context();
+                js_error(msg,
+                         line != null ? line : ctx.tokline,
+                         col != null ? col : ctx.tokcol,
+                         pos != null ? pos : ctx.tokpos);
+        };
+
+        function token_error(token, msg) {
+                croak(msg, token.line, token.col);
+        };
+
+        function unexpected(token) {
+                if (token == null)
+                        token = S.token;
+                token_error(token, "Unexpected token: " + token.type + " (" + token.value + ")");
+        };
+
+        function expect_token(type, val) {
+                if (is(type, val)) {
+                        return next();
+                }
+                token_error(S.token, "Unexpected token " + S.token.type + ", expected " + type);
+        };
+
+        function expect(punc) { return expect_token("punc", punc); };
+
+        function can_insert_semicolon() {
+                return !exigent_mode && (
+                        S.token.nlb || is("eof") || is("punc", "}")
+                );
+        };
+
+        function semicolon() {
+                if (is("punc", ";")) next();
+                else if (!can_insert_semicolon()) unexpected();
+        };
+
+        function as() {
+                return slice(arguments);
+        };
+
+        function parenthesised() {
+                expect("(");
+                var ex = expression();
+                expect(")");
+                return ex;
+        };
+
+        function add_tokens(str, start, end) {
+                return str instanceof NodeWithToken ? str : new NodeWithToken(str, start, end);
+        };
+
+        function maybe_embed_tokens(parser) {
+                if (embed_tokens) return function() {
+                        var start = S.token;
+                        var ast = parser.apply(this, arguments);
+                        ast[0] = add_tokens(ast[0], start, prev());
+                        return ast;
+                };
+                else return parser;
+        };
+
+        var statement = maybe_embed_tokens(function() {
+                if (is("operator", "/") || is("operator", "/=")) {
+                        S.peeked = null;
+                        S.token = S.input(S.token.value.substr(1)); // force regexp
+                }
+                switch (S.token.type) {
+                    case "string":
+                        var dir = S.in_directives, stat = simple_statement();
+                        if (dir && stat[1][0] == "string" && !is("punc", ","))
+                            return as("directive", stat[1][1]);
+                        return stat;
+                    case "num":
+                    case "regexp":
+                    case "operator":
+                    case "atom":
+                        return simple_statement();
+
+                    case "name":
+                        return is_token(peek(), "punc", ":")
+                                ? labeled_statement(prog1(S.token.value, next, next))
+                                : simple_statement();
+
+                    case "punc":
+                        switch (S.token.value) {
+                            case "{":
+                                return as("block", block_());
+                            case "[":
+                            case "(":
+                                return simple_statement();
+                            case ";":
+                                next();
+                                return as("block");
+                            default:
+                                unexpected();
+                        }
+
+                    case "keyword":
+                        switch (prog1(S.token.value, next)) {
+                            case "break":
+                                return break_cont("break");
+
+                            case "continue":
+                                return break_cont("continue");
+
+                            case "debugger":
+                                semicolon();
+                                return as("debugger");
+
+                            case "do":
+                                return (function(body){
+                                        expect_token("keyword", "while");
+                                        return as("do", prog1(parenthesised, semicolon), body);
+                                })(in_loop(statement));
+
+                            case "for":
+                                return for_();
+
+                            case "function":
+                                return function_(true);
+
+                            case "if":
+                                return if_();
+
+                            case "return":
+                                if (S.in_function == 0)
+                                        croak("'return' outside of function");
+                                return as("return",
+                                          is("punc", ";")
+                                          ? (next(), null)
+                                          : can_insert_semicolon()
+                                          ? null
+                                          : prog1(expression, semicolon));
+
+                            case "switch":
+                                return as("switch", parenthesised(), switch_block_());
+
+                            case "throw":
+                                if (S.token.nlb)
+                                        croak("Illegal newline after 'throw'");
+                                return as("throw", prog1(expression, semicolon));
+
+                            case "try":
+                                return try_();
+
+                            case "var":
+                                return prog1(var_, semicolon);
+
+                            case "const":
+                                return prog1(const_, semicolon);
+
+                            case "while":
+                                return as("while", parenthesised(), in_loop(statement));
+
+                            case "with":
+                                return as("with", parenthesised(), statement());
+
+                            default:
+                                unexpected();
+                        }
+                }
+        });
+
+        function labeled_statement(label) {
+                S.labels.push(label);
+                var start = S.token, stat = statement();
+                if (exigent_mode && !HOP(STATEMENTS_WITH_LABELS, stat[0]))
+                        unexpected(start);
+                S.labels.pop();
+                return as("label", label, stat);
+        };
+
+        function simple_statement() {
+                return as("stat", prog1(expression, semicolon));
+        };
+
+        function break_cont(type) {
+                var name;
+                if (!can_insert_semicolon()) {
+                        name = is("name") ? S.token.value : null;
+                }
+                if (name != null) {
+                        next();
+                        if (!member(name, S.labels))
+                                croak("Label " + name + " without matching loop or statement");
+                }
+                else if (S.in_loop == 0)
+                        croak(type + " not inside a loop or switch");
+                semicolon();
+                return as(type, name);
+        };
+
+        function for_() {
+                expect("(");
+                var init = null;
+                if (!is("punc", ";")) {
+                        init = is("keyword", "var")
+                                ? (next(), var_(true))
+                                : expression(true, true);
+                        if (is("operator", "in")) {
+                                if (init[0] == "var" && init[1].length > 1)
+                                        croak("Only one variable declaration allowed in for..in loop");
+                                return for_in(init);
+                        }
+                }
+                return regular_for(init);
+        };
+
+        function regular_for(init) {
+                expect(";");
+                var test = is("punc", ";") ? null : expression();
+                expect(";");
+                var step = is("punc", ")") ? null : expression();
+                expect(")");
+                return as("for", init, test, step, in_loop(statement));
+        };
+
+        function for_in(init) {
+                var lhs = init[0] == "var" ? as("name", init[1][0]) : init;
+                next();
+                var obj = expression();
+                expect(")");
+                return as("for-in", init, lhs, obj, in_loop(statement));
+        };
+
+        var function_ = function(in_statement) {
+                var name = is("name") ? prog1(S.token.value, next) : null;
+                if (in_statement && !name)
+                        unexpected();
+                expect("(");
+                return as(in_statement ? "defun" : "function",
+                          name,
+                          // arguments
+                          (function(first, a){
+                                  while (!is("punc", ")")) {
+                                          if (first) first = false; else expect(",");
+                                          if (!is("name")) unexpected();
+                                          a.push(S.token.value);
+                                          next();
+                                  }
+                                  next();
+                                  return a;
+                          })(true, []),
+                          // body
+                          (function(){
+                                  ++S.in_function;
+                                  var loop = S.in_loop;
+                                  S.in_directives = true;
+                                  S.in_loop = 0;
+                                  var a = block_();
+                                  --S.in_function;
+                                  S.in_loop = loop;
+                                  return a;
+                          })());
+        };
+
+        function if_() {
+                var cond = parenthesised(), body = statement(), belse;
+                if (is("keyword", "else")) {
+                        next();
+                        belse = statement();
+                }
+                return as("if", cond, body, belse);
+        };
+
+        function block_() {
+                expect("{");
+                var a = [];
+                while (!is("punc", "}")) {
+                        if (is("eof")) unexpected();
+                        a.push(statement());
+                }
+                next();
+                return a;
+        };
+
+        var switch_block_ = curry(in_loop, function(){
+                expect("{");
+                var a = [], cur = null;
+                while (!is("punc", "}")) {
+                        if (is("eof")) unexpected();
+                        if (is("keyword", "case")) {
+                                next();
+                                cur = [];
+                                a.push([ expression(), cur ]);
+                                expect(":");
+                        }
+                        else if (is("keyword", "default")) {
+                                next();
+                                expect(":");
+                                cur = [];
+                                a.push([ null, cur ]);
+                        }
+                        else {
+                                if (!cur) unexpected();
+                                cur.push(statement());
+                        }
+                }
+                next();
+                return a;
+        });
+
+        function try_() {
+                var body = block_(), bcatch, bfinally;
+                if (is("keyword", "catch")) {
+                        next();
+                        expect("(");
+                        if (!is("name"))
+                                croak("Name expected");
+                        var name = S.token.value;
+                        next();
+                        expect(")");
+                        bcatch = [ name, block_() ];
+                }
+                if (is("keyword", "finally")) {
+                        next();
+                        bfinally = block_();
+                }
+                if (!bcatch && !bfinally)
+                        croak("Missing catch/finally blocks");
+                return as("try", body, bcatch, bfinally);
+        };
+
+        function vardefs(no_in) {
+                var a = [];
+                for (;;) {
+                        if (!is("name"))
+                                unexpected();
+                        var name = S.token.value;
+                        next();
+                        if (is("operator", "=")) {
+                                next();
+                                a.push([ name, expression(false, no_in) ]);
+                        } else {
+                                a.push([ name ]);
+                        }
+                        if (!is("punc", ","))
+                                break;
+                        next();
+                }
+                return a;
+        };
+
+        function var_(no_in) {
+                return as("var", vardefs(no_in));
+        };
+
+        function const_() {
+                return as("const", vardefs());
+        };
+
+        function new_() {
+                var newexp = expr_atom(false), args;
+                if (is("punc", "(")) {
+                        next();
+                        args = expr_list(")");
+                } else {
+                        args = [];
+                }
+                return subscripts(as("new", newexp, args), true);
+        };
+
+        var expr_atom = maybe_embed_tokens(function(allow_calls) {
+                if (is("operator", "new")) {
+                        next();
+                        return new_();
+                }
+                if (is("punc")) {
+                        switch (S.token.value) {
+                            case "(":
+                                next();
+                                return subscripts(prog1(expression, curry(expect, ")")), allow_calls);
+                            case "[":
+                                next();
+                                return subscripts(array_(), allow_calls);
+                            case "{":
+                                next();
+                                return subscripts(object_(), allow_calls);
+                        }
+                        unexpected();
+                }
+                if (is("keyword", "function")) {
+                        next();
+                        return subscripts(function_(false), allow_calls);
+                }
+                if (HOP(ATOMIC_START_TOKEN, S.token.type)) {
+                        var atom = S.token.type == "regexp"
+                                ? as("regexp", S.token.value[0], S.token.value[1])
+                                : as(S.token.type, S.token.value);
+                        return subscripts(prog1(atom, next), allow_calls);
+                }
+                unexpected();
+        });
+
+        function expr_list(closing, allow_trailing_comma, allow_empty) {
+                var first = true, a = [];
+                while (!is("punc", closing)) {
+                        if (first) first = false; else expect(",");
+                        if (allow_trailing_comma && is("punc", closing)) break;
+                        if (is("punc", ",") && allow_empty) {
+                                a.push([ "atom", "undefined" ]);
+                        } else {
+                                a.push(expression(false));
+                        }
+                }
+                next();
+                return a;
+        };
+
+        function array_() {
+                return as("array", expr_list("]", !exigent_mode, true));
+        };
+
+        function object_() {
+                var first = true, a = [];
+                while (!is("punc", "}")) {
+                        if (first) first = false; else expect(",");
+                        if (!exigent_mode && is("punc", "}"))
+                                // allow trailing comma
+                                break;
+                        var type = S.token.type;
+                        var name = as_property_name();
+                        if (type == "name" && (name == "get" || name == "set") && !is("punc", ":")) {
+                                a.push([ as_name(), function_(false), name ]);
+                        } else {
+                                expect(":");
+                                a.push([ name, expression(false) ]);
+                        }
+                        // FIXME [!!] Line not in original parse-js,
+                        // added to be able to warn about unquoted
+                        // keyword properties
+                        a[a.length - 1].type = type;
+                }
+                next();
+                return as("object", a);
+        };
+
+        function as_property_name() {
+                switch (S.token.type) {
+                    case "num":
+                    case "string":
+                        return prog1(S.token.value, next);
+                }
+                return as_name();
+        };
+
+        function as_name() {
+                switch (S.token.type) {
+                    case "name":
+                    case "operator":
+                    case "keyword":
+                    case "atom":
+                        return prog1(S.token.value, next);
+                    default:
+                        unexpected();
+                }
+        };
+
+        function subscripts(expr, allow_calls) {
+                if (is("punc", ".")) {
+                        next();
+                        return subscripts(as("dot", expr, as_name()), allow_calls);
+                }
+                if (is("punc", "[")) {
+                        next();
+                        return subscripts(as("sub", expr, prog1(expression, curry(expect, "]"))), allow_calls);
+                }
+                if (allow_calls && is("punc", "(")) {
+                        next();
+                        return subscripts(as("call", expr, expr_list(")")), true);
+                }
+                return expr;
+        };
+
+        function maybe_unary(allow_calls) {
+                if (is("operator") && HOP(UNARY_PREFIX, S.token.value)) {
+                        return make_unary("unary-prefix",
+                                          prog1(S.token.value, next),
+                                          maybe_unary(allow_calls));
+                }
+                var val = expr_atom(allow_calls);
+                while (is("operator") && HOP(UNARY_POSTFIX, S.token.value) && !S.token.nlb) {
+                        val = make_unary("unary-postfix", S.token.value, val);
+                        next();
+                }
+                return val;
+        };
+
+        function make_unary(tag, op, expr) {
+                if ((op == "++" || op == "--") && !is_assignable(expr))
+                        croak("Invalid use of " + op + " operator");
+                return as(tag, op, expr);
+        };
+
+        function expr_op(left, min_prec, no_in) {
+                var op = is("operator") ? S.token.value : null;
+                if (op && op == "in" && no_in) op = null;
+                var prec = op != null ? PRECEDENCE[op] : null;
+                if (prec != null && prec > min_prec) {
+                        next();
+                        var right = expr_op(maybe_unary(true), prec, no_in);
+                        return expr_op(as("binary", op, left, right), min_prec, no_in);
+                }
+                return left;
+        };
+
+        function expr_ops(no_in) {
+                return expr_op(maybe_unary(true), 0, no_in);
+        };
+
+        function maybe_conditional(no_in) {
+                var expr = expr_ops(no_in);
+                if (is("operator", "?")) {
+                        next();
+                        var yes = expression(false);
+                        expect(":");
+                        return as("conditional", expr, yes, expression(false, no_in));
+                }
+                return expr;
+        };
+
+        function is_assignable(expr) {
+                if (!exigent_mode) return true;
+                switch (expr[0]+"") {
+                    case "dot":
+                    case "sub":
+                    case "new":
+                    case "call":
+                        return true;
+                    case "name":
+                        return expr[1] != "this";
+                }
+        };
+
+        function maybe_assign(no_in) {
+                var left = maybe_conditional(no_in), val = S.token.value;
+                if (is("operator") && HOP(ASSIGNMENT, val)) {
+                        if (is_assignable(left)) {
+                                next();
+                                return as("assign", ASSIGNMENT[val], left, maybe_assign(no_in));
+                        }
+                        croak("Invalid assignment");
+                }
+                return left;
+        };
+
+        var expression = maybe_embed_tokens(function(commas, no_in) {
+                if (arguments.length == 0)
+                        commas = true;
+                var expr = maybe_assign(no_in);
+                if (commas && is("punc", ",")) {
+                        next();
+                        return as("seq", expr, expression(true, no_in));
+                }
+                return expr;
+        });
+
+        function in_loop(cont) {
+                try {
+                        ++S.in_loop;
+                        return cont();
+                } finally {
+                        --S.in_loop;
+                }
+        };
+
+        return as("toplevel", (function(a){
+                while (!is("eof"))
+                        a.push(statement());
+                return a;
+        })([]));
+
+};
+
+/* -----[ Utilities ]----- */
+
+function curry(f) {
+        var args = slice(arguments, 1);
+        return function() { return f.apply(this, args.concat(slice(arguments))); };
+};
+
+function prog1(ret) {
+        if (ret instanceof Function)
+                ret = ret();
+        for (var i = 1, n = arguments.length; --n > 0; ++i)
+                arguments[i]();
+        return ret;
+};
+
+function array_to_hash(a) {
+        var ret = {};
+        for (var i = 0; i < a.length; ++i)
+                ret[a[i]] = true;
+        return ret;
+};
+
+function slice(a, start) {
+        return Array.prototype.slice.call(a, start || 0);
+};
+
+function characters(str) {
+        return str.split("");
+};
+
+function member(name, array) {
+        for (var i = array.length; --i >= 0;)
+                if (array[i] == name)
+                        return true;
+        return false;
+};
+
+function HOP(obj, prop) {
+        return Object.prototype.hasOwnProperty.call(obj, prop);
+};
+
+var warn = function() {};
+
+/* -----[ Exports ]----- */
+
+exports.tokenizer = tokenizer;
+exports.parse = parse;
+exports.slice = slice;
+exports.curry = curry;
+exports.member = member;
+exports.array_to_hash = array_to_hash;
+exports.PRECEDENCE = PRECEDENCE;
+exports.KEYWORDS_ATOM = KEYWORDS_ATOM;
+exports.RESERVED_WORDS = RESERVED_WORDS;
+exports.KEYWORDS = KEYWORDS;
+exports.ATOMIC_START_TOKEN = ATOMIC_START_TOKEN;
+exports.OPERATORS = OPERATORS;
+exports.is_alphanumeric_char = is_alphanumeric_char;
+exports.is_identifier_start = is_identifier_start;
+exports.is_identifier_char = is_identifier_char;
+exports.set_logger = function(logger) {
+        warn = logger;
+};
+
+// Local variables:
+// js-indent-level: 8
+// End:
diff --git a/third-party/codemirror-3.15/test/lint/walk.js b/third-party/codemirror-3.15/test/lint/walk.js
new file mode 100644 (file)
index 0000000..97321ac
--- /dev/null
@@ -0,0 +1,216 @@
+// AST walker module for Mozilla Parser API compatible trees
+
+(function(exports) {
+  "use strict";
+
+  // A simple walk is one where you simply specify callbacks to be
+  // called on specific nodes. The last two arguments are optional. A
+  // simple use would be
+  //
+  //     walk.simple(myTree, {
+  //         Expression: function(node) { ... }
+  //     });
+  //
+  // to do something with all expressions. All Parser API node types
+  // can be used to identify node types, as well as Expression,
+  // Statement, and ScopeBody, which denote categories of nodes.
+  //
+  // The base argument can be used to pass a custom (recursive)
+  // walker, and state can be used to give this walked an initial
+  // state.
+  exports.simple = function(node, visitors, base, state) {
+    if (!base) base = exports;
+    function c(node, st, override) {
+      var type = override || node.type, found = visitors[type];
+      if (found) found(node, st);
+      base[type](node, st, c);
+    }
+    c(node, state);
+  };
+
+  // A recursive walk is one where your functions override the default
+  // walkers. They can modify and replace the state parameter that's
+  // threaded through the walk, and can opt how and whether to walk
+  // their child nodes (by calling their third argument on these
+  // nodes).
+  exports.recursive = function(node, state, funcs, base) {
+    var visitor = exports.make(funcs, base);
+    function c(node, st, override) {
+      visitor[override || node.type](node, st, c);
+    }
+    c(node, state);
+  };
+
+  // Used to create a custom walker. Will fill in all missing node
+  // type properties with the defaults.
+  exports.make = function(funcs, base) {
+    if (!base) base = exports;
+    var visitor = {};
+    for (var type in base)
+      visitor[type] = funcs.hasOwnProperty(type) ? funcs[type] : base[type];
+    return visitor;
+  };
+
+  function skipThrough(node, st, c) { c(node, st); }
+  function ignore(node, st, c) {}
+
+  // Node walkers.
+
+  exports.Program = exports.BlockStatement = function(node, st, c) {
+    for (var i = 0; i < node.body.length; ++i)
+      c(node.body[i], st, "Statement");
+  };
+  exports.Statement = skipThrough;
+  exports.EmptyStatement = ignore;
+  exports.ExpressionStatement = function(node, st, c) {
+    c(node.expression, st, "Expression");
+  };
+  exports.IfStatement = function(node, st, c) {
+    c(node.test, st, "Expression");
+    c(node.consequent, st, "Statement");
+    if (node.alternate) c(node.alternate, st, "Statement");
+  };
+  exports.LabeledStatement = function(node, st, c) {
+    c(node.body, st, "Statement");
+  };
+  exports.BreakStatement = exports.ContinueStatement = ignore;
+  exports.WithStatement = function(node, st, c) {
+    c(node.object, st, "Expression");
+    c(node.body, st, "Statement");
+  };
+  exports.SwitchStatement = function(node, st, c) {
+    c(node.discriminant, st, "Expression");
+    for (var i = 0; i < node.cases.length; ++i) {
+      var cs = node.cases[i];
+      if (cs.test) c(cs.test, st, "Expression");
+      for (var j = 0; j < cs.consequent.length; ++j)
+        c(cs.consequent[j], st, "Statement");
+    }
+  };
+  exports.ReturnStatement = function(node, st, c) {
+    if (node.argument) c(node.argument, st, "Expression");
+  };
+  exports.ThrowStatement = function(node, st, c) {
+    c(node.argument, st, "Expression");
+  };
+  exports.TryStatement = function(node, st, c) {
+    c(node.block, st, "Statement");
+    for (var i = 0; i < node.handlers.length; ++i)
+      c(node.handlers[i].body, st, "ScopeBody");
+    if (node.finalizer) c(node.finalizer, st, "Statement");
+  };
+  exports.WhileStatement = function(node, st, c) {
+    c(node.test, st, "Expression");
+    c(node.body, st, "Statement");
+  };
+  exports.DoWhileStatement = exports.WhileStatement;
+  exports.ForStatement = function(node, st, c) {
+    if (node.init) c(node.init, st, "ForInit");
+    if (node.test) c(node.test, st, "Expression");
+    if (node.update) c(node.update, st, "Expression");
+    c(node.body, st, "Statement");
+  };
+  exports.ForInStatement = function(node, st, c) {
+    c(node.left, st, "ForInit");
+    c(node.right, st, "Expression");
+    c(node.body, st, "Statement");
+  };
+  exports.ForInit = function(node, st, c) {
+    if (node.type == "VariableDeclaration") c(node, st);
+    else c(node, st, "Expression");
+  };
+  exports.DebuggerStatement = ignore;
+
+  exports.FunctionDeclaration = function(node, st, c) {
+    c(node, st, "Function");
+  };
+  exports.VariableDeclaration = function(node, st, c) {
+    for (var i = 0; i < node.declarations.length; ++i) {
+      var decl = node.declarations[i];
+      if (decl.init) c(decl.init, st, "Expression");
+    }
+  };
+
+  exports.Function = function(node, st, c) {
+    c(node.body, st, "ScopeBody");
+  };
+  exports.ScopeBody = function(node, st, c) {
+    c(node, st, "Statement");
+  };
+
+  exports.Expression = skipThrough;
+  exports.ThisExpression = ignore;
+  exports.ArrayExpression = function(node, st, c) {
+    for (var i = 0; i < node.elements.length; ++i) {
+      var elt = node.elements[i];
+      if (elt) c(elt, st, "Expression");
+    }
+  };
+  exports.ObjectExpression = function(node, st, c) {
+    for (var i = 0; i < node.properties.length; ++i)
+      c(node.properties[i].value, st, "Expression");
+  };
+  exports.FunctionExpression = exports.FunctionDeclaration;
+  exports.SequenceExpression = function(node, st, c) {
+    for (var i = 0; i < node.expressions.length; ++i)
+      c(node.expressions[i], st, "Expression");
+  };
+  exports.UnaryExpression = exports.UpdateExpression = function(node, st, c) {
+    c(node.argument, st, "Expression");
+  };
+  exports.BinaryExpression = exports.AssignmentExpression = exports.LogicalExpression = function(node, st, c) {
+    c(node.left, st, "Expression");
+    c(node.right, st, "Expression");
+  };
+  exports.ConditionalExpression = function(node, st, c) {
+    c(node.test, st, "Expression");
+    c(node.consequent, st, "Expression");
+    c(node.alternate, st, "Expression");
+  };
+  exports.NewExpression = exports.CallExpression = function(node, st, c) {
+    c(node.callee, st, "Expression");
+    if (node.arguments) for (var i = 0; i < node.arguments.length; ++i)
+      c(node.arguments[i], st, "Expression");
+  };
+  exports.MemberExpression = function(node, st, c) {
+    c(node.object, st, "Expression");
+    if (node.computed) c(node.property, st, "Expression");
+  };
+  exports.Identifier = exports.Literal = ignore;
+
+  // A custom walker that keeps track of the scope chain and the
+  // variables defined in it.
+  function makeScope(prev) {
+    return {vars: Object.create(null), prev: prev};
+  }
+  exports.scopeVisitor = exports.make({
+    Function: function(node, scope, c) {
+      var inner = makeScope(scope);
+      for (var i = 0; i < node.params.length; ++i)
+        inner.vars[node.params[i].name] = {type: "argument", node: node.params[i]};
+      if (node.id) {
+        var decl = node.type == "FunctionDeclaration";
+        (decl ? scope : inner).vars[node.id.name] =
+          {type: decl ? "function" : "function name", node: node.id};
+      }
+      c(node.body, inner, "ScopeBody");
+    },
+    TryStatement: function(node, scope, c) {
+      c(node.block, scope, "Statement");
+      for (var i = 0; i < node.handlers.length; ++i) {
+        var handler = node.handlers[i], inner = makeScope(scope);
+        inner.vars[handler.param.name] = {type: "catch clause", node: handler.param};
+        c(handler.body, inner, "ScopeBody");
+      }
+      if (node.finalizer) c(node.finalizer, scope, "Statement");
+    },
+    VariableDeclaration: function(node, scope, c) {
+      for (var i = 0; i < node.declarations.length; ++i) {
+        var decl = node.declarations[i];
+        scope.vars[decl.id.name] = {type: "var", node: decl.id};
+        if (decl.init) c(decl.init, scope, "Expression");
+      }
+    }
+  });
+
+})(typeof exports == "undefined" ? acorn.walk = {} : exports);
diff --git a/third-party/codemirror-3.15/test/mode_test.css b/third-party/codemirror-3.15/test/mode_test.css
new file mode 100644 (file)
index 0000000..1ac6673
--- /dev/null
@@ -0,0 +1,10 @@
+.mt-output .mt-token {
+  border: 1px solid #ddd;
+  white-space: pre;
+  font-family: "Consolas", monospace;
+  text-align: center;
+}
+
+.mt-output .mt-style {
+  font-size: x-small;
+}
diff --git a/third-party/codemirror-3.15/test/mode_test.js b/third-party/codemirror-3.15/test/mode_test.js
new file mode 100644 (file)
index 0000000..1439cab
--- /dev/null
@@ -0,0 +1,192 @@
+/**
+ * Helper to test CodeMirror highlighting modes. It pretty prints output of the
+ * highlighter and can check against expected styles.
+ *
+ * Mode tests are registered by calling test.mode(testName, mode,
+ * tokens), where mode is a mode object as returned by
+ * CodeMirror.getMode, and tokens is an array of lines that make up
+ * the test.
+ *
+ * These lines are strings, in which styled stretches of code are
+ * enclosed in brackets `[]`, and prefixed by their style. For
+ * example, `[keyword if]`. Brackets in the code itself must be
+ * duplicated to prevent them from being interpreted as token
+ * boundaries. For example `a[[i]]` for `a[i]`. If a token has
+ * multiple styles, the styles must be separated by ampersands, for
+ * example `[tag&error </hmtl>]`.
+ *
+ * See the test.js files in the css, markdown, gfm, and stex mode
+ * directories for examples.
+ */
+(function() {
+  function findSingle(str, pos, ch) {
+    for (;;) {
+      var found = str.indexOf(ch, pos);
+      if (found == -1) return null;
+      if (str.charAt(found + 1) != ch) return found;
+      pos = found + 2;
+    }
+  }
+
+  var styleName = /[\w&-_]+/g;
+  function parseTokens(strs) {
+    var tokens = [], plain = "";
+    for (var i = 0; i < strs.length; ++i) {
+      if (i) plain += "\n";
+      var str = strs[i], pos = 0;
+      while (pos < str.length) {
+        var style = null, text;
+        if (str.charAt(pos) == "[" && str.charAt(pos+1) != "[") {
+          styleName.lastIndex = pos + 1;
+          var m = styleName.exec(str);
+          style = m[0].replace(/&/g, " ");
+          var textStart = pos + style.length + 2;
+          var end = findSingle(str, textStart, "]");
+          if (end == null) throw new Error("Unterminated token at " + pos + " in '" + str + "'" + style);
+          text = str.slice(textStart, end);
+          pos = end + 1;
+        } else {
+          var end = findSingle(str, pos, "[");
+          if (end == null) end = str.length;
+          text = str.slice(pos, end);
+          pos = end;
+        }
+        text = text.replace(/\[\[|\]\]/g, function(s) {return s.charAt(0);});
+        tokens.push(style, text);
+        plain += text;
+      }
+    }
+    return {tokens: tokens, plain: plain};
+  }
+
+  test.mode = function(name, mode, tokens, modeName) {
+    var data = parseTokens(tokens);
+    return test((modeName || mode.name) + "_" + name, function() {
+      return compare(data.plain, data.tokens, mode);
+    });
+  };
+
+  function compare(text, expected, mode) {
+
+    var expectedOutput = [];
+    for (var i = 0; i < expected.length; i += 2) {
+      var sty = expected[i];
+      if (sty && sty.indexOf(" ")) sty = sty.split(' ').sort().join(' ');
+      expectedOutput.push(sty, expected[i + 1]);
+    }
+
+    var observedOutput = highlight(text, mode);
+
+    var pass, passStyle = "";
+    pass = highlightOutputsEqual(expectedOutput, observedOutput);
+    passStyle = pass ? 'mt-pass' : 'mt-fail';
+
+    var s = '';
+    if (pass) {
+      s += '<div class="mt-test ' + passStyle + '">';
+      s +=   '<pre>' + text.replace('&', '&amp;').replace('<', '&lt;') + '</pre>';
+      s +=   '<div class="cm-s-default">';
+      s +=   prettyPrintOutputTable(observedOutput);
+      s +=   '</div>';
+      s += '</div>';
+      return s;
+    } else {
+      s += '<div class="mt-test ' + passStyle + '">';
+      s +=   '<pre>' + text.replace('&', '&amp;').replace('<', '&lt;') + '</pre>';
+      s +=   '<div class="cm-s-default">';
+      s += 'expected:';
+      s +=   prettyPrintOutputTable(expectedOutput);
+      s += 'observed:';
+      s +=   prettyPrintOutputTable(observedOutput);
+      s +=   '</div>';
+      s += '</div>';
+      throw s;
+    }
+  }
+
+  /**
+   * Emulation of CodeMirror's internal highlight routine for testing. Multi-line
+   * input is supported.
+   *
+   * @param string to highlight
+   *
+   * @param mode the mode that will do the actual highlighting
+   *
+   * @return array of [style, token] pairs
+   */
+  function highlight(string, mode) {
+    var state = mode.startState()
+
+    var lines = string.replace(/\r\n/g,'\n').split('\n');
+    var st = [], pos = 0;
+    for (var i = 0; i < lines.length; ++i) {
+      var line = lines[i], newLine = true;
+      var stream = new CodeMirror.StringStream(line);
+      if (line == "" && mode.blankLine) mode.blankLine(state);
+      /* Start copied code from CodeMirror.highlight */
+      while (!stream.eol()) {
+        var style = mode.token(stream, state), substr = stream.current();
+        if (style && style.indexOf(" ") > -1) style = style.split(' ').sort().join(' ');
+
+        stream.start = stream.pos;
+        if (pos && st[pos-2] == style && !newLine) {
+          st[pos-1] += substr;
+        } else if (substr) {
+          st[pos++] = style; st[pos++] = substr;
+        }
+        // Give up when line is ridiculously long
+        if (stream.pos > 5000) {
+          st[pos++] = null; st[pos++] = this.text.slice(stream.pos);
+          break;
+        }
+        newLine = false;
+      }
+    }
+
+    return st;
+  }
+
+  /**
+   * Compare two arrays of output from highlight.
+   *
+   * @param o1 array of [style, token] pairs
+   *
+   * @param o2 array of [style, token] pairs
+   *
+   * @return boolean; true iff outputs equal
+   */
+  function highlightOutputsEqual(o1, o2) {
+    if (o1.length != o2.length) return false;
+    for (var i = 0; i < o1.length; ++i)
+      if (o1[i] != o2[i]) return false;
+    return true;
+  }
+
+  /**
+   * Print tokens and corresponding styles in a table. Spaces in the token are
+   * replaced with 'interpunct' dots (&middot;).
+   *
+   * @param output array of [style, token] pairs
+   *
+   * @return html string
+   */
+  function prettyPrintOutputTable(output) {
+    var s = '<table class="mt-output">';
+    s += '<tr>';
+    for (var i = 0; i < output.length; i += 2) {
+      var style = output[i], val = output[i+1];
+      s +=
+      '<td class="mt-token">' +
+        '<span class="cm-' + String(style).replace(/ +/g, " cm-") + '">' +
+        val.replace(/ /g,'\xb7').replace('&', '&amp;').replace('<', '&lt;') +
+        '</span>' +
+        '</td>';
+    }
+    s += '</tr><tr>';
+    for (var i = 0; i < output.length; i += 2) {
+      s += '<td class="mt-style"><span>' + (output[i] || null) + '</span></td>';
+    }
+    s += '</table>';
+    return s;
+  }
+})();
diff --git a/third-party/codemirror-3.15/test/phantom_driver.js b/third-party/codemirror-3.15/test/phantom_driver.js
new file mode 100644 (file)
index 0000000..dbad08d
--- /dev/null
@@ -0,0 +1,31 @@
+var page = require('webpage').create();
+
+page.open("http://localhost:3000/test/index.html", function (status) {
+  if (status != "success") {
+    console.log("page couldn't be loaded successfully");
+    phantom.exit(1);
+  }
+  waitFor(function () {
+    return page.evaluate(function () {
+      var output = document.getElementById('status');
+      if (!output) { return false; }
+      return (/^(\d+ failures?|all passed)/i).test(output.innerText);
+    });
+  }, function () {
+    var failed = page.evaluate(function () { return window.failed; });
+    var output = page.evaluate(function () {
+      return document.getElementById('output').innerText + "\n" +
+        document.getElementById('status').innerText;
+    });
+    console.log(output);
+    phantom.exit(failed > 0 ? 1 : 0);
+  });
+});
+
+function waitFor (test, cb) {
+  if (test()) {
+    cb();
+  } else {
+    setTimeout(function () { waitFor(test, cb); }, 250);
+  }
+}
diff --git a/third-party/codemirror-3.15/test/run.js b/third-party/codemirror-3.15/test/run.js
new file mode 100755 (executable)
index 0000000..52221be
--- /dev/null
@@ -0,0 +1,34 @@
+#!/usr/bin/env node
+
+var lint = require("./lint/lint");
+
+lint.checkDir("mode");
+lint.checkDir("lib");
+lint.checkDir("addon");
+lint.checkDir("keymap");
+
+var ok = lint.success();
+
+var files = new (require('node-static').Server)('.');
+
+var server = require('http').createServer(function (req, res) {
+  req.addListener('end', function () {
+    files.serve(req, res);
+  });
+}).addListener('error', function (err) {
+  throw err;
+}).listen(3000, function () {
+  var child_process = require('child_process');
+  child_process.exec("which phantomjs", function (err) {
+    if (err) {
+      console.error("PhantomJS is not installed. Download from http://phantomjs.org");
+      process.exit(1);
+    }
+    var cmd = 'phantomjs test/phantom_driver.js';
+    child_process.exec(cmd, function (err, stdout) {
+      server.close();
+      console.log(stdout);
+      process.exit(err || !ok ? 1 : 0);
+    });
+  });
+});
diff --git a/third-party/codemirror-3.15/test/test.js b/third-party/codemirror-3.15/test/test.js
new file mode 100644 (file)
index 0000000..67b25d0
--- /dev/null
@@ -0,0 +1,1511 @@
+var Pos = CodeMirror.Pos;
+
+function forEach(arr, f) {
+  for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]);
+}
+
+function addDoc(cm, width, height) {
+  var content = [], line = "";
+  for (var i = 0; i < width; ++i) line += "x";
+  for (var i = 0; i < height; ++i) content.push(line);
+  cm.setValue(content.join("\n"));
+}
+
+function byClassName(elt, cls) {
+  if (elt.getElementsByClassName) return elt.getElementsByClassName(cls);
+  var found = [], re = new RegExp("\\b" + cls + "\\b");
+  function search(elt) {
+    if (elt.nodeType == 3) return;
+    if (re.test(elt.className)) found.push(elt);
+    for (var i = 0, e = elt.childNodes.length; i < e; ++i)
+      search(elt.childNodes[i]);
+  }
+  search(elt);
+  return found;
+}
+
+var ie_lt8 = /MSIE [1-7]\b/.test(navigator.userAgent);
+var mac = /Mac/.test(navigator.platform);
+var phantom = /PhantomJS/.test(navigator.userAgent);
+var opera = /Opera\/\./.test(navigator.userAgent);
+var opera_version = opera && navigator.userAgent.match(/Version\/(\d+\.\d+)/);
+if (opera_version) opera_version = Number(opera_version);
+var opera_lt10 = opera && (!opera_version || opera_version < 10);
+
+namespace = "core_";
+
+test("core_fromTextArea", function() {
+  var te = document.getElementById("code");
+  te.value = "CONTENT";
+  var cm = CodeMirror.fromTextArea(te);
+  is(!te.offsetHeight);
+  eq(cm.getValue(), "CONTENT");
+  cm.setValue("foo\nbar");
+  eq(cm.getValue(), "foo\nbar");
+  cm.save();
+  is(/^foo\r?\nbar$/.test(te.value));
+  cm.setValue("xxx");
+  cm.toTextArea();
+  is(te.offsetHeight);
+  eq(te.value, "xxx");
+});
+
+testCM("getRange", function(cm) {
+  eq(cm.getLine(0), "1234");
+  eq(cm.getLine(1), "5678");
+  eq(cm.getLine(2), null);
+  eq(cm.getLine(-1), null);
+  eq(cm.getRange(Pos(0, 0), Pos(0, 3)), "123");
+  eq(cm.getRange(Pos(0, -1), Pos(0, 200)), "1234");
+  eq(cm.getRange(Pos(0, 2), Pos(1, 2)), "34\n56");
+  eq(cm.getRange(Pos(1, 2), Pos(100, 0)), "78");
+}, {value: "1234\n5678"});
+
+testCM("replaceRange", function(cm) {
+  eq(cm.getValue(), "");
+  cm.replaceRange("foo\n", Pos(0, 0));
+  eq(cm.getValue(), "foo\n");
+  cm.replaceRange("a\nb", Pos(0, 1));
+  eq(cm.getValue(), "fa\nboo\n");
+  eq(cm.lineCount(), 3);
+  cm.replaceRange("xyzzy", Pos(0, 0), Pos(1, 1));
+  eq(cm.getValue(), "xyzzyoo\n");
+  cm.replaceRange("abc", Pos(0, 0), Pos(10, 0));
+  eq(cm.getValue(), "abc");
+  eq(cm.lineCount(), 1);
+});
+
+testCM("selection", function(cm) {
+  cm.setSelection(Pos(0, 4), Pos(2, 2));
+  is(cm.somethingSelected());
+  eq(cm.getSelection(), "11\n222222\n33");
+  eqPos(cm.getCursor(false), Pos(2, 2));
+  eqPos(cm.getCursor(true), Pos(0, 4));
+  cm.setSelection(Pos(1, 0));
+  is(!cm.somethingSelected());
+  eq(cm.getSelection(), "");
+  eqPos(cm.getCursor(true), Pos(1, 0));
+  cm.replaceSelection("abc");
+  eq(cm.getSelection(), "abc");
+  eq(cm.getValue(), "111111\nabc222222\n333333");
+  cm.replaceSelection("def", "end");
+  eq(cm.getSelection(), "");
+  eqPos(cm.getCursor(true), Pos(1, 3));
+  cm.setCursor(Pos(2, 1));
+  eqPos(cm.getCursor(true), Pos(2, 1));
+  cm.setCursor(1, 2);
+  eqPos(cm.getCursor(true), Pos(1, 2));
+}, {value: "111111\n222222\n333333"});
+
+testCM("extendSelection", function(cm) {
+  cm.setExtending(true);
+  addDoc(cm, 10, 10);
+  cm.setSelection(Pos(3, 5));
+  eqPos(cm.getCursor("head"), Pos(3, 5));
+  eqPos(cm.getCursor("anchor"), Pos(3, 5));
+  cm.setSelection(Pos(2, 5), Pos(5, 5));
+  eqPos(cm.getCursor("head"), Pos(5, 5));
+  eqPos(cm.getCursor("anchor"), Pos(2, 5));
+  eqPos(cm.getCursor("start"), Pos(2, 5));
+  eqPos(cm.getCursor("end"), Pos(5, 5));
+  cm.setSelection(Pos(5, 5), Pos(2, 5));
+  eqPos(cm.getCursor("head"), Pos(2, 5));
+  eqPos(cm.getCursor("anchor"), Pos(5, 5));
+  eqPos(cm.getCursor("start"), Pos(2, 5));
+  eqPos(cm.getCursor("end"), Pos(5, 5));
+  cm.extendSelection(Pos(3, 2));
+  eqPos(cm.getCursor("head"), Pos(3, 2));
+  eqPos(cm.getCursor("anchor"), Pos(5, 5));
+  cm.extendSelection(Pos(6, 2));
+  eqPos(cm.getCursor("head"), Pos(6, 2));
+  eqPos(cm.getCursor("anchor"), Pos(5, 5));
+  cm.extendSelection(Pos(6, 3), Pos(6, 4));
+  eqPos(cm.getCursor("head"), Pos(6, 4));
+  eqPos(cm.getCursor("anchor"), Pos(5, 5));
+  cm.extendSelection(Pos(0, 3), Pos(0, 4));
+  eqPos(cm.getCursor("head"), Pos(0, 3));
+  eqPos(cm.getCursor("anchor"), Pos(5, 5));
+  cm.extendSelection(Pos(4, 5), Pos(6, 5));
+  eqPos(cm.getCursor("head"), Pos(6, 5));
+  eqPos(cm.getCursor("anchor"), Pos(4, 5));
+  cm.setExtending(false);
+  cm.extendSelection(Pos(0, 3), Pos(0, 4));
+  eqPos(cm.getCursor("head"), Pos(0, 4));
+  eqPos(cm.getCursor("anchor"), Pos(0, 3));
+});
+
+testCM("lines", function(cm) {
+  eq(cm.getLine(0), "111111");
+  eq(cm.getLine(1), "222222");
+  eq(cm.getLine(-1), null);
+  cm.removeLine(1);
+  cm.setLine(1, "abc");
+  eq(cm.getValue(), "111111\nabc");
+}, {value: "111111\n222222\n333333"});
+
+testCM("indent", function(cm) {
+  cm.indentLine(1);
+  eq(cm.getLine(1), "   blah();");
+  cm.setOption("indentUnit", 8);
+  cm.indentLine(1);
+  eq(cm.getLine(1), "\tblah();");
+  cm.setOption("indentUnit", 10);
+  cm.setOption("tabSize", 4);
+  cm.indentLine(1);
+  eq(cm.getLine(1), "\t\t  blah();");
+}, {value: "if (x) {\nblah();\n}", indentUnit: 3, indentWithTabs: true, tabSize: 8});
+
+testCM("indentByNumber", function(cm) {
+  cm.indentLine(0, 2);
+  eq(cm.getLine(0), "  foo");
+  cm.indentLine(0, -200);
+  eq(cm.getLine(0), "foo");
+  cm.setSelection(Pos(0, 0), Pos(1, 2));
+  cm.indentSelection(3);
+  eq(cm.getValue(), "   foo\n   bar\nbaz");
+}, {value: "foo\nbar\nbaz"});
+
+test("core_defaults", function() {
+  var defsCopy = {}, defs = CodeMirror.defaults;
+  for (var opt in defs) defsCopy[opt] = defs[opt];
+  defs.indentUnit = 5;
+  defs.value = "uu";
+  defs.enterMode = "keep";
+  defs.tabindex = 55;
+  var place = document.getElementById("testground"), cm = CodeMirror(place);
+  try {
+    eq(cm.getOption("indentUnit"), 5);
+    cm.setOption("indentUnit", 10);
+    eq(defs.indentUnit, 5);
+    eq(cm.getValue(), "uu");
+    eq(cm.getOption("enterMode"), "keep");
+    eq(cm.getInputField().tabIndex, 55);
+  }
+  finally {
+    for (var opt in defsCopy) defs[opt] = defsCopy[opt];
+    place.removeChild(cm.getWrapperElement());
+  }
+});
+
+testCM("lineInfo", function(cm) {
+  eq(cm.lineInfo(-1), null);
+  var mark = document.createElement("span");
+  var lh = cm.setGutterMarker(1, "FOO", mark);
+  var info = cm.lineInfo(1);
+  eq(info.text, "222222");
+  eq(info.gutterMarkers.FOO, mark);
+  eq(info.line, 1);
+  eq(cm.lineInfo(2).gutterMarkers, null);
+  cm.setGutterMarker(lh, "FOO", null);
+  eq(cm.lineInfo(1).gutterMarkers, null);
+  cm.setGutterMarker(1, "FOO", mark);
+  cm.setGutterMarker(0, "FOO", mark);
+  cm.clearGutter("FOO");
+  eq(cm.lineInfo(0).gutterMarkers, null);
+  eq(cm.lineInfo(1).gutterMarkers, null);
+}, {value: "111111\n222222\n333333"});
+
+testCM("coords", function(cm) {
+  cm.setSize(null, 100);
+  addDoc(cm, 32, 200);
+  var top = cm.charCoords(Pos(0, 0));
+  var bot = cm.charCoords(Pos(200, 30));
+  is(top.left < bot.left);
+  is(top.top < bot.top);
+  is(top.top < top.bottom);
+  cm.scrollTo(null, 100);
+  var top2 = cm.charCoords(Pos(0, 0));
+  is(top.top > top2.top);
+  eq(top.left, top2.left);
+});
+
+testCM("coordsChar", function(cm) {
+  addDoc(cm, 35, 70);
+  for (var i = 0; i < 2; ++i) {
+    var sys = i ? "local" : "page";
+    for (var ch = 0; ch <= 35; ch += 5) {
+      for (var line = 0; line < 70; line += 5) {
+        cm.setCursor(line, ch);
+        var coords = cm.charCoords(Pos(line, ch), sys);
+        var pos = cm.coordsChar({left: coords.left + 1, top: coords.top + 1}, sys);
+        eqPos(pos, Pos(line, ch));
+      }
+    }
+  }
+}, {lineNumbers: true});
+
+testCM("posFromIndex", function(cm) {
+  cm.setValue(
+    "This function should\n" +
+    "convert a zero based index\n" +
+    "to line and ch."
+  );
+
+  var examples = [
+    { index: -1, line: 0, ch: 0  }, // <- Tests clipping
+    { index: 0,  line: 0, ch: 0  },
+    { index: 10, line: 0, ch: 10 },
+    { index: 39, line: 1, ch: 18 },
+    { index: 55, line: 2, ch: 7  },
+    { index: 63, line: 2, ch: 15 },
+    { index: 64, line: 2, ch: 15 }  // <- Tests clipping
+  ];
+
+  for (var i = 0; i < examples.length; i++) {
+    var example = examples[i];
+    var pos = cm.posFromIndex(example.index);
+    eq(pos.line, example.line);
+    eq(pos.ch, example.ch);
+    if (example.index >= 0 && example.index < 64)
+      eq(cm.indexFromPos(pos), example.index);
+  }
+});
+
+testCM("undo", function(cm) {
+  cm.setLine(0, "def");
+  eq(cm.historySize().undo, 1);
+  cm.undo();
+  eq(cm.getValue(), "abc");
+  eq(cm.historySize().undo, 0);
+  eq(cm.historySize().redo, 1);
+  cm.redo();
+  eq(cm.getValue(), "def");
+  eq(cm.historySize().undo, 1);
+  eq(cm.historySize().redo, 0);
+  cm.setValue("1\n\n\n2");
+  cm.clearHistory();
+  eq(cm.historySize().undo, 0);
+  for (var i = 0; i < 20; ++i) {
+    cm.replaceRange("a", Pos(0, 0));
+    cm.replaceRange("b", Pos(3, 0));
+  }
+  eq(cm.historySize().undo, 40);
+  for (var i = 0; i < 40; ++i)
+    cm.undo();
+  eq(cm.historySize().redo, 40);
+  eq(cm.getValue(), "1\n\n\n2");
+}, {value: "abc"});
+
+testCM("undoDepth", function(cm) {
+  cm.replaceRange("d", Pos(0));
+  cm.replaceRange("e", Pos(0));
+  cm.replaceRange("f", Pos(0));
+  cm.undo(); cm.undo(); cm.undo();
+  eq(cm.getValue(), "abcd");
+}, {value: "abc", undoDepth: 2});
+
+testCM("undoDoesntClearValue", function(cm) {
+  cm.undo();
+  eq(cm.getValue(), "x");
+}, {value: "x"});
+
+testCM("undoMultiLine", function(cm) {
+  cm.operation(function() {
+    cm.replaceRange("x", Pos(0, 0));
+    cm.replaceRange("y", Pos(1, 0));
+  });
+  cm.undo();
+  eq(cm.getValue(), "abc\ndef\nghi");
+  cm.operation(function() {
+    cm.replaceRange("y", Pos(1, 0));
+    cm.replaceRange("x", Pos(0, 0));
+  });
+  cm.undo();
+  eq(cm.getValue(), "abc\ndef\nghi");
+  cm.operation(function() {
+    cm.replaceRange("y", Pos(2, 0));
+    cm.replaceRange("x", Pos(1, 0));
+    cm.replaceRange("z", Pos(2, 0));
+  });
+  cm.undo();
+  eq(cm.getValue(), "abc\ndef\nghi", 3);
+}, {value: "abc\ndef\nghi"});
+
+testCM("undoComposite", function(cm) {
+  cm.replaceRange("y", Pos(1));
+  cm.operation(function() {
+    cm.replaceRange("x", Pos(0));
+    cm.replaceRange("z", Pos(2));
+  });
+  eq(cm.getValue(), "ax\nby\ncz\n");
+  cm.undo();
+  eq(cm.getValue(), "a\nby\nc\n");
+  cm.undo();
+  eq(cm.getValue(), "a\nb\nc\n");
+  cm.redo(); cm.redo();
+  eq(cm.getValue(), "ax\nby\ncz\n");
+}, {value: "a\nb\nc\n"});
+
+testCM("undoSelection", function(cm) {
+  cm.setSelection(Pos(0, 2), Pos(0, 4));
+  cm.replaceSelection("");
+  cm.setCursor(Pos(1, 0));
+  cm.undo();
+  eqPos(cm.getCursor(true), Pos(0, 2));
+  eqPos(cm.getCursor(false), Pos(0, 4));
+  cm.setCursor(Pos(1, 0));
+  cm.redo();
+  eqPos(cm.getCursor(true), Pos(0, 2));
+  eqPos(cm.getCursor(false), Pos(0, 2));
+}, {value: "abcdefgh\n"});
+
+testCM("markTextSingleLine", function(cm) {
+  forEach([{a: 0, b: 1, c: "", f: 2, t: 5},
+           {a: 0, b: 4, c: "", f: 0, t: 2},
+           {a: 1, b: 2, c: "x", f: 3, t: 6},
+           {a: 4, b: 5, c: "", f: 3, t: 5},
+           {a: 4, b: 5, c: "xx", f: 3, t: 7},
+           {a: 2, b: 5, c: "", f: 2, t: 3},
+           {a: 2, b: 5, c: "abcd", f: 6, t: 7},
+           {a: 2, b: 6, c: "x", f: null, t: null},
+           {a: 3, b: 6, c: "", f: null, t: null},
+           {a: 0, b: 9, c: "hallo", f: null, t: null},
+           {a: 4, b: 6, c: "x", f: 3, t: 4},
+           {a: 4, b: 8, c: "", f: 3, t: 4},
+           {a: 6, b: 6, c: "a", f: 3, t: 6},
+           {a: 8, b: 9, c: "", f: 3, t: 6}], function(test) {
+    cm.setValue("1234567890");
+    var r = cm.markText(Pos(0, 3), Pos(0, 6), {className: "foo"});
+    cm.replaceRange(test.c, Pos(0, test.a), Pos(0, test.b));
+    var f = r.find();
+    eq(f && f.from.ch, test.f); eq(f && f.to.ch, test.t);
+  });
+});
+
+testCM("markTextMultiLine", function(cm) {
+  function p(v) { return v && Pos(v[0], v[1]); }
+  forEach([{a: [0, 0], b: [0, 5], c: "", f: [0, 0], t: [2, 5]},
+           {a: [0, 0], b: [0, 5], c: "foo\n", f: [1, 0], t: [3, 5]},
+           {a: [0, 1], b: [0, 10], c: "", f: [0, 1], t: [2, 5]},
+           {a: [0, 5], b: [0, 6], c: "x", f: [0, 6], t: [2, 5]},
+           {a: [0, 0], b: [1, 0], c: "", f: [0, 0], t: [1, 5]},
+           {a: [0, 6], b: [2, 4], c: "", f: [0, 5], t: [0, 7]},
+           {a: [0, 6], b: [2, 4], c: "aa", f: [0, 5], t: [0, 9]},
+           {a: [1, 2], b: [1, 8], c: "", f: [0, 5], t: [2, 5]},
+           {a: [0, 5], b: [2, 5], c: "xx", f: null, t: null},
+           {a: [0, 0], b: [2, 10], c: "x", f: null, t: null},
+           {a: [1, 5], b: [2, 5], c: "", f: [0, 5], t: [1, 5]},
+           {a: [2, 0], b: [2, 3], c: "", f: [0, 5], t: [2, 2]},
+           {a: [2, 5], b: [3, 0], c: "a\nb", f: [0, 5], t: [2, 5]},
+           {a: [2, 3], b: [3, 0], c: "x", f: [0, 5], t: [2, 3]},
+           {a: [1, 1], b: [1, 9], c: "1\n2\n3", f: [0, 5], t: [4, 5]}], function(test) {
+    cm.setValue("aaaaaaaaaa\nbbbbbbbbbb\ncccccccccc\ndddddddd\n");
+    var r = cm.markText(Pos(0, 5), Pos(2, 5),
+                        {className: "CodeMirror-matchingbracket"});
+    cm.replaceRange(test.c, p(test.a), p(test.b));
+    var f = r.find();
+    eqPos(f && f.from, p(test.f)); eqPos(f && f.to, p(test.t));
+  });
+});
+
+testCM("markTextUndo", function(cm) {
+  var marker1, marker2, bookmark;
+  marker1 = cm.markText(Pos(0, 1), Pos(0, 3),
+                        {className: "CodeMirror-matchingbracket"});
+  marker2 = cm.markText(Pos(0, 0), Pos(2, 1),
+                        {className: "CodeMirror-matchingbracket"});
+  bookmark = cm.setBookmark(Pos(1, 5));
+  cm.operation(function(){
+    cm.replaceRange("foo", Pos(0, 2));
+    cm.replaceRange("bar\nbaz\nbug\n", Pos(2, 0), Pos(3, 0));
+  });
+  var v1 = cm.getValue();
+  cm.setValue("");
+  eq(marker1.find(), null); eq(marker2.find(), null); eq(bookmark.find(), null);
+  cm.undo();
+  eqPos(bookmark.find(), Pos(1, 5), "still there");
+  cm.undo();
+  var m1Pos = marker1.find(), m2Pos = marker2.find();
+  eqPos(m1Pos.from, Pos(0, 1)); eqPos(m1Pos.to, Pos(0, 3));
+  eqPos(m2Pos.from, Pos(0, 0)); eqPos(m2Pos.to, Pos(2, 1));
+  eqPos(bookmark.find(), Pos(1, 5));
+  cm.redo(); cm.redo();
+  eq(bookmark.find(), null);
+  cm.undo();
+  eqPos(bookmark.find(), Pos(1, 5));
+  eq(cm.getValue(), v1);
+}, {value: "1234\n56789\n00\n"});
+
+testCM("markTextStayGone", function(cm) {
+  var m1 = cm.markText(Pos(0, 0), Pos(0, 1));
+  cm.replaceRange("hi", Pos(0, 2));
+  m1.clear();
+  cm.undo();
+  eq(m1.find(), null);
+}, {value: "hello"});
+
+testCM("undoPreservesNewMarks", function(cm) {
+  cm.markText(Pos(0, 3), Pos(0, 4));
+  cm.markText(Pos(1, 1), Pos(1, 3));
+  cm.replaceRange("", Pos(0, 3), Pos(3, 1));
+  var mBefore = cm.markText(Pos(0, 0), Pos(0, 1));
+  var mAfter = cm.markText(Pos(0, 5), Pos(0, 6));
+  var mAround = cm.markText(Pos(0, 2), Pos(0, 4));
+  cm.undo();
+  eqPos(mBefore.find().from, Pos(0, 0));
+  eqPos(mBefore.find().to, Pos(0, 1));
+  eqPos(mAfter.find().from, Pos(3, 3));
+  eqPos(mAfter.find().to, Pos(3, 4));
+  eqPos(mAround.find().from, Pos(0, 2));
+  eqPos(mAround.find().to, Pos(3, 2));
+  var found = cm.findMarksAt(Pos(2, 2));
+  eq(found.length, 1);
+  eq(found[0], mAround);
+}, {value: "aaaa\nbbbb\ncccc\ndddd"});
+
+testCM("markClearBetween", function(cm) {
+  cm.setValue("aaa\nbbb\nccc\nddd\n");
+  cm.markText(Pos(0, 0), Pos(2));
+  cm.replaceRange("aaa\nbbb\nccc", Pos(0, 0), Pos(2));
+  eq(cm.findMarksAt(Pos(1, 1)).length, 0);
+});
+
+testCM("deleteSpanCollapsedInclusiveLeft", function(cm) {
+  var from = Pos(1, 0), to = Pos(1, 1);
+  var m = cm.markText(from, to, {collapsed: true, inclusiveLeft: true});
+  // Delete collapsed span.
+  cm.replaceRange("", from, to);
+}, {value: "abc\nX\ndef"});
+
+testCM("bookmark", function(cm) {
+  function p(v) { return v && Pos(v[0], v[1]); }
+  forEach([{a: [1, 0], b: [1, 1], c: "", d: [1, 4]},
+           {a: [1, 1], b: [1, 1], c: "xx", d: [1, 7]},
+           {a: [1, 4], b: [1, 5], c: "ab", d: [1, 6]},
+           {a: [1, 4], b: [1, 6], c: "", d: null},
+           {a: [1, 5], b: [1, 6], c: "abc", d: [1, 5]},
+           {a: [1, 6], b: [1, 8], c: "", d: [1, 5]},
+           {a: [1, 4], b: [1, 4], c: "\n\n", d: [3, 1]},
+           {bm: [1, 9], a: [1, 1], b: [1, 1], c: "\n", d: [2, 8]}], function(test) {
+    cm.setValue("1234567890\n1234567890\n1234567890");
+    var b = cm.setBookmark(p(test.bm) || Pos(1, 5));
+    cm.replaceRange(test.c, p(test.a), p(test.b));
+    eqPos(b.find(), p(test.d));
+  });
+});
+
+testCM("bookmarkInsertLeft", function(cm) {
+  var br = cm.setBookmark(Pos(0, 2), {insertLeft: false});
+  var bl = cm.setBookmark(Pos(0, 2), {insertLeft: true});
+  cm.setCursor(Pos(0, 2));
+  cm.replaceSelection("hi");
+  eqPos(br.find(), Pos(0, 2));
+  eqPos(bl.find(), Pos(0, 4));
+  cm.replaceRange("", Pos(0, 4), Pos(0, 5));
+  cm.replaceRange("", Pos(0, 2), Pos(0, 4));
+  cm.replaceRange("", Pos(0, 1), Pos(0, 2));
+  // Verify that deleting next to bookmarks doesn't kill them
+  eqPos(br.find(), Pos(0, 1));
+  eqPos(bl.find(), Pos(0, 1));
+}, {value: "abcdef"});
+
+testCM("bookmarkCursor", function(cm) {
+  var pos01 = cm.cursorCoords(Pos(0, 1)), pos11 = cm.cursorCoords(Pos(1, 1)),
+      pos20 = cm.cursorCoords(Pos(2, 0)), pos30 = cm.cursorCoords(Pos(3, 0)),
+      pos41 = cm.cursorCoords(Pos(4, 1));
+  cm.setBookmark(Pos(0, 1), {widget: document.createTextNode("←"), insertLeft: true});
+  cm.setBookmark(Pos(2, 0), {widget: document.createTextNode("←"), insertLeft: true});
+  cm.setBookmark(Pos(1, 1), {widget: document.createTextNode("→")});
+  cm.setBookmark(Pos(3, 0), {widget: document.createTextNode("→")});
+  var new01 = cm.cursorCoords(Pos(0, 1)), new11 = cm.cursorCoords(Pos(1, 1)),
+      new20 = cm.cursorCoords(Pos(2, 0)), new30 = cm.cursorCoords(Pos(3, 0));
+  is(new01.left == pos01.left && new01.top == pos01.top, "at left, middle of line");
+  is(new11.left > pos11.left && new11.top == pos11.top, "at right, middle of line");
+  is(new20.left == pos20.left && new20.top == pos20.top, "at left, empty line");
+  is(new30.left > pos30.left && new30.top == pos30.top, "at right, empty line");
+  cm.setBookmark(Pos(4, 0), {widget: document.createTextNode("→")});
+  is(cm.cursorCoords(Pos(4, 1)).left > pos41.left, "single-char bug");
+}, {value: "foo\nbar\n\n\nx\ny"});
+
+testCM("getAllMarks", function(cm) {
+  addDoc(cm, 10, 10);
+  var m1 = cm.setBookmark(Pos(0, 2));
+  var m2 = cm.markText(Pos(0, 2), Pos(3, 2));
+  var m3 = cm.markText(Pos(1, 2), Pos(1, 8));
+  var m4 = cm.markText(Pos(8, 0), Pos(9, 0));
+  eq(cm.getAllMarks().length, 4);
+  m1.clear();
+  m3.clear();
+  eq(cm.getAllMarks().length, 2);
+});
+
+testCM("bug577", function(cm) {
+  cm.setValue("a\nb");
+  cm.clearHistory();
+  cm.setValue("fooooo");
+  cm.undo();
+});
+
+testCM("scrollSnap", function(cm) {
+  cm.setSize(100, 100);
+  addDoc(cm, 200, 200);
+  cm.setCursor(Pos(100, 180));
+  var info = cm.getScrollInfo();
+  is(info.left > 0 && info.top > 0);
+  cm.setCursor(Pos(0, 0));
+  info = cm.getScrollInfo();
+  is(info.left == 0 && info.top == 0, "scrolled clean to top");
+  cm.setCursor(Pos(100, 180));
+  cm.setCursor(Pos(199, 0));
+  info = cm.getScrollInfo();
+  is(info.left == 0 && info.top + 2 > info.height - cm.getScrollerElement().clientHeight, "scrolled clean to bottom");
+});
+
+testCM("scrollIntoView", function(cm) {
+  if (phantom) return;
+  var outer = cm.getWrapperElement().getBoundingClientRect();
+  function test(line, ch) {
+    var pos = Pos(line, ch);
+    cm.scrollIntoView(pos);
+    var box = cm.charCoords(pos, "window");
+    is(box.left >= outer.left && box.right <= outer.right &&
+       box.top >= outer.top && box.bottom <= outer.bottom);
+  }
+  addDoc(cm, 200, 200);
+  test(199, 199);
+  test(0, 0);
+  test(100, 100);
+  test(199, 0);
+  test(0, 199);
+  test(100, 100);
+});
+
+testCM("selectionPos", function(cm) {
+  if (phantom) return;
+  cm.setSize(100, 100);
+  addDoc(cm, 200, 100);
+  cm.setSelection(Pos(1, 100), Pos(98, 100));
+  var lineWidth = cm.charCoords(Pos(0, 200), "local").left;
+  var lineHeight = (cm.charCoords(Pos(99)).top - cm.charCoords(Pos(0)).top) / 100;
+  cm.scrollTo(0, 0);
+  var selElt = byClassName(cm.getWrapperElement(), "CodeMirror-selected");
+  var outer = cm.getWrapperElement().getBoundingClientRect();
+  var sawMiddle, sawTop, sawBottom;
+  for (var i = 0, e = selElt.length; i < e; ++i) {
+    var box = selElt[i].getBoundingClientRect();
+    var atLeft = box.left - outer.left < 30;
+    var width = box.right - box.left;
+    var atRight = box.right - outer.left > .8 * lineWidth;
+    if (atLeft && atRight) {
+      sawMiddle = true;
+      is(box.bottom - box.top > 90 * lineHeight, "middle high");
+      is(width > .9 * lineWidth, "middle wide");
+    } else {
+      is(width > .4 * lineWidth, "top/bot wide enough");
+      is(width < .6 * lineWidth, "top/bot slim enough");
+      if (atLeft) {
+        sawBottom = true;
+        is(box.top - outer.top > 96 * lineHeight, "bot below");
+      } else if (atRight) {
+        sawTop = true;
+        is(box.top - outer.top < 2.1 * lineHeight, "top above");
+      }
+    }
+  }
+  is(sawTop && sawBottom && sawMiddle, "all parts");
+}, null);
+
+testCM("restoreHistory", function(cm) {
+  cm.setValue("abc\ndef");
+  cm.setLine(1, "hello");
+  cm.setLine(0, "goop");
+  cm.undo();
+  var storedVal = cm.getValue(), storedHist = cm.getHistory();
+  if (window.JSON) storedHist = JSON.parse(JSON.stringify(storedHist));
+  eq(storedVal, "abc\nhello");
+  cm.setValue("");
+  cm.clearHistory();
+  eq(cm.historySize().undo, 0);
+  cm.setValue(storedVal);
+  cm.setHistory(storedHist);
+  cm.redo();
+  eq(cm.getValue(), "goop\nhello");
+  cm.undo(); cm.undo();
+  eq(cm.getValue(), "abc\ndef");
+});
+
+testCM("doubleScrollbar", function(cm) {
+  var dummy = document.body.appendChild(document.createElement("p"));
+  dummy.style.cssText = "height: 50px; overflow: scroll; width: 50px";
+  var scrollbarWidth = dummy.offsetWidth + 1 - dummy.clientWidth;
+  document.body.removeChild(dummy);
+  if (scrollbarWidth < 2) return;
+  cm.setSize(null, 100);
+  addDoc(cm, 1, 300);
+  var wrap = cm.getWrapperElement();
+  is(wrap.offsetWidth - byClassName(wrap, "CodeMirror-lines")[0].offsetWidth <= scrollbarWidth * 1.5);
+});
+
+testCM("weirdLinebreaks", function(cm) {
+  cm.setValue("foo\nbar\rbaz\r\nquux\n\rplop");
+  is(cm.getValue(), "foo\nbar\nbaz\nquux\n\nplop");
+  is(cm.lineCount(), 6);
+  cm.setValue("\n\n");
+  is(cm.lineCount(), 3);
+});
+
+testCM("setSize", function(cm) {
+  cm.setSize(100, 100);
+  var wrap = cm.getWrapperElement();
+  is(wrap.offsetWidth, 100);
+  is(wrap.offsetHeight, 100);
+  cm.setSize("100%", "3em");
+  is(wrap.style.width, "100%");
+  is(wrap.style.height, "3em");
+  cm.setSize(null, 40);
+  is(wrap.style.width, "100%");
+  is(wrap.style.height, "40px");
+});
+
+function foldLines(cm, start, end, autoClear) {
+  return cm.markText(Pos(start, 0), Pos(end - 1), {
+    inclusiveLeft: true,
+    inclusiveRight: true,
+    collapsed: true,
+    clearOnEnter: autoClear
+  });
+}
+
+testCM("collapsedLines", function(cm) {
+  addDoc(cm, 4, 10);
+  var range = foldLines(cm, 4, 5), cleared = 0;
+  CodeMirror.on(range, "clear", function() {cleared++;});
+  cm.setCursor(Pos(3, 0));
+  CodeMirror.commands.goLineDown(cm);
+  eqPos(cm.getCursor(), Pos(5, 0));
+  cm.setLine(3, "abcdefg");
+  cm.setCursor(Pos(3, 6));
+  CodeMirror.commands.goLineDown(cm);
+  eqPos(cm.getCursor(), Pos(5, 4));
+  cm.setLine(3, "ab");
+  cm.setCursor(Pos(3, 2));
+  CodeMirror.commands.goLineDown(cm);
+  eqPos(cm.getCursor(), Pos(5, 2));
+  cm.operation(function() {range.clear(); range.clear();});
+  eq(cleared, 1);
+});
+
+testCM("collapsedRangeCoordsChar", function(cm) {
+  var pos_1_3 = cm.charCoords(Pos(1, 3));
+  pos_1_3.left += 2; pos_1_3.top += 2;
+  var opts = {collapsed: true, inclusiveLeft: true, inclusiveRight: true};
+  var m1 = cm.markText(Pos(0, 0), Pos(2, 0), opts);
+  eqPos(cm.coordsChar(pos_1_3), Pos(3, 3));
+  m1.clear();
+  var m1 = cm.markText(Pos(0, 0), Pos(1, 1), opts);
+  var m2 = cm.markText(Pos(1, 1), Pos(2, 0), opts);
+  eqPos(cm.coordsChar(pos_1_3), Pos(3, 3));
+  m1.clear(); m2.clear();
+  var m1 = cm.markText(Pos(0, 0), Pos(1, 6), opts);
+  eqPos(cm.coordsChar(pos_1_3), Pos(3, 3));
+}, {value: "123456\nabcdef\nghijkl\nmnopqr\n"});
+
+testCM("hiddenLinesAutoUnfold", function(cm) {
+  var range = foldLines(cm, 1, 3, true), cleared = 0;
+  CodeMirror.on(range, "clear", function() {cleared++;});
+  cm.setCursor(Pos(3, 0));
+  eq(cleared, 0);
+  cm.execCommand("goCharLeft");
+  eq(cleared, 1);
+  range = foldLines(cm, 1, 3, true);
+  CodeMirror.on(range, "clear", function() {cleared++;});
+  eqPos(cm.getCursor(), Pos(3, 0));
+  cm.setCursor(Pos(0, 3));
+  cm.execCommand("goCharRight");
+  eq(cleared, 2);
+}, {value: "abc\ndef\nghi\njkl"});
+
+testCM("hiddenLinesSelectAll", function(cm) {  // Issue #484
+  addDoc(cm, 4, 20);
+  foldLines(cm, 0, 10);
+  foldLines(cm, 11, 20);
+  CodeMirror.commands.selectAll(cm);
+  eqPos(cm.getCursor(true), Pos(10, 0));
+  eqPos(cm.getCursor(false), Pos(10, 4));
+});
+
+
+testCM("everythingFolded", function(cm) {
+  addDoc(cm, 2, 2);
+  function enterPress() {
+    cm.triggerOnKeyDown({type: "keydown", keyCode: 13, preventDefault: function(){}, stopPropagation: function(){}});
+  }
+  var fold = foldLines(cm, 0, 2);
+  enterPress();
+  eq(cm.getValue(), "xx\nxx");
+  fold.clear();
+  fold = foldLines(cm, 0, 2, true);
+  eq(fold.find(), null);
+  enterPress();
+  eq(cm.getValue(), "\nxx\nxx");
+});
+
+testCM("structuredFold", function(cm) {
+  if (phantom) return;
+  addDoc(cm, 4, 8);
+  var range = cm.markText(Pos(1, 2), Pos(6, 2), {
+    replacedWith: document.createTextNode("Q")
+  });
+  cm.setCursor(0, 3);
+  CodeMirror.commands.goLineDown(cm);
+  eqPos(cm.getCursor(), Pos(6, 2));
+  CodeMirror.commands.goCharLeft(cm);
+  eqPos(cm.getCursor(), Pos(1, 2));
+  CodeMirror.commands.delCharAfter(cm);
+  eq(cm.getValue(), "xxxx\nxxxx\nxxxx");
+  addDoc(cm, 4, 8);
+  range = cm.markText(Pos(1, 2), Pos(6, 2), {
+    replacedWith: document.createTextNode("M"),
+    clearOnEnter: true
+  });
+  var cleared = 0;
+  CodeMirror.on(range, "clear", function(){++cleared;});
+  cm.setCursor(0, 3);
+  CodeMirror.commands.goLineDown(cm);
+  eqPos(cm.getCursor(), Pos(6, 2));
+  CodeMirror.commands.goCharLeft(cm);
+  eqPos(cm.getCursor(), Pos(6, 1));
+  eq(cleared, 1);
+  range.clear();
+  eq(cleared, 1);
+  range = cm.markText(Pos(1, 2), Pos(6, 2), {
+    replacedWith: document.createTextNode("Q"),
+    clearOnEnter: true
+  });
+  range.clear();
+  cm.setCursor(1, 2);
+  CodeMirror.commands.goCharRight(cm);
+  eqPos(cm.getCursor(), Pos(1, 3));
+  range = cm.markText(Pos(2, 0), Pos(4, 4), {
+    replacedWith: document.createTextNode("M")
+  });
+  cm.setCursor(1, 0);
+  CodeMirror.commands.goLineDown(cm);
+  eqPos(cm.getCursor(), Pos(2, 0));
+}, null);
+
+testCM("nestedFold", function(cm) {
+  addDoc(cm, 10, 3);
+  function fold(ll, cl, lr, cr) {
+    return cm.markText(Pos(ll, cl), Pos(lr, cr), {collapsed: true});
+  }
+  var inner1 = fold(0, 6, 1, 3), inner2 = fold(0, 2, 1, 8), outer = fold(0, 1, 2, 3), inner0 = fold(0, 5, 0, 6);
+  cm.setCursor(0, 1);
+  CodeMirror.commands.goCharRight(cm);
+  eqPos(cm.getCursor(), Pos(2, 3));
+  inner0.clear();
+  CodeMirror.commands.goCharLeft(cm);
+  eqPos(cm.getCursor(), Pos(0, 1));
+  outer.clear();
+  CodeMirror.commands.goCharRight(cm);
+  eqPos(cm.getCursor(), Pos(0, 2));
+  CodeMirror.commands.goCharRight(cm);
+  eqPos(cm.getCursor(), Pos(1, 8));
+  inner2.clear();
+  CodeMirror.commands.goCharLeft(cm);
+  eqPos(cm.getCursor(), Pos(1, 7));
+  cm.setCursor(0, 5);
+  CodeMirror.commands.goCharRight(cm);
+  eqPos(cm.getCursor(), Pos(0, 6));
+  CodeMirror.commands.goCharRight(cm);
+  eqPos(cm.getCursor(), Pos(1, 3));
+});
+
+testCM("badNestedFold", function(cm) {
+  addDoc(cm, 4, 4);
+  cm.markText(Pos(0, 2), Pos(3, 2), {collapsed: true});
+  var caught;
+  try {cm.markText(Pos(0, 1), Pos(0, 3), {collapsed: true});}
+  catch(e) {caught = e;}
+  is(caught instanceof Error, "no error");
+  is(/overlap/i.test(caught.message), "wrong error");
+});
+
+testCM("wrappingInlineWidget", function(cm) {
+  cm.setSize("11em");
+  var w = document.createElement("span");
+  w.style.color = "red";
+  w.innerHTML = "one two three four";
+  cm.markText(Pos(0, 6), Pos(0, 9), {replacedWith: w});
+  var cur0 = cm.cursorCoords(Pos(0, 0)), cur1 = cm.cursorCoords(Pos(0, 10));
+  is(cur0.top < cur1.top);
+  is(cur0.bottom < cur1.bottom);
+  var curL = cm.cursorCoords(Pos(0, 6)), curR = cm.cursorCoords(Pos(0, 9));
+  eq(curL.top, cur0.top);
+  eq(curL.bottom, cur0.bottom);
+  eq(curR.top, cur1.top);
+  eq(curR.bottom, cur1.bottom);
+  cm.replaceRange("", Pos(0, 9), Pos(0));
+  curR = cm.cursorCoords(Pos(0, 9));
+  eq(curR.top, cur1.top);
+  eq(curR.bottom, cur1.bottom);
+}, {value: "1 2 3 xxx 4", lineWrapping: true});
+
+testCM("changedInlineWidget", function(cm) {
+  cm.setSize("10em");
+  var w = document.createElement("span");
+  w.innerHTML = "x";
+  var m = cm.markText(Pos(0, 4), Pos(0, 5), {replacedWith: w});
+  w.innerHTML = "and now the widget is really really long all of a sudden and a scrollbar is needed";
+  m.changed();
+  var hScroll = byClassName(cm.getWrapperElement(), "CodeMirror-hscrollbar")[0];
+  is(hScroll.scrollWidth > hScroll.clientWidth);
+}, {value: "hello there"});
+
+testCM("inlineWidget", function(cm) {
+  var w = cm.setBookmark(Pos(0, 2), {widget: document.createTextNode("uu")});
+  cm.setCursor(0, 2);
+  CodeMirror.commands.goLineDown(cm);
+  eqPos(cm.getCursor(), Pos(1, 4));
+  cm.setCursor(0, 2);
+  cm.replaceSelection("hi");
+  eqPos(w.find(), Pos(0, 2));
+  cm.setCursor(0, 1);
+  cm.replaceSelection("ay");
+  eqPos(w.find(), Pos(0, 4));
+  eq(cm.getLine(0), "uayuhiuu");
+}, {value: "uuuu\nuuuuuu"});
+
+testCM("wrappingAndResizing", function(cm) {
+  cm.setSize(null, "auto");
+  cm.setOption("lineWrapping", true);
+  var wrap = cm.getWrapperElement(), h0 = wrap.offsetHeight;
+  var doc = "xxx xxx xxx xxx xxx";
+  cm.setValue(doc);
+  for (var step = 10, w = cm.charCoords(Pos(0, 18), "div").right;; w += step) {
+    cm.setSize(w);
+    if (wrap.offsetHeight <= h0 * (opera_lt10 ? 1.2 : 1.5)) {
+      if (step == 10) { w -= 10; step = 1; }
+      else break;
+    }
+  }
+  // Ensure that putting the cursor at the end of the maximally long
+  // line doesn't cause wrapping to happen.
+  cm.setCursor(Pos(0, doc.length));
+  eq(wrap.offsetHeight, h0);
+  cm.replaceSelection("x");
+  is(wrap.offsetHeight > h0, "wrapping happens");
+  // Now add a max-height and, in a document consisting of
+  // almost-wrapped lines, go over it so that a scrollbar appears.
+  cm.setValue(doc + "\n" + doc + "\n");
+  cm.getScrollerElement().style.maxHeight = "100px";
+  cm.replaceRange("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n!\n", Pos(2, 0));
+  forEach([Pos(0, doc.length), Pos(0, doc.length - 1),
+           Pos(0, 0), Pos(1, doc.length), Pos(1, doc.length - 1)],
+          function(pos) {
+    var coords = cm.charCoords(pos);
+    eqPos(pos, cm.coordsChar({left: coords.left + 2, top: coords.top + 5}));
+  });
+}, null, ie_lt8);
+
+testCM("measureEndOfLine", function(cm) {
+  cm.setSize(null, "auto");
+  var inner = byClassName(cm.getWrapperElement(), "CodeMirror-lines")[0].firstChild;
+  var lh = inner.offsetHeight;
+  for (var step = 10, w = cm.charCoords(Pos(0, 7), "div").right;; w += step) {
+    cm.setSize(w);
+    if (inner.offsetHeight < 2.5 * lh) {
+      if (step == 10) { w -= 10; step = 1; }
+      else break;
+    }
+  }
+  cm.setValue(cm.getValue() + "\n\n");
+  var endPos = cm.charCoords(Pos(0, 18), "local");
+  is(endPos.top > lh * .8, "not at top");
+  is(endPos.left > w - 20, "not at right");
+  endPos = cm.charCoords(Pos(0, 18));
+  eqPos(cm.coordsChar({left: endPos.left, top: endPos.top + 5}), Pos(0, 18));
+}, {mode: "text/html", value: "<!-- foo barrr -->", lineWrapping: true}, ie_lt8 || opera_lt10);
+
+testCM("scrollVerticallyAndHorizontally", function(cm) {
+  cm.setSize(100, 100);
+  addDoc(cm, 40, 40);
+  cm.setCursor(39);
+  var wrap = cm.getWrapperElement(), bar = byClassName(wrap, "CodeMirror-vscrollbar")[0];
+  is(bar.offsetHeight < wrap.offsetHeight, "vertical scrollbar limited by horizontal one");
+  var cursorBox = byClassName(wrap, "CodeMirror-cursor")[0].getBoundingClientRect();
+  var editorBox = wrap.getBoundingClientRect();
+  is(cursorBox.bottom < editorBox.top + cm.getScrollerElement().clientHeight,
+     "bottom line visible");
+}, {lineNumbers: true});
+
+testCM("moveVstuck", function(cm) {
+  var lines = byClassName(cm.getWrapperElement(), "CodeMirror-lines")[0].firstChild, h0 = lines.offsetHeight;
+  var val = "fooooooooooooooooooooooooo baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaar\n";
+  cm.setValue(val);
+  for (var w = cm.charCoords(Pos(0, 26), "div").right * 2.8;; w += 5) {
+    cm.setSize(w);
+    if (lines.offsetHeight <= 3.5 * h0) break;
+  }
+  cm.setCursor(Pos(0, val.length - 1));
+  cm.moveV(-1, "line");
+  eqPos(cm.getCursor(), Pos(0, 26));
+}, {lineWrapping: true}, ie_lt8 || opera_lt10);
+
+testCM("clickTab", function(cm) {
+  var p0 = cm.charCoords(Pos(0, 0));
+  eqPos(cm.coordsChar({left: p0.left + 5, top: p0.top + 5}), Pos(0, 0));
+  eqPos(cm.coordsChar({left: p0.right - 5, top: p0.top + 5}), Pos(0, 1));
+}, {value: "\t\n\n", lineWrapping: true, tabSize: 8});
+
+testCM("verticalScroll", function(cm) {
+  cm.setSize(100, 200);
+  cm.setValue("foo\nbar\nbaz\n");
+  var sc = cm.getScrollerElement(), baseWidth = sc.scrollWidth;
+  cm.setLine(0, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaah");
+  is(sc.scrollWidth > baseWidth, "scrollbar present");
+  cm.setLine(0, "foo");
+  if (!phantom) eq(sc.scrollWidth, baseWidth, "scrollbar gone");
+  cm.setLine(0, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaah");
+  cm.setLine(1, "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbh");
+  is(sc.scrollWidth > baseWidth, "present again");
+  var curWidth = sc.scrollWidth;
+  cm.setLine(0, "foo");
+  is(sc.scrollWidth < curWidth, "scrollbar smaller");
+  is(sc.scrollWidth > baseWidth, "but still present");
+});
+
+testCM("extraKeys", function(cm) {
+  var outcome;
+  function fakeKey(expected, code, props) {
+    if (typeof code == "string") code = code.charCodeAt(0);
+    var e = {type: "keydown", keyCode: code, preventDefault: function(){}, stopPropagation: function(){}};
+    if (props) for (var n in props) e[n] = props[n];
+    outcome = null;
+    cm.triggerOnKeyDown(e);
+    eq(outcome, expected);
+  }
+  CodeMirror.commands.testCommand = function() {outcome = "tc";};
+  CodeMirror.commands.goTestCommand = function() {outcome = "gtc";};
+  cm.setOption("extraKeys", {"Shift-X": function() {outcome = "sx";},
+                             "X": function() {outcome = "x";},
+                             "Ctrl-Alt-U": function() {outcome = "cau";},
+                             "End": "testCommand",
+                             "Home": "goTestCommand",
+                             "Tab": false});
+  fakeKey(null, "U");
+  fakeKey("cau", "U", {ctrlKey: true, altKey: true});
+  fakeKey(null, "U", {shiftKey: true, ctrlKey: true, altKey: true});
+  fakeKey("x", "X");
+  fakeKey("sx", "X", {shiftKey: true});
+  fakeKey("tc", 35);
+  fakeKey(null, 35, {shiftKey: true});
+  fakeKey("gtc", 36);
+  fakeKey("gtc", 36, {shiftKey: true});
+  fakeKey(null, 9);
+}, null, window.opera && mac);
+
+testCM("wordMovementCommands", function(cm) {
+  cm.execCommand("goWordLeft");
+  eqPos(cm.getCursor(), Pos(0, 0));
+  cm.execCommand("goWordRight"); cm.execCommand("goWordRight");
+  eqPos(cm.getCursor(), Pos(0, 7));
+  cm.execCommand("goWordLeft");
+  eqPos(cm.getCursor(), Pos(0, 5));
+  cm.execCommand("goWordRight"); cm.execCommand("goWordRight");
+  eqPos(cm.getCursor(), Pos(0, 12));
+  cm.execCommand("goWordLeft");
+  eqPos(cm.getCursor(), Pos(0, 9));
+  cm.execCommand("goWordRight"); cm.execCommand("goWordRight"); cm.execCommand("goWordRight");
+  eqPos(cm.getCursor(), Pos(0, 24));
+  cm.execCommand("goWordRight"); cm.execCommand("goWordRight");
+  eqPos(cm.getCursor(), Pos(1, 9));
+  cm.execCommand("goWordRight");
+  eqPos(cm.getCursor(), Pos(1, 13));
+  cm.execCommand("goWordRight"); cm.execCommand("goWordRight");
+  eqPos(cm.getCursor(), Pos(2, 0));
+}, {value: "this is (the) firstline.\na foo12\u00e9\u00f8\u00d7bar\n"});
+
+testCM("groupMovementCommands", function(cm) {
+  cm.execCommand("goGroupLeft");
+  eqPos(cm.getCursor(), Pos(0, 0));
+  cm.execCommand("goGroupRight");
+  eqPos(cm.getCursor(), Pos(0, 4));
+  cm.execCommand("goGroupRight");
+  eqPos(cm.getCursor(), Pos(0, 7));
+  cm.execCommand("goGroupRight");
+  eqPos(cm.getCursor(), Pos(0, 10));
+  cm.execCommand("goGroupLeft");
+  eqPos(cm.getCursor(), Pos(0, 7));
+  cm.execCommand("goGroupRight"); cm.execCommand("goGroupRight"); cm.execCommand("goGroupRight");
+  eqPos(cm.getCursor(), Pos(0, 15));
+  cm.setCursor(Pos(0, 17));
+  cm.execCommand("goGroupLeft");
+  eqPos(cm.getCursor(), Pos(0, 16));
+  cm.execCommand("goGroupLeft");
+  eqPos(cm.getCursor(), Pos(0, 14));
+  cm.execCommand("goGroupRight"); cm.execCommand("goGroupRight");
+  eqPos(cm.getCursor(), Pos(0, 20));
+  cm.execCommand("goGroupRight");
+  eqPos(cm.getCursor(), Pos(1, 5));
+  cm.execCommand("goGroupLeft"); cm.execCommand("goGroupLeft");
+  eqPos(cm.getCursor(), Pos(1, 0));
+  cm.execCommand("goGroupLeft");
+  eqPos(cm.getCursor(), Pos(0, 16));
+}, {value: "booo ba---quux. ffff\n  abc d"});
+
+testCM("charMovementCommands", function(cm) {
+  cm.execCommand("goCharLeft"); cm.execCommand("goColumnLeft");
+  eqPos(cm.getCursor(), Pos(0, 0));
+  cm.execCommand("goCharRight"); cm.execCommand("goCharRight");
+  eqPos(cm.getCursor(), Pos(0, 2));
+  cm.setCursor(Pos(1, 0));
+  cm.execCommand("goColumnLeft");
+  eqPos(cm.getCursor(), Pos(1, 0));
+  cm.execCommand("goCharLeft");
+  eqPos(cm.getCursor(), Pos(0, 5));
+  cm.execCommand("goColumnRight");
+  eqPos(cm.getCursor(), Pos(0, 5));
+  cm.execCommand("goCharRight");
+  eqPos(cm.getCursor(), Pos(1, 0));
+  cm.execCommand("goLineEnd");
+  eqPos(cm.getCursor(), Pos(1, 5));
+  cm.execCommand("goLineStartSmart");
+  eqPos(cm.getCursor(), Pos(1, 1));
+  cm.execCommand("goLineStartSmart");
+  eqPos(cm.getCursor(), Pos(1, 0));
+  cm.setCursor(Pos(2, 0));
+  cm.execCommand("goCharRight"); cm.execCommand("goColumnRight");
+  eqPos(cm.getCursor(), Pos(2, 0));
+}, {value: "line1\n ine2\n"});
+
+testCM("verticalMovementCommands", function(cm) {
+  cm.execCommand("goLineUp");
+  eqPos(cm.getCursor(), Pos(0, 0));
+  cm.execCommand("goLineDown");
+  if (!phantom) // This fails in PhantomJS, though not in a real Webkit
+    eqPos(cm.getCursor(), Pos(1, 0));
+  cm.setCursor(Pos(1, 12));
+  cm.execCommand("goLineDown");
+  eqPos(cm.getCursor(), Pos(2, 5));
+  cm.execCommand("goLineDown");
+  eqPos(cm.getCursor(), Pos(3, 0));
+  cm.execCommand("goLineUp");
+  eqPos(cm.getCursor(), Pos(2, 5));
+  cm.execCommand("goLineUp");
+  eqPos(cm.getCursor(), Pos(1, 12));
+  cm.execCommand("goPageDown");
+  eqPos(cm.getCursor(), Pos(5, 0));
+  cm.execCommand("goPageDown"); cm.execCommand("goLineDown");
+  eqPos(cm.getCursor(), Pos(5, 0));
+  cm.execCommand("goPageUp");
+  eqPos(cm.getCursor(), Pos(0, 0));
+}, {value: "line1\nlong long line2\nline3\n\nline5\n"});
+
+testCM("verticalMovementCommandsWrapping", function(cm) {
+  cm.setSize(120);
+  cm.setCursor(Pos(0, 5));
+  cm.execCommand("goLineDown");
+  eq(cm.getCursor().line, 0);
+  is(cm.getCursor().ch > 5, "moved beyond wrap");
+  for (var i = 0; ; ++i) {
+    is(i < 20, "no endless loop");
+    cm.execCommand("goLineDown");
+    var cur = cm.getCursor();
+    if (cur.line == 1) eq(cur.ch, 5);
+    if (cur.line == 2) { eq(cur.ch, 1); break; }
+  }
+}, {value: "a very long line that wraps around somehow so that we can test cursor movement\nshortone\nk",
+    lineWrapping: true});
+
+testCM("rtlMovement", function(cm) {
+  forEach(["خحج", "خحabcخحج", "abخحخحجcd", "abخde", "abخح2342خ1حج", "خ1ح2خح3حxج",
+           "خحcd", "1خحcd", "abcdeح1ج", "خمرحبها مها!", "foobarر",
+           "<img src=\"/בדיקה3.jpg\">"], function(line) {
+    var inv = line.charAt(0) == "خ";
+    cm.setValue(line + "\n"); cm.execCommand(inv ? "goLineEnd" : "goLineStart");
+    var cursor = byClassName(cm.getWrapperElement(), "CodeMirror-cursor")[0];
+    var prevX = cursor.offsetLeft, prevY = cursor.offsetTop;
+    for (var i = 0; i <= line.length; ++i) {
+      cm.execCommand("goCharRight");
+      if (i == line.length) is(cursor.offsetTop > prevY, "next line");
+      else is(cursor.offsetLeft > prevX, "moved right");
+      prevX = cursor.offsetLeft; prevY = cursor.offsetTop;
+    }
+    cm.setCursor(0, 0); cm.execCommand(inv ? "goLineStart" : "goLineEnd");
+    prevX = cursor.offsetLeft;
+    for (var i = 0; i < line.length; ++i) {
+      cm.execCommand("goCharLeft");
+      is(cursor.offsetLeft < prevX, "moved left");
+      prevX = cursor.offsetLeft;
+    }
+  });
+}, {rtlMoveVisually: true});
+
+// Verify that updating a line clears its bidi ordering
+testCM("bidiUpdate", function(cm) {
+  cm.setCursor(Pos(0, 2));
+  cm.replaceSelection("خحج", "start");
+  cm.execCommand("goCharRight");
+  eqPos(cm.getCursor(), Pos(0, 4));
+}, {value: "abcd\n"});
+
+testCM("movebyTextUnit", function(cm) {
+  cm.setValue("בְּרֵאשִ\ńéée\n");
+  cm.execCommand("goLineEnd");
+  for (var i = 0; i < 4; ++i) cm.execCommand("goCharRight");
+  eqPos(cm.getCursor(), Pos(0, 0));
+  cm.execCommand("goCharRight");
+  eqPos(cm.getCursor(), Pos(1, 0));
+  cm.execCommand("goCharRight");
+  cm.execCommand("goCharRight");
+  eqPos(cm.getCursor(), Pos(1, 3));
+  cm.execCommand("goCharRight");
+  cm.execCommand("goCharRight");
+  eqPos(cm.getCursor(), Pos(1, 6));
+});
+
+testCM("lineChangeEvents", function(cm) {
+  addDoc(cm, 3, 5);
+  var log = [], want = ["ch 0", "ch 1", "del 2", "ch 0", "ch 0", "del 1", "del 3", "del 4"];
+  for (var i = 0; i < 5; ++i) {
+    CodeMirror.on(cm.getLineHandle(i), "delete", function(i) {
+      return function() {log.push("del " + i);};
+    }(i));
+    CodeMirror.on(cm.getLineHandle(i), "change", function(i) {
+      return function() {log.push("ch " + i);};
+    }(i));
+  }
+  cm.replaceRange("x", Pos(0, 1));
+  cm.replaceRange("xy", Pos(1, 1), Pos(2));
+  cm.replaceRange("foo\nbar", Pos(0, 1));
+  cm.replaceRange("", Pos(0, 0), Pos(cm.lineCount()));
+  eq(log.length, want.length, "same length");
+  for (var i = 0; i < log.length; ++i)
+    eq(log[i], want[i]);
+});
+
+testCM("scrollEntirelyToRight", function(cm) {
+  if (phantom) return;
+  addDoc(cm, 500, 2);
+  cm.setCursor(Pos(0, 500));
+  var wrap = cm.getWrapperElement(), cur = byClassName(wrap, "CodeMirror-cursor")[0];
+  is(wrap.getBoundingClientRect().right > cur.getBoundingClientRect().left);
+});
+
+testCM("lineWidgets", function(cm) {
+  addDoc(cm, 500, 3);
+  var last = cm.charCoords(Pos(2, 0));
+  var node = document.createElement("div");
+  node.innerHTML = "hi";
+  var widget = cm.addLineWidget(1, node);
+  is(last.top < cm.charCoords(Pos(2, 0)).top, "took up space");
+  cm.setCursor(Pos(1, 1));
+  cm.execCommand("goLineDown");
+  eqPos(cm.getCursor(), Pos(2, 1));
+  cm.execCommand("goLineUp");
+  eqPos(cm.getCursor(), Pos(1, 1));
+});
+
+testCM("lineWidgetFocus", function(cm) {
+  var place = document.getElementById("testground");
+  place.className = "offscreen";
+  try {
+    addDoc(cm, 500, 10);
+    var node = document.createElement("input");
+    var widget = cm.addLineWidget(1, node);
+    node.focus();
+    eq(document.activeElement, node);
+    cm.replaceRange("new stuff", Pos(1, 0));
+    eq(document.activeElement, node);
+  } finally {
+    place.className = "";
+  }
+});
+
+testCM("getLineNumber", function(cm) {
+  addDoc(cm, 2, 20);
+  var h1 = cm.getLineHandle(1);
+  eq(cm.getLineNumber(h1), 1);
+  cm.replaceRange("hi\nbye\n", Pos(0, 0));
+  eq(cm.getLineNumber(h1), 3);
+  cm.setValue("");
+  eq(cm.getLineNumber(h1), null);
+});
+
+testCM("jumpTheGap", function(cm) {
+  var longLine = "abcdef ghiklmnop qrstuvw xyz ";
+  longLine += longLine; longLine += longLine; longLine += longLine;
+  cm.setLine(2, longLine);
+  cm.setSize("200px", null);
+  cm.getWrapperElement().style.lineHeight = 2;
+  cm.refresh();
+  cm.setCursor(Pos(0, 1));
+  cm.execCommand("goLineDown");
+  eqPos(cm.getCursor(), Pos(1, 1));
+  cm.execCommand("goLineDown");
+  eqPos(cm.getCursor(), Pos(2, 1));
+  cm.execCommand("goLineDown");
+  eq(cm.getCursor().line, 2);
+  is(cm.getCursor().ch > 1);
+  cm.execCommand("goLineUp");
+  eqPos(cm.getCursor(), Pos(2, 1));
+  cm.execCommand("goLineUp");
+  eqPos(cm.getCursor(), Pos(1, 1));
+  var node = document.createElement("div");
+  node.innerHTML = "hi"; node.style.height = "30px";
+  cm.addLineWidget(0, node);
+  cm.addLineWidget(1, node.cloneNode(true), {above: true});
+  cm.setCursor(Pos(0, 2));
+  cm.execCommand("goLineDown");
+  eqPos(cm.getCursor(), Pos(1, 2));
+  cm.execCommand("goLineUp");
+  eqPos(cm.getCursor(), Pos(0, 2));
+}, {lineWrapping: true, value: "abc\ndef\nghi\njkl\n"});
+
+testCM("addLineClass", function(cm) {
+  function cls(line, text, bg, wrap) {
+    var i = cm.lineInfo(line);
+    eq(i.textClass, text);
+    eq(i.bgClass, bg);
+    eq(i.wrapClass, wrap);
+  }
+  cm.addLineClass(0, "text", "foo");
+  cm.addLineClass(0, "text", "bar");
+  cm.addLineClass(1, "background", "baz");
+  cm.addLineClass(1, "wrap", "foo");
+  cls(0, "foo bar", null, null);
+  cls(1, null, "baz", "foo");
+  var lines = cm.display.lineDiv;
+  eq(byClassName(lines, "foo").length, 2);
+  eq(byClassName(lines, "bar").length, 1);
+  eq(byClassName(lines, "baz").length, 1);
+  cm.removeLineClass(0, "text", "foo");
+  cls(0, "bar", null, null);
+  cm.removeLineClass(0, "text", "foo");
+  cls(0, "bar", null, null);
+  cm.removeLineClass(0, "text", "bar");
+  cls(0, null, null, null);
+  cm.addLineClass(1, "wrap", "quux");
+  cls(1, null, "baz", "foo quux");
+  cm.removeLineClass(1, "wrap");
+  cls(1, null, "baz", null);
+}, {value: "hohoho\n"});
+
+testCM("atomicMarker", function(cm) {
+  addDoc(cm, 10, 10);
+  function atom(ll, cl, lr, cr, li, ri) {
+    return cm.markText(Pos(ll, cl), Pos(lr, cr),
+                       {atomic: true, inclusiveLeft: li, inclusiveRight: ri});
+  }
+  var m = atom(0, 1, 0, 5);
+  cm.setCursor(Pos(0, 1));
+  cm.execCommand("goCharRight");
+  eqPos(cm.getCursor(), Pos(0, 5));
+  cm.execCommand("goCharLeft");
+  eqPos(cm.getCursor(), Pos(0, 1));
+  m.clear();
+  m = atom(0, 0, 0, 5, true);
+  eqPos(cm.getCursor(), Pos(0, 5), "pushed out");
+  cm.execCommand("goCharLeft");
+  eqPos(cm.getCursor(), Pos(0, 5));
+  m.clear();
+  m = atom(8, 4, 9, 10, false, true);
+  cm.setCursor(Pos(9, 8));
+  eqPos(cm.getCursor(), Pos(8, 4), "set");
+  cm.execCommand("goCharRight");
+  eqPos(cm.getCursor(), Pos(8, 4), "char right");
+  cm.execCommand("goLineDown");
+  eqPos(cm.getCursor(), Pos(8, 4), "line down");
+  cm.execCommand("goCharLeft");
+  eqPos(cm.getCursor(), Pos(8, 3));
+  m.clear();
+  m = atom(1, 1, 3, 8);
+  cm.setCursor(Pos(2, 0));
+  eqPos(cm.getCursor(), Pos(3, 8));
+  cm.execCommand("goCharLeft");
+  eqPos(cm.getCursor(), Pos(1, 1));
+  cm.execCommand("goCharRight");
+  eqPos(cm.getCursor(), Pos(3, 8));
+  cm.execCommand("goLineUp");
+  eqPos(cm.getCursor(), Pos(1, 1));
+  cm.execCommand("goLineDown");
+  eqPos(cm.getCursor(), Pos(3, 8));
+  cm.execCommand("delCharBefore");
+  eq(cm.getValue().length, 80, "del chunk");
+  m = atom(3, 0, 5, 5);
+  cm.setCursor(Pos(3, 0));
+  cm.execCommand("delWordAfter");
+  eq(cm.getValue().length, 53, "del chunk");
+});
+
+testCM("readOnlyMarker", function(cm) {
+  function mark(ll, cl, lr, cr, at) {
+    return cm.markText(Pos(ll, cl), Pos(lr, cr),
+                       {readOnly: true, atomic: at});
+  }
+  var m = mark(0, 1, 0, 4);
+  cm.setCursor(Pos(0, 2));
+  cm.replaceSelection("hi", "end");
+  eqPos(cm.getCursor(), Pos(0, 2));
+  eq(cm.getLine(0), "abcde");
+  cm.execCommand("selectAll");
+  cm.replaceSelection("oops");
+  eq(cm.getValue(), "oopsbcd");
+  cm.undo();
+  eqPos(m.find().from, Pos(0, 1));
+  eqPos(m.find().to, Pos(0, 4));
+  m.clear();
+  cm.setCursor(Pos(0, 2));
+  cm.replaceSelection("hi");
+  eq(cm.getLine(0), "abhicde");
+  eqPos(cm.getCursor(), Pos(0, 4));
+  m = mark(0, 2, 2, 2, true);
+  cm.setSelection(Pos(1, 1), Pos(2, 4));
+  cm.replaceSelection("t", "end");
+  eqPos(cm.getCursor(), Pos(2, 3));
+  eq(cm.getLine(2), "klto");
+  cm.execCommand("goCharLeft");
+  cm.execCommand("goCharLeft");
+  eqPos(cm.getCursor(), Pos(0, 2));
+  cm.setSelection(Pos(0, 1), Pos(0, 3));
+  cm.replaceSelection("xx");
+  eqPos(cm.getCursor(), Pos(0, 3));
+  eq(cm.getLine(0), "axxhicde");
+}, {value: "abcde\nfghij\nklmno\n"});
+
+testCM("dirtyBit", function(cm) {
+  eq(cm.isClean(), true);
+  cm.replaceSelection("boo");
+  eq(cm.isClean(), false);
+  cm.undo();
+  eq(cm.isClean(), true);
+  cm.replaceSelection("boo");
+  cm.replaceSelection("baz");
+  cm.undo();
+  eq(cm.isClean(), false);
+  cm.markClean();
+  eq(cm.isClean(), true);
+  cm.undo();
+  eq(cm.isClean(), false);
+  cm.redo();
+  eq(cm.isClean(), true);
+});
+
+testCM("addKeyMap", function(cm) {
+  function sendKey(code) {
+    cm.triggerOnKeyDown({type: "keydown", keyCode: code,
+                         preventDefault: function(){}, stopPropagation: function(){}});
+  }
+
+  sendKey(39);
+  eqPos(cm.getCursor(), Pos(0, 1));
+  var test = 0;
+  var map1 = {Right: function() { ++test; }}, map2 = {Right: function() { test += 10; }}
+  cm.addKeyMap(map1);
+  sendKey(39);
+  eqPos(cm.getCursor(), Pos(0, 1));
+  eq(test, 1);
+  cm.addKeyMap(map2, true);
+  sendKey(39);
+  eq(test, 2);
+  cm.removeKeyMap(map1);
+  sendKey(39);
+  eq(test, 12);
+  cm.removeKeyMap(map2);
+  sendKey(39);
+  eq(test, 12);
+  eqPos(cm.getCursor(), Pos(0, 2));
+  cm.addKeyMap({Right: function() { test = 55; }, name: "mymap"});
+  sendKey(39);
+  eq(test, 55);
+  cm.removeKeyMap("mymap");
+  sendKey(39);
+  eqPos(cm.getCursor(), Pos(0, 3));
+}, {value: "abc"});
+
+testCM("findPosH", function(cm) {
+  forEach([{from: Pos(0, 0), to: Pos(0, 1), by: 1},
+           {from: Pos(0, 0), to: Pos(0, 0), by: -1, hitSide: true},
+           {from: Pos(0, 0), to: Pos(0, 4), by: 1, unit: "word"},
+           {from: Pos(0, 0), to: Pos(0, 8), by: 2, unit: "word"},
+           {from: Pos(0, 0), to: Pos(2, 0), by: 20, unit: "word", hitSide: true},
+           {from: Pos(0, 7), to: Pos(0, 5), by: -1, unit: "word"},
+           {from: Pos(0, 4), to: Pos(0, 8), by: 1, unit: "word"},
+           {from: Pos(1, 0), to: Pos(1, 18), by: 3, unit: "word"},
+           {from: Pos(1, 22), to: Pos(1, 5), by: -3, unit: "word"},
+           {from: Pos(1, 15), to: Pos(1, 10), by: -5},
+           {from: Pos(1, 15), to: Pos(1, 10), by: -5, unit: "column"},
+           {from: Pos(1, 15), to: Pos(1, 0), by: -50, unit: "column", hitSide: true},
+           {from: Pos(1, 15), to: Pos(1, 24), by: 50, unit: "column", hitSide: true},
+           {from: Pos(1, 15), to: Pos(2, 0), by: 50, hitSide: true}], function(t) {
+    var r = cm.findPosH(t.from, t.by, t.unit || "char");
+    eqPos(r, t.to);
+    eq(!!r.hitSide, !!t.hitSide);
+  });
+}, {value: "line one\nline two.something.other\n"});
+
+testCM("beforeChange", function(cm) {
+  cm.on("beforeChange", function(cm, change) {
+    var text = [];
+    for (var i = 0; i < change.text.length; ++i)
+      text.push(change.text[i].replace(/\s/g, "_"));
+    change.update(null, null, text);
+  });
+  cm.setValue("hello, i am a\nnew document\n");
+  eq(cm.getValue(), "hello,_i_am_a\nnew_document\n");
+  CodeMirror.on(cm.getDoc(), "beforeChange", function(doc, change) {
+    if (change.from.line == 0) change.cancel();
+  });
+  cm.setValue("oops"); // Canceled
+  eq(cm.getValue(), "hello,_i_am_a\nnew_document\n");
+  cm.replaceRange("hey hey hey", Pos(1, 0), Pos(2, 0));
+  eq(cm.getValue(), "hello,_i_am_a\nhey_hey_hey");
+}, {value: "abcdefghijk"});
+
+testCM("beforeChangeUndo", function(cm) {
+  cm.setLine(0, "hi");
+  cm.setLine(0, "bye");
+  eq(cm.historySize().undo, 2);
+  cm.on("beforeChange", function(cm, change) {
+    is(!change.update);
+    change.cancel();
+  });
+  cm.undo();
+  eq(cm.historySize().undo, 0);
+  eq(cm.getValue(), "bye\ntwo");
+}, {value: "one\ntwo"});
+
+testCM("beforeSelectionChange", function(cm) {
+  function notAtEnd(cm, pos) {
+    var len = cm.getLine(pos.line).length;
+    if (!len || pos.ch == len) return Pos(pos.line, pos.ch - 1);
+    return pos;
+  }
+  cm.on("beforeSelectionChange", function(cm, sel) {
+    sel.head = notAtEnd(cm, sel.head);
+    sel.anchor = notAtEnd(cm, sel.anchor);
+  });
+
+  addDoc(cm, 10, 10);
+  cm.execCommand("goLineEnd");
+  eqPos(cm.getCursor(), Pos(0, 9));
+  cm.execCommand("selectAll");
+  eqPos(cm.getCursor("start"), Pos(0, 0));
+  eqPos(cm.getCursor("end"), Pos(9, 9));
+});
+
+testCM("change_removedText", function(cm) {
+  cm.setValue("abc\ndef");
+
+  var removedText;
+  cm.on("change", function(cm, change) {
+    removedText = [change.removed, change.next && change.next.removed];
+  });
+
+  cm.operation(function() {
+    cm.replaceRange("xyz", Pos(0, 0), Pos(1,1));
+    cm.replaceRange("123", Pos(0,0));
+  });
+
+  eq(removedText[0].join("\n"), "abc\nd");
+  eq(removedText[1].join("\n"), "");
+
+  cm.undo();
+  eq(removedText[0].join("\n"), "123");
+  eq(removedText[1].join("\n"), "xyz");
+
+  cm.redo();
+  eq(removedText[0].join("\n"), "abc\nd");
+  eq(removedText[1].join("\n"), "");
+});
diff --git a/third-party/codemirror-3.15/test/vim_test.js b/third-party/codemirror-3.15/test/vim_test.js
new file mode 100644 (file)
index 0000000..ec0fae0
--- /dev/null
@@ -0,0 +1,2356 @@
+var code = '' +
+' wOrd1 (#%\n' +
+' word3] \n' +
+'aopop pop 0 1 2 3 4\n' +
+' (a) [b] {c} \n' +
+'int getchar(void) {\n' +
+'  static char buf[BUFSIZ];\n' +
+'  static char *bufp = buf;\n' +
+'  if (n == 0) {  /* buffer is empty */\n' +
+'    n = read(0, buf, sizeof buf);\n' +
+'    bufp = buf;\n' +
+'  }\n' +
+'\n' +
+'  return (--n >= 0) ? (unsigned char) *bufp++ : EOF;\n' +
+' \n' +
+'}\n';
+
+var lines = (function() {
+  lineText = code.split('\n');
+  var ret = [];
+  for (var i = 0; i < lineText.length; i++) {
+    ret[i] = {
+      line: i,
+      length: lineText[i].length,
+      lineText: lineText[i],
+      textStart: /^\s*/.exec(lineText[i])[0].length
+    };
+  }
+  return ret;
+})();
+var endOfDocument = makeCursor(lines.length - 1,
+    lines[lines.length - 1].length);
+var wordLine = lines[0];
+var bigWordLine = lines[1];
+var charLine = lines[2];
+var bracesLine = lines[3];
+var seekBraceLine = lines[4];
+
+var word1 = {
+  start: { line: wordLine.line, ch: 1 },
+  end: { line: wordLine.line, ch: 5 }
+};
+var word2 = {
+  start: { line: wordLine.line, ch: word1.end.ch + 2 },
+  end: { line: wordLine.line, ch: word1.end.ch + 4 }
+};
+var word3 = {
+  start: { line: bigWordLine.line, ch: 1 },
+  end: { line: bigWordLine.line, ch: 5 }
+};
+var bigWord1 = word1;
+var bigWord2 = word2;
+var bigWord3 = {
+  start: { line: bigWordLine.line, ch: 1 },
+  end: { line: bigWordLine.line, ch: 7 }
+};
+var bigWord4 = {
+  start: { line: bigWordLine.line, ch: bigWord1.end.ch + 3 },
+  end: { line: bigWordLine.line, ch: bigWord1.end.ch + 7 }
+};
+
+var oChars = [ { line: charLine.line, ch: 1 },
+    { line: charLine.line, ch: 3 },
+    { line: charLine.line, ch: 7 } ];
+var pChars = [ { line: charLine.line, ch: 2 },
+    { line: charLine.line, ch: 4 },
+    { line: charLine.line, ch: 6 },
+    { line: charLine.line, ch: 8 } ];
+var numChars = [ { line: charLine.line, ch: 10 },
+    { line: charLine.line, ch: 12 },
+    { line: charLine.line, ch: 14 },
+    { line: charLine.line, ch: 16 },
+    { line: charLine.line, ch: 18 }];
+var parens1 = {
+  start: { line: bracesLine.line, ch: 1 },
+  end: { line: bracesLine.line, ch: 3 }
+};
+var squares1 = {
+  start: { line: bracesLine.line, ch: 5 },
+  end: { line: bracesLine.line, ch: 7 }
+};
+var curlys1 = {
+  start: { line: bracesLine.line, ch: 9 },
+  end: { line: bracesLine.line, ch: 11 }
+};
+var seekOutside = {
+  start: { line: seekBraceLine.line, ch: 1 },
+  end: { line: seekBraceLine.line, ch: 16 }
+};
+var seekInside = {
+  start: { line: seekBraceLine.line, ch: 14 },
+  end: { line: seekBraceLine.line, ch: 11 }
+};
+
+function copyCursor(cur) {
+  return { ch: cur.ch, line: cur.line };
+}
+
+function testVim(name, run, opts, expectedFail) {
+  var vimOpts = {
+    lineNumbers: true,
+    vimMode: true,
+    showCursorWhenSelecting: true,
+    value: code
+  };
+  for (var prop in opts) {
+    if (opts.hasOwnProperty(prop)) {
+      vimOpts[prop] = opts[prop];
+    }
+  }
+  return test('vim_' + name, function() {
+    var place = document.getElementById("testground");
+    var cm = CodeMirror(place, vimOpts);
+    var vim = CodeMirror.Vim.maybeInitVimState_(cm);
+
+    function doKeysFn(cm) {
+      return function(args) {
+        if (args instanceof Array) {
+          arguments = args;
+        }
+        for (var i = 0; i < arguments.length; i++) {
+          CodeMirror.Vim.handleKey(cm, arguments[i]);
+        }
+      }
+    }
+    function doInsertModeKeysFn(cm) {
+      return function(args) {
+        if (args instanceof Array) { arguments = args; }
+        function executeHandler(handler) {
+          if (typeof handler == 'string') {
+            CodeMirror.commands[handler](cm);
+          } else {
+            handler(cm);
+          }
+          return true;
+        }
+        for (var i = 0; i < arguments.length; i++) {
+          var key = arguments[i];
+          // Find key in keymap and handle.
+          var handled = CodeMirror.lookupKey(key, ['vim-insert'], executeHandler);
+          // Record for insert mode.
+          if (handled === true && cm.state.vim.insertMode && arguments[i] != 'Esc') {
+            var lastChange = CodeMirror.Vim.getVimGlobalState_().macroModeState.lastInsertModeChanges;
+            if (lastChange) {
+              lastChange.changes.push(new CodeMirror.Vim.InsertModeKey(key));
+            }
+          }
+        }
+      }
+    }
+    function doExFn(cm) {
+      return function(command) {
+        cm.openDialog = helpers.fakeOpenDialog(command);
+        helpers.doKeys(':');
+      }
+    }
+    function assertCursorAtFn(cm) {
+      return function(line, ch) {
+        var pos;
+        if (ch == null && typeof line.line == 'number') {
+          pos = line;
+        } else {
+          pos = makeCursor(line, ch);
+        }
+        eqPos(pos, cm.getCursor());
+      }
+    }
+    function fakeOpenDialog(result) {
+      return function(text, callback) {
+        return callback(result);
+      }
+    }
+    var helpers = {
+      doKeys: doKeysFn(cm),
+      // Warning: Only emulates keymap events, not character insertions. Use
+      // replaceRange to simulate character insertions.
+      // Keys are in CodeMirror format, NOT vim format.
+      doInsertModeKeys: doInsertModeKeysFn(cm),
+      doEx: doExFn(cm),
+      assertCursorAt: assertCursorAtFn(cm),
+      fakeOpenDialog: fakeOpenDialog,
+      getRegisterController: function() {
+        return CodeMirror.Vim.getRegisterController();
+      }
+    }
+    CodeMirror.Vim.resetVimGlobalState_();
+    var successful = false;
+    try {
+      run(cm, vim, helpers);
+      successful = true;
+    } finally {
+      if ((debug && !successful) || verbose) {
+        place.style.visibility = "visible";
+      } else {
+        place.removeChild(cm.getWrapperElement());
+      }
+    }
+  }, expectedFail);
+};
+testVim('qq@q', function(cm, vim, helpers) {
+  cm.setCursor(0, 0);
+  helpers.doKeys('q', 'q', 'l', 'l', 'q');
+  helpers.assertCursorAt(0,2);
+  helpers.doKeys('@', 'q');
+  helpers.assertCursorAt(0,4);
+}, { value: '            '});
+testVim('@@', function(cm, vim, helpers) {
+  cm.setCursor(0, 0);
+  helpers.doKeys('q', 'q', 'l', 'l', 'q');
+  helpers.assertCursorAt(0,2);
+  helpers.doKeys('@', 'q');
+  helpers.assertCursorAt(0,4);
+  helpers.doKeys('@', '@');
+  helpers.assertCursorAt(0,6);
+}, { value: '            '});
+var jumplistScene = ''+
+  'word\n'+
+  '(word)\n'+
+  '{word\n'+
+  'word.\n'+
+  '\n'+
+  'word search\n'+
+  '}word\n'+
+  'word\n'+
+  'word\n';
+function testJumplist(name, keys, endPos, startPos, dialog) {
+  endPos = makeCursor(endPos[0], endPos[1]);
+  startPos = makeCursor(startPos[0], startPos[1]);
+  testVim(name, function(cm, vim, helpers) {
+    CodeMirror.Vim.resetVimGlobalState_();
+    if(dialog)cm.openDialog = helpers.fakeOpenDialog('word');
+    cm.setCursor(startPos);
+    helpers.doKeys.apply(null, keys);
+    helpers.assertCursorAt(endPos);
+  }, {value: jumplistScene});
+};
+testJumplist('jumplist_H', ['H', '<C-o>'], [5,2], [5,2]);
+testJumplist('jumplist_M', ['M', '<C-o>'], [2,2], [2,2]);
+testJumplist('jumplist_L', ['L', '<C-o>'], [2,2], [2,2]);
+testJumplist('jumplist_[[', ['[', '[', '<C-o>'], [5,2], [5,2]);
+testJumplist('jumplist_]]', [']', ']', '<C-o>'], [2,2], [2,2]);
+testJumplist('jumplist_G', ['G', '<C-o>'], [5,2], [5,2]);
+testJumplist('jumplist_gg', ['g', 'g', '<C-o>'], [5,2], [5,2]);
+testJumplist('jumplist_%', ['%', '<C-o>'], [1,5], [1,5]);
+testJumplist('jumplist_{', ['{', '<C-o>'], [1,5], [1,5]);
+testJumplist('jumplist_}', ['}', '<C-o>'], [1,5], [1,5]);
+testJumplist('jumplist_\'', ['m', 'a', 'h', '\'', 'a', 'h', '<C-i>'], [1,5], [1,5]);
+testJumplist('jumplist_`', ['m', 'a', 'h', '`', 'a', 'h', '<C-i>'], [1,5], [1,5]);
+testJumplist('jumplist_*_cachedCursor', ['*', '<C-o>'], [1,3], [1,3]);
+testJumplist('jumplist_#_cachedCursor', ['#', '<C-o>'], [1,3], [1,3]);
+testJumplist('jumplist_n', ['#', 'n', '<C-o>'], [1,1], [2,3]);
+testJumplist('jumplist_N', ['#', 'N', '<C-o>'], [1,1], [2,3]);
+testJumplist('jumplist_repeat_<c-o>', ['*', '*', '*', '3', '<C-o>'], [2,3], [2,3]);
+testJumplist('jumplist_repeat_<c-i>', ['*', '*', '*', '3', '<C-o>', '2', '<C-i>'], [5,0], [2,3]);
+testJumplist('jumplist_repeated_motion', ['3', '*', '<C-o>'], [2,3], [2,3]);
+testJumplist('jumplist_/', ['/', '<C-o>'], [2,3], [2,3], 'dialog');
+testJumplist('jumplist_?', ['?', '<C-o>'], [2,3], [2,3], 'dialog');
+testJumplist('jumplist_skip_delted_mark<c-o>',
+             ['*', 'n', 'n', 'k', 'd', 'k', '<C-o>', '<C-o>', '<C-o>'],
+             [0,2], [0,2]);
+testJumplist('jumplist_skip_delted_mark<c-i>',
+             ['*', 'n', 'n', 'k', 'd', 'k', '<C-o>', '<C-i>', '<C-i>'],
+             [1,0], [0,2]);
+/**
+ * @param name Name of the test
+ * @param keys An array of keys or a string with a single key to simulate.
+ * @param endPos The expected end position of the cursor.
+ * @param startPos The position the cursor should start at, defaults to 0, 0.
+ */
+function testMotion(name, keys, endPos, startPos) {
+  testVim(name, function(cm, vim, helpers) {
+    if (!startPos) {
+      startPos = { line: 0, ch: 0 };
+    }
+    cm.setCursor(startPos);
+    helpers.doKeys(keys);
+    helpers.assertCursorAt(endPos);
+  });
+};
+
+function makeCursor(line, ch) {
+  return { line: line, ch: ch };
+};
+
+function offsetCursor(cur, offsetLine, offsetCh) {
+  return { line: cur.line + offsetLine, ch: cur.ch + offsetCh };
+};
+
+// Motion tests
+testMotion('|', '|', makeCursor(0, 0), makeCursor(0,4));
+testMotion('|_repeat', ['3', '|'], makeCursor(0, 2), makeCursor(0,4));
+testMotion('h', 'h', makeCursor(0, 0), word1.start);
+testMotion('h_repeat', ['3', 'h'], offsetCursor(word1.end, 0, -3), word1.end);
+testMotion('l', 'l', makeCursor(0, 1));
+testMotion('l_repeat', ['2', 'l'], makeCursor(0, 2));
+testMotion('j', 'j', offsetCursor(word1.end, 1, 0), word1.end);
+testMotion('j_repeat', ['2', 'j'], offsetCursor(word1.end, 2, 0), word1.end);
+testMotion('j_repeat_clip', ['1000', 'j'], endOfDocument);
+testMotion('k', 'k', offsetCursor(word3.end, -1, 0), word3.end);
+testMotion('k_repeat', ['2', 'k'], makeCursor(0, 4), makeCursor(2, 4));
+testMotion('k_repeat_clip', ['1000', 'k'], makeCursor(0, 4), makeCursor(2, 4));
+testMotion('w', 'w', word1.start);
+testMotion('w_multiple_newlines_no_space', 'w', makeCursor(12, 2), makeCursor(11, 2));
+testMotion('w_multiple_newlines_with_space', 'w', makeCursor(14, 0), makeCursor(12, 51));
+testMotion('w_repeat', ['2', 'w'], word2.start);
+testMotion('w_wrap', ['w'], word3.start, word2.start);
+testMotion('w_endOfDocument', 'w', endOfDocument, endOfDocument);
+testMotion('w_start_to_end', ['1000', 'w'], endOfDocument, makeCursor(0, 0));
+testMotion('W', 'W', bigWord1.start);
+testMotion('W_repeat', ['2', 'W'], bigWord3.start, bigWord1.start);
+testMotion('e', 'e', word1.end);
+testMotion('e_repeat', ['2', 'e'], word2.end);
+testMotion('e_wrap', 'e', word3.end, word2.end);
+testMotion('e_endOfDocument', 'e', endOfDocument, endOfDocument);
+testMotion('e_start_to_end', ['1000', 'e'], endOfDocument, makeCursor(0, 0));
+testMotion('b', 'b', word3.start, word3.end);
+testMotion('b_repeat', ['2', 'b'], word2.start, word3.end);
+testMotion('b_wrap', 'b', word2.start, word3.start);
+testMotion('b_startOfDocument', 'b', makeCursor(0, 0), makeCursor(0, 0));
+testMotion('b_end_to_start', ['1000', 'b'], makeCursor(0, 0), endOfDocument);
+testMotion('ge', ['g', 'e'], word2.end, word3.end);
+testMotion('ge_repeat', ['2', 'g', 'e'], word1.end, word3.start);
+testMotion('ge_wrap', ['g', 'e'], word2.end, word3.start);
+testMotion('ge_startOfDocument', ['g', 'e'], makeCursor(0, 0),
+    makeCursor(0, 0));
+testMotion('ge_end_to_start', ['1000', 'g', 'e'], makeCursor(0, 0), endOfDocument);
+testMotion('gg', ['g', 'g'], makeCursor(lines[0].line, lines[0].textStart),
+    makeCursor(3, 1));
+testMotion('gg_repeat', ['3', 'g', 'g'],
+    makeCursor(lines[2].line, lines[2].textStart));
+testMotion('G', 'G',
+    makeCursor(lines[lines.length - 1].line, lines[lines.length - 1].textStart),
+    makeCursor(3, 1));
+testMotion('G_repeat', ['3', 'G'], makeCursor(lines[2].line,
+    lines[2].textStart));
+// TODO: Make the test code long enough to test Ctrl-F and Ctrl-B.
+testMotion('0', '0', makeCursor(0, 0), makeCursor(0, 8));
+testMotion('^', '^', makeCursor(0, lines[0].textStart), makeCursor(0, 8));
+testMotion('+', '+', makeCursor(1, lines[1].textStart), makeCursor(0, 8));
+testMotion('-', '-', makeCursor(0, lines[0].textStart), makeCursor(1, 4));
+testMotion('_', ['6','_'], makeCursor(5, lines[5].textStart), makeCursor(0, 8));
+testMotion('$', '$', makeCursor(0, lines[0].length - 1), makeCursor(0, 1));
+testMotion('$_repeat', ['2', '$'], makeCursor(1, lines[1].length - 1),
+    makeCursor(0, 3));
+testMotion('f', ['f', 'p'], pChars[0], makeCursor(charLine.line, 0));
+testMotion('f_repeat', ['2', 'f', 'p'], pChars[2], pChars[0]);
+testMotion('f_num', ['f', '2'], numChars[2], makeCursor(charLine.line, 0));
+testMotion('t', ['t','p'], offsetCursor(pChars[0], 0, -1),
+    makeCursor(charLine.line, 0));
+testMotion('t_repeat', ['2', 't', 'p'], offsetCursor(pChars[2], 0, -1),
+    pChars[0]);
+testMotion('F', ['F', 'p'], pChars[0], pChars[1]);
+testMotion('F_repeat', ['2', 'F', 'p'], pChars[0], pChars[2]);
+testMotion('T', ['T', 'p'], offsetCursor(pChars[0], 0, 1), pChars[1]);
+testMotion('T_repeat', ['2', 'T', 'p'], offsetCursor(pChars[0], 0, 1), pChars[2]);
+testMotion('%_parens', ['%'], parens1.end, parens1.start);
+testMotion('%_squares', ['%'], squares1.end, squares1.start);
+testMotion('%_braces', ['%'], curlys1.end, curlys1.start);
+testMotion('%_seek_outside', ['%'], seekOutside.end, seekOutside.start);
+testMotion('%_seek_inside', ['%'], seekInside.end, seekInside.start);
+testVim('%_seek_skip', function(cm, vim, helpers) {
+  cm.setCursor(0,0);
+  helpers.doKeys(['%']);
+  helpers.assertCursorAt(0,9);
+}, {value:'01234"("()'});
+testVim('%_skip_string', function(cm, vim, helpers) {
+  cm.setCursor(0,0);
+  helpers.doKeys(['%']);
+  helpers.assertCursorAt(0,4);
+  cm.setCursor(0,2);
+  helpers.doKeys(['%']);
+  helpers.assertCursorAt(0,0);
+}, {value:'(")")'});
+(')')
+testVim('%_skip_comment', function(cm, vim, helpers) {
+  cm.setCursor(0,0);
+  helpers.doKeys(['%']);
+  helpers.assertCursorAt(0,6);
+  cm.setCursor(0,3);
+  helpers.doKeys(['%']);
+  helpers.assertCursorAt(0,0);
+}, {value:'(/*)*/)'});
+// Make sure that moving down after going to the end of a line always leaves you
+// at the end of a line, but preserves the offset in other cases
+testVim('Changing lines after Eol operation', function(cm, vim, helpers) {
+  cm.setCursor(0,0);
+  helpers.doKeys(['$']);
+  helpers.doKeys(['j']);
+  // After moving to Eol and then down, we should be at Eol of line 2
+  helpers.assertCursorAt({ line: 1, ch: lines[1].length - 1 });
+  helpers.doKeys(['j']);
+  // After moving down, we should be at Eol of line 3
+  helpers.assertCursorAt({ line: 2, ch: lines[2].length - 1 });
+  helpers.doKeys(['h']);
+  helpers.doKeys(['j']);
+  // After moving back one space and then down, since line 4 is shorter than line 2, we should
+  // be at Eol of line 2 - 1
+  helpers.assertCursorAt({ line: 3, ch: lines[3].length - 1 });
+  helpers.doKeys(['j']);
+  helpers.doKeys(['j']);
+  // After moving down again, since line 3 has enough characters, we should be back to the
+  // same place we were at on line 1
+  helpers.assertCursorAt({ line: 5, ch: lines[2].length - 2 });
+});
+//making sure gj and gk recover from clipping
+testVim('gj_gk_clipping', function(cm,vim,helpers){
+  cm.setCursor(0, 1);
+  helpers.doKeys('g','j','g','j');
+  helpers.assertCursorAt(2, 1);
+  helpers.doKeys('g','k','g','k');
+  helpers.assertCursorAt(0, 1);
+},{value: 'line 1\n\nline 2'});
+//testing a mix of j/k and gj/gk
+testVim('j_k_and_gj_gk', function(cm,vim,helpers){
+  cm.setSize(120);
+  cm.setCursor(0, 0);
+  //go to the last character on the first line
+  helpers.doKeys('$');
+  //move up/down on the column within the wrapped line
+  //side-effect: cursor is not locked to eol anymore
+  helpers.doKeys('g','k');
+  var cur=cm.getCursor();
+  eq(cur.line,0);
+  is((cur.ch<176),'gk didn\'t move cursor back (1)');
+  helpers.doKeys('g','j');
+  helpers.assertCursorAt(0, 176);
+  //should move to character 177 on line 2 (j/k preserve character index within line)
+  helpers.doKeys('j');
+  //due to different line wrapping, the cursor can be on a different screen-x now
+  //gj and gk preserve screen-x on movement, much like moveV
+  helpers.doKeys('3','g','k');
+  cur=cm.getCursor();
+  eq(cur.line,1);
+  is((cur.ch<176),'gk didn\'t move cursor back (2)');
+  helpers.doKeys('g','j','2','g','j');
+  //should return to the same character-index
+  helpers.doKeys('k');
+  helpers.assertCursorAt(0, 176);
+},{ lineWrapping:true, value: 'This line is intentially long to test movement of gj and gk over wrapped lines. I will start on the end of this line, then make a step up and back to set the origin for j and k.\nThis line is supposed to be even longer than the previous. I will jump here and make another wiggle with gj and gk, before I jump back to the line above. Both wiggles should not change my cursor\'s target character but both j/k and gj/gk change each other\'s reference position.'});
+testVim('gj_gk', function(cm, vim, helpers) {
+  if (phantom) return;
+  cm.setSize(120);
+  // Test top of document edge case.
+  cm.setCursor(0, 4);
+  helpers.doKeys('g', 'j');
+  helpers.doKeys('10', 'g', 'k');
+  helpers.assertCursorAt(0, 4);
+
+  // Test moving down preserves column position.
+  helpers.doKeys('g', 'j');
+  var pos1 = cm.getCursor();
+  var expectedPos2 = { line: 0, ch: (pos1.ch - 4) * 2 + 4};
+  helpers.doKeys('g', 'j');
+  helpers.assertCursorAt(expectedPos2);
+
+  // Move to the last character
+  cm.setCursor(0, 0);
+  // Move left to reset HSPos
+  helpers.doKeys('h');
+  // Test bottom of document edge case.
+  helpers.doKeys('100', 'g', 'j');
+  var endingPos = cm.getCursor();
+  is(endingPos != 0, 'gj should not be on wrapped line 0');
+  var topLeftCharCoords = cm.charCoords(makeCursor(0, 0));
+  var endingCharCoords = cm.charCoords(endingPos);
+  is(topLeftCharCoords.left == endingCharCoords.left, 'gj should end up on column 0');
+},{ lineNumbers: false, lineWrapping:true, value: 'Thislineisintentiallylongtotestmovementofgjandgkoverwrappedlines.' });
+testVim('}', function(cm, vim, helpers) {
+  cm.setCursor(0, 0);
+  helpers.doKeys('}');
+  helpers.assertCursorAt(1, 0);
+  cm.setCursor(0, 0);
+  helpers.doKeys('2', '}');
+  helpers.assertCursorAt(4, 0);
+  cm.setCursor(0, 0);
+  helpers.doKeys('6', '}');
+  helpers.assertCursorAt(5, 0);
+}, { value: 'a\n\nb\nc\n\nd' });
+testVim('{', function(cm, vim, helpers) {
+  cm.setCursor(5, 0);
+  helpers.doKeys('{');
+  helpers.assertCursorAt(4, 0);
+  cm.setCursor(5, 0);
+  helpers.doKeys('2', '{');
+  helpers.assertCursorAt(1, 0);
+  cm.setCursor(5, 0);
+  helpers.doKeys('6', '{');
+  helpers.assertCursorAt(0, 0);
+}, { value: 'a\n\nb\nc\n\nd' });
+
+// Operator tests
+testVim('dl', function(cm, vim, helpers) {
+  var curStart = makeCursor(0, 0);
+  cm.setCursor(curStart);
+  helpers.doKeys('d', 'l');
+  eq('word1 ', cm.getValue());
+  var register = helpers.getRegisterController().getRegister();
+  eq(' ', register.text);
+  is(!register.linewise);
+  eqPos(curStart, cm.getCursor());
+}, { value: ' word1 ' });
+testVim('dl_eol', function(cm, vim, helpers) {
+  cm.setCursor(0, 6);
+  helpers.doKeys('d', 'l');
+  eq(' word1', cm.getValue());
+  var register = helpers.getRegisterController().getRegister();
+  eq(' ', register.text);
+  is(!register.linewise);
+  helpers.assertCursorAt(0, 5);
+}, { value: ' word1 ' });
+testVim('dl_repeat', function(cm, vim, helpers) {
+  var curStart = makeCursor(0, 0);
+  cm.setCursor(curStart);
+  helpers.doKeys('2', 'd', 'l');
+  eq('ord1 ', cm.getValue());
+  var register = helpers.getRegisterController().getRegister();
+  eq(' w', register.text);
+  is(!register.linewise);
+  eqPos(curStart, cm.getCursor());
+}, { value: ' word1 ' });
+testVim('dh', function(cm, vim, helpers) {
+  var curStart = makeCursor(0, 3);
+  cm.setCursor(curStart);
+  helpers.doKeys('d', 'h');
+  eq(' wrd1 ', cm.getValue());
+  var register = helpers.getRegisterController().getRegister();
+  eq('o', register.text);
+  is(!register.linewise);
+  eqPos(offsetCursor(curStart, 0 , -1), cm.getCursor());
+}, { value: ' word1 ' });
+testVim('dj', function(cm, vim, helpers) {
+  var curStart = makeCursor(0, 3);
+  cm.setCursor(curStart);
+  helpers.doKeys('d', 'j');
+  eq(' word3', cm.getValue());
+  var register = helpers.getRegisterController().getRegister();
+  eq(' word1\nword2\n', register.text);
+  is(register.linewise);
+  helpers.assertCursorAt(0, 1);
+}, { value: ' word1\nword2\n word3' });
+testVim('dj_end_of_document', function(cm, vim, helpers) {
+  var curStart = makeCursor(0, 3);
+  cm.setCursor(curStart);
+  helpers.doKeys('d', 'j');
+  eq(' word1 ', cm.getValue());
+  var register = helpers.getRegisterController().getRegister();
+  eq('', register.text);
+  is(!register.linewise);
+  helpers.assertCursorAt(0, 3);
+}, { value: ' word1 ' });
+testVim('dk', function(cm, vim, helpers) {
+  var curStart = makeCursor(1, 3);
+  cm.setCursor(curStart);
+  helpers.doKeys('d', 'k');
+  eq(' word3', cm.getValue());
+  var register = helpers.getRegisterController().getRegister();
+  eq(' word1\nword2\n', register.text);
+  is(register.linewise);
+  helpers.assertCursorAt(0, 1);
+}, { value: ' word1\nword2\n word3' });
+testVim('dk_start_of_document', function(cm, vim, helpers) {
+  var curStart = makeCursor(0, 3);
+  cm.setCursor(curStart);
+  helpers.doKeys('d', 'k');
+  eq(' word1 ', cm.getValue());
+  var register = helpers.getRegisterController().getRegister();
+  eq('', register.text);
+  is(!register.linewise);
+  helpers.assertCursorAt(0, 3);
+}, { value: ' word1 ' });
+testVim('dw_space', function(cm, vim, helpers) {
+  var curStart = makeCursor(0, 0);
+  cm.setCursor(curStart);
+  helpers.doKeys('d', 'w');
+  eq('word1 ', cm.getValue());
+  var register = helpers.getRegisterController().getRegister();
+  eq(' ', register.text);
+  is(!register.linewise);
+  eqPos(curStart, cm.getCursor());
+}, { value: ' word1 ' });
+testVim('dw_word', function(cm, vim, helpers) {
+  var curStart = makeCursor(0, 1);
+  cm.setCursor(curStart);
+  helpers.doKeys('d', 'w');
+  eq(' word2', cm.getValue());
+  var register = helpers.getRegisterController().getRegister();
+  eq('word1 ', register.text);
+  is(!register.linewise);
+  eqPos(curStart, cm.getCursor());
+}, { value: ' word1 word2' });
+testVim('dw_only_word', function(cm, vim, helpers) {
+  // Test that if there is only 1 word left, dw deletes till the end of the
+  // line.
+  cm.setCursor(0, 1);
+  helpers.doKeys('d', 'w');
+  eq(' ', cm.getValue());
+  var register = helpers.getRegisterController().getRegister();
+  eq('word1 ', register.text);
+  is(!register.linewise);
+  helpers.assertCursorAt(0, 0);
+}, { value: ' word1 ' });
+testVim('dw_eol', function(cm, vim, helpers) {
+  // Assert that dw does not delete the newline if last word to delete is at end
+  // of line.
+  cm.setCursor(0, 1);
+  helpers.doKeys('d', 'w');
+  eq(' \nword2', cm.getValue());
+  var register = helpers.getRegisterController().getRegister();
+  eq('word1', register.text);
+  is(!register.linewise);
+  helpers.assertCursorAt(0, 0);
+}, { value: ' word1\nword2' });
+testVim('dw_eol_with_multiple_newlines', function(cm, vim, helpers) {
+  // Assert that dw does not delete the newline if last word to delete is at end
+  // of line and it is followed by multiple newlines.
+  cm.setCursor(0, 1);
+  helpers.doKeys('d', 'w');
+  eq(' \n\nword2', cm.getValue());
+  var register = helpers.getRegisterController().getRegister();
+  eq('word1', register.text);
+  is(!register.linewise);
+  helpers.assertCursorAt(0, 0);
+}, { value: ' word1\n\nword2' });
+testVim('dw_empty_line_followed_by_whitespace', function(cm, vim, helpers) {
+  cm.setCursor(0, 0);
+  helpers.doKeys('d', 'w');
+  eq('  \nword', cm.getValue());
+}, { value: '\n  \nword' });
+testVim('dw_empty_line_followed_by_word', function(cm, vim, helpers) {
+  cm.setCursor(0, 0);
+  helpers.doKeys('d', 'w');
+  eq('word', cm.getValue());
+}, { value: '\nword' });
+testVim('dw_empty_line_followed_by_empty_line', function(cm, vim, helpers) {
+  cm.setCursor(0, 0);
+  helpers.doKeys('d', 'w');
+  eq('\n', cm.getValue());
+}, { value: '\n\n' });
+testVim('dw_whitespace_followed_by_whitespace', function(cm, vim, helpers) {
+  cm.setCursor(0, 0);
+  helpers.doKeys('d', 'w');
+  eq('\n   \n', cm.getValue());
+}, { value: '  \n   \n' });
+testVim('dw_whitespace_followed_by_empty_line', function(cm, vim, helpers) {
+  cm.setCursor(0, 0);
+  helpers.doKeys('d', 'w');
+  eq('\n\n', cm.getValue());
+}, { value: '  \n\n' });
+testVim('dw_word_whitespace_word', function(cm, vim, helpers) {
+  cm.setCursor(0, 0);
+  helpers.doKeys('d', 'w');
+  eq('\n   \nword2', cm.getValue());
+}, { value: 'word1\n   \nword2'})
+testVim('dw_end_of_document', function(cm, vim, helpers) {
+  cm.setCursor(1, 2);
+  helpers.doKeys('d', 'w');
+  eq('\nab', cm.getValue());
+}, { value: '\nabc' });
+testVim('dw_repeat', function(cm, vim, helpers) {
+  // Assert that dw does delete newline if it should go to the next line, and
+  // that repeat works properly.
+  cm.setCursor(0, 1);
+  helpers.doKeys('d', '2', 'w');
+  eq(' ', cm.getValue());
+  var register = helpers.getRegisterController().getRegister();
+  eq('word1\nword2', register.text);
+  is(!register.linewise);
+  helpers.assertCursorAt(0, 0);
+}, { value: ' word1\nword2' });
+testVim('de_word_start_and_empty_lines', function(cm, vim, helpers) {
+  cm.setCursor(0, 0);
+  helpers.doKeys('d', 'e');
+  eq('\n\n', cm.getValue());
+}, { value: 'word\n\n' });
+testVim('de_word_end_and_empty_lines', function(cm, vim, helpers) {
+  cm.setCursor(0, 3);
+  helpers.doKeys('d', 'e');
+  eq('wor', cm.getValue());
+}, { value: 'word\n\n\n' });
+testVim('de_whitespace_and_empty_lines', function(cm, vim, helpers) {
+  cm.setCursor(0, 0);
+  helpers.doKeys('d', 'e');
+  eq('', cm.getValue());
+}, { value: '   \n\n\n' });
+testVim('de_end_of_document', function(cm, vim, helpers) {
+  cm.setCursor(1, 2);
+  helpers.doKeys('d', 'e');
+  eq('\nab', cm.getValue());
+}, { value: '\nabc' });
+testVim('db_empty_lines', function(cm, vim, helpers) {
+  cm.setCursor(2, 0);
+  helpers.doKeys('d', 'b');
+  eq('\n\n', cm.getValue());
+}, { value: '\n\n\n' });
+testVim('db_word_start_and_empty_lines', function(cm, vim, helpers) {
+  cm.setCursor(2, 0);
+  helpers.doKeys('d', 'b');
+  eq('\nword', cm.getValue());
+}, { value: '\n\nword' });
+testVim('db_word_end_and_empty_lines', function(cm, vim, helpers) {
+  cm.setCursor(2, 3);
+  helpers.doKeys('d', 'b');
+  eq('\n\nd', cm.getValue());
+}, { value: '\n\nword' });
+testVim('db_whitespace_and_empty_lines', function(cm, vim, helpers) {
+  cm.setCursor(2, 0);
+  helpers.doKeys('d', 'b');
+  eq('', cm.getValue());
+}, { value: '\n   \n' });
+testVim('db_start_of_document', function(cm, vim, helpers) {
+  cm.setCursor(0, 0);
+  helpers.doKeys('d', 'b');
+  eq('abc\n', cm.getValue());
+}, { value: 'abc\n' });
+testVim('dge_empty_lines', function(cm, vim, helpers) {
+  cm.setCursor(1, 0);
+  helpers.doKeys('d', 'g', 'e');
+  // Note: In real VIM the result should be '', but it's not quite consistent,
+  // since 2 newlines are deleted. But in the similar case of word\n\n, only
+  // 1 newline is deleted. We'll diverge from VIM's behavior since it's much
+  // easier this way.
+  eq('\n', cm.getValue());
+}, { value: '\n\n' });
+testVim('dge_word_and_empty_lines', function(cm, vim, helpers) {
+  cm.setCursor(1, 0);
+  helpers.doKeys('d', 'g', 'e');
+  eq('wor\n', cm.getValue());
+}, { value: 'word\n\n'});
+testVim('dge_whitespace_and_empty_lines', function(cm, vim, helpers) {
+  cm.setCursor(2, 0);
+  helpers.doKeys('d', 'g', 'e');
+  eq('', cm.getValue());
+}, { value: '\n  \n' });
+testVim('dge_start_of_document', function(cm, vim, helpers) {
+  cm.setCursor(0, 0);
+  helpers.doKeys('d', 'g', 'e');
+  eq('bc\n', cm.getValue());
+}, { value: 'abc\n' });
+testVim('d_inclusive', function(cm, vim, helpers) {
+  // Assert that when inclusive is set, the character the cursor is on gets
+  // deleted too.
+  var curStart = makeCursor(0, 1);
+  cm.setCursor(curStart);
+  helpers.doKeys('d', 'e');
+  eq('  ', cm.getValue());
+  var register = helpers.getRegisterController().getRegister();
+  eq('word1', register.text);
+  is(!register.linewise);
+  eqPos(curStart, cm.getCursor());
+}, { value: ' word1 ' });
+testVim('d_reverse', function(cm, vim, helpers) {
+  // Test that deleting in reverse works.
+  cm.setCursor(1, 0);
+  helpers.doKeys('d', 'b');
+  eq(' word2 ', cm.getValue());
+  var register = helpers.getRegisterController().getRegister();
+  eq('word1\n', register.text);
+  is(!register.linewise);
+  helpers.assertCursorAt(0, 1);
+}, { value: ' word1\nword2 ' });
+testVim('dd', function(cm, vim, helpers) {
+  cm.setCursor(0, 3);
+  var expectedBuffer = cm.getRange({ line: 0, ch: 0 },
+    { line: 1, ch: 0 });
+  var expectedLineCount = cm.lineCount() - 1;
+  helpers.doKeys('d', 'd');
+  eq(expectedLineCount, cm.lineCount());
+  var register = helpers.getRegisterController().getRegister();
+  eq(expectedBuffer, register.text);
+  is(register.linewise);
+  helpers.assertCursorAt(0, lines[1].textStart);
+});
+testVim('dd_prefix_repeat', function(cm, vim, helpers) {
+  cm.setCursor(0, 3);
+  var expectedBuffer = cm.getRange({ line: 0, ch: 0 },
+    { line: 2, ch: 0 });
+  var expectedLineCount = cm.lineCount() - 2;
+  helpers.doKeys('2', 'd', 'd');
+  eq(expectedLineCount, cm.lineCount());
+  var register = helpers.getRegisterController().getRegister();
+  eq(expectedBuffer, register.text);
+  is(register.linewise);
+  helpers.assertCursorAt(0, lines[2].textStart);
+});
+testVim('dd_motion_repeat', function(cm, vim, helpers) {
+  cm.setCursor(0, 3);
+  var expectedBuffer = cm.getRange({ line: 0, ch: 0 },
+    { line: 2, ch: 0 });
+  var expectedLineCount = cm.lineCount() - 2;
+  helpers.doKeys('d', '2', 'd');
+  eq(expectedLineCount, cm.lineCount());
+  var register = helpers.getRegisterController().getRegister();
+  eq(expectedBuffer, register.text);
+  is(register.linewise);
+  helpers.assertCursorAt(0, lines[2].textStart);
+});
+testVim('dd_multiply_repeat', function(cm, vim, helpers) {
+  cm.setCursor(0, 3);
+  var expectedBuffer = cm.getRange({ line: 0, ch: 0 },
+    { line: 6, ch: 0 });
+  var expectedLineCount = cm.lineCount() - 6;
+  helpers.doKeys('2', 'd', '3', 'd');
+  eq(expectedLineCount, cm.lineCount());
+  var register = helpers.getRegisterController().getRegister();
+  eq(expectedBuffer, register.text);
+  is(register.linewise);
+  helpers.assertCursorAt(0, lines[6].textStart);
+});
+testVim('dd_lastline', function(cm, vim, helpers) {
+  cm.setCursor(cm.lineCount(), 0);
+  var expectedLineCount = cm.lineCount() - 1;
+  helpers.doKeys('d', 'd');
+  eq(expectedLineCount, cm.lineCount());
+  helpers.assertCursorAt(cm.lineCount() - 1, 0);
+});
+// Yank commands should behave the exact same as d commands, expect that nothing
+// gets deleted.
+testVim('yw_repeat', function(cm, vim, helpers) {
+  // Assert that yw does yank newline if it should go to the next line, and
+  // that repeat works properly.
+  var curStart = makeCursor(0, 1);
+  cm.setCursor(curStart);
+  helpers.doKeys('y', '2', 'w');
+  eq(' word1\nword2', cm.getValue());
+  var register = helpers.getRegisterController().getRegister();
+  eq('word1\nword2', register.text);
+  is(!register.linewise);
+  eqPos(curStart, cm.getCursor());
+}, { value: ' word1\nword2' });
+testVim('yy_multiply_repeat', function(cm, vim, helpers) {
+  var curStart = makeCursor(0, 3);
+  cm.setCursor(curStart);
+  var expectedBuffer = cm.getRange({ line: 0, ch: 0 },
+    { line: 6, ch: 0 });
+  var expectedLineCount = cm.lineCount();
+  helpers.doKeys('2', 'y', '3', 'y');
+  eq(expectedLineCount, cm.lineCount());
+  var register = helpers.getRegisterController().getRegister();
+  eq(expectedBuffer, register.text);
+  is(register.linewise);
+  eqPos(curStart, cm.getCursor());
+});
+// Change commands behave like d commands except that it also enters insert
+// mode. In addition, when the change is linewise, an additional newline is
+// inserted so that insert mode starts on that line.
+testVim('cw', function(cm, vim, helpers) {
+  cm.setCursor(0, 0);
+  helpers.doKeys('c', '2', 'w');
+  eq(' word3', cm.getValue());
+  helpers.assertCursorAt(0, 0);
+}, { value: 'word1 word2 word3'});
+testVim('cw_repeat', function(cm, vim, helpers) {
+  // Assert that cw does delete newline if it should go to the next line, and
+  // that repeat works properly.
+  var curStart = makeCursor(0, 1);
+  cm.setCursor(curStart);
+  helpers.doKeys('c', '2', 'w');
+  eq(' ', cm.getValue());
+  var register = helpers.getRegisterController().getRegister();
+  eq('word1\nword2', register.text);
+  is(!register.linewise);
+  eqPos(curStart, cm.getCursor());
+  eq('vim-insert', cm.getOption('keyMap'));
+}, { value: ' word1\nword2' });
+testVim('cc_multiply_repeat', function(cm, vim, helpers) {
+  cm.setCursor(0, 3);
+  var expectedBuffer = cm.getRange({ line: 0, ch: 0 },
+    { line: 6, ch: 0 });
+  var expectedLineCount = cm.lineCount() - 5;
+  helpers.doKeys('2', 'c', '3', 'c');
+  eq(expectedLineCount, cm.lineCount());
+  var register = helpers.getRegisterController().getRegister();
+  eq(expectedBuffer, register.text);
+  is(register.linewise);
+  eq('vim-insert', cm.getOption('keyMap'));
+});
+testVim('cc_append', function(cm, vim, helpers) {
+  var expectedLineCount = cm.lineCount();
+  cm.setCursor(cm.lastLine(), 0);
+  helpers.doKeys('c', 'c');
+  eq(expectedLineCount, cm.lineCount());
+});
+// Swapcase commands edit in place and do not modify registers.
+testVim('g~w_repeat', function(cm, vim, helpers) {
+  // Assert that dw does delete newline if it should go to the next line, and
+  // that repeat works properly.
+  var curStart = makeCursor(0, 1);
+  cm.setCursor(curStart);
+  helpers.doKeys('g', '~', '2', 'w');
+  eq(' WORD1\nWORD2', cm.getValue());
+  var register = helpers.getRegisterController().getRegister();
+  eq('', register.text);
+  is(!register.linewise);
+  eqPos(curStart, cm.getCursor());
+}, { value: ' word1\nword2' });
+testVim('g~g~', function(cm, vim, helpers) {
+  var curStart = makeCursor(0, 3);
+  cm.setCursor(curStart);
+  var expectedLineCount = cm.lineCount();
+  var expectedValue = cm.getValue().toUpperCase();
+  helpers.doKeys('2', 'g', '~', '3', 'g', '~');
+  eq(expectedValue, cm.getValue());
+  var register = helpers.getRegisterController().getRegister();
+  eq('', register.text);
+  is(!register.linewise);
+  eqPos(curStart, cm.getCursor());
+}, { value: ' word1\nword2\nword3\nword4\nword5\nword6' });
+testVim('>{motion}', function(cm, vim, helpers) {
+  cm.setCursor(1, 3);
+  var expectedLineCount = cm.lineCount();
+  var expectedValue = '   word1\n  word2\nword3 ';
+  helpers.doKeys('>', 'k');
+  eq(expectedValue, cm.getValue());
+  var register = helpers.getRegisterController().getRegister();
+  eq('', register.text);
+  is(!register.linewise);
+  helpers.assertCursorAt(0, 3);
+}, { value: ' word1\nword2\nword3 ', indentUnit: 2 });
+testVim('>>', function(cm, vim, helpers) {
+  cm.setCursor(0, 3);
+  var expectedLineCount = cm.lineCount();
+  var expectedValue = '   word1\n  word2\nword3 ';
+  helpers.doKeys('2', '>', '>');
+  eq(expectedValue, cm.getValue());
+  var register = helpers.getRegisterController().getRegister();
+  eq('', register.text);
+  is(!register.linewise);
+  helpers.assertCursorAt(0, 3);
+}, { value: ' word1\nword2\nword3 ', indentUnit: 2 });
+testVim('<{motion}', function(cm, vim, helpers) {
+  cm.setCursor(1, 3);
+  var expectedLineCount = cm.lineCount();
+  var expectedValue = ' word1\nword2\nword3 ';
+  helpers.doKeys('<', 'k');
+  eq(expectedValue, cm.getValue());
+  var register = helpers.getRegisterController().getRegister();
+  eq('', register.text);
+  is(!register.linewise);
+  helpers.assertCursorAt(0, 1);
+}, { value: '   word1\n  word2\nword3 ', indentUnit: 2 });
+testVim('<<', function(cm, vim, helpers) {
+  cm.setCursor(0, 3);
+  var expectedLineCount = cm.lineCount();
+  var expectedValue = ' word1\nword2\nword3 ';
+  helpers.doKeys('2', '<', '<');
+  eq(expectedValue, cm.getValue());
+  var register = helpers.getRegisterController().getRegister();
+  eq('', register.text);
+  is(!register.linewise);
+  helpers.assertCursorAt(0, 1);
+}, { value: '   word1\n  word2\nword3 ', indentUnit: 2 });
+
+// Edit tests
+function testEdit(name, before, pos, edit, after) {
+  return testVim(name, function(cm, vim, helpers) {
+             cm.setCursor(0, before.search(pos));
+             helpers.doKeys.apply(this, edit.split(''));
+             eq(after, cm.getValue());
+           }, {value: before});
+}
+
+// These Delete tests effectively cover word-wise Change, Visual & Yank.
+// Tabs are used as differentiated whitespace to catch edge cases.
+// Normal word:
+testEdit('diw_mid_spc', 'foo \tbAr\t baz', /A/, 'diw', 'foo \t\t baz');
+testEdit('daw_mid_spc', 'foo \tbAr\t baz', /A/, 'daw', 'foo \tbaz');
+testEdit('diw_mid_punct', 'foo \tbAr.\t baz', /A/, 'diw', 'foo \t.\t baz');
+testEdit('daw_mid_punct', 'foo \tbAr.\t baz', /A/, 'daw', 'foo.\t baz');
+testEdit('diw_mid_punct2', 'foo \t,bAr.\t baz', /A/, 'diw', 'foo \t,.\t baz');
+testEdit('daw_mid_punct2', 'foo \t,bAr.\t baz', /A/, 'daw', 'foo \t,.\t baz');
+testEdit('diw_start_spc', 'bAr \tbaz', /A/, 'diw', ' \tbaz');
+testEdit('daw_start_spc', 'bAr \tbaz', /A/, 'daw', 'baz');
+testEdit('diw_start_punct', 'bAr. \tbaz', /A/, 'diw', '. \tbaz');
+testEdit('daw_start_punct', 'bAr. \tbaz', /A/, 'daw', '. \tbaz');
+testEdit('diw_end_spc', 'foo \tbAr', /A/, 'diw', 'foo \t');
+testEdit('daw_end_spc', 'foo \tbAr', /A/, 'daw', 'foo');
+testEdit('diw_end_punct', 'foo \tbAr.', /A/, 'diw', 'foo \t.');
+testEdit('daw_end_punct', 'foo \tbAr.', /A/, 'daw', 'foo.');
+// Big word:
+testEdit('diW_mid_spc', 'foo \tbAr\t baz', /A/, 'diW', 'foo \t\t baz');
+testEdit('daW_mid_spc', 'foo \tbAr\t baz', /A/, 'daW', 'foo \tbaz');
+testEdit('diW_mid_punct', 'foo \tbAr.\t baz', /A/, 'diW', 'foo \t\t baz');
+testEdit('daW_mid_punct', 'foo \tbAr.\t baz', /A/, 'daW', 'foo \tbaz');
+testEdit('diW_mid_punct2', 'foo \t,bAr.\t baz', /A/, 'diW', 'foo \t\t baz');
+testEdit('daW_mid_punct2', 'foo \t,bAr.\t baz', /A/, 'daW', 'foo \tbaz');
+testEdit('diW_start_spc', 'bAr\t baz', /A/, 'diW', '\t baz');
+testEdit('daW_start_spc', 'bAr\t baz', /A/, 'daW', 'baz');
+testEdit('diW_start_punct', 'bAr.\t baz', /A/, 'diW', '\t baz');
+testEdit('daW_start_punct', 'bAr.\t baz', /A/, 'daW', 'baz');
+testEdit('diW_end_spc', 'foo \tbAr', /A/, 'diW', 'foo \t');
+testEdit('daW_end_spc', 'foo \tbAr', /A/, 'daW', 'foo');
+testEdit('diW_end_punct', 'foo \tbAr.', /A/, 'diW', 'foo \t');
+testEdit('daW_end_punct', 'foo \tbAr.', /A/, 'daW', 'foo');
+
+// Operator-motion tests
+testVim('D', function(cm, vim, helpers) {
+  cm.setCursor(0, 3);
+  helpers.doKeys('D');
+  eq(' wo\nword2\n word3', cm.getValue());
+  var register = helpers.getRegisterController().getRegister();
+  eq('rd1', register.text);
+  is(!register.linewise);
+  helpers.assertCursorAt(0, 2);
+}, { value: ' word1\nword2\n word3' });
+testVim('C', function(cm, vim, helpers) {
+  var curStart = makeCursor(0, 3);
+  cm.setCursor(curStart);
+  helpers.doKeys('C');
+  eq(' wo\nword2\n word3', cm.getValue());
+  var register = helpers.getRegisterController().getRegister();
+  eq('rd1', register.text);
+  is(!register.linewise);
+  eqPos(curStart, cm.getCursor());
+  eq('vim-insert', cm.getOption('keyMap'));
+}, { value: ' word1\nword2\n word3' });
+testVim('Y', function(cm, vim, helpers) {
+  var curStart = makeCursor(0, 3);
+  cm.setCursor(curStart);
+  helpers.doKeys('Y');
+  eq(' word1\nword2\n word3', cm.getValue());
+  var register = helpers.getRegisterController().getRegister();
+  eq('rd1', register.text);
+  is(!register.linewise);
+  helpers.assertCursorAt(0, 3);
+}, { value: ' word1\nword2\n word3' });
+testVim('~', function(cm, vim, helpers) {
+  helpers.doKeys('3', '~');
+  eq('ABCdefg', cm.getValue());
+  helpers.assertCursorAt(0, 3);
+}, { value: 'abcdefg' });
+
+// Action tests
+testVim('ctrl-a', function(cm, vim, helpers) {
+  cm.setCursor(0, 0);
+  helpers.doKeys('<C-a>');
+  eq('-9', cm.getValue());
+  helpers.assertCursorAt(0, 1);
+  helpers.doKeys('2','<C-a>');
+  eq('-7', cm.getValue());
+}, {value: '-10'});
+testVim('ctrl-x', function(cm, vim, helpers) {
+  cm.setCursor(0, 0);
+  helpers.doKeys('<C-x>');
+  eq('-1', cm.getValue());
+  helpers.assertCursorAt(0, 1);
+  helpers.doKeys('2','<C-x>');
+  eq('-3', cm.getValue());
+}, {value: '0'});
+testVim('<C-x>/<C-a> search forward', function(cm, vim, helpers) {
+  ['<C-x>', '<C-a>'].forEach(function(key) {
+    cm.setCursor(0, 0);
+    helpers.doKeys(key);
+    helpers.assertCursorAt(0, 5);
+    helpers.doKeys('l');
+    helpers.doKeys(key);
+    helpers.assertCursorAt(0, 10);
+    cm.setCursor(0, 11);
+    helpers.doKeys(key);
+    helpers.assertCursorAt(0, 11);
+  });
+}, {value: '__jmp1 jmp2 jmp'});
+testVim('a', function(cm, vim, helpers) {
+  cm.setCursor(0, 1);
+  helpers.doKeys('a');
+  helpers.assertCursorAt(0, 2);
+  eq('vim-insert', cm.getOption('keyMap'));
+});
+testVim('a_eol', function(cm, vim, helpers) {
+  cm.setCursor(0, lines[0].length - 1);
+  helpers.doKeys('a');
+  helpers.assertCursorAt(0, lines[0].length);
+  eq('vim-insert', cm.getOption('keyMap'));
+});
+testVim('i', function(cm, vim, helpers) {
+  cm.setCursor(0, 1);
+  helpers.doKeys('i');
+  helpers.assertCursorAt(0, 1);
+  eq('vim-insert', cm.getOption('keyMap'));
+});
+testVim('i_repeat', function(cm, vim, helpers) {
+  helpers.doKeys('3', 'i');
+  cm.replaceRange('test', cm.getCursor());
+  helpers.doInsertModeKeys('Esc');
+  eq('testtesttest', cm.getValue());
+  helpers.assertCursorAt(0, 11);
+}, { value: '' });
+testVim('i_repeat_delete', function(cm, vim, helpers) {
+  cm.setCursor(0, 4);
+  helpers.doKeys('2', 'i');
+  cm.replaceRange('z', cm.getCursor());
+  helpers.doInsertModeKeys('Backspace', 'Backspace', 'Esc');
+  eq('abe', cm.getValue());
+  helpers.assertCursorAt(0, 1);
+}, { value: 'abcde' });
+testVim('A', function(cm, vim, helpers) {
+  helpers.doKeys('A');
+  helpers.assertCursorAt(0, lines[0].length);
+  eq('vim-insert', cm.getOption('keyMap'));
+});
+testVim('I', function(cm, vim, helpers) {
+  cm.setCursor(0, 4);
+  helpers.doKeys('I');
+  helpers.assertCursorAt(0, lines[0].textStart);
+  eq('vim-insert', cm.getOption('keyMap'));
+});
+testVim('I_repeat', function(cm, vim, helpers) {
+  cm.setCursor(0, 1);
+  helpers.doKeys('3', 'I');
+  cm.replaceRange('test', cm.getCursor());
+  helpers.doInsertModeKeys('Esc');
+  eq('testtesttestblah', cm.getValue());
+  helpers.assertCursorAt(0, 11);
+}, { value: 'blah' });
+testVim('o', function(cm, vim, helpers) {
+  cm.setCursor(0, 4);
+  helpers.doKeys('o');
+  eq('word1\n\nword2', cm.getValue());
+  helpers.assertCursorAt(1, 0);
+  eq('vim-insert', cm.getOption('keyMap'));
+}, { value: 'word1\nword2' });
+testVim('o_repeat', function(cm, vim, helpers) {
+  cm.setCursor(0, 0);
+  helpers.doKeys('3', 'o');
+  cm.replaceRange('test', cm.getCursor());
+  helpers.doInsertModeKeys('Esc');
+  eq('\ntest\ntest\ntest', cm.getValue());
+  helpers.assertCursorAt(3, 3);
+}, { value: '' });
+testVim('O', function(cm, vim, helpers) {
+  cm.setCursor(0, 4);
+  helpers.doKeys('O');
+  eq('\nword1\nword2', cm.getValue());
+  helpers.assertCursorAt(0, 0);
+  eq('vim-insert', cm.getOption('keyMap'));
+}, { value: 'word1\nword2' });
+testVim('J', function(cm, vim, helpers) {
+  cm.setCursor(0, 4);
+  helpers.doKeys('J');
+  var expectedValue = 'word1  word2\nword3\n word4';
+  eq(expectedValue, cm.getValue());
+  helpers.assertCursorAt(0, expectedValue.indexOf('word2') - 1);
+}, { value: 'word1 \n    word2\nword3\n word4' });
+testVim('J_repeat', function(cm, vim, helpers) {
+  cm.setCursor(0, 4);
+  helpers.doKeys('3', 'J');
+  var expectedValue = 'word1  word2 word3\n word4';
+  eq(expectedValue, cm.getValue());
+  helpers.assertCursorAt(0, expectedValue.indexOf('word3') - 1);
+}, { value: 'word1 \n    word2\nword3\n word4' });
+testVim('p', function(cm, vim, helpers) {
+  cm.setCursor(0, 1);
+  helpers.getRegisterController().pushText('"', 'yank', 'abc\ndef', false);
+  helpers.doKeys('p');
+  eq('__abc\ndef_', cm.getValue());
+  helpers.assertCursorAt(1, 2);
+}, { value: '___' });
+testVim('p_register', function(cm, vim, helpers) {
+  cm.setCursor(0, 1);
+  helpers.getRegisterController().getRegister('a').set('abc\ndef', false);
+  helpers.doKeys('"', 'a', 'p');
+  eq('__abc\ndef_', cm.getValue());
+  helpers.assertCursorAt(1, 2);
+}, { value: '___' });
+testVim('p_wrong_register', function(cm, vim, helpers) {
+  cm.setCursor(0, 1);
+  helpers.getRegisterController().getRegister('a').set('abc\ndef', false);
+  helpers.doKeys('p');
+  eq('___', cm.getValue());
+  helpers.assertCursorAt(0, 1);
+}, { value: '___' });
+testVim('p_line', function(cm, vim, helpers) {
+  cm.setCursor(0, 1);
+  helpers.getRegisterController().pushText('"', 'yank', '  a\nd\n', true);
+  helpers.doKeys('2', 'p');
+  eq('___\n  a\nd\n  a\nd', cm.getValue());
+  helpers.assertCursorAt(1, 2);
+}, { value: '___' });
+testVim('P', function(cm, vim, helpers) {
+  cm.setCursor(0, 1);
+  helpers.getRegisterController().pushText('"', 'yank', 'abc\ndef', false);
+  helpers.doKeys('P');
+  eq('_abc\ndef__', cm.getValue());
+  helpers.assertCursorAt(1, 3);
+}, { value: '___' });
+testVim('P_line', function(cm, vim, helpers) {
+  cm.setCursor(0, 1);
+  helpers.getRegisterController().pushText('"', 'yank', '  a\nd\n', true);
+  helpers.doKeys('2', 'P');
+  eq('  a\nd\n  a\nd\n___', cm.getValue());
+  helpers.assertCursorAt(0, 2);
+}, { value: '___' });
+testVim('r', function(cm, vim, helpers) {
+  cm.setCursor(0, 1);
+  helpers.doKeys('3', 'r', 'u');
+  eq('wuuuet\nanother', cm.getValue(),'3r failed');
+  helpers.assertCursorAt(0, 3);
+  cm.setCursor(0, 4);
+  helpers.doKeys('v', 'j', 'h', 'r', '<Space>');
+  eq('wuuu  \n    her', cm.getValue(),'Replacing selection by space-characters failed');
+}, { value: 'wordet\nanother' });
+testVim('R', function(cm, vim, helpers) {
+  cm.setCursor(0, 1);
+  helpers.doKeys('R');
+  helpers.assertCursorAt(0, 1);
+  eq('vim-replace', cm.getOption('keyMap'));
+  is(cm.state.overwrite, 'Setting overwrite state failed');
+});
+testVim('mark', function(cm, vim, helpers) {
+  cm.setCursor(2, 2);
+  helpers.doKeys('m', 't');
+  cm.setCursor(0, 0);
+  helpers.doKeys('\'', 't');
+  helpers.assertCursorAt(2, 2);
+  cm.setCursor(0, 0);
+  helpers.doKeys('`', 't');
+  helpers.assertCursorAt(2, 2);
+});
+testVim('jumpToMark_next', function(cm, vim, helpers) {
+  cm.setCursor(2, 2);
+  helpers.doKeys('m', 't');
+  cm.setCursor(0, 0);
+  helpers.doKeys(']', '`');
+  helpers.assertCursorAt(2, 2);
+  cm.setCursor(0, 0);
+  helpers.doKeys(']', '\'');
+  helpers.assertCursorAt(2, 0);
+});
+testVim('jumpToMark_next_repeat', function(cm, vim, helpers) {
+  cm.setCursor(2, 2);
+  helpers.doKeys('m', 'a');
+  cm.setCursor(3, 2);
+  helpers.doKeys('m', 'b');
+  cm.setCursor(4, 2);
+  helpers.doKeys('m', 'c');
+  cm.setCursor(0, 0);
+  helpers.doKeys('2', ']', '`');
+  helpers.assertCursorAt(3, 2);
+  cm.setCursor(0, 0);
+  helpers.doKeys('2', ']', '\'');
+  helpers.assertCursorAt(3, 1);
+});
+testVim('jumpToMark_next_sameline', function(cm, vim, helpers) {
+  cm.setCursor(2, 0);
+  helpers.doKeys('m', 'a');
+  cm.setCursor(2, 4);
+  helpers.doKeys('m', 'b');
+  cm.setCursor(2, 2);
+  helpers.doKeys(']', '`');
+  helpers.assertCursorAt(2, 4);
+});
+testVim('jumpToMark_next_onlyprev', function(cm, vim, helpers) {
+  cm.setCursor(2, 0);
+  helpers.doKeys('m', 'a');
+  cm.setCursor(4, 0);
+  helpers.doKeys(']', '`');
+  helpers.assertCursorAt(4, 0);
+});
+testVim('jumpToMark_next_nomark', function(cm, vim, helpers) {
+  cm.setCursor(2, 2);
+  helpers.doKeys(']', '`');
+  helpers.assertCursorAt(2, 2);
+  helpers.doKeys(']', '\'');
+  helpers.assertCursorAt(2, 0);
+});
+testVim('jumpToMark_next_linewise_over', function(cm, vim, helpers) {
+  cm.setCursor(2, 2);
+  helpers.doKeys('m', 'a');
+  cm.setCursor(3, 4);
+  helpers.doKeys('m', 'b');
+  cm.setCursor(2, 1);
+  helpers.doKeys(']', '\'');
+  helpers.assertCursorAt(3, 1);
+});
+testVim('jumpToMark_next_action', function(cm, vim, helpers) {
+  cm.setCursor(2, 2);
+  helpers.doKeys('m', 't');
+  cm.setCursor(0, 0);
+  helpers.doKeys('d', ']', '`');
+  helpers.assertCursorAt(0, 0);
+  var actual = cm.getLine(0);
+  var expected = 'pop pop 0 1 2 3 4';
+  eq(actual, expected, "Deleting while jumping to the next mark failed.");
+});
+testVim('jumpToMark_next_line_action', function(cm, vim, helpers) {
+  cm.setCursor(2, 2);
+  helpers.doKeys('m', 't');
+  cm.setCursor(0, 0);
+  helpers.doKeys('d', ']', '\'');
+  helpers.assertCursorAt(0, 1);
+  var actual = cm.getLine(0);
+  var expected = ' (a) [b] {c} '
+  eq(actual, expected, "Deleting while jumping to the next mark line failed.");
+});
+testVim('jumpToMark_prev', function(cm, vim, helpers) {
+  cm.setCursor(2, 2);
+  helpers.doKeys('m', 't');
+  cm.setCursor(4, 0);
+  helpers.doKeys('[', '`');
+  helpers.assertCursorAt(2, 2);
+  cm.setCursor(4, 0);
+  helpers.doKeys('[', '\'');
+  helpers.assertCursorAt(2, 0);
+});
+testVim('jumpToMark_prev_repeat', function(cm, vim, helpers) {
+  cm.setCursor(2, 2);
+  helpers.doKeys('m', 'a');
+  cm.setCursor(3, 2);
+  helpers.doKeys('m', 'b');
+  cm.setCursor(4, 2);
+  helpers.doKeys('m', 'c');
+  cm.setCursor(5, 0);
+  helpers.doKeys('2', '[', '`');
+  helpers.assertCursorAt(3, 2);
+  cm.setCursor(5, 0);
+  helpers.doKeys('2', '[', '\'');
+  helpers.assertCursorAt(3, 1);
+});
+testVim('jumpToMark_prev_sameline', function(cm, vim, helpers) {
+  cm.setCursor(2, 0);
+  helpers.doKeys('m', 'a');
+  cm.setCursor(2, 4);
+  helpers.doKeys('m', 'b');
+  cm.setCursor(2, 2);
+  helpers.doKeys('[', '`');
+  helpers.assertCursorAt(2, 0);
+});
+testVim('jumpToMark_prev_onlynext', function(cm, vim, helpers) {
+  cm.setCursor(4, 4);
+  helpers.doKeys('m', 'a');
+  cm.setCursor(2, 0);
+  helpers.doKeys('[', '`');
+  helpers.assertCursorAt(2, 0);
+});
+testVim('jumpToMark_prev_nomark', function(cm, vim, helpers) {
+  cm.setCursor(2, 2);
+  helpers.doKeys('[', '`');
+  helpers.assertCursorAt(2, 2);
+  helpers.doKeys('[', '\'');
+  helpers.assertCursorAt(2, 0);
+});
+testVim('jumpToMark_prev_linewise_over', function(cm, vim, helpers) {
+  cm.setCursor(2, 2);
+  helpers.doKeys('m', 'a');
+  cm.setCursor(3, 4);
+  helpers.doKeys('m', 'b');
+  cm.setCursor(3, 6);
+  helpers.doKeys('[', '\'');
+  helpers.assertCursorAt(2, 0);
+});
+testVim('delmark_single', function(cm, vim, helpers) {
+  cm.setCursor(1, 2);
+  helpers.doKeys('m', 't');
+  helpers.doEx('delmarks t');
+  cm.setCursor(0, 0);
+  helpers.doKeys('`', 't');
+  helpers.assertCursorAt(0, 0);
+});
+testVim('delmark_range', function(cm, vim, helpers) {
+  cm.setCursor(1, 2);
+  helpers.doKeys('m', 'a');
+  cm.setCursor(2, 2);
+  helpers.doKeys('m', 'b');
+  cm.setCursor(3, 2);
+  helpers.doKeys('m', 'c');
+  cm.setCursor(4, 2);
+  helpers.doKeys('m', 'd');
+  cm.setCursor(5, 2);
+  helpers.doKeys('m', 'e');
+  helpers.doEx('delmarks b-d');
+  cm.setCursor(0, 0);
+  helpers.doKeys('`', 'a');
+  helpers.assertCursorAt(1, 2);
+  helpers.doKeys('`', 'b');
+  helpers.assertCursorAt(1, 2);
+  helpers.doKeys('`', 'c');
+  helpers.assertCursorAt(1, 2);
+  helpers.doKeys('`', 'd');
+  helpers.assertCursorAt(1, 2);
+  helpers.doKeys('`', 'e');
+  helpers.assertCursorAt(5, 2);
+});
+testVim('delmark_multi', function(cm, vim, helpers) {
+  cm.setCursor(1, 2);
+  helpers.doKeys('m', 'a');
+  cm.setCursor(2, 2);
+  helpers.doKeys('m', 'b');
+  cm.setCursor(3, 2);
+  helpers.doKeys('m', 'c');
+  cm.setCursor(4, 2);
+  helpers.doKeys('m', 'd');
+  cm.setCursor(5, 2);
+  helpers.doKeys('m', 'e');
+  helpers.doEx('delmarks bcd');
+  cm.setCursor(0, 0);
+  helpers.doKeys('`', 'a');
+  helpers.assertCursorAt(1, 2);
+  helpers.doKeys('`', 'b');
+  helpers.assertCursorAt(1, 2);
+  helpers.doKeys('`', 'c');
+  helpers.assertCursorAt(1, 2);
+  helpers.doKeys('`', 'd');
+  helpers.assertCursorAt(1, 2);
+  helpers.doKeys('`', 'e');
+  helpers.assertCursorAt(5, 2);
+});
+testVim('delmark_multi_space', function(cm, vim, helpers) {
+  cm.setCursor(1, 2);
+  helpers.doKeys('m', 'a');
+  cm.setCursor(2, 2);
+  helpers.doKeys('m', 'b');
+  cm.setCursor(3, 2);
+  helpers.doKeys('m', 'c');
+  cm.setCursor(4, 2);
+  helpers.doKeys('m', 'd');
+  cm.setCursor(5, 2);
+  helpers.doKeys('m', 'e');
+  helpers.doEx('delmarks b c d');
+  cm.setCursor(0, 0);
+  helpers.doKeys('`', 'a');
+  helpers.assertCursorAt(1, 2);
+  helpers.doKeys('`', 'b');
+  helpers.assertCursorAt(1, 2);
+  helpers.doKeys('`', 'c');
+  helpers.assertCursorAt(1, 2);
+  helpers.doKeys('`', 'd');
+  helpers.assertCursorAt(1, 2);
+  helpers.doKeys('`', 'e');
+  helpers.assertCursorAt(5, 2);
+});
+testVim('delmark_all', function(cm, vim, helpers) {
+  cm.setCursor(1, 2);
+  helpers.doKeys('m', 'a');
+  cm.setCursor(2, 2);
+  helpers.doKeys('m', 'b');
+  cm.setCursor(3, 2);
+  helpers.doKeys('m', 'c');
+  cm.setCursor(4, 2);
+  helpers.doKeys('m', 'd');
+  cm.setCursor(5, 2);
+  helpers.doKeys('m', 'e');
+  helpers.doEx('delmarks a b-de');
+  cm.setCursor(0, 0);
+  helpers.doKeys('`', 'a');
+  helpers.assertCursorAt(0, 0);
+  helpers.doKeys('`', 'b');
+  helpers.assertCursorAt(0, 0);
+  helpers.doKeys('`', 'c');
+  helpers.assertCursorAt(0, 0);
+  helpers.doKeys('`', 'd');
+  helpers.assertCursorAt(0, 0);
+  helpers.doKeys('`', 'e');
+  helpers.assertCursorAt(0, 0);
+});
+testVim('visual', function(cm, vim, helpers) {
+  helpers.doKeys('l', 'v', 'l', 'l');
+  helpers.assertCursorAt(0, 3);
+  eqPos(makeCursor(0, 1), cm.getCursor('anchor'));
+  helpers.doKeys('d');
+  eq('15', cm.getValue());
+}, { value: '12345' });
+testVim('visual_line', function(cm, vim, helpers) {
+  helpers.doKeys('l', 'V', 'l', 'j', 'j', 'd');
+  eq(' 4\n 5', cm.getValue());
+}, { value: ' 1\n 2\n 3\n 4\n 5' });
+testVim('visual_marks', function(cm, vim, helpers) {
+  helpers.doKeys('l', 'v', 'l', 'l', 'v');
+  // Test visual mode marks
+  cm.setCursor(0, 0);
+  helpers.doKeys('\'', '<');
+  helpers.assertCursorAt(0, 1);
+  helpers.doKeys('\'', '>');
+  helpers.assertCursorAt(0, 3);
+});
+testVim('visual_join', function(cm, vim, helpers) {
+  helpers.doKeys('l', 'V', 'l', 'j', 'j', 'J');
+  eq(' 1 2 3\n 4\n 5', cm.getValue());
+}, { value: ' 1\n 2\n 3\n 4\n 5' });
+testVim('visual_blank', function(cm, vim, helpers) {
+  helpers.doKeys('v', 'k');
+  eq(vim.visualMode, true);
+}, { value: '\n' });
+testVim('/ and n/N', function(cm, vim, helpers) {
+  cm.openDialog = helpers.fakeOpenDialog('match');
+  helpers.doKeys('/');
+  helpers.assertCursorAt(0, 11);
+  helpers.doKeys('n');
+  helpers.assertCursorAt(1, 6);
+  helpers.doKeys('N');
+  helpers.assertCursorAt(0, 11);
+
+  cm.setCursor(0, 0);
+  helpers.doKeys('2', '/');
+  helpers.assertCursorAt(1, 6);
+}, { value: 'match nope match \n nope Match' });
+testVim('/_case', function(cm, vim, helpers) {
+  cm.openDialog = helpers.fakeOpenDialog('Match');
+  helpers.doKeys('/');
+  helpers.assertCursorAt(1, 6);
+}, { value: 'match nope match \n nope Match' });
+testVim('/_nongreedy', function(cm, vim, helpers) {
+  cm.openDialog = helpers.fakeOpenDialog('aa');
+  helpers.doKeys('/');
+  helpers.assertCursorAt(0, 4);
+  helpers.doKeys('n');
+  helpers.assertCursorAt(1, 3);
+  helpers.doKeys('n');
+  helpers.assertCursorAt(0, 0);
+}, { value: 'aaa aa \n a aa'});
+testVim('?_nongreedy', function(cm, vim, helpers) {
+  cm.openDialog = helpers.fakeOpenDialog('aa');
+  helpers.doKeys('?');
+  helpers.assertCursorAt(1, 3);
+  helpers.doKeys('n');
+  helpers.assertCursorAt(0, 4);
+  helpers.doKeys('n');
+  helpers.assertCursorAt(0, 0);
+}, { value: 'aaa aa \n a aa'});
+testVim('/_greedy', function(cm, vim, helpers) {
+  cm.openDialog = helpers.fakeOpenDialog('a+');
+  helpers.doKeys('/');
+  helpers.assertCursorAt(0, 4);
+  helpers.doKeys('n');
+  helpers.assertCursorAt(1, 1);
+  helpers.doKeys('n');
+  helpers.assertCursorAt(1, 3);
+  helpers.doKeys('n');
+  helpers.assertCursorAt(0, 0);
+}, { value: 'aaa aa \n a aa'});
+testVim('?_greedy', function(cm, vim, helpers) {
+  cm.openDialog = helpers.fakeOpenDialog('a+');
+  helpers.doKeys('?');
+  helpers.assertCursorAt(1, 3);
+  helpers.doKeys('n');
+  helpers.assertCursorAt(1, 1);
+  helpers.doKeys('n');
+  helpers.assertCursorAt(0, 4);
+  helpers.doKeys('n');
+  helpers.assertCursorAt(0, 0);
+}, { value: 'aaa aa \n a aa'});
+testVim('/_greedy_0_or_more', function(cm, vim, helpers) {
+  cm.openDialog = helpers.fakeOpenDialog('a*');
+  helpers.doKeys('/');
+  helpers.assertCursorAt(0, 3);
+  helpers.doKeys('n');
+  helpers.assertCursorAt(0, 4);
+  helpers.doKeys('n');
+  helpers.assertCursorAt(0, 5);
+  helpers.doKeys('n');
+  helpers.assertCursorAt(1, 0);
+  helpers.doKeys('n');
+  helpers.assertCursorAt(1, 1);
+  helpers.doKeys('n');
+  helpers.assertCursorAt(0, 0);
+}, { value: 'aaa  aa\n aa'});
+testVim('?_greedy_0_or_more', function(cm, vim, helpers) {
+  cm.openDialog = helpers.fakeOpenDialog('a*');
+  helpers.doKeys('?');
+  helpers.assertCursorAt(1, 1);
+  helpers.doKeys('n');
+  helpers.assertCursorAt(1, 0);
+  helpers.doKeys('n');
+  helpers.assertCursorAt(0, 5);
+  helpers.doKeys('n');
+  helpers.assertCursorAt(0, 4);
+  helpers.doKeys('n');
+  helpers.assertCursorAt(0, 3);
+  helpers.doKeys('n');
+  helpers.assertCursorAt(0, 0);
+}, { value: 'aaa  aa\n aa'});
+testVim('? and n/N', function(cm, vim, helpers) {
+  cm.openDialog = helpers.fakeOpenDialog('match');
+  helpers.doKeys('?');
+  helpers.assertCursorAt(1, 6);
+  helpers.doKeys('n');
+  helpers.assertCursorAt(0, 11);
+  helpers.doKeys('N');
+  helpers.assertCursorAt(1, 6);
+
+  cm.setCursor(0, 0);
+  helpers.doKeys('2', '?');
+  helpers.assertCursorAt(0, 11);
+}, { value: 'match nope match \n nope Match' });
+testVim('*', function(cm, vim, helpers) {
+  cm.setCursor(0, 9);
+  helpers.doKeys('*');
+  helpers.assertCursorAt(0, 22);
+
+  cm.setCursor(0, 9);
+  helpers.doKeys('2', '*');
+  helpers.assertCursorAt(1, 8);
+}, { value: 'nomatch match nomatch match \nnomatch Match' });
+testVim('*_no_word', function(cm, vim, helpers) {
+  cm.setCursor(0, 0);
+  helpers.doKeys('*');
+  helpers.assertCursorAt(0, 0);
+}, { value: ' \n match \n' });
+testVim('*_symbol', function(cm, vim, helpers) {
+  cm.setCursor(0, 0);
+  helpers.doKeys('*');
+  helpers.assertCursorAt(1, 0);
+}, { value: ' /}\n/} match \n' });
+testVim('#', function(cm, vim, helpers) {
+  cm.setCursor(0, 9);
+  helpers.doKeys('#');
+  helpers.assertCursorAt(1, 8);
+
+  cm.setCursor(0, 9);
+  helpers.doKeys('2', '#');
+  helpers.assertCursorAt(0, 22);
+}, { value: 'nomatch match nomatch match \nnomatch Match' });
+testVim('*_seek', function(cm, vim, helpers) {
+  // Should skip over space and symbols.
+  cm.setCursor(0, 3);
+  helpers.doKeys('*');
+  helpers.assertCursorAt(0, 22);
+}, { value: '    :=  match nomatch match \nnomatch Match' });
+testVim('#', function(cm, vim, helpers) {
+  // Should skip over space and symbols.
+  cm.setCursor(0, 3);
+  helpers.doKeys('#');
+  helpers.assertCursorAt(1, 8);
+}, { value: '    :=  match nomatch match \nnomatch Match' });
+testVim('.', function(cm, vim, helpers) {
+  cm.setCursor(0, 0);
+  helpers.doKeys('2', 'd', 'w');
+  helpers.doKeys('.');
+  eq('5 6', cm.getValue());
+}, { value: '1 2 3 4 5 6'});
+testVim('._repeat', function(cm, vim, helpers) {
+  cm.setCursor(0, 0);
+  helpers.doKeys('2', 'd', 'w');
+  helpers.doKeys('3', '.');
+  eq('6', cm.getValue());
+}, { value: '1 2 3 4 5 6'});
+testVim('._insert', function(cm, vim, helpers) {
+  helpers.doKeys('i');
+  cm.replaceRange('test', cm.getCursor());
+  helpers.doInsertModeKeys('Esc');
+  helpers.doKeys('.');
+  eq('testestt', cm.getValue());
+  helpers.assertCursorAt(0, 6);
+}, { value: ''});
+testVim('._insert_repeat', function(cm, vim, helpers) {
+  helpers.doKeys('i');
+  cm.replaceRange('test', cm.getCursor());
+  cm.setCursor(0, 4);
+  helpers.doInsertModeKeys('Esc');
+  helpers.doKeys('2', '.');
+  eq('testesttestt', cm.getValue());
+  helpers.assertCursorAt(0, 10);
+}, { value: ''});
+testVim('._repeat_insert', function(cm, vim, helpers) {
+  helpers.doKeys('3', 'i');
+  cm.replaceRange('te', cm.getCursor());
+  cm.setCursor(0, 2);
+  helpers.doInsertModeKeys('Esc');
+  helpers.doKeys('.');
+  eq('tetettetetee', cm.getValue());
+  helpers.assertCursorAt(0, 10);
+}, { value: ''});
+testVim('._insert_o', function(cm, vim, helpers) {
+  helpers.doKeys('o');
+  cm.replaceRange('z', cm.getCursor());
+  cm.setCursor(1, 1);
+  helpers.doInsertModeKeys('Esc');
+  helpers.doKeys('.');
+  eq('\nz\nz', cm.getValue());
+  helpers.assertCursorAt(2, 0);
+}, { value: ''});
+testVim('._insert_o_repeat', function(cm, vim, helpers) {
+  helpers.doKeys('o');
+  cm.replaceRange('z', cm.getCursor());
+  helpers.doInsertModeKeys('Esc');
+  cm.setCursor(1, 0);
+  helpers.doKeys('2', '.');
+  eq('\nz\nz\nz', cm.getValue());
+  helpers.assertCursorAt(3, 0);
+}, { value: ''});
+testVim('._insert_o_indent', function(cm, vim, helpers) {
+  helpers.doKeys('o');
+  cm.replaceRange('z', cm.getCursor());
+  helpers.doInsertModeKeys('Esc');
+  cm.setCursor(1, 2);
+  helpers.doKeys('.');
+  eq('{\n  z\n  z', cm.getValue());
+  helpers.assertCursorAt(2, 2);
+}, { value: '{'});
+testVim('._insert_cw', function(cm, vim, helpers) {
+  helpers.doKeys('c', 'w');
+  cm.replaceRange('test', cm.getCursor());
+  helpers.doInsertModeKeys('Esc');
+  cm.setCursor(0, 3);
+  helpers.doKeys('2', 'l');
+  helpers.doKeys('.');
+  eq('test test word3', cm.getValue());
+  helpers.assertCursorAt(0, 8);
+}, { value: 'word1 word2 word3' });
+testVim('._insert_cw_repeat', function(cm, vim, helpers) {
+  // For some reason, repeat cw in desktop VIM will does not repeat insert mode
+  // changes. Will conform to that behavior.
+  helpers.doKeys('c', 'w');
+  cm.replaceRange('test', cm.getCursor());
+  helpers.doInsertModeKeys('Esc');
+  cm.setCursor(0, 4);
+  helpers.doKeys('l');
+  helpers.doKeys('2', '.');
+  eq('test test', cm.getValue());
+  helpers.assertCursorAt(0, 8);
+}, { value: 'word1 word2 word3' });
+testVim('._delete', function(cm, vim, helpers) {
+  cm.setCursor(0, 5);
+  helpers.doKeys('i');
+  helpers.doInsertModeKeys('Backspace', 'Esc');
+  helpers.doKeys('.');
+  eq('zace', cm.getValue());
+  helpers.assertCursorAt(0, 1);
+}, { value: 'zabcde'});
+testVim('._delete_repeat', function(cm, vim, helpers) {
+  cm.setCursor(0, 6);
+  helpers.doKeys('i');
+  helpers.doInsertModeKeys('Backspace', 'Esc');
+  helpers.doKeys('2', '.');
+  eq('zzce', cm.getValue());
+  helpers.assertCursorAt(0, 1);
+}, { value: 'zzabcde'});
+testVim('f;', function(cm, vim, helpers) {
+  cm.setCursor(0, 0);
+  helpers.doKeys('f', 'x');
+  helpers.doKeys(';');
+  helpers.doKeys('2', ';');
+  eq(9, cm.getCursor().ch);
+}, { value: '01x3xx678x'});
+testVim('F;', function(cm, vim, helpers) {
+  cm.setCursor(0, 8);
+  helpers.doKeys('F', 'x');
+  helpers.doKeys(';');
+  helpers.doKeys('2', ';');
+  eq(2, cm.getCursor().ch);
+}, { value: '01x3xx6x8x'});
+testVim('t;', function(cm, vim, helpers) {
+  cm.setCursor(0, 0);
+  helpers.doKeys('t', 'x');
+  helpers.doKeys(';');
+  helpers.doKeys('2', ';');
+  eq(8, cm.getCursor().ch);
+}, { value: '01x3xx678x'});
+testVim('T;', function(cm, vim, helpers) {
+  cm.setCursor(0, 9);
+  helpers.doKeys('T', 'x');
+  helpers.doKeys(';');
+  helpers.doKeys('2', ';');
+  eq(2, cm.getCursor().ch);
+}, { value: '0xx3xx678x'});
+testVim('f,', function(cm, vim, helpers) {
+  cm.setCursor(0, 6);
+  helpers.doKeys('f', 'x');
+  helpers.doKeys(',');
+  helpers.doKeys('2', ',');
+  eq(2, cm.getCursor().ch);
+}, { value: '01x3xx678x'});
+testVim('F,', function(cm, vim, helpers) {
+  cm.setCursor(0, 3);
+  helpers.doKeys('F', 'x');
+  helpers.doKeys(',');
+  helpers.doKeys('2', ',');
+  eq(9, cm.getCursor().ch);
+}, { value: '01x3xx678x'});
+testVim('t,', function(cm, vim, helpers) {
+  cm.setCursor(0, 6);
+  helpers.doKeys('t', 'x');
+  helpers.doKeys(',');
+  helpers.doKeys('2', ',');
+  eq(3, cm.getCursor().ch);
+}, { value: '01x3xx678x'});
+testVim('T,', function(cm, vim, helpers) {
+  cm.setCursor(0, 4);
+  helpers.doKeys('T', 'x');
+  helpers.doKeys(',');
+  helpers.doKeys('2', ',');
+  eq(8, cm.getCursor().ch);
+}, { value: '01x3xx67xx'});
+testVim('fd,;', function(cm, vim, helpers) {
+  cm.setCursor(0, 0);
+  helpers.doKeys('f', '4');
+  cm.setCursor(0, 0);
+  helpers.doKeys('d', ';');
+  eq('56789', cm.getValue());
+  helpers.doKeys('u');
+  cm.setCursor(0, 9);
+  helpers.doKeys('d', ',');
+  eq('01239', cm.getValue());
+}, { value: '0123456789'});
+testVim('Fd,;', function(cm, vim, helpers) {
+  cm.setCursor(0, 9);
+  helpers.doKeys('F', '4');
+  cm.setCursor(0, 9);
+  helpers.doKeys('d', ';');
+  eq('01239', cm.getValue());
+  helpers.doKeys('u');
+  cm.setCursor(0, 0);
+  helpers.doKeys('d', ',');
+  eq('56789', cm.getValue());
+}, { value: '0123456789'});
+testVim('td,;', function(cm, vim, helpers) {
+  cm.setCursor(0, 0);
+  helpers.doKeys('t', '4');
+  cm.setCursor(0, 0);
+  helpers.doKeys('d', ';');
+  eq('456789', cm.getValue());
+  helpers.doKeys('u');
+  cm.setCursor(0, 9);
+  helpers.doKeys('d', ',');
+  eq('012349', cm.getValue());
+}, { value: '0123456789'});
+testVim('Td,;', function(cm, vim, helpers) {
+  cm.setCursor(0, 9);
+  helpers.doKeys('T', '4');
+  cm.setCursor(0, 9);
+  helpers.doKeys('d', ';');
+  eq('012349', cm.getValue());
+  helpers.doKeys('u');
+  cm.setCursor(0, 0);
+  helpers.doKeys('d', ',');
+  eq('456789', cm.getValue());
+}, { value: '0123456789'});
+testVim('fc,;', function(cm, vim, helpers) {
+  cm.setCursor(0, 0);
+  helpers.doKeys('f', '4');
+  cm.setCursor(0, 0);
+  helpers.doKeys('c', ';', 'Esc');
+  eq('56789', cm.getValue());
+  helpers.doKeys('u');
+  cm.setCursor(0, 9);
+  helpers.doKeys('c', ',');
+  eq('01239', cm.getValue());
+}, { value: '0123456789'});
+testVim('Fc,;', function(cm, vim, helpers) {
+  cm.setCursor(0, 9);
+  helpers.doKeys('F', '4');
+  cm.setCursor(0, 9);
+  helpers.doKeys('c', ';', 'Esc');
+  eq('01239', cm.getValue());
+  helpers.doKeys('u');
+  cm.setCursor(0, 0);
+  helpers.doKeys('c', ',');
+  eq('56789', cm.getValue());
+}, { value: '0123456789'});
+testVim('tc,;', function(cm, vim, helpers) {
+  cm.setCursor(0, 0);
+  helpers.doKeys('t', '4');
+  cm.setCursor(0, 0);
+  helpers.doKeys('c', ';', 'Esc');
+  eq('456789', cm.getValue());
+  helpers.doKeys('u');
+  cm.setCursor(0, 9);
+  helpers.doKeys('c', ',');
+  eq('012349', cm.getValue());
+}, { value: '0123456789'});
+testVim('Tc,;', function(cm, vim, helpers) {
+  cm.setCursor(0, 9);
+  helpers.doKeys('T', '4');
+  cm.setCursor(0, 9);
+  helpers.doKeys('c', ';', 'Esc');
+  eq('012349', cm.getValue());
+  helpers.doKeys('u');
+  cm.setCursor(0, 0);
+  helpers.doKeys('c', ',');
+  eq('456789', cm.getValue());
+}, { value: '0123456789'});
+testVim('fy,;', function(cm, vim, helpers) {
+  cm.setCursor(0, 0);
+  helpers.doKeys('f', '4');
+  cm.setCursor(0, 0);
+  helpers.doKeys('y', ';', 'P');
+  eq('012340123456789', cm.getValue());
+  helpers.doKeys('u');
+  cm.setCursor(0, 9);
+  helpers.doKeys('y', ',', 'P');
+  eq('012345678456789', cm.getValue());
+}, { value: '0123456789'});
+testVim('Fy,;', function(cm, vim, helpers) {
+  cm.setCursor(0, 9);
+  helpers.doKeys('F', '4');
+  cm.setCursor(0, 9);
+  helpers.doKeys('y', ';', 'p');
+  eq('012345678945678', cm.getValue());
+  helpers.doKeys('u');
+  cm.setCursor(0, 0);
+  helpers.doKeys('y', ',', 'P');
+  eq('012340123456789', cm.getValue());
+}, { value: '0123456789'});
+testVim('ty,;', function(cm, vim, helpers) {
+  cm.setCursor(0, 0);
+  helpers.doKeys('t', '4');
+  cm.setCursor(0, 0);
+  helpers.doKeys('y', ';', 'P');
+  eq('01230123456789', cm.getValue());
+  helpers.doKeys('u');
+  cm.setCursor(0, 9);
+  helpers.doKeys('y', ',', 'p');
+  eq('01234567895678', cm.getValue());
+}, { value: '0123456789'});
+testVim('Ty,;', function(cm, vim, helpers) {
+  cm.setCursor(0, 9);
+  helpers.doKeys('T', '4');
+  cm.setCursor(0, 9);
+  helpers.doKeys('y', ';', 'p');
+  eq('01234567895678', cm.getValue());
+  helpers.doKeys('u');
+  cm.setCursor(0, 0);
+  helpers.doKeys('y', ',', 'P');
+  eq('01230123456789', cm.getValue());
+}, { value: '0123456789'});
+testVim('HML', function(cm, vim, helpers) {
+  var lines = 35;
+  var textHeight = cm.defaultTextHeight();
+  cm.setSize(600, lines*textHeight);
+  cm.setCursor(120, 0);
+  helpers.doKeys('H');
+  helpers.assertCursorAt(86, 2);
+  helpers.doKeys('L');
+  helpers.assertCursorAt(120, 4);
+  helpers.doKeys('M');
+  helpers.assertCursorAt(103,4);
+}, { value: (function(){
+  var lines = new Array(100);
+  var upper = '  xx\n';
+  var lower = '    xx\n';
+  upper = lines.join(upper);
+  lower = lines.join(lower);
+  return upper + lower;
+})()});
+
+var zVals = ['zb','zz','zt','z-','z.','z<CR>'].map(function(e, idx){
+  var lineNum = 250;
+  var lines = 35;
+  testVim(e, function(cm, vim, helpers) {
+    var k1 = e[0];
+    var k2 = e.substring(1);
+    var textHeight = cm.defaultTextHeight();
+    cm.setSize(600, lines*textHeight);
+    cm.setCursor(lineNum, 0);
+    helpers.doKeys(k1, k2);
+    zVals[idx] = cm.getScrollInfo().top;
+  }, { value: (function(){
+    return new Array(500).join('\n');
+  })()});
+});
+testVim('zb<zz', function(cm, vim, helpers){
+  eq(zVals[0]<zVals[1], true);
+});
+testVim('zz<zt', function(cm, vim, helpers){
+  eq(zVals[1]<zVals[2], true);
+});
+testVim('zb==z-', function(cm, vim, helpers){
+  eq(zVals[0], zVals[3]);
+});
+testVim('zz==z.', function(cm, vim, helpers){
+  eq(zVals[1], zVals[4]);
+});
+testVim('zt==z<CR>', function(cm, vim, helpers){
+  eq(zVals[2], zVals[5]);
+});
+
+var squareBracketMotionSandbox = ''+
+  '({\n'+//0
+  '  ({\n'+//11
+  '  /*comment {\n'+//2
+  '            */(\n'+//3
+  '#else                \n'+//4
+  '  /*       )\n'+//5
+  '#if        }\n'+//6
+  '  )}*/\n'+//7
+  ')}\n'+//8
+  '{}\n'+//9
+  '#else {{\n'+//10
+  '{}\n'+//11
+  '}\n'+//12
+  '{\n'+//13
+  '#endif\n'+//14
+  '}\n'+//15
+  '}\n'+//16
+  '#else';//17
+testVim('[[, ]]', function(cm, vim, helpers) {
+  cm.setCursor(0, 0);
+  helpers.doKeys(']', ']');
+  helpers.assertCursorAt(9,0);
+  helpers.doKeys('2', ']', ']');
+  helpers.assertCursorAt(13,0);
+  helpers.doKeys(']', ']');
+  helpers.assertCursorAt(17,0);
+  helpers.doKeys('[', '[');
+  helpers.assertCursorAt(13,0);
+  helpers.doKeys('2', '[', '[');
+  helpers.assertCursorAt(9,0);
+  helpers.doKeys('[', '[');
+  helpers.assertCursorAt(0,0);
+}, { value: squareBracketMotionSandbox});
+testVim('[], ][', function(cm, vim, helpers) {
+  cm.setCursor(0, 0);
+  helpers.doKeys(']', '[');
+  helpers.assertCursorAt(12,0);
+  helpers.doKeys('2', ']', '[');
+  helpers.assertCursorAt(16,0);
+  helpers.doKeys(']', '[');
+  helpers.assertCursorAt(17,0);
+  helpers.doKeys('[', ']');
+  helpers.assertCursorAt(16,0);
+  helpers.doKeys('2', '[', ']');
+  helpers.assertCursorAt(12,0);
+  helpers.doKeys('[', ']');
+  helpers.assertCursorAt(0,0);
+}, { value: squareBracketMotionSandbox});
+testVim('[{, ]}', function(cm, vim, helpers) {
+  cm.setCursor(4, 10);
+  helpers.doKeys('[', '{');
+  helpers.assertCursorAt(2,12);
+  helpers.doKeys('2', '[', '{');
+  helpers.assertCursorAt(0,1);
+  cm.setCursor(4, 10);
+  helpers.doKeys(']', '}');
+  helpers.assertCursorAt(6,11);
+  helpers.doKeys('2', ']', '}');
+  helpers.assertCursorAt(8,1);
+  cm.setCursor(0,1);
+  helpers.doKeys(']', '}');
+  helpers.assertCursorAt(8,1);
+  helpers.doKeys('[', '{');
+  helpers.assertCursorAt(0,1);
+}, { value: squareBracketMotionSandbox});
+testVim('[(, ])', function(cm, vim, helpers) {
+  cm.setCursor(4, 10);
+  helpers.doKeys('[', '(');
+  helpers.assertCursorAt(3,14);
+  helpers.doKeys('2', '[', '(');
+  helpers.assertCursorAt(0,0);
+  cm.setCursor(4, 10);
+  helpers.doKeys(']', ')');
+  helpers.assertCursorAt(5,11);
+  helpers.doKeys('2', ']', ')');
+  helpers.assertCursorAt(8,0);
+  helpers.doKeys('[', '(');
+  helpers.assertCursorAt(0,0);
+  helpers.doKeys(']', ')');
+  helpers.assertCursorAt(8,0);
+}, { value: squareBracketMotionSandbox});
+testVim('[*, ]*, [/, ]/', function(cm, vim, helpers) {
+  ['*', '/'].forEach(function(key){
+    cm.setCursor(7, 0);
+    helpers.doKeys('2', '[', key);
+    helpers.assertCursorAt(2,2);
+    helpers.doKeys('2', ']', key);
+    helpers.assertCursorAt(7,5);
+  });
+}, { value: squareBracketMotionSandbox});
+testVim('[#, ]#', function(cm, vim, helpers) {
+  cm.setCursor(10, 3);
+  helpers.doKeys('2', '[', '#');
+  helpers.assertCursorAt(4,0);
+  helpers.doKeys('5', ']', '#');
+  helpers.assertCursorAt(17,0);
+  cm.setCursor(10, 3);
+  helpers.doKeys(']', '#');
+  helpers.assertCursorAt(14,0);
+}, { value: squareBracketMotionSandbox});
+testVim('[m, ]m, [M, ]M', function(cm, vim, helpers) {
+  cm.setCursor(11, 0);
+  helpers.doKeys('[', 'm');
+  helpers.assertCursorAt(10,7);
+  helpers.doKeys('4', '[', 'm');
+  helpers.assertCursorAt(1,3);
+  helpers.doKeys('5', ']', 'm');
+  helpers.assertCursorAt(11,0);
+  helpers.doKeys('[', 'M');
+  helpers.assertCursorAt(9,1);
+  helpers.doKeys('3', ']', 'M');
+  helpers.assertCursorAt(15,0);
+  helpers.doKeys('5', '[', 'M');
+  helpers.assertCursorAt(7,3);
+}, { value: squareBracketMotionSandbox});
+
+// Ex mode tests
+testVim('ex_go_to_line', function(cm, vim, helpers) {
+  cm.setCursor(0, 0);
+  helpers.doEx('4');
+  helpers.assertCursorAt(3, 0);
+}, { value: 'a\nb\nc\nd\ne\n'});
+testVim('ex_write', function(cm, vim, helpers) {
+  var tmp = CodeMirror.commands.save;
+  var written;
+  var actualCm;
+  CodeMirror.commands.save = function(cm) {
+    written = true;
+    actualCm = cm;
+  };
+  // Test that w, wr, wri ... write all trigger :write.
+  var command = 'write';
+  for (var i = 1; i < command.length; i++) {
+    written = false;
+    actualCm = null;
+    helpers.doEx(command.substring(0, i));
+    eq(written, true);
+    eq(actualCm, cm);
+  }
+  CodeMirror.commands.save = tmp;
+});
+testVim('ex_sort', function(cm, vim, helpers) {
+  helpers.doEx('sort');
+  eq('Z\na\nb\nc\nd', cm.getValue());
+}, { value: 'b\nZ\nd\nc\na'});
+testVim('ex_sort_reverse', function(cm, vim, helpers) {
+  helpers.doEx('sort!');
+  eq('d\nc\nb\na', cm.getValue());
+}, { value: 'b\nd\nc\na'});
+testVim('ex_sort_range', function(cm, vim, helpers) {
+  helpers.doEx('2,3sort');
+  eq('b\nc\nd\na', cm.getValue());
+}, { value: 'b\nd\nc\na'});
+testVim('ex_sort_oneline', function(cm, vim, helpers) {
+  helpers.doEx('2sort');
+  // Expect no change.
+  eq('b\nd\nc\na', cm.getValue());
+}, { value: 'b\nd\nc\na'});
+testVim('ex_sort_ignoreCase', function(cm, vim, helpers) {
+  helpers.doEx('sort i');
+  eq('a\nb\nc\nd\nZ', cm.getValue());
+}, { value: 'b\nZ\nd\nc\na'});
+testVim('ex_sort_unique', function(cm, vim, helpers) {
+  helpers.doEx('sort u');
+  eq('Z\na\nb\nc\nd', cm.getValue());
+}, { value: 'b\nZ\na\na\nd\na\nc\na'});
+testVim('ex_sort_decimal', function(cm, vim, helpers) {
+  helpers.doEx('sort d');
+  eq('d3\n s5\n6\n.9', cm.getValue());
+}, { value: '6\nd3\n s5\n.9'});
+testVim('ex_sort_decimal_negative', function(cm, vim, helpers) {
+  helpers.doEx('sort d');
+  eq('z-9\nd3\n s5\n6\n.9', cm.getValue());
+}, { value: '6\nd3\n s5\n.9\nz-9'});
+testVim('ex_sort_decimal_reverse', function(cm, vim, helpers) {
+  helpers.doEx('sort! d');
+  eq('.9\n6\n s5\nd3', cm.getValue());
+}, { value: '6\nd3\n s5\n.9'});
+testVim('ex_sort_hex', function(cm, vim, helpers) {
+  helpers.doEx('sort x');
+  eq(' s5\n6\n.9\n&0xB\nd3', cm.getValue());
+}, { value: '6\nd3\n s5\n&0xB\n.9'});
+testVim('ex_sort_octal', function(cm, vim, helpers) {
+  helpers.doEx('sort o');
+  eq('.8\n.9\nd3\n s5\n6', cm.getValue());
+}, { value: '6\nd3\n s5\n.9\n.8'});
+testVim('ex_sort_decimal_mixed', function(cm, vim, helpers) {
+  helpers.doEx('sort d');
+  eq('y\nz\nc1\nb2\na3', cm.getValue());
+}, { value: 'a3\nz\nc1\ny\nb2'});
+testVim('ex_sort_decimal_mixed_reverse', function(cm, vim, helpers) {
+  helpers.doEx('sort! d');
+  eq('a3\nb2\nc1\nz\ny', cm.getValue());
+}, { value: 'a3\nz\nc1\ny\nb2'});
+testVim('ex_substitute_same_line', function(cm, vim, helpers) {
+  cm.setCursor(1, 0);
+  helpers.doEx('s/one/two');
+  eq('one one\n two two', cm.getValue());
+}, { value: 'one one\n one one'});
+testVim('ex_substitute_global', function(cm, vim, helpers) {
+  cm.setCursor(1, 0);
+  helpers.doEx('%s/one/two');
+  eq('two two\n two two', cm.getValue());
+}, { value: 'one one\n one one'});
+testVim('ex_substitute_input_range', function(cm, vim, helpers) {
+  cm.setCursor(1, 0);
+  helpers.doEx('1,3s/\\d/0');
+  eq('0\n0\n0\n4', cm.getValue());
+}, { value: '1\n2\n3\n4' });
+testVim('ex_substitute_visual_range', function(cm, vim, helpers) {
+  cm.setCursor(1, 0);
+  // Set last visual mode selection marks '< and '> at lines 2 and 4
+  helpers.doKeys('V', '2', 'j', 'v');
+  helpers.doEx('\'<,\'>s/\\d/0');
+  eq('1\n0\n0\n0\n5', cm.getValue());
+}, { value: '1\n2\n3\n4\n5' });
+testVim('ex_substitute_capture', function(cm, vim, helpers) {
+  cm.setCursor(1, 0);
+  helpers.doEx('s/(\\d+)/$1$1/')
+  eq('a1111 a1212 a1313', cm.getValue());
+}, { value: 'a11 a12 a13' });
+testVim('ex_substitute_empty_query', function(cm, vim, helpers) {
+  // If the query is empty, use last query.
+  cm.setCursor(1, 0);
+  cm.openDialog = helpers.fakeOpenDialog('1');
+  helpers.doKeys('/');
+  helpers.doEx('s//b');
+  eq('abb ab2 ab3', cm.getValue());
+}, { value: 'a11 a12 a13' });
+testVim('ex_substitute_count', function(cm, vim, helpers) {
+  cm.setCursor(1, 0);
+  helpers.doEx('s/\\d/0/i 2');
+  eq('1\n0\n0\n4', cm.getValue());
+}, { value: '1\n2\n3\n4' });
+testVim('ex_substitute_count_with_range', function(cm, vim, helpers) {
+  cm.setCursor(1, 0);
+  helpers.doEx('1,3s/\\d/0/ 3');
+  eq('1\n2\n0\n0', cm.getValue());
+}, { value: '1\n2\n3\n4' });
+function testSubstituteConfirm(name, command, initialValue, expectedValue, keys, finalPos) {
+  testVim(name, function(cm, vim, helpers) {
+    var savedOpenDialog = cm.openDialog;
+    var savedKeyName = CodeMirror.keyName;
+    var onKeyDown;
+    var recordedCallback;
+    var closed = true; // Start out closed, set false on second openDialog.
+    function close() {
+      closed = true;
+    }
+    // First openDialog should save callback.
+    cm.openDialog = function(template, callback, options) {
+      recordedCallback = callback;
+    }
+    // Do first openDialog.
+    helpers.doKeys(':');
+    // Second openDialog should save keyDown handler.
+    cm.openDialog = function(template, callback, options) {
+      onKeyDown = options.onKeyDown;
+      closed = false;
+    };
+    // Return the command to Vim and trigger second openDialog.
+    recordedCallback(command);
+    // The event should really use keyCode, but here just mock it out and use
+    // key and replace keyName to just return key.
+    CodeMirror.keyName = function (e) { return e.key; }
+    keys = keys.toUpperCase();
+    for (var i = 0; i < keys.length; i++) {
+      is(!closed);
+      onKeyDown({ key: keys.charAt(i) }, '', close);
+    }
+    try {
+      eq(expectedValue, cm.getValue());
+      helpers.assertCursorAt(finalPos);
+      is(closed);
+    } catch(e) {
+      throw e
+    } finally {
+      // Restore overriden functions.
+      CodeMirror.keyName = savedKeyName;
+      cm.openDialog = savedOpenDialog;
+    }
+  }, { value: initialValue });
+};
+testSubstituteConfirm('ex_substitute_confirm_emptydoc',
+    '%s/x/b/c', '', '', '', makeCursor(0, 0));
+testSubstituteConfirm('ex_substitute_confirm_nomatch',
+    '%s/x/b/c', 'ba a\nbab', 'ba a\nbab', '', makeCursor(0, 0));
+testSubstituteConfirm('ex_substitute_confirm_accept',
+    '%s/a/b/c', 'ba a\nbab', 'bb b\nbbb', 'yyy', makeCursor(1, 1));
+testSubstituteConfirm('ex_substitute_confirm_random_keys',
+    '%s/a/b/c', 'ba a\nbab', 'bb b\nbbb', 'ysdkywerty', makeCursor(1, 1));
+testSubstituteConfirm('ex_substitute_confirm_some',
+    '%s/a/b/c', 'ba a\nbab', 'bb a\nbbb', 'yny', makeCursor(1, 1));
+testSubstituteConfirm('ex_substitute_confirm_all',
+    '%s/a/b/c', 'ba a\nbab', 'bb b\nbbb', 'a', makeCursor(1, 1));
+testSubstituteConfirm('ex_substitute_confirm_accept_then_all',
+    '%s/a/b/c', 'ba a\nbab', 'bb b\nbbb', 'ya', makeCursor(1, 1));
+testSubstituteConfirm('ex_substitute_confirm_quit',
+    '%s/a/b/c', 'ba a\nbab', 'bb a\nbab', 'yq', makeCursor(0, 3));
+testSubstituteConfirm('ex_substitute_confirm_last',
+    '%s/a/b/c', 'ba a\nbab', 'bb b\nbab', 'yl', makeCursor(0, 3));
+testSubstituteConfirm('ex_substitute_confirm_oneline',
+    '1s/a/b/c', 'ba a\nbab', 'bb b\nbab', 'yl', makeCursor(0, 3));
+testSubstituteConfirm('ex_substitute_confirm_range_accept',
+    '1,2s/a/b/c', 'aa\na \na\na', 'bb\nb \na\na', 'yyy', makeCursor(1, 0));
+testSubstituteConfirm('ex_substitute_confirm_range_some',
+    '1,3s/a/b/c', 'aa\na \na\na', 'ba\nb \nb\na', 'ynyy', makeCursor(2, 0));
+testSubstituteConfirm('ex_substitute_confirm_range_all',
+    '1,3s/a/b/c', 'aa\na \na\na', 'bb\nb \nb\na', 'a', makeCursor(2, 0));
+testSubstituteConfirm('ex_substitute_confirm_range_last',
+    '1,3s/a/b/c', 'aa\na \na\na', 'bb\nb \na\na', 'yyl', makeCursor(1, 0));
+//:noh should clear highlighting of search-results but allow to resume search through n
+testVim('ex_noh_clearSearchHighlight', function(cm, vim, helpers) {
+  cm.openDialog = helpers.fakeOpenDialog('match');
+  helpers.doKeys('?');
+  helpers.doEx('noh');
+  eq(vim.searchState_.getOverlay(),null,'match-highlighting wasn\'t cleared');
+  helpers.doKeys('n');
+  helpers.assertCursorAt(0, 11,'can\'t resume search after clearing highlighting');
+}, { value: 'match nope match \n nope Match' });
+// TODO: Reset key maps after each test.
+testVim('ex_map_key2key', function(cm, vim, helpers) {
+  helpers.doEx('map a x');
+  helpers.doKeys('a');
+  helpers.assertCursorAt(0, 0);
+  eq('bc', cm.getValue());
+}, { value: 'abc' });
+testVim('ex_map_key2key_to_colon', function(cm, vim, helpers) {
+  helpers.doEx('map ; :');
+  var dialogOpened = false;
+  cm.openDialog = function() {
+    dialogOpened = true;
+  }
+  helpers.doKeys(';');
+  eq(dialogOpened, true);
+});
+testVim('ex_map_ex2key:', function(cm, vim, helpers) {
+  helpers.doEx('map :del x');
+  helpers.doEx('del');
+  helpers.assertCursorAt(0, 0);
+  eq('bc', cm.getValue());
+}, { value: 'abc' });
+testVim('ex_map_ex2ex', function(cm, vim, helpers) {
+  helpers.doEx('map :del :w');
+  var tmp = CodeMirror.commands.save;
+  var written = false;
+  var actualCm;
+  CodeMirror.commands.save = function(cm) {
+    written = true;
+    actualCm = cm;
+  };
+  helpers.doEx('del');
+  CodeMirror.commands.save = tmp;
+  eq(written, true);
+  eq(actualCm, cm);
+});
+testVim('ex_map_key2ex', function(cm, vim, helpers) {
+  helpers.doEx('map a :w');
+  var tmp = CodeMirror.commands.save;
+  var written = false;
+  var actualCm;
+  CodeMirror.commands.save = function(cm) {
+    written = true;
+    actualCm = cm;
+  };
+  helpers.doKeys('a');
+  CodeMirror.commands.save = tmp;
+  eq(written, true);
+  eq(actualCm, cm);
+});
+// Testing registration of functions as ex-commands and mapping to <Key>-keys
+testVim('ex_api_test', function(cm, vim, helpers) {
+  var res=false;
+  var val='from';
+  CodeMirror.Vim.defineEx('extest','ext',function(cm,params){
+    if(params.args)val=params.args[0];
+    else res=true;
+  });
+  helpers.doEx(':ext to');
+  eq(val,'to','Defining ex-command failed');
+  CodeMirror.Vim.map('<C-CR><Space>',':ext');
+  helpers.doKeys('<C-CR>','<Space>');
+  is(res,'Mapping to key failed');
+});
+// For now, this test needs to be last because it messes up : for future tests.
+testVim('ex_map_key2key_from_colon', function(cm, vim, helpers) {
+  helpers.doEx('map : x');
+  helpers.doKeys(':');
+  helpers.assertCursorAt(0, 0);
+  eq('bc', cm.getValue());
+}, { value: 'abc' });
diff --git a/third-party/codemirror-3.15/theme/3024-day.css b/third-party/codemirror-3.15/theme/3024-day.css
new file mode 100644 (file)
index 0000000..e931a49
--- /dev/null
@@ -0,0 +1,33 @@
+/*
+
+    Name:       3024 day
+    Author:     Jan T. Sott (http://github.com/idleberg)
+
+    CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-codemirror)
+    Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16)
+
+*/
+
+.cm-s-3024-day.CodeMirror {background: #f7f7f7; color: #3a3432;}
+.cm-s-3024-day div.CodeMirror-selected {background: #d6d5d4 !important;}
+.cm-s-3024-day .CodeMirror-gutters {background: #f7f7f7; border-right: 0px;}
+.cm-s-3024-day .CodeMirror-linenumber {color: #807d7c;}
+.cm-s-3024-day .CodeMirror-cursor {border-left: 1px solid #5c5855 !important;}
+
+.cm-s-3024-day span.cm-comment {color: #cdab53;}
+.cm-s-3024-day span.cm-atom {color: #a16a94;}
+.cm-s-3024-day span.cm-number {color: #a16a94;}
+
+.cm-s-3024-day span.cm-property, .cm-s-3024-day span.cm-attribute {color: #01a252;}
+.cm-s-3024-day span.cm-keyword {color: #db2d20;}
+.cm-s-3024-day span.cm-string {color: #fded02;}
+
+.cm-s-3024-day span.cm-variable {color: #01a252;}
+.cm-s-3024-day span.cm-variable-2 {color: #01a0e4;}
+.cm-s-3024-day span.cm-def {color: #e8bbd0;}
+.cm-s-3024-day span.cm-error {background: #db2d20; color: #5c5855;}
+.cm-s-3024-day span.cm-bracket {color: #3a3432;}
+.cm-s-3024-day span.cm-tag {color: #db2d20;}
+.cm-s-3024-day span.cm-link {color: #a16a94;}
+
+.cm-s-3024-day .CodeMirror-matchingbracket { text-decoration: underline; color: white !important;}
diff --git a/third-party/codemirror-3.15/theme/3024-night.css b/third-party/codemirror-3.15/theme/3024-night.css
new file mode 100644 (file)
index 0000000..87c7f8a
--- /dev/null
@@ -0,0 +1,33 @@
+/*
+
+    Name:       3024 night
+    Author:     Jan T. Sott (http://github.com/idleberg)
+
+    CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-codemirror)
+    Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16)
+
+*/
+
+.cm-s-3024-night.CodeMirror {background: #090300; color: #d6d5d4;}
+.cm-s-3024-night div.CodeMirror-selected {background: #3a3432 !important;}
+.cm-s-3024-night .CodeMirror-gutters {background: #090300; border-right: 0px;}
+.cm-s-3024-night .CodeMirror-linenumber {color: #5c5855;}
+.cm-s-3024-night .CodeMirror-cursor {border-left: 1px solid #807d7c !important;}
+
+.cm-s-3024-night span.cm-comment {color: #cdab53;}
+.cm-s-3024-night span.cm-atom {color: #a16a94;}
+.cm-s-3024-night span.cm-number {color: #a16a94;}
+
+.cm-s-3024-night span.cm-property, .cm-s-3024-night span.cm-attribute {color: #01a252;}
+.cm-s-3024-night span.cm-keyword {color: #db2d20;}
+.cm-s-3024-night span.cm-string {color: #fded02;}
+
+.cm-s-3024-night span.cm-variable {color: #01a252;}
+.cm-s-3024-night span.cm-variable-2 {color: #01a0e4;}
+.cm-s-3024-night span.cm-def {color: #e8bbd0;}
+.cm-s-3024-night span.cm-error {background: #db2d20; color: #807d7c;}
+.cm-s-3024-night span.cm-bracket {color: #d6d5d4;}
+.cm-s-3024-night span.cm-tag {color: #db2d20;}
+.cm-s-3024-night span.cm-link {color: #a16a94;}
+
+.cm-s-3024-night .CodeMirror-matchingbracket { text-decoration: underline; color: white !important;}
diff --git a/third-party/codemirror-3.15/theme/ambiance-mobile.css b/third-party/codemirror-3.15/theme/ambiance-mobile.css
new file mode 100644 (file)
index 0000000..88d332e
--- /dev/null
@@ -0,0 +1,5 @@
+.cm-s-ambiance.CodeMirror {
+  -webkit-box-shadow: none;
+  -moz-box-shadow: none;
+  box-shadow: none;
+}
diff --git a/third-party/codemirror-3.15/theme/ambiance.css b/third-party/codemirror-3.15/theme/ambiance.css
new file mode 100644 (file)
index 0000000..0185426
--- /dev/null
@@ -0,0 +1,75 @@
+/* ambiance theme for codemirror */
+
+/* Color scheme */
+
+.cm-s-ambiance .cm-keyword { color: #cda869; }
+.cm-s-ambiance .cm-atom { color: #CF7EA9; }
+.cm-s-ambiance .cm-number { color: #78CF8A; }
+.cm-s-ambiance .cm-def { color: #aac6e3; }
+.cm-s-ambiance .cm-variable { color: #ffb795; }
+.cm-s-ambiance .cm-variable-2 { color: #eed1b3; }
+.cm-s-ambiance .cm-variable-3 { color: #faded3; }
+.cm-s-ambiance .cm-property { color: #eed1b3; }
+.cm-s-ambiance .cm-operator {color: #fa8d6a;}
+.cm-s-ambiance .cm-comment { color: #555; font-style:italic; }
+.cm-s-ambiance .cm-string { color: #8f9d6a; }
+.cm-s-ambiance .cm-string-2 { color: #9d937c; }
+.cm-s-ambiance .cm-meta { color: #D2A8A1; }
+.cm-s-ambiance .cm-error { color: #AF2018; }
+.cm-s-ambiance .cm-qualifier { color: yellow; }
+.cm-s-ambiance .cm-builtin { color: #9999cc; }
+.cm-s-ambiance .cm-bracket { color: #24C2C7; }
+.cm-s-ambiance .cm-tag { color: #fee4ff }
+.cm-s-ambiance .cm-attribute {  color: #9B859D; }
+.cm-s-ambiance .cm-header {color: blue;}
+.cm-s-ambiance .cm-quote { color: #24C2C7; }
+.cm-s-ambiance .cm-hr { color: pink; }
+.cm-s-ambiance .cm-link { color: #F4C20B; }
+.cm-s-ambiance .cm-special { color: #FF9D00; }
+
+.cm-s-ambiance .CodeMirror-matchingbracket { color: #0f0; }
+.cm-s-ambiance .CodeMirror-nonmatchingbracket { color: #f22; }
+
+.cm-s-ambiance .CodeMirror-selected {
+  background: rgba(255, 255, 255, 0.15);
+}
+.cm-s-ambiance .CodeMirror-focused .CodeMirror-selected {
+  background: rgba(255, 255, 255, 0.10);
+}
+
+/* Editor styling */
+
+.cm-s-ambiance.CodeMirror {
+  line-height: 1.40em;
+  font-family: Monaco, Menlo,"Andale Mono","lucida console","Courier New",monospace !important;
+  color: #E6E1DC;
+  background-color: #202020;
+  -webkit-box-shadow: inset 0 0 10px black;
+  -moz-box-shadow: inset 0 0 10px black;
+  box-shadow: inset 0 0 10px black;
+}
+
+.cm-s-ambiance .CodeMirror-gutters {
+  background: #3D3D3D;
+  border-right: 1px solid #4D4D4D;
+  box-shadow: 0 10px 20px black;
+}
+
+.cm-s-ambiance .CodeMirror-linenumber {
+  text-shadow: 0px 1px 1px #4d4d4d;
+  color: #222;
+  padding: 0 5px;
+}
+
+.cm-s-ambiance .CodeMirror-lines .CodeMirror-cursor {
+  border-left: 1px solid #7991E8;
+}
+
+.cm-s-ambiance .activeline {
+  background: none repeat scroll 0% 0% rgba(255, 255, 255, 0.031);
+}
+
+.cm-s-ambiance.CodeMirror,
+.cm-s-ambiance .CodeMirror-gutters {
+  background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAQAAAAHUWYVAABFFUlEQVQYGbzBCeDVU/74/6fj9HIcx/FRHx9JCFmzMyGRURhLZIkUsoeRfUjS2FNDtr6WkMhO9sm+S8maJfu+Jcsg+/o/c+Z4z/t97/vezy3z+z8ekGlnYICG/o7gdk+wmSHZ1z4pJItqapjoKXWahm8NmV6eOTbWUOp6/6a/XIg6GQqmenJ2lDHyvCFZ2cBDbmtHA043VFhHwXxClWmeYAdLhV00Bd85go8VmaFCkbVkzlQENzfBDZ5gtN7HwF0KDrTwJ0dypSOzpaKCMwQHKTIreYIxlmhXTzTWkVm+LTynZhiSBT3RZQ7aGfjGEd3qyXQ1FDymqbKxpspERQN2MiRjNZlFFQXfCNFm9nM1zpAsoYjmtRTc5ajwuaXc5xrWskT97RaKzAGe5ARHhVUsDbjKklziiX5WROcJwSNCNI+9w1Jwv4Zb2r7lCMZ4oq5C0EdTx+2GzNuKpJ+iFf38JEWkHJn9DNF7mmBDITrWEg0VWL3pHU20tSZnuqWu+R3BtYa8XxV1HO7GyD32UkOpL/yDloINFTmvtId+nmAjxRw40VMwVKiwrKLE4bK5UOVntYwhOcSSXKrJHKPJedocpGjVz/ZMIbnYUPB10/eKCrs5apqpgVmWzBYWpmtKHecJPjaUuEgRDDaU0oZghCJ6zNMQ5ZhDYx05r5v2muQdM0EILtXUsaKiQX9WMEUotagQzFbUNN6NUPC2nm5pxEWGCjMc3GdJHjSU2kORLK/JGSrkfGEIjncU/CYUnOipoYemwj8tST9NsJmB7TUVXtbUtXATJVZXBMvYeTXJfobgJUPmGMP/yFaWonaa6BcFO3nqcIqCozSZoZoSr1g4zJOzuyGnxTEX3lUEJ7WcZgme8ddaWvWJo2AJR9DZU3CUIbhCSG6ybSwN6qtJVnCU2svDTP2ZInOw2cBTrqtQahtNZn9NcJ4l2NaSmSkkP1noZWnVwkLmdUPOwLZEwy2Z3S3R+4rIG9hcbpPXHFVWcQdZkn2FOta3cKWQnNRC5g1LsJah4GCzSVsKnCOY5OAFRTBekyyryeyilhFKva75r4Mc0aWanGEaThcy31s439KKxTzJYY5WTHPU1FtIHjQU3Oip4xlNzj/lBw23dYZVliQa7WAXf4shetcQfatI+jWRDBPmyNeW6A1P5kdDgyYJlba0BIM8BZu1JfrFwItyjcAMR3K0BWOIrtMEXyhyrlVEx3ui5dUBjmB/Q3CXW85R4mBD0s7B+4q5tKUjOlb9qqmhi5AZ6GFIC5HXtOobdYGlVdMVbNJ8toNTFcHxnoL+muBagcctjWnbNMuR00uI7nQESwg5q2qqrKWIfrNUmeQocY6HuyxJV02wj36w00yhpmUFenv4p6fUkZYqLyuinx2RGOjhCXYyJF84oiU00YMOOhhquNdfbOB7gU88pY4xJO8LVdp6/q2voeB4R04vIdhSE40xZObx1HGGJ/ja0LBthFInKaLPPFzuCaYaoj8JjPME8yoyxo6zlBqkiUZYgq00OYMswbWO5NGmq+xhipxHLRW29ARjNKXO0wRnear8XSg4XFPLKEPUS1GqvyLwiuBUoa7zpZ0l5xxFwWmWZC1H5h5FwU8eQ7K+g8UcVY6TMQreVQT/8uQ8Z+ALIXnSEa2pYZQneE9RZbSBNYXfWYJzW/h/4j4Dp1tYVcFIC5019Vyi4ThPqSFCzjGWaHQTBU8q6vrVwgxP9Lkm840imWKpcLCjYTtrKuwvsKSnrvHCXGkSMk9p6lhckfRpIeis+N2PiszT+mFLspyGleUhDwcLrZqmyeylxwjBcKHEapqkmyangyLZRVOijwOtCY5SsG5zL0OwlCJ4y5KznF3EUNDDrinwiyLZRzOXtlBbK5ITHFGLp8Q0R6ab6mS7enI2cFrxOyHvOCFaT1HThS1krjCwqWeurCkk+willhCC+RSZnRXBiZaC5RXRIZYKp2lyfrHwiKPKR0JDzrdU2EFgpidawlFDR6FgXUMNa+g1FY3bUQh2cLCwosRdnuQTS/S+JVrGLeWIvtQUvONJxlqSQYYKpwoN2kaocLjdVsis4Mk80ESF2YpSkzwldjHkjFCUutI/r+EHDU8oCs6yzL3PhWiEooZdFMkymlas4AcI3KmoMMNSQ3tHzjGWCrcJJdYyZC7QFGwjRL9p+MrRkAGWzIaWCn9W0F3TsK01c2ZvQw0byvxuQU0r1lM0qJO7wW0kRIMdDTtXEdzi4VIh+EoIHm0mWtAtpCixlabgn83fKTI7anJe9ST7WIK1DMGpQmYeA58ImV6ezOGOzK2Kgq01pd60cKWiUi9Lievb/0vIDPHQ05Kzt4ddPckQBQtoaurjyHnek/nKzpQLrVgKPjIkh2v4uyezpv+Xoo7fPFXaGFp1vaLKxQ4uUpQQS5VuQs7BCq4xRJv7fwpVvvFEB3j+620haOuocqMhWd6TTPAEx+mdFNGHdranFe95WrWmIvlY4F1Dle2ECgc6cto7SryuqGGGha0tFQ5V53migUKmg6XKAo4qS3mik+0OZpAhOLeZKicacgaYcyx5hypYQE02ZA4xi/pNhOQxR4klNKyqacj+mpxnLTnnGSo85++3ZCZq6lrZkXlGEX3o+C9FieccJbZWVFjC0Yo1FZnJhoYMFoI1hEZ9r6hwg75HwzBNhbZCdJEfJwTPGzJvaKImw1yYX1HDAmpXR+ZJQ/SmgqMNVQb5vgamGwLtt7VwvP7Qk1xpiM5x5Cyv93E06MZmgs0Nya2azIKOYKCGBQQW97RmhKNKF02JZqHEJ4o58qp7X5EcZmc56trXEqzjCBZ1MFGR87Ql2tSTs6CGxS05PTzRQorkbw7aKoKXFDXsYW42VJih/q+FP2BdTzDTwVqOYB13liM50vG7wy28qagyuIXMeQI/Oqq8bcn5wJI50xH00CRntyfpL1T4hydYpoXgNiFzoIUTDZnLNRzh4TBHwbYGDvZkxmlyJloyr6tRihpeUG94GnKtIznREF0tzJG/OOr73JBcrSh1k6WuTprgLU+mnSGnv6Zge0NNz+kTDdH8nuAuTdJDCNb21LCiIuqlYbqGzT3RAoZofQfjFazkqeNWdYaGvYTM001EW2oKPvVk1ldUGSgUtHFwjKM1h9jnFcmy5lChoLNaQMGGDsYbKixlaMBmmsx1QjCfflwTfO/gckW0ruZ3jugKR3R5W9hGUWqCgxuFgsuaCHorotGKzGaeZB9DMsaTnKCpMtwTvOzhYk0rdrArKCqcaWmVk1+F372ur1YkKxgatI8Qfe1gIX9wE9FgS8ESmuABIXnRUbCapcKe+nO7slClSZFzpV/LkLncEb1qiO42fS3R855Su2mCLh62t1SYZZYVmKwIHjREF2uihTzB20JOkz7dkxzYQnK0UOU494wh+VWRc6Un2kpTaVgLDFEkJ/uhzRcI0YKGgpGWOlocBU/a4fKoJ/pEaNV6jip3+Es9VXY078rGnmAdf7t9ylPXS34RBSuYPs1UecZTU78WanhBCHpZ5sAoTz0LGZKjPf9TRypqWEiTvOFglL1fCEY3wY/++rbk7C8bWebA6p6om6PgOL2kp44TFJlVNBXae2rqqdZztOJpT87GQsE9jqCPIe9VReZuQ/CIgacsyZdCpIScSYqcZk8r+nsyCzhyfhOqHGOIvrLknC8wTpFcaYiGC/RU1NRbUeUpocQOnkRpGOrIOcNRx+1uA0UrzhSSt+VyS3SJpnFWkzNDqOFGIWcfR86DnmARTQ1HKIL33ExPiemeOhYSSjzlSUZZuE4TveoJLnBUOFof6KiysCbnAEcZgcUNTDOwkqWu3RWtmGpZwlHhJENdZ3miGz0lJlsKnjbwqSHQjpxnFDlTLLwqJPMZMjd7KrzkSG7VsxXBZE+F8YZkb01Oe00yyRK9psh5SYh29ySPKBo2ylNht7ZkZnsKenjKNJu9PNEyZpaCHv4Kt6RQsLvAVp7M9kIimmCUwGeWqLMmGuIotYMmWNpSahkhZw9FqZsVnKJhsjAHvtHMsTM9fCI06Dx/u3vfUXCqfsKRc4oFY2jMsoo/7DJDwZ1CsIKnJu+J9ldkpmiCxQx1rWjI+T9FwcWWzOuaYH0Hj7klNRVWEQpmaqosakiGNTFHdjS/qnUdmf0NJW5xsL0HhimCCZZSRzmSPTXJQ4aaztAwtZnoabebJ+htCaZ7Cm535ByoqXKbX1WRc4Eh2MkRXWzImVc96Cj4VdOKVxR84VdQsIUM8Psoou2byVHyZFuq7O8otbSQ2UAoeEWTudATLGSpZzVLlXVkPU2Jc+27lsw2jmg5T5VhbeE3BT083K9WsTTkFU/Osi0rC5lRlpwRHUiesNS0sOvmqGML1aRbPAxTJD9ZKtxuob+hhl8cwYGWpJ8nub7t5p6coYbMovZ1BTdaKn1jYD6h4GFDNFyT/Kqe1XCXphXHOKLZmuRSRdBPEfVUXQzJm5YGPGGJdvAEr7hHNdGZnuBvrpciGmopOLf5N0uVMy0FfYToJk90uUCbJupaVpO53UJXR2bVpoU00V2KOo4zMFrBd0Jtz2pa0clT5Q5L8IpQ177mWQejPMEJhuQjS10ref6HHjdEhy1P1EYR7GtO0uSsKJQYLiTnG1rVScj5lyazpqWGl5uBbRWl7m6ixGOOnEsMJR7z8J0n6KMnCdxhiNYQCoZ6CmYLnO8omC3MkW3bktlPmEt/VQQHejL3+dOE5FlPdK/Mq8hZxxJtLyRrepLThYKbLZxkSb5W52vYxNOaOxUF0yxMUPwBTYqCzy01XayYK0sJyWBLqX0MwU5CzoymRzV0EjjeUeLgDpTo6ij42ZAzvD01dHUUTPLU96MdLbBME8nFBn7zJCMtJcZokn8YoqU0FS5WFKyniHobguMcmW8N0XkWZjkyN3hqOMtS08r+/xTBwpZSZ3qiVRX8SzMHHjfUNFjgHEPmY9PL3ykEzxkSre/1ZD6z/NuznuB0RcE1TWTm9zRgfUWVJiG6yrzgmWPXC8EAR4Wxhlad0ZbgQyEz3pG5RVEwwDJH2mgKpjcTiCOzn1lfUWANFbZ2BA8balnEweJC9J0iuaeZoI+ippFCztEKVvckR2iice1JvhVytrQwUAZpgsubCPaU7xUe9vWnaOpaSBEspalykhC9bUlOMpT42ZHca6hyrqKmw/wMR8H5ZmdFoBVJb03O4UL0tSNnvIeRmkrLWqrs78gcrEn2tpcboh0UPOW3UUR9PMk4T4nnNKWmCjlrefhCwxRNztfmIQVdDElvS4m1/WuOujoZCs5XVOjtKPGokJzsYCtFYoWonSPT21DheU/wWhM19FcElwqNGOsp9Q8N/cwXaiND1MmeL1Q5XROtYYgGeFq1aTMsoMmcrKjQrOFQTQ1fmBYhmW6o8Jkjc7iDJRTBIo5kgJD5yMEYA3srCg7VFKwiVJkmRCc5ohGOKhsYMn/XBLdo5taZjlb9YAlGWRimqbCsoY7HFAXLa5I1HPRxMMsQDHFkWtRNniqT9UEeNjcE7RUlrCJ4R2CSJuqlKHWvJXjAUNcITYkenuBRB84TbeepcqTj3zZyFJzgYQdHnqfgI0ddUwS6GqWpsKWhjq9cV0vBAEMN2znq+EBfIWT+pClYw5xsTlJU6GeIBsjGmmANTzJZiIYpgrM0Oa8ZMjd7NP87jxhqGOhJlnQtjuQpB+8aEE00wZFznSJPyHxgH3HkPOsJFvYk8zqCHzTs1BYOa4J3PFU+UVRZxlHDM4YavlNUuMoRveiZA2d7grMNc2g+RbSCEKzmgYsUmWmazFJyoiOZ4KnyhKOGRzWJa0+moyV4TVHDzn51Awtqaphfk/lRQ08FX1iiqxTB/kLwd0VynKfEvI6cd4XMV5bMhZ7gZUWVzYQ6Nm2BYzxJbw3bGthEUUMfgbGeorae6DxHtJoZ6alhZ0+ytiVoK1R4z5PTrOECT/SugseEOlb1MMNR4VRNcJy+V1Hg9ONClSZFZjdHlc6W6FBLdJja2MC5hhpu0DBYEY1TFGwiFAxRRCsYkiM9JRb0JNMVkW6CZYT/2EiTGWmo8k+h4FhDNE7BvppoTSFnmCV5xZKzvcCdDo7VVPnIU+I+Rc68juApC90MwcFCsJ5hDqxgScYKreruyQwTqrzoqDCmhWi4IbhB0Yrt3RGa6GfDv52rKXWhh28dyZaWUvcZeMTBaZoSGyiCtRU5J8iviioHaErs7Jkj61syVzTTgOcUOQ8buFBTYWdL5g3T4qlpe0+wvD63heAXRfCCIed9RbCsp2CiI7raUOYOTU13N8PNHvpaGvayo4a3LLT1lDrVEPT2zLUlheB1R+ZTRfKWJ+dcocLJfi11vyJ51lLqJ0WD7tRwryezjiV5W28uJO9qykzX8JDe2lHl/9oyBwa2UMfOngpXCixvKdXTk3wrsKmiVYdZIqsoWEERjbcUNDuiaQomGoIbFdEHmsyWnuR+IeriKDVLnlawlyNHKwKlSU631PKep8J4Q+ayjkSLKYLhalNHlYvttb6fHm0p6OApsZ4l2VfdqZkjuysy6ysKLlckf1KUutCTs39bmCgEyyoasIWlVaMF7mgmWtBT8Kol5xpH9IGllo8cJdopcvZ2sImlDmMIbtDk3KIpeNiS08lQw11NFPTwVFlPP6pJ2gvRfI7gQUfmNAtf6Gs0wQxDsKGlVBdF8rCa3jzdwMaGHOsItrZk7hAyOzpK9VS06j5F49b0VNGOOfKs3lDToMsMBe9ZWtHFEgxTJLs7qrygKZjUnmCYoeAqeU6jqWuLJup4WghOdvCYJnrSkSzoyRkm5M2StQwVltPkfCAk58tET/CSg+8MUecmotMEnhBKfWBIZsg2ihruMJQaoIm+tkTLKEqspMh00w95gvFCQRtDwTT1gVDDSEVdlwqZfxoQRbK0g+tbiBZxzKlpnpypejdDwTaeOvorMk/IJE10h9CqRe28hhLbe0pMsdSwv4ZbhKivo2BjDWfL8UKJgeavwlwb5KlwhyE4u4XkGE2ytZCznKLCDZZq42VzT8HLCrpruFbIfOIINmh/qCdZ1ZBc65kLHR1Bkyf5zn6pN3SvGKIlFNGplhrO9QSXanLOMQTLCa0YJCRrCZm/CZmrLTm7WzCK4GJDiWUdFeYx1LCFg3NMd0XmCuF3Y5rITLDUsYS9zoHVzwnJoYpSTQoObyEzr4cFBNqYTopoaU/wkyLZ2lPhX/5Y95ulxGTV7KjhWrOZgl8MyUUafjYraNjNU1N3IWcjT5WzWqjwtoarHSUObGYO3GCJZpsBlnJGPd6ZYLyl1GdCA2625IwwJDP8GUKymbzuyPlZlvTUsaUh5zFDhRWFzPKKZLAlWdcQbObgF9tOqOsmB1dqcqYJmWstFbZRRI9poolmqiLnU0POvxScpah2iSL5UJNzgScY5+AuIbpO0YD3NCW+dLMszFSdFCWGqG6eVq2uYVNDdICGD6W7EPRWZEY5gpsE9rUkS3mijzzJnm6UpUFXG1hCUeVoS5WfNcFpblELL2qqrCvMvRfd45oalvKU2tiQ6ePJOVMRXase9iTtLJztPxJKLWpo2CRDcJwn2sWSLKIO1WQWNTCvpVUvOZhgSC40JD0dOctaSqzkCRbXsKlb11Oip6PCJ0IwSJM31j3akRxlP7Rwn6aGaUL0qiLnJkvB3xWZ2+Q1TfCwpQH3G0o92UzmX4o/oJNQMMSQc547wVHhdk+VCw01DFYEnTxzZKAm74QmeNNR1w6WzEhNK15VJzuCdxQ53dRUDws5KvwgBMOEgpcVNe0hZI6RXT1Jd0cyj5nsaEAHgVmGaJIlWdsc5Ui2ElrRR6jrRAttNMEAIWrTDFubkZaok7/AkzfIwfuWVq0jHzuCK4QabtLUMVPB3kJ0oyHTSVFlqMALilJf2Rf8k5aaHtMfayocLBS8L89oKoxpJvnAkDPa0qp5DAUTHKWmCcnthlou8iCKaFFLHWcINd1nyIwXqrSxMNmSs6KmoL2QrKuWtlQ5V0120xQ5vRyZS1rgFkWwhiOwiuQbR0OOVhQM9iS3tiXp4RawRPMp5tDletOOBL95MpM01dZTBM9pkn5qF010rIeHFcFZhmSGpYpTsI6nwhqe5C9ynhlpp5ophuRb6WcJFldkVnVEwwxVfrVkvnWUuNLCg5bgboFHPDlDPDmnK7hUrWiIbjadDclujlZcaokOFup4Ri1kacV6jmrrK1hN9bGwpKEBQ4Q6DvIUXOmo6U5LqQM6EPyiKNjVkPnJkDPNEaxhiFay5ExW1NXVUGqcpYYdPcGiCq7z/TSlbhL4pplWXKd7NZO5QQFrefhRQW/NHOsqcIglc4UhWklR8K0QzbAw08CBDnpbgqXdeD/QUsM4RZXDFBW6WJKe/mFPdH0LtBgiq57wFLzlyQzz82qYx5D5WJP5yVJDW01BfyHnS6HKO/reZqId1WGa4Hkh2kWodJ8i6KoIPlAj2hPt76CzXsVR6koPRzWTfKqIentatYpQw2me4AA3y1Kind3SwoOKZDcFXTwl9tWU6mfgRk9d71sKtlNwrjnYw5tC5n5LdKiGry3JKNlHEd3oaMCFHrazBPMp/uNJ+V7IudcSbeOIdjUEdwl0VHCOZo5t6YluEuaC9mQeMgSfOyKnYGFHcIeQ84yQWbuJYJpZw5CzglDH7gKnWqqM9ZTaXcN0TeYhR84eQtJT76JJ1lREe7WnnvsMmRc9FQ7SBBM9mV3lCUdmHk/S2RAMt0QjFNFqQpWjDPQ01DXWUdDBkXziKPjGEP3VP+zIWU2t7im41FOloyWzn/L6dkUy3VLDaZ6appgDLHPjJEsyvJngWEPUyVBiAaHCTEXwrLvSEbV1e1gKJniicWorC1MUrVjB3uDhJE/wgSOzk1DXpk0k73qCM8xw2UvD5kJmDUfOomqMpWCkJRlvKXGmoeBm18USjVIk04SClxTB6YrgLAPLWYK9HLUt5cmc0vYES8GnTeRc6skZbQkWdxRsIcyBRzx1DbTk9FbU0caTPOgJHhJKnOGIVhQqvKmo0llRw9sabrZkDtdg3PqaKi9oatjY8B+G371paMg6+mZFNNtQ04mWBq3rYLOmtWWQp8KJnpy9DdFensyjdqZ+yY40VJlH8wcdLzC8PZnvHMFUTZUrDTkLyQaGus5X5LzpYAf3i+e/ZlhqGqWhh6Ou6xTR9Z6oi5AZZtp7Mj2EEm8oSpxiYZCHU/1fbGdNNNRRoZMhmilEb2gqHOEJDtXkHK/JnG6IrvbPCwV3NhONVdS1thBMs1T4QOBcTWa2IzhMk2nW5Kyn9tXUtpv9RsG2msxk+ZsQzRQacJncpgke0+T8y5Fzj8BiGo7XlJjaTIlpQs7KFjpqGnKuoyEPeIKnFMkZHvopgh81ySxNFWvJWcKRs70j2FOT012IllEEO1n4pD1513Yg2ssQPOThOkvyrqHUdEXOSEsihmBbTbKX1kLBPWqWkLOqJbjB3GBIZmoa8qWl4CG/iZ7oiA72ZL7TJNeZUY7kFQftDcHHluBzRbCegzMtrRjVQpX2lgoPKKLJAkcbMl01XK2p7yhL8pCBbQ3BN2avJgKvttcrWDK3CiUOVxQ8ZP+pqXKyIxnmBymCg5vJjNfkPK4+c8cIfK8ocVt7kmfd/I5SR1hKvCzUtb+lhgc00ZaO6CyhIQP1Uv4yIZjload72PXX0OIJvnFU+0Zf6MhsJwTfW0r0UwQfW4LNLZl5HK261JCZ4qnBaAreVAS3WrjV0LBnNDUNNDToCEeFfwgcb4gOEqLRhirWkexrCEYKVV711DLYEE1XBEsp5tpTGjorkomKYF9FDXv7fR3BGwbettSxnyL53MBPjsxDZjMh+VUW9NRxq1DhVk+FSxQcaGjV9Pawv6eGByw5qzoy7xk4RsOShqjJwWKe/1pEEfzkobeD/dQJmpqedcyBTy2sr4nGNRH0c0SPWTLrqAc0OQcb/gemKgqucQT7ySWKCn2EUotoCvpZct7RO2sy/QW0IWcXd7pQRQyZVwT2USRO87uhjioTLKV2brpMUcMQRbKH/N2T+UlTpaMls6cmc6CCNy3JdYYSUzzJQ4oSD3oKLncULOiJvjBEC2oqnCJkJluCYy2ZQ5so9YYlZ1VLlQU1mXEW1jZERwj/MUSRc24TdexlqLKfQBtDTScJUV8FszXBEY5ktpD5Ur9hYB4Nb1iikw3JoYpkKX+RodRKFt53MMuRnKSpY31PwYaGaILh3wxJGz9TkTPEETxoCWZrgvOlmyMzxFEwVJE5xZKzvyJ4WxEc16Gd4Xe3Weq4XH2jKRikqOkGQ87hQnC7wBmGYLAnesX3M+S87eFATauuN+Qcrh7xIxXJbUIdMw3JGE3ylCWzrieaqCn4zhGM19TQ3z1oH1AX+pWEqIc7wNGAkULBo/ZxRaV9NNyh4Br3rCHZzbzmSfawBL0dNRwpW1kK9mxPXR9povcdrGSZK9c2k0xwFGzjuniCtRSZCZ6ccZ7gaktmgAOtKbG/JnOkJrjcQTdFMsxRQ2cLY3WTIrlCw1eWKn8R6pvt4GFDso3QoL4a3nLk3G6JrtME3dSenpx7PNFTmga0EaJTLQ061sEeQoWXhSo9LTXsaSjoJQRXeZLtDclbCrYzfzHHeaKjHCVOUkQHO3JeEepr56mhiyaYYKjjNU+Fed1wS5VlhWSqI/hYUdDOkaxiKehoyOnrCV5yBHtbWFqTHCCwtpDcYolesVR5yUzTZBb3RNMd0d6WP+SvhuBmRcGxnuQzT95IC285cr41cLGQ6aJJhmi4TMGempxeimBRQw1tFKV+8jd6KuzoSTqqDxzRtpZkurvKEHxlqXKRIjjfUNNXQsNOsRScoWFLT+YeRZVD3GRN0MdQcKqQjHDMrdGGVu3iYJpQx3WGUvfbmxwFfR20WBq0oYY7LMFhhgYtr8jpaEnaOzjawWWaTP8mMr0t/EPDPoqcnxTBI5o58L7uoWnMrpoqPwgVrlAUWE+V+TQl9rawoyP6QGAlQw2TPRX+YSkxyBC8Z6jhHkXBgQL7WII3DVFnRfCrBfxewv9D6xsyjys4VkhWb9pUU627JllV0YDNHMku/ldNMMXDEo4aFnAkk4U6frNEU4XgZUPmEKHUl44KrzmYamjAbh0JFvGnaTLPu1s9jPCwjFpYiN7z1DTOk/nc07CfDFzmCf7i+bfNHXhDtLeBXzTBT5rkMvWOIxpl4EMh2LGJBu2syDnAEx2naEhHDWMMzPZEhygyS1mS5RTJr5ZkoKbEUoYqr2kqdDUE8ztK7OaIntJkFrIECwv8LJTaVx5XJE86go8dFeZ3FN3rjabCAYpoYEeC9zzJVULBbmZhDyd7ko09ydpNZ3nm2Kee4FPPXHnYEF1nqOFEC08LUVcDvYXkJHW8gTaKCk9YGOeIJhqiE4ToPEepdp7IWFjdwnWaufGMwJJCMtUTTBBK9BGCOy2tGGrJTHIwyEOzp6aPzNMOtlZkDvcEWpP5SVNhfkvDxhmSazTJXYrM9U1E0xwFVwqZQwzJxw6+kGGGUj2FglGGmnb1/G51udRSMNlTw6GGnCcUwVcOpmsqTHa06o72sw1RL02p9z0VbnMLOaIX3QKaYKSCFQzBKEUNHTSc48k53RH9wxGMtpQa5KjjW0W0n6XCCCG4yxNNdhQ4R4l1Ff+2sSd6UFHiIEOyqqFgT01mEUMD+joy75jPhOA+oVVLm309FR4yVOlp4RhLiScNmSmaYF5Pw0STrOIoWMSR2UkRXOMp+M4SHW8o8Zoi6OZgjKOaFar8zZDzkWzvKOjkKBjmCXby8JahhjXULY4KlzgKLvAwxVGhvyd4zxB1d9T0piazmKLCVZY5sKiD0y2ZSYrkUEPUbIk+dlQ4SJHTR50k1DPaUWIdTZW9NJwnJMOECgd7ou/MnppMJ02O1VT4Wsh85MnZzcFTngpXGKo84qmwgKbCL/orR/SzJ2crA+t6Mp94KvxJUeIbT3CQu1uIdlQEOzlKfS3UMcrTiFmOuroocrZrT2AcmamOKg8YomeEKm/rlT2sociMaybaUlFhuqHCM2qIJ+rg4EcDFymiDSxzaHdPcpE62pD5kyM5SBMoA1PaUtfIthS85ig1VPiPPYXgYEMNk4Qq7TXBgo7oT57gPUdwgCHzhIVFPFU6OYJzHAX9m5oNrVjeE61miDrqQ4VSa1oiURTsKHC0IfjNwU2WzK6eqK8jWln4g15TVBnqmDteCJ501PGAocJhhqjZdtBEB6lnhLreFJKxmlKbeGrqLiSThVIbCdGzloasa6lpMQXHCME2boLpJgT7yWaemu6wBONbqGNVRS0PKIL7LckbjmQtR7K8I5qtqel+T/ChJTNIKLjdUMNIRyvOEko9YYl2cwQveBikCNawJKcLBbc7+JM92mysNvd/Fqp8a0k6CNEe7cnZrxlW0wQXaXjaktnRwNOGZKYiONwS7a1JVheq3WgJHlQUGKHKmp4KAxXR/ULURcNgoa4zhKSLpZR3kxRRb0NmD0OFn+UCS7CzI1nbP6+o4x47QZE5xRCt3ZagnYcvmpYQktXdk5YKXTzBC57kKEe0VVuiSYqapssMS3C9p2CKkHOg8B8Pa8p5atrIw3qezIWanMGa5HRDNF6RM9wcacl0N+Q8Z8hsIkSnaIIdHRUOEebAPy1zbCkhM062FCJtif7PU+UtoVXzWKqM1PxXO8cfdruhFQ/a6x3JKYagvVDhQEtNiyiiSQ7OsuRsZUku0CRNDs4Sog6KKjsZgk2bYJqijgsEenoKeniinRXBn/U3lgpPdyDZynQx8IiioMnCep5Ky8mjGs6Wty0l1hUQTcNWswS3WRp2kCNZwJG8omG8JphPUaFbC8lEfabwP7VtM9yoaNCAjpR41VNhrD9LkbN722v0CoZMByFzhaW+MyzRYEWFDQwN2M4/JiT76PuljT3VU/A36eaIThb+R9oZGOAJ9tewkgGvqOMNRWYjT/Cwu99Q8LqDE4TgbLWxJ1jaDDAERsFOFrobgjUsBScaguXU8kKm2RL19tRypSHnHNlHiIZqgufs4opgQdVdwxBNNFBR6kVFqb8ogimOzB6a6HTzrlDHEpYaxjiiA4TMQobkDg2vejjfwJGWmnbVFAw3H3hq2NyQfG7hz4aC+w3BbwbesG0swYayvpAs6++Ri1Vfzx93mFChvyN5xVHTS+0p9aqCAxyZ6ZacZyw5+7uuQkFPR9DDk9NOiE7X1PCYJVjVUqq7JlrHwWALF5nfHNGjApdpqgzx5OwilDhCiDYTgnc9waGW4BdLNNUQvOtpzDOWHDH8D7TR/A/85KljEQu3NREc4Pl/6B1Hhc8Umb5CsKMmGC9EPcxoT2amwHNCmeOEnOPbklnMkbOgIvO5UMOpQrS9UGVdt6iH/fURjhI/WOpaW9OKLYRod6HCUEdOX000wpDZQ6hwg6LgZfOqo1RfT/CrJzjekXOGhpc1VW71ZLbXyyp+93ILbC1kPtIEYx0FIx1VDrLoVzXRKRYWk809yYlC9ImcrinxtabKnzRJk3lAU1OLEN1j2zrYzr2myHRXJFf4h4QKT1qSTzTB5+ZNTzTRkAxX8FcLV2uS8eoQQ2aAkFzvCM72sJIcJET3WPjRk5wi32uSS9rfZajpWEvj9hW42F4o5NytSXYy8IKHay10VYdrcl4SkqscrXpMwyGOgtkajheSxdQqmpxP1L3t4R5PqasFnrQEjytq6qgp9Y09Qx9o4S1FzhUCn1kyHSzBWLemoSGvOqLNhZyBjmCaAUYpMgt4Ck7wBBMMwWKWgjsUwTaGVsxWC1mYoKiyqqeGKYqonSIRQ3KIkHO0pmAxTdBHkbOvfllfr+AA+7gnc50huVKYK393FOyg7rbPO/izI7hE4CnHHHnJ0ogNPRUGeUpsrZZTBJcrovUcJe51BPsr6GkJdhCCsZ6aTtMEb2pqWkqeVtDXE/QVggsU/Nl86d9RMF3DxvZTA58agu810RWawCiSzzXBeU3MMW9oyJUedvNEvQyNu1f10BSMddR1vaLCYpYa/mGocLSiYDcLbQz8aMn5iyF4xBNMs1P0QEOV7o5gaWGuzSeLue4tt3ro7y4Tgm4G/mopdZgl6q0o6KzJWE3mMksNr3r+a6CbT8g5wZNzT9O7fi/zpaOmnz3BRoqos+tv9zMbdpxsqDBOEewtJLt7cg5wtKKbvldpSzRRCD43VFheCI7yZLppggMVBS/KMAdHODJvOwq2NQSbKKKPLdFWQs7Fqo+mpl01JXYRgq8dnGLhTiFzqmWsUMdpllZdbKlyvSdYxhI9YghOtxR8LgSLWHK62mGGVoxzBE8LNWzqH9CUesQzFy5RQzTc56mhi6fgXEWwpKfE5Z7M05ZgZUPmo6auiv8YKzDYwWBLMErIbKHJvOwIrvEdhOBcQ9JdU1NHQ7CXn2XIDFBKU2WAgcX9UAUzDXWd5alwuyJ41Z9rjKLCL4aCp4WarhPm2rH+SaHUYE001JDZ2ZAzXPjdMpZWvC9wmqIB2lLhQ01D5jO06hghWMndbM7yRJMsoCj1vYbnFQVrW9jak3OlEJ3s/96+p33dEPRV5GxiqaGjIthUU6FFEZyqCa5qJrpBdzSw95IUnOPIrCUUjRZQFrbw5PR0R1qiYx3cb6nrWUMrBmmiBQxVHtTew5ICP/ip6g4hed/Akob/32wvBHsIOX83cI8hGeNeNPCIkPmXe8fPKx84OMSRM1MTdXSwjCZ4S30jVGhvqTRak/OVhgGazHuOCud5onEO1lJr6ecVyaOK6H7zqlBlIaHE0oroCgfvGJIdPcmfLNGLjpz7hZwZQpUbFME0A1cIJa7VNORkgfsMBatbKgwwJM9bSvQXeNOvbIjelg6WWvo5kvbKaJJNHexkKNHL9xRyFlH8Ti2riB5wVPhUk7nGkJnoCe428LR/wRGdYIlmWebCyxou1rCk4g/ShugBDX0V0ZQWkh0dOVsagkM0yV6OoLd5ye+pRlsCr0n+KiQrGuq5yJDzrTAXHtLUMduTDBVKrSm3eHL+6ijxhFDX9Z5gVU/wliHYTMiMFpKLNMEywu80wd3meoFmt6VbRMPenhrOc6DVe4pgXU8DnnHakLOIIrlF4FZPIw6R+zxBP0dyq6OOZ4Q5sLKCcz084ok+VsMMyQhNZmmBgX5xIXOEJTmi7VsGTvMTNdHHhpzdbE8Du2oKxgvBqQKdDDnTFOylCFaxR1syz2iqrOI/FEpNc3C6f11/7+ASS6l2inq2ciTrCCzgyemrCL5SVPjQkdPZUmGy2c9Sw9FtR1sS30RmsKPCS4rkIC/2U0MduwucYolGaPjKEyhzmiPYXagyWbYz8LWBDdzRimAXzxx4z8K9hpzlhLq+NiQ97HuKorMUfK/OVvC2JfiHUPCQI/q7J2gjK+tTDNxkCc4TMssqCs4TGtLVwQihyoAWgj9bosU80XGW6Ac9TJGziaUh5+hnFcHOnlaM1iRn29NaqGENTTTSUHCH2tWTeV0osUhH6psuVLjRUmGWhm6OZEshGeNowABHcJ2Bpy2ZszRcKkRXd2QuKVEeXnbfaEq825FguqfgfE2whlChSRMdron+LATTPQ2Z369t4B9C5gs/ylzv+CMmepIDPclFQl13W0rspPd1JOcbghGOEutqCv5qacURQl3dDKyvyJlqKXGPgcM9FfawJAMVmdcspcYKOZc4GjDYkFlK05olNMHyHn4zFNykyOxt99RkHlfwmiHo60l2EKI+mhreEKp080Tbug08BVPcgoqC5zWt+NLDTZ7oNSF51N1qie7Va3uCCwyZbkINf/NED6jzOsBdZjFN8oqG3wxVunqCSYYKf3EdhJyf9YWGf7tRU2oH3VHgPr1fe5J9hOgHd7xQ0y7qBwXr23aGErP0cm64JVjZwsOGqL+mhNgZmhJLW2oY4UhedsyBgzrCKrq7BmcpNVhR6jBPq64Vgi+kn6XE68pp8J5/+0wRHGOpsKenQn9DZntPzjRLZpDAdD2fnSgkG9tmIXnUwQ6WVighs7Yi2MxQ0N3CqYaCXkJ0oyOztMDJjmSSpcpvlrk0RMMOjmArQ04PRV1DO1FwhCVaUVPpKUM03JK5SxPsIWRu8/CGHi8UHChiqGFDTbSRJWeYUDDcH6vJWUxR4k1FXbMUwV6e4AJFXS8oMqsZKqzvYQ9DDQdZckY4aGsIhtlubbd2r3j4QBMoTamdPZk7O/Bf62lacZwneNjQoGcdVU7zJOd7ghsUHOkosagic6cnWc8+4gg285R6zZP5s1/LUbCKIznTwK36PkdwlOrl4U1LwfdCCa+IrvFkmgw1PCAUXKWo0sURXWcI2muKJlgyFzhynCY4RBOsqCjoI1R5zREco0n2Vt09BQtYSizgKNHfUmUrQ5UOCh51BFcLmY7umhYqXKQomOop8bUnWNNQcIiBcYaC6xzMNOS8JQQfeqKBmmglB+97ok/lfk3ygaHSyZaCRTzRxQo6GzLfa2jWBPepw+UmT7SQEJyiyRkhBLMVOfcoMjcK0eZChfUNzFAUzCsEN5vP/X1uP/n/aoMX+K+nw/Hjr/9xOo7j7Pju61tLcgvJpTWXNbfN5jLpi6VfCOviTktKlFusQixdEKWmEBUKNaIpjZRSSOXSgzaaKLdabrm1/9nZ+/f+vd/vz/v9+Xy+zZ7PRorYoZqyLrCwQdEAixxVOEXNNnjX2nUSRlkqGmWowk8lxR50JPy9Bo6qJXaXwNvREBvnThPEPrewryLhcAnj5WE15Fqi8W7R1sAuEu86S4ENikItFN4xkv9Af4nXSnUVcLiA9xzesFpivRRVeFKtsMRaKBhuSbjOELnAUtlSQUpXgdfB4Z1oSbnFEetbQ0IrAe+Y+pqnDcEJFj6S8LDZzZHwY4e3XONNlARraomNEt2bkvGsosA3ioyHm+6jCMbI59wqt4eeara28IzEmyPgoRaUOEDhTVdEJhmCoTWfC0p8aNkCp0oYqih2iqGi4yXeMkOsn4LdLLnmKfh/YogjNsPebeFGR4m9BJHLzB61XQ3BtpISfS2FugsK9FAtLWX1dCRcrCnUp44CNzuCowUZmxSRgYaE6Za0W2u/E7CVXCiI/UOR8aAm1+OSyE3mOUcwyc1zBBeoX1kiKy0Zfxck1Gsyulti11i83QTBF5Kg3pDQThFMVHiPSlK+0cSedng/VaS8bOZbtsBcTcZAR8JP5KeqQ1OYKAi20njdNNRpgnsU//K+JnaXJaGTomr7aYIphoRn9aeShJWKEq9LcozSF7QleEfDI5LYm5bgVkFkRwVDBCVu0DDIkGupo8TZBq+/pMQURYErJQmPKGKjNDkWOLx7Jd5QizdUweIaKrlP7SwJDhZvONjLkOsBBX9UpGxnydhXkfBLQ8IxgojQbLFnJf81JytSljclYYyEFyx0kVBvKWOFJmONpshGAcsduQY5giVNCV51eOdJYo/pLhbvM0uDHSevNKRcrKZIqnCtJeEsO95RoqcgGK4ocZcho1tTYtcZvH41pNQ7vA0WrhIfOSraIIntIAi+NXWCErdbkvrWwjRLrt0NKUdL6KSOscTOdMSOUtBHwL6OLA0vNSdynaWQEnCpIvKaIrJJEbvHkmuNhn6OjM8VkSGSqn1uYJCGHnq9I3aLhNME3t6GjIkO7xrNFumpyTNX/NrwX7CrIRiqqWijI9JO4d1iieykyfiposQIQ8YjjsjlBh6oHWbwRjgYJQn2NgSnNycmJAk3NiXhx44Sxykihxm8ybUwT1OVKySc7vi3OXVkdBJ4AyXBeksDXG0IhgtYY0lY5ahCD0ehborIk5aUWRJviMA7Xt5kyRjonrXENkm8yYqgs8VzgrJmClK20uMM3jRJ0FiQICQF9hdETlLQWRIb5ki6WDfWRPobvO6a4GP5mcOrNzDFELtTkONLh9dXE8xypEg7z8A9jkhrQ6Fhjlg/QVktJXxt4WXzT/03Q8IaQWSqIuEvloQ2mqC9Jfi7wRul4RX3pSPlzpoVlmCtI2jvKHCFhjcM3sN6lqF6HxnKelLjXWbwrpR4xzuCrTUZx2qq9oAh8p6ixCUGr78g8oyjRAtB5CZFwi80VerVpI0h+IeBxa6Zg6kWvpDHaioYYuEsRbDC3eOmC2JvGYLeioxGknL2UATNJN6hmtj1DlpLvDVmocYbrGCVJKOrg4X6DgddLA203BKMFngdJJFtFd7vJLm6KEpc5yjQrkk7M80SGe34X24nSex1Ra5Omgb71JKyg8SrU3i/kARKwWpH0kOGhKkObyfd0ZGjvyXlAkVZ4xRbYJ2irFMkFY1SwyWxr2oo4zlNiV+7zmaweFpT4kR3kaDAFW6xpSqzJay05FtYR4HmZhc9UxKbbfF2V8RG1MBmSaE+kmC6JnaRXK9gsiXhJHl/U0qM0WTcbyhwkYIvFGwjSbjfwhiJt8ZSQU+Bd5+marPMOkVkD0muxYLIfEuhh60x/J92itguihJSEMySVPQnTewnEm+620rTQEMsOfo4/kP/0ARvWjitlpSX7GxBgcMEsd3EEeYWvdytd+Saawi6aCIj1CkGb6Aj9rwhx16Cf3vAwFy5pyLhVonXzy51FDpdEblbkdJbUcEPDEFzQ8qNmhzzLTmmKWKbFCXeEuRabp6rxbvAtLF442QjQ+wEA9eL1xSR7Q0JXzlSHjJ4exq89yR0laScJ/FW6z4a73pFMEfDiRZvuvijIt86RaSFOl01riV2mD1UEvxGk/Geg5aWwGki1zgKPG9J2U8PEg8qYvMsZeytiTRXBMslCU8JSlxi8EabjwUldlDNLfzTUmCgxWsjqWCOHavYAqsknKFIO0yQ61VL5AVFxk6WhEaCAkdJgt9aSkzXlKNX2jEa79waYuc7gq0N3GDJGCBhoiTXUEPsdknCUE1CK0fwsiaylSF2uiDyO4XX3pFhNd7R4itFGc0k/ElBZwWvq+GC6szVeEoS/MZ+qylwpKNKv9Z469UOjqCjwlusicyTxG6VpNxcQ8IncoR4RhLbR+NdpGGmJWOcIzJGUuKPGpQg8rrG21dOMqQssJQ4RxH5jaUqnZuQ0F4Q+cjxLwPtpZbIAk3QTJHQWBE5S1BokoVtDd6lhqr9UpHSUxMcIYl9pojsb8h4SBOsMQcqvOWC2E8EVehqiJ1hrrAEbQxeK0NGZ0Gkq+guSRgniM23bIHVkqwx4hiHd7smaOyglyIyQuM978j4VS08J/A2G1KeMBRo4fBaSNhKUEZfQewVQ/C1I+MgfbEleEzCUw7mKXI0M3hd1EESVji8x5uQ41nxs1q4RMJCCXs7Iq9acpxn22oSDnQ/sJTxsCbHIYZiLyhY05TY0ZLIOQrGaSJDDN4t8pVaIrsqqFdEegtizc1iTew5Q4ayBDMUsQMkXocaYkc0hZua412siZ1rSXlR460zRJ5SlHGe5j801RLMlJTxtaOM3Q1pvxJ45zUlWFD7rsAbpfEm1JHxG0eh8w2R7QQVzBUw28FhFp5QZzq8t2rx2joqulYTWSuJdTYfWwqMFMcovFmSyJPNyLhE4E10pHzYjOC3huArRa571ZsGajQpQx38SBP5pyZB6lMU3khDnp0MBV51BE9o2E+TY5Ml2E8S7C0o6w1xvCZjf0HkVEHCzFoyNmqC+9wdcqN+Tp7jSDheE9ws8Y5V0NJCn2bk2tqSY4okdrEhx1iDN8cSudwepWmAGXKcJXK65H9to8jYQRH7SBF01ESUJdd0TayVInaWhLkOjlXE5irKGOnI6GSWGCJa482zBI9rCr0jyTVcEuzriC1vcr6mwFGSiqy5zMwxBH/TJHwjSPhL8+01kaaSUuMFKTcLEvaUePcrSmwn8DZrgikWb7CGPxkSjhQwrRk57tctmxLsb9sZvL9LSlyuSLlWkqOjwduo8b6Uv1DkmudIeFF2dHCgxVtk8dpIvHpBxhEOdhKk7OLIUSdJ+cSRY57B+0DgGUUlNfpthTfGkauzxrvTsUUaCVhlKeteTXCoJDCa2NOKhOmC4G1H8JBd4OBZReSRGkqcb/CO1PyLJTLB4j1q8JYaIutEjSLX8YKM+a6phdMsdLFUoV5RTm9JSkuDN8WcIon0NZMNZWh1q8C7SJEwV5HxrmnnTrf3KoJBlmCYI2ilSLlfEvlE4011NNgjgthzEua0oKK7JLE7HZHlEl60BLMVFewg4EWNt0ThrVNEVkkiTwpKXSWJzdRENgvKGq4IhjsiezgSFtsfCUq8qki5S1LRQeYQQ4nemmCkImWMw3tFUoUBZk4NOeZYEp4XRKTGa6wJjrWNHBVJR4m3FCnbuD6aak2WsMTh3SZImGCIPKNgsDpVwnsa70K31lCFJZYcwwSMFcQulGTsZuEaSdBXkPGZhu0FsdUO73RHjq8MPGGIfaGIbVTk6iuI3GFgucHrIQkmWSJdBd7BBu+uOryWAhY7+Lki9rK5wtEQzWwvtbqGhIMFwWRJsElsY4m9IIg9L6lCX0VklaPAYkfkZEGDnOWowlBJjtMUkcGK4Lg6EtoZInMUBVYLgn0UsdmCyCz7gIGHFfk+k1QwTh5We7A9x+IdJ6CvIkEagms0hR50eH9UnTQJ+2oiKyVlLFUE+8gBGu8MQ3CppUHesnjTHN4QB/UGPhCTHLFPHMFrCqa73gqObUJGa03wgbhHkrCfpEpzNLE7JDS25FMKhlhKKWKfCgqstLCPu1zBXy0J2ztwjtixBu8UTRn9LVtkmCN2iyFhtME70JHRQ1KVZXqKI/KNIKYMCYs1GUMEKbM1bKOI9LDXC7zbHS+bt+1MTWS9odA9DtrYtpbImQJ2VHh/lisEwaHqUk1kjKTAKknkBEXkbkdMGwq0dnhzLJF3NJH3JVwrqOB4Sca2hti75nmJN0WzxS6UxDYoEpxpa4htVlRjkYE7DZGzJVU72uC9IyhQL4i8YfGWSYLLNcHXloyz7QhNifmKSE9JgfGmuyLhc403Xm9vqcp6gXe3xuuv8F6VJNxkyTHEkHG2g0aKXL0MsXc1bGfgas2//dCONXiNLCX+5mB7eZIl1kHh7ajwpikyzlUUWOVOsjSQlsS+M0R+pPje/dzBXRZGO0rMtgQrLLG9VSu9n6CMXS3BhwYmSoIBhsjNBmZbgusE9BCPCP5triU4VhNbJfE+swSP27aayE8tuTpYYjtrYjMVGZdp2NpS1s6aBnKSHDsbKuplKbHM4a0wMFd/5/DmGyKrJSUaW4IBrqUhx0vyfzTBBLPIUcnZdrAkNsKR0sWRspumSns6Ch0v/qqIbBYUWKvPU/CFoyrDJGwSNFhbA/MlzKqjrO80hRbpKx0Jewsi/STftwGSlKc1JZyAzx05dhLEdnfQvhZOqiHWWEAHC7+30FuRcZUgaO5gpaIK+xsiHRUsqaPElTV40xQZQ107Q9BZE1nryDVGU9ZSQ47bmhBpLcYpUt7S+xuK/FiT8qKjwXYw5ypS2iuCv7q1gtgjhuBuB8LCFY5cUuCNtsQOFcT+4Ih9JX+k8Ea6v0iCIRZOtCT0Et00JW5UeC85Cg0ScK0k411HcG1zKtre3SeITBRk7WfwDhEvaYLTHP9le0m8By0JDwn4TlLW/aJOvGHxdjYUes+ScZigCkYQdNdEOhkiezgShqkx8ueKjI8lDfK2oNiOFvrZH1hS+tk7NV7nOmLHicGWEgubkXKdwdtZknCLJXaCpkrjZBtLZFsDP9CdxWsSr05Sxl6CMmoFbCOgryX40uDtamB7SVmXW4Ihlgpmq+00tBKUUa83WbjLUNkzDmY7cow1JDygyPGlhgGKYKz4vcV7QBNbJIgM11TUqZaMdwTeSguH6rOaw1JRKzaaGyxVm2EJ/uCIrVWUcZUkcp2grMsEjK+DMwS59jQk3Kd6SEq1d0S6uVmO4Bc1lDXTUcHjluCXEq+1OlBDj1pi9zgiXxnKuE0SqTXwhqbETW6RggMEnGl/q49UT2iCzgJvRwVXS2K/d6+ZkyUl7jawSVLit46EwxVljDZwoSQ20sDBihztHfk2yA8NVZghiXwrYHQdfKAOtzsayjhY9bY0yE2CWEeJ9xfzO423xhL5syS2TFJofO2pboHob0nY4GiAgRrvGQEDa/FWSsoaaYl0syRsEt3kWoH3B01shCXhTUWe9w3Bt44SC9QCh3eShQctwbaK2ApLroGCMlZrYqvlY3qYhM0aXpFkPOuoqJ3Dm6fxXrGwVF9gCWZagjPqznfkuMKQ8DPTQRO8ZqG1hPGKEm9IgpGW4DZDgTNriTxvFiq+Lz+0cKfp4wj6OCK9JSnzNSn9LFU7UhKZZMnYwcJ8s8yRsECScK4j5UOB95HFO0CzhY4xJxuCix0lDlEUeMdS6EZBkTsUkZ4K74dugyTXS7aNgL8aqjDfkCE0ZbwkCXpaWCKhl8P7VD5jxykivSyxyZrYERbe168LYu9ZYh86IkscgVLE7tWPKmJv11CgoyJltMEbrohtVAQfO4ImltiHEroYEs7RxAarVpY8AwXMcMReFOTYWe5iiLRQxJ5Q8DtJ8LQhWOhIeFESPGsILhbNDRljNbHzNRlTFbk2S3L0NOS6V1KFJYKUbSTcIIhM0wQ/s2TM0SRMNcQmSap3jCH4yhJZKSkwyRHpYYgsFeQ4U7xoCB7VVOExhXepo9ABBsYbvGWKXPME3lyH95YioZ0gssQRWWbI+FaSMkXijZXwgiTlYdPdkNLaETxlyDVIwqeaEus0aTcYcg0RVOkpR3CSJqIddK+90JCxzsDVloyrFd5ZAr4TBKfaWa6boEA7C7s6EpYaeFPjveooY72mjIccLHJ9HUwVlDhKkmutJDJBwnp1rvulJZggKDRfbXAkvC/4l3ozQOG9a8lxjx0i7nV4jSXc7vhe3OwIxjgSHjdEhhsif9YkPGlus3iLFDnWOFhtCZbJg0UbQcIaR67JjthoCyMEZRwhiXWyxO5QxI6w5NhT4U1WsJvDO60J34fW9hwzwlKij6ZAW9ne4L0s8C6XeBMEkd/LQy1VucBRot6QMlbivaBhoBgjqGiCJNhsqVp/S2SsG6DIONCR0dXhvWbJ+MRRZJkkuEjgDXJjFQW6SSL7GXK8Z2CZg7cVsbWGoKmEpzQ5elpiy8Ryg7dMkLLUEauzeO86CuwlSOlgYLojZWeJ9xM3S1PWfEfKl5ISLQ0MEKR8YOB2QfCxJBjrKPCN4f9MkaSsqoVXJBmP7EpFZ9UQfOoOFwSzBN4MQ8LsGrymlipcJQhmy0GaQjPqCHaXRwuCZwRbqK2Fg9wlClZqYicrIgMdZfxTQ0c7TBIbrChxmuzoKG8XRaSrIhhiyNFJkrC7oIAWMEOQa5aBekPCRknCo4IKPrYkvCDI8aYmY7WFtprgekcJZ3oLIqssCSMtFbQTJKwXYy3BY5oCh2iKPCpJOE+zRdpYgi6O2KmOAgvVCYaU4ySRek1sgyFhJ403QFHiVEmJHwtybO1gs8Hr5+BETQX3War0qZngYGgtVZtoqd6vFSk/UwdZElYqyjrF4HXUeFspIi9IGKf4j92pKGAdCYMVsbcV3kRF0N+R8LUd5PCsIGWoxDtBkCI0nKofdJQxT+LtZflvuc8Q3CjwWkq8KwUpHzkK/NmSsclCL0nseQdj5FRH5CNHSgtLiW80Of5HU9Hhlsga9bnBq3fEVltKfO5IaSTmGjjc4J0otcP7QsJUSQM8pEj5/wCuUuC2DWz8AAAAAElFTkSuQmCC");
+}
diff --git a/third-party/codemirror-3.15/theme/base16-dark.css b/third-party/codemirror-3.15/theme/base16-dark.css
new file mode 100644 (file)
index 0000000..7a818b7
--- /dev/null
@@ -0,0 +1,33 @@
+/*
+
+    Name:       Base16 Default Dark
+    Author:     Chris Kempson (http://chriskempson.com)
+
+    CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-chrome-devtools)
+    Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16)
+
+*/
+
+.cm-s-base16-dark.CodeMirror {background: #151515; color: #e0e0e0;}
+.cm-s-base16-dark div.CodeMirror-selected {background: #202020 !important;}
+.cm-s-base16-dark .CodeMirror-gutters {background: #151515; border-right: 0px;}
+.cm-s-base16-dark .CodeMirror-linenumber {color: #505050;}
+.cm-s-base16-dark .CodeMirror-cursor {border-left: 1px solid #b0b0b0 !important;}
+
+.cm-s-base16-dark span.cm-comment {color: #8f5536;}
+.cm-s-base16-dark span.cm-atom {color: #aa759f;}
+.cm-s-base16-dark span.cm-number {color: #aa759f;}
+
+.cm-s-base16-dark span.cm-property, .cm-s-base16-dark span.cm-attribute {color: #90a959;}
+.cm-s-base16-dark span.cm-keyword {color: #ac4142;}
+.cm-s-base16-dark span.cm-string {color: #f4bf75;}
+
+.cm-s-base16-dark span.cm-variable {color: #90a959;}
+.cm-s-base16-dark span.cm-variable-2 {color: #6a9fb5;}
+.cm-s-base16-dark span.cm-def {color: #d28445;}
+.cm-s-base16-dark span.cm-error {background: #ac4142; color: #b0b0b0;}
+.cm-s-base16-dark span.cm-bracket {color: #e0e0e0;}
+.cm-s-base16-dark span.cm-tag {color: #ac4142;}
+.cm-s-base16-dark span.cm-link {color: #aa759f;}
+
+.cm-s-base16-dark .CodeMirror-matchingbracket { text-decoration: underline; color: white !important;}
diff --git a/third-party/codemirror-3.15/theme/base16-light.css b/third-party/codemirror-3.15/theme/base16-light.css
new file mode 100644 (file)
index 0000000..a3b2d4d
--- /dev/null
@@ -0,0 +1,33 @@
+/*
+
+    Name:       Base16 Default Light
+    Author:     Chris Kempson (http://chriskempson.com)
+
+    CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-chrome-devtools)
+    Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16)
+
+*/
+
+.cm-s-base16-light.CodeMirror {background: #f5f5f5; color: #202020;}
+.cm-s-base16-light div.CodeMirror-selected {background: #e0e0e0 !important;}
+.cm-s-base16-light .CodeMirror-gutters {background: #f5f5f5; border-right: 0px;}
+.cm-s-base16-light .CodeMirror-linenumber {color: #b0b0b0;}
+.cm-s-base16-light .CodeMirror-cursor {border-left: 1px solid #505050 !important;}
+
+.cm-s-base16-light span.cm-comment {color: #8f5536;}
+.cm-s-base16-light span.cm-atom {color: #aa759f;}
+.cm-s-base16-light span.cm-number {color: #aa759f;}
+
+.cm-s-base16-light span.cm-property, .cm-s-base16-light span.cm-attribute {color: #90a959;}
+.cm-s-base16-light span.cm-keyword {color: #ac4142;}
+.cm-s-base16-light span.cm-string {color: #f4bf75;}
+
+.cm-s-base16-light span.cm-variable {color: #90a959;}
+.cm-s-base16-light span.cm-variable-2 {color: #6a9fb5;}
+.cm-s-base16-light span.cm-def {color: #d28445;}
+.cm-s-base16-light span.cm-error {background: #ac4142; color: #505050;}
+.cm-s-base16-light span.cm-bracket {color: #202020;}
+.cm-s-base16-light span.cm-tag {color: #ac4142;}
+.cm-s-base16-light span.cm-link {color: #aa759f;}
+
+.cm-s-base16-light .CodeMirror-matchingbracket { text-decoration: underline; color: white !important;}
diff --git a/third-party/codemirror-3.15/theme/blackboard.css b/third-party/codemirror-3.15/theme/blackboard.css
new file mode 100644 (file)
index 0000000..f2bde69
--- /dev/null
@@ -0,0 +1,25 @@
+/* Port of TextMate's Blackboard theme */
+
+.cm-s-blackboard.CodeMirror { background: #0C1021; color: #F8F8F8; }
+.cm-s-blackboard .CodeMirror-selected { background: #253B76 !important; }
+.cm-s-blackboard .CodeMirror-gutters { background: #0C1021; border-right: 0; }
+.cm-s-blackboard .CodeMirror-linenumber { color: #888; }
+.cm-s-blackboard .CodeMirror-cursor { border-left: 1px solid #A7A7A7 !important; }
+
+.cm-s-blackboard .cm-keyword { color: #FBDE2D; }
+.cm-s-blackboard .cm-atom { color: #D8FA3C; }
+.cm-s-blackboard .cm-number { color: #D8FA3C; }
+.cm-s-blackboard .cm-def { color: #8DA6CE; }
+.cm-s-blackboard .cm-variable { color: #FF6400; }
+.cm-s-blackboard .cm-operator { color: #FBDE2D;}
+.cm-s-blackboard .cm-comment { color: #AEAEAE; }
+.cm-s-blackboard .cm-string { color: #61CE3C; }
+.cm-s-blackboard .cm-string-2 { color: #61CE3C; }
+.cm-s-blackboard .cm-meta { color: #D8FA3C; }
+.cm-s-blackboard .cm-error { background: #9D1E15; color: #F8F8F8; }
+.cm-s-blackboard .cm-builtin { color: #8DA6CE; }
+.cm-s-blackboard .cm-tag { color: #8DA6CE; }
+.cm-s-blackboard .cm-attribute { color: #8DA6CE; }
+.cm-s-blackboard .cm-header { color: #FF6400; }
+.cm-s-blackboard .cm-hr { color: #AEAEAE; }
+.cm-s-blackboard .cm-link { color: #8DA6CE; }
diff --git a/third-party/codemirror-3.15/theme/cobalt.css b/third-party/codemirror-3.15/theme/cobalt.css
new file mode 100644 (file)
index 0000000..6095799
--- /dev/null
@@ -0,0 +1,18 @@
+.cm-s-cobalt.CodeMirror { background: #002240; color: white; }
+.cm-s-cobalt div.CodeMirror-selected { background: #b36539 !important; }
+.cm-s-cobalt .CodeMirror-gutters { background: #002240; border-right: 1px solid #aaa; }
+.cm-s-cobalt .CodeMirror-linenumber { color: #d0d0d0; }
+.cm-s-cobalt .CodeMirror-cursor { border-left: 1px solid white !important; }
+
+.cm-s-cobalt span.cm-comment { color: #08f; }
+.cm-s-cobalt span.cm-atom { color: #845dc4; }
+.cm-s-cobalt span.cm-number, .cm-s-cobalt span.cm-attribute { color: #ff80e1; }
+.cm-s-cobalt span.cm-keyword { color: #ffee80; }
+.cm-s-cobalt span.cm-string { color: #3ad900; }
+.cm-s-cobalt span.cm-meta { color: #ff9d00; }
+.cm-s-cobalt span.cm-variable-2, .cm-s-cobalt span.cm-tag { color: #9effff; }
+.cm-s-cobalt span.cm-variable-3, .cm-s-cobalt span.cm-def { color: white; }
+.cm-s-cobalt span.cm-error { color: #9d1e15; }
+.cm-s-cobalt span.cm-bracket { color: #d8d8d8; }
+.cm-s-cobalt span.cm-builtin, .cm-s-cobalt span.cm-special { color: #ff9e59; }
+.cm-s-cobalt span.cm-link { color: #845dc4; }
diff --git a/third-party/codemirror-3.15/theme/eclipse.css b/third-party/codemirror-3.15/theme/eclipse.css
new file mode 100644 (file)
index 0000000..4137bbe
--- /dev/null
@@ -0,0 +1,25 @@
+.cm-s-eclipse span.cm-meta {color: #FF1717;}
+.cm-s-eclipse span.cm-keyword { line-height: 1em; font-weight: bold; color: #7F0055; }
+.cm-s-eclipse span.cm-atom {color: #219;}
+.cm-s-eclipse span.cm-number {color: #164;}
+.cm-s-eclipse span.cm-def {color: #00f;}
+.cm-s-eclipse span.cm-variable {color: black;}
+.cm-s-eclipse span.cm-variable-2 {color: #0000C0;}
+.cm-s-eclipse span.cm-variable-3 {color: #0000C0;}
+.cm-s-eclipse span.cm-property {color: black;}
+.cm-s-eclipse span.cm-operator {color: black;}
+.cm-s-eclipse span.cm-comment {color: #3F7F5F;}
+.cm-s-eclipse span.cm-string {color: #2A00FF;}
+.cm-s-eclipse span.cm-string-2 {color: #f50;}
+.cm-s-eclipse span.cm-error {color: #f00;}
+.cm-s-eclipse span.cm-qualifier {color: #555;}
+.cm-s-eclipse span.cm-builtin {color: #30a;}
+.cm-s-eclipse span.cm-bracket {color: #cc7;}
+.cm-s-eclipse span.cm-tag {color: #170;}
+.cm-s-eclipse span.cm-attribute {color: #00c;}
+.cm-s-eclipse span.cm-link {color: #219;}
+
+.cm-s-eclipse .CodeMirror-matchingbracket {
+       outline:1px solid grey;
+       color:black !important;
+}
diff --git a/third-party/codemirror-3.15/theme/elegant.css b/third-party/codemirror-3.15/theme/elegant.css
new file mode 100644 (file)
index 0000000..d0ce0cb
--- /dev/null
@@ -0,0 +1,10 @@
+.cm-s-elegant span.cm-number, .cm-s-elegant span.cm-string, .cm-s-elegant span.cm-atom {color: #762;}
+.cm-s-elegant span.cm-comment {color: #262; font-style: italic; line-height: 1em;}
+.cm-s-elegant span.cm-meta {color: #555; font-style: italic; line-height: 1em;}
+.cm-s-elegant span.cm-variable {color: black;}
+.cm-s-elegant span.cm-variable-2 {color: #b11;}
+.cm-s-elegant span.cm-qualifier {color: #555;}
+.cm-s-elegant span.cm-keyword {color: #730;}
+.cm-s-elegant span.cm-builtin {color: #30a;}
+.cm-s-elegant span.cm-error {background-color: #fdd;}
+.cm-s-elegant span.cm-link {color: #762;}
diff --git a/third-party/codemirror-3.15/theme/erlang-dark.css b/third-party/codemirror-3.15/theme/erlang-dark.css
new file mode 100644 (file)
index 0000000..cf5bf2b
--- /dev/null
@@ -0,0 +1,21 @@
+.cm-s-erlang-dark.CodeMirror { background: #002240; color: white; }
+.cm-s-erlang-dark div.CodeMirror-selected { background: #b36539 !important; }
+.cm-s-erlang-dark .CodeMirror-gutters { background: #002240; border-right: 1px solid #aaa; }
+.cm-s-erlang-dark .CodeMirror-linenumber { color: #d0d0d0; }
+.cm-s-erlang-dark .CodeMirror-cursor { border-left: 1px solid white !important; }
+
+.cm-s-erlang-dark span.cm-atom       { color: #845dc4; }
+.cm-s-erlang-dark span.cm-attribute  { color: #ff80e1; }
+.cm-s-erlang-dark span.cm-bracket    { color: #ff9d00; }
+.cm-s-erlang-dark span.cm-builtin    { color: #eaa; }
+.cm-s-erlang-dark span.cm-comment    { color: #77f; }
+.cm-s-erlang-dark span.cm-def        { color: #e7a; }
+.cm-s-erlang-dark span.cm-error      { color: #9d1e15; }
+.cm-s-erlang-dark span.cm-keyword    { color: #ffee80; }
+.cm-s-erlang-dark span.cm-meta       { color: #50fefe; }
+.cm-s-erlang-dark span.cm-number     { color: #ffd0d0; }
+.cm-s-erlang-dark span.cm-operator   { color: #d11; }
+.cm-s-erlang-dark span.cm-string     { color: #3ad900; }
+.cm-s-erlang-dark span.cm-tag        { color: #9effff; }
+.cm-s-erlang-dark span.cm-variable   { color: #50fe50; }
+.cm-s-erlang-dark span.cm-variable-2 { color: #e0e; }
diff --git a/third-party/codemirror-3.15/theme/lesser-dark.css b/third-party/codemirror-3.15/theme/lesser-dark.css
new file mode 100644 (file)
index 0000000..0bd08f5
--- /dev/null
@@ -0,0 +1,44 @@
+/*
+http://lesscss.org/ dark theme
+Ported to CodeMirror by Peter Kroon
+*/
+.cm-s-lesser-dark {
+  line-height: 1.3em;
+}
+.cm-s-lesser-dark {
+  font-family: 'Bitstream Vera Sans Mono', 'DejaVu Sans Mono', 'Monaco', Courier, monospace !important;
+}
+
+.cm-s-lesser-dark.CodeMirror { background: #262626; color: #EBEFE7; text-shadow: 0 -1px 1px #262626; }
+.cm-s-lesser-dark div.CodeMirror-selected {background: #45443B !important;} /* 33322B*/
+.cm-s-lesser-dark .CodeMirror-cursor { border-left: 1px solid white !important; }
+.cm-s-lesser-dark pre { padding: 0 8px; }/*editable code holder*/
+
+.cm-s-lesser-dark.CodeMirror span.CodeMirror-matchingbracket { color: #7EFC7E; }/*65FC65*/
+
+.cm-s-lesser-dark .CodeMirror-gutters { background: #262626; border-right:1px solid #aaa; }
+.cm-s-lesser-dark .CodeMirror-linenumber { color: #777; }
+
+.cm-s-lesser-dark span.cm-keyword { color: #599eff; }
+.cm-s-lesser-dark span.cm-atom { color: #C2B470; }
+.cm-s-lesser-dark span.cm-number { color: #B35E4D; }
+.cm-s-lesser-dark span.cm-def {color: white;}
+.cm-s-lesser-dark span.cm-variable { color:#D9BF8C; }
+.cm-s-lesser-dark span.cm-variable-2 { color: #669199; }
+.cm-s-lesser-dark span.cm-variable-3 { color: white; }
+.cm-s-lesser-dark span.cm-property {color: #92A75C;}
+.cm-s-lesser-dark span.cm-operator {color: #92A75C;}
+.cm-s-lesser-dark span.cm-comment { color: #666; }
+.cm-s-lesser-dark span.cm-string { color: #BCD279; }
+.cm-s-lesser-dark span.cm-string-2 {color: #f50;}
+.cm-s-lesser-dark span.cm-meta { color: #738C73; }
+.cm-s-lesser-dark span.cm-error { color: #9d1e15; }
+.cm-s-lesser-dark span.cm-qualifier {color: #555;}
+.cm-s-lesser-dark span.cm-builtin { color: #ff9e59; }
+.cm-s-lesser-dark span.cm-bracket { color: #EBEFE7; }
+.cm-s-lesser-dark span.cm-tag { color: #669199; }
+.cm-s-lesser-dark span.cm-attribute {color: #00c;}
+.cm-s-lesser-dark span.cm-header {color: #a0a;}
+.cm-s-lesser-dark span.cm-quote {color: #090;}
+.cm-s-lesser-dark span.cm-hr {color: #999;}
+.cm-s-lesser-dark span.cm-link {color: #00c;}
diff --git a/third-party/codemirror-3.15/theme/midnight.css b/third-party/codemirror-3.15/theme/midnight.css
new file mode 100644 (file)
index 0000000..bc2d49b
--- /dev/null
@@ -0,0 +1,43 @@
+/* Based on the theme at http://bonsaiden.github.com/JavaScript-Garden */
+
+/*<!--match-->*/
+.cm-s-midnight span.CodeMirror-matchhighlight { background: #494949 }
+.cm-s-midnight.CodeMirror-focused span.CodeMirror-matchhighlight { background: #314D67 !important; }
+
+/*<!--activeline-->*/
+.cm-s-midnight .activeline {background: #253540 !important;}
+
+.cm-s-midnight.CodeMirror {
+    background: #0F192A;
+    color: #D1EDFF;
+}
+
+.cm-s-midnight.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}
+
+.cm-s-midnight div.CodeMirror-selected {background: #314D67 !important;}
+.cm-s-midnight .CodeMirror-gutters {background: #0F192A; border-right: 1px solid;}
+.cm-s-midnight .CodeMirror-linenumber {color: #D0D0D0;}
+.cm-s-midnight .CodeMirror-cursor {
+    border-left: 1px solid #F8F8F0 !important;
+}
+
+.cm-s-midnight span.cm-comment {color: #428BDD;}
+.cm-s-midnight span.cm-atom {color: #AE81FF;}
+.cm-s-midnight span.cm-number {color: #D1EDFF;}
+
+.cm-s-midnight span.cm-property, .cm-s-midnight span.cm-attribute {color: #A6E22E;}
+.cm-s-midnight span.cm-keyword {color: #E83737;}
+.cm-s-midnight span.cm-string {color: #1DC116;}
+
+.cm-s-midnight span.cm-variable {color: #FFAA3E;}
+.cm-s-midnight span.cm-variable-2 {color: #FFAA3E;}
+.cm-s-midnight span.cm-def {color: #4DD;}
+.cm-s-midnight span.cm-error {background: #F92672; color: #F8F8F0;}
+.cm-s-midnight span.cm-bracket {color: #D1EDFF;}
+.cm-s-midnight span.cm-tag {color: #008;}
+.cm-s-midnight span.cm-link {color: #AE81FF;}
+
+.cm-s-midnight .CodeMirror-matchingbracket {
+  text-decoration: underline;
+  color: white !important;
+}
diff --git a/third-party/codemirror-3.15/theme/monokai.css b/third-party/codemirror-3.15/theme/monokai.css
new file mode 100644 (file)
index 0000000..a0b3c7c
--- /dev/null
@@ -0,0 +1,28 @@
+/* Based on Sublime Text's Monokai theme */
+
+.cm-s-monokai.CodeMirror {background: #272822; color: #f8f8f2;}
+.cm-s-monokai div.CodeMirror-selected {background: #49483E !important;}
+.cm-s-monokai .CodeMirror-gutters {background: #272822; border-right: 0px;}
+.cm-s-monokai .CodeMirror-linenumber {color: #d0d0d0;}
+.cm-s-monokai .CodeMirror-cursor {border-left: 1px solid #f8f8f0 !important;}
+
+.cm-s-monokai span.cm-comment {color: #75715e;}
+.cm-s-monokai span.cm-atom {color: #ae81ff;}
+.cm-s-monokai span.cm-number {color: #ae81ff;}
+
+.cm-s-monokai span.cm-property, .cm-s-monokai span.cm-attribute {color: #a6e22e;}
+.cm-s-monokai span.cm-keyword {color: #f92672;}
+.cm-s-monokai span.cm-string {color: #e6db74;}
+
+.cm-s-monokai span.cm-variable {color: #a6e22e;}
+.cm-s-monokai span.cm-variable-2 {color: #9effff;}
+.cm-s-monokai span.cm-def {color: #fd971f;}
+.cm-s-monokai span.cm-error {background: #f92672; color: #f8f8f0;}
+.cm-s-monokai span.cm-bracket {color: #f8f8f2;}
+.cm-s-monokai span.cm-tag {color: #f92672;}
+.cm-s-monokai span.cm-link {color: #ae81ff;}
+
+.cm-s-monokai .CodeMirror-matchingbracket {
+  text-decoration: underline;
+  color: white !important;
+}
diff --git a/third-party/codemirror-3.15/theme/neat.css b/third-party/codemirror-3.15/theme/neat.css
new file mode 100644 (file)
index 0000000..8a307f8
--- /dev/null
@@ -0,0 +1,9 @@
+.cm-s-neat span.cm-comment { color: #a86; }
+.cm-s-neat span.cm-keyword { line-height: 1em; font-weight: bold; color: blue; }
+.cm-s-neat span.cm-string { color: #a22; }
+.cm-s-neat span.cm-builtin { line-height: 1em; font-weight: bold; color: #077; }
+.cm-s-neat span.cm-special { line-height: 1em; font-weight: bold; color: #0aa; }
+.cm-s-neat span.cm-variable { color: black; }
+.cm-s-neat span.cm-number, .cm-s-neat span.cm-atom { color: #3a3; }
+.cm-s-neat span.cm-meta {color: #555;}
+.cm-s-neat span.cm-link { color: #3a3; }
diff --git a/third-party/codemirror-3.15/theme/night.css b/third-party/codemirror-3.15/theme/night.css
new file mode 100644 (file)
index 0000000..8804a39
--- /dev/null
@@ -0,0 +1,21 @@
+/* Loosely based on the Midnight Textmate theme */
+
+.cm-s-night.CodeMirror { background: #0a001f; color: #f8f8f8; }
+.cm-s-night div.CodeMirror-selected { background: #447 !important; }
+.cm-s-night .CodeMirror-gutters { background: #0a001f; border-right: 1px solid #aaa; }
+.cm-s-night .CodeMirror-linenumber { color: #f8f8f8; }
+.cm-s-night .CodeMirror-cursor { border-left: 1px solid white !important; }
+
+.cm-s-night span.cm-comment { color: #6900a1; }
+.cm-s-night span.cm-atom { color: #845dc4; }
+.cm-s-night span.cm-number, .cm-s-night span.cm-attribute { color: #ffd500; }
+.cm-s-night span.cm-keyword { color: #599eff; }
+.cm-s-night span.cm-string { color: #37f14a; }
+.cm-s-night span.cm-meta { color: #7678e2; }
+.cm-s-night span.cm-variable-2, .cm-s-night span.cm-tag { color: #99b2ff; }
+.cm-s-night span.cm-variable-3, .cm-s-night span.cm-def { color: white; }
+.cm-s-night span.cm-error { color: #9d1e15; }
+.cm-s-night span.cm-bracket { color: #8da6ce; }
+.cm-s-night span.cm-comment { color: #6900a1; }
+.cm-s-night span.cm-builtin, .cm-s-night span.cm-special { color: #ff9e59; }
+.cm-s-night span.cm-link { color: #845dc4; }
diff --git a/third-party/codemirror-3.15/theme/rubyblue.css b/third-party/codemirror-3.15/theme/rubyblue.css
new file mode 100644 (file)
index 0000000..23c0cc7
--- /dev/null
@@ -0,0 +1,21 @@
+.cm-s-rubyblue { font-family: Trebuchet, Verdana, sans-serif; }        /* - customized editor font - */
+
+.cm-s-rubyblue.CodeMirror { background: #112435; color: white; }
+.cm-s-rubyblue div.CodeMirror-selected { background: #38566F !important; }
+.cm-s-rubyblue .CodeMirror-gutters { background: #1F4661; border-right: 7px solid #3E7087; }
+.cm-s-rubyblue .CodeMirror-linenumber { color: white; }
+.cm-s-rubyblue .CodeMirror-cursor { border-left: 1px solid white !important; }
+
+.cm-s-rubyblue span.cm-comment { color: #999; font-style:italic; line-height: 1em; }
+.cm-s-rubyblue span.cm-atom { color: #F4C20B; }
+.cm-s-rubyblue span.cm-number, .cm-s-rubyblue span.cm-attribute { color: #82C6E0; }
+.cm-s-rubyblue span.cm-keyword { color: #F0F; }
+.cm-s-rubyblue span.cm-string { color: #F08047; }
+.cm-s-rubyblue span.cm-meta { color: #F0F; }
+.cm-s-rubyblue span.cm-variable-2, .cm-s-rubyblue span.cm-tag { color: #7BD827; }
+.cm-s-rubyblue span.cm-variable-3, .cm-s-rubyblue span.cm-def { color: white; }
+.cm-s-rubyblue span.cm-error { color: #AF2018; }
+.cm-s-rubyblue span.cm-bracket { color: #F0F; }
+.cm-s-rubyblue span.cm-link { color: #F4C20B; }
+.cm-s-rubyblue span.CodeMirror-matchingbracket { color:#F0F !important; }
+.cm-s-rubyblue span.cm-builtin, .cm-s-rubyblue span.cm-special { color: #FF9D00; }
diff --git a/third-party/codemirror-3.15/theme/solarized.css b/third-party/codemirror-3.15/theme/solarized.css
new file mode 100644 (file)
index 0000000..06a6c7f
--- /dev/null
@@ -0,0 +1,207 @@
+/*
+Solarized theme for code-mirror
+http://ethanschoonover.com/solarized
+*/
+
+/*
+Solarized color pallet
+http://ethanschoonover.com/solarized/img/solarized-palette.png
+*/
+
+.solarized.base03 { color: #002b36; }
+.solarized.base02 { color: #073642; }
+.solarized.base01 { color: #586e75; }
+.solarized.base00 { color: #657b83; }
+.solarized.base0 { color: #839496; }
+.solarized.base1 { color: #93a1a1; }
+.solarized.base2 { color: #eee8d5; }
+.solarized.base3  { color: #fdf6e3; }
+.solarized.solar-yellow  { color: #b58900; }
+.solarized.solar-orange  { color: #cb4b16; }
+.solarized.solar-red { color: #dc322f; }
+.solarized.solar-magenta { color: #d33682; }
+.solarized.solar-violet  { color: #6c71c4; }
+.solarized.solar-blue { color: #268bd2; }
+.solarized.solar-cyan { color: #2aa198; }
+.solarized.solar-green { color: #859900; }
+
+/* Color scheme for code-mirror */
+
+.cm-s-solarized {
+  line-height: 1.45em;
+  font-family: Menlo,Monaco,"Andale Mono","lucida console","Courier New",monospace !important;
+  color-profile: sRGB;
+  rendering-intent: auto;
+}
+.cm-s-solarized.cm-s-dark {
+  color: #839496;
+  background-color:  #002b36;
+  text-shadow: #002b36 0 1px;
+}
+.cm-s-solarized.cm-s-light {
+  background-color: #fdf6e3;
+  color: #657b83;
+  text-shadow: #eee8d5 0 1px;
+}
+
+.cm-s-solarized .CodeMirror-widget {
+  text-shadow: none;
+}
+
+
+.cm-s-solarized .cm-keyword { color: #cb4b16 }
+.cm-s-solarized .cm-atom { color: #d33682; }
+.cm-s-solarized .cm-number { color: #d33682; }
+.cm-s-solarized .cm-def { color: #2aa198; }
+
+.cm-s-solarized .cm-variable { color: #268bd2; }
+.cm-s-solarized .cm-variable-2 { color: #b58900; }
+.cm-s-solarized .cm-variable-3 { color: #6c71c4; }
+
+.cm-s-solarized .cm-property { color: #2aa198; }
+.cm-s-solarized .cm-operator {color: #6c71c4;}
+
+.cm-s-solarized .cm-comment { color: #586e75; font-style:italic; }
+
+.cm-s-solarized .cm-string { color: #859900; }
+.cm-s-solarized .cm-string-2 { color: #b58900; }
+
+.cm-s-solarized .cm-meta { color: #859900; }
+.cm-s-solarized .cm-error,
+.cm-s-solarized .cm-invalidchar {
+  color: #586e75;
+  border-bottom: 1px dotted #dc322f;
+}
+.cm-s-solarized .cm-qualifier { color: #b58900; }
+.cm-s-solarized .cm-builtin { color: #d33682; }
+.cm-s-solarized .cm-bracket { color: #cb4b16; }
+.cm-s-solarized .CodeMirror-matchingbracket { color: #859900; }
+.cm-s-solarized .CodeMirror-nonmatchingbracket { color: #dc322f; }
+.cm-s-solarized .cm-tag { color: #93a1a1 }
+.cm-s-solarized .cm-attribute {  color: #2aa198; }
+.cm-s-solarized .cm-header { color: #586e75; }
+.cm-s-solarized .cm-quote { color: #93a1a1; }
+.cm-s-solarized .cm-hr {
+  color: transparent;
+  border-top: 1px solid #586e75;
+  display: block;
+}
+.cm-s-solarized .cm-link { color: #93a1a1; cursor: pointer; }
+.cm-s-solarized .cm-special { color: #6c71c4; }
+.cm-s-solarized .cm-em {
+  color: #999;
+  text-decoration: underline;
+  text-decoration-style: dotted;
+}
+.cm-s-solarized .cm-strong { color: #eee; }
+.cm-s-solarized .cm-tab:before {
+  content: "➤";   /*visualize tab character*/
+  color: #586e75;
+}
+
+.cm-s-solarized.cm-s-dark .CodeMirror-focused .CodeMirror-selected {
+  background: #386774;
+  color: inherit;
+}
+
+.cm-s-solarized.cm-s-dark ::selection {
+  background: #386774;
+  color: inherit;
+}
+
+.cm-s-solarized.cm-s-dark .CodeMirror-selected {
+  background: #586e75;
+}
+
+.cm-s-solarized.cm-s-light .CodeMirror-focused .CodeMirror-selected {
+  background: #eee8d5;
+  color: inherit;
+}
+
+.cm-s-solarized.cm-s-light ::selection {
+  background: #eee8d5;
+  color: inherit;
+}
+
+.cm-s-solarized.cm-s-light .CodeMirror-selected {
+  background: #93a1a1;
+}
+
+
+
+/* Editor styling */
+
+
+
+/* Little shadow on the view-port of the buffer view */
+.cm-s-solarized.CodeMirror {
+  -moz-box-shadow: inset 7px 0 12px -6px #000;
+  -webkit-box-shadow: inset 7px 0 12px -6px #000;
+  box-shadow: inset 7px 0 12px -6px #000;
+}
+
+/* Gutter border and some shadow from it  */
+.cm-s-solarized .CodeMirror-gutters {
+  padding: 0 15px 0 10px;
+  box-shadow: 0 10px 20px black;
+  border-right: 1px solid;
+}
+
+/* Gutter colors and line number styling based of color scheme (dark / light) */
+
+/* Dark */
+.cm-s-solarized.cm-s-dark .CodeMirror-gutters {
+  background-color: #073642;
+  border-color: #00232c;
+}
+
+.cm-s-solarized.cm-s-dark .CodeMirror-linenumber {
+  text-shadow: #021014 0 -1px;
+}
+
+/* Light */
+.cm-s-solarized.cm-s-light .CodeMirror-gutters {
+  background-color: #eee8d5;
+  border-color: #eee8d5;
+}
+
+/* Common */
+.cm-s-solarized .CodeMirror-linenumber {
+  color: #586e75;
+}
+
+.cm-s-solarized .CodeMirror-gutter .CodeMirror-gutter-text {
+  color: #586e75;
+}
+
+.cm-s-solarized .CodeMirror-lines {
+  padding-left: 5px;
+}
+
+.cm-s-solarized .CodeMirror-lines .CodeMirror-cursor {
+  border-left: 1px solid #819090;
+}
+
+/*
+Active line. Negative margin compensates left padding of the text in the
+view-port
+*/
+.cm-s-solarized .activeline {
+  margin-left: -20px;
+}
+
+.cm-s-solarized.cm-s-dark .activeline {
+  background: rgba(255, 255, 255, 0.05);
+
+}
+.cm-s-solarized.cm-s-light .activeline {
+  background: rgba(0, 0, 0, 0.05);
+}
+
+/*
+View-port and gutter both get little noise background to give it a real feel.
+*/
+.cm-s-solarized.CodeMirror,
+.cm-s-solarized .CodeMirror-gutters {
+  background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAQAAAAHUWYVAABFFUlEQVQYGbzBCeDVU/74/6fj9HIcx/FRHx9JCFmzMyGRURhLZIkUsoeRfUjS2FNDtr6WkMhO9sm+S8maJfu+Jcsg+/o/c+Z4z/t97/vezy3z+z8ekGlnYICG/o7gdk+wmSHZ1z4pJItqapjoKXWahm8NmV6eOTbWUOp6/6a/XIg6GQqmenJ2lDHyvCFZ2cBDbmtHA043VFhHwXxClWmeYAdLhV00Bd85go8VmaFCkbVkzlQENzfBDZ5gtN7HwF0KDrTwJ0dypSOzpaKCMwQHKTIreYIxlmhXTzTWkVm+LTynZhiSBT3RZQ7aGfjGEd3qyXQ1FDymqbKxpspERQN2MiRjNZlFFQXfCNFm9nM1zpAsoYjmtRTc5ajwuaXc5xrWskT97RaKzAGe5ARHhVUsDbjKklziiX5WROcJwSNCNI+9w1Jwv4Zb2r7lCMZ4oq5C0EdTx+2GzNuKpJ+iFf38JEWkHJn9DNF7mmBDITrWEg0VWL3pHU20tSZnuqWu+R3BtYa8XxV1HO7GyD32UkOpL/yDloINFTmvtId+nmAjxRw40VMwVKiwrKLE4bK5UOVntYwhOcSSXKrJHKPJedocpGjVz/ZMIbnYUPB10/eKCrs5apqpgVmWzBYWpmtKHecJPjaUuEgRDDaU0oZghCJ6zNMQ5ZhDYx05r5v2muQdM0EILtXUsaKiQX9WMEUotagQzFbUNN6NUPC2nm5pxEWGCjMc3GdJHjSU2kORLK/JGSrkfGEIjncU/CYUnOipoYemwj8tST9NsJmB7TUVXtbUtXATJVZXBMvYeTXJfobgJUPmGMP/yFaWonaa6BcFO3nqcIqCozSZoZoSr1g4zJOzuyGnxTEX3lUEJ7WcZgme8ddaWvWJo2AJR9DZU3CUIbhCSG6ybSwN6qtJVnCU2svDTP2ZInOw2cBTrqtQahtNZn9NcJ4l2NaSmSkkP1noZWnVwkLmdUPOwLZEwy2Z3S3R+4rIG9hcbpPXHFVWcQdZkn2FOta3cKWQnNRC5g1LsJah4GCzSVsKnCOY5OAFRTBekyyryeyilhFKva75r4Mc0aWanGEaThcy31s439KKxTzJYY5WTHPU1FtIHjQU3Oip4xlNzj/lBw23dYZVliQa7WAXf4shetcQfatI+jWRDBPmyNeW6A1P5kdDgyYJlba0BIM8BZu1JfrFwItyjcAMR3K0BWOIrtMEXyhyrlVEx3ui5dUBjmB/Q3CXW85R4mBD0s7B+4q5tKUjOlb9qqmhi5AZ6GFIC5HXtOobdYGlVdMVbNJ8toNTFcHxnoL+muBagcctjWnbNMuR00uI7nQESwg5q2qqrKWIfrNUmeQocY6HuyxJV02wj36w00yhpmUFenv4p6fUkZYqLyuinx2RGOjhCXYyJF84oiU00YMOOhhquNdfbOB7gU88pY4xJO8LVdp6/q2voeB4R04vIdhSE40xZObx1HGGJ/ja0LBthFInKaLPPFzuCaYaoj8JjPME8yoyxo6zlBqkiUZYgq00OYMswbWO5NGmq+xhipxHLRW29ARjNKXO0wRnear8XSg4XFPLKEPUS1GqvyLwiuBUoa7zpZ0l5xxFwWmWZC1H5h5FwU8eQ7K+g8UcVY6TMQreVQT/8uQ8Z+ALIXnSEa2pYZQneE9RZbSBNYXfWYJzW/h/4j4Dp1tYVcFIC5019Vyi4ThPqSFCzjGWaHQTBU8q6vrVwgxP9Lkm840imWKpcLCjYTtrKuwvsKSnrvHCXGkSMk9p6lhckfRpIeis+N2PiszT+mFLspyGleUhDwcLrZqmyeylxwjBcKHEapqkmyangyLZRVOijwOtCY5SsG5zL0OwlCJ4y5KznF3EUNDDrinwiyLZRzOXtlBbK5ITHFGLp8Q0R6ab6mS7enI2cFrxOyHvOCFaT1HThS1krjCwqWeurCkk+willhCC+RSZnRXBiZaC5RXRIZYKp2lyfrHwiKPKR0JDzrdU2EFgpidawlFDR6FgXUMNa+g1FY3bUQh2cLCwosRdnuQTS/S+JVrGLeWIvtQUvONJxlqSQYYKpwoN2kaocLjdVsis4Mk80ESF2YpSkzwldjHkjFCUutI/r+EHDU8oCs6yzL3PhWiEooZdFMkymlas4AcI3KmoMMNSQ3tHzjGWCrcJJdYyZC7QFGwjRL9p+MrRkAGWzIaWCn9W0F3TsK01c2ZvQw0byvxuQU0r1lM0qJO7wW0kRIMdDTtXEdzi4VIh+EoIHm0mWtAtpCixlabgn83fKTI7anJe9ST7WIK1DMGpQmYeA58ImV6ezOGOzK2Kgq01pd60cKWiUi9Lievb/0vIDPHQ05Kzt4ddPckQBQtoaurjyHnek/nKzpQLrVgKPjIkh2v4uyezpv+Xoo7fPFXaGFp1vaLKxQ4uUpQQS5VuQs7BCq4xRJv7fwpVvvFEB3j+620haOuocqMhWd6TTPAEx+mdFNGHdranFe95WrWmIvlY4F1Dle2ECgc6cto7SryuqGGGha0tFQ5V53migUKmg6XKAo4qS3mik+0OZpAhOLeZKicacgaYcyx5hypYQE02ZA4xi/pNhOQxR4klNKyqacj+mpxnLTnnGSo85++3ZCZq6lrZkXlGEX3o+C9FieccJbZWVFjC0Yo1FZnJhoYMFoI1hEZ9r6hwg75HwzBNhbZCdJEfJwTPGzJvaKImw1yYX1HDAmpXR+ZJQ/SmgqMNVQb5vgamGwLtt7VwvP7Qk1xpiM5x5Cyv93E06MZmgs0Nya2azIKOYKCGBQQW97RmhKNKF02JZqHEJ4o58qp7X5EcZmc56trXEqzjCBZ1MFGR87Ql2tSTs6CGxS05PTzRQorkbw7aKoKXFDXsYW42VJih/q+FP2BdTzDTwVqOYB13liM50vG7wy28qagyuIXMeQI/Oqq8bcn5wJI50xH00CRntyfpL1T4hydYpoXgNiFzoIUTDZnLNRzh4TBHwbYGDvZkxmlyJloyr6tRihpeUG94GnKtIznREF0tzJG/OOr73JBcrSh1k6WuTprgLU+mnSGnv6Zge0NNz+kTDdH8nuAuTdJDCNb21LCiIuqlYbqGzT3RAoZofQfjFazkqeNWdYaGvYTM001EW2oKPvVk1ldUGSgUtHFwjKM1h9jnFcmy5lChoLNaQMGGDsYbKixlaMBmmsx1QjCfflwTfO/gckW0ruZ3jugKR3R5W9hGUWqCgxuFgsuaCHorotGKzGaeZB9DMsaTnKCpMtwTvOzhYk0rdrArKCqcaWmVk1+F372ur1YkKxgatI8Qfe1gIX9wE9FgS8ESmuABIXnRUbCapcKe+nO7slClSZFzpV/LkLncEb1qiO42fS3R855Su2mCLh62t1SYZZYVmKwIHjREF2uihTzB20JOkz7dkxzYQnK0UOU494wh+VWRc6Un2kpTaVgLDFEkJ/uhzRcI0YKGgpGWOlocBU/a4fKoJ/pEaNV6jip3+Es9VXY078rGnmAdf7t9ylPXS34RBSuYPs1UecZTU78WanhBCHpZ5sAoTz0LGZKjPf9TRypqWEiTvOFglL1fCEY3wY/++rbk7C8bWebA6p6om6PgOL2kp44TFJlVNBXae2rqqdZztOJpT87GQsE9jqCPIe9VReZuQ/CIgacsyZdCpIScSYqcZk8r+nsyCzhyfhOqHGOIvrLknC8wTpFcaYiGC/RU1NRbUeUpocQOnkRpGOrIOcNRx+1uA0UrzhSSt+VyS3SJpnFWkzNDqOFGIWcfR86DnmARTQ1HKIL33ExPiemeOhYSSjzlSUZZuE4TveoJLnBUOFof6KiysCbnAEcZgcUNTDOwkqWu3RWtmGpZwlHhJENdZ3miGz0lJlsKnjbwqSHQjpxnFDlTLLwqJPMZMjd7KrzkSG7VsxXBZE+F8YZkb01Oe00yyRK9psh5SYh29ySPKBo2ylNht7ZkZnsKenjKNJu9PNEyZpaCHv4Kt6RQsLvAVp7M9kIimmCUwGeWqLMmGuIotYMmWNpSahkhZw9FqZsVnKJhsjAHvtHMsTM9fCI06Dx/u3vfUXCqfsKRc4oFY2jMsoo/7DJDwZ1CsIKnJu+J9ldkpmiCxQx1rWjI+T9FwcWWzOuaYH0Hj7klNRVWEQpmaqosakiGNTFHdjS/qnUdmf0NJW5xsL0HhimCCZZSRzmSPTXJQ4aaztAwtZnoabebJ+htCaZ7Cm535ByoqXKbX1WRc4Eh2MkRXWzImVc96Cj4VdOKVxR84VdQsIUM8Psoou2byVHyZFuq7O8otbSQ2UAoeEWTudATLGSpZzVLlXVkPU2Jc+27lsw2jmg5T5VhbeE3BT083K9WsTTkFU/Osi0rC5lRlpwRHUiesNS0sOvmqGML1aRbPAxTJD9ZKtxuob+hhl8cwYGWpJ8nub7t5p6coYbMovZ1BTdaKn1jYD6h4GFDNFyT/Kqe1XCXphXHOKLZmuRSRdBPEfVUXQzJm5YGPGGJdvAEr7hHNdGZnuBvrpciGmopOLf5N0uVMy0FfYToJk90uUCbJupaVpO53UJXR2bVpoU00V2KOo4zMFrBd0Jtz2pa0clT5Q5L8IpQ177mWQejPMEJhuQjS10ref6HHjdEhy1P1EYR7GtO0uSsKJQYLiTnG1rVScj5lyazpqWGl5uBbRWl7m6ixGOOnEsMJR7z8J0n6KMnCdxhiNYQCoZ6CmYLnO8omC3MkW3bktlPmEt/VQQHejL3+dOE5FlPdK/Mq8hZxxJtLyRrepLThYKbLZxkSb5W52vYxNOaOxUF0yxMUPwBTYqCzy01XayYK0sJyWBLqX0MwU5CzoymRzV0EjjeUeLgDpTo6ij42ZAzvD01dHUUTPLU96MdLbBME8nFBn7zJCMtJcZokn8YoqU0FS5WFKyniHobguMcmW8N0XkWZjkyN3hqOMtS08r+/xTBwpZSZ3qiVRX8SzMHHjfUNFjgHEPmY9PL3ykEzxkSre/1ZD6z/NuznuB0RcE1TWTm9zRgfUWVJiG6yrzgmWPXC8EAR4Wxhlad0ZbgQyEz3pG5RVEwwDJH2mgKpjcTiCOzn1lfUWANFbZ2BA8balnEweJC9J0iuaeZoI+ippFCztEKVvckR2iice1JvhVytrQwUAZpgsubCPaU7xUe9vWnaOpaSBEspalykhC9bUlOMpT42ZHca6hyrqKmw/wMR8H5ZmdFoBVJb03O4UL0tSNnvIeRmkrLWqrs78gcrEn2tpcboh0UPOW3UUR9PMk4T4nnNKWmCjlrefhCwxRNztfmIQVdDElvS4m1/WuOujoZCs5XVOjtKPGokJzsYCtFYoWonSPT21DheU/wWhM19FcElwqNGOsp9Q8N/cwXaiND1MmeL1Q5XROtYYgGeFq1aTMsoMmcrKjQrOFQTQ1fmBYhmW6o8Jkjc7iDJRTBIo5kgJD5yMEYA3srCg7VFKwiVJkmRCc5ohGOKhsYMn/XBLdo5taZjlb9YAlGWRimqbCsoY7HFAXLa5I1HPRxMMsQDHFkWtRNniqT9UEeNjcE7RUlrCJ4R2CSJuqlKHWvJXjAUNcITYkenuBRB84TbeepcqTj3zZyFJzgYQdHnqfgI0ddUwS6GqWpsKWhjq9cV0vBAEMN2znq+EBfIWT+pClYw5xsTlJU6GeIBsjGmmANTzJZiIYpgrM0Oa8ZMjd7NP87jxhqGOhJlnQtjuQpB+8aEE00wZFznSJPyHxgH3HkPOsJFvYk8zqCHzTs1BYOa4J3PFU+UVRZxlHDM4YavlNUuMoRveiZA2d7grMNc2g+RbSCEKzmgYsUmWmazFJyoiOZ4KnyhKOGRzWJa0+moyV4TVHDzn51Awtqaphfk/lRQ08FX1iiqxTB/kLwd0VynKfEvI6cd4XMV5bMhZ7gZUWVzYQ6Nm2BYzxJbw3bGthEUUMfgbGeorae6DxHtJoZ6alhZ0+ytiVoK1R4z5PTrOECT/SugseEOlb1MMNR4VRNcJy+V1Hg9ONClSZFZjdHlc6W6FBLdJja2MC5hhpu0DBYEY1TFGwiFAxRRCsYkiM9JRb0JNMVkW6CZYT/2EiTGWmo8k+h4FhDNE7BvppoTSFnmCV5xZKzvcCdDo7VVPnIU+I+Rc68juApC90MwcFCsJ5hDqxgScYKreruyQwTqrzoqDCmhWi4IbhB0Yrt3RGa6GfDv52rKXWhh28dyZaWUvcZeMTBaZoSGyiCtRU5J8iviioHaErs7Jkj61syVzTTgOcUOQ8buFBTYWdL5g3T4qlpe0+wvD63heAXRfCCIed9RbCsp2CiI7raUOYOTU13N8PNHvpaGvayo4a3LLT1lDrVEPT2zLUlheB1R+ZTRfKWJ+dcocLJfi11vyJ51lLqJ0WD7tRwryezjiV5W28uJO9qykzX8JDe2lHl/9oyBwa2UMfOngpXCixvKdXTk3wrsKmiVYdZIqsoWEERjbcUNDuiaQomGoIbFdEHmsyWnuR+IeriKDVLnlawlyNHKwKlSU631PKep8J4Q+ayjkSLKYLhalNHlYvttb6fHm0p6OApsZ4l2VfdqZkjuysy6ysKLlckf1KUutCTs39bmCgEyyoasIWlVaMF7mgmWtBT8Kol5xpH9IGllo8cJdopcvZ2sImlDmMIbtDk3KIpeNiS08lQw11NFPTwVFlPP6pJ2gvRfI7gQUfmNAtf6Gs0wQxDsKGlVBdF8rCa3jzdwMaGHOsItrZk7hAyOzpK9VS06j5F49b0VNGOOfKs3lDToMsMBe9ZWtHFEgxTJLs7qrygKZjUnmCYoeAqeU6jqWuLJup4WghOdvCYJnrSkSzoyRkm5M2StQwVltPkfCAk58tET/CSg+8MUecmotMEnhBKfWBIZsg2ihruMJQaoIm+tkTLKEqspMh00w95gvFCQRtDwTT1gVDDSEVdlwqZfxoQRbK0g+tbiBZxzKlpnpypejdDwTaeOvorMk/IJE10h9CqRe28hhLbe0pMsdSwv4ZbhKivo2BjDWfL8UKJgeavwlwb5KlwhyE4u4XkGE2ytZCznKLCDZZq42VzT8HLCrpruFbIfOIINmh/qCdZ1ZBc65kLHR1Bkyf5zn6pN3SvGKIlFNGplhrO9QSXanLOMQTLCa0YJCRrCZm/CZmrLTm7WzCK4GJDiWUdFeYx1LCFg3NMd0XmCuF3Y5rITLDUsYS9zoHVzwnJoYpSTQoObyEzr4cFBNqYTopoaU/wkyLZ2lPhX/5Y95ulxGTV7KjhWrOZgl8MyUUafjYraNjNU1N3IWcjT5WzWqjwtoarHSUObGYO3GCJZpsBlnJGPd6ZYLyl1GdCA2625IwwJDP8GUKymbzuyPlZlvTUsaUh5zFDhRWFzPKKZLAlWdcQbObgF9tOqOsmB1dqcqYJmWstFbZRRI9poolmqiLnU0POvxScpah2iSL5UJNzgScY5+AuIbpO0YD3NCW+dLMszFSdFCWGqG6eVq2uYVNDdICGD6W7EPRWZEY5gpsE9rUkS3mijzzJnm6UpUFXG1hCUeVoS5WfNcFpblELL2qqrCvMvRfd45oalvKU2tiQ6ePJOVMRXase9iTtLJztPxJKLWpo2CRDcJwn2sWSLKIO1WQWNTCvpVUvOZhgSC40JD0dOctaSqzkCRbXsKlb11Oip6PCJ0IwSJM31j3akRxlP7Rwn6aGaUL0qiLnJkvB3xWZ2+Q1TfCwpQH3G0o92UzmX4o/oJNQMMSQc547wVHhdk+VCw01DFYEnTxzZKAm74QmeNNR1w6WzEhNK15VJzuCdxQ53dRUDws5KvwgBMOEgpcVNe0hZI6RXT1Jd0cyj5nsaEAHgVmGaJIlWdsc5Ui2ElrRR6jrRAttNMEAIWrTDFubkZaok7/AkzfIwfuWVq0jHzuCK4QabtLUMVPB3kJ0oyHTSVFlqMALilJf2Rf8k5aaHtMfayocLBS8L89oKoxpJvnAkDPa0qp5DAUTHKWmCcnthlou8iCKaFFLHWcINd1nyIwXqrSxMNmSs6KmoL2QrKuWtlQ5V0120xQ5vRyZS1rgFkWwhiOwiuQbR0OOVhQM9iS3tiXp4RawRPMp5tDletOOBL95MpM01dZTBM9pkn5qF010rIeHFcFZhmSGpYpTsI6nwhqe5C9ynhlpp5ophuRb6WcJFldkVnVEwwxVfrVkvnWUuNLCg5bgboFHPDlDPDmnK7hUrWiIbjadDclujlZcaokOFup4Ri1kacV6jmrrK1hN9bGwpKEBQ4Q6DvIUXOmo6U5LqQM6EPyiKNjVkPnJkDPNEaxhiFay5ExW1NXVUGqcpYYdPcGiCq7z/TSlbhL4pplWXKd7NZO5QQFrefhRQW/NHOsqcIglc4UhWklR8K0QzbAw08CBDnpbgqXdeD/QUsM4RZXDFBW6WJKe/mFPdH0LtBgiq57wFLzlyQzz82qYx5D5WJP5yVJDW01BfyHnS6HKO/reZqId1WGa4Hkh2kWodJ8i6KoIPlAj2hPt76CzXsVR6koPRzWTfKqIentatYpQw2me4AA3y1Kind3SwoOKZDcFXTwl9tWU6mfgRk9d71sKtlNwrjnYw5tC5n5LdKiGry3JKNlHEd3oaMCFHrazBPMp/uNJ+V7IudcSbeOIdjUEdwl0VHCOZo5t6YluEuaC9mQeMgSfOyKnYGFHcIeQ84yQWbuJYJpZw5CzglDH7gKnWqqM9ZTaXcN0TeYhR84eQtJT76JJ1lREe7WnnvsMmRc9FQ7SBBM9mV3lCUdmHk/S2RAMt0QjFNFqQpWjDPQ01DXWUdDBkXziKPjGEP3VP+zIWU2t7im41FOloyWzn/L6dkUy3VLDaZ6appgDLHPjJEsyvJngWEPUyVBiAaHCTEXwrLvSEbV1e1gKJniicWorC1MUrVjB3uDhJE/wgSOzk1DXpk0k73qCM8xw2UvD5kJmDUfOomqMpWCkJRlvKXGmoeBm18USjVIk04SClxTB6YrgLAPLWYK9HLUt5cmc0vYES8GnTeRc6skZbQkWdxRsIcyBRzx1DbTk9FbU0caTPOgJHhJKnOGIVhQqvKmo0llRw9sabrZkDtdg3PqaKi9oatjY8B+G371paMg6+mZFNNtQ04mWBq3rYLOmtWWQp8KJnpy9DdFensyjdqZ+yY40VJlH8wcdLzC8PZnvHMFUTZUrDTkLyQaGus5X5LzpYAf3i+e/ZlhqGqWhh6Ou6xTR9Z6oi5AZZtp7Mj2EEm8oSpxiYZCHU/1fbGdNNNRRoZMhmilEb2gqHOEJDtXkHK/JnG6IrvbPCwV3NhONVdS1thBMs1T4QOBcTWa2IzhMk2nW5Kyn9tXUtpv9RsG2msxk+ZsQzRQacJncpgke0+T8y5Fzj8BiGo7XlJjaTIlpQs7KFjpqGnKuoyEPeIKnFMkZHvopgh81ySxNFWvJWcKRs70j2FOT012IllEEO1n4pD1513Yg2ssQPOThOkvyrqHUdEXOSEsihmBbTbKX1kLBPWqWkLOqJbjB3GBIZmoa8qWl4CG/iZ7oiA72ZL7TJNeZUY7kFQftDcHHluBzRbCegzMtrRjVQpX2lgoPKKLJAkcbMl01XK2p7yhL8pCBbQ3BN2avJgKvttcrWDK3CiUOVxQ8ZP+pqXKyIxnmBymCg5vJjNfkPK4+c8cIfK8ocVt7kmfd/I5SR1hKvCzUtb+lhgc00ZaO6CyhIQP1Uv4yIZjload72PXX0OIJvnFU+0Zf6MhsJwTfW0r0UwQfW4LNLZl5HK261JCZ4qnBaAreVAS3WrjV0LBnNDUNNDToCEeFfwgcb4gOEqLRhirWkexrCEYKVV711DLYEE1XBEsp5tpTGjorkomKYF9FDXv7fR3BGwbettSxnyL53MBPjsxDZjMh+VUW9NRxq1DhVk+FSxQcaGjV9Pawv6eGByw5qzoy7xk4RsOShqjJwWKe/1pEEfzkobeD/dQJmpqedcyBTy2sr4nGNRH0c0SPWTLrqAc0OQcb/gemKgqucQT7ySWKCn2EUotoCvpZct7RO2sy/QW0IWcXd7pQRQyZVwT2USRO87uhjioTLKV2brpMUcMQRbKH/N2T+UlTpaMls6cmc6CCNy3JdYYSUzzJQ4oSD3oKLncULOiJvjBEC2oqnCJkJluCYy2ZQ5so9YYlZ1VLlQU1mXEW1jZERwj/MUSRc24TdexlqLKfQBtDTScJUV8FszXBEY5ktpD5Ur9hYB4Nb1iikw3JoYpkKX+RodRKFt53MMuRnKSpY31PwYaGaILh3wxJGz9TkTPEETxoCWZrgvOlmyMzxFEwVJE5xZKzvyJ4WxEc16Gd4Xe3Weq4XH2jKRikqOkGQ87hQnC7wBmGYLAnesX3M+S87eFATauuN+Qcrh7xIxXJbUIdMw3JGE3ylCWzrieaqCn4zhGM19TQ3z1oH1AX+pWEqIc7wNGAkULBo/ZxRaV9NNyh4Br3rCHZzbzmSfawBL0dNRwpW1kK9mxPXR9povcdrGSZK9c2k0xwFGzjuniCtRSZCZ6ccZ7gaktmgAOtKbG/JnOkJrjcQTdFMsxRQ2cLY3WTIrlCw1eWKn8R6pvt4GFDso3QoL4a3nLk3G6JrtME3dSenpx7PNFTmga0EaJTLQ061sEeQoWXhSo9LTXsaSjoJQRXeZLtDclbCrYzfzHHeaKjHCVOUkQHO3JeEepr56mhiyaYYKjjNU+Fed1wS5VlhWSqI/hYUdDOkaxiKehoyOnrCV5yBHtbWFqTHCCwtpDcYolesVR5yUzTZBb3RNMd0d6WP+SvhuBmRcGxnuQzT95IC285cr41cLGQ6aJJhmi4TMGempxeimBRQw1tFKV+8jd6KuzoSTqqDxzRtpZkurvKEHxlqXKRIjjfUNNXQsNOsRScoWFLT+YeRZVD3GRN0MdQcKqQjHDMrdGGVu3iYJpQx3WGUvfbmxwFfR20WBq0oYY7LMFhhgYtr8jpaEnaOzjawWWaTP8mMr0t/EPDPoqcnxTBI5o58L7uoWnMrpoqPwgVrlAUWE+V+TQl9rawoyP6QGAlQw2TPRX+YSkxyBC8Z6jhHkXBgQL7WII3DVFnRfCrBfxewv9D6xsyjys4VkhWb9pUU627JllV0YDNHMku/ldNMMXDEo4aFnAkk4U6frNEU4XgZUPmEKHUl44KrzmYamjAbh0JFvGnaTLPu1s9jPCwjFpYiN7z1DTOk/nc07CfDFzmCf7i+bfNHXhDtLeBXzTBT5rkMvWOIxpl4EMh2LGJBu2syDnAEx2naEhHDWMMzPZEhygyS1mS5RTJr5ZkoKbEUoYqr2kqdDUE8ztK7OaIntJkFrIECwv8LJTaVx5XJE86go8dFeZ3FN3rjabCAYpoYEeC9zzJVULBbmZhDyd7ko09ydpNZ3nm2Kee4FPPXHnYEF1nqOFEC08LUVcDvYXkJHW8gTaKCk9YGOeIJhqiE4ToPEepdp7IWFjdwnWaufGMwJJCMtUTTBBK9BGCOy2tGGrJTHIwyEOzp6aPzNMOtlZkDvcEWpP5SVNhfkvDxhmSazTJXYrM9U1E0xwFVwqZQwzJxw6+kGGGUj2FglGGmnb1/G51udRSMNlTw6GGnCcUwVcOpmsqTHa06o72sw1RL02p9z0VbnMLOaIX3QKaYKSCFQzBKEUNHTSc48k53RH9wxGMtpQa5KjjW0W0n6XCCCG4yxNNdhQ4R4l1Ff+2sSd6UFHiIEOyqqFgT01mEUMD+joy75jPhOA+oVVLm309FR4yVOlp4RhLiScNmSmaYF5Pw0STrOIoWMSR2UkRXOMp+M4SHW8o8Zoi6OZgjKOaFar8zZDzkWzvKOjkKBjmCXby8JahhjXULY4KlzgKLvAwxVGhvyd4zxB1d9T0piazmKLCVZY5sKiD0y2ZSYrkUEPUbIk+dlQ4SJHTR50k1DPaUWIdTZW9NJwnJMOECgd7ou/MnppMJ02O1VT4Wsh85MnZzcFTngpXGKo84qmwgKbCL/orR/SzJ2crA+t6Mp94KvxJUeIbT3CQu1uIdlQEOzlKfS3UMcrTiFmOuroocrZrT2AcmamOKg8YomeEKm/rlT2sociMaybaUlFhuqHCM2qIJ+rg4EcDFymiDSxzaHdPcpE62pD5kyM5SBMoA1PaUtfIthS85ig1VPiPPYXgYEMNk4Qq7TXBgo7oT57gPUdwgCHzhIVFPFU6OYJzHAX9m5oNrVjeE61miDrqQ4VSa1oiURTsKHC0IfjNwU2WzK6eqK8jWln4g15TVBnqmDteCJ501PGAocJhhqjZdtBEB6lnhLreFJKxmlKbeGrqLiSThVIbCdGzloasa6lpMQXHCME2boLpJgT7yWaemu6wBONbqGNVRS0PKIL7LckbjmQtR7K8I5qtqel+T/ChJTNIKLjdUMNIRyvOEko9YYl2cwQveBikCNawJKcLBbc7+JM92mysNvd/Fqp8a0k6CNEe7cnZrxlW0wQXaXjaktnRwNOGZKYiONwS7a1JVheq3WgJHlQUGKHKmp4KAxXR/ULURcNgoa4zhKSLpZR3kxRRb0NmD0OFn+UCS7CzI1nbP6+o4x47QZE5xRCt3ZagnYcvmpYQktXdk5YKXTzBC57kKEe0VVuiSYqapssMS3C9p2CKkHOg8B8Pa8p5atrIw3qezIWanMGa5HRDNF6RM9wcacl0N+Q8Z8hsIkSnaIIdHRUOEebAPy1zbCkhM062FCJtif7PU+UtoVXzWKqM1PxXO8cfdruhFQ/a6x3JKYagvVDhQEtNiyiiSQ7OsuRsZUku0CRNDs4Sog6KKjsZgk2bYJqijgsEenoKeniinRXBn/U3lgpPdyDZynQx8IiioMnCep5Ky8mjGs6Wty0l1hUQTcNWswS3WRp2kCNZwJG8omG8JphPUaFbC8lEfabwP7VtM9yoaNCAjpR41VNhrD9LkbN722v0CoZMByFzhaW+MyzRYEWFDQwN2M4/JiT76PuljT3VU/A36eaIThb+R9oZGOAJ9tewkgGvqOMNRWYjT/Cwu99Q8LqDE4TgbLWxJ1jaDDAERsFOFrobgjUsBScaguXU8kKm2RL19tRypSHnHNlHiIZqgufs4opgQdVdwxBNNFBR6kVFqb8ogimOzB6a6HTzrlDHEpYaxjiiA4TMQobkDg2vejjfwJGWmnbVFAw3H3hq2NyQfG7hz4aC+w3BbwbesG0swYayvpAs6++Ri1Vfzx93mFChvyN5xVHTS+0p9aqCAxyZ6ZacZyw5+7uuQkFPR9DDk9NOiE7X1PCYJVjVUqq7JlrHwWALF5nfHNGjApdpqgzx5OwilDhCiDYTgnc9waGW4BdLNNUQvOtpzDOWHDH8D7TR/A/85KljEQu3NREc4Pl/6B1Hhc8Umb5CsKMmGC9EPcxoT2amwHNCmeOEnOPbklnMkbOgIvO5UMOpQrS9UGVdt6iH/fURjhI/WOpaW9OKLYRod6HCUEdOX000wpDZQ6hwg6LgZfOqo1RfT/CrJzjekXOGhpc1VW71ZLbXyyp+93ILbC1kPtIEYx0FIx1VDrLoVzXRKRYWk809yYlC9ImcrinxtabKnzRJk3lAU1OLEN1j2zrYzr2myHRXJFf4h4QKT1qSTzTB5+ZNTzTRkAxX8FcLV2uS8eoQQ2aAkFzvCM72sJIcJET3WPjRk5wi32uSS9rfZajpWEvj9hW42F4o5NytSXYy8IKHay10VYdrcl4SkqscrXpMwyGOgtkajheSxdQqmpxP1L3t4R5PqasFnrQEjytq6qgp9Y09Qx9o4S1FzhUCn1kyHSzBWLemoSGvOqLNhZyBjmCaAUYpMgt4Ck7wBBMMwWKWgjsUwTaGVsxWC1mYoKiyqqeGKYqonSIRQ3KIkHO0pmAxTdBHkbOvfllfr+AA+7gnc50huVKYK393FOyg7rbPO/izI7hE4CnHHHnJ0ogNPRUGeUpsrZZTBJcrovUcJe51BPsr6GkJdhCCsZ6aTtMEb2pqWkqeVtDXE/QVggsU/Nl86d9RMF3DxvZTA58agu810RWawCiSzzXBeU3MMW9oyJUedvNEvQyNu1f10BSMddR1vaLCYpYa/mGocLSiYDcLbQz8aMn5iyF4xBNMs1P0QEOV7o5gaWGuzSeLue4tt3ro7y4Tgm4G/mopdZgl6q0o6KzJWE3mMksNr3r+a6CbT8g5wZNzT9O7fi/zpaOmnz3BRoqos+tv9zMbdpxsqDBOEewtJLt7cg5wtKKbvldpSzRRCD43VFheCI7yZLppggMVBS/KMAdHODJvOwq2NQSbKKKPLdFWQs7Fqo+mpl01JXYRgq8dnGLhTiFzqmWsUMdpllZdbKlyvSdYxhI9YghOtxR8LgSLWHK62mGGVoxzBE8LNWzqH9CUesQzFy5RQzTc56mhi6fgXEWwpKfE5Z7M05ZgZUPmo6auiv8YKzDYwWBLMErIbKHJvOwIrvEdhOBcQ9JdU1NHQ7CXn2XIDFBKU2WAgcX9UAUzDXWd5alwuyJ41Z9rjKLCL4aCp4WarhPm2rH+SaHUYE001JDZ2ZAzXPjdMpZWvC9wmqIB2lLhQ01D5jO06hghWMndbM7yRJMsoCj1vYbnFQVrW9jak3OlEJ3s/96+p33dEPRV5GxiqaGjIthUU6FFEZyqCa5qJrpBdzSw95IUnOPIrCUUjRZQFrbw5PR0R1qiYx3cb6nrWUMrBmmiBQxVHtTew5ICP/ip6g4hed/Akob/32wvBHsIOX83cI8hGeNeNPCIkPmXe8fPKx84OMSRM1MTdXSwjCZ4S30jVGhvqTRak/OVhgGazHuOCud5onEO1lJr6ecVyaOK6H7zqlBlIaHE0oroCgfvGJIdPcmfLNGLjpz7hZwZQpUbFME0A1cIJa7VNORkgfsMBatbKgwwJM9bSvQXeNOvbIjelg6WWvo5kvbKaJJNHexkKNHL9xRyFlH8Ti2riB5wVPhUk7nGkJnoCe428LR/wRGdYIlmWebCyxou1rCk4g/ShugBDX0V0ZQWkh0dOVsagkM0yV6OoLd5ye+pRlsCr0n+KiQrGuq5yJDzrTAXHtLUMduTDBVKrSm3eHL+6ijxhFDX9Z5gVU/wliHYTMiMFpKLNMEywu80wd3meoFmt6VbRMPenhrOc6DVe4pgXU8DnnHakLOIIrlF4FZPIw6R+zxBP0dyq6OOZ4Q5sLKCcz084ok+VsMMyQhNZmmBgX5xIXOEJTmi7VsGTvMTNdHHhpzdbE8Du2oKxgvBqQKdDDnTFOylCFaxR1syz2iqrOI/FEpNc3C6f11/7+ASS6l2inq2ciTrCCzgyemrCL5SVPjQkdPZUmGy2c9Sw9FtR1sS30RmsKPCS4rkIC/2U0MduwucYolGaPjKEyhzmiPYXagyWbYz8LWBDdzRimAXzxx4z8K9hpzlhLq+NiQ97HuKorMUfK/OVvC2JfiHUPCQI/q7J2gjK+tTDNxkCc4TMssqCs4TGtLVwQihyoAWgj9bosU80XGW6Ac9TJGziaUh5+hnFcHOnlaM1iRn29NaqGENTTTSUHCH2tWTeV0osUhH6psuVLjRUmGWhm6OZEshGeNowABHcJ2Bpy2ZszRcKkRXd2QuKVEeXnbfaEq825FguqfgfE2whlChSRMdron+LATTPQ2Z369t4B9C5gs/ylzv+CMmepIDPclFQl13W0rspPd1JOcbghGOEutqCv5qacURQl3dDKyvyJlqKXGPgcM9FfawJAMVmdcspcYKOZc4GjDYkFlK05olNMHyHn4zFNykyOxt99RkHlfwmiHo60l2EKI+mhreEKp080Tbug08BVPcgoqC5zWt+NLDTZ7oNSF51N1qie7Va3uCCwyZbkINf/NED6jzOsBdZjFN8oqG3wxVunqCSYYKf3EdhJyf9YWGf7tRU2oH3VHgPr1fe5J9hOgHd7xQ0y7qBwXr23aGErP0cm64JVjZwsOGqL+mhNgZmhJLW2oY4UhedsyBgzrCKrq7BmcpNVhR6jBPq64Vgi+kn6XE68pp8J5/+0wRHGOpsKenQn9DZntPzjRLZpDAdD2fnSgkG9tmIXnUwQ6WVighs7Yi2MxQ0N3CqYaCXkJ0oyOztMDJjmSSpcpvlrk0RMMOjmArQ04PRV1DO1FwhCVaUVPpKUM03JK5SxPsIWRu8/CGHi8UHChiqGFDTbSRJWeYUDDcH6vJWUxR4k1FXbMUwV6e4AJFXS8oMqsZKqzvYQ9DDQdZckY4aGsIhtlubbd2r3j4QBMoTamdPZk7O/Bf62lacZwneNjQoGcdVU7zJOd7ghsUHOkosagic6cnWc8+4gg285R6zZP5s1/LUbCKIznTwK36PkdwlOrl4U1LwfdCCa+IrvFkmgw1PCAUXKWo0sURXWcI2muKJlgyFzhynCY4RBOsqCjoI1R5zREco0n2Vt09BQtYSizgKNHfUmUrQ5UOCh51BFcLmY7umhYqXKQomOop8bUnWNNQcIiBcYaC6xzMNOS8JQQfeqKBmmglB+97ok/lfk3ygaHSyZaCRTzRxQo6GzLfa2jWBPepw+UmT7SQEJyiyRkhBLMVOfcoMjcK0eZChfUNzFAUzCsEN5vP/X1uP/n/aoMX+K+nw/Hjr/9xOo7j7Pju61tLcgvJpTWXNbfN5jLpi6VfCOviTktKlFusQixdEKWmEBUKNaIpjZRSSOXSgzaaKLdabrm1/9nZ+/f+vd/vz/v9+Xy+zZ7PRorYoZqyLrCwQdEAixxVOEXNNnjX2nUSRlkqGmWowk8lxR50JPy9Bo6qJXaXwNvREBvnThPEPrewryLhcAnj5WE15Fqi8W7R1sAuEu86S4ENikItFN4xkv9Af4nXSnUVcLiA9xzesFpivRRVeFKtsMRaKBhuSbjOELnAUtlSQUpXgdfB4Z1oSbnFEetbQ0IrAe+Y+pqnDcEJFj6S8LDZzZHwY4e3XONNlARraomNEt2bkvGsosA3ioyHm+6jCMbI59wqt4eeara28IzEmyPgoRaUOEDhTVdEJhmCoTWfC0p8aNkCp0oYqih2iqGi4yXeMkOsn4LdLLnmKfh/YogjNsPebeFGR4m9BJHLzB61XQ3BtpISfS2FugsK9FAtLWX1dCRcrCnUp44CNzuCowUZmxSRgYaE6Za0W2u/E7CVXCiI/UOR8aAm1+OSyE3mOUcwyc1zBBeoX1kiKy0Zfxck1Gsyulti11i83QTBF5Kg3pDQThFMVHiPSlK+0cSedng/VaS8bOZbtsBcTcZAR8JP5KeqQ1OYKAi20njdNNRpgnsU//K+JnaXJaGTomr7aYIphoRn9aeShJWKEq9LcozSF7QleEfDI5LYm5bgVkFkRwVDBCVu0DDIkGupo8TZBq+/pMQURYErJQmPKGKjNDkWOLx7Jd5QizdUweIaKrlP7SwJDhZvONjLkOsBBX9UpGxnydhXkfBLQ8IxgojQbLFnJf81JytSljclYYyEFyx0kVBvKWOFJmONpshGAcsduQY5giVNCV51eOdJYo/pLhbvM0uDHSevNKRcrKZIqnCtJeEsO95RoqcgGK4ocZcho1tTYtcZvH41pNQ7vA0WrhIfOSraIIntIAi+NXWCErdbkvrWwjRLrt0NKUdL6KSOscTOdMSOUtBHwL6OLA0vNSdynaWQEnCpIvKaIrJJEbvHkmuNhn6OjM8VkSGSqn1uYJCGHnq9I3aLhNME3t6GjIkO7xrNFumpyTNX/NrwX7CrIRiqqWijI9JO4d1iieykyfiposQIQ8YjjsjlBh6oHWbwRjgYJQn2NgSnNycmJAk3NiXhx44Sxykihxm8ybUwT1OVKySc7vi3OXVkdBJ4AyXBeksDXG0IhgtYY0lY5ahCD0ehborIk5aUWRJviMA7Xt5kyRjonrXENkm8yYqgs8VzgrJmClK20uMM3jRJ0FiQICQF9hdETlLQWRIb5ki6WDfWRPobvO6a4GP5mcOrNzDFELtTkONLh9dXE8xypEg7z8A9jkhrQ6Fhjlg/QVktJXxt4WXzT/03Q8IaQWSqIuEvloQ2mqC9Jfi7wRul4RX3pSPlzpoVlmCtI2jvKHCFhjcM3sN6lqF6HxnKelLjXWbwrpR4xzuCrTUZx2qq9oAh8p6ixCUGr78g8oyjRAtB5CZFwi80VerVpI0h+IeBxa6Zg6kWvpDHaioYYuEsRbDC3eOmC2JvGYLeioxGknL2UATNJN6hmtj1DlpLvDVmocYbrGCVJKOrg4X6DgddLA203BKMFngdJJFtFd7vJLm6KEpc5yjQrkk7M80SGe34X24nSex1Ra5Omgb71JKyg8SrU3i/kARKwWpH0kOGhKkObyfd0ZGjvyXlAkVZ4xRbYJ2irFMkFY1SwyWxr2oo4zlNiV+7zmaweFpT4kR3kaDAFW6xpSqzJay05FtYR4HmZhc9UxKbbfF2V8RG1MBmSaE+kmC6JnaRXK9gsiXhJHl/U0qM0WTcbyhwkYIvFGwjSbjfwhiJt8ZSQU+Bd5+marPMOkVkD0muxYLIfEuhh60x/J92itguihJSEMySVPQnTewnEm+620rTQEMsOfo4/kP/0ARvWjitlpSX7GxBgcMEsd3EEeYWvdytd+Saawi6aCIj1CkGb6Aj9rwhx16Cf3vAwFy5pyLhVonXzy51FDpdEblbkdJbUcEPDEFzQ8qNmhzzLTmmKWKbFCXeEuRabp6rxbvAtLF442QjQ+wEA9eL1xSR7Q0JXzlSHjJ4exq89yR0laScJ/FW6z4a73pFMEfDiRZvuvijIt86RaSFOl01riV2mD1UEvxGk/Geg5aWwGki1zgKPG9J2U8PEg8qYvMsZeytiTRXBMslCU8JSlxi8EabjwUldlDNLfzTUmCgxWsjqWCOHavYAqsknKFIO0yQ61VL5AVFxk6WhEaCAkdJgt9aSkzXlKNX2jEa79waYuc7gq0N3GDJGCBhoiTXUEPsdknCUE1CK0fwsiaylSF2uiDyO4XX3pFhNd7R4itFGc0k/ElBZwWvq+GC6szVeEoS/MZ+qylwpKNKv9Z469UOjqCjwlusicyTxG6VpNxcQ8IncoR4RhLbR+NdpGGmJWOcIzJGUuKPGpQg8rrG21dOMqQssJQ4RxH5jaUqnZuQ0F4Q+cjxLwPtpZbIAk3QTJHQWBE5S1BokoVtDd6lhqr9UpHSUxMcIYl9pojsb8h4SBOsMQcqvOWC2E8EVehqiJ1hrrAEbQxeK0NGZ0Gkq+guSRgniM23bIHVkqwx4hiHd7smaOyglyIyQuM978j4VS08J/A2G1KeMBRo4fBaSNhKUEZfQewVQ/C1I+MgfbEleEzCUw7mKXI0M3hd1EESVji8x5uQ41nxs1q4RMJCCXs7Iq9acpxn22oSDnQ/sJTxsCbHIYZiLyhY05TY0ZLIOQrGaSJDDN4t8pVaIrsqqFdEegtizc1iTew5Q4ayBDMUsQMkXocaYkc0hZua412siZ1rSXlR460zRJ5SlHGe5j801RLMlJTxtaOM3Q1pvxJ45zUlWFD7rsAbpfEm1JHxG0eh8w2R7QQVzBUw28FhFp5QZzq8t2rx2joqulYTWSuJdTYfWwqMFMcovFmSyJPNyLhE4E10pHzYjOC3huArRa571ZsGajQpQx38SBP5pyZB6lMU3khDnp0MBV51BE9o2E+TY5Ml2E8S7C0o6w1xvCZjf0HkVEHCzFoyNmqC+9wdcqN+Tp7jSDheE9ws8Y5V0NJCn2bk2tqSY4okdrEhx1iDN8cSudwepWmAGXKcJXK65H9to8jYQRH7SBF01ESUJdd0TayVInaWhLkOjlXE5irKGOnI6GSWGCJa482zBI9rCr0jyTVcEuzriC1vcr6mwFGSiqy5zMwxBH/TJHwjSPhL8+01kaaSUuMFKTcLEvaUePcrSmwn8DZrgikWb7CGPxkSjhQwrRk57tctmxLsb9sZvL9LSlyuSLlWkqOjwduo8b6Uv1DkmudIeFF2dHCgxVtk8dpIvHpBxhEOdhKk7OLIUSdJ+cSRY57B+0DgGUUlNfpthTfGkauzxrvTsUUaCVhlKeteTXCoJDCa2NOKhOmC4G1H8JBd4OBZReSRGkqcb/CO1PyLJTLB4j1q8JYaIutEjSLX8YKM+a6phdMsdLFUoV5RTm9JSkuDN8WcIon0NZMNZWh1q8C7SJEwV5HxrmnnTrf3KoJBlmCYI2ilSLlfEvlE4011NNgjgthzEua0oKK7JLE7HZHlEl60BLMVFewg4EWNt0ThrVNEVkkiTwpKXSWJzdRENgvKGq4IhjsiezgSFtsfCUq8qki5S1LRQeYQQ4nemmCkImWMw3tFUoUBZk4NOeZYEp4XRKTGa6wJjrWNHBVJR4m3FCnbuD6aak2WsMTh3SZImGCIPKNgsDpVwnsa70K31lCFJZYcwwSMFcQulGTsZuEaSdBXkPGZhu0FsdUO73RHjq8MPGGIfaGIbVTk6iuI3GFgucHrIQkmWSJdBd7BBu+uOryWAhY7+Lki9rK5wtEQzWwvtbqGhIMFwWRJsElsY4m9IIg9L6lCX0VklaPAYkfkZEGDnOWowlBJjtMUkcGK4Lg6EtoZInMUBVYLgn0UsdmCyCz7gIGHFfk+k1QwTh5We7A9x+IdJ6CvIkEagms0hR50eH9UnTQJ+2oiKyVlLFUE+8gBGu8MQ3CppUHesnjTHN4QB/UGPhCTHLFPHMFrCqa73gqObUJGa03wgbhHkrCfpEpzNLE7JDS25FMKhlhKKWKfCgqstLCPu1zBXy0J2ztwjtixBu8UTRn9LVtkmCN2iyFhtME70JHRQ1KVZXqKI/KNIKYMCYs1GUMEKbM1bKOI9LDXC7zbHS+bt+1MTWS9odA9DtrYtpbImQJ2VHh/lisEwaHqUk1kjKTAKknkBEXkbkdMGwq0dnhzLJF3NJH3JVwrqOB4Sca2hti75nmJN0WzxS6UxDYoEpxpa4htVlRjkYE7DZGzJVU72uC9IyhQL4i8YfGWSYLLNcHXloyz7QhNifmKSE9JgfGmuyLhc403Xm9vqcp6gXe3xuuv8F6VJNxkyTHEkHG2g0aKXL0MsXc1bGfgas2//dCONXiNLCX+5mB7eZIl1kHh7ajwpikyzlUUWOVOsjSQlsS+M0R+pPje/dzBXRZGO0rMtgQrLLG9VSu9n6CMXS3BhwYmSoIBhsjNBmZbgusE9BCPCP5triU4VhNbJfE+swSP27aayE8tuTpYYjtrYjMVGZdp2NpS1s6aBnKSHDsbKuplKbHM4a0wMFd/5/DmGyKrJSUaW4IBrqUhx0vyfzTBBLPIUcnZdrAkNsKR0sWRspumSns6Ch0v/qqIbBYUWKvPU/CFoyrDJGwSNFhbA/MlzKqjrO80hRbpKx0Jewsi/STftwGSlKc1JZyAzx05dhLEdnfQvhZOqiHWWEAHC7+30FuRcZUgaO5gpaIK+xsiHRUsqaPElTV40xQZQ107Q9BZE1nryDVGU9ZSQ47bmhBpLcYpUt7S+xuK/FiT8qKjwXYw5ypS2iuCv7q1gtgjhuBuB8LCFY5cUuCNtsQOFcT+4Ih9JX+k8Ea6v0iCIRZOtCT0Et00JW5UeC85Cg0ScK0k411HcG1zKtre3SeITBRk7WfwDhEvaYLTHP9le0m8By0JDwn4TlLW/aJOvGHxdjYUes+ScZigCkYQdNdEOhkiezgShqkx8ueKjI8lDfK2oNiOFvrZH1hS+tk7NV7nOmLHicGWEgubkXKdwdtZknCLJXaCpkrjZBtLZFsDP9CdxWsSr05Sxl6CMmoFbCOgryX40uDtamB7SVmXW4Ihlgpmq+00tBKUUa83WbjLUNkzDmY7cow1JDygyPGlhgGKYKz4vcV7QBNbJIgM11TUqZaMdwTeSguH6rOaw1JRKzaaGyxVm2EJ/uCIrVWUcZUkcp2grMsEjK+DMwS59jQk3Kd6SEq1d0S6uVmO4Bc1lDXTUcHjluCXEq+1OlBDj1pi9zgiXxnKuE0SqTXwhqbETW6RggMEnGl/q49UT2iCzgJvRwVXS2K/d6+ZkyUl7jawSVLit46EwxVljDZwoSQ20sDBihztHfk2yA8NVZghiXwrYHQdfKAOtzsayjhY9bY0yE2CWEeJ9xfzO423xhL5syS2TFJofO2pboHob0nY4GiAgRrvGQEDa/FWSsoaaYl0syRsEt3kWoH3B01shCXhTUWe9w3Bt44SC9QCh3eShQctwbaK2ApLroGCMlZrYqvlY3qYhM0aXpFkPOuoqJ3Dm6fxXrGwVF9gCWZagjPqznfkuMKQ8DPTQRO8ZqG1hPGKEm9IgpGW4DZDgTNriTxvFiq+Lz+0cKfp4wj6OCK9JSnzNSn9LFU7UhKZZMnYwcJ8s8yRsECScK4j5UOB95HFO0CzhY4xJxuCix0lDlEUeMdS6EZBkTsUkZ4K74dugyTXS7aNgL8aqjDfkCE0ZbwkCXpaWCKhl8P7VD5jxykivSyxyZrYERbe168LYu9ZYh86IkscgVLE7tWPKmJv11CgoyJltMEbrohtVAQfO4ImltiHEroYEs7RxAarVpY8AwXMcMReFOTYWe5iiLRQxJ5Q8DtJ8LQhWOhIeFESPGsILhbNDRljNbHzNRlTFbk2S3L0NOS6V1KFJYKUbSTcIIhM0wQ/s2TM0SRMNcQmSap3jCH4yhJZKSkwyRHpYYgsFeQ4U7xoCB7VVOExhXepo9ABBsYbvGWKXPME3lyH95YioZ0gssQRWWbI+FaSMkXijZXwgiTlYdPdkNLaETxlyDVIwqeaEus0aTcYcg0RVOkpR3CSJqIddK+90JCxzsDVloyrFd5ZAr4TBKfaWa6boEA7C7s6EpYaeFPjveooY72mjIccLHJ9HUwVlDhKkmutJDJBwnp1rvulJZggKDRfbXAkvC/4l3ozQOG9a8lxjx0i7nV4jSXc7vhe3OwIxjgSHjdEhhsif9YkPGlus3iLFDnWOFhtCZbJg0UbQcIaR67JjthoCyMEZRwhiXWyxO5QxI6w5NhT4U1WsJvDO60J34fW9hwzwlKij6ZAW9ne4L0s8C6XeBMEkd/LQy1VucBRot6QMlbivaBhoBgjqGiCJNhsqVp/S2SsG6DIONCR0dXhvWbJ+MRRZJkkuEjgDXJjFQW6SSL7GXK8Z2CZg7cVsbWGoKmEpzQ5elpiy8Ryg7dMkLLUEauzeO86CuwlSOlgYLojZWeJ9xM3S1PWfEfKl5ISLQ0MEKR8YOB2QfCxJBjrKPCN4f9MkaSsqoVXJBmP7EpFZ9UQfOoOFwSzBN4MQ8LsGrymlipcJQhmy0GaQjPqCHaXRwuCZwRbqK2Fg9wlClZqYicrIgMdZfxTQ0c7TBIbrChxmuzoKG8XRaSrIhhiyNFJkrC7oIAWMEOQa5aBekPCRknCo4IKPrYkvCDI8aYmY7WFtprgekcJZ3oLIqssCSMtFbQTJKwXYy3BY5oCh2iKPCpJOE+zRdpYgi6O2KmOAgvVCYaU4ySRek1sgyFhJ403QFHiVEmJHwtybO1gs8Hr5+BETQX3War0qZngYGgtVZtoqd6vFSk/UwdZElYqyjrF4HXUeFspIi9IGKf4j92pKGAdCYMVsbcV3kRF0N+R8LUd5PCsIGWoxDtBkCI0nKofdJQxT+LtZflvuc8Q3CjwWkq8KwUpHzkK/NmSsclCL0nseQdj5FRH5CNHSgtLiW80Of5HU9Hhlsga9bnBq3fEVltKfO5IaSTmGjjc4J0otcP7QsJUSQM8pEj5/wCuUuC2DWz8AAAAAElFTkSuQmCC");
+}
diff --git a/third-party/codemirror-3.15/theme/tomorrow-night-eighties.css b/third-party/codemirror-3.15/theme/tomorrow-night-eighties.css
new file mode 100644 (file)
index 0000000..d682120
--- /dev/null
@@ -0,0 +1,33 @@
+/*
+
+    Name:       Tomorrow Night - Eighties
+    Author:     Chris Kempson
+
+    CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-codemirror)
+    Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16)
+
+*/
+
+.cm-s-tomorrow-night-eighties.CodeMirror {background: #000000; color: #CCCCCC;}
+.cm-s-tomorrow-night-eighties div.CodeMirror-selected {background: #2D2D2D !important;}
+.cm-s-tomorrow-night-eighties .CodeMirror-gutters {background: #000000; border-right: 0px;}
+.cm-s-tomorrow-night-eighties .CodeMirror-linenumber {color: #515151;}
+.cm-s-tomorrow-night-eighties .CodeMirror-cursor {border-left: 1px solid #6A6A6A !important;}
+
+.cm-s-tomorrow-night-eighties span.cm-comment {color: #d27b53;}
+.cm-s-tomorrow-night-eighties span.cm-atom {color: #a16a94;}
+.cm-s-tomorrow-night-eighties span.cm-number {color: #a16a94;}
+
+.cm-s-tomorrow-night-eighties span.cm-property, .cm-s-tomorrow-night-eighties span.cm-attribute {color: #99cc99;}
+.cm-s-tomorrow-night-eighties span.cm-keyword {color: #f2777a;}
+.cm-s-tomorrow-night-eighties span.cm-string {color: #ffcc66;}
+
+.cm-s-tomorrow-night-eighties span.cm-variable {color: #99cc99;}
+.cm-s-tomorrow-night-eighties span.cm-variable-2 {color: #6699cc;}
+.cm-s-tomorrow-night-eighties span.cm-def {color: #f99157;}
+.cm-s-tomorrow-night-eighties span.cm-error {background: #f2777a; color: #6A6A6A;}
+.cm-s-tomorrow-night-eighties span.cm-bracket {color: #CCCCCC;}
+.cm-s-tomorrow-night-eighties span.cm-tag {color: #f2777a;}
+.cm-s-tomorrow-night-eighties span.cm-link {color: #a16a94;}
+
+.cm-s-tomorrow-night-eighties .CodeMirror-matchingbracket { text-decoration: underline; color: white !important;}
diff --git a/third-party/codemirror-3.15/theme/twilight.css b/third-party/codemirror-3.15/theme/twilight.css
new file mode 100644 (file)
index 0000000..fd8944b
--- /dev/null
@@ -0,0 +1,26 @@
+.cm-s-twilight.CodeMirror { background: #141414; color: #f7f7f7; } /**/
+.cm-s-twilight .CodeMirror-selected { background: #323232 !important; } /**/
+
+.cm-s-twilight .CodeMirror-gutters { background: #222; border-right: 1px solid #aaa; }
+.cm-s-twilight .CodeMirror-linenumber { color: #aaa; }
+.cm-s-twilight .CodeMirror-cursor { border-left: 1px solid white !important; }
+
+.cm-s-twilight .cm-keyword {  color: #f9ee98; } /**/
+.cm-s-twilight .cm-atom { color: #FC0; }
+.cm-s-twilight .cm-number { color:  #ca7841; } /**/
+.cm-s-twilight .cm-def { color: #8DA6CE; }
+.cm-s-twilight span.cm-variable-2, .cm-s-twilight span.cm-tag { color: #607392; } /**/
+.cm-s-twilight span.cm-variable-3, .cm-s-twilight span.cm-def { color: #607392; } /**/
+.cm-s-twilight .cm-operator { color: #cda869; } /**/
+.cm-s-twilight .cm-comment { color:#777; font-style:italic; font-weight:normal; } /**/
+.cm-s-twilight .cm-string { color:#8f9d6a; font-style:italic; } /**/
+.cm-s-twilight .cm-string-2 { color:#bd6b18 } /*?*/
+.cm-s-twilight .cm-meta { background-color:#141414; color:#f7f7f7; } /*?*/
+.cm-s-twilight .cm-error { border-bottom: 1px solid red; }
+.cm-s-twilight .cm-builtin { color: #cda869; } /*?*/
+.cm-s-twilight .cm-tag { color: #997643; } /**/
+.cm-s-twilight .cm-attribute { color: #d6bb6d; } /*?*/
+.cm-s-twilight .cm-header { color: #FF6400; }
+.cm-s-twilight .cm-hr { color: #AEAEAE; }
+.cm-s-twilight .cm-link {   color:#ad9361; font-style:italic; text-decoration:none; } /**/
+
diff --git a/third-party/codemirror-3.15/theme/vibrant-ink.css b/third-party/codemirror-3.15/theme/vibrant-ink.css
new file mode 100644 (file)
index 0000000..4445be2
--- /dev/null
@@ -0,0 +1,27 @@
+/* Taken from the popular Visual Studio Vibrant Ink Schema */
+
+.cm-s-vibrant-ink.CodeMirror { background: black; color: white; }
+.cm-s-vibrant-ink .CodeMirror-selected { background: #35493c !important; }
+
+.cm-s-vibrant-ink .CodeMirror-gutters { background: #002240; border-right: 1px solid #aaa; }
+.cm-s-vibrant-ink .CodeMirror-linenumber { color: #d0d0d0; }
+.cm-s-vibrant-ink .CodeMirror-cursor { border-left: 1px solid white !important; }
+
+.cm-s-vibrant-ink .cm-keyword {  color: #CC7832; }
+.cm-s-vibrant-ink .cm-atom { color: #FC0; }
+.cm-s-vibrant-ink .cm-number { color:  #FFEE98; }
+.cm-s-vibrant-ink .cm-def { color: #8DA6CE; }
+.cm-s-vibrant-ink span.cm-variable-2, .cm-s-vibrant span.cm-tag { color: #FFC66D }
+.cm-s-vibrant-ink span.cm-variable-3, .cm-s-vibrant span.cm-def { color: #FFC66D }
+.cm-s-vibrant-ink .cm-operator { color: #888; }
+.cm-s-vibrant-ink .cm-comment { color: gray; font-weight: bold; }
+.cm-s-vibrant-ink .cm-string { color:  #A5C25C }
+.cm-s-vibrant-ink .cm-string-2 { color: red }
+.cm-s-vibrant-ink .cm-meta { color: #D8FA3C; }
+.cm-s-vibrant-ink .cm-error { border-bottom: 1px solid red; }
+.cm-s-vibrant-ink .cm-builtin { color: #8DA6CE; }
+.cm-s-vibrant-ink .cm-tag { color: #8DA6CE; }
+.cm-s-vibrant-ink .cm-attribute { color: #8DA6CE; }
+.cm-s-vibrant-ink .cm-header { color: #FF6400; }
+.cm-s-vibrant-ink .cm-hr { color: #AEAEAE; }
+.cm-s-vibrant-ink .cm-link { color: blue; }
diff --git a/third-party/codemirror-3.15/theme/xq-dark.css b/third-party/codemirror-3.15/theme/xq-dark.css
new file mode 100644 (file)
index 0000000..fd9bb12
--- /dev/null
@@ -0,0 +1,46 @@
+/*
+Copyright (C) 2011 by MarkLogic Corporation
+Author: Mike Brevoort <mike@brevoort.com>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+.cm-s-xq-dark.CodeMirror { background: #0a001f; color: #f8f8f8; }
+.cm-s-xq-dark span.CodeMirror-selected { background: #a8f !important; }
+.cm-s-xq-dark .CodeMirror-gutters { background: #0a001f; border-right: 1px solid #aaa; }
+.cm-s-xq-dark .CodeMirror-linenumber { color: #f8f8f8; }
+.cm-s-xq-dark .CodeMirror-cursor { border-left: 1px solid white !important; }
+
+.cm-s-xq-dark span.cm-keyword {color: #FFBD40;}
+.cm-s-xq-dark span.cm-atom {color: #6C8CD5;}
+.cm-s-xq-dark span.cm-number {color: #164;}
+.cm-s-xq-dark span.cm-def {color: #FFF; text-decoration:underline;}
+.cm-s-xq-dark span.cm-variable {color: #FFF;}
+.cm-s-xq-dark span.cm-variable-2 {color: #EEE;}
+.cm-s-xq-dark span.cm-variable-3 {color: #DDD;}
+.cm-s-xq-dark span.cm-property {}
+.cm-s-xq-dark span.cm-operator {}
+.cm-s-xq-dark span.cm-comment {color: gray;}
+.cm-s-xq-dark span.cm-string {color: #9FEE00;}
+.cm-s-xq-dark span.cm-meta {color: yellow;}
+.cm-s-xq-dark span.cm-error {color: #f00;}
+.cm-s-xq-dark span.cm-qualifier {color: #FFF700;}
+.cm-s-xq-dark span.cm-builtin {color: #30a;}
+.cm-s-xq-dark span.cm-bracket {color: #cc7;}
+.cm-s-xq-dark span.cm-tag {color: #FFBD40;}
+.cm-s-xq-dark span.cm-attribute {color: #FFF700;}
diff --git a/third-party/codemirror-3.15/theme/xq-light.css b/third-party/codemirror-3.15/theme/xq-light.css
new file mode 100644 (file)
index 0000000..08784d5
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+Copyright (C) 2011 by MarkLogic Corporation
+Author: Mike Brevoort <mike@brevoort.com>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+.cm-s-xq-light span.cm-keyword {line-height: 1em; font-weight: bold; color: #5A5CAD; }
+.cm-s-xq-light span.cm-atom {color: #6C8CD5;}
+.cm-s-xq-light span.cm-number {color: #164;}
+.cm-s-xq-light span.cm-def {text-decoration:underline;}
+.cm-s-xq-light span.cm-variable {color: black; }
+.cm-s-xq-light span.cm-variable-2 {color:black;}
+.cm-s-xq-light span.cm-variable-3 {color: black; }
+.cm-s-xq-light span.cm-property {}
+.cm-s-xq-light span.cm-operator {}
+.cm-s-xq-light span.cm-comment {color: #0080FF; font-style: italic;}
+.cm-s-xq-light span.cm-string {color: red;}
+.cm-s-xq-light span.cm-meta {color: yellow;}
+.cm-s-xq-light span.cm-error {color: #f00;}
+.cm-s-xq-light span.cm-qualifier {color: grey}
+.cm-s-xq-light span.cm-builtin {color: #7EA656;}
+.cm-s-xq-light span.cm-bracket {color: #cc7;}
+.cm-s-xq-light span.cm-tag {color: #3F7F7F;}
+.cm-s-xq-light span.cm-attribute {color: #7F007F;}
+
+.cm-s-xq-light .CodeMirror-activeline-background {background: #e8f2ff !important;}
+.cm-s-xq-light .CodeMirror-matchingbracket {border:1px solid grey;color:black !important;background:yellow;}
\ No newline at end of file
diff --git a/third-party/jquery-notify/alert.png b/third-party/jquery-notify/alert.png
new file mode 100644 (file)
index 0000000..d64c533
Binary files /dev/null and b/third-party/jquery-notify/alert.png differ
diff --git a/third-party/jquery-notify/jquery.notify.js b/third-party/jquery-notify/jquery.notify.js
new file mode 100644 (file)
index 0000000..dd1d748
--- /dev/null
@@ -0,0 +1,156 @@
+/* jQuery Notify UI Widget 1.5 by Eric Hynds
+ * http://www.erichynds.com/jquery/a-jquery-ui-growl-ubuntu-notification-widget/
+ *
+ * Depends:
+ *   - jQuery 1.4+
+ *   - jQuery UI 1.8 widget factory
+ *
+ * Dual licensed under the MIT and GPL licenses:
+ *   http://www.opensource.org/licenses/mit-license.php
+ *   http://www.gnu.org/licenses/gpl.html
+*/
+(function($){
+
+  $.widget("ech.notify", {
+
+    options: {
+      speed: 500,
+      expires: 5000,
+      stack: "below",
+      custom: false,
+      queue: false
+    },
+
+    _create: function(){
+      var self = this;
+      this.templates = {};
+      this.keys = [];
+
+      // build and save templates
+      this.element.addClass("ui-notify").children().addClass("ui-notify-message ui-notify-message-style").each(function(i){
+        var key = this.id || i;
+        self.keys.push(key);
+        self.templates[key] = $(this).removeAttr("id").wrap("<div></div>").parent().html(); // because $(this).andSelf().html() no workie
+      }).end().empty().show();
+    },
+
+    create: function(template, msg, opts){
+      if(typeof template === "object"){
+        opts = msg;
+        msg = template;
+        template = null;
+      }
+
+      var tpl = this.templates[ template || this.keys[0]];
+
+      // remove default styling class if rolling w/ custom classes
+      if(opts && opts.custom){
+        tpl = $(tpl).removeClass("ui-notify-message-style").wrap("<div></div>").parent().html();
+      }
+
+      this.openNotifications = this.openNotifications || 0;
+
+      // return a new notification instance
+      return new $.ech.notify.instance(this)._create(msg, $.extend({}, this.options, opts), tpl);            
+    }
+  });
+
+  // instance constructor
+  $.extend($.ech.notify, {
+    instance: function(widget){
+      this.__super = widget;
+      this.isOpen = false;
+    }
+  });
+
+  // instance methods
+  $.extend($.ech.notify.instance.prototype, {
+
+    _create: function(params, options, template){
+      this.options = options;
+
+      var self = this,
+
+      // build html template
+      html = template.replace(/#(?:\{|%7B)(.*?)(?:\}|%7D)/g, function($1, $2){
+        return ($2 in params) ? params[$2] : '';
+      }),
+
+      // the actual message
+      m = (this.element = $(html)),
+
+      // close link
+      closelink = m.find(".ui-notify-close");
+
+      // clickable?
+      if(typeof this.options.click === "function"){
+        m.addClass("ui-notify-click").bind("click", function(e){
+          self._trigger("click", e, self);
+        });
+      }
+
+      // show close link?
+      if(closelink.length){
+        closelink.bind("click", function(){
+          self.close();
+          return false;
+        });
+      }
+
+      this.__super.element.queue("notify", function(){
+        self.open();
+
+        // auto expire?
+        if(typeof options.expires === "number" && options.expires > 0){
+          setTimeout($.proxy(self.close, self), options.expires);
+        }
+      });
+
+      if(!this.options.queue || this.__super.openNotifications <= this.options.queue - 1) {
+        this.__super.element.dequeue("notify");
+      }
+
+      return this;
+    },
+
+    close: function(){
+      var speed = this.options.speed;
+
+      this.element.fadeTo(speed, 0).slideUp(speed, $.proxy(function(){
+        this._trigger("close");
+        this.isOpen = false;
+        this.element.remove();
+        this.__super.openNotifications -= 1;
+        this.__super.element.dequeue("notify");
+      }, this));
+
+      return this;
+    },
+
+    open: function(){
+      if(this.isOpen || this._trigger("beforeopen") === false){
+        return this;
+      }
+
+      var self = this;
+
+      this.__super.openNotifications += 1;
+
+      this.element[this.options.stack === "above" ? "prependTo" : "appendTo"](this.__super.element).css({ display:"none", opacity:"" }).fadeIn(this.options.speed, function(){
+        self._trigger("open");
+        self.isOpen = true;
+      });
+
+      return this;
+    },
+
+    widget: function(){
+      return this.element;
+    },
+
+    _trigger: function(type, e, instance){
+      return this.__super._trigger.call( this, type, e, instance );
+    }
+  });
+
+})(jQuery);
diff --git a/third-party/jquery-notify/jquery.notify.min.js b/third-party/jquery-notify/jquery.notify.min.js
new file mode 100644 (file)
index 0000000..4a076e1
--- /dev/null
@@ -0,0 +1,12 @@
+/* jQuery Notify UI Widget 1.5 by Eric Hynds
+ * http://www.erichynds.com/jquery/a-jquery-ui-growl-ubuntu-notification-widget/
+ *
+ * Depends:
+ *   - jQuery 1.4
+ *   - jQuery UI 1.8 widget factory
+ *
+ * Dual licensed under the MIT and GPL licenses:
+ *   http://www.opensource.org/licenses/mit-license.php
+ *   http://www.gnu.org/licenses/gpl.html
+*/
+(function(d){d.widget("ech.notify",{options:{speed:500,expires:5E3,stack:"below",custom:!1,queue:!1},_create:function(){var a=this;this.templates={};this.keys=[];this.element.addClass("ui-notify").children().addClass("ui-notify-message ui-notify-message-style").each(function(b){b=this.id||b;a.keys.push(b);a.templates[b]=d(this).removeAttr("id").wrap("<div></div>").parent().html()}).end().empty().show()},create:function(a,b,c){"object"===typeof a&&(c=b,b=a,a=null);a=this.templates[a||this.keys[0]];c&&c.custom&&(a=d(a).removeClass("ui-notify-message-style").wrap("<div></div>").parent().html());this.openNotifications=this.openNotifications||0;return(new d.ech.notify.instance(this))._create(b,d.extend({},this.options,c),a)}});d.extend(d.ech.notify,{instance:function(a){this.__super=a;this.isOpen=!1}});d.extend(d.ech.notify.instance.prototype,{_create:function(a,b,c){this.options=b;var e=this,c=c.replace(/#(?:\{|%7B)(.*?)(?:\}|%7D)/g,function(b,c){return c in a?a[c]:""}),c=this.element=d(c),f=c.find(".ui-notify-close");"function"===typeof this.options.click&&c.addClass("ui-notify-click").bind("click",function(a){e._trigger("click",a,e)});f.length&&f.bind("click",function(){e.close();return!1});this.__super.element.queue("notify",function(){e.open();"number"===typeof b.expires&&0<b.expires&&setTimeout(d.proxy(e.close,e),b.expires)});(!this.options.queue||this.__super.openNotifications<=this.options.queue-1)&&this.__super.element.dequeue("notify");return this},close:function(){var a=this.options.speed;this.element.fadeTo(a,0).slideUp(a,d.proxy(function(){this._trigger("close");this.isOpen=!1;this.element.remove();this.__super.openNotifications-=1;this.__super.element.dequeue("notify")},this));return this},open:function(){if(this.isOpen||!1===this._trigger("beforeopen"))return this;var a=this;this.__super.openNotifications+=1;this.element["above"===this.options.stack?"prependTo":"appendTo"](this.__super.element).css({display:"none",opacity:""}).fadeIn(this.options.speed,function(){a._trigger("open");a.isOpen=!0});return this},widget:function(){return this.element},_trigger:function(a,b,c){return this.__super._trigger.call(this,a,b,c)}})})(jQuery);
diff --git a/third-party/jquery-notify/style.css b/third-party/jquery-notify/style.css
new file mode 100644 (file)
index 0000000..167ebb5
--- /dev/null
@@ -0,0 +1,21 @@
+html, body { margin:0; padding:0; font:12px Helvetica, Arial, sans-serif }
+#content { padding:10px 30px; }
+a { color:#477099; text-decoration:none }
+a:hover { text-decoration:underline }
+
+#bar { background:#252823; padding:5px 10px; border-bottom:4px solid #C3D3DA }
+#bar h1 { margin:0; padding:0; color:#fff; font-size:40px; letter-spacing:-1px; text-shadow:0 0 4px #000000 }
+#bar h1 span { color:#C3D3DA }
+#bar div { float:right; margin-top:-50px; padding:20px 20px 0 0 }
+#bar a { color:#fff }
+
+.message { padding:10px; margin:15px 0; display:block; text-align:left; }
+.message-title { font-weight:bold; font-size:1.25em; }
+.message-body { margin-top:4px; }
+.error, .notice, .success {padding:.8em;margin-bottom:1em;border:2px solid #ddd;}
+.error {background:#FBE3E4;color:#8a1f11;border-color:#FBC2C4;}
+.notice {background:#FFF6BF;color:#514721;border-color:#FFD324;}
+.success {background:#E6EFC2;color:#264409;border-color:#C6D880;}
+.error a {color:#8a1f11;}
+.notice a {color:#514721;}
+.success a {color:#264409;}
diff --git a/third-party/jquery-notify/ui.notify.css b/third-party/jquery-notify/ui.notify.css
new file mode 100644 (file)
index 0000000..7d88a60
--- /dev/null
@@ -0,0 +1,20 @@
+.ui-notify { width:500px; position:fixed; top: 67px; right:10px; z-index: 999;}
+/* .ui-notify { width:350px; position:fixed; top:10px; right:10px; } */
+.ui-notify-message { padding:10px; margin-bottom:15px; -moz-border-radius:8px; -webkit-border-radius:8px; border-radius:8px; /* jordan */ max-height: 600px; }
+.ui-notify-message h1 { font-size:14px; margin:0; padding:0 }
+.ui-notify-message p { margin:3px 0; padding:0; line-height:18px }
+.ui-notify-message:last-child { margin-bottom:0 }
+.ui-notify-message-style { background:#000; background:rgba(0,0,0,0.8); -moz-box-shadow: 0 0 6px #000; -webkit-box-shadow: 0 0 6px #000; box-shadow: 0 0 6px #000; }
+.ui-notify-message-style h1 { color:#fff; font-weight:bold }
+.ui-notify-close { color:#fff; text-decoration:underline }
+.ui-notify-click { cursor:pointer }
+.ui-notify-cross { margin-top:-4px; float:right; cursor:pointer; text-decoration:none; font-size:12px; font-weight:bold; text-shadow:0 1px 1px #fff; padding:2px }
+.ui-notify-cross:hover { color:#ffffab }
+.ui-notify-cross:active { position:relative; top:1px }
+/* jordan */ 
+.ui-notify-message-style p,.ui-notify-message-style pre { 
+    font: normal 10px "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif;
+    background-color:#111; 
+    color:#eee;
+    max-height: 500px; 
+    overflow: auto; }
diff --git a/third-party/jquery/js/jquery.validate.js b/third-party/jquery/js/jquery.validate.js
new file mode 100644 (file)
index 0000000..51eb2ef
--- /dev/null
@@ -0,0 +1,1222 @@
+/**
+ * jQuery Validation Plugin 1.11.0pre
+ *
+ * http://bassistance.de/jquery-plugins/jquery-plugin-validation/
+ * http://docs.jquery.com/Plugins/Validation
+ *
+ * Copyright 2013 Jörn Zaefferer
+ * Released under the MIT license:
+ *   http://www.opensource.org/licenses/mit-license.php
+ */
+
+(function($) {
+
+$.extend($.fn, {
+    // http://docs.jquery.com/Plugins/Validation/validate
+    validate: function( options ) {
+
+        // if nothing is selected, return nothing; can't chain anyway
+        if ( !this.length ) {
+            if ( options && options.debug && window.console ) {
+                console.warn( "Nothing selected, can't validate, returning nothing." );
+            }
+            return;
+        }
+
+        // check if a validator for this form was already created
+        var validator = $.data( this[0], "validator" );
+        if ( validator ) {
+            return validator;
+        }
+
+        // Add novalidate tag if HTML5.
+        this.attr( "novalidate", "novalidate" );
+
+        validator = new $.validator( options, this[0] );
+        $.data( this[0], "validator", validator );
+
+        if ( validator.settings.onsubmit ) {
+
+            this.validateDelegate( ":submit", "click", function( event ) {
+                if ( validator.settings.submitHandler ) {
+                    validator.submitButton = event.target;
+                }
+                // allow suppressing validation by adding a cancel class to the submit button
+                if ( $(event.target).hasClass("cancel") ) {
+                    validator.cancelSubmit = true;
+                }
+            });
+
+            // validate the form on submit
+            this.submit( function( event ) {
+                if ( validator.settings.debug ) {
+                    // prevent form submit to be able to see console output
+                    event.preventDefault();
+                }
+                function handle() {
+                    var hidden;
+                    if ( validator.settings.submitHandler ) {
+                        if ( validator.submitButton ) {
+                            // insert a hidden input as a replacement for the missing submit button
+                            hidden = $("<input type='hidden'/>").attr("name", validator.submitButton.name).val(validator.submitButton.value).appendTo(validator.currentForm);
+                        }
+                        validator.settings.submitHandler.call( validator, validator.currentForm, event );
+                        if ( validator.submitButton ) {
+                            // and clean up afterwards; thanks to no-block-scope, hidden can be referenced
+                            hidden.remove();
+                        }
+                        return false;
+                    }
+                    return true;
+                }
+
+                // prevent submit for invalid forms or custom submit handlers
+                if ( validator.cancelSubmit ) {
+                    validator.cancelSubmit = false;
+                    return handle();
+                }
+                if ( validator.form() ) {
+                    if ( validator.pendingRequest ) {
+                        validator.formSubmitted = true;
+                        return false;
+                    }
+                    return handle();
+                } else {
+                    validator.focusInvalid();
+                    return false;
+                }
+            });
+        }
+
+        return validator;
+    },
+    // http://docs.jquery.com/Plugins/Validation/valid
+    valid: function() {
+        if ( $(this[0]).is("form")) {
+            return this.validate().form();
+        } else {
+            var valid = true;
+            var validator = $(this[0].form).validate();
+            this.each(function() {
+                valid &= validator.element(this);
+            });
+            return valid;
+        }
+    },
+    // attributes: space seperated list of attributes to retrieve and remove
+    removeAttrs: function( attributes ) {
+        var result = {},
+            $element = this;
+        $.each(attributes.split(/\s/), function( index, value ) {
+            result[value] = $element.attr(value);
+            $element.removeAttr(value);
+        });
+        return result;
+    },
+    // http://docs.jquery.com/Plugins/Validation/rules
+    rules: function( command, argument ) {
+        var element = this[0];
+
+        if ( command ) {
+            var settings = $.data(element.form, "validator").settings;
+            var staticRules = settings.rules;
+            var existingRules = $.validator.staticRules(element);
+            switch(command) {
+            case "add":
+                $.extend(existingRules, $.validator.normalizeRule(argument));
+                staticRules[element.name] = existingRules;
+                if ( argument.messages ) {
+                    settings.messages[element.name] = $.extend( settings.messages[element.name], argument.messages );
+                }
+                break;
+            case "remove":
+                if ( !argument ) {
+                    delete staticRules[element.name];
+                    return existingRules;
+                }
+                var filtered = {};
+                $.each(argument.split(/\s/), function( index, method ) {
+                    filtered[method] = existingRules[method];
+                    delete existingRules[method];
+                });
+                return filtered;
+            }
+        }
+
+        var data = $.validator.normalizeRules(
+        $.extend(
+            {},
+            $.validator.classRules(element),
+            $.validator.attributeRules(element),
+            $.validator.dataRules(element),
+            $.validator.staticRules(element)
+        ), element);
+
+        // make sure required is at front
+        if ( data.required ) {
+            var param = data.required;
+            delete data.required;
+            data = $.extend({required: param}, data);
+        }
+
+        return data;
+    }
+});
+
+// Custom selectors
+$.extend($.expr[":"], {
+    // http://docs.jquery.com/Plugins/Validation/blank
+    blank: function( a ) { return !$.trim("" + a.value); },
+    // http://docs.jquery.com/Plugins/Validation/filled
+    filled: function( a ) { return !!$.trim("" + a.value); },
+    // http://docs.jquery.com/Plugins/Validation/unchecked
+    unchecked: function( a ) { return !a.checked; }
+});
+
+// constructor for validator
+$.validator = function( options, form ) {
+    this.settings = $.extend( true, {}, $.validator.defaults, options );
+    this.currentForm = form;
+    this.init();
+};
+
+$.validator.format = function( source, params ) {
+    if ( arguments.length === 1 ) {
+        return function() {
+            var args = $.makeArray(arguments);
+            args.unshift(source);
+            return $.validator.format.apply( this, args );
+        };
+    }
+    if ( arguments.length > 2 && params.constructor !== Array  ) {
+        params = $.makeArray(arguments).slice(1);
+    }
+    if ( params.constructor !== Array ) {
+        params = [ params ];
+    }
+    $.each(params, function( i, n ) {
+        source = source.replace( new RegExp("\\{" + i + "\\}", "g"), function() {
+            return n;
+        });
+    });
+    return source;
+};
+
+$.extend($.validator, {
+
+    defaults: {
+        messages: {},
+        groups: {},
+        rules: {},
+        errorClass: "error",
+        validClass: "valid",
+        errorElement: "label",
+        focusInvalid: true,
+        errorContainer: $([]),
+        errorLabelContainer: $([]),
+        onsubmit: true,
+        ignore: ":hidden",
+        ignoreTitle: false,
+        onfocusin: function( element, event ) {
+            this.lastActive = element;
+
+            // hide error label and remove error class on focus if enabled
+            if ( this.settings.focusCleanup && !this.blockFocusCleanup ) {
+                if ( this.settings.unhighlight ) {
+                    this.settings.unhighlight.call( this, element, this.settings.errorClass, this.settings.validClass );
+                }
+                this.addWrapper(this.errorsFor(element)).hide();
+            }
+        },
+        onfocusout: function( element, event ) {
+            if ( !this.checkable(element) && (element.name in this.submitted || !this.optional(element)) ) {
+                this.element(element);
+            }
+        },
+        onkeyup: function( element, event ) {
+            if ( event.which === 9 && this.elementValue(element) === "" ) {
+                return;
+            } else if ( element.name in this.submitted || element === this.lastElement ) {
+                this.element(element);
+            }
+        },
+        onclick: function( element, event ) {
+            // click on selects, radiobuttons and checkboxes
+            if ( element.name in this.submitted ) {
+                this.element(element);
+            }
+            // or option elements, check parent select in that case
+            else if ( element.parentNode.name in this.submitted ) {
+                this.element(element.parentNode);
+            }
+        },
+        highlight: function( element, errorClass, validClass ) {
+            if ( element.type === "radio" ) {
+                this.findByName(element.name).addClass(errorClass).removeClass(validClass);
+            } else {
+                $(element).addClass(errorClass).removeClass(validClass);
+            }
+        },
+        unhighlight: function( element, errorClass, validClass ) {
+            if ( element.type === "radio" ) {
+                this.findByName(element.name).removeClass(errorClass).addClass(validClass);
+            } else {
+                $(element).removeClass(errorClass).addClass(validClass);
+            }
+        }
+    },
+
+    // http://docs.jquery.com/Plugins/Validation/Validator/setDefaults
+    setDefaults: function( settings ) {
+        $.extend( $.validator.defaults, settings );
+    },
+
+    messages: {
+        required: "This field is required.",
+        remote: "Please fix this field.",
+        email: "Please enter a valid email address.",
+        url: "Please enter a valid URL.",
+        date: "Please enter a valid date.",
+        dateISO: "Please enter a valid date (ISO).",
+        number: "Please enter a valid number.",
+        digits: "Please enter only digits.",
+        creditcard: "Please enter a valid credit card number.",
+        equalTo: "Please enter the same value again.",
+        maxlength: $.validator.format("Please enter no more than {0} characters."),
+        minlength: $.validator.format("Please enter at least {0} characters."),
+        rangelength: $.validator.format("Please enter a value between {0} and {1} characters long."),
+        range: $.validator.format("Please enter a value between {0} and {1}."),
+        max: $.validator.format("Please enter a value less than or equal to {0}."),
+        min: $.validator.format("Please enter a value greater than or equal to {0}.")
+    },
+
+    autoCreateRanges: false,
+
+    prototype: {
+
+        init: function() {
+            this.labelContainer = $(this.settings.errorLabelContainer);
+            this.errorContext = this.labelContainer.length && this.labelContainer || $(this.currentForm);
+            this.containers = $(this.settings.errorContainer).add( this.settings.errorLabelContainer );
+            this.submitted = {};
+            this.valueCache = {};
+            this.pendingRequest = 0;
+            this.pending = {};
+            this.invalid = {};
+            this.reset();
+
+            var groups = (this.groups = {});
+            $.each(this.settings.groups, function( key, value ) {
+                if ( typeof value === "string" ) {
+                    value = value.split(/\s/);
+                }
+                $.each(value, function( index, name ) {
+                    groups[name] = key;
+                });
+            });
+            var rules = this.settings.rules;
+            $.each(rules, function( key, value ) {
+                rules[key] = $.validator.normalizeRule(value);
+            });
+
+            function delegate(event) {
+                var validator = $.data(this[0].form, "validator"),
+                    eventType = "on" + event.type.replace(/^validate/, "");
+                if ( validator.settings[eventType] ) {
+                    validator.settings[eventType].call(validator, this[0], event);
+                }
+            }
+            $(this.currentForm)
+                .validateDelegate(":text, [type='password'], [type='file'], select, textarea, " +
+                    "[type='number'], [type='search'] ,[type='tel'], [type='url'], " +
+                    "[type='email'], [type='datetime'], [type='date'], [type='month'], " +
+                    "[type='week'], [type='time'], [type='datetime-local'], " +
+                    "[type='range'], [type='color'] ",
+                    "focusin focusout keyup", delegate)
+                .validateDelegate("[type='radio'], [type='checkbox'], select, option", "click", delegate);
+
+            if ( this.settings.invalidHandler ) {
+                $(this.currentForm).bind("invalid-form.validate", this.settings.invalidHandler);
+            }
+        },
+
+        // http://docs.jquery.com/Plugins/Validation/Validator/form
+        form: function() {
+            this.checkForm();
+            $.extend(this.submitted, this.errorMap);
+            this.invalid = $.extend({}, this.errorMap);
+            if ( !this.valid() ) {
+                $(this.currentForm).triggerHandler("invalid-form", [this]);
+            }
+            this.showErrors();
+            return this.valid();
+        },
+
+        checkForm: function() {
+            this.prepareForm();
+            for ( var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++ ) {
+                this.check( elements[i] );
+            }
+            return this.valid();
+        },
+
+        // http://docs.jquery.com/Plugins/Validation/Validator/element
+        element: function( element ) {
+            element = this.validationTargetFor( this.clean( element ) );
+            this.lastElement = element;
+            this.prepareElement( element );
+            this.currentElements = $(element);
+            var result = this.check( element ) !== false;
+            if ( result ) {
+                delete this.invalid[element.name];
+            } else {
+                this.invalid[element.name] = true;
+            }
+            if ( !this.numberOfInvalids() ) {
+                // Hide error containers on last error
+                this.toHide = this.toHide.add( this.containers );
+            }
+            this.showErrors();
+            return result;
+        },
+
+        // http://docs.jquery.com/Plugins/Validation/Validator/showErrors
+        showErrors: function( errors ) {
+            if ( errors ) {
+                // add items to error list and map
+                $.extend( this.errorMap, errors );
+                this.errorList = [];
+                for ( var name in errors ) {
+                    this.errorList.push({
+                        message: errors[name],
+                        element: this.findByName(name)[0]
+                    });
+                }
+                // remove items from success list
+                this.successList = $.grep( this.successList, function( element ) {
+                    return !(element.name in errors);
+                });
+            }
+            if ( this.settings.showErrors ) {
+                this.settings.showErrors.call( this, this.errorMap, this.errorList );
+            } else {
+                this.defaultShowErrors();
+            }
+        },
+
+        // http://docs.jquery.com/Plugins/Validation/Validator/resetForm
+        resetForm: function() {
+            if ( $.fn.resetForm ) {
+                $(this.currentForm).resetForm();
+            }
+            this.submitted = {};
+            this.lastElement = null;
+            this.prepareForm();
+            this.hideErrors();
+            this.elements().removeClass( this.settings.errorClass ).removeData( "previousValue" );
+        },
+
+        numberOfInvalids: function() {
+            return this.objectLength(this.invalid);
+        },
+
+        objectLength: function( obj ) {
+            var count = 0;
+            for ( var i in obj ) {
+                count++;
+            }
+            return count;
+        },
+
+        hideErrors: function() {
+            this.addWrapper( this.toHide ).hide();
+        },
+
+        valid: function() {
+            return this.size() === 0;
+        },
+
+        size: function() {
+            return this.errorList.length;
+        },
+
+        focusInvalid: function() {
+            if ( this.settings.focusInvalid ) {
+                try {
+                    $(this.findLastActive() || this.errorList.length && this.errorList[0].element || [])
+                    .filter(":visible")
+                    .focus()
+                    // manually trigger focusin event; without it, focusin handler isn't called, findLastActive won't have anything to find
+                    .trigger("focusin");
+                } catch(e) {
+                    // ignore IE throwing errors when focusing hidden elements
+                }
+            }
+        },
+
+        findLastActive: function() {
+            var lastActive = this.lastActive;
+            return lastActive && $.grep(this.errorList, function( n ) {
+                return n.element.name === lastActive.name;
+            }).length === 1 && lastActive;
+        },
+
+        elements: function() {
+            var validator = this,
+                rulesCache = {};
+
+            // select all valid inputs inside the form (no submit or reset buttons)
+            return $(this.currentForm)
+            .find("input, select, textarea")
+            .not(":submit, :reset, :image, [disabled]")
+            .not( this.settings.ignore )
+            .filter(function() {
+                if ( !this.name ) {
+                    if ( window.console ) {
+                        console.error( "%o has no name assigned", this );
+                    }
+                    throw new Error( "Failed to validate, found an element with no name assigned. See console for element reference." );
+                }
+
+                // select only the first element for each name, and only those with rules specified
+                if ( this.name in rulesCache || !validator.objectLength($(this).rules()) ) {
+                    return false;
+                }
+
+                rulesCache[this.name] = true;
+                return true;
+            });
+        },
+
+        clean: function( selector ) {
+            return $(selector)[0];
+        },
+
+        errors: function() {
+            var errorClass = this.settings.errorClass.replace(" ", ".");
+            return $(this.settings.errorElement + "." + errorClass, this.errorContext);
+        },
+
+        reset: function() {
+            this.successList = [];
+            this.errorList = [];
+            this.errorMap = {};
+            this.toShow = $([]);
+            this.toHide = $([]);
+            this.currentElements = $([]);
+        },
+
+        prepareForm: function() {
+            this.reset();
+            this.toHide = this.errors().add( this.containers );
+        },
+
+        prepareElement: function( element ) {
+            this.reset();
+            this.toHide = this.errorsFor(element);
+        },
+
+        elementValue: function( element ) {
+            var type = $(element).attr("type"),
+                val = $(element).val();
+
+            if ( type === "radio" || type === "checkbox" ) {
+                return $("input[name='" + $(element).attr("name") + "']:checked").val();
+            }
+
+            if ( typeof val === "string" ) {
+                return val.replace(/\r/g, "");
+            }
+            return val;
+        },
+
+        check: function( element ) {
+            element = this.validationTargetFor( this.clean( element ) );
+
+            var rules = $(element).rules();
+            var dependencyMismatch = false;
+            var val = this.elementValue(element);
+            var result;
+
+            for (var method in rules ) {
+                var rule = { method: method, parameters: rules[method] };
+                try {
+
+                    result = $.validator.methods[method].call( this, val, element, rule.parameters );
+
+                    // if a method indicates that the field is optional and therefore valid,
+                    // don't mark it as valid when there are no other rules
+                    if ( result === "dependency-mismatch" ) {
+                        dependencyMismatch = true;
+                        continue;
+                    }
+                    dependencyMismatch = false;
+
+                    if ( result === "pending" ) {
+                        this.toHide = this.toHide.not( this.errorsFor(element) );
+                        return;
+                    }
+
+                    if ( !result ) {
+                        this.formatAndAdd( element, rule );
+                        return false;
+                    }
+                } catch(e) {
+                    if ( this.settings.debug && window.console ) {
+                        console.log( "Exception occured when checking element " + element.id + ", check the '" + rule.method + "' method.", e );
+                    }
+                    throw e;
+                }
+            }
+            if ( dependencyMismatch ) {
+                return;
+            }
+            if ( this.objectLength(rules) ) {
+                this.successList.push(element);
+            }
+            return true;
+        },
+
+        // return the custom message for the given element and validation method
+        // specified in the element's HTML5 data attribute
+        customDataMessage: function( element, method ) {
+            return $(element).data("msg-" + method.toLowerCase()) || (element.attributes && $(element).attr("data-msg-" + method.toLowerCase()));
+        },
+
+        // return the custom message for the given element name and validation method
+        customMessage: function( name, method ) {
+            var m = this.settings.messages[name];
+            return m && (m.constructor === String ? m : m[method]);
+        },
+
+        // return the first defined argument, allowing empty strings
+        findDefined: function() {
+            for(var i = 0; i < arguments.length; i++) {
+                if ( arguments[i] !== undefined ) {
+                    return arguments[i];
+                }
+            }
+            return undefined;
+        },
+
+        defaultMessage: function( element, method ) {
+            return this.findDefined(
+                this.customMessage( element.name, method ),
+                this.customDataMessage( element, method ),
+                // title is never undefined, so handle empty string as undefined
+                !this.settings.ignoreTitle && element.title || undefined,
+                $.validator.messages[method],
+                "<strong>Warning: No message defined for " + element.name + "</strong>"
+            );
+        },
+
+        formatAndAdd: function( element, rule ) {
+            var message = this.defaultMessage( element, rule.method ),
+                theregex = /\$?\{(\d+)\}/g;
+            if ( typeof message === "function" ) {
+                message = message.call(this, rule.parameters, element);
+            } else if (theregex.test(message)) {
+                message = $.validator.format(message.replace(theregex, "{$1}"), rule.parameters);
+            }
+            this.errorList.push({
+                message: message,
+                element: element
+            });
+
+            this.errorMap[element.name] = message;
+            this.submitted[element.name] = message;
+        },
+
+        addWrapper: function( toToggle ) {
+            if ( this.settings.wrapper ) {
+                toToggle = toToggle.add( toToggle.parent( this.settings.wrapper ) );
+            }
+            return toToggle;
+        },
+
+        defaultShowErrors: function() {
+            var i, elements;
+            for ( i = 0; this.errorList[i]; i++ ) {
+                var error = this.errorList[i];
+                if ( this.settings.highlight ) {
+                    this.settings.highlight.call( this, error.element, this.settings.errorClass, this.settings.validClass );
+                }
+                this.showLabel( error.element, error.message );
+            }
+            if ( this.errorList.length ) {
+                this.toShow = this.toShow.add( this.containers );
+            }
+            if ( this.settings.success ) {
+                for ( i = 0; this.successList[i]; i++ ) {
+                    this.showLabel( this.successList[i] );
+                }
+            }
+            if ( this.settings.unhighlight ) {
+                for ( i = 0, elements = this.validElements(); elements[i]; i++ ) {
+                    this.settings.unhighlight.call( this, elements[i], this.settings.errorClass, this.settings.validClass );
+                }
+            }
+            this.toHide = this.toHide.not( this.toShow );
+            this.hideErrors();
+            this.addWrapper( this.toShow ).show();
+        },
+
+        validElements: function() {
+            return this.currentElements.not(this.invalidElements());
+        },
+
+        invalidElements: function() {
+            return $(this.errorList).map(function() {
+                return this.element;
+            });
+        },
+
+        showLabel: function( element, message ) {
+            var label = this.errorsFor( element );
+            if ( label.length ) {
+                // refresh error/success class
+                label.removeClass( this.settings.validClass ).addClass( this.settings.errorClass );
+
+                // check if we have a generated label, replace the message then
+                if ( label.attr("generated") ) {
+                    label.html(message);
+                }
+            } else {
+                // create label
+                label = $("<" + this.settings.errorElement + "/>")
+                    .attr({"for":  this.idOrName(element), generated: true})
+                    .addClass(this.settings.errorClass)
+                    .html(message || "");
+                if ( this.settings.wrapper ) {
+                    // make sure the element is visible, even in IE
+                    // actually showing the wrapped element is handled elsewhere
+                    label = label.hide().show().wrap("<" + this.settings.wrapper + "/>").parent();
+                }
+                if ( !this.labelContainer.append(label).length ) {
+                    if ( this.settings.errorPlacement ) {
+                        this.settings.errorPlacement(label, $(element) );
+                    } else {
+                        label.insertAfter(element);
+                    }
+                }
+            }
+            if ( !message && this.settings.success ) {
+                label.text("");
+                if ( typeof this.settings.success === "string" ) {
+                    label.addClass( this.settings.success );
+                } else {
+                    this.settings.success( label, element );
+                }
+            }
+            this.toShow = this.toShow.add(label);
+        },
+
+        errorsFor: function( element ) {
+            var name = this.idOrName(element);
+            return this.errors().filter(function() {
+                return $(this).attr("for") === name;
+            });
+        },
+
+        idOrName: function( element ) {
+            return this.groups[element.name] || (this.checkable(element) ? element.name : element.id || element.name);
+        },
+
+        validationTargetFor: function( element ) {
+            // if radio/checkbox, validate first element in group instead
+            if ( this.checkable(element) ) {
+                element = this.findByName( element.name ).not(this.settings.ignore)[0];
+            }
+            return element;
+        },
+
+        checkable: function( element ) {
+            return (/radio|checkbox/i).test(element.type);
+        },
+
+        findByName: function( name ) {
+            return $(this.currentForm).find("[name='" + name + "']");
+        },
+
+        getLength: function( value, element ) {
+            switch( element.nodeName.toLowerCase() ) {
+            case "select":
+                return $("option:selected", element).length;
+            case "input":
+                if ( this.checkable( element) ) {
+                    return this.findByName(element.name).filter(":checked").length;
+                }
+            }
+            return value.length;
+        },
+
+        depend: function( param, element ) {
+            return this.dependTypes[typeof param] ? this.dependTypes[typeof param](param, element) : true;
+        },
+
+        dependTypes: {
+            "boolean": function( param, element ) {
+                return param;
+            },
+            "string": function( param, element ) {
+                return !!$(param, element.form).length;
+            },
+            "function": function( param, element ) {
+                return param(element);
+            }
+        },
+
+        optional: function( element ) {
+            var val = this.elementValue(element);
+            return !$.validator.methods.required.call(this, val, element) && "dependency-mismatch";
+        },
+
+        startRequest: function( element ) {
+            if ( !this.pending[element.name] ) {
+                this.pendingRequest++;
+                this.pending[element.name] = true;
+            }
+        },
+
+        stopRequest: function( element, valid ) {
+            this.pendingRequest--;
+            // sometimes synchronization fails, make sure pendingRequest is never < 0
+            if ( this.pendingRequest < 0 ) {
+                this.pendingRequest = 0;
+            }
+            delete this.pending[element.name];
+            if ( valid && this.pendingRequest === 0 && this.formSubmitted && this.form() ) {
+                $(this.currentForm).submit();
+                this.formSubmitted = false;
+            } else if (!valid && this.pendingRequest === 0 && this.formSubmitted) {
+                $(this.currentForm).triggerHandler("invalid-form", [this]);
+                this.formSubmitted = false;
+            }
+        },
+
+        previousValue: function( element ) {
+            return $.data(element, "previousValue") || $.data(element, "previousValue", {
+                old: null,
+                valid: true,
+                message: this.defaultMessage( element, "remote" )
+            });
+        }
+
+    },
+
+    classRuleSettings: {
+        required: {required: true},
+        email: {email: true},
+        url: {url: true},
+        date: {date: true},
+        dateISO: {dateISO: true},
+        number: {number: true},
+        digits: {digits: true},
+        creditcard: {creditcard: true}
+    },
+
+    addClassRules: function( className, rules ) {
+        if ( className.constructor === String ) {
+            this.classRuleSettings[className] = rules;
+        } else {
+            $.extend(this.classRuleSettings, className);
+        }
+    },
+
+    classRules: function( element ) {
+        var rules = {};
+        var classes = $(element).attr("class");
+        if ( classes ) {
+            $.each(classes.split(" "), function() {
+                if ( this in $.validator.classRuleSettings ) {
+                    $.extend(rules, $.validator.classRuleSettings[this]);
+                }
+            });
+        }
+        return rules;
+    },
+
+    attributeRules: function( element ) {
+        var rules = {};
+        var $element = $(element);
+
+        for (var method in $.validator.methods) {
+            var value;
+
+            // support for <input required> in both html5 and older browsers
+            if ( method === "required" ) {
+                value = $element.get(0).getAttribute(method);
+                // Some browsers return an empty string for the required attribute
+                // and non-HTML5 browsers might have required="" markup
+                if ( value === "" ) {
+                    value = true;
+                }
+                // force non-HTML5 browsers to return bool
+                value = !!value;
+            } else {
+                value = $element.attr(method);
+            }
+
+            if ( value ) {
+                rules[method] = value;
+            } else if ( $element[0].getAttribute("type") === method ) {
+                rules[method] = true;
+            }
+        }
+
+        // maxlength may be returned as -1, 2147483647 (IE) and 524288 (safari) for text inputs
+        if ( rules.maxlength && /-1|2147483647|524288/.test(rules.maxlength) ) {
+            delete rules.maxlength;
+        }
+
+        return rules;
+    },
+
+    dataRules: function( element ) {
+        var method, value,
+            rules = {}, $element = $(element);
+        for (method in $.validator.methods) {
+            value = $element.data("rule-" + method.toLowerCase());
+            if ( value !== undefined ) {
+                rules[method] = value;
+            }
+        }
+        return rules;
+    },
+
+    staticRules: function( element ) {
+        var rules = {};
+        var validator = $.data(element.form, "validator");
+        if ( validator.settings.rules ) {
+            rules = $.validator.normalizeRule(validator.settings.rules[element.name]) || {};
+        }
+        return rules;
+    },
+
+    normalizeRules: function( rules, element ) {
+        // handle dependency check
+        $.each(rules, function( prop, val ) {
+            // ignore rule when param is explicitly false, eg. required:false
+            if ( val === false ) {
+                delete rules[prop];
+                return;
+            }
+            if ( val.param || val.depends ) {
+                var keepRule = true;
+                switch (typeof val.depends) {
+                case "string":
+                    keepRule = !!$(val.depends, element.form).length;
+                    break;
+                case "function":
+                    keepRule = val.depends.call(element, element);
+                    break;
+                }
+                if ( keepRule ) {
+                    rules[prop] = val.param !== undefined ? val.param : true;
+                } else {
+                    delete rules[prop];
+                }
+            }
+        });
+
+        // evaluate parameters
+        $.each(rules, function( rule, parameter ) {
+            rules[rule] = $.isFunction(parameter) ? parameter(element) : parameter;
+        });
+
+        // clean number parameters
+        $.each(["minlength", "maxlength", "min", "max"], function() {
+            if ( rules[this] ) {
+                rules[this] = Number(rules[this]);
+            }
+        });
+        $.each(["rangelength", "range"], function() {
+            var parts;
+            if ( rules[this] ) {
+                if ( $.isArray(rules[this]) ) {
+                    rules[this] = [Number(rules[this][0]), Number(rules[this][1])];
+                } else if ( typeof rules[this] === "string" ) {
+                    parts = rules[this].split(/[\s,]+/);
+                    rules[this] = [Number(parts[0]), Number(parts[1])];
+                }
+            }
+        });
+
+        if ( $.validator.autoCreateRanges ) {
+            // auto-create ranges
+            if ( rules.min && rules.max ) {
+                rules.range = [rules.min, rules.max];
+                delete rules.min;
+                delete rules.max;
+            }
+            if ( rules.minlength && rules.maxlength ) {
+                rules.rangelength = [rules.minlength, rules.maxlength];
+                delete rules.minlength;
+                delete rules.maxlength;
+            }
+        }
+
+        return rules;
+    },
+
+    // Converts a simple string to a {string: true} rule, e.g., "required" to {required:true}
+    normalizeRule: function( data ) {
+        if ( typeof data === "string" ) {
+            var transformed = {};
+            $.each(data.split(/\s/), function() {
+                transformed[this] = true;
+            });
+            data = transformed;
+        }
+        return data;
+    },
+
+    // http://docs.jquery.com/Plugins/Validation/Validator/addMethod
+    addMethod: function( name, method, message ) {
+        $.validator.methods[name] = method;
+        $.validator.messages[name] = message !== undefined ? message : $.validator.messages[name];
+        if ( method.length < 3 ) {
+            $.validator.addClassRules(name, $.validator.normalizeRule(name));
+        }
+    },
+
+    methods: {
+
+        // http://docs.jquery.com/Plugins/Validation/Methods/required
+        required: function( value, element, param ) {
+            // check if dependency is met
+            if ( !this.depend(param, element) ) {
+                return "dependency-mismatch";
+            }
+            if ( element.nodeName.toLowerCase() === "select" ) {
+                // could be an array for select-multiple or a string, both are fine this way
+                var val = $(element).val();
+                return val && val.length > 0;
+            }
+            if ( this.checkable(element) ) {
+                return this.getLength(value, element) > 0;
+            }
+            return $.trim(value).length > 0;
+        },
+
+        // http://docs.jquery.com/Plugins/Validation/Methods/remote
+        remote: function( value, element, param ) {
+            if ( this.optional(element) ) {
+                return "dependency-mismatch";
+            }
+
+            var previous = this.previousValue(element);
+            if (!this.settings.messages[element.name] ) {
+                this.settings.messages[element.name] = {};
+            }
+            previous.originalMessage = this.settings.messages[element.name].remote;
+            this.settings.messages[element.name].remote = previous.message;
+
+            param = typeof param === "string" && {url:param} || param;
+
+            if ( previous.old === value ) {
+                return previous.valid;
+            }
+
+            previous.old = value;
+            var validator = this;
+            this.startRequest(element);
+            var data = {};
+            data[element.name] = value;
+            $.ajax($.extend(true, {
+                url: param,
+                mode: "abort",
+                port: "validate" + element.name,
+                dataType: "json",
+                data: data,
+                success: function( response ) {
+                    validator.settings.messages[element.name].remote = previous.originalMessage;
+                    var valid = response === true || response === "true";
+                    if ( valid ) {
+                        var submitted = validator.formSubmitted;
+                        validator.prepareElement(element);
+                        validator.formSubmitted = submitted;
+                        validator.successList.push(element);
+                        delete validator.invalid[element.name];
+                        validator.showErrors();
+                    } else {
+                        var errors = {};
+                        var message = response || validator.defaultMessage( element, "remote" );
+                        errors[element.name] = previous.message = $.isFunction(message) ? message(value) : message;
+                        validator.invalid[element.name] = true;
+                        validator.showErrors(errors);
+                    }
+                    previous.valid = valid;
+                    validator.stopRequest(element, valid);
+                }
+            }, param));
+            return "pending";
+        },
+
+        // http://docs.jquery.com/Plugins/Validation/Methods/minlength
+        minlength: function( value, element, param ) {
+            var length = $.isArray( value ) ? value.length : this.getLength($.trim(value), element);
+            return this.optional(element) || length >= param;
+        },
+
+        // http://docs.jquery.com/Plugins/Validation/Methods/maxlength
+        maxlength: function( value, element, param ) {
+            var length = $.isArray( value ) ? value.length : this.getLength($.trim(value), element);
+            return this.optional(element) || length <= param;
+        },
+
+        // http://docs.jquery.com/Plugins/Validation/Methods/rangelength
+        rangelength: function( value, element, param ) {
+            var length = $.isArray( value ) ? value.length : this.getLength($.trim(value), element);
+            return this.optional(element) || ( length >= param[0] && length <= param[1] );
+        },
+
+        // http://docs.jquery.com/Plugins/Validation/Methods/min
+        min: function( value, element, param ) {
+            return this.optional(element) || value >= param;
+        },
+
+        // http://docs.jquery.com/Plugins/Validation/Methods/max
+        max: function( value, element, param ) {
+            return this.optional(element) || value <= param;
+        },
+
+        // http://docs.jquery.com/Plugins/Validation/Methods/range
+        range: function( value, element, param ) {
+            return this.optional(element) || ( value >= param[0] && value <= param[1] );
+        },
+
+        // http://docs.jquery.com/Plugins/Validation/Methods/email
+        email: function( value, element ) {
+            // contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
+            return this.optional(element) || /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(value);
+        },
+
+        // http://docs.jquery.com/Plugins/Validation/Methods/url
+        url: function( value, element ) {
+            // contributed by Scott Gonzalez: http://projects.scottsplayground.com/iri/
+            return this.optional(element) || /^(https?|s?ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value);
+        },
+
+        // http://docs.jquery.com/Plugins/Validation/Methods/date
+        date: function( value, element ) {
+            return this.optional(element) || !/Invalid|NaN/.test(new Date(value).toString());
+        },
+
+        // http://docs.jquery.com/Plugins/Validation/Methods/dateISO
+        dateISO: function( value, element ) {
+            return this.optional(element) || /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/.test(value);
+        },
+
+        // http://docs.jquery.com/Plugins/Validation/Methods/number
+        number: function( value, element ) {
+            return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(value);
+        },
+
+        // http://docs.jquery.com/Plugins/Validation/Methods/digits
+        digits: function( value, element ) {
+            return this.optional(element) || /^\d+$/.test(value);
+        },
+
+        // http://docs.jquery.com/Plugins/Validation/Methods/creditcard
+        // based on http://en.wikipedia.org/wiki/Luhn
+        creditcard: function( value, element ) {
+            if ( this.optional(element) ) {
+                return "dependency-mismatch";
+            }
+            // accept only spaces, digits and dashes
+            if ( /[^0-9 \-]+/.test(value) ) {
+                return false;
+            }
+            var nCheck = 0,
+                nDigit = 0,
+                bEven = false;
+
+            value = value.replace(/\D/g, "");
+
+            for (var n = value.length - 1; n >= 0; n--) {
+                var cDigit = value.charAt(n);
+                nDigit = parseInt(cDigit, 10);
+                if ( bEven ) {
+                    if ( (nDigit *= 2) > 9 ) {
+                        nDigit -= 9;
+                    }
+                }
+                nCheck += nDigit;
+                bEven = !bEven;
+            }
+
+            return (nCheck % 10) === 0;
+        },
+
+        // http://docs.jquery.com/Plugins/Validation/Methods/equalTo
+        equalTo: function( value, element, param ) {
+            // bind to the blur event of the target in order to revalidate whenever the target field is updated
+            // TODO find a way to bind the event just once, avoiding the unbind-rebind overhead
+            var target = $(param);
+            if ( this.settings.onfocusout ) {
+                target.unbind(".validate-equalTo").bind("blur.validate-equalTo", function() {
+                    $(element).valid();
+                });
+            }
+            return value === target.val();
+        }
+
+    }
+
+});
+
+// deprecated, use $.validator.format instead
+$.format = $.validator.format;
+
+}(jQuery));
+
+// ajax mode: abort
+// usage: $.ajax({ mode: "abort"[, port: "uniqueport"]});
+// if mode:"abort" is used, the previous request on that port (port can be undefined) is aborted via XMLHttpRequest.abort()
+(function($) {
+    var pendingRequests = {};
+    // Use a prefilter if available (1.5+)
+    if ( $.ajaxPrefilter ) {
+        $.ajaxPrefilter(function( settings, _, xhr ) {
+            var port = settings.port;
+            if ( settings.mode === "abort" ) {
+                if ( pendingRequests[port] ) {
+                    pendingRequests[port].abort();
+                }
+                pendingRequests[port] = xhr;
+            }
+        });
+    } else {
+        // Proxy ajax
+        var ajax = $.ajax;
+        $.ajax = function( settings ) {
+            var mode = ( "mode" in settings ? settings : $.ajaxSettings ).mode,
+                port = ( "port" in settings ? settings : $.ajaxSettings ).port;
+            if ( mode === "abort" ) {
+                if ( pendingRequests[port] ) {
+                    pendingRequests[port].abort();
+                }
+                return (pendingRequests[port] = ajax.apply(this, arguments));
+            }
+            return ajax.apply(this, arguments);
+        };
+    }
+}(jQuery));
+
+// provides delegate(type: String, delegate: Selector, handler: Callback) plugin for easier event delegation
+// handler is only called when $(event.target).is(delegate), in the scope of the jquery-object for event.target
+(function($) {
+    $.extend($.fn, {
+        validateDelegate: function( delegate, type, handler ) {
+            return this.bind(type, function( event ) {
+                var target = $(event.target);
+                if ( target.is(delegate) ) {
+                    return handler.apply(target, arguments);
+                }
+            });
+        }
+    });
+}(jQuery));
+
+
diff --git a/third-party/mustache/mustache.js b/third-party/mustache/mustache.js
new file mode 100644 (file)
index 0000000..bee26f9
--- /dev/null
@@ -0,0 +1,536 @@
+/*!
+ * mustache.js - Logic-less {{mustache}} templates with JavaScript
+ * http://github.com/janl/mustache.js
+ */
+
+/*global define: false*/
+
+(function (root, factory) {
+  if (typeof exports === "object" && exports) {
+    factory(exports); // CommonJS
+  } else {
+    var mustache = {};
+    factory(mustache);
+    if (typeof define === "function" && define.amd) {
+      define(mustache); // AMD
+    } else {
+      root.Mustache = mustache; // <script>
+    }
+  }
+}(this, function (mustache) {
+
+  var whiteRe = /\s*/;
+  var spaceRe = /\s+/;
+  var nonSpaceRe = /\S/;
+  var eqRe = /\s*=/;
+  var curlyRe = /\s*\}/;
+  var tagRe = /#|\^|\/|>|\{|&|=|!/;
+
+  // Workaround for https://issues.apache.org/jira/browse/COUCHDB-577
+  // See https://github.com/janl/mustache.js/issues/189
+  var RegExp_test = RegExp.prototype.test;
+  function testRegExp(re, string) {
+    return RegExp_test.call(re, string);
+  }
+
+  function isWhitespace(string) {
+    return !testRegExp(nonSpaceRe, string);
+  }
+
+  var Object_toString = Object.prototype.toString;
+  var isArray = Array.isArray || function (obj) {
+    return Object_toString.call(obj) === '[object Array]';
+  };
+
+  function escapeRegExp(string) {
+    return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
+  }
+
+  var entityMap = {
+    "&": "&amp;",
+    "<": "&lt;",
+    ">": "&gt;",
+    '"': '&quot;',
+    "'": '&#39;',
+    "/": '&#x2F;'
+  };
+
+  function escapeHtml(string) {
+    return String(string).replace(/[&<>"'\/]/g, function (s) {
+      return entityMap[s];
+    });
+  }
+
+  function Scanner(string) {
+    this.string = string;
+    this.tail = string;
+    this.pos = 0;
+  }
+
+  /**
+   * Returns `true` if the tail is empty (end of string).
+   */
+  Scanner.prototype.eos = function () {
+    return this.tail === "";
+  };
+
+  /**
+   * Tries to match the given regular expression at the current position.
+   * Returns the matched text if it can match, the empty string otherwise.
+   */
+  Scanner.prototype.scan = function (re) {
+    var match = this.tail.match(re);
+
+    if (match && match.index === 0) {
+      this.tail = this.tail.substring(match[0].length);
+      this.pos += match[0].length;
+      return match[0];
+    }
+
+    return "";
+  };
+
+  /**
+   * Skips all text until the given regular expression can be matched. Returns
+   * the skipped string, which is the entire tail if no match can be made.
+   */
+  Scanner.prototype.scanUntil = function (re) {
+    var match, pos = this.tail.search(re);
+
+    switch (pos) {
+    case -1:
+      match = this.tail;
+      this.pos += this.tail.length;
+      this.tail = "";
+      break;
+    case 0:
+      match = "";
+      break;
+    default:
+      match = this.tail.substring(0, pos);
+      this.tail = this.tail.substring(pos);
+      this.pos += pos;
+    }
+
+    return match;
+  };
+
+  function Context(view, parent) {
+    this.view = view || {};
+    this.parent = parent;
+    this._cache = {};
+  }
+
+  Context.make = function (view) {
+    return (view instanceof Context) ? view : new Context(view);
+  };
+
+  Context.prototype.push = function (view) {
+    return new Context(view, this);
+  };
+
+  Context.prototype.lookup = function (name) {
+    var value = this._cache[name];
+
+    if (!value) {
+      if (name == '.') {
+        value = this.view;
+      } else {
+        var context = this;
+
+        while (context) {
+          if (name.indexOf('.') > 0) {
+            value = context.view;
+            var names = name.split('.'), i = 0;
+            while (value && i < names.length) {
+              value = value[names[i++]];
+            }
+          } else {
+            value = context.view[name];
+          }
+
+          if (value != null) break;
+
+          context = context.parent;
+        }
+      }
+
+      this._cache[name] = value;
+    }
+
+    if (typeof value === 'function') value = value.call(this.view);
+
+    return value;
+  };
+
+  function Writer() {
+    this.clearCache();
+  }
+
+  Writer.prototype.clearCache = function () {
+    this._cache = {};
+    this._partialCache = {};
+  };
+
+  Writer.prototype.compile = function (template, tags) {
+    var fn = this._cache[template];
+
+    if (!fn) {
+      var tokens = mustache.parse(template, tags);
+      fn = this._cache[template] = this.compileTokens(tokens, template);
+    }
+
+    return fn;
+  };
+
+  Writer.prototype.compilePartial = function (name, template, tags) {
+    var fn = this.compile(template, tags);
+    this._partialCache[name] = fn;
+    return fn;
+  };
+
+  Writer.prototype.getPartial = function (name) {
+    if (!(name in this._partialCache) && this._loadPartial) {
+      this.compilePartial(name, this._loadPartial(name));
+    }
+
+    return this._partialCache[name];
+  };
+
+  Writer.prototype.compileTokens = function (tokens, template) {
+    var self = this;
+    return function (view, partials) {
+      if (partials) {
+        if (typeof partials === 'function') {
+          self._loadPartial = partials;
+        } else {
+          for (var name in partials) {
+            self.compilePartial(name, partials[name]);
+          }
+        }
+      }
+
+      return renderTokens(tokens, self, Context.make(view), template);
+    };
+  };
+
+  Writer.prototype.render = function (template, view, partials) {
+    return this.compile(template)(view, partials);
+  };
+
+  /**
+   * Low-level function that renders the given `tokens` using the given `writer`
+   * and `context`. The `template` string is only needed for templates that use
+   * higher-order sections to extract the portion of the original template that
+   * was contained in that section.
+   */
+  function renderTokens(tokens, writer, context, template) {
+    var buffer = '';
+
+    var token, tokenValue, value;
+    for (var i = 0, len = tokens.length; i < len; ++i) {
+      token = tokens[i];
+      tokenValue = token[1];
+
+      switch (token[0]) {
+      case '#':
+        value = context.lookup(tokenValue);
+
+        if (typeof value === 'object') {
+          if (isArray(value)) {
+            for (var j = 0, jlen = value.length; j < jlen; ++j) {
+              buffer += renderTokens(token[4], writer, context.push(value[j]), template);
+            }
+          } else if (value) {
+            buffer += renderTokens(token[4], writer, context.push(value), template);
+          }
+        } else if (typeof value === 'function') {
+          var text = template == null ? null : template.slice(token[3], token[5]);
+          value = value.call(context.view, text, function (template) {
+            return writer.render(template, context);
+          });
+          if (value != null) buffer += value;
+        } else if (value) {
+          buffer += renderTokens(token[4], writer, context, template);
+        }
+
+        break;
+      case '^':
+        value = context.lookup(tokenValue);
+
+        // Use JavaScript's definition of falsy. Include empty arrays.
+        // See https://github.com/janl/mustache.js/issues/186
+        if (!value || (isArray(value) && value.length === 0)) {
+          buffer += renderTokens(token[4], writer, context, template);
+        }
+
+        break;
+      case '>':
+        value = writer.getPartial(tokenValue);
+        if (typeof value === 'function') buffer += value(context);
+        break;
+      case '&':
+        value = context.lookup(tokenValue);
+        if (value != null) buffer += value;
+        break;
+      case 'name':
+        value = context.lookup(tokenValue);
+        if (value != null) buffer += mustache.escape(value);
+        break;
+      case 'text':
+        buffer += tokenValue;
+        break;
+      }
+    }
+
+    return buffer;
+  }
+
+  /**
+   * Forms the given array of `tokens` into a nested tree structure where
+   * tokens that represent a section have two additional items: 1) an array of
+   * all tokens that appear in that section and 2) the index in the original
+   * template that represents the end of that section.
+   */
+  function nestTokens(tokens) {
+    var tree = [];
+    var collector = tree;
+    var sections = [];
+
+    var token;
+    for (var i = 0, len = tokens.length; i < len; ++i) {
+      token = tokens[i];
+      switch (token[0]) {
+      case '#':
+      case '^':
+        sections.push(token);
+        collector.push(token);
+        collector = token[4] = [];
+        break;
+      case '/':
+        var section = sections.pop();
+        section[5] = token[2];
+        collector = sections.length > 0 ? sections[sections.length - 1][4] : tree;
+        break;
+      default:
+        collector.push(token);
+      }
+    }
+
+    return tree;
+  }
+
+  /**
+   * Combines the values of consecutive text tokens in the given `tokens` array
+   * to a single token.
+   */
+  function squashTokens(tokens) {
+    var squashedTokens = [];
+
+    var token, lastToken;
+    for (var i = 0, len = tokens.length; i < len; ++i) {
+      token = tokens[i];
+      if (token) {
+        if (token[0] === 'text' && lastToken && lastToken[0] === 'text') {
+          lastToken[1] += token[1];
+          lastToken[3] = token[3];
+        } else {
+          lastToken = token;
+          squashedTokens.push(token);
+        }
+      }
+    }
+
+    return squashedTokens;
+  }
+
+  function escapeTags(tags) {
+    return [
+      new RegExp(escapeRegExp(tags[0]) + "\\s*"),
+      new RegExp("\\s*" + escapeRegExp(tags[1]))
+    ];
+  }
+
+  /**
+   * Breaks up the given `template` string into a tree of token objects. If
+   * `tags` is given here it must be an array with two string values: the
+   * opening and closing tags used in the template (e.g. ["<%", "%>"]). Of
+   * course, the default is to use mustaches (i.e. Mustache.tags).
+   */
+  function parseTemplate(template, tags) {
+    template = template || '';
+    tags = tags || mustache.tags;
+
+    if (typeof tags === 'string') tags = tags.split(spaceRe);
+    if (tags.length !== 2) throw new Error('Invalid tags: ' + tags.join(', '));
+
+    var tagRes = escapeTags(tags);
+    var scanner = new Scanner(template);
+
+    var sections = [];     // Stack to hold section tokens
+    var tokens = [];       // Buffer to hold the tokens
+    var spaces = [];       // Indices of whitespace tokens on the current line
+    var hasTag = false;    // Is there a {{tag}} on the current line?
+    var nonSpace = false;  // Is there a non-space char on the current line?
+
+    // Strips all whitespace tokens array for the current line
+    // if there was a {{#tag}} on it and otherwise only space.
+    function stripSpace() {
+      if (hasTag && !nonSpace) {
+        while (spaces.length) {
+          delete tokens[spaces.pop()];
+        }
+      } else {
+        spaces = [];
+      }
+
+      hasTag = false;
+      nonSpace = false;
+    }
+
+    var start, type, value, chr, token;
+    while (!scanner.eos()) {
+      start = scanner.pos;
+
+      // Match any text between tags.
+      value = scanner.scanUntil(tagRes[0]);
+      if (value) {
+        for (var i = 0, len = value.length; i < len; ++i) {
+          chr = value.charAt(i);
+
+          if (isWhitespace(chr)) {
+            spaces.push(tokens.length);
+          } else {
+            nonSpace = true;
+          }
+
+          tokens.push(['text', chr, start, start + 1]);
+          start += 1;
+
+          // Check for whitespace on the current line.
+          if (chr == '\n') stripSpace();
+        }
+      }
+
+      // Match the opening tag.
+      if (!scanner.scan(tagRes[0])) break;
+      hasTag = true;
+
+      // Get the tag type.
+      type = scanner.scan(tagRe) || 'name';
+      scanner.scan(whiteRe);
+
+      // Get the tag value.
+      if (type === '=') {
+        value = scanner.scanUntil(eqRe);
+        scanner.scan(eqRe);
+        scanner.scanUntil(tagRes[1]);
+      } else if (type === '{') {
+        value = scanner.scanUntil(new RegExp('\\s*' + escapeRegExp('}' + tags[1])));
+        scanner.scan(curlyRe);
+        scanner.scanUntil(tagRes[1]);
+        type = '&';
+      } else {
+        value = scanner.scanUntil(tagRes[1]);
+      }
+
+      // Match the closing tag.
+      if (!scanner.scan(tagRes[1])) throw new Error('Unclosed tag at ' + scanner.pos);
+
+      token = [type, value, start, scanner.pos];
+      tokens.push(token);
+
+      if (type === '#' || type === '^') {
+        sections.push(token);
+      } else if (type === '/') {
+        // Check section nesting.
+        if (sections.length === 0) throw new Error('Unopened section "' + value + '" at ' + start);
+        var openSection = sections.pop();
+        if (openSection[1] !== value) throw new Error('Unclosed section "' + openSection[1] + '" at ' + start);
+      } else if (type === 'name' || type === '{' || type === '&') {
+        nonSpace = true;
+      } else if (type === '=') {
+        // Set the tags for the next time around.
+        tags = value.split(spaceRe);
+        if (tags.length !== 2) throw new Error('Invalid tags at ' + start + ': ' + tags.join(', '));
+        tagRes = escapeTags(tags);
+      }
+    }
+
+    // Make sure there are no open sections when we're done.
+    var openSection = sections.pop();
+    if (openSection) throw new Error('Unclosed section "' + openSection[1] + '" at ' + scanner.pos);
+
+    tokens = squashTokens(tokens);
+
+    return nestTokens(tokens);
+  }
+
+  mustache.name = "mustache.js";
+  mustache.version = "0.7.2";
+  mustache.tags = ["{{", "}}"];
+
+  mustache.Scanner = Scanner;
+  mustache.Context = Context;
+  mustache.Writer = Writer;
+
+  mustache.parse = parseTemplate;
+
+  // Export the escaping function so that the user may override it.
+  // See https://github.com/janl/mustache.js/issues/244
+  mustache.escape = escapeHtml;
+
+  // All Mustache.* functions use this writer.
+  var defaultWriter = new Writer();
+
+  /**
+   * Clears all cached templates and partials in the default writer.
+   */
+  mustache.clearCache = function () {
+    return defaultWriter.clearCache();
+  };
+
+  /**
+   * Compiles the given `template` to a reusable function using the default
+   * writer.
+   */
+  mustache.compile = function (template, tags) {
+    return defaultWriter.compile(template, tags);
+  };
+
+  /**
+   * Compiles the partial with the given `name` and `template` to a reusable
+   * function using the default writer.
+   */
+  mustache.compilePartial = function (name, template, tags) {
+    return defaultWriter.compilePartial(name, template, tags);
+  };
+
+  /**
+   * Compiles the given array of tokens (the output of a parse) to a reusable
+   * function using the default writer.
+   */
+  mustache.compileTokens = function (tokens, template) {
+    return defaultWriter.compileTokens(tokens, template);
+  };
+
+  /**
+   * Renders the `template` with the given `view` and `partials` using the
+   * default writer.
+   */
+  mustache.render = function (template, view, partials) {
+    return defaultWriter.render(template, view, partials);
+  };
+
+  // This is here for backwards compatibility with 0.4.x.
+  mustache.to_html = function (template, view, partials, send) {
+    var result = mustache.render(template, view, partials);
+
+    if (typeof send === "function") {
+      send(result);
+    } else {
+      return result;
+    }
+  };
+
+}));
diff --git a/third-party/smartwizard-1636c86/images/loader.gif b/third-party/smartwizard-1636c86/images/loader.gif
new file mode 100644 (file)
index 0000000..7e717cd
Binary files /dev/null and b/third-party/smartwizard-1636c86/images/loader.gif differ
diff --git a/third-party/smartwizard-1636c86/index.htm b/third-party/smartwizard-1636c86/index.htm
new file mode 100644 (file)
index 0000000..13bad1d
--- /dev/null
@@ -0,0 +1,160 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml"><head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>Smart Wizard 2 - Basic Example  - a javascript jQuery wizard control plugin</title>
+
+<link href="styles/smart_wizard.css" rel="stylesheet" type="text/css">
+<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
+<script type="text/javascript" src="js/jquery.smartWizard-2.0.min.js"></script>
+
+<script type="text/javascript">
+    $(document).ready(function(){
+       // Smart Wizard         
+               $('#wizard').smartWizard();
+      
+      function onFinishCallback(){
+        $('#wizard').smartWizard('showMessage','Finish Clicked');
+      }     
+               });
+</script>
+
+</head><body>
+
+<table align="center" border="0" cellpadding="0" cellspacing="0">
+<tr><td> 
+<!-- Smart Wizard -->
+               <div id="wizard" class="swMain">
+                       <ul>
+                               <li><a href="#step-1">
+                <span class="stepNumber">1</span>
+                <span class="stepDesc">
+                   Step 1<br />
+                   <small>Step 1 description</small>
+                </span>
+            </a></li>
+                               <li><a href="#step-2">
+                <span class="stepNumber">2</span>
+                <span class="stepDesc">
+                   Step 2<br />
+                   <small>Step 2 description</small>
+                </span>
+            </a></li>
+                               <li><a href="#step-3">
+                <span class="stepNumber">3</span>
+                <span class="stepDesc">
+                   Step 3<br />
+                   <small>Step 3 description</small>
+                </span>                   
+             </a></li>
+                               <li><a href="#step-4">
+                <span class="stepNumber">4</span>
+                <span class="stepDesc">
+                   Step 4<br />
+                   <small>Step 4 description</small>
+                </span>                   
+            </a></li>
+                       </ul>
+                       <div id="step-1">       
+            <h2 class="StepTitle">Step 1 Content</h2>
+            <ul type="disk">
+                                   <li>List 1</li>
+                                   <li>List 2</li>
+            </ul>
+            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>                               
+        </div>
+                       <div id="step-2">
+            <h2 class="StepTitle">Step 2 Content</h2>  
+            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p> 
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>          
+        </div>                      
+                       <div id="step-3">
+            <h2 class="StepTitle">Step 3 Content</h2>  
+            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>                                                         
+        </div>
+                       <div id="step-4">
+            <h2 class="StepTitle">Step 4 Content</h2>  
+            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>                                       
+        </div>
+               </div>
+<!-- End SmartWizard Content -->               
+               
+</td></tr>
+</table>
+               
+</body>
+</html>
diff --git a/third-party/smartwizard-1636c86/js/jquery-1.4.2.min.js b/third-party/smartwizard-1636c86/js/jquery-1.4.2.min.js
new file mode 100644 (file)
index 0000000..7c24308
--- /dev/null
@@ -0,0 +1,154 @@
+/*!
+ * jQuery JavaScript Library v1.4.2
+ * http://jquery.com/
+ *
+ * Copyright 2010, John Resig
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ * http://jquery.org/license
+ *
+ * Includes Sizzle.js
+ * http://sizzlejs.com/
+ * Copyright 2010, The Dojo Foundation
+ * Released under the MIT, BSD, and GPL Licenses.
+ *
+ * Date: Sat Feb 13 22:33:48 2010 -0500
+ */
+(function(A,w){function ma(){if(!c.isReady){try{s.documentElement.doScroll("left")}catch(a){setTimeout(ma,1);return}c.ready()}}function Qa(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 X(a,b,d,f,e,j){var i=a.length;if(typeof b==="object"){for(var o in b)X(a,o,b[o],f,e,d);return a}if(d!==w){f=!j&&f&&c.isFunction(d);for(o=0;o<i;o++)e(a[o],b,f?d.call(a[o],o,e(a[o],b)):d,j);return a}return i?
+e(a[0],b):w}function J(){return(new Date).getTime()}function Y(){return false}function Z(){return true}function na(a,b,d){d[0].type=a;return c.event.handle.apply(b,d)}function oa(a){var b,d=[],f=[],e=arguments,j,i,o,k,n,r;i=c.data(this,"events");if(!(a.liveFired===this||!i||!i.live||a.button&&a.type==="click")){a.liveFired=this;var u=i.live.slice(0);for(k=0;k<u.length;k++){i=u[k];i.origType.replace(O,"")===a.type?f.push(i.selector):u.splice(k--,1)}j=c(a.target).closest(f,a.currentTarget);n=0;for(r=
+j.length;n<r;n++)for(k=0;k<u.length;k++){i=u[k];if(j[n].selector===i.selector){o=j[n].elem;f=null;if(i.preType==="mouseenter"||i.preType==="mouseleave")f=c(a.relatedTarget).closest(i.selector)[0];if(!f||f!==o)d.push({elem:o,handleObj:i})}}n=0;for(r=d.length;n<r;n++){j=d[n];a.currentTarget=j.elem;a.data=j.handleObj.data;a.handleObj=j.handleObj;if(j.handleObj.origHandler.apply(j.elem,e)===false){b=false;break}}return b}}function pa(a,b){return"live."+(a&&a!=="*"?a+".":"")+b.replace(/\./g,"`").replace(/ /g,
+"&")}function qa(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function ra(a,b){var d=0;b.each(function(){if(this.nodeName===(a[d]&&a[d].nodeName)){var f=c.data(a[d++]),e=c.data(this,f);if(f=f&&f.events){delete e.handle;e.events={};for(var j in f)for(var i in f[j])c.event.add(this,j,f[j][i],f[j][i].data)}}})}function sa(a,b,d){var f,e,j;b=b&&b[0]?b[0].ownerDocument||b[0]:s;if(a.length===1&&typeof a[0]==="string"&&a[0].length<512&&b===s&&!ta.test(a[0])&&(c.support.checkClone||!ua.test(a[0]))){e=
+true;if(j=c.fragments[a[0]])if(j!==1)f=j}if(!f){f=b.createDocumentFragment();c.clean(a,b,f,d)}if(e)c.fragments[a[0]]=j?f:1;return{fragment:f,cacheable:e}}function K(a,b){var d={};c.each(va.concat.apply([],va.slice(0,b)),function(){d[this]=a});return d}function wa(a){return"scrollTo"in a&&a.document?a:a.nodeType===9?a.defaultView||a.parentWindow:false}var c=function(a,b){return new c.fn.init(a,b)},Ra=A.jQuery,Sa=A.$,s=A.document,T,Ta=/^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/,Ua=/^.[^:#\[\.,]*$/,Va=/\S/,
+Wa=/^(\s|\u00A0)+|(\s|\u00A0)+$/g,Xa=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,P=navigator.userAgent,xa=false,Q=[],L,$=Object.prototype.toString,aa=Object.prototype.hasOwnProperty,ba=Array.prototype.push,R=Array.prototype.slice,ya=Array.prototype.indexOf;c.fn=c.prototype={init:function(a,b){var d,f;if(!a)return this;if(a.nodeType){this.context=this[0]=a;this.length=1;return this}if(a==="body"&&!b){this.context=s;this[0]=s.body;this.selector="body";this.length=1;return this}if(typeof a==="string")if((d=Ta.exec(a))&&
+(d[1]||!b))if(d[1]){f=b?b.ownerDocument||b:s;if(a=Xa.exec(a))if(c.isPlainObject(b)){a=[s.createElement(a[1])];c.fn.attr.call(a,b,true)}else a=[f.createElement(a[1])];else{a=sa([d[1]],[f]);a=(a.cacheable?a.fragment.cloneNode(true):a.fragment).childNodes}return c.merge(this,a)}else{if(b=s.getElementById(d[2])){if(b.id!==d[2])return T.find(a);this.length=1;this[0]=b}this.context=s;this.selector=a;return this}else if(!b&&/^\w+$/.test(a)){this.selector=a;this.context=s;a=s.getElementsByTagName(a);return c.merge(this,
+a)}else return!b||b.jquery?(b||T).find(a):c(b).find(a);else if(c.isFunction(a))return T.ready(a);if(a.selector!==w){this.selector=a.selector;this.context=a.context}return c.makeArray(a,this)},selector:"",jquery:"1.4.2",length:0,size:function(){return this.length},toArray:function(){return R.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this.slice(a)[0]:this[a]},pushStack:function(a,b,d){var f=c();c.isArray(a)?ba.apply(f,a):c.merge(f,a);f.prevObject=this;f.context=this.context;if(b===
+"find")f.selector=this.selector+(this.selector?" ":"")+d;else if(b)f.selector=this.selector+"."+b+"("+d+")";return f},each:function(a,b){return c.each(this,a,b)},ready:function(a){c.bindReady();if(c.isReady)a.call(s,c);else Q&&Q.push(a);return this},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(R.apply(this,arguments),"slice",R.call(arguments).join(","))},map:function(a){return this.pushStack(c.map(this,
+function(b,d){return a.call(b,d,b)}))},end:function(){return this.prevObject||c(null)},push:ba,sort:[].sort,splice:[].splice};c.fn.init.prototype=c.fn;c.extend=c.fn.extend=function(){var a=arguments[0]||{},b=1,d=arguments.length,f=false,e,j,i,o;if(typeof a==="boolean"){f=a;a=arguments[1]||{};b=2}if(typeof a!=="object"&&!c.isFunction(a))a={};if(d===b){a=this;--b}for(;b<d;b++)if((e=arguments[b])!=null)for(j in e){i=a[j];o=e[j];if(a!==o)if(f&&o&&(c.isPlainObject(o)||c.isArray(o))){i=i&&(c.isPlainObject(i)||
+c.isArray(i))?i:c.isArray(o)?[]:{};a[j]=c.extend(f,i,o)}else if(o!==w)a[j]=o}return a};c.extend({noConflict:function(a){A.$=Sa;if(a)A.jQuery=Ra;return c},isReady:false,ready:function(){if(!c.isReady){if(!s.body)return setTimeout(c.ready,13);c.isReady=true;if(Q){for(var a,b=0;a=Q[b++];)a.call(s,c);Q=null}c.fn.triggerHandler&&c(s).triggerHandler("ready")}},bindReady:function(){if(!xa){xa=true;if(s.readyState==="complete")return c.ready();if(s.addEventListener){s.addEventListener("DOMContentLoaded",
+L,false);A.addEventListener("load",c.ready,false)}else if(s.attachEvent){s.attachEvent("onreadystatechange",L);A.attachEvent("onload",c.ready);var a=false;try{a=A.frameElement==null}catch(b){}s.documentElement.doScroll&&a&&ma()}}},isFunction:function(a){return $.call(a)==="[object Function]"},isArray:function(a){return $.call(a)==="[object Array]"},isPlainObject:function(a){if(!a||$.call(a)!=="[object Object]"||a.nodeType||a.setInterval)return false;if(a.constructor&&!aa.call(a,"constructor")&&!aa.call(a.constructor.prototype,
+"isPrototypeOf"))return false;var b;for(b in a);return b===w||aa.call(a,b)},isEmptyObject:function(a){for(var b in a)return false;return true},error:function(a){throw a;},parseJSON:function(a){if(typeof a!=="string"||!a)return null;a=c.trim(a);if(/^[\],:{}\s]*$/.test(a.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"")))return A.JSON&&A.JSON.parse?A.JSON.parse(a):(new Function("return "+
+a))();else c.error("Invalid JSON: "+a)},noop:function(){},globalEval:function(a){if(a&&Va.test(a)){var b=s.getElementsByTagName("head")[0]||s.documentElement,d=s.createElement("script");d.type="text/javascript";if(c.support.scriptEval)d.appendChild(s.createTextNode(a));else d.text=a;b.insertBefore(d,b.firstChild);b.removeChild(d)}},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,b,d){var f,e=0,j=a.length,i=j===w||c.isFunction(a);if(d)if(i)for(f in a){if(b.apply(a[f],
+d)===false)break}else for(;e<j;){if(b.apply(a[e++],d)===false)break}else if(i)for(f in a){if(b.call(a[f],f,a[f])===false)break}else for(d=a[0];e<j&&b.call(d,e,d)!==false;d=a[++e]);return a},trim:function(a){return(a||"").replace(Wa,"")},makeArray:function(a,b){b=b||[];if(a!=null)a.length==null||typeof a==="string"||c.isFunction(a)||typeof a!=="function"&&a.setInterval?ba.call(b,a):c.merge(b,a);return b},inArray:function(a,b){if(b.indexOf)return b.indexOf(a);for(var d=0,f=b.length;d<f;d++)if(b[d]===
+a)return d;return-1},merge:function(a,b){var d=a.length,f=0;if(typeof b.length==="number")for(var e=b.length;f<e;f++)a[d++]=b[f];else for(;b[f]!==w;)a[d++]=b[f++];a.length=d;return a},grep:function(a,b,d){for(var f=[],e=0,j=a.length;e<j;e++)!d!==!b(a[e],e)&&f.push(a[e]);return f},map:function(a,b,d){for(var f=[],e,j=0,i=a.length;j<i;j++){e=b(a[j],j,d);if(e!=null)f[f.length]=e}return f.concat.apply([],f)},guid:1,proxy:function(a,b,d){if(arguments.length===2)if(typeof b==="string"){d=a;a=d[b];b=w}else if(b&&
+!c.isFunction(b)){d=b;b=w}if(!b&&a)b=function(){return a.apply(d||this,arguments)};if(a)b.guid=a.guid=a.guid||b.guid||c.guid++;return b},uaMatch:function(a){a=a.toLowerCase();a=/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version)?[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||!/compatible/.test(a)&&/(mozilla)(?:.*? rv:([\w.]+))?/.exec(a)||[];return{browser:a[1]||"",version:a[2]||"0"}},browser:{}});P=c.uaMatch(P);if(P.browser){c.browser[P.browser]=true;c.browser.version=P.version}if(c.browser.webkit)c.browser.safari=
+true;if(ya)c.inArray=function(a,b){return ya.call(b,a)};T=c(s);if(s.addEventListener)L=function(){s.removeEventListener("DOMContentLoaded",L,false);c.ready()};else if(s.attachEvent)L=function(){if(s.readyState==="complete"){s.detachEvent("onreadystatechange",L);c.ready()}};(function(){c.support={};var a=s.documentElement,b=s.createElement("script"),d=s.createElement("div"),f="script"+J();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 e=d.getElementsByTagName("*"),j=d.getElementsByTagName("a")[0];if(!(!e||!e.length||!j)){c.support={leadingWhitespace:d.firstChild.nodeType===3,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/red/.test(j.getAttribute("style")),hrefNormalized:j.getAttribute("href")==="/a",opacity:/^0.55$/.test(j.style.opacity),cssFloat:!!j.style.cssFloat,checkOn:d.getElementsByTagName("input")[0].value==="on",optSelected:s.createElement("select").appendChild(s.createElement("option")).selected,
+parentNode:d.removeChild(d.appendChild(s.createElement("div"))).parentNode===null,deleteExpando:true,checkClone:false,scriptEval:false,noCloneEvent:true,boxModel:null};b.type="text/javascript";try{b.appendChild(s.createTextNode("window."+f+"=1;"))}catch(i){}a.insertBefore(b,a.firstChild);if(A[f]){c.support.scriptEval=true;delete A[f]}try{delete b.test}catch(o){c.support.deleteExpando=false}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function k(){c.support.noCloneEvent=
+false;d.detachEvent("onclick",k)});d.cloneNode(true).fireEvent("onclick")}d=s.createElement("div");d.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";a=s.createDocumentFragment();a.appendChild(d.firstChild);c.support.checkClone=a.cloneNode(true).cloneNode(true).lastChild.checked;c(function(){var k=s.createElement("div");k.style.width=k.style.paddingLeft="1px";s.body.appendChild(k);c.boxModel=c.support.boxModel=k.offsetWidth===2;s.body.removeChild(k).style.display="none"});a=function(k){var n=
+s.createElement("div");k="on"+k;var r=k in n;if(!r){n.setAttribute(k,"return;");r=typeof n[k]==="function"}return r};c.support.submitBubbles=a("submit");c.support.changeBubbles=a("change");a=b=d=e=j=null}})();c.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};var G="jQuery"+J(),Ya=0,za={};c.extend({cache:{},expando:G,noData:{embed:true,object:true,
+applet:true},data:function(a,b,d){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var f=a[G],e=c.cache;if(!f&&typeof b==="string"&&d===w)return null;f||(f=++Ya);if(typeof b==="object"){a[G]=f;e[f]=c.extend(true,{},b)}else if(!e[f]){a[G]=f;e[f]={}}a=e[f];if(d!==w)a[b]=d;return typeof b==="string"?a[b]:a}},removeData:function(a,b){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var d=a[G],f=c.cache,e=f[d];if(b){if(e){delete e[b];c.isEmptyObject(e)&&c.removeData(a)}}else{if(c.support.deleteExpando)delete a[c.expando];
+else a.removeAttribute&&a.removeAttribute(c.expando);delete f[d]}}}});c.fn.extend({data:function(a,b){if(typeof a==="undefined"&&this.length)return c.data(this[0]);else if(typeof a==="object")return this.each(function(){c.data(this,a)});var d=a.split(".");d[1]=d[1]?"."+d[1]:"";if(b===w){var f=this.triggerHandler("getData"+d[1]+"!",[d[0]]);if(f===w&&this.length)f=c.data(this[0],a);return f===w&&d[1]?this.data(d[0]):f}else return this.trigger("setData"+d[1]+"!",[d[0],b]).each(function(){c.data(this,
+a,b)})},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 f=c.data(a,b);if(!d)return f||[];if(!f||c.isArray(d))f=c.data(a,b,c.makeArray(d));else f.push(d);return f}},dequeue:function(a,b){b=b||"fx";var d=c.queue(a,b),f=d.shift();if(f==="inprogress")f=d.shift();if(f){b==="fx"&&d.unshift("inprogress");f.call(a,function(){c.dequeue(a,b)})}}});c.fn.extend({queue:function(a,b){if(typeof a!=="string"){b=a;a="fx"}if(b===
+w)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 Aa=/[\n\t]/g,ca=/\s+/,Za=/\r/g,$a=/href|src|style/,ab=/(button|input)/i,bb=/(button|input|object|select|textarea)/i,
+cb=/^(a|area)$/i,Ba=/radio|checkbox/;c.fn.extend({attr:function(a,b){return X(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(n){var r=c(this);r.addClass(a.call(this,n,r.attr("class")))});if(a&&typeof a==="string")for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1)if(e.className){for(var j=" "+e.className+" ",
+i=e.className,o=0,k=b.length;o<k;o++)if(j.indexOf(" "+b[o]+" ")<0)i+=" "+b[o];e.className=c.trim(i)}else e.className=a}return this},removeClass:function(a){if(c.isFunction(a))return this.each(function(k){var n=c(this);n.removeClass(a.call(this,k,n.attr("class")))});if(a&&typeof a==="string"||a===w)for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1&&e.className)if(a){for(var j=(" "+e.className+" ").replace(Aa," "),i=0,o=b.length;i<o;i++)j=j.replace(" "+b[i]+" ",
+" ");e.className=c.trim(j)}else e.className=""}return this},toggleClass:function(a,b){var d=typeof a,f=typeof b==="boolean";if(c.isFunction(a))return this.each(function(e){var j=c(this);j.toggleClass(a.call(this,e,j.attr("class"),b),b)});return this.each(function(){if(d==="string")for(var e,j=0,i=c(this),o=b,k=a.split(ca);e=k[j++];){o=f?o:!i.hasClass(e);i[o?"addClass":"removeClass"](e)}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(Aa," ").indexOf(a)>-1)return true;return false},val:function(a){if(a===w){var b=this[0];if(b){if(c.nodeName(b,"option"))return(b.attributes.value||{}).specified?b.value:b.text;if(c.nodeName(b,"select")){var d=b.selectedIndex,f=[],e=b.options;b=b.type==="select-one";if(d<0)return null;var j=b?d:0;for(d=b?d+1:e.length;j<d;j++){var i=
+e[j];if(i.selected){a=c(i).val();if(b)return a;f.push(a)}}return f}if(Ba.test(b.type)&&!c.support.checkOn)return b.getAttribute("value")===null?"on":b.value;return(b.value||"").replace(Za,"")}return w}var o=c.isFunction(a);return this.each(function(k){var n=c(this),r=a;if(this.nodeType===1){if(o)r=a.call(this,k,n.val());if(typeof r==="number")r+="";if(c.isArray(r)&&Ba.test(this.type))this.checked=c.inArray(n.val(),r)>=0;else if(c.nodeName(this,"select")){var u=c.makeArray(r);c("option",this).each(function(){this.selected=
+c.inArray(c(this).val(),u)>=0});if(!u.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,f){if(!a||a.nodeType===3||a.nodeType===8)return w;if(f&&b in c.attrFn)return c(a)[b](d);f=a.nodeType!==1||!c.isXMLDoc(a);var e=d!==w;b=f&&c.props[b]||b;if(a.nodeType===1){var j=$a.test(b);if(b in a&&f&&!j){if(e){b==="type"&&ab.test(a.nodeName)&&a.parentNode&&c.error("type property can't be changed");
+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:bb.test(a.nodeName)||cb.test(a.nodeName)&&a.href?0:w;return a[b]}if(!c.support.style&&f&&b==="style"){if(e)a.style.cssText=""+d;return a.style.cssText}e&&a.setAttribute(b,""+d);a=!c.support.hrefNormalized&&f&&j?a.getAttribute(b,2):a.getAttribute(b);return a===null?w:a}return c.style(a,b,d)}});var O=/\.(.*)$/,db=function(a){return a.replace(/[^\w\s\.\|`]/g,
+function(b){return"\\"+b})};c.event={add:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){if(a.setInterval&&a!==A&&!a.frameElement)a=A;var e,j;if(d.handler){e=d;d=e.handler}if(!d.guid)d.guid=c.guid++;if(j=c.data(a)){var i=j.events=j.events||{},o=j.handle;if(!o)j.handle=o=function(){return typeof c!=="undefined"&&!c.event.triggered?c.event.handle.apply(o.elem,arguments):w};o.elem=a;b=b.split(" ");for(var k,n=0,r;k=b[n++];){j=e?c.extend({},e):{handler:d,data:f};if(k.indexOf(".")>-1){r=k.split(".");
+k=r.shift();j.namespace=r.slice(0).sort().join(".")}else{r=[];j.namespace=""}j.type=k;j.guid=d.guid;var u=i[k],z=c.event.special[k]||{};if(!u){u=i[k]=[];if(!z.setup||z.setup.call(a,f,r,o)===false)if(a.addEventListener)a.addEventListener(k,o,false);else a.attachEvent&&a.attachEvent("on"+k,o)}if(z.add){z.add.call(a,j);if(!j.handler.guid)j.handler.guid=d.guid}u.push(j);c.event.global[k]=true}a=null}}},global:{},remove:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){var e,j=0,i,o,k,n,r,u,z=c.data(a),
+C=z&&z.events;if(z&&C){if(b&&b.type){d=b.handler;b=b.type}if(!b||typeof b==="string"&&b.charAt(0)==="."){b=b||"";for(e in C)c.event.remove(a,e+b)}else{for(b=b.split(" ");e=b[j++];){n=e;i=e.indexOf(".")<0;o=[];if(!i){o=e.split(".");e=o.shift();k=new RegExp("(^|\\.)"+c.map(o.slice(0).sort(),db).join("\\.(?:.*\\.)?")+"(\\.|$)")}if(r=C[e])if(d){n=c.event.special[e]||{};for(B=f||0;B<r.length;B++){u=r[B];if(d.guid===u.guid){if(i||k.test(u.namespace)){f==null&&r.splice(B--,1);n.remove&&n.remove.call(a,u)}if(f!=
+null)break}}if(r.length===0||f!=null&&r.length===1){if(!n.teardown||n.teardown.call(a,o)===false)Ca(a,e,z.handle);delete C[e]}}else for(var B=0;B<r.length;B++){u=r[B];if(i||k.test(u.namespace)){c.event.remove(a,n,u.handler,B);r.splice(B--,1)}}}if(c.isEmptyObject(C)){if(b=z.handle)b.elem=null;delete z.events;delete z.handle;c.isEmptyObject(z)&&c.removeData(a)}}}}},trigger:function(a,b,d,f){var e=a.type||a;if(!f){a=typeof a==="object"?a[G]?a:c.extend(c.Event(e),a):c.Event(e);if(e.indexOf("!")>=0){a.type=
+e=e.slice(0,-1);a.exclusive=true}if(!d){a.stopPropagation();c.event.global[e]&&c.each(c.cache,function(){this.events&&this.events[e]&&c.event.trigger(a,b,this.handle.elem)})}if(!d||d.nodeType===3||d.nodeType===8)return w;a.result=w;a.target=d;b=c.makeArray(b);b.unshift(a)}a.currentTarget=d;(f=c.data(d,"handle"))&&f.apply(d,b);f=d.parentNode||d.ownerDocument;try{if(!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()]))if(d["on"+e]&&d["on"+e].apply(d,b)===false)a.result=false}catch(j){}if(!a.isPropagationStopped()&&
+f)c.event.trigger(a,b,f,true);else if(!a.isDefaultPrevented()){f=a.target;var i,o=c.nodeName(f,"a")&&e==="click",k=c.event.special[e]||{};if((!k._default||k._default.call(d,a)===false)&&!o&&!(f&&f.nodeName&&c.noData[f.nodeName.toLowerCase()])){try{if(f[e]){if(i=f["on"+e])f["on"+e]=null;c.event.triggered=true;f[e]()}}catch(n){}if(i)f["on"+e]=i;c.event.triggered=false}}},handle:function(a){var b,d,f,e;a=arguments[0]=c.event.fix(a||A.event);a.currentTarget=this;b=a.type.indexOf(".")<0&&!a.exclusive;
+if(!b){d=a.type.split(".");a.type=d.shift();f=new RegExp("(^|\\.)"+d.slice(0).sort().join("\\.(?:.*\\.)?")+"(\\.|$)")}e=c.data(this,"events");d=e[a.type];if(e&&d){d=d.slice(0);e=0;for(var j=d.length;e<j;e++){var i=d[e];if(b||f.test(i.namespace)){a.handler=i.handler;a.data=i.data;a.handleObj=i;i=i.handler.apply(this,arguments);if(i!==w){a.result=i;if(i===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 originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
+fix:function(a){if(a[G])return a;var b=a;a=c.Event(b);for(var d=this.props.length,f;d;){f=this.props[--d];a[f]=b[f]}if(!a.target)a.target=a.srcElement||s;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=s.documentElement;d=s.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&&(a.charCode||a.charCode===0?a.charCode:a.keyCode))a.which=a.charCode||a.keyCode;if(!a.metaKey&&a.ctrlKey)a.metaKey=a.ctrlKey;if(!a.which&&a.button!==w)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,a.origType,c.extend({},a,{handler:oa}))},remove:function(a){var b=true,d=a.origType.replace(O,"");c.each(c.data(this,
+"events").live||[],function(){if(d===this.origType.replace(O,""))return b=false});b&&c.event.remove(this,a.origType,oa)}},beforeunload:{setup:function(a,b,d){if(this.setInterval)this.onbeforeunload=d;return false},teardown:function(a,b){if(this.onbeforeunload===b)this.onbeforeunload=null}}}};var Ca=s.removeEventListener?function(a,b,d){a.removeEventListener(b,d,false)}:function(a,b,d){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=J();this[G]=true};c.Event.prototype={preventDefault:function(){this.isDefaultPrevented=Z;var a=this.originalEvent;if(a){a.preventDefault&&a.preventDefault();a.returnValue=false}},stopPropagation:function(){this.isPropagationStopped=Z;var a=this.originalEvent;if(a){a.stopPropagation&&a.stopPropagation();a.cancelBubble=true}},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=Z;this.stopPropagation()},isDefaultPrevented:Y,isPropagationStopped:Y,
+isImmediatePropagationStopped:Y};var Da=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){}},Ea=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?Ea:Da,a)},teardown:function(d){c.event.remove(this,b,d&&d.selector?Ea:Da)}}});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)return na("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)return na("submit",this,arguments)})}else return false},teardown:function(){c.event.remove(this,".specialSubmit")}};
+if(!c.support.changeBubbles){var da=/textarea|input|select/i,ea,Fa=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(f){return f.selected}).join("-"):"";else if(a.nodeName.toLowerCase()==="select")d=a.selectedIndex;return d},fa=function(a,b){var d=a.target,f,e;if(!(!da.test(d.nodeName)||d.readOnly)){f=c.data(d,"_change_data");e=Fa(d);if(a.type!=="focusout"||d.type!=="radio")c.data(d,"_change_data",
+e);if(!(f===w||e===f))if(f!=null||e){a.type="change";return c.event.trigger(a,b,d)}}};c.event.special.change={filters:{focusout:fa,click:function(a){var b=a.target,d=b.type;if(d==="radio"||d==="checkbox"||b.nodeName.toLowerCase()==="select")return fa.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 fa.call(this,a)},beforeactivate:function(a){a=a.target;c.data(a,
+"_change_data",Fa(a))}},setup:function(){if(this.type==="file")return false;for(var a in ea)c.event.add(this,a+".specialChange",ea[a]);return da.test(this.nodeName)},teardown:function(){c.event.remove(this,".specialChange");return da.test(this.nodeName)}};ea=c.event.special.change.filters}s.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(f){f=c.event.fix(f);f.type=b;return c.event.handle.call(this,f)}c.event.special[b]={setup:function(){this.addEventListener(a,
+d,true)},teardown:function(){this.removeEventListener(a,d,true)}}});c.each(["bind","one"],function(a,b){c.fn[b]=function(d,f,e){if(typeof d==="object"){for(var j in d)this[b](j,f,d[j],e);return this}if(c.isFunction(f)){e=f;f=w}var i=b==="one"?c.proxy(e,function(k){c(this).unbind(k,i);return e.apply(this,arguments)}):e;if(d==="unload"&&b!=="one")this.one(d,f,e);else{j=0;for(var o=this.length;j<o;j++)c.event.add(this[j],d,i,f)}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 f=this.length;d<f;d++)c.event.remove(this[d],a,b)}return this},delegate:function(a,b,d,f){return this.live(b,d,f,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]){a=c.Event(a);a.preventDefault();a.stopPropagation();c.event.trigger(a,b,this[0]);return a.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(f){var e=(c.data(this,"lastToggle"+a.guid)||0)%d;c.data(this,"lastToggle"+a.guid,e+1);f.preventDefault();return b[e].apply(this,arguments)||false}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var Ga={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};c.each(["live","die"],function(a,b){c.fn[b]=function(d,f,e,j){var i,o=0,k,n,r=j||this.selector,
+u=j?this:c(this.context);if(c.isFunction(f)){e=f;f=w}for(d=(d||"").split(" ");(i=d[o++])!=null;){j=O.exec(i);k="";if(j){k=j[0];i=i.replace(O,"")}if(i==="hover")d.push("mouseenter"+k,"mouseleave"+k);else{n=i;if(i==="focus"||i==="blur"){d.push(Ga[i]+k);i+=k}else i=(Ga[i]||i)+k;b==="live"?u.each(function(){c.event.add(this,pa(i,r),{data:f,selector:r,handler:e,origType:i,origHandler:e,preType:n})}):u.unbind(pa(i,r),e)}}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){return d?this.bind(b,d):this.trigger(b)};if(c.attrFn)c.attrFn[b]=true});A.attachEvent&&!A.addEventListener&&A.attachEvent("onunload",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){for(var h="",l,m=0;g[m];m++){l=g[m];if(l.nodeType===3||l.nodeType===4)h+=l.nodeValue;else if(l.nodeType!==8)h+=a(l.childNodes)}return h}function b(g,h,l,m,q,p){q=0;for(var v=m.length;q<v;q++){var t=m[q];
+if(t){t=t[g];for(var y=false;t;){if(t.sizcache===l){y=m[t.sizset];break}if(t.nodeType===1&&!p){t.sizcache=l;t.sizset=q}if(t.nodeName.toLowerCase()===h){y=t;break}t=t[g]}m[q]=y}}}function d(g,h,l,m,q,p){q=0;for(var v=m.length;q<v;q++){var t=m[q];if(t){t=t[g];for(var y=false;t;){if(t.sizcache===l){y=m[t.sizset];break}if(t.nodeType===1){if(!p){t.sizcache=l;t.sizset=q}if(typeof h!=="string"){if(t===h){y=true;break}}else if(k.filter(h,[t]).length>0){y=t;break}}t=t[g]}m[q]=y}}}var f=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
+e=0,j=Object.prototype.toString,i=false,o=true;[0,0].sort(function(){o=false;return 0});var k=function(g,h,l,m){l=l||[];var q=h=h||s;if(h.nodeType!==1&&h.nodeType!==9)return[];if(!g||typeof g!=="string")return l;for(var p=[],v,t,y,S,H=true,M=x(h),I=g;(f.exec(""),v=f.exec(I))!==null;){I=v[3];p.push(v[1]);if(v[2]){S=v[3];break}}if(p.length>1&&r.exec(g))if(p.length===2&&n.relative[p[0]])t=ga(p[0]+p[1],h);else for(t=n.relative[p[0]]?[h]:k(p.shift(),h);p.length;){g=p.shift();if(n.relative[g])g+=p.shift();
+t=ga(g,t)}else{if(!m&&p.length>1&&h.nodeType===9&&!M&&n.match.ID.test(p[0])&&!n.match.ID.test(p[p.length-1])){v=k.find(p.shift(),h,M);h=v.expr?k.filter(v.expr,v.set)[0]:v.set[0]}if(h){v=m?{expr:p.pop(),set:z(m)}:k.find(p.pop(),p.length===1&&(p[0]==="~"||p[0]==="+")&&h.parentNode?h.parentNode:h,M);t=v.expr?k.filter(v.expr,v.set):v.set;if(p.length>0)y=z(t);else H=false;for(;p.length;){var D=p.pop();v=D;if(n.relative[D])v=p.pop();else D="";if(v==null)v=h;n.relative[D](y,v,M)}}else y=[]}y||(y=t);y||k.error(D||
+g);if(j.call(y)==="[object Array]")if(H)if(h&&h.nodeType===1)for(g=0;y[g]!=null;g++){if(y[g]&&(y[g]===true||y[g].nodeType===1&&E(h,y[g])))l.push(t[g])}else for(g=0;y[g]!=null;g++)y[g]&&y[g].nodeType===1&&l.push(t[g]);else l.push.apply(l,y);else z(y,l);if(S){k(S,q,l,m);k.uniqueSort(l)}return l};k.uniqueSort=function(g){if(B){i=o;g.sort(B);if(i)for(var h=1;h<g.length;h++)g[h]===g[h-1]&&g.splice(h--,1)}return g};k.matches=function(g,h){return k(g,null,null,h)};k.find=function(g,h,l){var m,q;if(!g)return[];
+for(var p=0,v=n.order.length;p<v;p++){var t=n.order[p];if(q=n.leftMatch[t].exec(g)){var y=q[1];q.splice(1,1);if(y.substr(y.length-1)!=="\\"){q[1]=(q[1]||"").replace(/\\/g,"");m=n.find[t](q,h,l);if(m!=null){g=g.replace(n.match[t],"");break}}}}m||(m=h.getElementsByTagName("*"));return{set:m,expr:g}};k.filter=function(g,h,l,m){for(var q=g,p=[],v=h,t,y,S=h&&h[0]&&x(h[0]);g&&h.length;){for(var H in n.filter)if((t=n.leftMatch[H].exec(g))!=null&&t[2]){var M=n.filter[H],I,D;D=t[1];y=false;t.splice(1,1);if(D.substr(D.length-
+1)!=="\\"){if(v===p)p=[];if(n.preFilter[H])if(t=n.preFilter[H](t,v,l,p,m,S)){if(t===true)continue}else y=I=true;if(t)for(var U=0;(D=v[U])!=null;U++)if(D){I=M(D,t,U,v);var Ha=m^!!I;if(l&&I!=null)if(Ha)y=true;else v[U]=false;else if(Ha){p.push(D);y=true}}if(I!==w){l||(v=p);g=g.replace(n.match[H],"");if(!y)return[];break}}}if(g===q)if(y==null)k.error(g);else break;q=g}return v};k.error=function(g){throw"Syntax error, unrecognized expression: "+g;};var n=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,h){var l=typeof h==="string",m=l&&!/\W/.test(h);l=l&&!m;if(m)h=h.toLowerCase();m=0;for(var q=g.length,p;m<q;m++)if(p=g[m]){for(;(p=p.previousSibling)&&p.nodeType!==1;);g[m]=l||p&&p.nodeName.toLowerCase()===h?p||false:p===h}l&&k.filter(h,g,true)},">":function(g,h){var l=typeof h==="string";if(l&&!/\W/.test(h)){h=h.toLowerCase();for(var m=0,q=g.length;m<q;m++){var p=g[m];if(p){l=p.parentNode;g[m]=l.nodeName.toLowerCase()===h?l:false}}}else{m=0;for(q=g.length;m<q;m++)if(p=g[m])g[m]=
+l?p.parentNode:p.parentNode===h;l&&k.filter(h,g,true)}},"":function(g,h,l){var m=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("parentNode",h,m,g,p,l)},"~":function(g,h,l){var m=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("previousSibling",h,m,g,p,l)}},find:{ID:function(g,h,l){if(typeof h.getElementById!=="undefined"&&!l)return(g=h.getElementById(g[1]))?[g]:[]},NAME:function(g,h){if(typeof h.getElementsByName!=="undefined"){var l=[];
+h=h.getElementsByName(g[1]);for(var m=0,q=h.length;m<q;m++)h[m].getAttribute("name")===g[1]&&l.push(h[m]);return l.length===0?null:l}},TAG:function(g,h){return h.getElementsByTagName(g[1])}},preFilter:{CLASS:function(g,h,l,m,q,p){g=" "+g[1].replace(/\\/g,"")+" ";if(p)return g;p=0;for(var v;(v=h[p])!=null;p++)if(v)if(q^(v.className&&(" "+v.className+" ").replace(/[\t\n]/g," ").indexOf(g)>=0))l||m.push(v);else if(l)h[p]=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 h=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(g[2]==="even"&&"2n"||g[2]==="odd"&&"2n+1"||!/\D/.test(g[2])&&"0n+"+g[2]||g[2]);g[2]=h[1]+(h[2]||1)-0;g[3]=h[3]-0}g[0]=e++;return g},ATTR:function(g,h,l,m,q,p){h=g[1].replace(/\\/g,"");if(!p&&n.attrMap[h])g[1]=n.attrMap[h];if(g[2]==="~=")g[4]=" "+g[4]+" ";return g},PSEUDO:function(g,h,l,m,q){if(g[1]==="not")if((f.exec(g[3])||"").length>1||/^\w/.test(g[3]))g[3]=k(g[3],null,null,h);else{g=k.filter(g[3],h,l,true^q);l||m.push.apply(m,
+g);return false}else if(n.match.POS.test(g[0])||n.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,h,l){return!!k(l[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,h){return h===0},last:function(g,h,l,m){return h===m.length-1},even:function(g,h){return h%2===0},odd:function(g,h){return h%2===1},lt:function(g,h,l){return h<l[3]-0},gt:function(g,h,l){return h>l[3]-0},nth:function(g,h,l){return l[3]-0===h},eq:function(g,h,l){return l[3]-0===h}},filter:{PSEUDO:function(g,h,l,m){var q=h[1],p=n.filters[q];if(p)return p(g,l,h,m);else if(q==="contains")return(g.textContent||g.innerText||a([g])||"").indexOf(h[3])>=0;else if(q==="not"){h=
+h[3];l=0;for(m=h.length;l<m;l++)if(h[l]===g)return false;return true}else k.error("Syntax error, unrecognized expression: "+q)},CHILD:function(g,h){var l=h[1],m=g;switch(l){case "only":case "first":for(;m=m.previousSibling;)if(m.nodeType===1)return false;if(l==="first")return true;m=g;case "last":for(;m=m.nextSibling;)if(m.nodeType===1)return false;return true;case "nth":l=h[2];var q=h[3];if(l===1&&q===0)return true;h=h[0];var p=g.parentNode;if(p&&(p.sizcache!==h||!g.nodeIndex)){var v=0;for(m=p.firstChild;m;m=
+m.nextSibling)if(m.nodeType===1)m.nodeIndex=++v;p.sizcache=h}g=g.nodeIndex-q;return l===0?g===0:g%l===0&&g/l>=0}},ID:function(g,h){return g.nodeType===1&&g.getAttribute("id")===h},TAG:function(g,h){return h==="*"&&g.nodeType===1||g.nodeName.toLowerCase()===h},CLASS:function(g,h){return(" "+(g.className||g.getAttribute("class"))+" ").indexOf(h)>-1},ATTR:function(g,h){var l=h[1];g=n.attrHandle[l]?n.attrHandle[l](g):g[l]!=null?g[l]:g.getAttribute(l);l=g+"";var m=h[2];h=h[4];return g==null?m==="!=":m===
+"="?l===h:m==="*="?l.indexOf(h)>=0:m==="~="?(" "+l+" ").indexOf(h)>=0:!h?l&&g!==false:m==="!="?l!==h:m==="^="?l.indexOf(h)===0:m==="$="?l.substr(l.length-h.length)===h:m==="|="?l===h||l.substr(0,h.length+1)===h+"-":false},POS:function(g,h,l,m){var q=n.setFilters[h[2]];if(q)return q(g,l,h,m)}}},r=n.match.POS;for(var u in n.match){n.match[u]=new RegExp(n.match[u].source+/(?![^\[]*\])(?![^\(]*\))/.source);n.leftMatch[u]=new RegExp(/(^(?:.|\r|\n)*?)/.source+n.match[u].source.replace(/\\(\d+)/g,function(g,
+h){return"\\"+(h-0+1)}))}var z=function(g,h){g=Array.prototype.slice.call(g,0);if(h){h.push.apply(h,g);return h}return g};try{Array.prototype.slice.call(s.documentElement.childNodes,0)}catch(C){z=function(g,h){h=h||[];if(j.call(g)==="[object Array]")Array.prototype.push.apply(h,g);else if(typeof g.length==="number")for(var l=0,m=g.length;l<m;l++)h.push(g[l]);else for(l=0;g[l];l++)h.push(g[l]);return h}}var B;if(s.documentElement.compareDocumentPosition)B=function(g,h){if(!g.compareDocumentPosition||
+!h.compareDocumentPosition){if(g==h)i=true;return g.compareDocumentPosition?-1:1}g=g.compareDocumentPosition(h)&4?-1:g===h?0:1;if(g===0)i=true;return g};else if("sourceIndex"in s.documentElement)B=function(g,h){if(!g.sourceIndex||!h.sourceIndex){if(g==h)i=true;return g.sourceIndex?-1:1}g=g.sourceIndex-h.sourceIndex;if(g===0)i=true;return g};else if(s.createRange)B=function(g,h){if(!g.ownerDocument||!h.ownerDocument){if(g==h)i=true;return g.ownerDocument?-1:1}var l=g.ownerDocument.createRange(),m=
+h.ownerDocument.createRange();l.setStart(g,0);l.setEnd(g,0);m.setStart(h,0);m.setEnd(h,0);g=l.compareBoundaryPoints(Range.START_TO_END,m);if(g===0)i=true;return g};(function(){var g=s.createElement("div"),h="script"+(new Date).getTime();g.innerHTML="<a name='"+h+"'/>";var l=s.documentElement;l.insertBefore(g,l.firstChild);if(s.getElementById(h)){n.find.ID=function(m,q,p){if(typeof q.getElementById!=="undefined"&&!p)return(q=q.getElementById(m[1]))?q.id===m[1]||typeof q.getAttributeNode!=="undefined"&&
+q.getAttributeNode("id").nodeValue===m[1]?[q]:w:[]};n.filter.ID=function(m,q){var p=typeof m.getAttributeNode!=="undefined"&&m.getAttributeNode("id");return m.nodeType===1&&p&&p.nodeValue===q}}l.removeChild(g);l=g=null})();(function(){var g=s.createElement("div");g.appendChild(s.createComment(""));if(g.getElementsByTagName("*").length>0)n.find.TAG=function(h,l){l=l.getElementsByTagName(h[1]);if(h[1]==="*"){h=[];for(var m=0;l[m];m++)l[m].nodeType===1&&h.push(l[m]);l=h}return l};g.innerHTML="<a href='#'></a>";
+if(g.firstChild&&typeof g.firstChild.getAttribute!=="undefined"&&g.firstChild.getAttribute("href")!=="#")n.attrHandle.href=function(h){return h.getAttribute("href",2)};g=null})();s.querySelectorAll&&function(){var g=k,h=s.createElement("div");h.innerHTML="<p class='TEST'></p>";if(!(h.querySelectorAll&&h.querySelectorAll(".TEST").length===0)){k=function(m,q,p,v){q=q||s;if(!v&&q.nodeType===9&&!x(q))try{return z(q.querySelectorAll(m),p)}catch(t){}return g(m,q,p,v)};for(var l in g)k[l]=g[l];h=null}}();
+(function(){var g=s.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){n.order.splice(1,0,"CLASS");n.find.CLASS=function(h,l,m){if(typeof l.getElementsByClassName!=="undefined"&&!m)return l.getElementsByClassName(h[1])};g=null}}})();var E=s.compareDocumentPosition?function(g,h){return!!(g.compareDocumentPosition(h)&16)}:
+function(g,h){return g!==h&&(g.contains?g.contains(h):true)},x=function(g){return(g=(g?g.ownerDocument||g:0).documentElement)?g.nodeName!=="HTML":false},ga=function(g,h){var l=[],m="",q;for(h=h.nodeType?[h]:h;q=n.match.PSEUDO.exec(g);){m+=q[0];g=g.replace(n.match.PSEUDO,"")}g=n.relative[g]?g+"*":g;q=0;for(var p=h.length;q<p;q++)k(g,h[q],l);return k.filter(m,l)};c.find=k;c.expr=k.selectors;c.expr[":"]=c.expr.filters;c.unique=k.uniqueSort;c.text=a;c.isXMLDoc=x;c.contains=E})();var eb=/Until$/,fb=/^(?:parents|prevUntil|prevAll)/,
+gb=/,/;R=Array.prototype.slice;var Ia=function(a,b,d){if(c.isFunction(b))return c.grep(a,function(e,j){return!!b.call(e,j,e)===d});else if(b.nodeType)return c.grep(a,function(e){return e===b===d});else if(typeof b==="string"){var f=c.grep(a,function(e){return e.nodeType===1});if(Ua.test(b))return c.filter(b,f,!d);else b=c.filter(b,f)}return c.grep(a,function(e){return c.inArray(e,b)>=0===d})};c.fn.extend({find:function(a){for(var b=this.pushStack("","find",a),d=0,f=0,e=this.length;f<e;f++){d=b.length;
+c.find(a,this[f],b);if(f>0)for(var j=d;j<b.length;j++)for(var i=0;i<d;i++)if(b[i]===b[j]){b.splice(j--,1);break}}return b},has:function(a){var b=c(a);return this.filter(function(){for(var d=0,f=b.length;d<f;d++)if(c.contains(this,b[d]))return true})},not:function(a){return this.pushStack(Ia(this,a,false),"not",a)},filter:function(a){return this.pushStack(Ia(this,a,true),"filter",a)},is:function(a){return!!a&&c.filter(a,this).length>0},closest:function(a,b){if(c.isArray(a)){var d=[],f=this[0],e,j=
+{},i;if(f&&a.length){e=0;for(var o=a.length;e<o;e++){i=a[e];j[i]||(j[i]=c.expr.match.POS.test(i)?c(i,b||this.context):i)}for(;f&&f.ownerDocument&&f!==b;){for(i in j){e=j[i];if(e.jquery?e.index(f)>-1:c(f).is(e)){d.push({selector:i,elem:f});delete j[i]}}f=f.parentNode}}return d}var k=c.expr.match.POS.test(a)?c(a,b||this.context):null;return this.map(function(n,r){for(;r&&r.ownerDocument&&r!==b;){if(k?k.index(r)>-1:c(r).is(a))return r;r=r.parentNode}return null})},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){a=typeof a==="string"?c(a,b||this.context):c.makeArray(a);b=c.merge(this.get(),a);return this.pushStack(qa(a[0])||qa(b[0])?b:c.unique(b))},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,f){var e=c.map(this,b,d);eb.test(a)||(f=d);if(f&&typeof f==="string")e=c.filter(f,e);e=this.length>1?c.unique(e):e;if((this.length>1||gb.test(f))&&fb.test(a))e=e.reverse();return this.pushStack(e,a,R.call(arguments).join(","))}});c.extend({filter:function(a,b,d){if(d)a=":not("+a+")";return c.find.matches(a,b)},dir:function(a,b,d){var f=[];for(a=a[b];a&&a.nodeType!==9&&(d===w||a.nodeType!==1||!c(a).is(d));){a.nodeType===
+1&&f.push(a);a=a[b]}return f},nth:function(a,b,d){b=b||1;for(var f=0;a;a=a[d])if(a.nodeType===1&&++f===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 Ja=/ jQuery\d+="(?:\d+|null)"/g,V=/^\s+/,Ka=/(<([\w:]+)[^>]*?)\/>/g,hb=/^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i,La=/<([\w:]+)/,ib=/<tbody/i,jb=/<|&#?\w+;/,ta=/<script|<object|<embed|<option|<style/i,ua=/checked\s*(?:[^=]|=\s*.checked.)/i,Ma=function(a,b,d){return hb.test(d)?
+a:b+"></"+d+">"},F={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,"",""]};F.optgroup=F.option;F.tbody=F.tfoot=F.colgroup=F.caption=F.thead;F.th=F.td;if(!c.support.htmlSerialize)F._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!==w)return this.empty().append((this[0]&&this[0].ownerDocument||s).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,f;(f=this[d])!=null;d++)if(!a||c.filter(a,[f]).length){if(!b&&f.nodeType===1){c.cleanData(f.getElementsByTagName("*"));c.cleanData([f])}f.parentNode&&f.parentNode.removeChild(f)}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,f=this.ownerDocument;if(!d){d=f.createElement("div");d.appendChild(this.cloneNode(true));d=d.innerHTML}return c.clean([d.replace(Ja,"").replace(/=([^="'>\s]+\/)>/g,'="$1">').replace(V,"")],f)[0]}else return this.cloneNode(true)});if(a===true){ra(this,b);ra(this.find("*"),b.find("*"))}return b},html:function(a){if(a===w)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(Ja,
+""):null;else if(typeof a==="string"&&!ta.test(a)&&(c.support.leadingWhitespace||!V.test(a))&&!F[(La.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Ka,Ma);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(f){this.empty().append(a)}}else c.isFunction(a)?this.each(function(e){var j=c(this),i=j.html();j.empty().append(function(){return a.call(this,e,i)})}):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),f=d.html();d.replaceWith(a.call(this,b,f))});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){function f(u){return c.nodeName(u,"table")?u.getElementsByTagName("tbody")[0]||
+u.appendChild(u.ownerDocument.createElement("tbody")):u}var e,j,i=a[0],o=[],k;if(!c.support.checkClone&&arguments.length===3&&typeof i==="string"&&ua.test(i))return this.each(function(){c(this).domManip(a,b,d,true)});if(c.isFunction(i))return this.each(function(u){var z=c(this);a[0]=i.call(this,u,b?z.html():w);z.domManip(a,b,d)});if(this[0]){e=i&&i.parentNode;e=c.support.parentNode&&e&&e.nodeType===11&&e.childNodes.length===this.length?{fragment:e}:sa(a,this,o);k=e.fragment;if(j=k.childNodes.length===
+1?(k=k.firstChild):k.firstChild){b=b&&c.nodeName(j,"tr");for(var n=0,r=this.length;n<r;n++)d.call(b?f(this[n],j):this[n],n>0||e.cacheable||this.length>1?k.cloneNode(true):k)}o.length&&c.each(o,Qa)}return this}});c.fragments={};c.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){c.fn[a]=function(d){var f=[];d=c(d);var e=this.length===1&&this[0].parentNode;if(e&&e.nodeType===11&&e.childNodes.length===1&&d.length===1){d[b](this[0]);
+return this}else{e=0;for(var j=d.length;e<j;e++){var i=(e>0?this.clone(true):this).get();c.fn[b].apply(c(d[e]),i);f=f.concat(i)}return this.pushStack(f,a,d.selector)}}});c.extend({clean:function(a,b,d,f){b=b||s;if(typeof b.createElement==="undefined")b=b.ownerDocument||b[0]&&b[0].ownerDocument||s;for(var e=[],j=0,i;(i=a[j])!=null;j++){if(typeof i==="number")i+="";if(i){if(typeof i==="string"&&!jb.test(i))i=b.createTextNode(i);else if(typeof i==="string"){i=i.replace(Ka,Ma);var o=(La.exec(i)||["",
+""])[1].toLowerCase(),k=F[o]||F._default,n=k[0],r=b.createElement("div");for(r.innerHTML=k[1]+i+k[2];n--;)r=r.lastChild;if(!c.support.tbody){n=ib.test(i);o=o==="table"&&!n?r.firstChild&&r.firstChild.childNodes:k[1]==="<table>"&&!n?r.childNodes:[];for(k=o.length-1;k>=0;--k)c.nodeName(o[k],"tbody")&&!o[k].childNodes.length&&o[k].parentNode.removeChild(o[k])}!c.support.leadingWhitespace&&V.test(i)&&r.insertBefore(b.createTextNode(V.exec(i)[0]),r.firstChild);i=r.childNodes}if(i.nodeType)e.push(i);else e=
+c.merge(e,i)}}if(d)for(j=0;e[j];j++)if(f&&c.nodeName(e[j],"script")&&(!e[j].type||e[j].type.toLowerCase()==="text/javascript"))f.push(e[j].parentNode?e[j].parentNode.removeChild(e[j]):e[j]);else{e[j].nodeType===1&&e.splice.apply(e,[j+1,0].concat(c.makeArray(e[j].getElementsByTagName("script"))));d.appendChild(e[j])}return e},cleanData:function(a){for(var b,d,f=c.cache,e=c.event.special,j=c.support.deleteExpando,i=0,o;(o=a[i])!=null;i++)if(d=o[c.expando]){b=f[d];if(b.events)for(var k in b.events)e[k]?
+c.event.remove(o,k):Ca(o,k,b.handle);if(j)delete o[c.expando];else o.removeAttribute&&o.removeAttribute(c.expando);delete f[d]}}});var kb=/z-?index|font-?weight|opacity|zoom|line-?height/i,Na=/alpha\([^)]*\)/,Oa=/opacity=([^)]*)/,ha=/float/i,ia=/-([a-z])/ig,lb=/([A-Z])/g,mb=/^-?\d+(?:px)?$/i,nb=/^-?\d/,ob={position:"absolute",visibility:"hidden",display:"block"},pb=["Left","Right"],qb=["Top","Bottom"],rb=s.defaultView&&s.defaultView.getComputedStyle,Pa=c.support.cssFloat?"cssFloat":"styleFloat",ja=
+function(a,b){return b.toUpperCase()};c.fn.css=function(a,b){return X(this,a,b,true,function(d,f,e){if(e===w)return c.curCSS(d,f);if(typeof e==="number"&&!kb.test(f))e+="px";c.style(d,f,e)})};c.extend({style:function(a,b,d){if(!a||a.nodeType===3||a.nodeType===8)return w;if((b==="width"||b==="height")&&parseFloat(d)<0)d=w;var f=a.style||a,e=d!==w;if(!c.support.opacity&&b==="opacity"){if(e){f.zoom=1;b=parseInt(d,10)+""==="NaN"?"":"alpha(opacity="+d*100+")";a=f.filter||c.curCSS(a,"filter")||"";f.filter=
+Na.test(a)?a.replace(Na,b):b}return f.filter&&f.filter.indexOf("opacity=")>=0?parseFloat(Oa.exec(f.filter)[1])/100+"":""}if(ha.test(b))b=Pa;b=b.replace(ia,ja);if(e)f[b]=d;return f[b]},css:function(a,b,d,f){if(b==="width"||b==="height"){var e,j=b==="width"?pb:qb;function i(){e=b==="width"?a.offsetWidth:a.offsetHeight;f!=="border"&&c.each(j,function(){f||(e-=parseFloat(c.curCSS(a,"padding"+this,true))||0);if(f==="margin")e+=parseFloat(c.curCSS(a,"margin"+this,true))||0;else e-=parseFloat(c.curCSS(a,
+"border"+this+"Width",true))||0})}a.offsetWidth!==0?i():c.swap(a,ob,i);return Math.max(0,Math.round(e))}return c.curCSS(a,b,d)},curCSS:function(a,b,d){var f,e=a.style;if(!c.support.opacity&&b==="opacity"&&a.currentStyle){f=Oa.test(a.currentStyle.filter||"")?parseFloat(RegExp.$1)/100+"":"";return f===""?"1":f}if(ha.test(b))b=Pa;if(!d&&e&&e[b])f=e[b];else if(rb){if(ha.test(b))b="float";b=b.replace(lb,"-$1").toLowerCase();e=a.ownerDocument.defaultView;if(!e)return null;if(a=e.getComputedStyle(a,null))f=
+a.getPropertyValue(b);if(b==="opacity"&&f==="")f="1"}else if(a.currentStyle){d=b.replace(ia,ja);f=a.currentStyle[b]||a.currentStyle[d];if(!mb.test(f)&&nb.test(f)){b=e.left;var j=a.runtimeStyle.left;a.runtimeStyle.left=a.currentStyle.left;e.left=d==="fontSize"?"1em":f||0;f=e.pixelLeft+"px";e.left=b;a.runtimeStyle.left=j}}return f},swap:function(a,b,d){var f={};for(var e in b){f[e]=a.style[e];a.style[e]=b[e]}d.call(a);for(e in b)a.style[e]=f[e]}});if(c.expr&&c.expr.filters){c.expr.filters.hidden=function(a){var b=
+a.offsetWidth,d=a.offsetHeight,f=a.nodeName.toLowerCase()==="tr";return b===0&&d===0&&!f?true:b>0&&d>0&&!f?false:c.curCSS(a,"display")==="none"};c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)}}var sb=J(),tb=/<script(.|\s)*?\/script>/gi,ub=/select|textarea/i,vb=/color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i,N=/=\?(&|$)/,ka=/\?/,wb=/(\?|&)_=.*?(&|$)/,xb=/^(\w+:)?\/\/([^\/?#]+)/,yb=/%20/g,zb=c.fn.load;c.fn.extend({load:function(a,b,d){if(typeof a!==
+"string")return zb.call(this,a);else if(!this.length)return this;var f=a.indexOf(" ");if(f>=0){var e=a.slice(f,a.length);a=a.slice(0,f)}f="GET";if(b)if(c.isFunction(b)){d=b;b=null}else if(typeof b==="object"){b=c.param(b,c.ajaxSettings.traditional);f="POST"}var j=this;c.ajax({url:a,type:f,dataType:"html",data:b,complete:function(i,o){if(o==="success"||o==="notmodified")j.html(e?c("<div />").append(i.responseText.replace(tb,"")).find(e):i.responseText);d&&j.each(d,[i.responseText,o,i])}});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||ub.test(this.nodeName)||vb.test(this.type))}).map(function(a,b){a=c(this).val();return a==null?null:c.isArray(a)?c.map(a,function(d){return{name:b.name,value:d}}):{name:b.name,value:a}}).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,f){if(c.isFunction(b)){f=f||d;d=b;b=null}return c.ajax({type:"GET",url:a,data:b,success:d,dataType:f})},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,f){if(c.isFunction(b)){f=f||d;d=b;b={}}return c.ajax({type:"POST",url:a,data:b,success:d,dataType:f})},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:A.XMLHttpRequest&&(A.location.protocol!=="file:"||!A.ActiveXObject)?function(){return new A.XMLHttpRequest}:function(){try{return new A.ActiveXObject("Microsoft.XMLHTTP")}catch(a){}},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},etag:{},ajax:function(a){function b(){e.success&&
+e.success.call(k,o,i,x);e.global&&f("ajaxSuccess",[x,e])}function d(){e.complete&&e.complete.call(k,x,i);e.global&&f("ajaxComplete",[x,e]);e.global&&!--c.active&&c.event.trigger("ajaxStop")}function f(q,p){(e.context?c(e.context):c.event).trigger(q,p)}var e=c.extend(true,{},c.ajaxSettings,a),j,i,o,k=a&&a.context||e,n=e.type.toUpperCase();if(e.data&&e.processData&&typeof e.data!=="string")e.data=c.param(e.data,e.traditional);if(e.dataType==="jsonp"){if(n==="GET")N.test(e.url)||(e.url+=(ka.test(e.url)?
+"&":"?")+(e.jsonp||"callback")+"=?");else if(!e.data||!N.test(e.data))e.data=(e.data?e.data+"&":"")+(e.jsonp||"callback")+"=?";e.dataType="json"}if(e.dataType==="json"&&(e.data&&N.test(e.data)||N.test(e.url))){j=e.jsonpCallback||"jsonp"+sb++;if(e.data)e.data=(e.data+"").replace(N,"="+j+"$1");e.url=e.url.replace(N,"="+j+"$1");e.dataType="script";A[j]=A[j]||function(q){o=q;b();d();A[j]=w;try{delete A[j]}catch(p){}z&&z.removeChild(C)}}if(e.dataType==="script"&&e.cache===null)e.cache=false;if(e.cache===
+false&&n==="GET"){var r=J(),u=e.url.replace(wb,"$1_="+r+"$2");e.url=u+(u===e.url?(ka.test(e.url)?"&":"?")+"_="+r:"")}if(e.data&&n==="GET")e.url+=(ka.test(e.url)?"&":"?")+e.data;e.global&&!c.active++&&c.event.trigger("ajaxStart");r=(r=xb.exec(e.url))&&(r[1]&&r[1]!==location.protocol||r[2]!==location.host);if(e.dataType==="script"&&n==="GET"&&r){var z=s.getElementsByTagName("head")[0]||s.documentElement,C=s.createElement("script");C.src=e.url;if(e.scriptCharset)C.charset=e.scriptCharset;if(!j){var B=
+false;C.onload=C.onreadystatechange=function(){if(!B&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){B=true;b();d();C.onload=C.onreadystatechange=null;z&&C.parentNode&&z.removeChild(C)}}}z.insertBefore(C,z.firstChild);return w}var E=false,x=e.xhr();if(x){e.username?x.open(n,e.url,e.async,e.username,e.password):x.open(n,e.url,e.async);try{if(e.data||a&&a.contentType)x.setRequestHeader("Content-Type",e.contentType);if(e.ifModified){c.lastModified[e.url]&&x.setRequestHeader("If-Modified-Since",
+c.lastModified[e.url]);c.etag[e.url]&&x.setRequestHeader("If-None-Match",c.etag[e.url])}r||x.setRequestHeader("X-Requested-With","XMLHttpRequest");x.setRequestHeader("Accept",e.dataType&&e.accepts[e.dataType]?e.accepts[e.dataType]+", */*":e.accepts._default)}catch(ga){}if(e.beforeSend&&e.beforeSend.call(k,x,e)===false){e.global&&!--c.active&&c.event.trigger("ajaxStop");x.abort();return false}e.global&&f("ajaxSend",[x,e]);var g=x.onreadystatechange=function(q){if(!x||x.readyState===0||q==="abort"){E||
+d();E=true;if(x)x.onreadystatechange=c.noop}else if(!E&&x&&(x.readyState===4||q==="timeout")){E=true;x.onreadystatechange=c.noop;i=q==="timeout"?"timeout":!c.httpSuccess(x)?"error":e.ifModified&&c.httpNotModified(x,e.url)?"notmodified":"success";var p;if(i==="success")try{o=c.httpData(x,e.dataType,e)}catch(v){i="parsererror";p=v}if(i==="success"||i==="notmodified")j||b();else c.handleError(e,x,i,p);d();q==="timeout"&&x.abort();if(e.async)x=null}};try{var h=x.abort;x.abort=function(){x&&h.call(x);
+g("abort")}}catch(l){}e.async&&e.timeout>0&&setTimeout(function(){x&&!E&&g("timeout")},e.timeout);try{x.send(n==="POST"||n==="PUT"||n==="DELETE"?e.data:null)}catch(m){c.handleError(e,x,null,m);d()}e.async||g();return x}},handleError:function(a,b,d,f){if(a.error)a.error.call(a.context||a,b,d,f);if(a.global)(a.context?c(a.context):c.event).trigger("ajaxError",[b,a,f])},active:0,httpSuccess:function(a){try{return!a.status&&location.protocol==="file:"||a.status>=200&&a.status<300||a.status===304||a.status===
+1223||a.status===0}catch(b){}return false},httpNotModified:function(a,b){var d=a.getResponseHeader("Last-Modified"),f=a.getResponseHeader("Etag");if(d)c.lastModified[b]=d;if(f)c.etag[b]=f;return a.status===304||a.status===0},httpData:function(a,b,d){var f=a.getResponseHeader("content-type")||"",e=b==="xml"||!b&&f.indexOf("xml")>=0;a=e?a.responseXML:a.responseText;e&&a.documentElement.nodeName==="parsererror"&&c.error("parsererror");if(d&&d.dataFilter)a=d.dataFilter(a,b);if(typeof a==="string")if(b===
+"json"||!b&&f.indexOf("json")>=0)a=c.parseJSON(a);else if(b==="script"||!b&&f.indexOf("javascript")>=0)c.globalEval(a);return a},param:function(a,b){function d(i,o){if(c.isArray(o))c.each(o,function(k,n){b||/\[\]$/.test(i)?f(i,n):d(i+"["+(typeof n==="object"||c.isArray(n)?k:"")+"]",n)});else!b&&o!=null&&typeof o==="object"?c.each(o,function(k,n){d(i+"["+k+"]",n)}):f(i,o)}function f(i,o){o=c.isFunction(o)?o():o;e[e.length]=encodeURIComponent(i)+"="+encodeURIComponent(o)}var e=[];if(b===w)b=c.ajaxSettings.traditional;
+if(c.isArray(a)||a.jquery)c.each(a,function(){f(this.name,this.value)});else for(var j in a)d(j,a[j]);return e.join("&").replace(yb,"+")}});var la={},Ab=/toggle|show|hide/,Bb=/^([+-]=)?([\d+-.]+)(.*)$/,W,va=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];c.fn.extend({show:function(a,b){if(a||a===0)return this.animate(K("show",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");
+this[a].style.display=d||"";if(c.css(this[a],"display")==="none"){d=this[a].nodeName;var f;if(la[d])f=la[d];else{var e=c("<"+d+" />").appendTo("body");f=e.css("display");if(f==="none")f="block";e.remove();la[d]=f}c.data(this[a],"olddisplay",f)}}a=0;for(b=this.length;a<b;a++)this[a].style.display=c.data(this[a],"olddisplay")||"";return this}},hide:function(a,b){if(a||a===0)return this.animate(K("hide",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");!d&&d!=="none"&&c.data(this[a],
+"olddisplay",c.css(this[a],"display"))}a=0;for(b=this.length;a<b;a++)this[a].style.display="none";return this}},_toggle:c.fn.toggle,toggle:function(a,b){var d=typeof a==="boolean";if(c.isFunction(a)&&c.isFunction(b))this._toggle.apply(this,arguments);else a==null||d?this.each(function(){var f=d?a:c(this).is(":hidden");c(this)[f?"show":"hide"]()}):this.animate(K("toggle",3),a,b);return this},fadeTo:function(a,b,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,d)},
+animate:function(a,b,d,f){var e=c.speed(b,d,f);if(c.isEmptyObject(a))return this.each(e.complete);return this[e.queue===false?"each":"queue"](function(){var j=c.extend({},e),i,o=this.nodeType===1&&c(this).is(":hidden"),k=this;for(i in a){var n=i.replace(ia,ja);if(i!==n){a[n]=a[i];delete a[i];i=n}if(a[i]==="hide"&&o||a[i]==="show"&&!o)return j.complete.call(this);if((i==="height"||i==="width")&&this.style){j.display=c.css(this,"display");j.overflow=this.style.overflow}if(c.isArray(a[i])){(j.specialEasing=
+j.specialEasing||{})[i]=a[i][1];a[i]=a[i][0]}}if(j.overflow!=null)this.style.overflow="hidden";j.curAnim=c.extend({},a);c.each(a,function(r,u){var z=new c.fx(k,j,r);if(Ab.test(u))z[u==="toggle"?o?"show":"hide":u](a);else{var C=Bb.exec(u),B=z.cur(true)||0;if(C){u=parseFloat(C[2]);var E=C[3]||"px";if(E!=="px"){k.style[r]=(u||1)+E;B=(u||1)/z.cur(true)*B;k.style[r]=B+E}if(C[1])u=(C[1]==="-="?-1:1)*u+B;z.custom(B,u,E)}else z.custom(B,u,"")}});return true})},stop:function(a,b){var d=c.timers;a&&this.queue([]);
+this.each(function(){for(var f=d.length-1;f>=0;f--)if(d[f].elem===this){b&&d[f](true);d.splice(f,1)}});b||this.dequeue();return this}});c.each({slideDown:K("show",1),slideUp:K("hide",1),slideToggle:K("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(a,b){c.fn[a]=function(d,f){return this.animate(b,d,f)}});c.extend({speed:function(a,b,d){var f=a&&typeof a==="object"?a:{complete:d||!d&&b||c.isFunction(a)&&a,duration:a,easing:d&&b||b&&!c.isFunction(b)&&b};f.duration=c.fx.off?0:typeof f.duration===
+"number"?f.duration:c.fx.speeds[f.duration]||c.fx.speeds._default;f.old=f.complete;f.complete=function(){f.queue!==false&&c(this).dequeue();c.isFunction(f.old)&&f.old.call(this)};return f},easing:{linear:function(a,b,d,f){return d+f*a},swing:function(a,b,d,f){return(-Math.cos(a*Math.PI)/2+0.5)*f+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);if((this.prop==="height"||this.prop==="width")&&this.elem.style)this.elem.style.display="block"},cur:function(a){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];return(a=parseFloat(c.css(this.elem,this.prop,a)))&&a>-10000?a:parseFloat(c.curCSS(this.elem,this.prop))||0},custom:function(a,b,d){function f(j){return e.step(j)}this.startTime=J();this.start=a;this.end=b;this.unit=d||this.unit||"px";this.now=this.start;
+this.pos=this.state=0;var e=this;f.elem=this.elem;if(f()&&c.timers.push(f)&&!W)W=setInterval(c.fx.tick,13)},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=J(),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 f in this.options.curAnim)if(this.options.curAnim[f]!==true)d=false;if(d){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;a=c.data(this.elem,"olddisplay");this.elem.style.display=a?a:this.options.display;if(c.css(this.elem,"display")==="none")this.elem.style.display="block"}this.options.hide&&c(this.elem).hide();if(this.options.hide||this.options.show)for(var e in this.options.curAnim)c.style(this.elem,
+e,this.options.orig[e]);this.options.complete.call(this.elem)}return false}else{e=b-this.startTime;this.state=e/this.options.duration;a=this.options.easing||(c.easing.swing?"swing":"linear");this.pos=c.easing[this.options.specialEasing&&this.options.specialEasing[this.prop]||a](this.state,e,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()},stop:function(){clearInterval(W);W=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};c.fn.offset="getBoundingClientRect"in s.documentElement?
+function(a){var b=this[0];if(a)return this.each(function(e){c.offset.setOffset(this,a,e)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);var d=b.getBoundingClientRect(),f=b.ownerDocument;b=f.body;f=f.documentElement;return{top:d.top+(self.pageYOffset||c.support.boxModel&&f.scrollTop||b.scrollTop)-(f.clientTop||b.clientTop||0),left:d.left+(self.pageXOffset||c.support.boxModel&&f.scrollLeft||b.scrollLeft)-(f.clientLeft||b.clientLeft||0)}}:function(a){var b=
+this[0];if(a)return this.each(function(r){c.offset.setOffset(this,a,r)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);c.offset.initialize();var d=b.offsetParent,f=b,e=b.ownerDocument,j,i=e.documentElement,o=e.body;f=(e=e.defaultView)?e.getComputedStyle(b,null):b.currentStyle;for(var k=b.offsetTop,n=b.offsetLeft;(b=b.parentNode)&&b!==o&&b!==i;){if(c.offset.supportsFixedPosition&&f.position==="fixed")break;j=e?e.getComputedStyle(b,null):b.currentStyle;
+k-=b.scrollTop;n-=b.scrollLeft;if(b===d){k+=b.offsetTop;n+=b.offsetLeft;if(c.offset.doesNotAddBorder&&!(c.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(b.nodeName))){k+=parseFloat(j.borderTopWidth)||0;n+=parseFloat(j.borderLeftWidth)||0}f=d;d=b.offsetParent}if(c.offset.subtractsBorderForOverflowNotVisible&&j.overflow!=="visible"){k+=parseFloat(j.borderTopWidth)||0;n+=parseFloat(j.borderLeftWidth)||0}f=j}if(f.position==="relative"||f.position==="static"){k+=o.offsetTop;n+=o.offsetLeft}if(c.offset.supportsFixedPosition&&
+f.position==="fixed"){k+=Math.max(i.scrollTop,o.scrollTop);n+=Math.max(i.scrollLeft,o.scrollLeft)}return{top:k,left:n}};c.offset={initialize:function(){var a=s.body,b=s.createElement("div"),d,f,e,j=parseFloat(c.curCSS(a,"marginTop",true))||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;f=d.firstChild;e=d.nextSibling.firstChild.firstChild;this.doesNotAddBorder=f.offsetTop!==5;this.doesAddBorderForTableAndCells=e.offsetTop===5;f.style.position="fixed";f.style.top="20px";this.supportsFixedPosition=f.offsetTop===20||f.offsetTop===15;f.style.position=f.style.top="";d.style.overflow="hidden";d.style.position="relative";this.subtractsBorderForOverflowNotVisible=f.offsetTop===-5;this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==j;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.curCSS(a,"marginTop",true))||0;d+=parseFloat(c.curCSS(a,"marginLeft",true))||0}return{top:b,left:d}},setOffset:function(a,b,d){if(/static/.test(c.curCSS(a,"position")))a.style.position="relative";var f=c(a),e=f.offset(),j=parseInt(c.curCSS(a,"top",true),10)||0,i=parseInt(c.curCSS(a,"left",true),10)||0;if(c.isFunction(b))b=b.call(a,
+d,e);d={top:b.top-e.top+j,left:b.left-e.left+i};"using"in b?b.using.call(a,d):f.css(d)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),f=/^body|html$/i.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.curCSS(a,"marginTop",true))||0;d.left-=parseFloat(c.curCSS(a,"marginLeft",true))||0;f.top+=parseFloat(c.curCSS(b[0],"borderTopWidth",true))||0;f.left+=parseFloat(c.curCSS(b[0],"borderLeftWidth",true))||0;return{top:d.top-
+f.top,left:d.left-f.left}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent||s.body;a&&!/^body|html$/i.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(f){var e=this[0],j;if(!e)return null;if(f!==w)return this.each(function(){if(j=wa(this))j.scrollTo(!a?f:c(j).scrollLeft(),a?f:c(j).scrollTop());else this[d]=f});else return(j=wa(e))?"pageXOffset"in j?j[a?"pageYOffset":
+"pageXOffset"]:c.support.boxModel&&j.document.documentElement[d]||j.document.body[d]:e[d]}});c.each(["Height","Width"],function(a,b){var d=b.toLowerCase();c.fn["inner"+b]=function(){return this[0]?c.css(this[0],d,false,"padding"):null};c.fn["outer"+b]=function(f){return this[0]?c.css(this[0],d,false,f?"margin":"border"):null};c.fn[d]=function(f){var e=this[0];if(!e)return f==null?null:this;if(c.isFunction(f))return this.each(function(j){var i=c(this);i[d](f.call(this,j,i[d]()))});return"scrollTo"in
+e&&e.document?e.document.compatMode==="CSS1Compat"&&e.document.documentElement["client"+b]||e.document.body["client"+b]:e.nodeType===9?Math.max(e.documentElement["client"+b],e.body["scroll"+b],e.documentElement["scroll"+b],e.body["offset"+b],e.documentElement["offset"+b]):f===w?c.css(e,d):this.css(d,typeof f==="string"?f:f+"px")}});A.jQuery=A.$=c})(window);
diff --git a/third-party/smartwizard-1636c86/js/jquery.smartWizard-2.0.js b/third-party/smartwizard-1636c86/js/jquery.smartWizard-2.0.js
new file mode 100644 (file)
index 0000000..813568b
--- /dev/null
@@ -0,0 +1,358 @@
+/*
+ * SmartWizard 2.0 plugin
+ * jQuery Wizard control Plugin
+ * by Dipu 
+ * 
+ * http://www.techlaboratory.net 
+ * http://tech-laboratory.blogspot.com
+ */
+(function($){
+    $.fn.smartWizard = function(action) {
+        var options = $.extend({}, $.fn.smartWizard.defaults, action);
+        var args = arguments;
+        
+        return this.each(function(){
+                var obj = $(this);
+                var curStepIdx = options.selected;
+                var steps = $("ul > li > a[href^='#step-']", obj); // Get all anchors in this array
+                var contentWidth = 0;
+                var loader,msgBox,elmActionBar,elmStepContainer,btNext,btPrevious,btFinish;
+                
+                elmActionBar = $('.actionBar',obj);
+                if(elmActionBar.length == 0){
+                  elmActionBar = $('<div></div>').addClass("actionBar");                
+                }
+
+                msgBox = $('.msgBox',obj);
+                if(msgBox.length == 0){
+                  msgBox = $('<div class="msgBox"><div class="content"></div><a href="#" class="close">X</a></div>');
+                  elmActionBar.append(msgBox);                
+                }
+                
+                $('.close',msgBox).click(function() {
+                    msgBox.fadeOut("normal");
+                    return false;
+                });
+                
+
+                // Method calling logic
+                if (!action || action === 'init' || typeof action === 'object') {
+                  init();
+                }else if (action === 'showMessage') {
+                  //showMessage(Array.prototype.slice.call( args, 1 ));
+                  var ar =  Array.prototype.slice.call( args, 1 );
+                  showMessage(ar[0]);
+                  return true;
+                }else if (action === 'setError') {
+                  var ar =  Array.prototype.slice.call( args, 1 );
+                  setError(ar[0].stepnum,ar[0].iserror);
+                  return true;
+                }else if (action === 'setDone') {
+                  var ar =  Array.prototype.slice.call( args, 1 );
+                  setDone(ar[0].stepnum,ar[0].isdone);
+                  return true;
+                } else {
+                  $.error( 'Method ' +  action + ' does not exist' );
+                }
+                
+                function init(){
+                  var allDivs =obj.children('div'); //$("div", obj);                
+                  obj.children('ul').addClass("anchor");
+                  allDivs.addClass("content");
+                  // Create Elements
+                  loader = $('<div>Loading</div>').addClass("loader");
+                  elmActionBar = $('<div></div>').addClass("actionBar");
+                  elmStepContainer = $('<div></div>').addClass("stepContainer");
+                  btNext = $('<a>'+options.labelNext+'</a>').attr("href","#").addClass("buttonNext");
+                  btPrevious = $('<a>'+options.labelPrevious+'</a>').attr("href","#").addClass("buttonPrevious");
+                  btFinish = $('<a>'+options.labelFinish+'</a>').attr("href","#").addClass("buttonFinish");
+                  
+                  // highlight steps with errors
+                  if(options.errorSteps && options.errorSteps.length>0){
+                    $.each(options.errorSteps, function(i, n){
+                      setError(n,true);
+                    });
+                  }
+
+
+                  elmStepContainer.append(allDivs);
+                  elmActionBar.append(loader);
+                  obj.append(elmStepContainer);
+                  obj.append(elmActionBar); 
+                  if (options.includeFinishButton) {
+                    elmActionBar.append(btFinish);
+                  }
+                  elmActionBar.append(btNext).append(btPrevious); 
+                  contentWidth = elmStepContainer.width();
+
+                  $(btNext).click(function() {
+                      if($(this).hasClass('buttonDisabled')){
+                        return false;
+                      }
+                      doForwardProgress();
+                      return false;
+                  }); 
+                  $(btPrevious).click(function() {
+                      if($(this).hasClass('buttonDisabled')){
+                        return false;
+                      }
+                      doBackwardProgress();
+                      return false;
+                  }); 
+                  $(btFinish).click(function() {
+                      if(!$(this).hasClass('buttonDisabled')){
+                         if($.isFunction(options.onFinish)) {
+                            if(!options.onFinish.call(this,$(steps))){
+                              return false;
+                            }
+                         }else{
+                           var frm = obj.parents('form');
+                           if(frm && frm.length){
+                             frm.submit();
+                           }                         
+                         }                      
+                      }
+
+                      return false;
+                  }); 
+                  
+                  $(steps).bind("click", function(e){
+                      if(steps.index(this) == curStepIdx){
+                        return false;                    
+                      }
+                      var nextStepIdx = steps.index(this);
+                      var isDone = steps.eq(nextStepIdx).attr("isDone") - 0;
+                      if(isDone == 1){
+                        LoadContent(nextStepIdx);                    
+                      }
+                      return false;
+                  }); 
+                  
+                  // Enable keyboard navigation                 
+                  if(options.keyNavigation){
+                      $(document).keyup(function(e){
+                          if(e.which==39){ // Right Arrow
+                            doForwardProgress();
+                          }else if(e.which==37){ // Left Arrow
+                            doBackwardProgress();
+                          }
+                      });
+                  }
+                  //  Prepare the steps
+                  prepareSteps();
+                  // Show the first slected step
+                  LoadContent(curStepIdx);                  
+                }
+
+                function prepareSteps(){
+                  if(!options.enableAllSteps){
+                    $(steps, obj).removeClass("selected").removeClass("done").addClass("disabled"); 
+                    $(steps, obj).attr("isDone",0);                 
+                  }else{
+                    $(steps, obj).removeClass("selected").removeClass("disabled").addClass("done"); 
+                    $(steps, obj).attr("isDone",1); 
+                  }
+
+                   $(steps, obj).each(function(i){
+                        $($(this).attr("href"), obj).hide();
+                        $(this).attr("rel",i+1);
+                  });
+                }
+                
+                function LoadContent(stepIdx){
+                    var selStep = steps.eq(stepIdx);
+                    var ajaxurl = options.contentURL;
+                    var hasContent =  selStep.data('hasContent');
+                    stepNum = stepIdx+1;
+                    if(ajaxurl && ajaxurl.length>0){
+                       if(options.contentCache && hasContent){
+                           showStep(stepIdx);                          
+                       }else{
+                           $.ajax({
+                            url: ajaxurl,
+                            type: "POST",
+                            data: ({step_number : stepNum}),
+                            dataType: "text",
+                            beforeSend: function(){ loader.show(); },
+                            error: function(){loader.hide();},
+                            success: function(res){ 
+                              loader.hide();       
+                              if(res && res.length>0){  
+                                 selStep.data('hasContent',true);            
+                                 $($(selStep, obj).attr("href"), obj).html(res);
+                                 showStep(stepIdx);
+                              }
+                            }
+                          }); 
+                      }
+                    }else{
+                      showStep(stepIdx);
+                    }
+                }
+                
+                function showStep(stepIdx){
+                    var selStep = steps.eq(stepIdx); 
+                    var curStep = steps.eq(curStepIdx);
+                    if(stepIdx != curStepIdx){
+                      if($.isFunction(options.onLeaveStep)) {
+                        if(!options.onLeaveStep.call(this,$(curStep))){
+                          return false;
+                        }
+                      }
+                    }     
+                    if (options.updateHeight)
+                        elmStepContainer.height($($(selStep, obj).attr("href"), obj).outerHeight());               
+                    if(options.transitionEffect == 'slide'){
+                      $($(curStep, obj).attr("href"), obj).slideUp("fast",function(e){
+                            $($(selStep, obj).attr("href"), obj).slideDown("fast");
+                            curStepIdx =  stepIdx;                        
+                            SetupStep(curStep,selStep);
+                          });
+                    } else if(options.transitionEffect == 'fade'){                      
+                      $($(curStep, obj).attr("href"), obj).fadeOut("fast",function(e){
+                            $($(selStep, obj).attr("href"), obj).fadeIn("fast");
+                            curStepIdx =  stepIdx;                        
+                            SetupStep(curStep,selStep);                           
+                          });                    
+                    } else if(options.transitionEffect == 'slideleft'){
+                        var nextElmLeft = 0;
+                        var curElementLeft = 0;
+                        if(stepIdx > curStepIdx){
+                            nextElmLeft1 = contentWidth + 10;
+                            nextElmLeft2 = 0;
+                            curElementLeft = 0 - $($(curStep, obj).attr("href"), obj).outerWidth();
+                        } else {
+                            nextElmLeft1 = 0 - $($(selStep, obj).attr("href"), obj).outerWidth() + 20;
+                            nextElmLeft2 = 0;
+                            curElementLeft = 10 + $($(curStep, obj).attr("href"), obj).outerWidth();
+                        }
+                        if(stepIdx == curStepIdx){
+                            nextElmLeft1 = $($(selStep, obj).attr("href"), obj).outerWidth() + 20;
+                            nextElmLeft2 = 0;
+                            curElementLeft = 0 - $($(curStep, obj).attr("href"), obj).outerWidth();                           
+                        }else{
+                            $($(curStep, obj).attr("href"), obj).animate({left:curElementLeft},"fast",function(e){
+                              $($(curStep, obj).attr("href"), obj).hide();
+                            });                       
+                        }
+
+                        $($(selStep, obj).attr("href"), obj).css("left",nextElmLeft1);
+                        $($(selStep, obj).attr("href"), obj).show();
+                        $($(selStep, obj).attr("href"), obj).animate({left:nextElmLeft2},"fast",function(e){
+                          curStepIdx =  stepIdx;                        
+                          SetupStep(curStep,selStep);                      
+                        });
+                    } else{
+                        $($(curStep, obj).attr("href"), obj).hide(); 
+                        $($(selStep, obj).attr("href"), obj).show();
+                        curStepIdx =  stepIdx;                        
+                        SetupStep(curStep,selStep);
+                    }
+                    return true;
+                }
+                
+                function SetupStep(curStep,selStep){
+                   $(curStep, obj).removeClass("selected");
+                   $(curStep, obj).addClass("done");
+                   
+                   $(selStep, obj).removeClass("disabled");
+                   $(selStep, obj).removeClass("done");
+                   $(selStep, obj).addClass("selected");
+                   $(selStep, obj).attr("isDone",1);
+                   adjustButton();
+                   if($.isFunction(options.onShowStep)) {
+                      if(!options.onShowStep.call(this,$(selStep))){
+                        return false;
+                      }
+                   } 
+                }                
+                
+                function doForwardProgress(){
+                  var nextStepIdx = curStepIdx + 1;
+                  if(steps.length <= nextStepIdx){
+                    if(!options.cycleSteps){
+                      return false;
+                    }                  
+                    nextStepIdx = 0;
+                  }
+                  LoadContent(nextStepIdx);
+                }
+                
+                function doBackwardProgress(){
+                  var nextStepIdx = curStepIdx-1;
+                  if(0 > nextStepIdx){
+                    if(!options.cycleSteps){
+                      return false;
+                    }
+                    nextStepIdx = steps.length - 1;
+                  }
+                  LoadContent(nextStepIdx);
+                }  
+                
+                function adjustButton(){
+                  if(!options.cycleSteps){                
+                    if(0 >= curStepIdx){
+                      $(btPrevious).addClass("buttonDisabled");
+                    }else{
+                      $(btPrevious).removeClass("buttonDisabled");
+                    }
+                    if((steps.length-1) <= curStepIdx){
+                      $(btNext).addClass("buttonDisabled");
+                    }else{
+                      $(btNext).removeClass("buttonDisabled");
+                    }
+                  }
+                  // Finish Button 
+                  if(!steps.hasClass('disabled') || options.enableFinishButton){
+                    $(btFinish).removeClass("buttonDisabled");
+                  }else{
+                    $(btFinish).addClass("buttonDisabled");
+                  }                  
+                }
+                
+                function showMessage(msg){
+                  $('.content',msgBox).html(msg);
+                       msgBox.show();
+                }
+                
+                function setError(stepnum,iserror){
+                  if(iserror){                    
+                    $(steps.eq(stepnum-1), obj).addClass('error')
+                  }else{
+                    $(steps.eq(stepnum-1), obj).removeClass("error");
+                  }                                   
+                }                        
+
+                function setDone(stepnum,isdone){
+                  if(isdone){                    
+                    $(steps.eq(stepnum-1), obj).removeClass("selected").removeClass("disabled").addClass('done')
+                  }else{
+                    $(steps.eq(stepnum-1), obj).removeClass("done");
+                  }                                   
+                }                        
+        });  
+    };  
+    // Default Properties and Events
+    $.fn.smartWizard.defaults = {
+          selected: 0,  // Selected Step, 0 = first step   
+          keyNavigation: true, // Enable/Disable key navigation(left and right keys are used if enabled)
+          enableAllSteps: false,
+          updateHeight: true,
+          transitionEffect: 'fade', // Effect on navigation, none/fade/slide/slideleft
+          contentURL:null, // content url, Enables Ajax content loading
+          contentCache:true, // cache step contents, if false content is fetched always from ajax url
+          cycleSteps: false, // cycle step navigation
+          includeFinishButton: true, // whether to show a Finish button
+          enableFinishButton: false, // make finish button enabled always
+          errorSteps:[],    // Array Steps with errors
+          labelNext:'Next',
+          labelPrevious:'Previous',
+          labelFinish:'Finish',          
+          onLeaveStep: null, // triggers when leaving a step
+          onShowStep: null,  // triggers when showing a step
+          onFinish: null  // triggers when Finish button is clicked
+    };    
+    
+})(jQuery);
diff --git a/third-party/smartwizard-1636c86/js/jquery.smartWizard-2.0.min.js b/third-party/smartwizard-1636c86/js/jquery.smartWizard-2.0.min.js
new file mode 100644 (file)
index 0000000..bada94d
--- /dev/null
@@ -0,0 +1,10 @@
+(function(a){a.fn.smartWizard=function(k){var c=a.extend({},a.fn.smartWizard.defaults,k),u=arguments;return this.each(function(){function z(){var d=b.children("div");b.children("ul").addClass("anchor");d.addClass("content");l=a("<div>Loading</div>").addClass("loader");i=a("<div></div>").addClass("actionBar");m=a("<div></div>").addClass("stepContainer");n=a("<a>"+c.labelNext+"</a>").attr("href","#").addClass("buttonNext");o=a("<a>"+c.labelPrevious+"</a>").attr("href","#").addClass("buttonPrevious");
+p=a("<a>"+c.labelFinish+"</a>").attr("href","#").addClass("buttonFinish");c.errorSteps&&c.errorSteps.length>0&&a.each(c.errorSteps,function(a,b){v(b,!0)});m.append(d);i.append(l);b.append(m);b.append(i);i.append(p).append(n).append(o);w=m.width();a(n).click(function(){x();return!1});a(o).click(function(){y();return!1});a(p).click(function(){if(!a(this).hasClass("buttonDisabled"))if(a.isFunction(c.onFinish))c.onFinish.call(this,a(f));else{var d=b.parents("form");d&&d.length&&d.submit()}return!1});
+a(f).bind("click",function(){if(f.index(this)==h)return!1;var a=f.index(this);f.eq(a).attr("isDone")-0==1&&q(a);return!1});c.keyNavigation&&a(document).keyup(function(a){a.which==39?x():a.which==37&&y()});A();q(h)}function A(){c.enableAllSteps?(a(f,b).removeClass("selected").removeClass("disabled").addClass("done"),a(f,b).attr("isDone",1)):(a(f,b).removeClass("selected").removeClass("done").addClass("disabled"),a(f,b).attr("isDone",0));a(f,b).each(function(d){a(a(this).attr("href"),b).hide();a(this).attr("rel",
+d+1)})}function q(d){var e=f.eq(d),g=c.contentURL,h=e.data("hasContent");stepNum=d+1;g&&g.length>0?c.contentCache&&h?t(d):a.ajax({url:g,type:"POST",data:{step_number:stepNum},dataType:"text",beforeSend:function(){l.show()},error:function(){l.hide()},success:function(c){l.hide();c&&c.length>0&&(e.data("hasContent",!0),a(a(e,b).attr("href"),b).html(c),t(d))}}):t(d)}function t(d){var e=f.eq(d),g=f.eq(h);if(d!=h&&a.isFunction(c.onLeaveStep)&&!c.onLeaveStep.call(this,a(g)))return!1;m.height(a(a(e,b).attr("href"),
+b).outerHeight());if(c.transitionEffect=="slide")a(a(g,b).attr("href"),b).slideUp("fast",function(){a(a(e,b).attr("href"),b).slideDown("fast");h=d;r(g,e)});else if(c.transitionEffect=="fade")a(a(g,b).attr("href"),b).fadeOut("fast",function(){a(a(e,b).attr("href"),b).fadeIn("fast");h=d;r(g,e)});else if(c.transitionEffect=="slideleft"){var i=0;d>h?(nextElmLeft1=w+10,nextElmLeft2=0,i=0-a(a(g,b).attr("href"),b).outerWidth()):(nextElmLeft1=0-a(a(e,b).attr("href"),b).outerWidth()+20,nextElmLeft2=0,i=10+
+a(a(g,b).attr("href"),b).outerWidth());d==h?(nextElmLeft1=a(a(e,b).attr("href"),b).outerWidth()+20,nextElmLeft2=0,i=0-a(a(g,b).attr("href"),b).outerWidth()):a(a(g,b).attr("href"),b).animate({left:i},"fast",function(){a(a(g,b).attr("href"),b).hide()});a(a(e,b).attr("href"),b).css("left",nextElmLeft1);a(a(e,b).attr("href"),b).show();a(a(e,b).attr("href"),b).animate({left:nextElmLeft2},"fast",function(){h=d;r(g,e)})}else a(a(g,b).attr("href"),b).hide(),a(a(e,b).attr("href"),b).show(),h=d,r(g,e);return!0}
+function r(d,e){a(d,b).removeClass("selected");a(d,b).addClass("done");a(e,b).removeClass("disabled");a(e,b).removeClass("done");a(e,b).addClass("selected");a(e,b).attr("isDone",1);c.cycleSteps||(0>=h?a(o).addClass("buttonDisabled"):a(o).removeClass("buttonDisabled"),f.length-1<=h?a(n).addClass("buttonDisabled"):a(n).removeClass("buttonDisabled"));!f.hasClass("disabled")||c.enableFinishButton?a(p).removeClass("buttonDisabled"):a(p).addClass("buttonDisabled");if(a.isFunction(c.onShowStep)&&!c.onShowStep.call(this,
+a(e)))return!1}function x(){var a=h+1;if(f.length<=a){if(!c.cycleSteps)return!1;a=0}q(a)}function y(){var a=h-1;if(0>a){if(!c.cycleSteps)return!1;a=f.length-1}q(a)}function B(b){a(".content",j).html(b);j.show()}function v(d,c){c?a(f.eq(d-1),b).addClass("error"):a(f.eq(d-1),b).removeClass("error")}var b=a(this),h=c.selected,f=a("ul > li > a",b),w=0,l,j,i,m,n,o,p;i=a(".actionBar",b);i.length==0&&(i=a("<div></div>").addClass("actionBar"));j=a(".msgBox",b);j.length==0&&(j=a('<div class="msgBox"><div class="content"></div><a href="#" class="close">X</a></div>'),
+i.append(j));a(".close",j).click(function(){j.fadeOut("normal");return!1});if(!k||k==="init"||typeof k==="object")z();else if(k==="showMessage"){var s=Array.prototype.slice.call(u,1);B(s[0]);return!0}else if(k==="setError")return s=Array.prototype.slice.call(u,1),v(s[0].stepnum,s[0].iserror),!0;else a.error("Method "+k+" does not exist")})};a.fn.smartWizard.defaults={selected:0,keyNavigation:!0,enableAllSteps:!1,transitionEffect:"fade",contentURL:null,contentCache:!0,cycleSteps:!1,enableFinishButton:!1,
+errorSteps:[],labelNext:"Next",labelPrevious:"Previous",labelFinish:"Finish",onLeaveStep:null,onShowStep:null,onFinish:null}})(jQuery);
\ No newline at end of file
diff --git a/third-party/smartwizard-1636c86/readme.md b/third-party/smartwizard-1636c86/readme.md
new file mode 100644 (file)
index 0000000..fe5aeb0
--- /dev/null
@@ -0,0 +1,34 @@
+Overview
+--------
+Smart Wizard is a flexible jQuery plug-in for wizard like interface. 
+It allows to group contents into sections and so it saves page space and also gives a neat and stylish interface for users.
+
+Demos
+-----
+[Basic Example](http://techlaboratory.net/labs/SmartWizard2/index.htm)
+[Ajax Contents](http://techlaboratory.net/labs/SmartWizard2/smartwizard2-ajax.htm)
+[Step Validation](http://techlaboratory.net/labs/SmartWizard2/smartwizard2-validation.php)
+[Multiple Wizard](http://techlaboratory.net/labs/SmartWizard2/smartwizard2-multiple.htm)
+[Vertical Style](http://techlaboratory.net/labs/SmartWizard2/smartwizard2-vertical.htm) 
+
+Features
+--------
+      Easy to implement, Minimal HTML required.
+      Ajax contents loading option.
+      Cool animation effects on step navigation. (none/fade/slide/slideleft)
+      Keyboard navigation option.
+      Horizontal and vertical style step anchors.
+      Easy step input validation option
+      Option to highlight error steps
+      In-built message box
+      Easy navigation with step anchors and navigation buttons
+      Can have multiple wizards on same page
+      Option to enable all steps on first load
+
+License
+-------
+Free to use and modify on both personal and commercial environment
+
+Creative Commons License
+Licensed under a [Creative Commons Attribution-ShareAlike 3.0 Unported License.](http://creativecommons.org/licenses/by-sa/3.0/)
\ No newline at end of file
diff --git a/third-party/smartwizard-1636c86/services/service.php b/third-party/smartwizard-1636c86/services/service.php
new file mode 100644 (file)
index 0000000..576c99d
--- /dev/null
@@ -0,0 +1,65 @@
+<?
+  $action = $_REQUEST["action"];
+  switch($action){
+      case "1":
+          getContent();
+        break;                     
+      default:
+        break;
+  }
+
+ function getContent(){
+   //sleep(1); 
+   $step_number = $_REQUEST["step_number"]; 
+   $html = '<h2 class="StepTitle">Step '.$step_number.' Content</h2>';
+   if($step_number == 1){
+      $html .='<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>';
+   }elseif($step_number == 2){
+      $html .='<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>
+            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>';
+   }elseif($step_number == 3){
+      $html .='<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>
+            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>
+            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>';
+   }else{
+      $html .='<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>';
+   }
+   echo $html;
+ }
+
+?>
\ No newline at end of file
diff --git a/third-party/smartwizard-1636c86/smartwizard2-ajax.htm b/third-party/smartwizard-1636c86/smartwizard2-ajax.htm
new file mode 100644 (file)
index 0000000..9ce8928
--- /dev/null
@@ -0,0 +1,158 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml"><head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>Smart Wizard 2 - Ajax Contents Example - a javascript jQuery wizard control plugin</title>
+
+<link href="styles/smart_wizard.css" rel="stylesheet" type="text/css">
+<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
+<script type="text/javascript" src="js/jquery.smartWizard-2.0.min.js"></script>
+
+<script type="text/javascript">
+    $(document).ready(function(){
+       // Smart Wizard         
+               $('#wizard').smartWizard({contentURL:'services/service.php?action=1',transitionEffect:'slideleft',onFinish:onFinishCallback});
+      
+      function onFinishCallback(){
+        alert('Finish Called');
+      }     
+               });
+</script>
+</head><body>
+
+<table align="center" border="0" cellpadding="0" cellspacing="0">
+<tr><td> 
+<!-- Smart Wizard -->
+               <div id="wizard" class="swMain">
+                       <ul>
+                               <li><a href="#step-1">
+                <span class="stepNumber">1</span>
+                <span class="stepDesc">
+                   Step 1<br />
+                   <small>Step 1 description</small>
+                </span>
+            </a></li>
+                               <li><a href="#step-2">
+                <span class="stepNumber">2</span>
+                <span class="stepDesc">
+                   Step 2<br />
+                   <small>Step 2 description</small>
+                </span>
+            </a></li>
+                               <li><a href="#step-3">
+                <span class="stepNumber">3</span>
+                <span class="stepDesc">
+                   Step 3<br />
+                   <small>Step 3 description</small>
+                </span>                   
+             </a></li>
+                               <li><a href="#step-4">
+                <span class="stepNumber">4</span>
+                <span class="stepDesc">
+                   Step 4<br />
+                   <small>Step 4 description</small>
+                </span>                   
+            </a></li>
+                       </ul>
+                       <div id="step-1">       
+            <h2 class="StepTitle">Step 1 Content</h2>
+            <ul type="disk">
+                                   <li>List 1</li>
+                                   <li>List 2</li>
+            </ul>
+            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>                               
+        </div>
+                       <div id="step-2">
+            <h2 class="StepTitle">Step 2 Content</h2>  
+            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p> 
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>          
+        </div>                      
+                       <div id="step-3">
+            <h2 class="StepTitle">Step 3 Content</h2>  
+            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>                                                         
+        </div>
+                       <div id="step-4">
+            <h2 class="StepTitle">Step 4 Content</h2>  
+            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>                                       
+        </div>
+               </div>
+<!-- End SmartWizard Content -->               
+
+</td></tr>
+</table>               
+</body>
+</html>
diff --git a/third-party/smartwizard-1636c86/smartwizard2-multiple.htm b/third-party/smartwizard-1636c86/smartwizard2-multiple.htm
new file mode 100644 (file)
index 0000000..0ec7816
--- /dev/null
@@ -0,0 +1,294 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml"><head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>Smart Wizard 2 - Multiple Wizard Example - a javascript jQuery wizard control plugin</title>
+
+<link href="styles/smart_wizard.css" rel="stylesheet" type="text/css">
+<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
+<script type="text/javascript" src="js/jquery.smartWizard-2.0.min.js"></script>
+
+<script type="text/javascript">
+    $(document).ready(function(){
+       //  Wizard 1    
+               $('#wizard1').smartWizard({transitionEffect:'fade',onFinish:onFinishCallback});
+       //  Wizard 2
+      $('#wizard2').smartWizard({transitionEffect:'slide',onFinish:onFinishCallback});
+      function onFinishCallback(){
+        alert('Finish Called');
+      }     
+               });
+</script>
+
+</head><body>
+
+<table align="center" border="0" cellpadding="0" cellspacing="0">
+<tr><td>
+<h3>Wizard 1</h3> 
+<!-- Smart Wizard wizard1-->
+               <div id="wizard1" class="swMain">
+                       <ul>
+                               <li><a href="#step-1">
+                <span class="stepNumber">1</span>
+                <span class="stepDesc">
+                   Step 1<br />
+                   <small>Step 1 description</small>
+                </span>
+            </a></li>
+                               <li><a href="#step-2">
+                <span class="stepNumber">2</span>
+                <span class="stepDesc">
+                   Step 2<br />
+                   <small>Step 2 description</small>
+                </span>
+            </a></li>
+                               <li><a href="#step-3">
+                <span class="stepNumber">3</span>
+                <span class="stepDesc">
+                   Step 3<br />
+                   <small>Step 3 description</small>
+                </span>                   
+             </a></li>
+                               <li><a href="#step-4">
+                <span class="stepNumber">4</span>
+                <span class="stepDesc">
+                   Step 4<br />
+                   <small>Step 4 description</small>
+                </span>                   
+            </a></li>
+                       </ul>
+                       <div id="step-1">       
+            <h2 class="StepTitle">Step 1 Content</h2>
+            <ul type="disk">
+                                   <li>List 1</li>
+                                   <li>List 2</li>
+            </ul>
+            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>                               
+        </div>
+                       <div id="step-2">
+            <h2 class="StepTitle">Step 2 Content</h2>  
+            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p> 
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>          
+        </div>                      
+                       <div id="step-3">
+            <h2 class="StepTitle">Step 3 Content</h2>  
+            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>                                                         
+        </div>
+                       <div id="step-4">
+            <h2 class="StepTitle">Step 4 Content</h2>  
+            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>                                       
+        </div>
+               </div>
+<!-- End SmartWizard Content 1 -->
+<br />  &nbsp;
+<h3>Wizard 2</h3>
+
+<!-- Smart Wizard wizard2-->
+               <div id="wizard2" class="swMain">
+                       <ul>
+                               <li><a href="#step-1">
+                <span class="stepNumber">1</span>
+                <span class="stepDesc">
+                   Step 1<br />
+                   <small>Step 1 description</small>
+                </span>
+            </a></li>
+                               <li><a href="#step-2">
+                <span class="stepNumber">2</span>
+                <span class="stepDesc">
+                   Step 2<br />
+                   <small>Step 2 description</small>
+                </span>
+            </a></li>
+                               <li><a href="#step-3">
+                <span class="stepNumber">3</span>
+                <span class="stepDesc">
+                   Step 3<br />
+                   <small>Step 3 description</small>
+                </span>                   
+             </a></li>
+                               <li><a href="#step-4">
+                <span class="stepNumber">4</span>
+                <span class="stepDesc">
+                   Step 4<br />
+                   <small>Step 4 description</small>
+                </span>                   
+            </a></li>
+                       </ul>
+                       <div id="step-1">       
+            <h2 class="StepTitle">Step 1 Content</h2>
+            <ul type="disk">
+                                   <li>List 1</li>
+                                   <li>List 2</li>
+            </ul>
+            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>                               
+        </div>
+                       <div id="step-2">
+            <h2 class="StepTitle">Step 2 Content</h2>  
+            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p> 
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>          
+        </div>                      
+                       <div id="step-3">
+            <h2 class="StepTitle">Step 3 Content</h2>  
+            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>                                                         
+        </div>
+                       <div id="step-4">
+            <h2 class="StepTitle">Step 4 Content</h2>  
+            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>                                       
+        </div>
+               </div>
+<!-- End SmartWizard Content 2 -->  
+
+</td></tr>
+</table>               
+</body>
+</html>
diff --git a/third-party/smartwizard-1636c86/smartwizard2-validation.php b/third-party/smartwizard-1636c86/smartwizard2-validation.php
new file mode 100644 (file)
index 0000000..9e5a443
--- /dev/null
@@ -0,0 +1,312 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml"><head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>Smart Wizard 2 - Step Validation Example - a javascript jQuery wizard control plugin</title>
+
+<link href="styles/smart_wizard.css" rel="stylesheet" type="text/css">
+<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
+<script type="text/javascript" src="js/jquery.smartWizard-2.0.min.js"></script>
+
+<script type="text/javascript">
+    $(document).ready(function(){
+       // Smart Wizard         
+               $('#wizard').smartWizard({transitionEffect:'slideleft',onLeaveStep:leaveAStepCallback,onFinish:onFinishCallback,enableFinishButton:true});
+
+      function leaveAStepCallback(obj){
+        var step_num= obj.attr('rel');
+        return validateSteps(step_num);
+      }
+      
+      function onFinishCallback(){
+       if(validateAllSteps()){
+        $('form').submit();
+       }
+      }
+               });
+          
+    function validateAllSteps(){
+       var isStepValid = true;
+       
+       if(validateStep1() == false){
+         isStepValid = false;
+         $('#wizard').smartWizard('setError',{stepnum:1,iserror:true});         
+       }else{
+         $('#wizard').smartWizard('setError',{stepnum:1,iserror:false});
+       }
+       
+       if(validateStep3() == false){
+         isStepValid = false;
+         $('#wizard').smartWizard('setError',{stepnum:3,iserror:true});         
+       }else{
+         $('#wizard').smartWizard('setError',{stepnum:3,iserror:false});
+       }
+       
+       if(!isStepValid){
+          $('#wizard').smartWizard('showMessage','Please correct the errors in the steps and continue');
+       }
+              
+       return isStepValid;
+    }  
+               
+               
+               function validateSteps(step){
+                 var isStepValid = true;
+      // validate step 1
+      if(step == 1){
+        if(validateStep1() == false ){
+          isStepValid = false; 
+          $('#wizard').smartWizard('showMessage','Please correct the errors in step'+step+ ' and click next.');
+          $('#wizard').smartWizard('setError',{stepnum:step,iserror:true});         
+        }else{
+          $('#wizard').smartWizard('setError',{stepnum:step,iserror:false});
+        }
+      }
+      
+      // validate step3
+      if(step == 3){
+        if(validateStep3() == false ){
+          isStepValid = false; 
+          $('#wizard').smartWizard('showMessage','Please correct the errors in step'+step+ ' and click next.');
+          $('#wizard').smartWizard('setError',{stepnum:step,iserror:true});         
+        }else{
+          $('#wizard').smartWizard('setError',{stepnum:step,iserror:false});
+        }
+      }
+      
+      return isStepValid;
+    }
+               
+               function validateStep1(){
+       var isValid = true; 
+       // Validate Username
+       var un = $('#username').val();
+       if(!un && un.length <= 0){
+         isValid = false;
+         $('#msg_username').html('Please fill username').show();
+       }else{
+         $('#msg_username').html('').hide();
+       }
+       
+       // validate password
+       var pw = $('#password').val();
+       if(!pw && pw.length <= 0){
+         isValid = false;
+         $('#msg_password').html('Please fill password').show();         
+       }else{
+         $('#msg_password').html('').hide();
+       }
+       
+       // validate confirm password
+       var cpw = $('#cpassword').val();
+       if(!cpw && cpw.length <= 0){
+         isValid = false;
+         $('#msg_cpassword').html('Please fill confirm password').show();         
+       }else{
+         $('#msg_cpassword').html('').hide();
+       }  
+       
+       // validate password match
+       if(pw && pw.length > 0 && cpw && cpw.length > 0){
+         if(pw != cpw){
+           isValid = false;
+           $('#msg_cpassword').html('Password mismatch').show();            
+         }else{
+           $('#msg_cpassword').html('').hide();
+         }
+       }
+       return isValid;
+    }
+    
+    function validateStep3(){
+      var isValid = true;    
+      //validate email  email
+      var email = $('#email').val();
+       if(email && email.length > 0){
+         if(!isValidEmailAddress(email)){
+           isValid = false;
+           $('#msg_email').html('Email is invalid').show();           
+         }else{
+          $('#msg_email').html('').hide();
+         }
+       }else{
+         isValid = false;
+         $('#msg_email').html('Please enter email').show();
+       }       
+      return isValid;
+    }
+    
+    // Email Validation
+    function isValidEmailAddress(emailAddress) {
+      var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
+      return pattern.test(emailAddress);
+    } 
+               
+               
+</script>
+</head><body>
+
+<table align="center" border="0" cellpadding="0" cellspacing="0">
+<tr><td>
+<?
+   if(isset($_REQUEST['issubmit'])){
+      echo "<strong>form is sumbitted</strong>";
+   }
+
+?>
+<form action="#" method="POST">
+  <input type='hidden' name="issubmit" value="1">
+<!-- Tabs -->
+               <div id="wizard" class="swMain">
+                       <ul>
+                               <li><a href="#step-1">
+                <span class="stepNumber">1</span>
+                <span class="stepDesc">
+                   Account Details<br />
+                   <small>Fill your account details</small>
+                </span>
+            </a></li>
+                               <li><a href="#step-2">
+                <span class="stepNumber">2</span>
+                <span class="stepDesc">
+                   Profile Details<br />
+                   <small>Fill your profile details</small>
+                </span>
+            </a></li>
+                               <li><a href="#step-3">
+                <span class="stepNumber">3</span>
+                <span class="stepDesc">
+                   Contact Details<br />
+                   <small>Fill your contact details</small>
+                </span>
+             </a></li>
+                               <li><a href="#step-4">
+                <span class="stepNumber">3</span>
+                <span class="stepDesc">
+                   Other Details<br />
+                   <small>Fill your other details</small>
+                </span>
+            </a></li>
+                       </ul>
+                       <div id="step-1">       
+            <h2 class="StepTitle">Step 1: Account Details</h2>
+            <table cellspacing="3" cellpadding="3" align="center">
+                               <tr>
+                       <td align="center" colspan="3">&nbsp;</td>
+                               </tr>        
+                               <tr>
+                       <td align="right">Username :</td>
+                       <td align="left">
+                         <input type="text" id="username" name="username" value="" class="txtBox">
+                      </td>
+                       <td align="left"><span id="msg_username"></span>&nbsp;</td>
+                               </tr>
+                               <tr>
+                       <td align="right">Password :</td>
+                       <td align="left">
+                         <input type="password" id="password" name="password" value="" class="txtBox">
+                      </td>
+                       <td align="left"><span id="msg_password"></span>&nbsp;</td>
+                               </tr> 
+                <tr>
+                       <td align="right">Confirm Password :</td>
+                       <td align="left">
+                         <input type="password" id="cpassword" name="cpassword" value="" class="txtBox">
+                      </td>
+                       <td align="left"><span id="msg_cpassword"></span>&nbsp;</td>
+                               </tr>                                                           
+                          </table>                             
+        </div>
+                       <div id="step-2">
+            <h2 class="StepTitle">Step 2: Profile Details</h2> 
+            <table cellspacing="3" cellpadding="3" align="center">
+                               <tr>
+                       <td align="center" colspan="3">&nbsp;</td>
+                               </tr>        
+                               <tr>
+                       <td align="right">First Name :</td>
+                       <td align="left">
+                         <input type="text" id="firstname" name="firstname" value="" class="txtBox">
+                      </td>
+                       <td align="left"><span id="msg_firstname"></span>&nbsp;</td>
+                               </tr>
+                               <tr>
+                       <td align="right">Last Name :</td>
+                       <td align="left">
+                         <input type="text" id="lastname" name="lastname" value="" class="txtBox">
+                      </td>
+                       <td align="left"><span id="msg_lastname"></span>&nbsp;</td>
+                               </tr> 
+                               <tr>
+                       <td align="right">Gender :</td>
+                       <td align="left">
+                        <select id="gender" name="gender" class="txtBox">
+                          <option value="">-select-</option>
+                          <option value="Female">Female</option>
+                          <option value="Male">Male</option>                 
+                        </select>
+                      </td>
+                       <td align="left"><span id="msg_gender"></span>&nbsp;</td>
+                               </tr>                                                           
+                          </table>        
+        </div>                      
+                       <div id="step-3">
+            <h2 class="StepTitle">Step 3: Contact Details</h2> 
+            <table cellspacing="3" cellpadding="3" align="center">
+                               <tr>
+                       <td align="center" colspan="3">&nbsp;</td>
+                               </tr>        
+                               <tr>
+                       <td align="right">Email :</td>
+                       <td align="left">
+                         <input type="text" id="email" name="email" value="" class="txtBox">
+                      </td>
+                       <td align="left"><span id="msg_email"></span>&nbsp;</td>
+                               </tr>
+                               <tr>
+                       <td align="right">Phone :</td>
+                       <td align="left">
+                         <input type="text" id="phone" name="phone" value="" class="txtBox">
+                      </td>
+                       <td align="left"><span id="msg_phone"></span>&nbsp;</td>
+                               </tr>                           
+                               <tr>
+                       <td align="right">Address :</td>
+                       <td align="left">
+                            <textarea name="address" id="address" class="txtBox" rows="3"></textarea>
+                      </td>
+                       <td align="left"><span id="msg_address"></span>&nbsp;</td>
+                               </tr>                                                           
+                          </table>                                                       
+        </div>
+                       <div id="step-4">
+            <h2 class="StepTitle">Step 4: Other Details</h2>   
+            <table cellspacing="3" cellpadding="3" align="center">
+                               <tr>
+                       <td align="center" colspan="3">&nbsp;</td>
+                               </tr>        
+                               <tr>
+                       <td align="right">Hobbies :</td>
+                       <td align="left">
+                         <input type="text" id="phone" name="phone" value="" class="txtBox">
+                      </td>
+                       <td align="left"><span id="msg_phone"></span>&nbsp;</td>
+                               </tr>                           
+                               <tr>
+                       <td align="right">About You :</td>
+                       <td align="left">
+                            <textarea name="address" id="address" class="txtBox" rows="5"></textarea>
+                      </td>
+                       <td align="left"><span id="msg_address"></span>&nbsp;</td>
+                               </tr>                                                           
+                          </table>                                     
+        </div>
+               </div>
+<!-- End SmartWizard Content -->               
+</form> 
+               
+</td></tr>
+</table> 
+
+</body>
+</html>
diff --git a/third-party/smartwizard-1636c86/smartwizard2-vertical.htm b/third-party/smartwizard-1636c86/smartwizard2-vertical.htm
new file mode 100644 (file)
index 0000000..99295cb
--- /dev/null
@@ -0,0 +1,165 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml"><head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>Smart Wizard 2 - Vertical Style Example - a javascript jQuery wizard control plugin</title>
+
+<link href="styles/smart_wizard_vertical.css" rel="stylesheet" type="text/css">
+<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
+<script type="text/javascript" src="js/jquery.smartWizard-2.0.min.js"></script>
+
+<script type="text/javascript">
+   
+    $(document).ready(function(){
+       // Smart Wizard 
+               $('#wizard').smartWizard({transitionEffect:'slide'});
+               });
+</script>
+
+</head><body>
+
+<table align="center" border="0" cellpadding="0" cellspacing="0">
+<tr><td> 
+<!-- Tabs -->
+               <div id="wizard" class="swMain">
+                       <ul>
+                               <li><a href="#step-1">
+                <span class="stepNumber">1</span>
+                <span class="stepDesc">
+                   Step 1<br />
+                   <small>Step 1 description</small>
+                </span>
+            </a></li>
+                               <li><a href="#step-2">
+                <span class="stepNumber">2</span>
+                <span class="stepDesc">
+                   Step 2<br />
+                   <small>Step 2 description having some more text</small>
+                </span>
+            </a></li>
+                               <li><a href="#step-3">
+                <span class="stepNumber">3</span>
+                <span class="stepDesc">
+                   Step 3<br />
+                   <small>Step 3 description</small>
+                </span>                   
+             </a></li>
+                               <li><a href="#step-4">
+                <span class="stepNumber">4</span>
+                <span class="stepDesc">
+                   Step 4<br />
+                   <small>Step 4 description</small>
+                </span>                   
+            </a></li>
+                       </ul>
+                       <div id="step-1">       
+            <h2 class="StepTitle">Step 1 Content</h2>
+            <ul type="disk">
+                                   <li>List 1</li>
+                                   <li>List 2</li>
+            </ul>
+            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>                               
+        </div>
+                       <div id="step-2">
+            <h2 class="StepTitle">Step 2 Content</h2>  
+            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p> 
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>            
+        </div>                      
+                       <div id="step-3">
+            <h2 class="StepTitle">Step 3 Content</h2>  
+            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>                                                         
+        </div>
+                       <div id="step-4">
+            <h2 class="StepTitle">Step 4 Content</h2>  
+            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>
+            <p>
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
+            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
+            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
+            Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
+            Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            </p>                                       
+        </div>
+               </div>
+               
+<!-- End SmartWizard Content -->               
+               
+</td></tr>
+</table>       
+       
+</body>
+</html>
diff --git a/third-party/smartwizard-1636c86/styles/smart_wizard.css b/third-party/smartwizard-1636c86/styles/smart_wizard.css
new file mode 100644 (file)
index 0000000..94e4da8
--- /dev/null
@@ -0,0 +1,305 @@
+/*   
+  SmartWizard 2.0 plugin 
+  jQuery Wizard control Plugin
+  by Dipu
+  
+  http://www.techlaboratory.net
+  http://tech-laboratory.blogspot.com
+*/
+.swMain {
+  position:relative;
+  display:block;
+  margin:0;
+  padding:0;
+  border: 0px solid #CCC;
+  overflow:visible;
+  float:left;
+  width:980px;
+}
+.swMain .stepContainer {
+  display:block;
+  position: relative;
+  margin: 0;
+  padding:0;    
+  border: 0px solid #CCC;    
+  overflow:hidden;
+  clear:both;
+  height:300px;
+}
+
+.swMain .stepContainer div.content {
+  display:block;
+  position: absolute;  
+  float:left;
+  margin: 0;
+  padding:5px;    
+  border: 1px solid #CCC; 
+  font: normal 12px Verdana, Arial, Helvetica, sans-serif; 
+  color:#5A5655;   
+  background-color:#F8F8F8;  
+  height:300px;
+  text-align:left;
+  overflow:visible;    
+  z-index:88; 
+  -webkit-border-radius: 5px;
+  -moz-border-radius  : 5px;
+  width:968px;
+  clear:both;
+}
+
+.swMain div.actionBar {
+  display:block;
+  position: relative; 
+  clear:both;
+  margin:             3px 0 0 0;   
+  border:             1px solid #CCC;
+  padding:            0;    
+  color:              #5A5655;   
+  background-color:   #F8F8F8;
+  height:40px;
+  text-align:left;
+  overflow:auto;    
+  z-index:88; 
+
+  -webkit-border-radius: 5px;
+  -moz-border-radius  : 5px;
+  left:0;
+}
+
+.swMain .stepContainer .StepTitle {
+  display:block;
+  position: relative;
+  margin:0;   
+  border:1px solid #E0E0E0;
+  padding:5px;   
+  font: bold 16px Verdana, Arial, Helvetica, sans-serif; 
+  color:#5A5655;   
+  background-color:#E0E0E0;
+  clear:both;
+  text-align:left; 
+  z-index:88;
+  -webkit-border-radius: 5px;
+  -moz-border-radius  : 5px;    
+}
+.swMain ul.anchor {
+  position: relative;
+  display:block;
+  float:left;
+  list-style: none;
+  padding: 0px;  
+  margin: 10px 0;      
+  clear: both;
+  border: 0px solid #CCCCCC;    
+  background: transparent; /*#EEEEEE */
+}
+.swMain ul.anchor li{ 
+  position: relative; 
+  display:block;
+  margin: 0;
+  padding: 0; 
+  padding-left:3px;
+  padding-right: 3px;
+  border: 0px solid #E0E0E0;      
+  float: left;
+}
+/* Anchor Element Style */
+.swMain ul.anchor li a {
+  display:block;
+  position:relative;
+  float:left;
+  margin:0;
+  padding:3px;
+  height:60px;
+  width:230px;
+  text-decoration: none;
+  outline-style:none;
+  -moz-border-radius  : 5px;
+  -webkit-border-radius: 5px;
+  z-index:99;
+}
+.swMain ul.anchor li a .stepNumber{
+  position:relative;
+  float:left;
+  width:30px;
+  text-align: center;
+  padding:5px;
+  padding-top:0;
+  font: bold 45px Verdana, Arial, Helvetica, sans-serif;
+}
+.swMain ul.anchor li a .stepDesc{
+  position:relative;
+  display:block;
+  float:left;
+  text-align: left;
+  padding:5px;
+
+  font: bold 20px Verdana, Arial, Helvetica, sans-serif;
+}
+.swMain ul.anchor li a .stepDesc small{
+  font: normal 12px Verdana, Arial, Helvetica, sans-serif;
+}
+.swMain ul.anchor li a.selected{
+  color:#F8F8F8;
+  background: #EA8511;  /* EA8511 */
+  border: 1px solid #EA8511;
+  cursor:text;
+  -moz-box-shadow: 5px 5px 8px #888;
+  -webkit-box-shadow: 5px 5px 8px #888;
+  box-shadow: 5px 5px 8px #888;
+}
+.swMain ul.anchor li a.selected:hover {
+  color:#F8F8F8;  
+  background: #EA8511;  
+}
+
+.swMain ul.anchor li a.done { 
+  position:relative;
+  color:#FFF;  
+  background: #8CC63F;  
+  border: 1px solid #8CC63F;   
+  z-index:99;
+}
+.swMain ul.anchor li a.done:hover {
+  color:#5A5655;  
+  background: #8CC63F; 
+  border: 1px solid #5A5655;   
+}
+.swMain ul.anchor li a.disabled {
+  color:#CCCCCC;  
+  background: #F8F8F8;
+  border: 1px solid #CCC;  
+  cursor:text;   
+}
+.swMain ul.anchor li a.disabled:hover {
+  color:#CCCCCC;  
+  background: #F8F8F8;     
+}
+
+.swMain ul.anchor li a.error {
+  color:#6c6c6c !important;  
+  background: #f08f75 !important;
+  border: 1px solid #fb3500 !important;      
+}
+.swMain ul.anchor li a.error:hover {
+  color:#000 !important;       
+}
+
+.swMain .buttonNext {
+  display:block;
+  float:right;
+  margin:5px 3px 0 3px;
+  padding:5px;
+  text-decoration: none;
+  text-align: center;
+  font: bold 13px Verdana, Arial, Helvetica, sans-serif;
+  width:100px;
+  color:#FFF;
+  outline-style:none;
+  background-color:   #5A5655;
+  border: 1px solid #5A5655;
+  -moz-border-radius  : 5px; 
+  -webkit-border-radius: 5px;    
+}
+.swMain .buttonDisabled {
+  color:#F8F8F8  !important;
+  background-color: #CCCCCC !important;
+  border: 1px solid #CCCCCC  !important;
+  cursor:text;    
+}
+.swMain .buttonPrevious {
+  display:block;
+  float:right;
+  margin:5px 3px 0 3px;
+  padding:5px;
+  text-decoration: none;
+  text-align: center;
+  font: bold 13px Verdana, Arial, Helvetica, sans-serif;
+  width:100px;
+  color:#FFF;
+  outline-style:none;
+  background-color:   #5A5655;
+  border: 1px solid #5A5655;
+  -moz-border-radius  : 5px; 
+  -webkit-border-radius: 5px;    
+}
+.swMain .buttonFinish {
+  display:block;
+  float:right;
+  margin:5px 10px 0 3px;
+  padding:5px;
+  text-decoration: none;
+  text-align: center;
+  font: bold 13px Verdana, Arial, Helvetica, sans-serif;
+  width:100px;
+  color:#FFF;
+  outline-style:none;
+  background-color:   #5A5655;
+  border: 1px solid #5A5655;
+  -moz-border-radius  : 5px; 
+  -webkit-border-radius: 5px;    
+}
+
+/* Form Styles */
+
+.txtBox {
+  border:1px solid #CCCCCC;
+  color:#5A5655;
+  font:13px Verdana,Arial,Helvetica,sans-serif;
+  padding:2px;
+  width:430px;
+}
+.txtBox:focus {
+  border:1px solid #EA8511;
+}
+
+.swMain .loader {
+  position:relative;  
+  display:none;
+  float:left;  
+  margin: 2px 0 0 2px;
+  padding:8px 10px 8px 40px;
+  border: 1px solid #FFD700; 
+  font: bold 13px Verdana, Arial, Helvetica, sans-serif; 
+  color:#5A5655;       
+  background: #FFF url(../images/loader.gif) no-repeat 5px;  
+  -moz-border-radius  : 5px;
+  -webkit-border-radius: 5px;
+  z-index:998;
+}
+.swMain .msgBox {
+  position:relative;  
+  display:none;
+  float:left;
+  margin: 4px 0 0 5px;
+  padding:5px;
+  border: 1px solid #FFD700; 
+  background-color: #FFFFDD;  
+  font: normal 12px Verdana, Arial, Helvetica, sans-serif; 
+  color:#5A5655;         
+  -moz-border-radius  : 5px;
+  -webkit-border-radius: 5px;
+  z-index:999;
+  min-width:200px;  
+}
+.swMain .msgBox .content {
+  font: normal 12px Verdana,Arial,Helvetica,sans-serif;
+  padding: 0px;
+  float:left;
+}
+.swMain .msgBox .close {
+  border: 1px solid #CCC;
+  border-radius: 3px;
+  color: #CCC;
+  display: block;
+  float: right;
+  margin: 0 0 0 5px;
+  outline-style: none;
+  padding: 0 2px 0 2px;
+  position: relative;
+  text-align: center;
+  text-decoration: none;
+}
+.swMain .msgBox .close:hover{
+  color: #EA8511;
+  border: 1px solid #EA8511;  
+}
\ No newline at end of file
diff --git a/third-party/smartwizard-1636c86/styles/smart_wizard_vertical.css b/third-party/smartwizard-1636c86/styles/smart_wizard_vertical.css
new file mode 100644 (file)
index 0000000..2df4b31
--- /dev/null
@@ -0,0 +1,306 @@
+/*   
+  SmartWizard 2.0 plugin 
+  jQuery Wizard control Plugin
+  by Dipu
+  
+  http://www.techlaboratory.net
+  http://tech-laboratory.blogspot.com
+*/
+.swMain {
+  position:relative;
+  display:block;
+  margin:0;
+  padding:0;
+  border: 0px solid #CCC;
+  overflow:visible;
+  float:left;
+  width:980px;/* */
+}
+.swMain .stepContainer {
+  display:block;
+  position: relative;
+  margin: 0;
+  padding:0;    
+  border: 0px solid #CCC;    
+  overflow:hidden;
+  clear:right;
+  height:300px;
+}
+
+.swMain .stepContainer div.content {
+  display:block;
+  position: absolute;  
+  float:left;
+  margin: 0;
+  padding:5px;    
+  border: 1px solid #CCC; 
+  font: normal 12px Verdana, Arial, Helvetica, sans-serif; 
+  color:#5A5655;   
+  background-color:#F8F8F8;  
+  height:300px;
+  text-align:left;
+  overflow:auto;    
+  z-index:88; 
+  -webkit-border-radius: 5px;
+  -moz-border-radius  : 5px;
+  width:720px;
+  clear:both;
+}
+
+.swMain div.actionBar {
+  display:block;
+  position: relative; 
+  clear:right;
+  margin:             3px 0 0 0;   
+  border:             1px solid #CCC;
+  padding:            0;    
+  color:              #5A5655;   
+  background-color:   #F8F8F8;
+  height:40px;
+/*  width:730px; 
+  float:right; */  
+  text-align:left;
+  overflow:auto;    
+  z-index:88; 
+  -webkit-border-radius: 5px;
+  -moz-border-radius  : 5px;
+
+}
+
+.swMain .stepContainer .StepTitle {
+  display:block;
+  position: relative;
+  margin:0;   
+  border:1px solid #E0E0E0;
+  padding:5px;   
+  font: bold 16px Verdana, Arial, Helvetica, sans-serif; 
+  color:#5A5655;   
+  background-color:#E0E0E0;
+  clear:both;
+  text-align:left; 
+  z-index:88;
+  -webkit-border-radius: 5px;
+  -moz-border-radius  : 5px;    
+}
+.swMain ul.anchor {
+  position: relative;
+  display:block;
+  float:left;
+  list-style: none;
+  padding: 0px;  
+  margin: 5px 10px 0 0;
+  border: 0px solid #CCCCCC;    
+  background: transparent; /*#EEEEEE */
+}
+.swMain ul.anchor li{ 
+  position: relative; 
+  display:block;
+  margin: 0;
+  padding: 0; 
+  padding-top:3px;
+  padding-bottom: 3px;
+  border: 0px solid #E0E0E0;      
+  float: left;
+  clear:both;
+}
+/* Anchor Element Style */
+.swMain ul.anchor li a {
+  display:block;
+  position:relative;
+  float:left;
+  margin:0;
+  padding:3px;
+  height:70px;
+  width:230px;
+  text-decoration: none;
+  outline-style:none;
+  -moz-border-radius  : 5px;
+  -webkit-border-radius: 5px;
+  z-index:99;
+}
+.swMain ul.anchor li a .stepNumber{
+  position:relative;
+  float:left;
+  width:30px;
+  text-align: center;
+  padding:5px;
+  padding-top:0;
+  font: bold 45px Verdana, Arial, Helvetica, sans-serif;
+}
+.swMain ul.anchor li a .stepDesc{
+  position:relative;
+  display:block;
+  float:left;
+  text-align: left;
+  padding:5px;
+  width:70%;
+  font: bold 20px Verdana, Arial, Helvetica, sans-serif;
+}
+.swMain ul.anchor li a .stepDesc small{
+  font: normal 12px Verdana, Arial, Helvetica, sans-serif;
+}
+.swMain ul.anchor li a.selected{
+  color:#F8F8F8;
+  background: #EA8511;  /* EA8511 */
+  border: 1px solid #EA8511;
+  cursor:text;
+  -moz-box-shadow: 1px 5px 10px #888;
+  -webkit-box-shadow: 1px 5px 10px #888;
+  box-shadow: 1px 5px 10px #888;
+}
+.swMain ul.anchor li a.selected:hover {
+  color:#F8F8F8;  
+  background: #EA8511;  
+}
+
+.swMain ul.anchor li a.done { 
+  position:relative;
+  color:#FFF;  
+  background: #8CC63F;  
+  border: 1px solid #8CC63F;   
+  z-index:99;
+}
+.swMain ul.anchor li a.done:hover {
+  color:#5A5655;  
+  background: #8CC63F; 
+  border: 1px solid #5A5655;   
+}
+.swMain ul.anchor li a.disabled {
+  color:#CCCCCC;  
+  background: #F8F8F8;
+  border: 1px solid #CCC;  
+  cursor:text;   
+}
+.swMain ul.anchor li a.disabled:hover {
+  color:#CCCCCC;  
+  background: #F8F8F8;     
+}
+
+.swMain ul.anchor li a.error {
+  color:#6c6c6c !important;  
+  background: #f08f75 !important;
+  border: 1px solid #fb3500 !important;      
+}
+.swMain ul.anchor li a.error:hover {
+  color:#000 !important;       
+}
+
+.swMain .buttonNext {
+  display:block;
+  float:right;
+  margin:5px 3px 0 3px;
+  padding:5px;
+  text-decoration: none;
+  text-align: center;
+  font: bold 13px Verdana, Arial, Helvetica, sans-serif;
+  width:100px;
+  color:#FFF;
+  outline-style:none;
+  background-color:   #5A5655;
+  border: 1px solid #5A5655;
+  -moz-border-radius  : 5px; 
+  -webkit-border-radius: 5px;    
+}
+.swMain .buttonDisabled {
+  color:#F8F8F8  !important;
+  background-color: #CCCCCC !important;
+  border: 1px solid #CCCCCC  !important;
+  cursor:text;    
+}
+.swMain .buttonPrevious {
+  display:block;
+  float:right;
+  margin:5px 3px 0 3px;
+  padding:5px;
+  text-decoration: none;
+  text-align: center;
+  font: bold 13px Verdana, Arial, Helvetica, sans-serif;
+  width:100px;
+  color:#FFF;
+  outline-style:none;
+  background-color:   #5A5655;
+  border: 1px solid #5A5655;
+  -moz-border-radius  : 5px; 
+  -webkit-border-radius: 5px;    
+}
+.swMain .buttonFinish {
+  display:block;
+  float:right;
+  margin:5px 10px 0 3px;
+  padding:5px;
+  text-decoration: none;
+  text-align: center;
+  font: bold 13px Verdana, Arial, Helvetica, sans-serif;
+  width:100px;
+  color:#FFF;
+  outline-style:none;
+  background-color:   #5A5655;
+  border: 1px solid #5A5655;
+  -moz-border-radius  : 5px; 
+  -webkit-border-radius: 5px;    
+}
+
+/* Form Styles */
+
+.txtBox {
+  border:1px solid #CCCCCC;
+  color:#5A5655;
+  font:13px Verdana,Arial,Helvetica,sans-serif;
+  padding:2px;
+  width:430px;
+}
+.txtBox:focus {
+  border:1px solid #EA8511;
+}
+
+.swMain .loader {
+  position:relative;  
+  display:none;
+  float:left;  
+  margin: 2px 0 0 2px;
+  padding:8px 10px 8px 40px;
+  border: 1px solid #FFD700; 
+  font: bold 13px Verdana, Arial, Helvetica, sans-serif; 
+  color:#5A5655;       
+  background: #FFF url(../images/loader.gif) no-repeat 5px;  
+  -moz-border-radius  : 5px;
+  -webkit-border-radius: 5px;
+  z-index:998;
+}
+.swMain .msgBox {
+  position:relative;  
+  display:none;
+  float:left;
+  margin: 4px 0 0 5px;
+  padding:5px;
+  border: 1px solid #FFD700; 
+  background-color: #FFFFDD;  
+  font: normal 12px Verdana, Arial, Helvetica, sans-serif; 
+  color:#5A5655;         
+  -moz-border-radius  : 5px;
+  -webkit-border-radius: 5px;
+  z-index:999;
+  min-width:200px;  
+}
+.swMain .msgBox .content {
+  font: normal 12px Verdana,Arial,Helvetica,sans-serif;
+  padding: 0px;
+  float:left;
+}
+.swMain .msgBox .close {
+  border: 1px solid #CCC;
+  border-radius: 3px;
+  color: #CCC;
+  display: block;
+  float: right;
+  margin: 0 0 0 5px;
+  outline-style: none;
+  padding: 0 2px 0 2px;
+  position: relative;
+  text-align: center;
+  text-decoration: none;
+}
+.swMain .msgBox .close:hover{
+  color: #EA8511;
+  border: 1px solid #EA8511;  
+}
\ No newline at end of file
index 6d6de77..e996477 100644 (file)
@@ -8,14 +8,15 @@ from django.shortcuts import render_to_response
 from django.contrib.auth.decorators import login_required
 
 from unfold.page import Page
-from manifold.manifoldquery import ManifoldQuery
+from manifold.core.query import Query
+#from manifold.manifoldquery import ManifoldQuery
 
 from plugins.stack.stack import Stack
 from plugins.lists.slicelist import SliceList
 from plugins.querycode.querycode import QueryCode
 from plugins.quickfilter.quickfilter import QuickFilter
 
-from myslice.viewutils import quickfilter_criterias
+from trash.trashutils  import quickfilter_criterias
 
 # 
 from myslice.viewutils import topmenu_items, the_user
@@ -25,16 +26,12 @@ def dashboard_view (request):
     
     page = Page(request)
 
-    slices_query = ManifoldQuery (action='get',
-                                  subject='slice',
-                                  timestamp='latest',
-                                  fields=['slice_hrn'],
-                                  filters=[],
-                                  # xxx filter : should filter on the slices the logged user can see
-                                  # we don't have the user's hrn yet
-                                  # in addition this currently returns all slices anyways
-                                  # filter = ...
-                                  sort='slice_hrn',)
+    slices_query = Query.get('slice').select('slice_hrn')
+#old#                                  # xxx filter : should filter on the slices the logged user can see
+#old#                                  # we don't have the user's hrn yet
+#old#                                  # in addition this currently returns all slices anyways
+#old#                                  # filter = ...
+#old#                                  sort='slice_hrn',)
     page.enqueue_query (slices_query)
 
     main_plugin = Stack (
index efc353b..236744f 100644 (file)
@@ -1,27 +1,27 @@
 # Create your views here.
 
-from django.core.context_processors import csrf
-from django.template import RequestContext
-from django.template.loader import render_to_string
-from django.shortcuts import render_to_response
+from django.core.context_processors     import csrf
+from django.template                    import RequestContext
+from django.template.loader             import render_to_string
+from django.shortcuts                   import render_to_response
 
-from django.contrib.auth.decorators import login_required
+from django.contrib.auth.decorators     import login_required
 
-from unfold.page import Page
-from manifold.manifoldquery import ManifoldQuery
+from unfold.page                        import Page
+from manifold.core.query                import Query
 
-from plugins.stack.stack import Stack
-from plugins.tabs.tabs import Tabs
-from plugins.lists.staticlist import StaticList
-from plugins.quickfilter.quickfilter import QuickFilter
-from plugins.querycode.querycode import QueryCode
-from plugins.raw.raw import Raw
-from plugins.messages.messages import Messages
-from plugins.hazelnut.hazelnut import Hazelnut
-from plugins.updater.updater import Updater
+from plugins.stack.stack                import Stack
+from plugins.tabs.tabs                  import Tabs
+from plugins.lists.staticlist           import StaticList
+from plugins.quickfilter.quickfilter    import QuickFilter
+from plugins.querycode.querycode        import QueryCode
+from plugins.raw.raw                    import Raw
+from plugins.messages.messages          import Messages
+from plugins.hazelnut                   import Hazelnut
+from plugins.updater                    import Updater
 
-from myslice.viewutils import topmenu_items, the_user
-from myslice.viewutils import hard_wired_slice_names, hard_wired_list, lorem_p, lorem, quickfilter_criterias
+from myslice.viewutils                  import topmenu_items, the_user
+from trash.trashutils                  import hard_wired_slice_names, hard_wired_list, lorem_p, lorem, quickfilter_criterias
 
 @login_required
 def test_plugin_view (request):
@@ -32,12 +32,7 @@ def test_plugin_view (request):
     template_env = {}
     
     slicename='ple.inria.heartbeat'
-    main_query = ManifoldQuery (action='get',
-                                subject='resource',
-                                timestamp='latest',
-                                fields=['network','type','hrn','hostname','sliver'],
-                                filters= [ [ 'slice_hrn', '=', slicename, ] ],
-                                )
+    main_query = Query.get('resource').filter_by('slice_hrn', '=', slicename).select(['network','type','hrn','hostname','sliver'])
     # without an hazelnut, this would use use : run_it=False as nothing would listen to the results
     page.enqueue_query (main_query, # run_it=False
                         )
index 81ad313..0207d4d 100644 (file)
@@ -8,7 +8,7 @@ from unfold.prelude import Prelude
 
 from myslice.viewutils import topmenu_items, the_user
 # tmp
-from myslice.viewutils import lorem, hard_wired_slice_names
+from trash.trashutils  import lorem, hard_wired_slice_names
 
 @login_required
 def tab_view (request):
diff --git a/trash/sliceview.py b/trash/sliceview.py
deleted file mode 100644 (file)
index 8f8a8ba..0000000
+++ /dev/null
@@ -1,172 +0,0 @@
-# Create your views here.
-
-from django.template import RequestContext
-from django.shortcuts import render_to_response
-
-from django.contrib.auth.decorators import login_required
-
-from unfold.page import Page
-from manifold.manifoldquery import ManifoldQuery
-
-from plugins.raw.raw import Raw
-from plugins.stack.stack import Stack
-from plugins.tabs.tabs import Tabs
-from plugins.lists.slicelist import SliceList
-from plugins.hazelnut.hazelnut import Hazelnut 
-from plugins.googlemap.googlemap import GoogleMap 
-from plugins.senslabmap.senslabmap import SensLabMap
-from plugins.querycode.querycode import QueryCode
-from plugins.quickfilter.quickfilter import QuickFilter
-from plugins.messages.messages import Messages
-
-from myslice.viewutils import quickfilter_criterias
-
-from myslice.viewutils import topmenu_items, the_user
-
-tmp_default_slice='ple.inria.heartbeat'
-
-@login_required
-def slice_view (request, slicename=tmp_default_slice):
-    
-    page = Page(request)
-
-    main_query = ManifoldQuery (action='get',
-                                subject='resource',
-                                timestamp='latest',
-                                fields=['network','type','hrn','hostname'],
-                                filters= [ [ 'slice_hrn', '=', slicename, ] ],
-                                )
-    page.enqueue_query (main_query)
-
-    main_plugin = Stack (
-        page=page,
-        title="Slice view for %s"%slicename,
-        domid='thestack',
-        togglable=False,
-        sons=[
-            Raw (page=page,togglable=False, toggled=True,html="<h2> Slice page for %s</h2>"%slicename),
-            Messages (
-                page=page,
-                title="Runtime messages for slice %s"%slicename,
-                domid="msgs-pre",
-                levels="ALL",
-                ),
-            Tabs (
-                page=page,
-                title="2 tabs : w/ and w/o checkboxes",
-                domid='thetabs',
-                # active_domid='checkboxes',
-                active_domid='gmap',
-                sons=[
-                    Hazelnut ( 
-                        page=page,
-                        title='a sample and simple hazelnut',
-                        domid='simple',
-                        # tab's sons preferably turn this off
-                        togglable=False,
-                        # this is the query at the core of the slice list
-                        query=main_query,
-                        ),
-                    Hazelnut ( 
-                        page=page,
-                        title='with checkboxes',
-                        domid='checkboxes',
-                        # tab's sons preferably turn this off
-                        togglable=False,
-                        # this is the query at the core of the slice list
-                        query=main_query,
-                        checkboxes=True,
-                        datatables_options = { 
-                            # for now we turn off sorting on the checkboxes columns this way
-                            # this of course should be automatic in hazelnut
-                            'aoColumns' : [ None, None, None, None, {'bSortable': False} ],
-                            'iDisplayLength' : 25,
-                            'bLengthChange' : True,
-                            },
-                        ),
-                    GoogleMap (
-                        page=page,
-                        title='geographic view',
-                        domid='gmap',
-                        # tab's sons preferably turn this off
-                        togglable=False,
-                        query=main_query,
-                        # center on Paris
-                        latitude=49.,
-                        longitude=2.2,
-                        zoom=3,
-                        ),
-                    Raw (
-#                    SensLabMap (
-                        page=page,
-                        title='3D view (disabled)',
-                        domid='smap',
-#                        # tab's sons preferably turn this off
-                        togglable=False,
-#                        query=main_query,
-                        html="""<p class='well'>
-Thierry: I am commeting off the use of <button class="btn btn-danger">SensLabMap</button> which,
- although rudimentarily ported to the django framework, 
-causes a weird behaviour especially wrt scrolling. 
-On my Mac <button class="btn btn-warning"> I cannot use the mouse to scroll</button> any longer
-if I keep this active, so for now it's disabled
-</p>""",
-                        ),
-                    ]),
-            Hazelnut ( 
-                page=page,
-                title='a hazelnut not in tabs',
-                domid='standalone',
-                # this is the query at the core of the slice list
-                query=main_query,
-                columns=['hrn','hostname'],
-                ),
-              # you don't *have to* set a domid, but if you plan on using toggled=persistent then it's required
-              # because domid is the key for storing toggle status in the browser
-            QueryCode (
-                page=page,
-                title='xmlrpc code (toggled=False)',
-                query=main_query,
-#                domid='xmlrpc',
-                toggled=False,
-                ),
-            QuickFilter (
-                page=page,
-                title="QuickFilter - requires metadata (toggled=False)",
-                criterias=quickfilter_criterias,
-                domid='filters',
-                toggled=False,
-                ),
-            Messages (
-                page=page,
-                title="Runtime messages (again)",
-                domid="msgs-post",
-                )
-              ])
-
-    # variables that will get passed to the view-unfold1.html template
-    template_env = {}
-    
-    # define 'unfold1_main' to the template engine - the main contents
-    template_env [ 'unfold1_main' ] = main_plugin.render(request)
-
-    # more general variables expected in the template
-    template_env [ 'title' ] = 'Test view that combines various plugins'
-    # the menu items on the top
-    template_env [ 'topmenu_items' ] = topmenu_items('slice', request) 
-    # so we can sho who is logged
-    template_env [ 'username' ] = the_user (request) 
-
-    # don't forget to run the requests
-    page.expose_queries ()
-
-    # xxx create another plugin with the same query and a different layout (with_datatables)
-    # show that it worls as expected, one single api call to backend and 2 refreshed views
-
-    # the prelude object in page contains a summary of the requirements() for all plugins
-    # define {js,css}_{files,chunks}
-    prelude_env = page.prelude_env()
-    template_env.update(prelude_env)
-    result=render_to_response ('view-unfold1.html',template_env,
-                               context_instance=RequestContext(request))
-    return result
diff --git a/trash/trashutils.py b/trash/trashutils.py
new file mode 100644 (file)
index 0000000..dd47013
--- /dev/null
@@ -0,0 +1,52 @@
+# a set of utilities to help make the global layout consistent across views
+
+# this 
+standard_topmenu_items = [ 
+#    { 'label':'Tab', 'href': '/tab/'},
+#    { 'label':'Scroll', 'href': '/scroll/'},
+#    { 'label':'One Plugin', 'href': '/plugin/'},
+# Thierry : using this goes to some test slice that not every one is in
+# besides, the topmenu needs to be shrunk down horizontally
+# otherwise the topmenu takes more vertical space than avail. and the layout is broken
+#    { 'label':'Slice', 'href': '/slice/'},
+    #{'label':'My Account', 'href': '/portal/account/'}
+    ]
+
+#login_out_items = { False: { 'label':'Login', 'href':'/login/'},
+#                    True:  { 'label':'Logout', 'href':'/logout/'}}
+
+# temporary for sample views
+lorem="""
+Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod <code>mazim placerat</code> facer possim assum. Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.
+"""
+
+lorem_p = "<p>"+lorem+"</p>"
+
+hard_wired_slice_names = []
+for site in [ 'inria', 'upmc' , 'ibbt' ]:
+    for slice in [ 'foo', 'bar', 'tutu', 'test', 'omf', 'heartbeat' ]:
+        hard_wired_slice_names.append ("ple.%s.%s"%(site,slice))
+
+# having html tags right here is not a real use case
+hard_wired_list=[]
+hard_wired_list.append("this hard-wired list")
+hard_wired_list.append("is defined")
+hard_wired_list.append("in plugins.simplelist.py")
+hard_wired_list.append("which in turn relies on")
+hard_wired_list.append("template widget-template.html")
+hard_wired_list.append("while it should of course")
+hard_wired_list.append("instead issue a query")
+hard_wired_list.append("and fill the DOM in js from there")
+hard_wired_list.append("it would however maybe make sense")
+hard_wired_list.append("to offer the option to 'datatablify'")
+hard_wired_list.append("the list from the python code")
+hard_wired_list.append("just like a standard plugin can be set as visible or not")
+hard_wired_list.append("")    
+hard_wired_list.append("OTOH and IMHO, there should be two separate and explicit subclasses of SimpleList for slices or testbeds")
+
+quickfilter_criterias = [
+    {'key': 'Slice', 'values': ['slice1','slice2']},
+    {'key': 'Type', 'values': ['type1','type2']},
+    {'key': 'Network', 'values': ['net1','net2']},
+    ]
+
diff --git a/trash/urls.py b/trash/urls.py
new file mode 100644 (file)
index 0000000..0c344ed
--- /dev/null
@@ -0,0 +1,8 @@
+from django.conf.urls           import patterns, include, url
+
+urlpatterns = patterns('',
+                       url(r'^tab/?$',          'trash.sampleviews.tab_view'),
+                       (r'^scroll/?$',          'trash.sampleviews.scroll_view'),
+                       (r'^plugin/?$',          'trash.pluginview.test_plugin_view'),
+                       (r'^dashboard/?$',       'trash.dashboard.dashboard_view'),
+)
index ffa6de9..16e28f3 100644 (file)
@@ -4,13 +4,13 @@ from unfold.plugin import Plugin
 # sons is expected to be a list of the contained plugins, and 
 # active_domid is the domid for the one son that should be displayed as active
 # some subclasses of Composite, like e.g. Tabs, will not behave as expected 
-# if a valid active_domid is not be provided
+# if a valid active_domid is not provided
 
 class Composite (Plugin):
 
-    def __init__ (self, sons=[], active_domid=None, *args, **kwds):
+    def __init__ (self, sons=None, active_domid=None, *args, **kwds):
         Plugin.__init__ (self, *args, **kwds)
-        self.sons=sons
+        self.sons= sons if sons else []
         self.active_domid=active_domid
         # make sure this is valid, unset otherwise, so we always have exactly one active
         self.check_active_domid()
similarity index 71%
rename from unfold/js/plugin.js
rename to unfold/js/plugin_helper.js
index 65d4d20..d15e7a7 100644 (file)
@@ -1,14 +1,14 @@
 //
 // storing toggle's status in localStorage
 // NOTE that localStorage only stores strings, so true becomes "true"
-var plugin = {
+var plugin_helper = {
 
     debug:false,
 
     ////////// use local storage to remember open/closed toggles
     store_status : function (domid,status) {
        var key='toggle.'+domid;
-       if (plugin.debug) messages.debug("storing toggle status " + status + " for " + domid + " key=" + key);
+       if (plugin_helper.debug) messages.debug("storing toggle status " + status + " for " + domid + " key=" + key);
        $.localStorage.setItem(key,status);
     },
     // restore last status
@@ -18,7 +18,7 @@ var plugin = {
        var retrieved=$.localStorage.getItem(key);
        // set default to true
        if (retrieved==null) retrieved="true";
-       if (plugin.debug) messages.debug ("retrieved toggle status for " + domid + " (key=" + key + ") -> " + retrieved);
+       if (plugin_helper.debug) messages.debug ("retrieved toggle status for " + domid + " (key=" + key + ") -> " + retrieved);
        return retrieved;
     },
     set_toggle_status : function (domid,status) {
@@ -27,12 +27,12 @@ var plugin = {
        var hidebtn=$('#hide-'+domid);
        if (status=="true")     { plugindiv.slideDown(); hidebtn.show(); showbtn.hide(); }
        else                    { plugindiv.slideUp();   hidebtn.hide(); showbtn.show(); }
-       plugin.store_status(domid,status);
+       plugin_helper.store_status(domid,status);
     },
     set_from_saved_status : function (domid) {
-       var previous_status=plugin.retrieve_last_status (domid);
-       if (plugin.debug) messages.debug("restoring initial status for domid " + domid + " -> " + previous_status);
-       plugin.set_toggle_status (domid,previous_status);
+       var previous_status=plugin_helper.retrieve_last_status (domid);
+       if (plugin_helper.debug) messages.debug("restoring initial status for domid " + domid + " -> " + previous_status);
+       plugin_helper.set_toggle_status (domid,previous_status);
     },
     // triggered upon $(document).ready
     init_all_plugins : function() {
@@ -40,19 +40,19 @@ var plugin = {
        // let us first make sure the right parts are turned on 
        $('.persistent-toggle').each(function() {
            var domid=this.id.replace('complete-','');
-           plugin.set_from_saved_status(domid);
+           plugin_helper.set_from_saved_status(domid);
        });
        // program the hide buttons so they do the right thing
        $('.plugin-hide').each(function() {
            $(this).click(function () { 
                var domid=this.id.replace('hide-','');
-               plugin.set_toggle_status(domid,"false");
+               plugin_helper.set_toggle_status(domid,"false");
            })});
        // same for show buttons
        $('.plugin-show').each(function() {
            $(this).click(function () { 
                var domid=this.id.replace('show-','');
-               plugin.set_toggle_status(domid,"true");
+               plugin_helper.set_toggle_status(domid,"true");
            })});
        // arm tooltips
        $('.plugin-tooltip').each(function(){ $(this).tooltip({'selector':'','placement':'right'}); });
@@ -62,5 +62,5 @@ var plugin = {
 /* upon document completion, we locate all the hide and show areas, 
  * and configure their behaviour 
  */
-$(document).ready(plugin.init_all_plugins)
+$(document).ready(plugin_helper.init_all_plugins)
 
index c104ea3..8d75cc3 100644 (file)
@@ -25,13 +25,17 @@ var unfold = {
     },
 
     get_value: function (value) {
-    //if(typeof(jQuery(value).attr('value'))!="undefined"){
-    if (/<span value=['"].*['"]>.*<\/span>/i.test(value)) {
-        return jQuery(value).attr('value');
-    } else {
-        return value;
+        //if(typeof(jQuery(value).attr('value'))!="undefined"){
+        if (/<span value=['"].*['"]>.*<\/span>/i.test(value)) {
+            return jQuery(value).attr('value');
+        } else {
+            return value;
+        }
+    },
+
+    escape_id: function(id) {
+        return id.replace( /(:|\.|\[|\])/g, "\\$1" );
     }
-}
 
 } // global unfold
 
index 86f9c08..07879e7 100644 (file)
@@ -53,9 +53,17 @@ class Page:
     # in this case (exec=True) the js async callback (see manifold.asynchroneous_success)
     # offers the option to deliver the result to a specific DOM elt (in this case, set domid)
     # otherwise (i.e. if domid not provided), it goes through the pubsub system (so all plugins can receive it)
-    def enqueue_query (self, query, run_it=True, domid=None):
+    # 
+    # NOTE:
+    # analyzed_query is required because it contains query_uuid that the
+    # plugins initialized in the python part will listen to. When a result is
+    # received in javascript, subresults should be publish to the appropriate
+    # query_uuid.
+    # 
+    def enqueue_query (self, query, run_it=True, domid=None, analyzed_query=None):
         # _queries is the set of all known queries
-        self._queries = self._queries.union(set( [ query, ] ))
+        # XXX complex XXX self._queries = self._queries.union(set( [ query, ] ))
+        self._queries.add((query, analyzed_query))
         # _queue is the list of queries that need to be triggered, with an optional domid
         # we only do this if run_it is set
         if run_it: self._queue.append ( (query.query_uuid,domid) )
@@ -67,7 +75,7 @@ class Page:
         # compute variables to expose to the template
         env = {}
         # expose the json definition of all queries
-        env['queries_json'] = [ query.to_json() for query in self._queries ]
+        env['queries_json'] = [ query.to_json(analyzed_query=aq) for (query, aq) in self._queries ]
         def query_publish_dom_tuple (a,b):
             result={'query_uuid':a}
             if b: result['domid']=b
@@ -80,24 +88,49 @@ class Page:
         self.expose_js_manifold_config()
 
 
+# DEPRECATED #    # needs to be called explicitly and only when metadata is actually required
+# DEPRECATED #    # in particular user needs to be logged
+# DEPRECATED #    def get_metadata (self):
+# DEPRECATED #        # look in session's cache - we don't want to retrieve this for every request
+# DEPRECATED #        session=self.request.session
+# DEPRECATED #        if 'manifold' not in session:
+# DEPRECATED #            print "Page.expose_js_metadata: no 'manifold' in session... - cannot retrieve metadata - skipping"
+# DEPRECATED #            return
+# DEPRECATED #        manifold=session['manifold']
+# DEPRECATED #        # if cached, use it
+# DEPRECATED #        if 'metadata' in manifold and isinstance(manifold['metadata'],MetaData):
+# DEPRECATED #            if debug: print "Page.get_metadata: return cached value"
+# DEPRECATED #            return manifold['metadata']
+# DEPRECATED #        # otherwise retrieve it
+# DEPRECATED #        manifold_api_session_auth = session['manifold']['auth']
+# DEPRECATED #        print "get_metadata(), manifold_api_session_auth =", session['manifold']['auth']
+# DEPRECATED #        metadata=MetaData (manifold_api_session_auth)
+# DEPRECATED #        metadata.fetch()
+# DEPRECATED #        # store it for next time
+# DEPRECATED #        manifold['metadata']=metadata
+# DEPRECATED #        if debug: print "Page.get_metadata: return new value"
+# DEPRECATED #        return metadata
+
     # needs to be called explicitly and only when metadata is actually required
     # in particular user needs to be logged
     def get_metadata (self):
         # look in session's cache - we don't want to retrieve this for every request
         session=self.request.session
+
         if 'manifold' not in session:
-            print "Page.expose_js_metadata: no 'manifold' in session... - cannot retrieve metadata - skipping"
-            return
-        manifold=session['manifold']
+            session['manifold'] = {}
+        manifold = session['manifold']
+
         # if cached, use it
         if 'metadata' in manifold and isinstance(manifold['metadata'],MetaData):
             if debug: print "Page.get_metadata: return cached value"
             return manifold['metadata']
-        # otherwise retrieve it
-        manifold_api_session_auth = session['manifold']['auth']
-        metadata=MetaData (manifold_api_session_auth)
+
+        metadata_auth = {'AuthMethod':'anonymous'}
+
+        metadata=MetaData (metadata_auth)
         metadata.fetch()
-            # store it for next time
+        # store it for next time
         manifold['metadata']=metadata
         if debug: print "Page.get_metadata: return new value"
         return metadata
index f0b6128..bcc03aa 100644 (file)
@@ -22,6 +22,8 @@ DEBUG= False
 # decorator to deflect calls on Plugin to its Prelude through self.page.prelude
 def to_prelude (method):
     def actual (self, *args, **kwds):
+        if not self.page: # jordan
+            return None
         prelude_method=Prelude.__dict__[method.__name__]
         return prelude_method(self.page.prelude,*args, **kwds)
     return actual
@@ -76,7 +78,7 @@ class Plugin:
         if not domid: domid=self.newdomid()
         self.domid=domid
         # title is shown when togglable
-        if not title: title="Plugin title for %s"%domid
+        #if not title: title="Plugin title for %s"%domid
         self.title=title
         self.classname=self._py_classname()
         self.plugin_classname=self._js_classname()
@@ -95,7 +97,8 @@ class Plugin:
             for (k,v) in self.__dict__.items(): print "dbg %s:%s"%(k,v)
             print "%s init dbg .... END"%self.classname
         # do this only once the structure is fine
-        self.page.record_plugin(self)
+        if self.page: # I assume we can have a None page (Jordan)
+            self.page.record_plugin(self)
 
     def __repr__ (self):
         return "[%s]:%s"%(self.classname,self.domid)
@@ -163,16 +166,19 @@ class Plugin:
         self.need_spin=self.start_with_spin()
         env.update(self.__dict__)
         # translate high-level 'toggled' into 4 different booleans
+        self.need_toggle = False
         if self.toggled=='persistent':
             # start with everything turned off and let the js callback do its job
-            env.update({'persistent_toggle':True,'display_hide_button':False,'display_show_button':False,'display_body':False})
+            env.update({'persistent_toggle':True,'display_hide_button':False,
+                        'display_show_button':False,'display_body':False})
         elif self.toggled==False:
-            env.update({'persistent_toggle':False,'display_hide_button':False,'display_show_button':True,'display_body':False})
+            env.update({'persistent_toggle':False,'display_hide_button':False,
+                        'display_show_button':True,'display_body':False})
         else:
-            env.update({'persistent_toggle':False,'display_hide_button':True,'display_show_button':False,'display_body':True})
+            env.update({'persistent_toggle':False,'display_hide_button':True,
+                        'display_show_button':False,'display_body':True})
         if self.need_debug(): 
             print "rendering plugin.html with env keys %s"%env.keys()
-            print "rendering plugin.html with env"
             for (k,v) in env.items(): 
                 if "display" in k or "persistent" in k: print k,'->',v
         result = render_to_string ('plugin.html',env)
@@ -257,7 +263,7 @@ class Plugin:
     def template_file (self):           return "undefined_template"
     def template_env (self, request):   return {}
 
-    def default_togglable (self):       return True
+    def default_togglable (self):       return False
     def default_toggled (self):         return 'persistent'
 
 #    # tell the framework about requirements (for the document <header>)
diff --git a/unfold/static.py b/unfold/static.py
new file mode 100644 (file)
index 0000000..815e8e2
--- /dev/null
@@ -0,0 +1,101 @@
+import os
+from django.conf import settings
+from django.utils.datastructures import SortedDict
+from django.contrib.staticfiles.finders import BaseFinder, FileSystemFinder
+from django.core.files.storage import FileSystemStorage
+
+class PluginFinder(FileSystemFinder):
+    """
+    A static files finder that looks in the directory of each plugin as
+    specified in the source_dir attribute of the given storage class.
+    """
+    def __init__(self, *args, **kwargs):
+        # The list of plugins that are handled
+        self.locations = []
+        # Mapping of plugin module paths to storage instances
+        self.storages = SortedDict()
+        plugins_dir = self.get_immediate_subdirs(settings.PLUGIN_DIR)
+        for root in plugins_dir:
+            if not os.path.exists(root) or not os.path.isdir(root):
+                continue
+            if ('', root) not in self.locations:
+                self.locations.append(('', root))
+        for _, root in self.locations:
+            filesystem_storage = FileSystemStorage(location=root)
+            filesystem_storage.prefix = ''
+            self.storages[root] = filesystem_storage
+
+    def get_immediate_subdirs(self, dir):
+        return [os.path.join(dir, name, 'static') for name in os.listdir(dir) 
+                if os.path.isdir(os.path.join(dir, name))]
+
+class ThirdPartyFinder(BaseFinder):
+    """
+    A static files inder that looks in the directory of each third-party
+    resources and tries to preserve the location of each file
+    """
+    # third-party/MODULE/path/to/js
+    extensions = {
+        # PREFIX : EXTENSIONS
+        ''   : ('.html',),
+        'js' : ('.js',),
+        'css': ('.css',),
+        'img': ('.png', '.ico',),
+    }
+
+    def find(self, search_path, all=False):
+        """
+        Given a relative file path this ought to find an
+        absolute file path.
+
+        If the ``all`` parameter is ``False`` (default) only
+        the first found file path will be returned; if set
+        to ``True`` a list of all found files paths is returned.
+        """
+        matches = []
+        #all_extensions = reduce(lambda x,y : x + y, extensions.values())
+
+        for (path, dirs, files) in os.walk(settings.THIRDPARTY_DIR):
+            for file in files:
+                name, extension = os.path.splitext(file)
+
+                for type, extensions in self.extensions.items():
+                    if not extension in extensions:
+                        continue
+                    if search_path == os.path.join(type, file):
+                        matched_path = os.path.join(path, file) 
+                        if not all:
+                            return matched_path
+                        matches.append(matched_path)
+        return matches
+
+    def list(self, ignore_patterns):
+        """
+        Given an optional list of paths to ignore, this should return
+        a two item iterable consisting of the relative path and storage
+        instance.
+        """
+        for (path, dirs, files) in os.walk(settings.THIRDPARTY_DIR):
+            for file in files:
+                name, extension = os.path.splitext(file)
+
+                for type, extensions in self.extensions.items():
+                    if not extension in extensions:
+                        continue
+                    filesystem_storage = FileSystemStorage(location=path)
+                    filesystem_storage.prefix = type
+                    yield file, filesystem_storage
+
+class BaseFinder(object):
+    """
+    A base file finder to be used for custom staticfiles finder classes.
+    """
+
+    def list(self, ignore_patterns):
+        """
+        Given an optional list of paths to ignore, this should return
+        a two item iterable consisting of the relative path and storage
+        instance.
+        """
+        raise NotImplementedError()
+
index 0d44075..5995a71 100644 (file)
@@ -1 +1 @@
-$(document).ready(function() { jQuery('#{{ domid }}').{{ plugin_classname }}({{ settings_json|safe }}); });
+$(document).ready(function() { $('#{{ domid }}').{{ plugin_classname }}({{ settings_json|safe }}); });
index 49d0560..88a56d9 100644 (file)
@@ -1,10 +1,12 @@
 {% if visible %}
-<div id='complete-{{ domid }}' class='plugin-toggle{% if need_spin %} need-spin{% endif %}{% if persistent_toggle %} persistent-toggle{% endif %}'>
+<div id='complete-{{ domid }}' class='{% if need_toggle %}plugin-toggle{% endif %}{% if need_spin %} need-spin{% endif %}{% if persistent_toggle %} persistent-toggle{% endif %}'>
 {% if togglable %}
 <h4 id='show-{{ domid }}' class='plugin-show'{% if not display_show_button %} style='display:none;'{% endif %}><i class="icon-hand-right"></i>
 <a href='#' class='plugin-tooltip' data-toggle='tooltip' data-original-title='Show plugin "{{ title }}" ({{ classname }})'>{{ title }}</a></h4>
 <h4 id='hide-{{ domid }}' class='plugin-hide'{% if not display_hide_button %} style='display:none;'{% endif %}><i class="icon-hand-down"></i>
+{% if title %}
 <a href='#' class='plugin-tooltip' data-toggle='tooltip' data-original-title='Hide plugin "{{ title }}" ({{ classname }})'>{{ title }}</a></h4>
+{% endif %}
 {% endif %}{# togglable #}
 {% endif %}{# visible #}
 
index d91775c..9346643 100644 (file)
@@ -3,5 +3,5 @@
 }
 #unfold2-margin {
     padding: 10;
-    background-color: #fff2ff;
+#    background-color: #fff2ff;
 }
index 0b9f14f..325b965 100644 (file)
@@ -9,3 +9,4 @@ button#logout {
     margin-left: 8px; 
     margin-bottom: 10px; 
 }
+span.logged-in { font-size: x-small; }
diff --git a/views/img/onelab-logo.png b/views/img/onelab-logo.png
new file mode 100644 (file)
index 0000000..6457ce8
Binary files /dev/null and b/views/img/onelab-logo.png differ
diff --git a/views/templates/base.html b/views/templates/base.html
new file mode 100644 (file)
index 0000000..db0d39f
--- /dev/null
@@ -0,0 +1,38 @@
+{# This is required by insert_above #}{% insert_handler %}<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
+<html lang="en"> <head>
+<title> MySlice - {{ title }} </title>
+<meta name="viewport" content="width=device-width, initial-scale=1.0">
+{# This is where insert_str will end up #}{% media_container prelude %}
+{% include 'messages-header.html' %}
+<script type="text/javascript"> {# raw js code - use {% insert prelude_js %} ... {% endinsert %} #} {% container prelude_js %}</script>
+<style type="text/css">{# In case we need to add raw css code #}{% container prelude_css %}</style>
+{{ header_prelude }}
+{% block head %} {% endblock head %}
+</head>{# let's add these ones no matter what #}
+{% insert_str prelude "css/layout-unfold2.css" %}
+{% insert_str prelude "js/jquery.min.js" %}
+{% insert_str prelude "js/jquery.html5storage.min.js" %}
+{% insert_str prelude "js/messages-runtime.js" %}
+{% insert_str prelude "js/class.js" %}
+{% insert_str prelude "js/plugin_helper.js" %}
+{% insert_str prelude "js/mustache.js" %}
+{% insert_str prelude "js/plugin.js" %}
+{% insert_str prelude "js/manifold.js" %}
+{% insert_str prelude "css/manifold.css" %}
+<body>
+{% block container %}
+<div id="container">
+  {% block topmenu %}
+  {% include 'widget-topmenu.html' %}
+  {% endblock topmenu %}
+{% include 'messages.html' %}
+<div class="container-fluid">
+  <div class="row-fluid">
+
+   {% block base_content%}{% endblock %}
+
+  </div><!--raw-fluid-->
+</div><!--container-fluid-->
+{% endblock container %}
+</body>
+</html>
index 2440651..851de44 100644 (file)
@@ -1,32 +1,9 @@
-{# This is required by insert_above #}{% insert_handler %}<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
-<html lang="en"> <head>
-<title> MySlice - {{ title }} </title>
-<meta name="viewport" content="width=device-width, initial-scale=1.0">
-{# This is where insert_str will end up #}{% media_container prelude %}
-<script type="text/javascript"> {# raw js code - use {% insert prelude_js %} ... {% endinsert %} #} {% container prelude_js %}</script>
-<style type="text/css">{# In case we need to add raw css code #}{% container prelude_css %}</style>
-{{ header_prelude }}
-</head>{# let's add these ones no matter what #}
-{# not yet needed {% insert_str prelude "css/layout-unfold1.css" %} #}
-{% insert_str prelude "js/jquery.min.js" %}
-{% insert_str prelude "js/jquery.html5storage.min.js" %}
-{% insert_str prelude "js/messages-runtime.js" %}
-{% insert_str prelude "js/plugin.js" %}
-<body>
-{% block container %}
-<div id="container">
-  {% block topmenu %}
-  {% include 'widget-topmenu.html' %}
-  {% endblock topmenu %}
-<div class="container-fluid">
-  <div class="row-fluid">
+{% extends "base.html" %}
+
+{% block base_content %}
     <div id="unfold1-main" class="span12 columns">
       {% block unfold1_main %}
       "The main content area (define block 'unfold1_main')"
       {% endblock unfold1_main %}
     </div><!--span12-->
-  </div><!--raw-fluid-->
-</div><!--container-fluid-->
-{% endblock container %}
-</body>
-</html>
+{% endblock %}
index b107b55..4754fa1 100644 (file)
@@ -1,25 +1,6 @@
-{# This is required by insert_above #}{% insert_handler %}<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
-<html lang="en"> <head>
-<title> MySlice - {{ title }} </title>
-<meta name="viewport" content="width=device-width, initial-scale=1.0">
-{# This is where insert_str will end up #}{% media_container prelude %}
-<script type="text/javascript"> {# raw js code - use {% insert prelude_js %} ... {% endinsert %} #} {% container prelude_js %}</script>
-<style type="text/css">{# In case we need to add raw css code #}{% container prelude_css %}</style>
-{{ header_prelude }}
-</head>{# let's add these ones no matter what #}
-{% insert_str prelude "css/layout-unfold2.css" %}
-{% insert_str prelude "js/jquery.min.js" %}
-{% insert_str prelude "js/jquery.html5storage.min.js" %}
-{% insert_str prelude "js/messages-runtime.js" %}
-{% insert_str prelude "js/plugin.js" %}
-<body>
-{% block container %}
-<div id="container">
-  {% block topmenu %}
-  {% include 'widget-topmenu.html' %}
-  {% endblock topmenu %}
-<div class="container-fluid">
-  <div class="row-fluid">
+{% extends "base.html" %}
+
+{% block base_content %}
     <div id="unfold2-main" class="span9 columns">
       {% block unfold2_main %}
       "The main content area (define block 'unfold2_main')"
@@ -30,8 +11,4 @@
       "The related content area (define block 'related_main')"
       {% endblock unfold2_margin %}
     </div><!--span3-->
-  </div><!--raw-fluid-->
-</div><!--container-fluid-->
-{% endblock container %}
-</body>
-</html>
+{% endblock %}
diff --git a/views/templates/messages-header.html b/views/templates/messages-header.html
new file mode 100644 (file)
index 0000000..0c292e7
--- /dev/null
@@ -0,0 +1,38 @@
+<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.js" type="text/javascript"></script>
+<!-- <script type="text/javascript">{{ STATIC_URL }}js/ui.widget.js</script> -->
+<script src="{{ STATIC_URL }}js/jquery.notify.js" type="text/javascript"></script>
+<link rel='stylesheet' href='{{ STATIC_URL }}css/ui.notify.css' type='text/css' />
+
+<script type="text/javascript">
+function create( template, vars, opts ){
+       return $container.notify("create", template, vars, opts);
+}
+
+$(function(){
+       // initialize widget on a container, passing in all the defaults.
+       // the defaults will apply to any notification created within this
+       // container, but can be overwritten on notification-by-notification
+       // basis.
+       $container = $("#notifications").notify();
+       
+       // create two when the pg loads
+       //create("default", { title:'Default Notification', text:'Example of a default notification.  I will fade out after 5 seconds'});
+       //create("sticky", { title:'Sticky Notification', text:'Example of a "sticky" notification.  Click on the X above to close me.'},{ expires:false });
+
+{% if messages %}
+       $(document).ready(function(){
+               {% for message in messages %}
+            $("#notifications").notify("create", {
+              title: 'Test Notification',
+              text: '{{ message }}'
+            },{
+              expires: false,
+              speed: 1000
+            });
+               {% endfor %}
+       });
+{% endif %}
+
+
+});
+</script>
diff --git a/views/templates/messages.html b/views/templates/messages.html
new file mode 100644 (file)
index 0000000..06ac2ef
--- /dev/null
@@ -0,0 +1,38 @@
+       <!--- container to hold notifications, and default templates --->
+<div id="notifications" style="display:none">
+               
+               <div id="default">
+                       <h1>#{title}</h1>
+                       <p>#{text}</p>
+               </div>
+               
+               <div id="sticky">
+                       <a class="ui-notify-close ui-notify-cross" href="#">x</a>
+                       <h1>#{title}</h1>
+                       <pre>#{text}</pre>
+               </div>
+               
+               <div id="themeroller" class="ui-state-error" style="padding:10px; -moz-box-shadow:0 0 6px #980000; -webkit-box-shadow:0 0 6px #980000; box-shadow:0 0 6px #980000;">
+                       <a class="ui-notify-close" href="#"><span class="ui-icon ui-icon-close" style="float:right"></span></a>
+                       <span style="float:left; margin:2px 5px 0 0;" class="ui-icon ui-icon-alert"></span>
+                       <h1>#{title}</h1>
+                       <p>#{text}</p>
+                       <p style="text-align:center"><a class="ui-notify-close" href="#">Close Me</a></p>
+               </div>
+               
+               <div id="withIcon">
+                       <a class="ui-notify-close ui-notify-cross" href="#">x</a>
+
+                       <div style="float:left;margin:0 10px 0 0"><img src="#{icon}" alt="warning" /></div>
+                       <h1>#{title}</h1>
+                       <p>#{text}</p>
+               </div>
+               
+               <div id="buttons">
+                       <h1>#{title}</h1>
+                       <p>#{text}</p>
+                       <p style="margin-top:10px;text-align:center">
+                               <input type="button" class="confirm" value="Close Dialog" />
+                       </p>
+               </div>
+       </div>
diff --git a/views/templates/view-login.html b/views/templates/view-login.html
deleted file mode 100644 (file)
index 6cd126e..0000000
+++ /dev/null
@@ -1,20 +0,0 @@
-{% extends 'layout-unfold2.html' %}
-
-{% block unfold2_margin %}
-{% include 'widget-login.html' %}
-{% endblock unfold2_margin %}
-
-{% block unfold2_main %}
-<code> This page is currently connected to two authentication systems:</code>
-<ul>
-<li> A manifold server, located at <code>{{ manifold_url }}</code>, (configured in <code>myslice/config.py</code>), and</li>
-<li>
-as a proof of concept, a set of hardwired user accounts, see <code>auth/backend.py</code> for more details. However these won't of course have the ability to run real queries at the backend so it's more for testing login and all this.
-Currently hard wired users are:
-<ul>
-  {% for k,v in hard_wired_users.iteritems %}
-  <li class='well'> Name= <code>{{ k }}</code>, Password= <code>{{ v }}</code> </li>
-  {% endfor %}
-</ul>
-</li></ul>
-{% endblock unfold2_main %}
index cc0fa70..1b14c8a 100644 (file)
@@ -6,13 +6,14 @@
 <div class="navbar navbar-fixed-top">
   <div class="navbar-inner">
     <div class="container-fluid">
-      <a class="brand" href="/"><img src="{{ STATIC_URL }}img/myslice-logo.png" height="30" alt="MySlice logo" /></a>
+      <a class="brand" href="/"><img src="{{ STATIC_URL }}img/onelab-logo.png" height="30" alt="OneLab logo" /></a>
+      <!--<a class="brand" href="/"><img src="{{ STATIC_URL }}img/myslice-logo.png" height="30" alt="MySlice logo" /></a>-->
       <div class="nav-collapse topmenu">
        <ul class="nav nav-pills" id='menu_ul'> {% for d in topmenu_items %} {% if d.is_active %}
          <li class='active'> <a href="{{ d.href }}"> {{ d.label }} </a> </li> {% else %}
          <li class='other'> <a href="{{ d.href }}"> {{ d.label }} </a> </li> {% endif %} {% endfor %}
        </ul> {# logout.js will attach a click function on that button, which then retrieves the 'username' attribute #}
-       <span class="navbar-text pull-right"> {% if username %} Logged in as {{ username }}
+       <span class="navbar-text pull-right logged-in"> {% if username %} Logged in as {{ username }}
        <button id='logout' class='btn btn-danger' username='{{ username }}'>Logout</a> {% else %}Not logged in{% endif %}</span>
       </div><!--nav-collapse-->
     </div><!--container-fluid-->